(Fread_file_name): Remove reference to insdef, deleted 2008-04-23.
[bpt/emacs.git] / lib-src / update-game-score.c
1 /* update-game-score.c --- Update a score file
2 Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007, 2008
3 Free Software Foundation, Inc.
4
5 This file is part of GNU Emacs.
6
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.
11
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.
16
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. */
21
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'.
25
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).
29
30 Created 2002/03/22, by Colin Walters <walters@debian.org>
31 */
32
33 #include <config.h>
34
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>
56
57 /* Needed for SunOS4, for instance. */
58 extern char *optarg;
59 extern int optind, opterr;
60
61 #define MAX_ATTEMPTS 5
62 #define MAX_SCORES 200
63 #define MAX_DATA_LEN 1024
64
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
71
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
76
77 int
78 usage (err)
79 int err;
80 {
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);
88 }
89
90 int lock_file P_ ((const char *filename, void **state));
91 int unlock_file P_ ((const char *filename, void *state));
92
93 struct score_entry
94 {
95 long score;
96 char *username;
97 char *data;
98 };
99
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));
107
108 void lose P_ ((const char *msg)) NO_RETURN;
109
110 void
111 lose (msg)
112 const char *msg;
113 {
114 fprintf (stderr, "%s\n", msg);
115 exit (EXIT_FAILURE);
116 }
117
118 void lose_syserr P_ ((const char *msg)) NO_RETURN;
119
120 /* Taken from sysdep.c. */
121 #ifndef HAVE_STRERROR
122 #ifndef WINDOWSNT
123 char *
124 strerror (errnum)
125 int errnum;
126 {
127 extern char *sys_errlist[];
128 extern int sys_nerr;
129
130 if (errnum >= 0 && errnum < sys_nerr)
131 return sys_errlist[errnum];
132 return (char *) "Unknown error";
133 }
134 #endif /* not WINDOWSNT */
135 #endif /* ! HAVE_STRERROR */
136
137 void
138 lose_syserr (msg)
139 const char *msg;
140 {
141 fprintf (stderr, "%s: %s\n", msg, strerror (errno));
142 exit (EXIT_FAILURE);
143 }
144
145 char *
146 get_user_id P_ ((void))
147 {
148 char *name;
149 struct passwd *buf = getpwuid (getuid ());
150 if (!buf)
151 {
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;
162 }
163 return buf->pw_name;
164 }
165
166 char *
167 get_prefix (running_suid, user_prefix)
168 int running_suid;
169 char *user_prefix;
170 {
171 if (!running_suid && user_prefix == NULL)
172 lose ("Not using a shared game directory, and no prefix given.");
173 if (running_suid)
174 {
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
180 }
181 return user_prefix;
182 }
183
184 int
185 main (argc, argv)
186 int argc;
187 char **argv;
188 {
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;
196
197 srand (time (0));
198
199 while ((c = getopt (argc, argv, "hrm:d:")) != -1)
200 switch (c)
201 {
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);
218 }
219
220 if (optind+3 != argc)
221 usage (EXIT_FAILURE);
222
223 running_suid = (getuid () != geteuid ());
224
225 prefix = get_prefix (running_suid, user_prefix);
226
227 scorefile = malloc (strlen (prefix) + strlen (argv[optind]) + 2);
228 if (!scorefile)
229 lose_syserr ("Couldn't allocate score file");
230
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';
238
239 user_id = get_user_id ();
240 if (user_id == NULL)
241 lose_syserr ("Couldn't determine user id");
242
243 if (stat (scorefile, &buf) < 0)
244 lose_syserr ("Failed to access scores file");
245
246 if (lock_file (scorefile, &lockstate) < 0)
247 lose_syserr ("Failed to lock scores file");
248
249 if (read_scores (scorefile, &scores, &scorecount) < 0)
250 {
251 unlock_file (scorefile, lockstate);
252 lose_syserr ("Failed to read scores file");
253 }
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)
265 {
266 unlock_file (scorefile, lockstate);
267 lose_syserr ("Failed to write scores file");
268 }
269 unlock_file (scorefile, lockstate);
270 exit (EXIT_SUCCESS);
271 }
272
273 int
274 read_score (f, score)
275 FILE *f;
276 struct score_entry *score;
277 {
278 int c;
279 if (feof (f))
280 return 1;
281 while ((c = getc (f)) != EOF
282 && isdigit (c))
283 {
284 score->score *= 10;
285 score->score += (c-48);
286 }
287 while ((c = getc (f)) != EOF
288 && isspace (c))
289 ;
290 if (c == EOF)
291 return -1;
292 ungetc (c, f);
293 #ifdef HAVE_GETDELIM
294 {
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';
301 }
302 #else
303 {
304 int unameread = 0;
305 int unamelen = 30;
306 char *username = malloc (unamelen);
307 if (!username)
308 return -1;
309
310 while ((c = getc (f)) != EOF
311 && !isspace (c))
312 {
313 if (unameread >= unamelen-1)
314 if (!(username = realloc (username, unamelen *= 2)))
315 return -1;
316 username[unameread] = c;
317 unameread++;
318 }
319 if (c == EOF)
320 return -1;
321 username[unameread] = '\0';
322 score->username = username;
323 }
324 #endif
325 #ifdef HAVE_GETLINE
326 score->data = NULL;
327 errno = 0;
328 {
329 size_t len;
330 if (getline (&score->data, &len, f) < 0)
331 return -1;
332 score->data[strlen (score->data)-1] = '\0';
333 }
334 #else
335 {
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')
343 {
344 if (cur >= len-1)
345 {
346 if (!(buf = realloc (buf, len *= 2)))
347 return -1;
348 }
349 buf[cur] = c;
350 cur++;
351 }
352 score->data = buf;
353 score->data[cur] = '\0';
354 }
355 #endif
356 return 0;
357 }
358
359 int
360 read_scores (filename, scores, count)
361 const char *filename;
362 struct score_entry **scores;
363 int *count;
364 {
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)
376 {
377 /* We encoutered an error */
378 if (readval < 0)
379 return -1;
380 scorecount++;
381 if (scorecount >= cursize)
382 {
383 cursize *= 2;
384 ret = (struct score_entry *)
385 realloc (ret, (sizeof (struct score_entry) * cursize));
386 if (!ret)
387 return -1;
388 }
389 }
390 *count = scorecount;
391 *scores = ret;
392 return 0;
393 }
394
395 int
396 score_compare (a, b)
397 const void *a;
398 const void *b;
399 {
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);
403 }
404
405 int
406 score_compare_reverse (a, b)
407 const void *a;
408 const void *b;
409 {
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);
413 }
414
415 int
416 push_score (scores, count, newscore, username, newdata)
417 struct score_entry **scores;
418 int *count; int newscore;
419 char *username;
420 char *newdata;
421 {
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;
433 }
434
435 void
436 sort_scores (scores, count, reverse)
437 struct score_entry *scores;
438 int count;
439 int reverse;
440 {
441 qsort (scores, count, sizeof (struct score_entry),
442 reverse ? score_compare_reverse : score_compare);
443 }
444
445 int
446 write_scores (filename, scores, count)
447 const char *filename;
448 const struct score_entry * scores;
449 int count;
450 {
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;
475 }
476
477 int
478 lock_file (filename, state)
479 const char *filename;
480 void **state;
481 {
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)
500 {
501 if (errno == EEXIST)
502 {
503 /* Break the lock; we won't corrupt the file, but we might
504 lose some scores. */
505 if (attempts > MAX_ATTEMPTS)
506 {
507 unlink (lockpath);
508 attempts = 0;
509 }
510 sleep ((rand () % 2)+1);
511 goto trylock;
512 }
513 else
514 return -1;
515 }
516 close (fd);
517 return 0;
518 }
519
520 int
521 unlock_file (filename, state)
522 const char *filename;
523 void *state;
524 {
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;
531 }
532
533 /* arch-tag: 2bf5c52e-4beb-463a-954e-c58b9c64736b
534 (do not change this comment) */
535
536 /* update-game-score.c ends here */