Provide custom-prompt-customize-unsaved-options.
[emacs.git] / lib-src / update-game-score.c
blob7a64cd04f479da1f23ab807cb298266b69b2037d
1 /* update-game-score.c --- Update a score file
3 Copyright (C) 2002-2014 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 <inttypes.h>
39 #include <limits.h>
40 #include <stdbool.h>
41 #include <string.h>
42 #include <stdlib.h>
43 #include <stdio.h>
44 #include <time.h>
45 #include <pwd.h>
46 #include <ctype.h>
47 #include <fcntl.h>
48 #include <sys/stat.h>
49 #include <getopt.h>
51 #ifdef WINDOWSNT
52 #include "ntlib.h"
53 #endif
55 #ifndef min
56 # define min(a,b) ((a) < (b) ? (a) : (b))
57 #endif
59 #define MAX_ATTEMPTS 5
60 #define MAX_DATA_LEN 1024
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 char *score;
80 char *user_data;
83 #define MAX_SCORES min (PTRDIFF_MAX, SIZE_MAX / sizeof (struct score_entry))
85 static int read_scores (const char *filename, struct score_entry **scores,
86 ptrdiff_t *count, ptrdiff_t *alloc);
87 static int push_score (struct score_entry **scores, ptrdiff_t *count,
88 ptrdiff_t *size, struct score_entry const *newscore);
89 static void sort_scores (struct score_entry *scores, ptrdiff_t count,
90 bool reverse);
91 static int write_scores (const char *filename,
92 const struct score_entry *scores, ptrdiff_t count);
94 static _Noreturn void
95 lose (const char *msg)
97 fprintf (stderr, "%s\n", msg);
98 exit (EXIT_FAILURE);
101 static _Noreturn void
102 lose_syserr (const char *msg)
104 fprintf (stderr, "%s: %s\n", msg,
105 errno ? strerror (errno) : "Invalid data in score file");
106 exit (EXIT_FAILURE);
109 static char *
110 get_user_id (void)
112 struct passwd *buf = getpwuid (getuid ());
113 if (!buf || strchr (buf->pw_name, ' ') || strchr (buf->pw_name, '\n'))
115 intmax_t uid = getuid ();
116 char *name = malloc (sizeof uid * CHAR_BIT / 3 + 4);
117 if (name)
118 sprintf (name, "%"PRIdMAX, uid);
119 return name;
121 return buf->pw_name;
124 static const char *
125 get_prefix (bool running_suid, const char *user_prefix)
127 if (!running_suid && user_prefix == NULL)
128 lose ("Not using a shared game directory, and no prefix given.");
129 if (running_suid)
131 #ifdef HAVE_SHARED_GAME_DIR
132 return HAVE_SHARED_GAME_DIR;
133 #else
134 lose ("This program was compiled without HAVE_SHARED_GAME_DIR,\n and should not be suid.");
135 #endif
137 return user_prefix;
140 static char *
141 normalize_integer (char *num)
143 bool neg;
144 char *p;
145 while (*num != '\n' && isspace (*num))
146 num++;
147 neg = *num == '-';
148 num += neg || *num == '-';
150 if (*num == '0')
152 while (*++num == '0')
153 continue;
154 neg &= !!*num;
155 num -= !*num;
158 for (p = num; '0' <= *p && *p <= '9'; p++)
159 continue;
161 if (*p || p == num)
163 errno = 0;
164 return 0;
167 if (neg)
168 *--num = '-';
169 return num;
173 main (int argc, char **argv)
175 int c;
176 bool running_suid;
177 void *lockstate;
178 char *scorefile;
179 char *end, *nl, *user, *data;
180 const char *prefix, *user_prefix = NULL;
181 struct score_entry *scores;
182 struct score_entry newscore;
183 bool reverse = false;
184 ptrdiff_t scorecount, scorealloc;
185 ptrdiff_t max_scores = MAX_SCORES;
187 srand (time (0));
189 while ((c = getopt (argc, argv, "hrm:d:")) != -1)
190 switch (c)
192 case 'h':
193 usage (EXIT_SUCCESS);
194 break;
195 case 'd':
196 user_prefix = optarg;
197 break;
198 case 'r':
199 reverse = 1;
200 break;
201 case 'm':
203 intmax_t m = strtoimax (optarg, &end, 10);
204 if (optarg == end || *end || m < 0)
205 usage (EXIT_FAILURE);
206 max_scores = min (m, MAX_SCORES);
208 break;
209 default:
210 usage (EXIT_FAILURE);
213 if (argc - optind != 3)
214 usage (EXIT_FAILURE);
216 running_suid = (getuid () != geteuid ());
218 prefix = get_prefix (running_suid, user_prefix);
220 scorefile = malloc (strlen (prefix) + strlen (argv[optind]) + 2);
221 if (!scorefile)
222 lose_syserr ("Couldn't allocate score file");
224 strcpy (scorefile, prefix);
225 strcat (scorefile, "/");
226 strcat (scorefile, argv[optind]);
228 newscore.score = normalize_integer (argv[optind + 1]);
229 if (! newscore.score)
231 fprintf (stderr, "%s: Invalid score\n", argv[optind + 1]);
232 return EXIT_FAILURE;
235 user = get_user_id ();
236 if (! user)
237 lose_syserr ("Couldn't determine user id");
238 data = argv[optind + 2];
239 if (strlen (data) > MAX_DATA_LEN)
240 data[MAX_DATA_LEN] = '\0';
241 nl = strchr (data, '\n');
242 if (nl)
243 *nl = '\0';
244 newscore.user_data = malloc (strlen (user) + 1 + strlen (data) + 1);
245 if (! newscore.user_data
246 || sprintf (newscore.user_data, "%s %s", user, data) < 0)
247 lose_syserr ("Memory exhausted");
249 if (lock_file (scorefile, &lockstate) < 0)
250 lose_syserr ("Failed to lock scores file");
252 if (read_scores (scorefile, &scores, &scorecount, &scorealloc) < 0)
254 unlock_file (scorefile, lockstate);
255 lose_syserr ("Failed to read scores file");
257 if (push_score (&scores, &scorecount, &scorealloc, &newscore) < 0)
259 unlock_file (scorefile, lockstate);
260 lose_syserr ("Failed to add score");
262 sort_scores (scores, scorecount, reverse);
263 /* Limit the number of scores. If we're using reverse sorting, then
264 also increment the beginning of the array, to skip over the
265 *smallest* scores. Otherwise, just decrementing the number of
266 scores suffices, since the smallest is at the end. */
267 if (scorecount > max_scores)
269 if (reverse)
270 scores += scorecount - max_scores;
271 scorecount = max_scores;
273 if (write_scores (scorefile, scores, scorecount) < 0)
275 unlock_file (scorefile, lockstate);
276 lose_syserr ("Failed to write scores file");
278 if (unlock_file (scorefile, lockstate) < 0)
279 lose_syserr ("Failed to unlock scores file");
280 exit (EXIT_SUCCESS);
283 static char *
284 read_score (char *p, struct score_entry *score)
286 score->score = p;
287 p = strchr (p, ' ');
288 if (!p)
289 return p;
290 *p++ = 0;
291 score->user_data = p;
292 p = strchr (p, '\n');
293 if (!p)
294 return p;
295 *p++ = 0;
296 return p;
299 static int
300 read_scores (const char *filename, struct score_entry **scores,
301 ptrdiff_t *count, ptrdiff_t *alloc)
303 char *p, *filedata;
304 ptrdiff_t filesize, nread;
305 struct stat st;
306 FILE *f = fopen (filename, "r");
307 if (!f)
308 return -1;
309 if (fstat (fileno (f), &st) != 0)
310 return -1;
311 if (! (0 <= st.st_size && st.st_size < min (PTRDIFF_MAX, SIZE_MAX)))
313 errno = EOVERFLOW;
314 return -1;
316 filesize = st.st_size;
317 filedata = malloc (filesize + 1);
318 if (! filedata)
319 return -1;
320 nread = fread (filedata, 1, filesize + 1, f);
321 if (filesize < nread)
323 errno = 0;
324 return -1;
326 if (nread < filesize)
327 filesize = nread;
328 if (ferror (f) || fclose (f) != 0)
329 return -1;
330 filedata[filesize] = 0;
331 if (strlen (filedata) != filesize)
333 errno = 0;
334 return -1;
337 *scores = 0;
338 *count = *alloc = 0;
339 for (p = filedata; p < filedata + filesize; )
341 struct score_entry entry;
342 p = read_score (p, &entry);
343 if (!p)
345 errno = 0;
346 return -1;
348 if (push_score (scores, count, alloc, &entry) < 0)
349 return -1;
351 return 0;
354 static int
355 score_compare (const void *a, const void *b)
357 const struct score_entry *sa = (const struct score_entry *) a;
358 const struct score_entry *sb = (const struct score_entry *) b;
359 char *sca = sa->score;
360 char *scb = sb->score;
361 size_t lena, lenb;
362 bool nega = *sca == '-';
363 bool negb = *scb == '-';
364 int diff = nega - negb;
365 if (diff)
366 return diff;
367 if (nega)
369 char *tmp = sca;
370 sca = scb + 1;
371 scb = tmp + 1;
373 lena = strlen (sca);
374 lenb = strlen (scb);
375 if (lena != lenb)
376 return lenb < lena ? -1 : 1;
377 return strcmp (scb, sca);
380 static int
381 score_compare_reverse (const void *a, const void *b)
383 return score_compare (b, a);
387 push_score (struct score_entry **scores, ptrdiff_t *count, ptrdiff_t *size,
388 struct score_entry const *newscore)
390 struct score_entry *newscores = *scores;
391 if (*count == *size)
393 ptrdiff_t newsize = *size;
394 if (newsize <= 0)
395 newsize = 1;
396 else if (newsize <= MAX_SCORES / 2)
397 newsize *= 2;
398 else if (newsize < MAX_SCORES)
399 newsize = MAX_SCORES;
400 else
402 errno = ENOMEM;
403 return -1;
405 newscores = realloc (newscores, sizeof *newscores * newsize);
406 if (!newscores)
407 return -1;
408 *scores = newscores;
409 *size = newsize;
411 newscores[*count] = *newscore;
412 (*count) += 1;
413 return 0;
416 static void
417 sort_scores (struct score_entry *scores, ptrdiff_t count, bool reverse)
419 qsort (scores, count, sizeof *scores,
420 reverse ? score_compare_reverse : score_compare);
423 static int
424 write_scores (const char *filename, const struct score_entry *scores,
425 ptrdiff_t count)
427 int fd;
428 FILE *f;
429 ptrdiff_t 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 fd = mkostemp (tempfile, 0);
436 if (fd < 0)
437 return -1;
438 #ifndef DOS_NT
439 if (fchmod (fd, 0644) != 0)
440 return -1;
441 #endif
442 f = fdopen (fd, "w");
443 if (! f)
444 return -1;
445 for (i = 0; i < count; i++)
446 if (fprintf (f, "%s %s\n", scores[i].score, scores[i].user_data) < 0)
447 return -1;
448 if (fclose (f) != 0)
449 return -1;
450 if (rename (tempfile, filename) != 0)
451 return -1;
452 return 0;
455 static int
456 lock_file (const char *filename, void **state)
458 int fd;
459 struct stat buf;
460 int attempts = 0;
461 const char *lockext = ".lockfile";
462 char *lockpath = malloc (strlen (filename) + strlen (lockext) + 60);
463 if (!lockpath)
464 return -1;
465 strcpy (lockpath, filename);
466 strcat (lockpath, lockext);
467 *state = lockpath;
469 while ((fd = open (lockpath, O_CREAT | O_EXCL, 0600)) < 0)
471 if (errno != EEXIST)
472 return -1;
473 attempts++;
475 /* Break the lock if it is over an hour old, or if we've tried
476 more than MAX_ATTEMPTS times. We won't corrupt the file, but
477 we might lose some scores. */
478 if (MAX_ATTEMPTS < attempts
479 || (stat (lockpath, &buf) == 0 && 60 * 60 < time (0) - buf.st_ctime))
481 if (unlink (lockpath) != 0 && errno != ENOENT)
482 return -1;
483 attempts = 0;
486 sleep ((rand () & 1) + 1);
489 close (fd);
490 return 0;
493 static int
494 unlock_file (const char *filename, void *state)
496 char *lockpath = (char *) state;
497 int saved_errno = errno;
498 int ret = unlink (lockpath);
499 int unlink_errno = errno;
500 free (lockpath);
501 errno = ret < 0 ? unlink_errno : saved_errno;
502 return ret;
505 /* update-game-score.c ends here */