(with-selected-window): Doc fix.
[emacs.git] / lib-src / update-game-score.c
blob8f7c90cad55454083f07ebb4dda60519c8e6fe42
1 /* update-game-score.c --- Update a score file
2 Copyright (C) 2002, 2003 Free Software Foundation, Inc.
4 This file is part of GNU Emacs.
6 GNU Emacs is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2, or (at your option)
9 any later version.
11 GNU Emacs is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with GNU Emacs; see the file COPYING. If not, write to
18 the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
19 Boston, MA 02111-1307, USA. */
21 /* This program is allows a game to securely and atomically update a
22 score file. It should be installed setuid, owned by an appropriate
23 user like `games'.
25 Alternatively, it can be compiled without HAVE_SHARED_GAME_DIR
26 defined, and in that case it will store scores in the user's home
27 directory (it should NOT be setuid).
29 Created 2002/03/22, by Colin Walters <walters@debian.org>
32 #include <config.h>
34 #ifdef HAVE_UNISTD_H
35 #include <unistd.h>
36 #endif
37 #include <errno.h>
38 #ifdef HAVE_STRING_H
39 #include <string.h>
40 #endif
41 #ifdef HAVE_STDLIB_H
42 #include <stdlib.h>
43 #endif
44 #include <stdio.h>
45 #include <time.h>
46 #include <pwd.h>
47 #include <ctype.h>
48 #ifdef HAVE_FCNTL_H
49 #include <fcntl.h>
50 #endif
51 #ifdef STDC_HEADERS
52 #include <stdarg.h>
53 #endif
54 #include <sys/stat.h>
56 /* Needed for SunOS4, for instance. */
57 extern char *optarg;
58 extern int optind, opterr;
60 #define MAX_ATTEMPTS 5
61 #define MAX_SCORES 200
62 #define MAX_DATA_LEN 1024
64 /* Declare the prototype for a general external function. */
65 #if defined (PROTOTYPES) || defined (WINDOWSNT)
66 #define P_(proto) proto
67 #else
68 #define P_(proto) ()
69 #endif
71 #ifndef HAVE_DIFFTIME
72 /* OK on POSIX (time_t is arithmetic type) modulo overflow in subtraction. */
73 #define difftime(t1, t0) (double)((t1) - (t0))
74 #endif
76 int
77 usage (err)
78 int err;
80 fprintf (stdout, "Usage: update-game-score [-m MAX ] [ -r ] game/scorefile SCORE DATA\n");
81 fprintf (stdout, " update-game-score -h\n");
82 fprintf (stdout, " -h\t\tDisplay this help.\n");
83 fprintf (stdout, " -m MAX\t\tLimit the maximum number of scores to MAX.\n");
84 fprintf (stdout, " -r\t\tSort the scores in increasing order.\n");
85 fprintf (stdout, " -d DIR\t\tStore scores in DIR (only if not setuid).\n");
86 exit (err);
89 int lock_file P_ ((const char *filename, void **state));
90 int unlock_file P_ ((const char *filename, void *state));
92 struct score_entry
94 long score;
95 char *username;
96 char *data;
99 int read_scores P_ ((const char *filename, struct score_entry **scores,
100 int *count));
101 int push_score P_ ((struct score_entry **scores, int *count,
102 int newscore, char *username, char *newdata));
103 void sort_scores P_ ((struct score_entry *scores, int count, int reverse));
104 int write_scores P_ ((const char *filename, const struct score_entry *scores,
105 int count));
107 void lose P_ ((const char *msg)) NO_RETURN;
109 void
110 lose (msg)
111 const char *msg;
113 fprintf (stderr, "%s\n", msg);
114 exit (EXIT_FAILURE);
117 void lose_syserr P_ ((const char *msg)) NO_RETURN;
119 /* Taken from sysdep.c. */
120 #ifndef HAVE_STRERROR
121 #ifndef WINDOWSNT
122 char *
123 strerror (errnum)
124 int errnum;
126 extern char *sys_errlist[];
127 extern int sys_nerr;
129 if (errnum >= 0 && errnum < sys_nerr)
130 return sys_errlist[errnum];
131 return (char *) "Unknown error";
133 #endif /* not WINDOWSNT */
134 #endif /* ! HAVE_STRERROR */
136 void
137 lose_syserr (msg)
138 const char *msg;
140 fprintf (stderr, "%s: %s\n", msg, strerror (errno));
141 exit (EXIT_FAILURE);
144 char *
145 get_user_id P_ ((void))
147 char *name;
148 struct passwd *buf = getpwuid (getuid ());
149 if (!buf)
151 int count = 1;
152 int uid = (int) getuid ();
153 int tuid = uid;
154 while (tuid /= 10)
155 count++;
156 name = malloc (count+1);
157 if (!name)
158 return NULL;
159 sprintf (name, "%d", uid);
160 return name;
162 return buf->pw_name;
165 char *
166 get_prefix (running_suid, user_prefix)
167 int running_suid;
168 char *user_prefix;
170 if (!running_suid && user_prefix == NULL)
171 lose ("Not using a shared game directory, and no prefix given.");
172 if (running_suid)
174 #ifdef HAVE_SHARED_GAME_DIR
175 return HAVE_SHARED_GAME_DIR;
176 #else
177 lose ("This program was compiled without HAVE_SHARED_GAME_DIR,\n and should not be suid.");
178 #endif
180 return user_prefix;
184 main (argc, argv)
185 int argc;
186 char **argv;
188 int c, running_suid;
189 void *lockstate;
190 char *user_id, *scorefile, *prefix, *user_prefix = NULL;
191 struct stat buf;
192 struct score_entry *scores;
193 int newscore, scorecount, reverse = 0, max = MAX_SCORES;
194 char *newdata;
196 srand (time (0));
198 while ((c = getopt (argc, argv, "hrm:d:")) != -1)
199 switch (c)
201 case 'h':
202 usage (EXIT_SUCCESS);
203 break;
204 case 'd':
205 user_prefix = optarg;
206 break;
207 case 'r':
208 reverse = 1;
209 break;
210 case 'm':
211 max = atoi (optarg);
212 if (max > MAX_SCORES)
213 max = MAX_SCORES;
214 break;
215 default:
216 usage (EXIT_FAILURE);
219 if (optind+3 != argc)
220 usage (EXIT_FAILURE);
222 running_suid = (getuid () != geteuid ());
224 prefix = get_prefix (running_suid, user_prefix);
226 scorefile = malloc (strlen (prefix) + strlen (argv[optind]) + 2);
227 if (!scorefile)
228 lose_syserr ("Couldn't allocate score file");
230 strcpy (scorefile, prefix);
231 strcat (scorefile, "/");
232 strcat (scorefile, argv[optind]);
233 newscore = atoi (argv[optind+1]);
234 newdata = argv[optind+2];
235 if (strlen (newdata) > MAX_DATA_LEN)
236 newdata[MAX_DATA_LEN] = '\0';
238 user_id = get_user_id ();
239 if (user_id == NULL)
240 lose_syserr ("Couldn't determine user id");
242 if (stat (scorefile, &buf) < 0)
243 lose_syserr ("Failed to access scores file");
245 if (lock_file (scorefile, &lockstate) < 0)
246 lose_syserr ("Failed to lock scores file");
248 if (read_scores (scorefile, &scores, &scorecount) < 0)
250 unlock_file (scorefile, lockstate);
251 lose_syserr ("Failed to read scores file");
253 push_score (&scores, &scorecount, newscore, user_id, newdata);
254 /* Limit the number of scores. If we're using reverse sorting, then
255 we should increment the beginning of the array, to skip over the
256 *smallest* scores. Otherwise, we just decrement the number of
257 scores, since the smallest will be at the end. */
258 if (scorecount > MAX_SCORES)
259 scorecount -= (scorecount - MAX_SCORES);
260 if (reverse)
261 scores += (scorecount - MAX_SCORES);
262 sort_scores (scores, scorecount, reverse);
263 if (write_scores (scorefile, scores, scorecount) < 0)
265 unlock_file (scorefile, lockstate);
266 lose_syserr ("Failed to write scores file");
268 unlock_file (scorefile, lockstate);
269 exit (EXIT_SUCCESS);
273 read_score (f, score)
274 FILE *f;
275 struct score_entry *score;
277 int c;
278 if (feof (f))
279 return 1;
280 while ((c = getc (f)) != EOF
281 && isdigit (c))
283 score->score *= 10;
284 score->score += (c-48);
286 while ((c = getc (f)) != EOF
287 && isspace (c))
289 if (c == EOF)
290 return -1;
291 ungetc (c, f);
292 #ifdef HAVE_GETDELIM
294 size_t count = 0;
295 if (getdelim (&score->username, &count, ' ', f) < 1
296 || score->username == NULL)
297 return -1;
298 /* Trim the space */
299 score->username[strlen (score->username)-1] = '\0';
301 #else
303 int unameread = 0;
304 int unamelen = 30;
305 char *username = malloc (unamelen);
306 if (!username)
307 return -1;
309 while ((c = getc (f)) != EOF
310 && !isspace (c))
312 if (unameread >= unamelen-1)
313 if (!(username = realloc (username, unamelen *= 2)))
314 return -1;
315 username[unameread] = c;
316 unameread++;
318 if (c == EOF)
319 return -1;
320 username[unameread] = '\0';
321 score->username = username;
323 #endif
324 #ifdef HAVE_GETLINE
325 score->data = NULL;
326 errno = 0;
328 size_t len;
329 if (getline (&score->data, &len, f) < 0)
330 return -1;
331 score->data[strlen (score->data)-1] = '\0';
333 #else
335 int cur = 0;
336 int len = 16;
337 char *buf = malloc (len);
338 if (!buf)
339 return -1;
340 while ((c = getc (f)) != EOF
341 && c != '\n')
343 if (cur >= len-1)
345 if (!(buf = realloc (buf, len *= 2)))
346 return -1;
348 buf[cur] = c;
349 cur++;
351 score->data = buf;
352 score->data[cur] = '\0';
354 #endif
355 return 0;
359 read_scores (filename, scores, count)
360 const char *filename;
361 struct score_entry **scores;
362 int *count;
364 int readval, scorecount, cursize;
365 struct score_entry *ret;
366 FILE *f = fopen (filename, "r");
367 if (!f)
368 return -1;
369 scorecount = 0;
370 cursize = 16;
371 ret = (struct score_entry *) malloc (sizeof (struct score_entry) * cursize);
372 if (!ret)
373 return -1;
374 while ((readval = read_score (f, &ret[scorecount])) == 0)
376 /* We encoutered an error */
377 if (readval < 0)
378 return -1;
379 scorecount++;
380 if (scorecount >= cursize)
382 cursize *= 2;
383 ret = (struct score_entry *)
384 realloc (ret, (sizeof (struct score_entry) * cursize));
385 if (!ret)
386 return -1;
389 *count = scorecount;
390 *scores = ret;
391 return 0;
395 score_compare (a, b)
396 const void *a;
397 const void *b;
399 const struct score_entry *sa = (const struct score_entry *) a;
400 const struct score_entry *sb = (const struct score_entry *) b;
401 return (sb->score > sa->score) - (sb->score < sa->score);
405 score_compare_reverse (a, b)
406 const void *a;
407 const void *b;
409 const struct score_entry *sa = (const struct score_entry *) a;
410 const struct score_entry *sb = (const struct score_entry *) b;
411 return (sa->score > sb->score) - (sa->score < sb->score);
415 push_score (scores, count, newscore, username, newdata)
416 struct score_entry **scores;
417 int *count; int newscore;
418 char *username;
419 char *newdata;
421 struct score_entry *newscores
422 = (struct score_entry *) realloc (*scores,
423 sizeof (struct score_entry) * ((*count) + 1));
424 if (!newscores)
425 return -1;
426 newscores[*count].score = newscore;
427 newscores[*count].username = username;
428 newscores[*count].data = newdata;
429 (*count) += 1;
430 *scores = newscores;
431 return 0;
434 void
435 sort_scores (scores, count, reverse)
436 struct score_entry *scores;
437 int count;
438 int reverse;
440 qsort (scores, count, sizeof (struct score_entry),
441 reverse ? score_compare_reverse : score_compare);
445 write_scores (filename, scores, count)
446 const char *filename;
447 const struct score_entry * scores;
448 int count;
450 FILE *f;
451 int i;
452 char *tempfile = malloc (strlen (filename) + strlen (".tempXXXXXX") + 1);
453 if (!tempfile)
454 return -1;
455 strcpy (tempfile, filename);
456 strcat (tempfile, ".tempXXXXXX");
457 #ifdef HAVE_MKSTEMP
458 if (mkstemp (tempfile) < 0
459 #else
460 if (mktemp (tempfile) != tempfile
461 #endif
462 || !(f = fopen (tempfile, "w")))
463 return -1;
464 for (i = 0; i < count; i++)
465 if (fprintf (f, "%ld %s %s\n", scores[i].score, scores[i].username,
466 scores[i].data) < 0)
467 return -1;
468 fclose (f);
469 if (rename (tempfile, filename) < 0)
470 return -1;
471 if (chmod (filename, 0644) < 0)
472 return -1;
473 return 0;
477 lock_file (filename, state)
478 const char *filename;
479 void **state;
481 int fd;
482 struct stat buf;
483 int attempts = 0;
484 char *lockext = ".lockfile";
485 char *lockpath = malloc (strlen (filename) + strlen (lockext) + 60);
486 if (!lockpath)
487 return -1;
488 strcpy (lockpath, filename);
489 strcat (lockpath, lockext);
490 *state = lockpath;
491 trylock:
492 attempts++;
493 /* If the lock is over an hour old, delete it. */
494 if (stat (lockpath, &buf) == 0
495 && (difftime (buf.st_ctime, time (NULL) > 60*60)))
496 unlink (lockpath);
497 fd = open (lockpath, O_CREAT | O_EXCL, 0600);
498 if (fd < 0)
500 if (errno == EEXIST)
502 /* Break the lock; we won't corrupt the file, but we might
503 lose some scores. */
504 if (attempts > MAX_ATTEMPTS)
506 unlink (lockpath);
507 attempts = 0;
509 sleep ((rand () % 2)+1);
510 goto trylock;
512 else
513 return -1;
515 close (fd);
516 return 0;
520 unlock_file (filename, state)
521 const char *filename;
522 void *state;
524 char *lockpath = (char *) state;
525 int ret = unlink (lockpath);
526 int saved_errno = errno;
527 free (lockpath);
528 errno = saved_errno;
529 return ret;
532 /* arch-tag: 2bf5c52e-4beb-463a-954e-c58b9c64736b
533 (do not change this comment) */
535 /* update-game-score.c ends here */