Merge branch 'master' into comment-cache
[emacs.git] / lib-src / update-game-score.c
blob5edc8e79569111d6de3c8974c3552c4b8ebe6719
1 /* update-game-score.c --- Update a score file
3 Copyright (C) 2002-2017 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 (at
12 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 either setuid or setgid, owned
25 by an appropriate user or group 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 <string.h>
41 #include <stdlib.h>
42 #include <stdio.h>
43 #include <time.h>
44 #include <pwd.h>
45 #include <ctype.h>
46 #include <fcntl.h>
47 #include <sys/stat.h>
48 #include <getopt.h>
50 #ifdef WINDOWSNT
51 #include "ntlib.h"
52 #endif
54 #ifndef min
55 # define min(a,b) ((a) < (b) ? (a) : (b))
56 #endif
58 #define MAX_ATTEMPTS 5
59 #define MAX_DATA_LEN 1024
61 static _Noreturn void
62 usage (int err)
64 fprintf (stdout, "Usage: update-game-score [-m MAX] [-r] [-d DIR] game/scorefile SCORE DATA\n");
65 fprintf (stdout, " update-game-score -h\n");
66 fprintf (stdout, " -h\t\tDisplay this help.\n");
67 fprintf (stdout, " -m MAX\t\tLimit the maximum number of scores to MAX.\n");
68 fprintf (stdout, " -r\t\tSort the scores in increasing order.\n");
69 fprintf (stdout, " -d DIR\t\tStore scores in DIR (only if not setuid).\n");
70 exit (err);
73 static int lock_file (const char *filename, void **state);
74 static int unlock_file (const char *filename, void *state);
76 struct score_entry
78 char *score;
79 char *user_data;
82 #define MAX_SCORES min (PTRDIFF_MAX, SIZE_MAX / sizeof (struct score_entry))
84 static int read_scores (const char *filename, struct score_entry **scores,
85 ptrdiff_t *count, ptrdiff_t *alloc);
86 static int push_score (struct score_entry **scores, ptrdiff_t *count,
87 ptrdiff_t *size, struct score_entry const *newscore);
88 static void sort_scores (struct score_entry *scores, ptrdiff_t count,
89 bool reverse);
90 static int write_scores (const char *filename, mode_t mode,
91 const struct score_entry *scores, ptrdiff_t count);
93 static _Noreturn void
94 lose (const char *msg)
96 fprintf (stderr, "%s\n", msg);
97 exit (EXIT_FAILURE);
100 static _Noreturn void
101 lose_syserr (const char *msg)
103 fprintf (stderr, "%s: %s\n", msg,
104 errno ? strerror (errno) : "Invalid data in score file");
105 exit (EXIT_FAILURE);
108 static char *
109 get_user_id (void)
111 struct passwd *buf = getpwuid (getuid ());
112 if (!buf || strchr (buf->pw_name, ' ') || strchr (buf->pw_name, '\n'))
114 intmax_t uid = getuid ();
115 char *name = malloc (sizeof uid * CHAR_BIT / 3 + 4);
116 if (name)
117 sprintf (name, "%"PRIdMAX, uid);
118 return name;
120 return buf->pw_name;
123 static const char *
124 get_prefix (bool privileged, const char *user_prefix)
126 if (privileged)
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"
132 "and should not run with elevated privileges.");
133 #endif
135 if (user_prefix == NULL)
136 lose ("Not using a shared game directory, and no prefix given.");
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, running_sgid;
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 ());
217 running_sgid = (getgid () != getegid ());
218 if (running_suid && running_sgid)
219 lose ("This program can run either suid or sgid, but not both.");
221 prefix = get_prefix (running_suid || running_sgid, user_prefix);
223 scorefile = malloc (strlen (prefix) + strlen (argv[optind]) + 2);
224 if (!scorefile)
225 lose_syserr ("Couldn't allocate score file");
227 char *z = stpcpy (scorefile, prefix);
228 *z++ = '/';
229 strcpy (z, argv[optind]);
231 newscore.score = normalize_integer (argv[optind + 1]);
232 if (! newscore.score)
234 fprintf (stderr, "%s: Invalid score\n", argv[optind + 1]);
235 return EXIT_FAILURE;
238 user = get_user_id ();
239 if (! user)
240 lose_syserr ("Couldn't determine user id");
241 data = argv[optind + 2];
242 if (strlen (data) > MAX_DATA_LEN)
243 data[MAX_DATA_LEN] = '\0';
244 nl = strchr (data, '\n');
245 if (nl)
246 *nl = '\0';
247 newscore.user_data = malloc (strlen (user) + 1 + strlen (data) + 1);
248 if (! newscore.user_data
249 || sprintf (newscore.user_data, "%s %s", user, data) < 0)
250 lose_syserr ("Memory exhausted");
252 if (lock_file (scorefile, &lockstate) < 0)
253 lose_syserr ("Failed to lock scores file");
255 if (read_scores (scorefile, &scores, &scorecount, &scorealloc) < 0)
257 unlock_file (scorefile, lockstate);
258 lose_syserr ("Failed to read scores file");
260 if (push_score (&scores, &scorecount, &scorealloc, &newscore) < 0)
262 unlock_file (scorefile, lockstate);
263 lose_syserr ("Failed to add score");
265 sort_scores (scores, scorecount, reverse);
266 /* Limit the number of scores. If we're using reverse sorting, then
267 also increment the beginning of the array, to skip over the
268 *smallest* scores. Otherwise, just decrementing the number of
269 scores suffices, since the smallest is at the end. */
270 if (scorecount > max_scores)
272 if (reverse)
273 scores += scorecount - max_scores;
274 scorecount = max_scores;
276 if (write_scores (scorefile, running_sgid ? 0664 : 0644,
277 scores, scorecount) < 0)
279 unlock_file (scorefile, lockstate);
280 lose_syserr ("Failed to write scores file");
282 if (unlock_file (scorefile, lockstate) < 0)
283 lose_syserr ("Failed to unlock scores file");
284 exit (EXIT_SUCCESS);
287 static char *
288 read_score (char *p, struct score_entry *score)
290 score->score = p;
291 p = strchr (p, ' ');
292 if (!p)
293 return p;
294 *p++ = 0;
295 score->user_data = p;
296 p = strchr (p, '\n');
297 if (!p)
298 return p;
299 *p++ = 0;
300 return p;
303 static int
304 read_scores (const char *filename, struct score_entry **scores,
305 ptrdiff_t *count, ptrdiff_t *alloc)
307 char *p, *filedata;
308 ptrdiff_t filesize, nread;
309 struct stat st;
310 FILE *f = fopen (filename, "r");
311 if (!f)
312 return -1;
313 if (fstat (fileno (f), &st) != 0)
314 return -1;
315 if (! (0 <= st.st_size && st.st_size < min (PTRDIFF_MAX, SIZE_MAX)))
317 errno = EOVERFLOW;
318 return -1;
320 filesize = st.st_size;
321 filedata = malloc (filesize + 1);
322 if (! filedata)
323 return -1;
324 nread = fread (filedata, 1, filesize + 1, f);
325 if (filesize < nread)
327 errno = 0;
328 return -1;
330 if (nread < filesize)
331 filesize = nread;
332 if (ferror (f) || fclose (f) != 0)
333 return -1;
334 filedata[filesize] = 0;
335 if (strlen (filedata) != filesize)
337 errno = 0;
338 return -1;
341 *scores = 0;
342 *count = *alloc = 0;
343 for (p = filedata; p < filedata + filesize; )
345 struct score_entry entry;
346 p = read_score (p, &entry);
347 if (!p)
349 errno = 0;
350 return -1;
352 if (push_score (scores, count, alloc, &entry) < 0)
353 return -1;
355 return 0;
358 static int
359 score_compare (const void *a, const void *b)
361 const struct score_entry *sa = (const struct score_entry *) a;
362 const struct score_entry *sb = (const struct score_entry *) b;
363 char *sca = sa->score;
364 char *scb = sb->score;
365 size_t lena, lenb;
366 bool nega = *sca == '-';
367 bool negb = *scb == '-';
368 int diff = nega - negb;
369 if (diff)
370 return diff;
371 if (nega)
373 char *tmp = sca;
374 sca = scb + 1;
375 scb = tmp + 1;
377 lena = strlen (sca);
378 lenb = strlen (scb);
379 if (lena != lenb)
380 return lenb < lena ? -1 : 1;
381 return strcmp (scb, sca);
384 static int
385 score_compare_reverse (const void *a, const void *b)
387 return score_compare (b, a);
391 push_score (struct score_entry **scores, ptrdiff_t *count, ptrdiff_t *size,
392 struct score_entry const *newscore)
394 struct score_entry *newscores = *scores;
395 if (*count == *size)
397 ptrdiff_t newsize = *size;
398 if (newsize <= 0)
399 newsize = 1;
400 else if (newsize <= MAX_SCORES / 2)
401 newsize *= 2;
402 else if (newsize < MAX_SCORES)
403 newsize = MAX_SCORES;
404 else
406 errno = ENOMEM;
407 return -1;
409 newscores = realloc (newscores, sizeof *newscores * newsize);
410 if (!newscores)
411 return -1;
412 *scores = newscores;
413 *size = newsize;
415 newscores[*count] = *newscore;
416 (*count) += 1;
417 return 0;
420 static void
421 sort_scores (struct score_entry *scores, ptrdiff_t count, bool reverse)
423 qsort (scores, count, sizeof *scores,
424 reverse ? score_compare_reverse : score_compare);
427 static int
428 write_scores (const char *filename, mode_t mode,
429 const struct score_entry *scores, ptrdiff_t count)
431 int fd;
432 FILE *f;
433 ptrdiff_t i;
434 char *tempfile = malloc (strlen (filename) + strlen (".tempXXXXXX") + 1);
435 if (!tempfile)
436 return -1;
437 strcpy (stpcpy (tempfile, filename), ".tempXXXXXX");
438 fd = mkostemp (tempfile, 0);
439 if (fd < 0)
440 return -1;
441 #ifndef DOS_NT
442 if (fchmod (fd, mode) != 0)
443 return -1;
444 #endif
445 f = fdopen (fd, "w");
446 if (! f)
447 return -1;
448 for (i = 0; i < count; i++)
449 if (fprintf (f, "%s %s\n", scores[i].score, scores[i].user_data) < 0)
450 return -1;
451 if (fclose (f) != 0)
452 return -1;
453 if (rename (tempfile, filename) != 0)
454 return -1;
455 return 0;
458 static int
459 lock_file (const char *filename, void **state)
461 int fd;
462 struct stat buf;
463 int attempts = 0;
464 const char *lockext = ".lockfile";
465 char *lockpath = malloc (strlen (filename) + strlen (lockext) + 60);
466 if (!lockpath)
467 return -1;
468 strcpy (stpcpy (lockpath, filename), lockext);
469 *state = lockpath;
471 while ((fd = open (lockpath, O_CREAT | O_EXCL, 0600)) < 0)
473 if (errno != EEXIST)
474 return -1;
475 attempts++;
477 /* Break the lock if it is over an hour old, or if we've tried
478 more than MAX_ATTEMPTS times. We won't corrupt the file, but
479 we might lose some scores. */
480 if (MAX_ATTEMPTS < attempts
481 || (stat (lockpath, &buf) == 0 && 60 * 60 < time (0) - buf.st_ctime))
483 if (unlink (lockpath) != 0 && errno != ENOENT)
484 return -1;
485 attempts = 0;
488 sleep ((rand () & 1) + 1);
491 close (fd);
492 return 0;
495 static int
496 unlock_file (const char *filename, void *state)
498 char *lockpath = (char *) state;
499 int saved_errno = errno;
500 int ret = unlink (lockpath);
501 int unlink_errno = errno;
502 free (lockpath);
503 errno = ret < 0 ? unlink_errno : saved_errno;
504 return ret;
507 /* update-game-score.c ends here */