Remove unnecessary variable declarations.
[emacs.git] / lib-src / update-game-score.c
blob188fa896bbd7e915133fc340c1d7ea67abc8efba
1 /* update-game-score.c --- Update a score file
2 Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007, 2008
3 Free Software Foundation, Inc.
5 This file is part of GNU Emacs.
7 GNU Emacs is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3, or (at your option)
10 any later version.
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs; see the file COPYING. If not, write to
19 the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
20 Boston, MA 02110-1301, USA. */
22 /* This program is allows a game to securely and atomically update a
23 score file. It should be installed setuid, owned by an appropriate
24 user like `games'.
26 Alternatively, it can be compiled without HAVE_SHARED_GAME_DIR
27 defined, and in that case it will store scores in the user's home
28 directory (it should NOT be setuid).
30 Created 2002/03/22, by Colin Walters <walters@debian.org>
33 #include <config.h>
35 #ifdef HAVE_UNISTD_H
36 #include <unistd.h>
37 #endif
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 #define MAX_ATTEMPTS 5
62 #define MAX_SCORES 200
63 #define MAX_DATA_LEN 1024
65 /* Declare the prototype for a general external function. */
66 #if defined (PROTOTYPES) || defined (WINDOWSNT)
67 #define P_(proto) proto
68 #else
69 #define P_(proto) ()
70 #endif
72 #ifndef HAVE_DIFFTIME
73 /* OK on POSIX (time_t is arithmetic type) modulo overflow in subtraction. */
74 #define difftime(t1, t0) (double)((t1) - (t0))
75 #endif
77 int
78 usage (err)
79 int err;
81 fprintf (stdout, "Usage: update-game-score [-m MAX ] [ -r ] game/scorefile SCORE DATA\n");
82 fprintf (stdout, " update-game-score -h\n");
83 fprintf (stdout, " -h\t\tDisplay this help.\n");
84 fprintf (stdout, " -m MAX\t\tLimit the maximum number of scores to MAX.\n");
85 fprintf (stdout, " -r\t\tSort the scores in increasing order.\n");
86 fprintf (stdout, " -d DIR\t\tStore scores in DIR (only if not setuid).\n");
87 exit (err);
90 int lock_file P_ ((const char *filename, void **state));
91 int unlock_file P_ ((const char *filename, void *state));
93 struct score_entry
95 long score;
96 char *username;
97 char *data;
100 int read_scores P_ ((const char *filename, struct score_entry **scores,
101 int *count));
102 int push_score P_ ((struct score_entry **scores, int *count,
103 int newscore, char *username, char *newdata));
104 void sort_scores P_ ((struct score_entry *scores, int count, int reverse));
105 int write_scores P_ ((const char *filename, const struct score_entry *scores,
106 int count));
108 void lose P_ ((const char *msg)) NO_RETURN;
110 void
111 lose (msg)
112 const char *msg;
114 fprintf (stderr, "%s\n", msg);
115 exit (EXIT_FAILURE);
118 void lose_syserr P_ ((const char *msg)) NO_RETURN;
120 /* Taken from sysdep.c. */
121 #ifndef HAVE_STRERROR
122 #ifndef WINDOWSNT
123 char *
124 strerror (errnum)
125 int errnum;
127 extern char *sys_errlist[];
128 extern int sys_nerr;
130 if (errnum >= 0 && errnum < sys_nerr)
131 return sys_errlist[errnum];
132 return (char *) "Unknown error";
134 #endif /* not WINDOWSNT */
135 #endif /* ! HAVE_STRERROR */
137 void
138 lose_syserr (msg)
139 const char *msg;
141 fprintf (stderr, "%s: %s\n", msg, strerror (errno));
142 exit (EXIT_FAILURE);
145 char *
146 get_user_id P_ ((void))
148 char *name;
149 struct passwd *buf = getpwuid (getuid ());
150 if (!buf)
152 int count = 1;
153 int uid = (int) getuid ();
154 int tuid = uid;
155 while (tuid /= 10)
156 count++;
157 name = malloc (count+1);
158 if (!name)
159 return NULL;
160 sprintf (name, "%d", uid);
161 return name;
163 return buf->pw_name;
166 char *
167 get_prefix (running_suid, user_prefix)
168 int running_suid;
169 char *user_prefix;
171 if (!running_suid && user_prefix == NULL)
172 lose ("Not using a shared game directory, and no prefix given.");
173 if (running_suid)
175 #ifdef HAVE_SHARED_GAME_DIR
176 return HAVE_SHARED_GAME_DIR;
177 #else
178 lose ("This program was compiled without HAVE_SHARED_GAME_DIR,\n and should not be suid.");
179 #endif
181 return user_prefix;
185 main (argc, argv)
186 int argc;
187 char **argv;
189 int c, running_suid;
190 void *lockstate;
191 char *user_id, *scorefile, *prefix, *user_prefix = NULL;
192 struct stat buf;
193 struct score_entry *scores;
194 int newscore, scorecount, reverse = 0, max = MAX_SCORES;
195 char *newdata;
197 srand (time (0));
199 while ((c = getopt (argc, argv, "hrm:d:")) != -1)
200 switch (c)
202 case 'h':
203 usage (EXIT_SUCCESS);
204 break;
205 case 'd':
206 user_prefix = optarg;
207 break;
208 case 'r':
209 reverse = 1;
210 break;
211 case 'm':
212 max = atoi (optarg);
213 if (max > MAX_SCORES)
214 max = MAX_SCORES;
215 break;
216 default:
217 usage (EXIT_FAILURE);
220 if (optind+3 != argc)
221 usage (EXIT_FAILURE);
223 running_suid = (getuid () != geteuid ());
225 prefix = get_prefix (running_suid, user_prefix);
227 scorefile = malloc (strlen (prefix) + strlen (argv[optind]) + 2);
228 if (!scorefile)
229 lose_syserr ("Couldn't allocate score file");
231 strcpy (scorefile, prefix);
232 strcat (scorefile, "/");
233 strcat (scorefile, argv[optind]);
234 newscore = atoi (argv[optind+1]);
235 newdata = argv[optind+2];
236 if (strlen (newdata) > MAX_DATA_LEN)
237 newdata[MAX_DATA_LEN] = '\0';
239 user_id = get_user_id ();
240 if (user_id == NULL)
241 lose_syserr ("Couldn't determine user id");
243 if (stat (scorefile, &buf) < 0)
244 lose_syserr ("Failed to access scores file");
246 if (lock_file (scorefile, &lockstate) < 0)
247 lose_syserr ("Failed to lock scores file");
249 if (read_scores (scorefile, &scores, &scorecount) < 0)
251 unlock_file (scorefile, lockstate);
252 lose_syserr ("Failed to read scores file");
254 push_score (&scores, &scorecount, newscore, user_id, newdata);
255 /* Limit the number of scores. If we're using reverse sorting, then
256 we should increment the beginning of the array, to skip over the
257 *smallest* scores. Otherwise, we just decrement the number of
258 scores, since the smallest will be at the end. */
259 if (scorecount > MAX_SCORES)
260 scorecount -= (scorecount - MAX_SCORES);
261 if (reverse)
262 scores += (scorecount - MAX_SCORES);
263 sort_scores (scores, scorecount, reverse);
264 if (write_scores (scorefile, scores, scorecount) < 0)
266 unlock_file (scorefile, lockstate);
267 lose_syserr ("Failed to write scores file");
269 unlock_file (scorefile, lockstate);
270 exit (EXIT_SUCCESS);
274 read_score (f, score)
275 FILE *f;
276 struct score_entry *score;
278 int c;
279 if (feof (f))
280 return 1;
281 while ((c = getc (f)) != EOF
282 && isdigit (c))
284 score->score *= 10;
285 score->score += (c-48);
287 while ((c = getc (f)) != EOF
288 && isspace (c))
290 if (c == EOF)
291 return -1;
292 ungetc (c, f);
293 #ifdef HAVE_GETDELIM
295 size_t count = 0;
296 if (getdelim (&score->username, &count, ' ', f) < 1
297 || score->username == NULL)
298 return -1;
299 /* Trim the space */
300 score->username[strlen (score->username)-1] = '\0';
302 #else
304 int unameread = 0;
305 int unamelen = 30;
306 char *username = malloc (unamelen);
307 if (!username)
308 return -1;
310 while ((c = getc (f)) != EOF
311 && !isspace (c))
313 if (unameread >= unamelen-1)
314 if (!(username = realloc (username, unamelen *= 2)))
315 return -1;
316 username[unameread] = c;
317 unameread++;
319 if (c == EOF)
320 return -1;
321 username[unameread] = '\0';
322 score->username = username;
324 #endif
325 #ifdef HAVE_GETLINE
326 score->data = NULL;
327 errno = 0;
329 size_t len;
330 if (getline (&score->data, &len, f) < 0)
331 return -1;
332 score->data[strlen (score->data)-1] = '\0';
334 #else
336 int cur = 0;
337 int len = 16;
338 char *buf = malloc (len);
339 if (!buf)
340 return -1;
341 while ((c = getc (f)) != EOF
342 && c != '\n')
344 if (cur >= len-1)
346 if (!(buf = realloc (buf, len *= 2)))
347 return -1;
349 buf[cur] = c;
350 cur++;
352 score->data = buf;
353 score->data[cur] = '\0';
355 #endif
356 return 0;
360 read_scores (filename, scores, count)
361 const char *filename;
362 struct score_entry **scores;
363 int *count;
365 int readval, scorecount, cursize;
366 struct score_entry *ret;
367 FILE *f = fopen (filename, "r");
368 if (!f)
369 return -1;
370 scorecount = 0;
371 cursize = 16;
372 ret = (struct score_entry *) malloc (sizeof (struct score_entry) * cursize);
373 if (!ret)
374 return -1;
375 while ((readval = read_score (f, &ret[scorecount])) == 0)
377 /* We encoutered an error */
378 if (readval < 0)
379 return -1;
380 scorecount++;
381 if (scorecount >= cursize)
383 cursize *= 2;
384 ret = (struct score_entry *)
385 realloc (ret, (sizeof (struct score_entry) * cursize));
386 if (!ret)
387 return -1;
390 *count = scorecount;
391 *scores = ret;
392 return 0;
396 score_compare (a, b)
397 const void *a;
398 const void *b;
400 const struct score_entry *sa = (const struct score_entry *) a;
401 const struct score_entry *sb = (const struct score_entry *) b;
402 return (sb->score > sa->score) - (sb->score < sa->score);
406 score_compare_reverse (a, b)
407 const void *a;
408 const void *b;
410 const struct score_entry *sa = (const struct score_entry *) a;
411 const struct score_entry *sb = (const struct score_entry *) b;
412 return (sa->score > sb->score) - (sa->score < sb->score);
416 push_score (scores, count, newscore, username, newdata)
417 struct score_entry **scores;
418 int *count; int newscore;
419 char *username;
420 char *newdata;
422 struct score_entry *newscores
423 = (struct score_entry *) realloc (*scores,
424 sizeof (struct score_entry) * ((*count) + 1));
425 if (!newscores)
426 return -1;
427 newscores[*count].score = newscore;
428 newscores[*count].username = username;
429 newscores[*count].data = newdata;
430 (*count) += 1;
431 *scores = newscores;
432 return 0;
435 void
436 sort_scores (scores, count, reverse)
437 struct score_entry *scores;
438 int count;
439 int reverse;
441 qsort (scores, count, sizeof (struct score_entry),
442 reverse ? score_compare_reverse : score_compare);
446 write_scores (filename, scores, count)
447 const char *filename;
448 const struct score_entry * scores;
449 int count;
451 FILE *f;
452 int i;
453 char *tempfile = malloc (strlen (filename) + strlen (".tempXXXXXX") + 1);
454 if (!tempfile)
455 return -1;
456 strcpy (tempfile, filename);
457 strcat (tempfile, ".tempXXXXXX");
458 #ifdef HAVE_MKSTEMP
459 if (mkstemp (tempfile) < 0
460 #else
461 if (mktemp (tempfile) != tempfile
462 #endif
463 || !(f = fopen (tempfile, "w")))
464 return -1;
465 for (i = 0; i < count; i++)
466 if (fprintf (f, "%ld %s %s\n", scores[i].score, scores[i].username,
467 scores[i].data) < 0)
468 return -1;
469 fclose (f);
470 if (rename (tempfile, filename) < 0)
471 return -1;
472 if (chmod (filename, 0644) < 0)
473 return -1;
474 return 0;
478 lock_file (filename, state)
479 const char *filename;
480 void **state;
482 int fd;
483 struct stat buf;
484 int attempts = 0;
485 char *lockext = ".lockfile";
486 char *lockpath = malloc (strlen (filename) + strlen (lockext) + 60);
487 if (!lockpath)
488 return -1;
489 strcpy (lockpath, filename);
490 strcat (lockpath, lockext);
491 *state = lockpath;
492 trylock:
493 attempts++;
494 /* If the lock is over an hour old, delete it. */
495 if (stat (lockpath, &buf) == 0
496 && (difftime (buf.st_ctime, time (NULL) > 60*60)))
497 unlink (lockpath);
498 fd = open (lockpath, O_CREAT | O_EXCL, 0600);
499 if (fd < 0)
501 if (errno == EEXIST)
503 /* Break the lock; we won't corrupt the file, but we might
504 lose some scores. */
505 if (attempts > MAX_ATTEMPTS)
507 unlink (lockpath);
508 attempts = 0;
510 sleep ((rand () % 2)+1);
511 goto trylock;
513 else
514 return -1;
516 close (fd);
517 return 0;
521 unlock_file (filename, state)
522 const char *filename;
523 void *state;
525 char *lockpath = (char *) state;
526 int ret = unlink (lockpath);
527 int saved_errno = errno;
528 free (lockpath);
529 errno = saved_errno;
530 return ret;
533 /* arch-tag: 2bf5c52e-4beb-463a-954e-c58b9c64736b
534 (do not change this comment) */
536 /* update-game-score.c ends here */