Spelling fixes.
[emacs.git] / lib-src / update-game-score.c
blob92c1663f6585fb0bfcb1bbcf3ff4b171492d3a7e
1 /* update-game-score.c --- Update a score file
3 Copyright (C) 2002-2013 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 #include <limits.h>
39 #include <string.h>
40 #include <stdlib.h>
41 #include <stdio.h>
42 #include <time.h>
43 #include <pwd.h>
44 #include <ctype.h>
45 #include <fcntl.h>
46 #include <sys/stat.h>
47 #include <getopt.h>
49 #ifdef WINDOWSNT
50 #include "ntlib.h"
51 #endif
53 #define MAX_ATTEMPTS 5
54 #define MAX_SCORES 200
55 #define MAX_DATA_LEN 1024
57 #ifndef HAVE_DIFFTIME
58 /* OK on POSIX (time_t is arithmetic type) modulo overflow in subtraction. */
59 #define difftime(t1, t0) (double)((t1) - (t0))
60 #endif
62 static _Noreturn void
63 usage (int err)
65 fprintf (stdout, "Usage: update-game-score [-m MAX] [-r] [-d DIR] game/scorefile SCORE DATA\n");
66 fprintf (stdout, " update-game-score -h\n");
67 fprintf (stdout, " -h\t\tDisplay this help.\n");
68 fprintf (stdout, " -m MAX\t\tLimit the maximum number of scores to MAX.\n");
69 fprintf (stdout, " -r\t\tSort the scores in increasing order.\n");
70 fprintf (stdout, " -d DIR\t\tStore scores in DIR (only if not setuid).\n");
71 exit (err);
74 static int lock_file (const char *filename, void **state);
75 static int unlock_file (const char *filename, void *state);
77 struct score_entry
79 long score;
80 char *username;
81 char *data;
84 static int read_scores (const char *filename, struct score_entry **scores,
85 int *count);
86 static int push_score (struct score_entry **scores, int *count,
87 int newscore, char *username, char *newdata);
88 static void sort_scores (struct score_entry *scores, int count, int reverse);
89 static int write_scores (const char *filename,
90 const struct score_entry *scores, int count);
92 static _Noreturn void
93 lose (const char *msg)
95 fprintf (stderr, "%s\n", msg);
96 exit (EXIT_FAILURE);
99 static _Noreturn void
100 lose_syserr (const char *msg)
102 fprintf (stderr, "%s: %s\n", msg, strerror (errno));
103 exit (EXIT_FAILURE);
106 static char *
107 get_user_id (void)
109 struct passwd *buf = getpwuid (getuid ());
110 if (!buf)
112 long uid = getuid ();
113 char *name = malloc (sizeof uid * CHAR_BIT / 3 + 1);
114 if (name)
115 sprintf (name, "%ld", uid);
116 return name;
118 return buf->pw_name;
121 static const char *
122 get_prefix (int running_suid, const char *user_prefix)
124 if (!running_suid && user_prefix == NULL)
125 lose ("Not using a shared game directory, and no prefix given.");
126 if (running_suid)
128 #ifdef HAVE_SHARED_GAME_DIR
129 return HAVE_SHARED_GAME_DIR;
130 #else
131 lose ("This program was compiled without HAVE_SHARED_GAME_DIR,\n and should not be suid.");
132 #endif
134 return user_prefix;
138 main (int argc, char **argv)
140 int c, running_suid;
141 void *lockstate;
142 char *user_id, *scorefile;
143 const char *prefix, *user_prefix = NULL;
144 struct stat buf;
145 struct score_entry *scores;
146 int newscore, scorecount, reverse = 0, max = MAX_SCORES;
147 char *newdata;
149 srand (time (0));
151 while ((c = getopt (argc, argv, "hrm:d:")) != -1)
152 switch (c)
154 case 'h':
155 usage (EXIT_SUCCESS);
156 break;
157 case 'd':
158 user_prefix = optarg;
159 break;
160 case 'r':
161 reverse = 1;
162 break;
163 case 'm':
164 max = atoi (optarg);
165 if (max > MAX_SCORES)
166 max = MAX_SCORES;
167 break;
168 default:
169 usage (EXIT_FAILURE);
172 if (optind+3 != argc)
173 usage (EXIT_FAILURE);
175 running_suid = (getuid () != geteuid ());
177 prefix = get_prefix (running_suid, user_prefix);
179 scorefile = malloc (strlen (prefix) + strlen (argv[optind]) + 2);
180 if (!scorefile)
181 lose_syserr ("Couldn't allocate score file");
183 strcpy (scorefile, prefix);
184 strcat (scorefile, "/");
185 strcat (scorefile, argv[optind]);
186 newscore = atoi (argv[optind+1]);
187 newdata = argv[optind+2];
188 if (strlen (newdata) > MAX_DATA_LEN)
189 newdata[MAX_DATA_LEN] = '\0';
191 user_id = get_user_id ();
192 if (user_id == NULL)
193 lose_syserr ("Couldn't determine user id");
195 if (stat (scorefile, &buf) < 0)
196 lose_syserr ("Failed to access scores file");
198 if (lock_file (scorefile, &lockstate) < 0)
199 lose_syserr ("Failed to lock scores file");
201 if (read_scores (scorefile, &scores, &scorecount) < 0)
203 unlock_file (scorefile, lockstate);
204 lose_syserr ("Failed to read scores file");
206 push_score (&scores, &scorecount, newscore, user_id, newdata);
207 sort_scores (scores, scorecount, reverse);
208 /* Limit the number of scores. If we're using reverse sorting, then
209 also increment the beginning of the array, to skip over the
210 *smallest* scores. Otherwise, just decrementing the number of
211 scores suffices, since the smallest is at the end. */
212 if (scorecount > MAX_SCORES)
214 if (reverse)
215 scores += (scorecount - MAX_SCORES);
216 scorecount = MAX_SCORES;
218 if (write_scores (scorefile, scores, scorecount) < 0)
220 unlock_file (scorefile, lockstate);
221 lose_syserr ("Failed to write scores file");
223 unlock_file (scorefile, lockstate);
224 exit (EXIT_SUCCESS);
227 static int
228 read_score (FILE *f, struct score_entry *score)
230 int c;
231 if ((c = getc (f)) != EOF)
232 ungetc (c, f);
233 if (feof (f))
234 return 1;
235 for (score->score = 0; (c = getc (f)) != EOF && isdigit (c); )
237 score->score *= 10;
238 score->score += (c-48);
240 while ((c = getc (f)) != EOF
241 && isspace (c))
243 if (c == EOF)
244 return -1;
245 ungetc (c, f);
246 #ifdef HAVE_GETDELIM
248 size_t count = 0;
249 if (getdelim (&score->username, &count, ' ', f) < 1
250 || score->username == NULL)
251 return -1;
252 /* Trim the space */
253 score->username[strlen (score->username)-1] = '\0';
255 #else
257 int unameread = 0;
258 int unamelen = 30;
259 char *username = malloc (unamelen);
260 if (!username)
261 return -1;
263 while ((c = getc (f)) != EOF
264 && !isspace (c))
266 if (unameread >= unamelen-1)
267 if (!(username = realloc (username, unamelen *= 2)))
268 return -1;
269 username[unameread] = c;
270 unameread++;
272 if (c == EOF)
273 return -1;
274 username[unameread] = '\0';
275 score->username = username;
277 #endif
278 #ifdef HAVE_GETLINE
279 score->data = NULL;
280 errno = 0;
282 size_t len;
283 if (getline (&score->data, &len, f) < 0)
284 return -1;
285 score->data[strlen (score->data)-1] = '\0';
287 #else
289 int cur = 0;
290 int len = 16;
291 char *buf = malloc (len);
292 if (!buf)
293 return -1;
294 while ((c = getc (f)) != EOF
295 && c != '\n')
297 if (cur >= len-1)
299 if (!(buf = realloc (buf, len *= 2)))
300 return -1;
302 buf[cur] = c;
303 cur++;
305 score->data = buf;
306 score->data[cur] = '\0';
308 #endif
309 return 0;
312 static int
313 read_scores (const char *filename, struct score_entry **scores, int *count)
315 int readval = -1, scorecount, cursize;
316 struct score_entry *ret;
317 FILE *f = fopen (filename, "r");
318 int retval = -1;
319 if (!f)
320 return -1;
321 scorecount = 0;
322 cursize = 16;
323 ret = (struct score_entry *) malloc (sizeof (struct score_entry) * cursize);
324 if (ret)
326 while ((readval = read_score (f, &ret[scorecount])) == 0)
328 scorecount++;
329 if (scorecount >= cursize)
331 cursize *= 2;
332 ret = (struct score_entry *)
333 realloc (ret, (sizeof (struct score_entry) * cursize));
334 if (!ret)
335 break;
339 if (readval > 0)
341 *count = scorecount;
342 *scores = ret;
343 retval = 0;
345 fclose (f);
346 return retval;
349 static int
350 score_compare (const void *a, const void *b)
352 const struct score_entry *sa = (const struct score_entry *) a;
353 const struct score_entry *sb = (const struct score_entry *) b;
354 return (sb->score > sa->score) - (sb->score < sa->score);
357 static int
358 score_compare_reverse (const void *a, const void *b)
360 const struct score_entry *sa = (const struct score_entry *) a;
361 const struct score_entry *sb = (const struct score_entry *) b;
362 return (sa->score > sb->score) - (sa->score < sb->score);
366 push_score (struct score_entry **scores, int *count, int newscore, char *username, char *newdata)
368 struct score_entry *newscores
369 = (struct score_entry *) realloc (*scores,
370 sizeof (struct score_entry) * ((*count) + 1));
371 if (!newscores)
372 return -1;
373 newscores[*count].score = newscore;
374 newscores[*count].username = username;
375 newscores[*count].data = newdata;
376 (*count) += 1;
377 *scores = newscores;
378 return 0;
381 static void
382 sort_scores (struct score_entry *scores, int count, int reverse)
384 qsort (scores, count, sizeof (struct score_entry),
385 reverse ? score_compare_reverse : score_compare);
388 static int
389 write_scores (const char *filename, const struct score_entry *scores, int count)
391 int fd;
392 FILE *f;
393 int i;
394 char *tempfile = malloc (strlen (filename) + strlen (".tempXXXXXX") + 1);
395 if (!tempfile)
396 return -1;
397 strcpy (tempfile, filename);
398 strcat (tempfile, ".tempXXXXXX");
399 fd = mkostemp (tempfile, 0);
400 if (fd < 0)
401 return -1;
402 f = fdopen (fd, "w");
403 if (! f)
404 return -1;
405 for (i = 0; i < count; i++)
406 if (fprintf (f, "%ld %s %s\n", scores[i].score, scores[i].username,
407 scores[i].data) < 0)
408 return -1;
409 fclose (f);
410 if (rename (tempfile, filename) < 0)
411 return -1;
412 if (chmod (filename, 0644) < 0)
413 return -1;
414 return 0;
417 static int
418 lock_file (const char *filename, void **state)
420 int fd;
421 struct stat buf;
422 int attempts = 0;
423 const char *lockext = ".lockfile";
424 char *lockpath = malloc (strlen (filename) + strlen (lockext) + 60);
425 if (!lockpath)
426 return -1;
427 strcpy (lockpath, filename);
428 strcat (lockpath, lockext);
429 *state = lockpath;
430 trylock:
431 attempts++;
432 /* If the lock is over an hour old, delete it. */
433 if (stat (lockpath, &buf) == 0
434 && (difftime (buf.st_ctime, time (NULL) > 60*60)))
435 unlink (lockpath);
436 fd = open (lockpath, O_CREAT | O_EXCL, 0600);
437 if (fd < 0)
439 if (errno == EEXIST)
441 /* Break the lock; we won't corrupt the file, but we might
442 lose some scores. */
443 if (attempts > MAX_ATTEMPTS)
445 unlink (lockpath);
446 attempts = 0;
448 sleep ((rand () % 2)+1);
449 goto trylock;
451 else
452 return -1;
454 close (fd);
455 return 0;
458 static int
459 unlock_file (const char *filename, void *state)
461 char *lockpath = (char *) state;
462 int ret = unlink (lockpath);
463 int saved_errno = errno;
464 free (lockpath);
465 errno = saved_errno;
466 return ret;
469 /* update-game-score.c ends here */