* customize.texi (Composite Types): Move alist/plist from Simple Types (Bug#7545).
[emacs.git] / lib-src / update-game-score.c
blobeb68dc09642751d6c96b7608af934b9c5c9db074
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 #ifdef HAVE_UNISTD_H
38 #include <unistd.h>
39 #endif
40 #include <errno.h>
41 #ifdef HAVE_STRING_H
42 #include <string.h>
43 #endif
44 #ifdef HAVE_STDLIB_H
45 #include <stdlib.h>
46 #endif
47 #include <stdio.h>
48 #include <time.h>
49 #include <pwd.h>
50 #include <ctype.h>
51 #ifdef HAVE_FCNTL_H
52 #include <fcntl.h>
53 #endif
54 #ifdef STDC_HEADERS
55 #include <stdarg.h>
56 #endif
57 #include <sys/stat.h>
59 /* Needed for SunOS4, for instance. */
60 extern char *optarg;
61 extern int optind, opterr;
63 #define MAX_ATTEMPTS 5
64 #define MAX_SCORES 200
65 #define MAX_DATA_LEN 1024
67 /* Declare the prototype for a general external function. */
68 #if defined (PROTOTYPES) || defined (WINDOWSNT)
69 #define P_(proto) proto
70 #else
71 #define P_(proto) ()
72 #endif
74 #ifndef HAVE_DIFFTIME
75 /* OK on POSIX (time_t is arithmetic type) modulo overflow in subtraction. */
76 #define difftime(t1, t0) (double)((t1) - (t0))
77 #endif
79 int
80 usage (err)
81 int err;
83 fprintf (stdout, "Usage: update-game-score [-m MAX ] [ -r ] game/scorefile SCORE DATA\n");
84 fprintf (stdout, " update-game-score -h\n");
85 fprintf (stdout, " -h\t\tDisplay this help.\n");
86 fprintf (stdout, " -m MAX\t\tLimit the maximum number of scores to MAX.\n");
87 fprintf (stdout, " -r\t\tSort the scores in increasing order.\n");
88 fprintf (stdout, " -d DIR\t\tStore scores in DIR (only if not setuid).\n");
89 exit (err);
92 int lock_file P_ ((const char *filename, void **state));
93 int unlock_file P_ ((const char *filename, void *state));
95 struct score_entry
97 long score;
98 char *username;
99 char *data;
102 int read_scores P_ ((const char *filename, struct score_entry **scores,
103 int *count));
104 int push_score P_ ((struct score_entry **scores, int *count,
105 int newscore, char *username, char *newdata));
106 void sort_scores P_ ((struct score_entry *scores, int count, int reverse));
107 int write_scores P_ ((const char *filename, const struct score_entry *scores,
108 int count));
110 void lose P_ ((const char *msg)) NO_RETURN;
112 void
113 lose (msg)
114 const char *msg;
116 fprintf (stderr, "%s\n", msg);
117 exit (EXIT_FAILURE);
120 void lose_syserr P_ ((const char *msg)) NO_RETURN;
122 /* Taken from sysdep.c. */
123 #ifndef HAVE_STRERROR
124 #ifndef WINDOWSNT
125 char *
126 strerror (errnum)
127 int errnum;
129 extern char *sys_errlist[];
130 extern int sys_nerr;
132 if (errnum >= 0 && errnum < sys_nerr)
133 return sys_errlist[errnum];
134 return (char *) "Unknown error";
136 #endif /* not WINDOWSNT */
137 #endif /* ! HAVE_STRERROR */
139 void
140 lose_syserr (msg)
141 const char *msg;
143 fprintf (stderr, "%s: %s\n", msg, strerror (errno));
144 exit (EXIT_FAILURE);
147 char *
148 get_user_id P_ ((void))
150 char *name;
151 struct passwd *buf = getpwuid (getuid ());
152 if (!buf)
154 int count = 1;
155 int uid = (int) getuid ();
156 int tuid = uid;
157 while (tuid /= 10)
158 count++;
159 name = malloc (count+1);
160 if (!name)
161 return NULL;
162 sprintf (name, "%d", uid);
163 return name;
165 return buf->pw_name;
168 char *
169 get_prefix (running_suid, user_prefix)
170 int running_suid;
171 char *user_prefix;
173 if (!running_suid && user_prefix == NULL)
174 lose ("Not using a shared game directory, and no prefix given.");
175 if (running_suid)
177 #ifdef HAVE_SHARED_GAME_DIR
178 return HAVE_SHARED_GAME_DIR;
179 #else
180 lose ("This program was compiled without HAVE_SHARED_GAME_DIR,\n and should not be suid.");
181 #endif
183 return user_prefix;
187 main (argc, argv)
188 int argc;
189 char **argv;
191 int c, running_suid;
192 void *lockstate;
193 char *user_id, *scorefile, *prefix, *user_prefix = NULL;
194 struct stat buf;
195 struct score_entry *scores;
196 int newscore, scorecount, reverse = 0, max = MAX_SCORES;
197 char *newdata;
199 srand (time (0));
201 while ((c = getopt (argc, argv, "hrm:d:")) != -1)
202 switch (c)
204 case 'h':
205 usage (EXIT_SUCCESS);
206 break;
207 case 'd':
208 user_prefix = optarg;
209 break;
210 case 'r':
211 reverse = 1;
212 break;
213 case 'm':
214 max = atoi (optarg);
215 if (max > MAX_SCORES)
216 max = MAX_SCORES;
217 break;
218 default:
219 usage (EXIT_FAILURE);
222 if (optind+3 != argc)
223 usage (EXIT_FAILURE);
225 running_suid = (getuid () != geteuid ());
227 prefix = get_prefix (running_suid, user_prefix);
229 scorefile = malloc (strlen (prefix) + strlen (argv[optind]) + 2);
230 if (!scorefile)
231 lose_syserr ("Couldn't allocate score file");
233 strcpy (scorefile, prefix);
234 strcat (scorefile, "/");
235 strcat (scorefile, argv[optind]);
236 newscore = atoi (argv[optind+1]);
237 newdata = argv[optind+2];
238 if (strlen (newdata) > MAX_DATA_LEN)
239 newdata[MAX_DATA_LEN] = '\0';
241 user_id = get_user_id ();
242 if (user_id == NULL)
243 lose_syserr ("Couldn't determine user id");
245 if (stat (scorefile, &buf) < 0)
246 lose_syserr ("Failed to access scores file");
248 if (lock_file (scorefile, &lockstate) < 0)
249 lose_syserr ("Failed to lock scores file");
251 if (read_scores (scorefile, &scores, &scorecount) < 0)
253 unlock_file (scorefile, lockstate);
254 lose_syserr ("Failed to read scores file");
256 push_score (&scores, &scorecount, newscore, user_id, newdata);
257 sort_scores (scores, scorecount, reverse);
258 /* Limit the number of scores. If we're using reverse sorting, then
259 we should increment the beginning of the array, to skip over the
260 *smallest* scores. Otherwise, we just decrement the number of
261 scores, since the smallest will be at the end. */
262 if (scorecount > MAX_SCORES)
263 scorecount -= (scorecount - MAX_SCORES);
264 if (reverse)
265 scores += (scorecount - MAX_SCORES);
266 if (write_scores (scorefile, scores, scorecount) < 0)
268 unlock_file (scorefile, lockstate);
269 lose_syserr ("Failed to write scores file");
271 unlock_file (scorefile, lockstate);
272 exit (EXIT_SUCCESS);
276 read_score (f, score)
277 FILE *f;
278 struct score_entry *score;
280 int c;
281 if (feof (f))
282 return 1;
283 while ((c = getc (f)) != EOF
284 && isdigit (c))
286 score->score *= 10;
287 score->score += (c-48);
289 while ((c = getc (f)) != EOF
290 && isspace (c))
292 if (c == EOF)
293 return -1;
294 ungetc (c, f);
295 #ifdef HAVE_GETDELIM
297 size_t count = 0;
298 if (getdelim (&score->username, &count, ' ', f) < 1
299 || score->username == NULL)
300 return -1;
301 /* Trim the space */
302 score->username[strlen (score->username)-1] = '\0';
304 #else
306 int unameread = 0;
307 int unamelen = 30;
308 char *username = malloc (unamelen);
309 if (!username)
310 return -1;
312 while ((c = getc (f)) != EOF
313 && !isspace (c))
315 if (unameread >= unamelen-1)
316 if (!(username = realloc (username, unamelen *= 2)))
317 return -1;
318 username[unameread] = c;
319 unameread++;
321 if (c == EOF)
322 return -1;
323 username[unameread] = '\0';
324 score->username = username;
326 #endif
327 #ifdef HAVE_GETLINE
328 score->data = NULL;
329 errno = 0;
331 size_t len;
332 if (getline (&score->data, &len, f) < 0)
333 return -1;
334 score->data[strlen (score->data)-1] = '\0';
336 #else
338 int cur = 0;
339 int len = 16;
340 char *buf = malloc (len);
341 if (!buf)
342 return -1;
343 while ((c = getc (f)) != EOF
344 && c != '\n')
346 if (cur >= len-1)
348 if (!(buf = realloc (buf, len *= 2)))
349 return -1;
351 buf[cur] = c;
352 cur++;
354 score->data = buf;
355 score->data[cur] = '\0';
357 #endif
358 return 0;
362 read_scores (filename, scores, count)
363 const char *filename;
364 struct score_entry **scores;
365 int *count;
367 int readval, scorecount, cursize;
368 struct score_entry *ret;
369 FILE *f = fopen (filename, "r");
370 if (!f)
371 return -1;
372 scorecount = 0;
373 cursize = 16;
374 ret = (struct score_entry *) malloc (sizeof (struct score_entry) * cursize);
375 if (!ret)
376 return -1;
377 while ((readval = read_score (f, &ret[scorecount])) == 0)
379 /* We encoutered an error */
380 if (readval < 0)
381 return -1;
382 scorecount++;
383 if (scorecount >= cursize)
385 cursize *= 2;
386 ret = (struct score_entry *)
387 realloc (ret, (sizeof (struct score_entry) * cursize));
388 if (!ret)
389 return -1;
392 *count = scorecount;
393 *scores = ret;
394 return 0;
398 score_compare (a, b)
399 const void *a;
400 const void *b;
402 const struct score_entry *sa = (const struct score_entry *) a;
403 const struct score_entry *sb = (const struct score_entry *) b;
404 return (sb->score > sa->score) - (sb->score < sa->score);
408 score_compare_reverse (a, b)
409 const void *a;
410 const void *b;
412 const struct score_entry *sa = (const struct score_entry *) a;
413 const struct score_entry *sb = (const struct score_entry *) b;
414 return (sa->score > sb->score) - (sa->score < sb->score);
418 push_score (scores, count, newscore, username, newdata)
419 struct score_entry **scores;
420 int *count; int newscore;
421 char *username;
422 char *newdata;
424 struct score_entry *newscores
425 = (struct score_entry *) realloc (*scores,
426 sizeof (struct score_entry) * ((*count) + 1));
427 if (!newscores)
428 return -1;
429 newscores[*count].score = newscore;
430 newscores[*count].username = username;
431 newscores[*count].data = newdata;
432 (*count) += 1;
433 *scores = newscores;
434 return 0;
437 void
438 sort_scores (scores, count, reverse)
439 struct score_entry *scores;
440 int count;
441 int reverse;
443 qsort (scores, count, sizeof (struct score_entry),
444 reverse ? score_compare_reverse : score_compare);
448 write_scores (filename, scores, count)
449 const char *filename;
450 const struct score_entry * scores;
451 int count;
453 FILE *f;
454 int i;
455 char *tempfile = malloc (strlen (filename) + strlen (".tempXXXXXX") + 1);
456 if (!tempfile)
457 return -1;
458 strcpy (tempfile, filename);
459 strcat (tempfile, ".tempXXXXXX");
460 #ifdef HAVE_MKSTEMP
461 if (mkstemp (tempfile) < 0
462 #else
463 if (mktemp (tempfile) != tempfile
464 #endif
465 || !(f = fopen (tempfile, "w")))
466 return -1;
467 for (i = 0; i < count; i++)
468 if (fprintf (f, "%ld %s %s\n", scores[i].score, scores[i].username,
469 scores[i].data) < 0)
470 return -1;
471 fclose (f);
472 if (rename (tempfile, filename) < 0)
473 return -1;
474 if (chmod (filename, 0644) < 0)
475 return -1;
476 return 0;
480 lock_file (filename, state)
481 const char *filename;
482 void **state;
484 int fd;
485 struct stat buf;
486 int attempts = 0;
487 char *lockext = ".lockfile";
488 char *lockpath = malloc (strlen (filename) + strlen (lockext) + 60);
489 if (!lockpath)
490 return -1;
491 strcpy (lockpath, filename);
492 strcat (lockpath, lockext);
493 *state = lockpath;
494 trylock:
495 attempts++;
496 /* If the lock is over an hour old, delete it. */
497 if (stat (lockpath, &buf) == 0
498 && (difftime (buf.st_ctime, time (NULL) > 60*60)))
499 unlink (lockpath);
500 fd = open (lockpath, O_CREAT | O_EXCL, 0600);
501 if (fd < 0)
503 if (errno == EEXIST)
505 /* Break the lock; we won't corrupt the file, but we might
506 lose some scores. */
507 if (attempts > MAX_ATTEMPTS)
509 unlink (lockpath);
510 attempts = 0;
512 sleep ((rand () % 2)+1);
513 goto trylock;
515 else
516 return -1;
518 close (fd);
519 return 0;
523 unlock_file (filename, state)
524 const char *filename;
525 void *state;
527 char *lockpath = (char *) state;
528 int ret = unlink (lockpath);
529 int saved_errno = errno;
530 free (lockpath);
531 errno = saved_errno;
532 return ret;
535 /* arch-tag: 2bf5c52e-4beb-463a-954e-c58b9c64736b
536 (do not change this comment) */
538 /* update-game-score.c ends here */