src/xdisp.c (single_display_spec_string): Correct a FIXME comment.
[emacs.git] / lib-src / update-game-score.c
blobe95e2ce259d479f4f0d8dc832fe7fd992f021caf
1 /* update-game-score.c --- Update a score file
3 Copyright (C) 2002-2011 Free Software Foundation, Inc.
5 Author: Colin Walters <walters@debian.org>
7 This file is part of GNU Emacs.
9 GNU Emacs is free software: you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation, either version 3 of the License, or
12 (at your option) any later version.
14 GNU Emacs is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 GNU General Public License for more details.
19 You should have received a copy of the GNU General Public License
20 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
23 /* This program allows a game to securely and atomically update a
24 score file. It should be installed setuid, owned by an appropriate
25 user like `games'.
27 Alternatively, it can be compiled without HAVE_SHARED_GAME_DIR
28 defined, and in that case it will store scores in the user's home
29 directory (it should NOT be setuid).
31 Created 2002/03/22.
34 #include <config.h>
36 #include <unistd.h>
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 static int usage (int err) NO_RETURN;
62 #define MAX_ATTEMPTS 5
63 #define MAX_SCORES 200
64 #define MAX_DATA_LEN 1024
66 #ifndef HAVE_DIFFTIME
67 /* OK on POSIX (time_t is arithmetic type) modulo overflow in subtraction. */
68 #define difftime(t1, t0) (double)((t1) - (t0))
69 #endif
71 static int
72 usage (int err)
74 fprintf (stdout, "Usage: update-game-score [-m MAX ] [ -r ] game/scorefile SCORE DATA\n");
75 fprintf (stdout, " update-game-score -h\n");
76 fprintf (stdout, " -h\t\tDisplay this help.\n");
77 fprintf (stdout, " -m MAX\t\tLimit the maximum number of scores to MAX.\n");
78 fprintf (stdout, " -r\t\tSort the scores in increasing order.\n");
79 fprintf (stdout, " -d DIR\t\tStore scores in DIR (only if not setuid).\n");
80 exit (err);
83 static int lock_file (const char *filename, void **state);
84 static int unlock_file (const char *filename, void *state);
86 struct score_entry
88 long score;
89 char *username;
90 char *data;
93 static int read_scores (const char *filename, struct score_entry **scores,
94 int *count);
95 static int push_score (struct score_entry **scores, int *count,
96 int newscore, char *username, char *newdata);
97 static void sort_scores (struct score_entry *scores, int count, int reverse);
98 static int write_scores (const char *filename,
99 const struct score_entry *scores, int count);
101 static void lose (const char *msg) NO_RETURN;
103 static void
104 lose (const char *msg)
106 fprintf (stderr, "%s\n", msg);
107 exit (EXIT_FAILURE);
110 static void lose_syserr (const char *msg) NO_RETURN;
112 /* Taken from sysdep.c. */
113 #ifndef HAVE_STRERROR
114 #ifndef WINDOWSNT
115 char *
116 strerror (errnum)
117 int errnum;
119 extern char *sys_errlist[];
120 extern int sys_nerr;
122 if (errnum >= 0 && errnum < sys_nerr)
123 return sys_errlist[errnum];
124 return (char *) "Unknown error";
126 #endif /* not WINDOWSNT */
127 #endif /* ! HAVE_STRERROR */
129 static void
130 lose_syserr (const char *msg)
132 fprintf (stderr, "%s: %s\n", msg, strerror (errno));
133 exit (EXIT_FAILURE);
136 static char *
137 get_user_id (void)
139 char *name;
140 struct passwd *buf = getpwuid (getuid ());
141 if (!buf)
143 int count = 1;
144 int uid = (int) getuid ();
145 int tuid = uid;
146 while (tuid /= 10)
147 count++;
148 name = malloc (count+1);
149 if (!name)
150 return NULL;
151 sprintf (name, "%d", uid);
152 return name;
154 return buf->pw_name;
157 static const char *
158 get_prefix (int running_suid, const char *user_prefix)
160 if (!running_suid && user_prefix == NULL)
161 lose ("Not using a shared game directory, and no prefix given.");
162 if (running_suid)
164 #ifdef HAVE_SHARED_GAME_DIR
165 return HAVE_SHARED_GAME_DIR;
166 #else
167 lose ("This program was compiled without HAVE_SHARED_GAME_DIR,\n and should not be suid.");
168 #endif
170 return user_prefix;
174 main (int argc, char **argv)
176 int c, running_suid;
177 void *lockstate;
178 char *user_id, *scorefile;
179 const char *prefix, *user_prefix = NULL;
180 struct stat buf;
181 struct score_entry *scores;
182 int newscore, scorecount, reverse = 0, max = MAX_SCORES;
183 char *newdata;
185 srand (time (0));
187 while ((c = getopt (argc, argv, "hrm:d:")) != -1)
188 switch (c)
190 case 'h':
191 usage (EXIT_SUCCESS);
192 break;
193 case 'd':
194 user_prefix = optarg;
195 break;
196 case 'r':
197 reverse = 1;
198 break;
199 case 'm':
200 max = atoi (optarg);
201 if (max > MAX_SCORES)
202 max = MAX_SCORES;
203 break;
204 default:
205 usage (EXIT_FAILURE);
208 if (optind+3 != argc)
209 usage (EXIT_FAILURE);
211 running_suid = (getuid () != geteuid ());
213 prefix = get_prefix (running_suid, user_prefix);
215 scorefile = malloc (strlen (prefix) + strlen (argv[optind]) + 2);
216 if (!scorefile)
217 lose_syserr ("Couldn't allocate score file");
219 strcpy (scorefile, prefix);
220 strcat (scorefile, "/");
221 strcat (scorefile, argv[optind]);
222 newscore = atoi (argv[optind+1]);
223 newdata = argv[optind+2];
224 if (strlen (newdata) > MAX_DATA_LEN)
225 newdata[MAX_DATA_LEN] = '\0';
227 user_id = get_user_id ();
228 if (user_id == NULL)
229 lose_syserr ("Couldn't determine user id");
231 if (stat (scorefile, &buf) < 0)
232 lose_syserr ("Failed to access scores file");
234 if (lock_file (scorefile, &lockstate) < 0)
235 lose_syserr ("Failed to lock scores file");
237 if (read_scores (scorefile, &scores, &scorecount) < 0)
239 unlock_file (scorefile, lockstate);
240 lose_syserr ("Failed to read scores file");
242 push_score (&scores, &scorecount, newscore, user_id, newdata);
243 sort_scores (scores, scorecount, reverse);
244 /* Limit the number of scores. If we're using reverse sorting, then
245 also increment the beginning of the array, to skip over the
246 *smallest* scores. Otherwise, just decrementing the number of
247 scores suffices, since the smallest is at the end. */
248 if (scorecount > MAX_SCORES)
250 if (reverse)
251 scores += (scorecount - MAX_SCORES);
252 scorecount = MAX_SCORES;
254 if (write_scores (scorefile, scores, scorecount) < 0)
256 unlock_file (scorefile, lockstate);
257 lose_syserr ("Failed to write scores file");
259 unlock_file (scorefile, lockstate);
260 exit (EXIT_SUCCESS);
263 static int
264 read_score (FILE *f, struct score_entry *score)
266 int c;
267 if (feof (f))
268 return 1;
269 while ((c = getc (f)) != EOF
270 && isdigit (c))
272 score->score *= 10;
273 score->score += (c-48);
275 while ((c = getc (f)) != EOF
276 && isspace (c))
278 if (c == EOF)
279 return -1;
280 ungetc (c, f);
281 #ifdef HAVE_GETDELIM
283 size_t count = 0;
284 if (getdelim (&score->username, &count, ' ', f) < 1
285 || score->username == NULL)
286 return -1;
287 /* Trim the space */
288 score->username[strlen (score->username)-1] = '\0';
290 #else
292 int unameread = 0;
293 int unamelen = 30;
294 char *username = malloc (unamelen);
295 if (!username)
296 return -1;
298 while ((c = getc (f)) != EOF
299 && !isspace (c))
301 if (unameread >= unamelen-1)
302 if (!(username = realloc (username, unamelen *= 2)))
303 return -1;
304 username[unameread] = c;
305 unameread++;
307 if (c == EOF)
308 return -1;
309 username[unameread] = '\0';
310 score->username = username;
312 #endif
313 #ifdef HAVE_GETLINE
314 score->data = NULL;
315 errno = 0;
317 size_t len;
318 if (getline (&score->data, &len, f) < 0)
319 return -1;
320 score->data[strlen (score->data)-1] = '\0';
322 #else
324 int cur = 0;
325 int len = 16;
326 char *buf = malloc (len);
327 if (!buf)
328 return -1;
329 while ((c = getc (f)) != EOF
330 && c != '\n')
332 if (cur >= len-1)
334 if (!(buf = realloc (buf, len *= 2)))
335 return -1;
337 buf[cur] = c;
338 cur++;
340 score->data = buf;
341 score->data[cur] = '\0';
343 #endif
344 return 0;
347 static int
348 read_scores (const char *filename, struct score_entry **scores, int *count)
350 int readval, scorecount, cursize;
351 struct score_entry *ret;
352 FILE *f = fopen (filename, "r");
353 if (!f)
354 return -1;
355 scorecount = 0;
356 cursize = 16;
357 ret = (struct score_entry *) malloc (sizeof (struct score_entry) * cursize);
358 if (!ret)
359 return -1;
360 while ((readval = read_score (f, &ret[scorecount])) == 0)
362 /* We encoutered an error */
363 if (readval < 0)
364 return -1;
365 scorecount++;
366 if (scorecount >= cursize)
368 cursize *= 2;
369 ret = (struct score_entry *)
370 realloc (ret, (sizeof (struct score_entry) * cursize));
371 if (!ret)
372 return -1;
375 *count = scorecount;
376 *scores = ret;
377 return 0;
380 static int
381 score_compare (const void *a, const void *b)
383 const struct score_entry *sa = (const struct score_entry *) a;
384 const struct score_entry *sb = (const struct score_entry *) b;
385 return (sb->score > sa->score) - (sb->score < sa->score);
388 static int
389 score_compare_reverse (const void *a, const void *b)
391 const struct score_entry *sa = (const struct score_entry *) a;
392 const struct score_entry *sb = (const struct score_entry *) b;
393 return (sa->score > sb->score) - (sa->score < sb->score);
397 push_score (struct score_entry **scores, int *count, int newscore, char *username, char *newdata)
399 struct score_entry *newscores
400 = (struct score_entry *) realloc (*scores,
401 sizeof (struct score_entry) * ((*count) + 1));
402 if (!newscores)
403 return -1;
404 newscores[*count].score = newscore;
405 newscores[*count].username = username;
406 newscores[*count].data = newdata;
407 (*count) += 1;
408 *scores = newscores;
409 return 0;
412 static void
413 sort_scores (struct score_entry *scores, int count, int reverse)
415 qsort (scores, count, sizeof (struct score_entry),
416 reverse ? score_compare_reverse : score_compare);
419 static int
420 write_scores (const char *filename, const struct score_entry *scores, int count)
422 FILE *f;
423 int i;
424 char *tempfile = malloc (strlen (filename) + strlen (".tempXXXXXX") + 1);
425 if (!tempfile)
426 return -1;
427 strcpy (tempfile, filename);
428 strcat (tempfile, ".tempXXXXXX");
429 #ifdef HAVE_MKSTEMP
430 if (mkstemp (tempfile) < 0
431 #else
432 if (mktemp (tempfile) != tempfile
433 #endif
434 || !(f = fopen (tempfile, "w")))
435 return -1;
436 for (i = 0; i < count; i++)
437 if (fprintf (f, "%ld %s %s\n", scores[i].score, scores[i].username,
438 scores[i].data) < 0)
439 return -1;
440 fclose (f);
441 if (rename (tempfile, filename) < 0)
442 return -1;
443 if (chmod (filename, 0644) < 0)
444 return -1;
445 return 0;
448 static int
449 lock_file (const char *filename, void **state)
451 int fd;
452 struct stat buf;
453 int attempts = 0;
454 const char *lockext = ".lockfile";
455 char *lockpath = malloc (strlen (filename) + strlen (lockext) + 60);
456 if (!lockpath)
457 return -1;
458 strcpy (lockpath, filename);
459 strcat (lockpath, lockext);
460 *state = lockpath;
461 trylock:
462 attempts++;
463 /* If the lock is over an hour old, delete it. */
464 if (stat (lockpath, &buf) == 0
465 && (difftime (buf.st_ctime, time (NULL) > 60*60)))
466 unlink (lockpath);
467 fd = open (lockpath, O_CREAT | O_EXCL, 0600);
468 if (fd < 0)
470 if (errno == EEXIST)
472 /* Break the lock; we won't corrupt the file, but we might
473 lose some scores. */
474 if (attempts > MAX_ATTEMPTS)
476 unlink (lockpath);
477 attempts = 0;
479 sleep ((rand () % 2)+1);
480 goto trylock;
482 else
483 return -1;
485 close (fd);
486 return 0;
489 static int
490 unlock_file (const char *filename, void *state)
492 char *lockpath = (char *) state;
493 int ret = unlink (lockpath);
494 int saved_errno = errno;
495 free (lockpath);
496 errno = saved_errno;
497 return ret;
501 /* update-game-score.c ends here */