(proced-mode-map): Prefer "m" for proced-mark.
[bpt/emacs.git] / lib-src / update-game-score.c
... / ...
CommitLineData
1/* update-game-score.c --- Update a score file
2
3Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009
4 Free Software Foundation, Inc.
5
6Author: Colin Walters <walters@debian.org>
7
8This file is part of GNU Emacs.
9
10GNU Emacs is free software: you can redistribute it and/or modify
11it under the terms of the GNU General Public License as published by
12the Free Software Foundation, either version 3 of the License, or
13(at your option) any later version.
14
15GNU Emacs is distributed in the hope that it will be useful,
16but WITHOUT ANY WARRANTY; without even the implied warranty of
17MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18GNU General Public License for more details.
19
20You should have received a copy of the GNU General Public License
21along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
22
23
24/* This program is 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'.
27
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).
31
32 Created 2002/03/22.
33*/
34
35#include <config.h>
36
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>
58
59/* Needed for SunOS4, for instance. */
60extern char *optarg;
61extern int optind, opterr;
62
63#define MAX_ATTEMPTS 5
64#define MAX_SCORES 200
65#define MAX_DATA_LEN 1024
66
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
73
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
78
79int
80usage (err)
81 int err;
82{
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);
90}
91
92int lock_file P_ ((const char *filename, void **state));
93int unlock_file P_ ((const char *filename, void *state));
94
95struct score_entry
96{
97 long score;
98 char *username;
99 char *data;
100};
101
102int read_scores P_ ((const char *filename, struct score_entry **scores,
103 int *count));
104int push_score P_ ((struct score_entry **scores, int *count,
105 int newscore, char *username, char *newdata));
106void sort_scores P_ ((struct score_entry *scores, int count, int reverse));
107int write_scores P_ ((const char *filename, const struct score_entry *scores,
108 int count));
109
110void lose P_ ((const char *msg)) NO_RETURN;
111
112void
113lose (msg)
114 const char *msg;
115{
116 fprintf (stderr, "%s\n", msg);
117 exit (EXIT_FAILURE);
118}
119
120void lose_syserr P_ ((const char *msg)) NO_RETURN;
121
122/* Taken from sysdep.c. */
123#ifndef HAVE_STRERROR
124#ifndef WINDOWSNT
125char *
126strerror (errnum)
127 int errnum;
128{
129 extern char *sys_errlist[];
130 extern int sys_nerr;
131
132 if (errnum >= 0 && errnum < sys_nerr)
133 return sys_errlist[errnum];
134 return (char *) "Unknown error";
135}
136#endif /* not WINDOWSNT */
137#endif /* ! HAVE_STRERROR */
138
139void
140lose_syserr (msg)
141 const char *msg;
142{
143 fprintf (stderr, "%s: %s\n", msg, strerror (errno));
144 exit (EXIT_FAILURE);
145}
146
147char *
148get_user_id P_ ((void))
149{
150 char *name;
151 struct passwd *buf = getpwuid (getuid ());
152 if (!buf)
153 {
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;
164 }
165 return buf->pw_name;
166}
167
168char *
169get_prefix (running_suid, user_prefix)
170 int running_suid;
171 char *user_prefix;
172{
173 if (!running_suid && user_prefix == NULL)
174 lose ("Not using a shared game directory, and no prefix given.");
175 if (running_suid)
176 {
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
182 }
183 return user_prefix;
184}
185
186int
187main (argc, argv)
188 int argc;
189 char **argv;
190{
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;
198
199 srand (time (0));
200
201 while ((c = getopt (argc, argv, "hrm:d:")) != -1)
202 switch (c)
203 {
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);
220 }
221
222 if (optind+3 != argc)
223 usage (EXIT_FAILURE);
224
225 running_suid = (getuid () != geteuid ());
226
227 prefix = get_prefix (running_suid, user_prefix);
228
229 scorefile = malloc (strlen (prefix) + strlen (argv[optind]) + 2);
230 if (!scorefile)
231 lose_syserr ("Couldn't allocate score file");
232
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';
240
241 user_id = get_user_id ();
242 if (user_id == NULL)
243 lose_syserr ("Couldn't determine user id");
244
245 if (stat (scorefile, &buf) < 0)
246 lose_syserr ("Failed to access scores file");
247
248 if (lock_file (scorefile, &lockstate) < 0)
249 lose_syserr ("Failed to lock scores file");
250
251 if (read_scores (scorefile, &scores, &scorecount) < 0)
252 {
253 unlock_file (scorefile, lockstate);
254 lose_syserr ("Failed to read scores file");
255 }
256 push_score (&scores, &scorecount, newscore, user_id, newdata);
257 /* Limit the number of scores. If we're using reverse sorting, then
258 we should increment the beginning of the array, to skip over the
259 *smallest* scores. Otherwise, we just decrement the number of
260 scores, since the smallest will be at the end. */
261 if (scorecount > MAX_SCORES)
262 scorecount -= (scorecount - MAX_SCORES);
263 if (reverse)
264 scores += (scorecount - MAX_SCORES);
265 sort_scores (scores, scorecount, reverse);
266 if (write_scores (scorefile, scores, scorecount) < 0)
267 {
268 unlock_file (scorefile, lockstate);
269 lose_syserr ("Failed to write scores file");
270 }
271 unlock_file (scorefile, lockstate);
272 exit (EXIT_SUCCESS);
273}
274
275int
276read_score (f, score)
277 FILE *f;
278 struct score_entry *score;
279{
280 int c;
281 if (feof (f))
282 return 1;
283 while ((c = getc (f)) != EOF
284 && isdigit (c))
285 {
286 score->score *= 10;
287 score->score += (c-48);
288 }
289 while ((c = getc (f)) != EOF
290 && isspace (c))
291 ;
292 if (c == EOF)
293 return -1;
294 ungetc (c, f);
295#ifdef HAVE_GETDELIM
296 {
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';
303 }
304#else
305 {
306 int unameread = 0;
307 int unamelen = 30;
308 char *username = malloc (unamelen);
309 if (!username)
310 return -1;
311
312 while ((c = getc (f)) != EOF
313 && !isspace (c))
314 {
315 if (unameread >= unamelen-1)
316 if (!(username = realloc (username, unamelen *= 2)))
317 return -1;
318 username[unameread] = c;
319 unameread++;
320 }
321 if (c == EOF)
322 return -1;
323 username[unameread] = '\0';
324 score->username = username;
325 }
326#endif
327#ifdef HAVE_GETLINE
328 score->data = NULL;
329 errno = 0;
330 {
331 size_t len;
332 if (getline (&score->data, &len, f) < 0)
333 return -1;
334 score->data[strlen (score->data)-1] = '\0';
335 }
336#else
337 {
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')
345 {
346 if (cur >= len-1)
347 {
348 if (!(buf = realloc (buf, len *= 2)))
349 return -1;
350 }
351 buf[cur] = c;
352 cur++;
353 }
354 score->data = buf;
355 score->data[cur] = '\0';
356 }
357#endif
358 return 0;
359}
360
361int
362read_scores (filename, scores, count)
363 const char *filename;
364 struct score_entry **scores;
365 int *count;
366{
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)
378 {
379 /* We encoutered an error */
380 if (readval < 0)
381 return -1;
382 scorecount++;
383 if (scorecount >= cursize)
384 {
385 cursize *= 2;
386 ret = (struct score_entry *)
387 realloc (ret, (sizeof (struct score_entry) * cursize));
388 if (!ret)
389 return -1;
390 }
391 }
392 *count = scorecount;
393 *scores = ret;
394 return 0;
395}
396
397int
398score_compare (a, b)
399 const void *a;
400 const void *b;
401{
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);
405}
406
407int
408score_compare_reverse (a, b)
409 const void *a;
410 const void *b;
411{
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);
415}
416
417int
418push_score (scores, count, newscore, username, newdata)
419 struct score_entry **scores;
420 int *count; int newscore;
421 char *username;
422 char *newdata;
423{
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;
435}
436
437void
438sort_scores (scores, count, reverse)
439 struct score_entry *scores;
440 int count;
441 int reverse;
442{
443 qsort (scores, count, sizeof (struct score_entry),
444 reverse ? score_compare_reverse : score_compare);
445}
446
447int
448write_scores (filename, scores, count)
449 const char *filename;
450 const struct score_entry * scores;
451 int count;
452{
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;
477}
478
479int
480lock_file (filename, state)
481 const char *filename;
482 void **state;
483{
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)
502 {
503 if (errno == EEXIST)
504 {
505 /* Break the lock; we won't corrupt the file, but we might
506 lose some scores. */
507 if (attempts > MAX_ATTEMPTS)
508 {
509 unlink (lockpath);
510 attempts = 0;
511 }
512 sleep ((rand () % 2)+1);
513 goto trylock;
514 }
515 else
516 return -1;
517 }
518 close (fd);
519 return 0;
520}
521
522int
523unlock_file (filename, state)
524 const char *filename;
525 void *state;
526{
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;
533}
534
535/* arch-tag: 2bf5c52e-4beb-463a-954e-c58b9c64736b
536 (do not change this comment) */
537
538/* update-game-score.c ends here */