ChangeLog fix.
[bpt/emacs.git] / lib-src / update-game-score.c
CommitLineData
2f1de3dd 1/* update-game-score.c --- Update a score file
294981c7 2
ba318903 3Copyright (C) 2002-2014 Free Software Foundation, Inc.
294981c7
GM
4
5Author: Colin Walters <walters@debian.org>
2f1de3dd
CW
6
7This file is part of GNU Emacs.
8
294981c7 9GNU Emacs is free software: you can redistribute it and/or modify
2f1de3dd 10it under the terms of the GNU General Public License as published by
294981c7
GM
11the Free Software Foundation, either version 3 of the License, or
12(at your option) any later version.
2f1de3dd
CW
13
14GNU Emacs is distributed in the hope that it will be useful,
15but WITHOUT ANY WARRANTY; without even the implied warranty of
16MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17GNU General Public License for more details.
18
19You should have received a copy of the GNU General Public License
294981c7
GM
20along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
21
2f1de3dd 22
89cc1591 23/* This program allows a game to securely and atomically update a
8eec804f
CW
24 score file. It should be installed setuid, owned by an appropriate
25 user like `games'.
26
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).
2f1de3dd 30
294981c7 31 Created 2002/03/22.
2f1de3dd
CW
32*/
33
c42d6dbd
EZ
34#include <config.h>
35
2f1de3dd
CW
36#include <unistd.h>
37#include <errno.h>
d70efef4 38#include <inttypes.h>
0c6d656d 39#include <limits.h>
d70efef4 40#include <stdbool.h>
2f1de3dd
CW
41#include <string.h>
42#include <stdlib.h>
43#include <stdio.h>
44#include <time.h>
cd553ffb 45#include <pwd.h>
2f1de3dd
CW
46#include <ctype.h>
47#include <fcntl.h>
48#include <sys/stat.h>
15142f27 49#include <getopt.h>
5b400482 50
7c4026b6
EZ
51#ifdef WINDOWSNT
52#include "ntlib.h"
53#endif
54
d70efef4
PE
55#ifndef min
56# define min(a,b) ((a) < (b) ? (a) : (b))
57#endif
58
2f1de3dd 59#define MAX_ATTEMPTS 5
8eec804f 60#define MAX_DATA_LEN 1024
5795b420 61
845ca893 62static _Noreturn void
873fbd0b 63usage (int err)
2f1de3dd 64{
ec3b5374 65 fprintf (stdout, "Usage: update-game-score [-m MAX] [-r] [-d DIR] game/scorefile SCORE DATA\n");
a5d107f3
RS
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);
2f1de3dd
CW
72}
73
b23b5a5b
PE
74static int lock_file (const char *filename, void **state);
75static int unlock_file (const char *filename, void *state);
2f1de3dd
CW
76
77struct score_entry
78{
d70efef4 79 intmax_t score;
cd553ffb 80 char *username;
2f1de3dd
CW
81 char *data;
82};
83
d70efef4
PE
84#define MAX_SCORES min (PTRDIFF_MAX, SIZE_MAX / sizeof (struct score_entry))
85
b23b5a5b 86static int read_scores (const char *filename, struct score_entry **scores,
d70efef4
PE
87 ptrdiff_t *count, ptrdiff_t *alloc);
88static int push_score (struct score_entry **scores, ptrdiff_t *count,
89 ptrdiff_t *size, struct score_entry const *newscore);
90static void sort_scores (struct score_entry *scores, ptrdiff_t count,
91 bool reverse);
b23b5a5b 92static int write_scores (const char *filename,
d70efef4 93 const struct score_entry *scores, ptrdiff_t count);
cf398788 94
845ca893 95static _Noreturn void
873fbd0b 96lose (const char *msg)
cf398788 97{
a5d107f3 98 fprintf (stderr, "%s\n", msg);
65396510 99 exit (EXIT_FAILURE);
cf398788 100}
2f1de3dd 101
845ca893 102static _Noreturn void
873fbd0b 103lose_syserr (const char *msg)
d99fabf0 104{
a5d107f3 105 fprintf (stderr, "%s: %s\n", msg, strerror (errno));
65396510 106 exit (EXIT_FAILURE);
d99fabf0
CW
107}
108
b23b5a5b 109static char *
f57e2426 110get_user_id (void)
cd553ffb 111{
a5d107f3 112 struct passwd *buf = getpwuid (getuid ());
d70efef4 113 if (!buf || strchr (buf->pw_name, ' ') || strchr (buf->pw_name, '\n'))
cd553ffb 114 {
d70efef4
PE
115 intmax_t uid = getuid ();
116 char *name = malloc (sizeof uid * CHAR_BIT / 3 + 4);
0c6d656d 117 if (name)
d70efef4 118 sprintf (name, "%"PRIdMAX, uid);
cd553ffb
CW
119 return name;
120 }
121 return buf->pw_name;
122}
123
b23b5a5b 124static const char *
d70efef4 125get_prefix (bool running_suid, const char *user_prefix)
8eec804f 126{
d99fabf0 127 if (!running_suid && user_prefix == NULL)
a5d107f3 128 lose ("Not using a shared game directory, and no prefix given.");
d99fabf0
CW
129 if (running_suid)
130 {
131#ifdef HAVE_SHARED_GAME_DIR
132 return HAVE_SHARED_GAME_DIR;
133#else
a5d107f3 134 lose ("This program was compiled without HAVE_SHARED_GAME_DIR,\n and should not be suid.");
d99fabf0
CW
135#endif
136 }
137 return user_prefix;
8eec804f
CW
138}
139
2f1de3dd 140int
873fbd0b 141main (int argc, char **argv)
2f1de3dd 142{
d70efef4
PE
143 int c;
144 bool running_suid;
2f1de3dd 145 void *lockstate;
d70efef4
PE
146 char *scorefile;
147 char *nl;
988e88ab 148 const char *prefix, *user_prefix = NULL;
2f1de3dd
CW
149 struct stat buf;
150 struct score_entry *scores;
d70efef4
PE
151 struct score_entry newscore;
152 bool reverse = false;
153 ptrdiff_t scorecount, scorealloc;
154 ptrdiff_t max_scores = MAX_SCORES;
2f1de3dd 155
a5d107f3 156 srand (time (0));
2f1de3dd 157
a5d107f3 158 while ((c = getopt (argc, argv, "hrm:d:")) != -1)
2f1de3dd
CW
159 switch (c)
160 {
161 case 'h':
65396510 162 usage (EXIT_SUCCESS);
2f1de3dd 163 break;
d99fabf0
CW
164 case 'd':
165 user_prefix = optarg;
166 break;
2f1de3dd
CW
167 case 'r':
168 reverse = 1;
169 break;
170 case 'm':
d70efef4
PE
171 {
172 intmax_t m = strtoimax (optarg, 0, 10);
173 if (m < 0)
174 usage (EXIT_FAILURE);
175 max_scores = min (m, MAX_SCORES);
176 }
2f1de3dd
CW
177 break;
178 default:
65396510 179 usage (EXIT_FAILURE);
2f1de3dd
CW
180 }
181
d70efef4 182 if (argc - optind != 3)
65396510 183 usage (EXIT_FAILURE);
5795b420 184
a5d107f3 185 running_suid = (getuid () != geteuid ());
5795b420 186
a5d107f3 187 prefix = get_prefix (running_suid, user_prefix);
8eec804f 188
a5d107f3 189 scorefile = malloc (strlen (prefix) + strlen (argv[optind]) + 2);
2f1de3dd 190 if (!scorefile)
a5d107f3 191 lose_syserr ("Couldn't allocate score file");
8eec804f 192
a5d107f3
RS
193 strcpy (scorefile, prefix);
194 strcat (scorefile, "/");
195 strcat (scorefile, argv[optind]);
d99fabf0 196
d70efef4
PE
197 newscore.score = strtoimax (argv[optind + 1], 0, 10);
198
199 newscore.data = argv[optind + 2];
200 if (strlen (newscore.data) > MAX_DATA_LEN)
201 newscore.data[MAX_DATA_LEN] = '\0';
202 nl = strchr (newscore.data, '\n');
203 if (nl)
204 *nl = '\0';
205
206 newscore.username = get_user_id ();
207 if (! newscore.username)
a5d107f3 208 lose_syserr ("Couldn't determine user id");
177c0ea7 209
a5d107f3
RS
210 if (stat (scorefile, &buf) < 0)
211 lose_syserr ("Failed to access scores file");
177c0ea7 212
a5d107f3
RS
213 if (lock_file (scorefile, &lockstate) < 0)
214 lose_syserr ("Failed to lock scores file");
177c0ea7 215
d70efef4 216 if (read_scores (scorefile, &scores, &scorecount, &scorealloc) < 0)
2f1de3dd 217 {
a5d107f3
RS
218 unlock_file (scorefile, lockstate);
219 lose_syserr ("Failed to read scores file");
2f1de3dd 220 }
d70efef4
PE
221 if (push_score (&scores, &scorecount, &scorealloc, &newscore) < 0)
222 {
223 unlock_file (scorefile, lockstate);
224 lose_syserr ("Failed to add score");
225 }
24e9e996 226 sort_scores (scores, scorecount, reverse);
8eec804f 227 /* Limit the number of scores. If we're using reverse sorting, then
f0d80d43
PE
228 also increment the beginning of the array, to skip over the
229 *smallest* scores. Otherwise, just decrementing the number of
230 scores suffices, since the smallest is at the end. */
d70efef4 231 if (scorecount > max_scores)
f0d80d43
PE
232 {
233 if (reverse)
d70efef4
PE
234 scores += scorecount - max_scores;
235 scorecount = max_scores;
f0d80d43 236 }
a5d107f3 237 if (write_scores (scorefile, scores, scorecount) < 0)
2f1de3dd 238 {
a5d107f3
RS
239 unlock_file (scorefile, lockstate);
240 lose_syserr ("Failed to write scores file");
2f1de3dd 241 }
d70efef4
PE
242 if (unlock_file (scorefile, lockstate) < 0)
243 lose_syserr ("Failed to unlock scores file");
65396510 244 exit (EXIT_SUCCESS);
2f1de3dd
CW
245}
246
b23b5a5b 247static int
873fbd0b 248read_score (FILE *f, struct score_entry *score)
2f1de3dd
CW
249{
250 int c;
98a428c1
EZ
251 if ((c = getc (f)) != EOF)
252 ungetc (c, f);
a5d107f3 253 if (feof (f))
2f1de3dd 254 return 1;
98a428c1 255 for (score->score = 0; (c = getc (f)) != EOF && isdigit (c); )
cd553ffb 256 {
d70efef4
PE
257 if (INTMAX_MAX / 10 < score->score)
258 return -1;
cd553ffb 259 score->score *= 10;
d70efef4
PE
260 if (INTMAX_MAX - (c - '0') < score->score)
261 return -1;
262 score->score += c - '0';
cd553ffb 263 }
a5d107f3
RS
264 while ((c = getc (f)) != EOF
265 && isspace (c))
cd553ffb
CW
266 ;
267 if (c == EOF)
268 return -1;
a5d107f3 269 ungetc (c, f);
cd553ffb
CW
270#ifdef HAVE_GETDELIM
271 {
7605f1bd 272 size_t count = 0;
dc217d01 273 score->username = 0;
a5d107f3 274 if (getdelim (&score->username, &count, ' ', f) < 1
cd553ffb
CW
275 || score->username == NULL)
276 return -1;
1d4328ff 277 /* Trim the space */
a5d107f3 278 score->username[strlen (score->username)-1] = '\0';
2f1de3dd 279 }
cd553ffb
CW
280#else
281 {
d70efef4
PE
282 ptrdiff_t unameread = 0;
283 ptrdiff_t unamelen = 30;
a5d107f3 284 char *username = malloc (unamelen);
f5bceaf8
CW
285 if (!username)
286 return -1;
177c0ea7 287
d70efef4 288 while ((c = getc (f)) != EOF && c != ' ')
cd553ffb 289 {
d70efef4
PE
290 if (unameread >= unamelen - 1)
291 {
292 ptrdiff_t unamelen_max = min (PTRDIFF_MAX, SIZE_MAX);
293 if (unamelen <= unamelen_max / 2)
294 unamelen *= 2;
295 else if (unamelen < unamelen_max)
296 unamelen = unamelen_max;
297 else
298 {
299 errno = ENOMEM;
300 return -1;
301 }
302 username = realloc (username, unamelen);
303 if (!username)
304 return -1;
305 }
cd553ffb
CW
306 username[unameread] = c;
307 unameread++;
308 }
177c0ea7 309 if (c == EOF)
f5bceaf8
CW
310 return -1;
311 username[unameread] = '\0';
cd553ffb
CW
312 score->username = username;
313 }
314#endif
2f1de3dd
CW
315#ifdef HAVE_GETLINE
316 score->data = NULL;
7605f1bd 317 errno = 0;
2f1de3dd 318 {
7605f1bd 319 size_t len;
a5d107f3 320 if (getline (&score->data, &len, f) < 0)
2f1de3dd 321 return -1;
a5d107f3 322 score->data[strlen (score->data)-1] = '\0';
2f1de3dd
CW
323 }
324#else
cd553ffb 325 {
d70efef4
PE
326 ptrdiff_t cur = 0;
327 ptrdiff_t len = 16;
a5d107f3 328 char *buf = malloc (len);
cd553ffb
CW
329 if (!buf)
330 return -1;
a5d107f3 331 while ((c = getc (f)) != EOF
f5bceaf8 332 && c != '\n')
cd553ffb
CW
333 {
334 if (cur >= len-1)
335 {
d70efef4
PE
336 if (min (PTRDIFF_MAX, SIZE_MAX) / 2 < len)
337 {
338 errno = ENOMEM;
339 return -1;
340 }
a5d107f3 341 if (!(buf = realloc (buf, len *= 2)))
cd553ffb
CW
342 return -1;
343 }
344 buf[cur] = c;
345 cur++;
346 }
347 score->data = buf;
5795b420 348 score->data[cur] = '\0';
cd553ffb 349 }
2f1de3dd 350#endif
2f1de3dd
CW
351 return 0;
352}
353
b23b5a5b 354static int
d70efef4
PE
355read_scores (const char *filename, struct score_entry **scores,
356 ptrdiff_t *count, ptrdiff_t *alloc)
2f1de3dd 357{
d70efef4
PE
358 int readval = -1;
359 ptrdiff_t scorecount = 0;
360 ptrdiff_t cursize = 0;
361 struct score_entry *ret = 0;
362 struct score_entry entry;
a5d107f3 363 FILE *f = fopen (filename, "r");
98a428c1 364 int retval = -1;
177c0ea7 365 if (!f)
2f1de3dd 366 return -1;
d70efef4
PE
367 while ((readval = read_score (f, &entry)) == 0)
368 if (push_score (&ret, &scorecount, &cursize, &entry) < 0)
369 return -1;
dc217d01 370 if (readval > 0 && fclose (f) == 0)
98a428c1
EZ
371 {
372 *count = scorecount;
d70efef4 373 *alloc = cursize;
98a428c1
EZ
374 *scores = ret;
375 retval = 0;
376 }
98a428c1 377 return retval;
2f1de3dd
CW
378}
379
b23b5a5b 380static int
873fbd0b 381score_compare (const void *a, const void *b)
2f1de3dd
CW
382{
383 const struct score_entry *sa = (const struct score_entry *) a;
384 const struct score_entry *sb = (const struct score_entry *) b;
385 return (sb->score > sa->score) - (sb->score < sa->score);
386}
387
b23b5a5b 388static int
873fbd0b 389score_compare_reverse (const void *a, const void *b)
2f1de3dd 390{
d70efef4 391 return score_compare (b, a);
2f1de3dd
CW
392}
393
394int
d70efef4
PE
395push_score (struct score_entry **scores, ptrdiff_t *count, ptrdiff_t *size,
396 struct score_entry const *newscore)
2f1de3dd 397{
d70efef4
PE
398 struct score_entry *newscores = *scores;
399 if (*count == *size)
400 {
401 ptrdiff_t newsize = *size;
402 if (newsize <= 0)
403 newsize = 1;
404 else if (newsize <= MAX_SCORES / 2)
405 newsize *= 2;
406 else if (newsize < MAX_SCORES)
407 newsize = MAX_SCORES;
408 else
409 {
410 errno = ENOMEM;
411 return -1;
412 }
413 newscores = realloc (newscores, sizeof *newscores * newsize);
414 if (!newscores)
415 return -1;
416 *scores = newscores;
417 *size = newsize;
418 }
419 newscores[*count] = *newscore;
2f1de3dd 420 (*count) += 1;
2f1de3dd
CW
421 return 0;
422}
177c0ea7 423
b23b5a5b 424static void
d70efef4 425sort_scores (struct score_entry *scores, ptrdiff_t count, bool reverse)
2f1de3dd 426{
d70efef4
PE
427 qsort (scores, count, sizeof *scores,
428 reverse ? score_compare_reverse : score_compare);
2f1de3dd
CW
429}
430
b23b5a5b 431static int
d70efef4
PE
432write_scores (const char *filename, const struct score_entry *scores,
433 ptrdiff_t count)
2f1de3dd 434{
e0fdb694 435 int fd;
177c0ea7 436 FILE *f;
d70efef4 437 ptrdiff_t i;
a5d107f3 438 char *tempfile = malloc (strlen (filename) + strlen (".tempXXXXXX") + 1);
2f1de3dd
CW
439 if (!tempfile)
440 return -1;
a5d107f3
RS
441 strcpy (tempfile, filename);
442 strcat (tempfile, ".tempXXXXXX");
e0fdb694
PE
443 fd = mkostemp (tempfile, 0);
444 if (fd < 0)
445 return -1;
dc217d01
PE
446 if (fchmod (fd, 0644) != 0)
447 return -1;
e0fdb694
PE
448 f = fdopen (fd, "w");
449 if (! f)
2f1de3dd
CW
450 return -1;
451 for (i = 0; i < count; i++)
d70efef4
PE
452 if (fprintf (f, "%"PRIdMAX" %s %s\n",
453 scores[i].score, scores[i].username, scores[i].data)
454 < 0)
2f1de3dd 455 return -1;
dc217d01 456 if (fclose (f) != 0)
2f1de3dd 457 return -1;
dc217d01 458 if (rename (tempfile, filename) != 0)
2f1de3dd 459 return -1;
8eec804f 460 return 0;
2f1de3dd 461}
177c0ea7 462
b23b5a5b 463static int
873fbd0b 464lock_file (const char *filename, void **state)
2f1de3dd
CW
465{
466 int fd;
7c4f6873 467 struct stat buf;
2f1de3dd 468 int attempts = 0;
988e88ab 469 const char *lockext = ".lockfile";
a5d107f3 470 char *lockpath = malloc (strlen (filename) + strlen (lockext) + 60);
2f1de3dd
CW
471 if (!lockpath)
472 return -1;
a5d107f3
RS
473 strcpy (lockpath, filename);
474 strcat (lockpath, lockext);
2f1de3dd
CW
475 *state = lockpath;
476 trylock:
477 attempts++;
dc217d01 478 /* If the lock is over an hour old, delete it. */
a5d107f3 479 if (stat (lockpath, &buf) == 0
dc217d01 480 && 60 * 60 < time (0) - buf.st_ctime)
a5d107f3 481 unlink (lockpath);
00a7e408
RS
482 fd = open (lockpath, O_CREAT | O_EXCL, 0600);
483 if (fd < 0)
2f1de3dd
CW
484 {
485 if (errno == EEXIST)
486 {
487 /* Break the lock; we won't corrupt the file, but we might
488 lose some scores. */
489 if (attempts > MAX_ATTEMPTS)
7c4f6873 490 {
a5d107f3 491 unlink (lockpath);
7c4f6873
CW
492 attempts = 0;
493 }
a5d107f3 494 sleep ((rand () % 2)+1);
2f1de3dd
CW
495 goto trylock;
496 }
497 else
498 return -1;
499 }
a5d107f3 500 close (fd);
2f1de3dd
CW
501 return 0;
502}
177c0ea7 503
b23b5a5b 504static int
873fbd0b 505unlock_file (const char *filename, void *state)
2f1de3dd
CW
506{
507 char *lockpath = (char *) state;
2f1de3dd 508 int saved_errno = errno;
d70efef4
PE
509 int ret = unlink (lockpath);
510 int unlink_errno = errno;
a5d107f3 511 free (lockpath);
d70efef4 512 errno = ret < 0 ? unlink_errno : saved_errno;
2f1de3dd
CW
513 return ret;
514}
ab5796a9 515
65396510 516/* update-game-score.c ends here */