Add pcomplete support for hosts defined in .ssh/config.
[emacs.git] / lib-src / update-game-score.c
blob0e74182a75f1104bbc747f47032a5731f0b89fe5
1 /* update-game-score.c --- Update a score file
3 Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011
4 Free Software Foundation, Inc.
6 Author: Colin Walters <walters@debian.org>
8 This file is part of GNU Emacs.
10 GNU Emacs is free software: you can redistribute it and/or modify
11 it under the terms of the GNU General Public License as published by
12 the Free Software Foundation, either version 3 of the License, or
13 (at your option) any later version.
15 GNU Emacs is distributed in the hope that it will be useful,
16 but WITHOUT ANY WARRANTY; without even the implied warranty of
17 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 GNU General Public License for more details.
20 You should have received a copy of the GNU General Public License
21 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
24 /* This program allows a game to securely and atomically update a
25 score file. It should be installed setuid, owned by an appropriate
26 user like `games'.
28 Alternatively, it can be compiled without HAVE_SHARED_GAME_DIR
29 defined, and in that case it will store scores in the user's home
30 directory (it should NOT be setuid).
32 Created 2002/03/22.
35 #include <config.h>
37 #include <unistd.h>
38 #include <errno.h>
39 #ifdef HAVE_STRING_H
40 #include <string.h>
41 #endif
42 #ifdef HAVE_STDLIB_H
43 #include <stdlib.h>
44 #endif
45 #include <stdio.h>
46 #include <time.h>
47 #include <pwd.h>
48 #include <ctype.h>
49 #ifdef HAVE_FCNTL_H
50 #include <fcntl.h>
51 #endif
52 #ifdef STDC_HEADERS
53 #include <stdarg.h>
54 #endif
55 #include <sys/stat.h>
57 /* Needed for SunOS4, for instance. */
58 extern char *optarg;
59 extern int optind, opterr;
61 int usage (int err) NO_RETURN;
63 #define MAX_ATTEMPTS 5
64 #define MAX_SCORES 200
65 #define MAX_DATA_LEN 1024
67 #ifndef HAVE_DIFFTIME
68 /* OK on POSIX (time_t is arithmetic type) modulo overflow in subtraction. */
69 #define difftime(t1, t0) (double)((t1) - (t0))
70 #endif
72 int
73 usage (int err)
75 fprintf (stdout, "Usage: update-game-score [-m MAX ] [ -r ] game/scorefile SCORE DATA\n");
76 fprintf (stdout, " update-game-score -h\n");
77 fprintf (stdout, " -h\t\tDisplay this help.\n");
78 fprintf (stdout, " -m MAX\t\tLimit the maximum number of scores to MAX.\n");
79 fprintf (stdout, " -r\t\tSort the scores in increasing order.\n");
80 fprintf (stdout, " -d DIR\t\tStore scores in DIR (only if not setuid).\n");
81 exit (err);
84 int lock_file (const char *filename, void **state);
85 int unlock_file (const char *filename, void *state);
87 struct score_entry
89 long score;
90 char *username;
91 char *data;
94 int read_scores (const char *filename, struct score_entry **scores,
95 int *count);
96 int push_score (struct score_entry **scores, int *count,
97 int newscore, char *username, char *newdata);
98 void sort_scores (struct score_entry *scores, int count, int reverse);
99 int write_scores (const char *filename, const struct score_entry *scores,
100 int count);
102 void lose (const char *msg) NO_RETURN;
104 void
105 lose (const char *msg)
107 fprintf (stderr, "%s\n", msg);
108 exit (EXIT_FAILURE);
111 void lose_syserr (const char *msg) NO_RETURN;
113 /* Taken from sysdep.c. */
114 #ifndef HAVE_STRERROR
115 #ifndef WINDOWSNT
116 char *
117 strerror (errnum)
118 int errnum;
120 extern char *sys_errlist[];
121 extern int sys_nerr;
123 if (errnum >= 0 && errnum < sys_nerr)
124 return sys_errlist[errnum];
125 return (char *) "Unknown error";
127 #endif /* not WINDOWSNT */
128 #endif /* ! HAVE_STRERROR */
130 void
131 lose_syserr (const char *msg)
133 fprintf (stderr, "%s: %s\n", msg, strerror (errno));
134 exit (EXIT_FAILURE);
137 char *
138 get_user_id (void)
140 char *name;
141 struct passwd *buf = getpwuid (getuid ());
142 if (!buf)
144 int count = 1;
145 int uid = (int) getuid ();
146 int tuid = uid;
147 while (tuid /= 10)
148 count++;
149 name = malloc (count+1);
150 if (!name)
151 return NULL;
152 sprintf (name, "%d", uid);
153 return name;
155 return buf->pw_name;
158 const char *
159 get_prefix (int running_suid, const char *user_prefix)
161 if (!running_suid && user_prefix == NULL)
162 lose ("Not using a shared game directory, and no prefix given.");
163 if (running_suid)
165 #ifdef HAVE_SHARED_GAME_DIR
166 return HAVE_SHARED_GAME_DIR;
167 #else
168 lose ("This program was compiled without HAVE_SHARED_GAME_DIR,\n and should not be suid.");
169 #endif
171 return user_prefix;
175 main (int argc, char **argv)
177 int c, running_suid;
178 void *lockstate;
179 char *user_id, *scorefile;
180 const char *prefix, *user_prefix = NULL;
181 struct stat buf;
182 struct score_entry *scores;
183 int newscore, scorecount, reverse = 0, max = MAX_SCORES;
184 char *newdata;
186 srand (time (0));
188 while ((c = getopt (argc, argv, "hrm:d:")) != -1)
189 switch (c)
191 case 'h':
192 usage (EXIT_SUCCESS);
193 break;
194 case 'd':
195 user_prefix = optarg;
196 break;
197 case 'r':
198 reverse = 1;
199 break;
200 case 'm':
201 max = atoi (optarg);
202 if (max > MAX_SCORES)
203 max = MAX_SCORES;
204 break;
205 default:
206 usage (EXIT_FAILURE);
209 if (optind+3 != argc)
210 usage (EXIT_FAILURE);
212 running_suid = (getuid () != geteuid ());
214 prefix = get_prefix (running_suid, user_prefix);
216 scorefile = malloc (strlen (prefix) + strlen (argv[optind]) + 2);
217 if (!scorefile)
218 lose_syserr ("Couldn't allocate score file");
220 strcpy (scorefile, prefix);
221 strcat (scorefile, "/");
222 strcat (scorefile, argv[optind]);
223 newscore = atoi (argv[optind+1]);
224 newdata = argv[optind+2];
225 if (strlen (newdata) > MAX_DATA_LEN)
226 newdata[MAX_DATA_LEN] = '\0';
228 user_id = get_user_id ();
229 if (user_id == NULL)
230 lose_syserr ("Couldn't determine user id");
232 if (stat (scorefile, &buf) < 0)
233 lose_syserr ("Failed to access scores file");
235 if (lock_file (scorefile, &lockstate) < 0)
236 lose_syserr ("Failed to lock scores file");
238 if (read_scores (scorefile, &scores, &scorecount) < 0)
240 unlock_file (scorefile, lockstate);
241 lose_syserr ("Failed to read scores file");
243 push_score (&scores, &scorecount, newscore, user_id, newdata);
244 sort_scores (scores, scorecount, reverse);
245 /* Limit the number of scores. If we're using reverse sorting, then
246 we should increment the beginning of the array, to skip over the
247 *smallest* scores. Otherwise, we just decrement the number of
248 scores, since the smallest will be at the end. */
249 if (scorecount > MAX_SCORES)
250 scorecount -= (scorecount - MAX_SCORES);
251 if (reverse)
252 scores += (scorecount - MAX_SCORES);
253 if (write_scores (scorefile, scores, scorecount) < 0)
255 unlock_file (scorefile, lockstate);
256 lose_syserr ("Failed to write scores file");
258 unlock_file (scorefile, lockstate);
259 exit (EXIT_SUCCESS);
263 read_score (FILE *f, struct score_entry *score)
265 int c;
266 if (feof (f))
267 return 1;
268 while ((c = getc (f)) != EOF
269 && isdigit (c))
271 score->score *= 10;
272 score->score += (c-48);
274 while ((c = getc (f)) != EOF
275 && isspace (c))
277 if (c == EOF)
278 return -1;
279 ungetc (c, f);
280 #ifdef HAVE_GETDELIM
282 size_t count = 0;
283 if (getdelim (&score->username, &count, ' ', f) < 1
284 || score->username == NULL)
285 return -1;
286 /* Trim the space */
287 score->username[strlen (score->username)-1] = '\0';
289 #else
291 int unameread = 0;
292 int unamelen = 30;
293 char *username = malloc (unamelen);
294 if (!username)
295 return -1;
297 while ((c = getc (f)) != EOF
298 && !isspace (c))
300 if (unameread >= unamelen-1)
301 if (!(username = realloc (username, unamelen *= 2)))
302 return -1;
303 username[unameread] = c;
304 unameread++;
306 if (c == EOF)
307 return -1;
308 username[unameread] = '\0';
309 score->username = username;
311 #endif
312 #ifdef HAVE_GETLINE
313 score->data = NULL;
314 errno = 0;
316 size_t len;
317 if (getline (&score->data, &len, f) < 0)
318 return -1;
319 score->data[strlen (score->data)-1] = '\0';
321 #else
323 int cur = 0;
324 int len = 16;
325 char *buf = malloc (len);
326 if (!buf)
327 return -1;
328 while ((c = getc (f)) != EOF
329 && c != '\n')
331 if (cur >= len-1)
333 if (!(buf = realloc (buf, len *= 2)))
334 return -1;
336 buf[cur] = c;
337 cur++;
339 score->data = buf;
340 score->data[cur] = '\0';
342 #endif
343 return 0;
347 read_scores (const char *filename, struct score_entry **scores, int *count)
349 int readval, scorecount, cursize;
350 struct score_entry *ret;
351 FILE *f = fopen (filename, "r");
352 if (!f)
353 return -1;
354 scorecount = 0;
355 cursize = 16;
356 ret = (struct score_entry *) malloc (sizeof (struct score_entry) * cursize);
357 if (!ret)
358 return -1;
359 while ((readval = read_score (f, &ret[scorecount])) == 0)
361 /* We encoutered an error */
362 if (readval < 0)
363 return -1;
364 scorecount++;
365 if (scorecount >= cursize)
367 cursize *= 2;
368 ret = (struct score_entry *)
369 realloc (ret, (sizeof (struct score_entry) * cursize));
370 if (!ret)
371 return -1;
374 *count = scorecount;
375 *scores = ret;
376 return 0;
380 score_compare (const void *a, const void *b)
382 const struct score_entry *sa = (const struct score_entry *) a;
383 const struct score_entry *sb = (const struct score_entry *) b;
384 return (sb->score > sa->score) - (sb->score < sa->score);
388 score_compare_reverse (const void *a, const void *b)
390 const struct score_entry *sa = (const struct score_entry *) a;
391 const struct score_entry *sb = (const struct score_entry *) b;
392 return (sa->score > sb->score) - (sa->score < sb->score);
396 push_score (struct score_entry **scores, int *count, int newscore, char *username, char *newdata)
398 struct score_entry *newscores
399 = (struct score_entry *) realloc (*scores,
400 sizeof (struct score_entry) * ((*count) + 1));
401 if (!newscores)
402 return -1;
403 newscores[*count].score = newscore;
404 newscores[*count].username = username;
405 newscores[*count].data = newdata;
406 (*count) += 1;
407 *scores = newscores;
408 return 0;
411 void
412 sort_scores (struct score_entry *scores, int count, int reverse)
414 qsort (scores, count, sizeof (struct score_entry),
415 reverse ? score_compare_reverse : score_compare);
419 write_scores (const char *filename, const struct score_entry *scores, int count)
421 FILE *f;
422 int i;
423 char *tempfile = malloc (strlen (filename) + strlen (".tempXXXXXX") + 1);
424 if (!tempfile)
425 return -1;
426 strcpy (tempfile, filename);
427 strcat (tempfile, ".tempXXXXXX");
428 #ifdef HAVE_MKSTEMP
429 if (mkstemp (tempfile) < 0
430 #else
431 if (mktemp (tempfile) != tempfile
432 #endif
433 || !(f = fopen (tempfile, "w")))
434 return -1;
435 for (i = 0; i < count; i++)
436 if (fprintf (f, "%ld %s %s\n", scores[i].score, scores[i].username,
437 scores[i].data) < 0)
438 return -1;
439 fclose (f);
440 if (rename (tempfile, filename) < 0)
441 return -1;
442 if (chmod (filename, 0644) < 0)
443 return -1;
444 return 0;
448 lock_file (const char *filename, void **state)
450 int fd;
451 struct stat buf;
452 int attempts = 0;
453 const char *lockext = ".lockfile";
454 char *lockpath = malloc (strlen (filename) + strlen (lockext) + 60);
455 if (!lockpath)
456 return -1;
457 strcpy (lockpath, filename);
458 strcat (lockpath, lockext);
459 *state = lockpath;
460 trylock:
461 attempts++;
462 /* If the lock is over an hour old, delete it. */
463 if (stat (lockpath, &buf) == 0
464 && (difftime (buf.st_ctime, time (NULL) > 60*60)))
465 unlink (lockpath);
466 fd = open (lockpath, O_CREAT | O_EXCL, 0600);
467 if (fd < 0)
469 if (errno == EEXIST)
471 /* Break the lock; we won't corrupt the file, but we might
472 lose some scores. */
473 if (attempts > MAX_ATTEMPTS)
475 unlink (lockpath);
476 attempts = 0;
478 sleep ((rand () % 2)+1);
479 goto trylock;
481 else
482 return -1;
484 close (fd);
485 return 0;
489 unlock_file (const char *filename, void *state)
491 char *lockpath = (char *) state;
492 int ret = unlink (lockpath);
493 int saved_errno = errno;
494 free (lockpath);
495 errno = saved_errno;
496 return ret;
500 /* update-game-score.c ends here */