*** empty log message ***
[emacs.git] / lib-src / update-game-score.c
blob2a699b2550d20ba832e9c23722bc89671b9177c5
1 /* update-game-score.c --- Update a score file
2 Copyright (C) 2002 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 int
72 usage (err)
73 int err;
75 fprintf (stdout, "Usage: update-game-score [-m MAX ] [ -r ] game/scorefile SCORE DATA\n");
76 fprintf (stdout, " update-game-score -h\n");
77 fprintf (stdout, " -h\t\tDisplay this help.\n");
78 fprintf (stdout, " -m MAX\t\tLimit the maximum number of scores to MAX.\n");
79 fprintf (stdout, " -r\t\tSort the scores in increasing order.\n");
80 fprintf (stdout, " -d DIR\t\tStore scores in DIR (only if not setuid).\n");
81 exit (err);
84 int lock_file P_ ((const char *filename, void **state));
85 int unlock_file P_ ((const char *filename, void *state));
87 struct score_entry
89 long score;
90 char *username;
91 char *data;
94 int read_scores P_ ((const char *filename, struct score_entry **scores,
95 int *count));
96 int push_score P_ ((struct score_entry **scores, int *count,
97 int newscore, char *username, char *newdata));
98 void sort_scores P_ ((struct score_entry *scores, int count, int reverse));
99 int write_scores P_ ((const char *filename, const struct score_entry *scores,
100 int count));
102 void lose P_ ((const char *msg)) NO_RETURN;
104 void
105 lose (msg)
106 const char *msg;
108 fprintf (stderr, "%s\n", msg);
109 exit (1);
112 void lose_syserr P_ ((const char *msg)) NO_RETURN;
114 void
115 lose_syserr (msg)
116 const char *msg;
118 fprintf (stderr, "%s: %s\n", msg, strerror (errno));
119 exit (1);
122 char *
123 get_user_id P_ ((void))
125 char *name;
126 struct passwd *buf = getpwuid (getuid ());
127 if (!buf)
129 int count = 1;
130 int uid = (int) getuid ();
131 int tuid = uid;
132 while (tuid /= 10)
133 count++;
134 name = malloc (count+1);
135 if (!name)
136 return NULL;
137 sprintf (name, "%d", uid);
138 return name;
140 return buf->pw_name;
143 char *
144 get_prefix (running_suid, user_prefix)
145 int running_suid;
146 char *user_prefix;
148 if (!running_suid && user_prefix == NULL)
149 lose ("Not using a shared game directory, and no prefix given.");
150 if (running_suid)
152 #ifdef HAVE_SHARED_GAME_DIR
153 return HAVE_SHARED_GAME_DIR;
154 #else
155 lose ("This program was compiled without HAVE_SHARED_GAME_DIR,\n and should not be suid.");
156 #endif
158 return user_prefix;
162 main (argc, argv)
163 int argc;
164 char **argv;
166 int c, running_suid;
167 void *lockstate;
168 char *user_id, *scorefile, *prefix, *user_prefix = NULL;
169 struct stat buf;
170 struct score_entry *scores;
171 int newscore, scorecount, reverse = 0, max = MAX_SCORES;
172 char *newdata;
174 srand (time (0));
176 while ((c = getopt (argc, argv, "hrm:d:")) != -1)
177 switch (c)
179 case 'h':
180 usage (0);
181 break;
182 case 'd':
183 user_prefix = optarg;
184 break;
185 case 'r':
186 reverse = 1;
187 break;
188 case 'm':
189 max = atoi (optarg);
190 if (max > MAX_SCORES)
191 max = MAX_SCORES;
192 break;
193 default:
194 usage (1);
197 if (optind+3 != argc)
198 usage (1);
200 running_suid = (getuid () != geteuid ());
202 prefix = get_prefix (running_suid, user_prefix);
204 scorefile = malloc (strlen (prefix) + strlen (argv[optind]) + 2);
205 if (!scorefile)
206 lose_syserr ("Couldn't allocate score file");
208 strcpy (scorefile, prefix);
209 strcat (scorefile, "/");
210 strcat (scorefile, argv[optind]);
211 newscore = atoi (argv[optind+1]);
212 newdata = argv[optind+2];
213 if (strlen (newdata) > MAX_DATA_LEN)
214 newdata[MAX_DATA_LEN] = '\0';
216 user_id = get_user_id ();
217 if (user_id == NULL)
218 lose_syserr ("Couldn't determine user id");
220 if (stat (scorefile, &buf) < 0)
221 lose_syserr ("Failed to access scores file");
223 if (lock_file (scorefile, &lockstate) < 0)
224 lose_syserr ("Failed to lock scores file");
226 if (read_scores (scorefile, &scores, &scorecount) < 0)
228 unlock_file (scorefile, lockstate);
229 lose_syserr ("Failed to read scores file");
231 push_score (&scores, &scorecount, newscore, user_id, newdata);
232 /* Limit the number of scores. If we're using reverse sorting, then
233 we should increment the beginning of the array, to skip over the
234 *smallest* scores. Otherwise, we just decrement the number of
235 scores, since the smallest will be at the end. */
236 if (scorecount > MAX_SCORES)
237 scorecount -= (scorecount - MAX_SCORES);
238 if (reverse)
239 scores += (scorecount - MAX_SCORES);
240 sort_scores (scores, scorecount, reverse);
241 if (write_scores (scorefile, scores, scorecount) < 0)
243 unlock_file (scorefile, lockstate);
244 lose_syserr ("Failed to write scores file");
246 unlock_file (scorefile, lockstate);
247 exit (0);
251 read_score (f, score)
252 FILE *f;
253 struct score_entry *score;
255 int c;
256 if (feof (f))
257 return 1;
258 while ((c = getc (f)) != EOF
259 && isdigit (c))
261 score->score *= 10;
262 score->score += (c-48);
264 while ((c = getc (f)) != EOF
265 && isspace (c))
267 if (c == EOF)
268 return -1;
269 ungetc (c, f);
270 #ifdef HAVE_GETDELIM
272 size_t count = 0;
273 if (getdelim (&score->username, &count, ' ', f) < 1
274 || score->username == NULL)
275 return -1;
276 /* Trim the space */
277 score->username[strlen (score->username)-1] = '\0';
279 #else
281 int unameread = 0;
282 int unamelen = 30;
283 char *username = malloc (unamelen);
284 if (!username)
285 return -1;
287 while ((c = getc (f)) != EOF
288 && !isspace (c))
290 if (unameread >= unamelen-1)
291 if (!(username = realloc (username, unamelen *= 2)))
292 return -1;
293 username[unameread] = c;
294 unameread++;
296 if (c == EOF)
297 return -1;
298 username[unameread] = '\0';
299 score->username = username;
301 #endif
302 #ifdef HAVE_GETLINE
303 score->data = NULL;
304 errno = 0;
306 size_t len;
307 if (getline (&score->data, &len, f) < 0)
308 return -1;
309 score->data[strlen (score->data)-1] = '\0';
311 #else
313 int cur = 0;
314 int len = 16;
315 char *buf = malloc (len);
316 if (!buf)
317 return -1;
318 while ((c = getc (f)) != EOF
319 && c != '\n')
321 if (cur >= len-1)
323 if (!(buf = realloc (buf, len *= 2)))
324 return -1;
326 buf[cur] = c;
327 cur++;
329 score->data = buf;
330 score->data[cur] = '\0';
332 #endif
333 return 0;
337 read_scores (filename, scores, count)
338 const char *filename;
339 struct score_entry **scores;
340 int *count;
342 int readval, scorecount, cursize;
343 struct score_entry *ret;
344 FILE *f = fopen (filename, "r");
345 if (!f)
346 return -1;
347 scorecount = 0;
348 cursize = 16;
349 ret = (struct score_entry *) malloc (sizeof (struct score_entry) * cursize);
350 if (!ret)
351 return -1;
352 while ((readval = read_score (f, &ret[scorecount])) == 0)
354 /* We encoutered an error */
355 if (readval < 0)
356 return -1;
357 scorecount++;
358 if (scorecount >= cursize)
360 cursize *= 2;
361 ret = (struct score_entry *)
362 realloc (ret, (sizeof (struct score_entry) * cursize));
363 if (!ret)
364 return -1;
367 *count = scorecount;
368 *scores = ret;
369 return 0;
373 score_compare (a, b)
374 const void *a;
375 const void *b;
377 const struct score_entry *sa = (const struct score_entry *) a;
378 const struct score_entry *sb = (const struct score_entry *) b;
379 return (sb->score > sa->score) - (sb->score < sa->score);
383 score_compare_reverse (a, b)
384 const void *a;
385 const void *b;
387 const struct score_entry *sa = (const struct score_entry *) a;
388 const struct score_entry *sb = (const struct score_entry *) b;
389 return (sa->score > sb->score) - (sa->score < sb->score);
393 push_score (scores, count, newscore, username, newdata)
394 struct score_entry **scores;
395 int *count; int newscore;
396 char *username;
397 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 void
413 sort_scores (scores, count, reverse)
414 struct score_entry *scores;
415 int count;
416 int reverse;
418 qsort (scores, count, sizeof (struct score_entry),
419 reverse ? score_compare_reverse : score_compare);
423 write_scores (filename, scores, count)
424 const char *filename;
425 const struct score_entry * scores;
426 int count;
428 FILE *f;
429 int i;
430 char *tempfile = malloc (strlen (filename) + strlen (".tempXXXXXX") + 1);
431 if (!tempfile)
432 return -1;
433 strcpy (tempfile, filename);
434 strcat (tempfile, ".tempXXXXXX");
435 #ifdef HAVE_MKSTEMP
436 if (mkstemp (tempfile) < 0
437 #else
438 if (mktemp (tempfile) != tempfile
439 #endif
440 || !(f = fopen (tempfile, "w")))
441 return -1;
442 for (i = 0; i < count; i++)
443 if (fprintf (f, "%ld %s %s\n", scores[i].score, scores[i].username,
444 scores[i].data) < 0)
445 return -1;
446 fclose (f);
447 if (rename (tempfile, filename) < 0)
448 return -1;
449 if (chmod (filename, 0644) < 0)
450 return -1;
451 return 0;
455 lock_file (filename, state)
456 const char *filename;
457 void **state;
459 int fd;
460 struct stat buf;
461 int attempts = 0;
462 char *lockext = ".lockfile";
463 char *lockpath = malloc (strlen (filename) + strlen (lockext) + 60);
464 if (!lockpath)
465 return -1;
466 strcpy (lockpath, filename);
467 strcat (lockpath, lockext);
468 *state = lockpath;
469 trylock:
470 attempts++;
471 /* If the lock is over an hour old, delete it. */
472 if (stat (lockpath, &buf) == 0
473 && (difftime (buf.st_ctime, time (NULL) > 60*60)))
474 unlink (lockpath);
475 fd = open (lockpath, O_CREAT | O_EXCL, 0600);
476 if (fd < 0)
478 if (errno == EEXIST)
480 /* Break the lock; we won't corrupt the file, but we might
481 lose some scores. */
482 if (attempts > MAX_ATTEMPTS)
484 unlink (lockpath);
485 attempts = 0;
487 sleep ((rand () % 2)+1);
488 goto trylock;
490 else
491 return -1;
493 close (fd);
494 return 0;
498 unlock_file (filename, state)
499 const char *filename;
500 void *state;
502 char *lockpath = (char *) state;
503 int ret = unlink (lockpath);
504 int saved_errno = errno;
505 free (lockpath);
506 errno = saved_errno;
507 return ret;