* lisp/version.el (emacs-bzr-version-bzr): Fix typo.
[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
1d28afaf
DL
62#ifndef HAVE_DIFFTIME
63/* OK on POSIX (time_t is arithmetic type) modulo overflow in subtraction. */
64#define difftime(t1, t0) (double)((t1) - (t0))
65#endif
66
845ca893 67static _Noreturn void
873fbd0b 68usage (int err)
2f1de3dd 69{
ec3b5374 70 fprintf (stdout, "Usage: update-game-score [-m MAX] [-r] [-d DIR] game/scorefile SCORE DATA\n");
a5d107f3
RS
71 fprintf (stdout, " update-game-score -h\n");
72 fprintf (stdout, " -h\t\tDisplay this help.\n");
73 fprintf (stdout, " -m MAX\t\tLimit the maximum number of scores to MAX.\n");
74 fprintf (stdout, " -r\t\tSort the scores in increasing order.\n");
75 fprintf (stdout, " -d DIR\t\tStore scores in DIR (only if not setuid).\n");
76 exit (err);
2f1de3dd
CW
77}
78
b23b5a5b
PE
79static int lock_file (const char *filename, void **state);
80static int unlock_file (const char *filename, void *state);
2f1de3dd
CW
81
82struct score_entry
83{
d70efef4 84 intmax_t score;
cd553ffb 85 char *username;
2f1de3dd
CW
86 char *data;
87};
88
d70efef4
PE
89#define MAX_SCORES min (PTRDIFF_MAX, SIZE_MAX / sizeof (struct score_entry))
90
b23b5a5b 91static int read_scores (const char *filename, struct score_entry **scores,
d70efef4
PE
92 ptrdiff_t *count, ptrdiff_t *alloc);
93static int push_score (struct score_entry **scores, ptrdiff_t *count,
94 ptrdiff_t *size, struct score_entry const *newscore);
95static void sort_scores (struct score_entry *scores, ptrdiff_t count,
96 bool reverse);
b23b5a5b 97static int write_scores (const char *filename,
d70efef4 98 const struct score_entry *scores, ptrdiff_t count);
cf398788 99
845ca893 100static _Noreturn void
873fbd0b 101lose (const char *msg)
cf398788 102{
a5d107f3 103 fprintf (stderr, "%s\n", msg);
65396510 104 exit (EXIT_FAILURE);
cf398788 105}
2f1de3dd 106
845ca893 107static _Noreturn void
873fbd0b 108lose_syserr (const char *msg)
d99fabf0 109{
a5d107f3 110 fprintf (stderr, "%s: %s\n", msg, strerror (errno));
65396510 111 exit (EXIT_FAILURE);
d99fabf0
CW
112}
113
b23b5a5b 114static char *
f57e2426 115get_user_id (void)
cd553ffb 116{
a5d107f3 117 struct passwd *buf = getpwuid (getuid ());
d70efef4 118 if (!buf || strchr (buf->pw_name, ' ') || strchr (buf->pw_name, '\n'))
cd553ffb 119 {
d70efef4
PE
120 intmax_t uid = getuid ();
121 char *name = malloc (sizeof uid * CHAR_BIT / 3 + 4);
0c6d656d 122 if (name)
d70efef4 123 sprintf (name, "%"PRIdMAX, uid);
cd553ffb
CW
124 return name;
125 }
126 return buf->pw_name;
127}
128
b23b5a5b 129static const char *
d70efef4 130get_prefix (bool running_suid, const char *user_prefix)
8eec804f 131{
d99fabf0 132 if (!running_suid && user_prefix == NULL)
a5d107f3 133 lose ("Not using a shared game directory, and no prefix given.");
d99fabf0
CW
134 if (running_suid)
135 {
136#ifdef HAVE_SHARED_GAME_DIR
137 return HAVE_SHARED_GAME_DIR;
138#else
a5d107f3 139 lose ("This program was compiled without HAVE_SHARED_GAME_DIR,\n and should not be suid.");
d99fabf0
CW
140#endif
141 }
142 return user_prefix;
8eec804f
CW
143}
144
2f1de3dd 145int
873fbd0b 146main (int argc, char **argv)
2f1de3dd 147{
d70efef4
PE
148 int c;
149 bool running_suid;
2f1de3dd 150 void *lockstate;
d70efef4
PE
151 char *scorefile;
152 char *nl;
988e88ab 153 const char *prefix, *user_prefix = NULL;
2f1de3dd
CW
154 struct stat buf;
155 struct score_entry *scores;
d70efef4
PE
156 struct score_entry newscore;
157 bool reverse = false;
158 ptrdiff_t scorecount, scorealloc;
159 ptrdiff_t max_scores = MAX_SCORES;
2f1de3dd 160
a5d107f3 161 srand (time (0));
2f1de3dd 162
a5d107f3 163 while ((c = getopt (argc, argv, "hrm:d:")) != -1)
2f1de3dd
CW
164 switch (c)
165 {
166 case 'h':
65396510 167 usage (EXIT_SUCCESS);
2f1de3dd 168 break;
d99fabf0
CW
169 case 'd':
170 user_prefix = optarg;
171 break;
2f1de3dd
CW
172 case 'r':
173 reverse = 1;
174 break;
175 case 'm':
d70efef4
PE
176 {
177 intmax_t m = strtoimax (optarg, 0, 10);
178 if (m < 0)
179 usage (EXIT_FAILURE);
180 max_scores = min (m, MAX_SCORES);
181 }
2f1de3dd
CW
182 break;
183 default:
65396510 184 usage (EXIT_FAILURE);
2f1de3dd
CW
185 }
186
d70efef4 187 if (argc - optind != 3)
65396510 188 usage (EXIT_FAILURE);
5795b420 189
a5d107f3 190 running_suid = (getuid () != geteuid ());
5795b420 191
a5d107f3 192 prefix = get_prefix (running_suid, user_prefix);
8eec804f 193
a5d107f3 194 scorefile = malloc (strlen (prefix) + strlen (argv[optind]) + 2);
2f1de3dd 195 if (!scorefile)
a5d107f3 196 lose_syserr ("Couldn't allocate score file");
8eec804f 197
a5d107f3
RS
198 strcpy (scorefile, prefix);
199 strcat (scorefile, "/");
200 strcat (scorefile, argv[optind]);
d99fabf0 201
d70efef4
PE
202 newscore.score = strtoimax (argv[optind + 1], 0, 10);
203
204 newscore.data = argv[optind + 2];
205 if (strlen (newscore.data) > MAX_DATA_LEN)
206 newscore.data[MAX_DATA_LEN] = '\0';
207 nl = strchr (newscore.data, '\n');
208 if (nl)
209 *nl = '\0';
210
211 newscore.username = get_user_id ();
212 if (! newscore.username)
a5d107f3 213 lose_syserr ("Couldn't determine user id");
177c0ea7 214
a5d107f3
RS
215 if (stat (scorefile, &buf) < 0)
216 lose_syserr ("Failed to access scores file");
177c0ea7 217
a5d107f3
RS
218 if (lock_file (scorefile, &lockstate) < 0)
219 lose_syserr ("Failed to lock scores file");
177c0ea7 220
d70efef4 221 if (read_scores (scorefile, &scores, &scorecount, &scorealloc) < 0)
2f1de3dd 222 {
a5d107f3
RS
223 unlock_file (scorefile, lockstate);
224 lose_syserr ("Failed to read scores file");
2f1de3dd 225 }
d70efef4
PE
226 if (push_score (&scores, &scorecount, &scorealloc, &newscore) < 0)
227 {
228 unlock_file (scorefile, lockstate);
229 lose_syserr ("Failed to add score");
230 }
24e9e996 231 sort_scores (scores, scorecount, reverse);
8eec804f 232 /* Limit the number of scores. If we're using reverse sorting, then
f0d80d43
PE
233 also increment the beginning of the array, to skip over the
234 *smallest* scores. Otherwise, just decrementing the number of
235 scores suffices, since the smallest is at the end. */
d70efef4 236 if (scorecount > max_scores)
f0d80d43
PE
237 {
238 if (reverse)
d70efef4
PE
239 scores += scorecount - max_scores;
240 scorecount = max_scores;
f0d80d43 241 }
a5d107f3 242 if (write_scores (scorefile, scores, scorecount) < 0)
2f1de3dd 243 {
a5d107f3
RS
244 unlock_file (scorefile, lockstate);
245 lose_syserr ("Failed to write scores file");
2f1de3dd 246 }
d70efef4
PE
247 if (unlock_file (scorefile, lockstate) < 0)
248 lose_syserr ("Failed to unlock scores file");
65396510 249 exit (EXIT_SUCCESS);
2f1de3dd
CW
250}
251
b23b5a5b 252static int
873fbd0b 253read_score (FILE *f, struct score_entry *score)
2f1de3dd
CW
254{
255 int c;
98a428c1
EZ
256 if ((c = getc (f)) != EOF)
257 ungetc (c, f);
a5d107f3 258 if (feof (f))
2f1de3dd 259 return 1;
98a428c1 260 for (score->score = 0; (c = getc (f)) != EOF && isdigit (c); )
cd553ffb 261 {
d70efef4
PE
262 if (INTMAX_MAX / 10 < score->score)
263 return -1;
cd553ffb 264 score->score *= 10;
d70efef4
PE
265 if (INTMAX_MAX - (c - '0') < score->score)
266 return -1;
267 score->score += c - '0';
cd553ffb 268 }
a5d107f3
RS
269 while ((c = getc (f)) != EOF
270 && isspace (c))
cd553ffb
CW
271 ;
272 if (c == EOF)
273 return -1;
a5d107f3 274 ungetc (c, f);
cd553ffb
CW
275#ifdef HAVE_GETDELIM
276 {
7605f1bd 277 size_t count = 0;
a5d107f3 278 if (getdelim (&score->username, &count, ' ', f) < 1
cd553ffb
CW
279 || score->username == NULL)
280 return -1;
1d4328ff 281 /* Trim the space */
a5d107f3 282 score->username[strlen (score->username)-1] = '\0';
2f1de3dd 283 }
cd553ffb
CW
284#else
285 {
d70efef4
PE
286 ptrdiff_t unameread = 0;
287 ptrdiff_t unamelen = 30;
a5d107f3 288 char *username = malloc (unamelen);
f5bceaf8
CW
289 if (!username)
290 return -1;
177c0ea7 291
d70efef4 292 while ((c = getc (f)) != EOF && c != ' ')
cd553ffb 293 {
d70efef4
PE
294 if (unameread >= unamelen - 1)
295 {
296 ptrdiff_t unamelen_max = min (PTRDIFF_MAX, SIZE_MAX);
297 if (unamelen <= unamelen_max / 2)
298 unamelen *= 2;
299 else if (unamelen < unamelen_max)
300 unamelen = unamelen_max;
301 else
302 {
303 errno = ENOMEM;
304 return -1;
305 }
306 username = realloc (username, unamelen);
307 if (!username)
308 return -1;
309 }
cd553ffb
CW
310 username[unameread] = c;
311 unameread++;
312 }
177c0ea7 313 if (c == EOF)
f5bceaf8
CW
314 return -1;
315 username[unameread] = '\0';
cd553ffb
CW
316 score->username = username;
317 }
318#endif
2f1de3dd
CW
319#ifdef HAVE_GETLINE
320 score->data = NULL;
7605f1bd 321 errno = 0;
2f1de3dd 322 {
7605f1bd 323 size_t len;
a5d107f3 324 if (getline (&score->data, &len, f) < 0)
2f1de3dd 325 return -1;
a5d107f3 326 score->data[strlen (score->data)-1] = '\0';
2f1de3dd
CW
327 }
328#else
cd553ffb 329 {
d70efef4
PE
330 ptrdiff_t cur = 0;
331 ptrdiff_t len = 16;
a5d107f3 332 char *buf = malloc (len);
cd553ffb
CW
333 if (!buf)
334 return -1;
a5d107f3 335 while ((c = getc (f)) != EOF
f5bceaf8 336 && c != '\n')
cd553ffb
CW
337 {
338 if (cur >= len-1)
339 {
d70efef4
PE
340 if (min (PTRDIFF_MAX, SIZE_MAX) / 2 < len)
341 {
342 errno = ENOMEM;
343 return -1;
344 }
a5d107f3 345 if (!(buf = realloc (buf, len *= 2)))
cd553ffb
CW
346 return -1;
347 }
348 buf[cur] = c;
349 cur++;
350 }
351 score->data = buf;
5795b420 352 score->data[cur] = '\0';
cd553ffb 353 }
2f1de3dd 354#endif
2f1de3dd
CW
355 return 0;
356}
357
b23b5a5b 358static int
d70efef4
PE
359read_scores (const char *filename, struct score_entry **scores,
360 ptrdiff_t *count, ptrdiff_t *alloc)
2f1de3dd 361{
d70efef4
PE
362 int readval = -1;
363 ptrdiff_t scorecount = 0;
364 ptrdiff_t cursize = 0;
365 struct score_entry *ret = 0;
366 struct score_entry entry;
a5d107f3 367 FILE *f = fopen (filename, "r");
98a428c1 368 int retval = -1;
177c0ea7 369 if (!f)
2f1de3dd 370 return -1;
d70efef4
PE
371 while ((readval = read_score (f, &entry)) == 0)
372 if (push_score (&ret, &scorecount, &cursize, &entry) < 0)
373 return -1;
98a428c1
EZ
374 if (readval > 0)
375 {
376 *count = scorecount;
d70efef4 377 *alloc = cursize;
98a428c1
EZ
378 *scores = ret;
379 retval = 0;
380 }
381 fclose (f);
382 return retval;
2f1de3dd
CW
383}
384
b23b5a5b 385static int
873fbd0b 386score_compare (const void *a, const void *b)
2f1de3dd
CW
387{
388 const struct score_entry *sa = (const struct score_entry *) a;
389 const struct score_entry *sb = (const struct score_entry *) b;
390 return (sb->score > sa->score) - (sb->score < sa->score);
391}
392
b23b5a5b 393static int
873fbd0b 394score_compare_reverse (const void *a, const void *b)
2f1de3dd 395{
d70efef4 396 return score_compare (b, a);
2f1de3dd
CW
397}
398
399int
d70efef4
PE
400push_score (struct score_entry **scores, ptrdiff_t *count, ptrdiff_t *size,
401 struct score_entry const *newscore)
2f1de3dd 402{
d70efef4
PE
403 struct score_entry *newscores = *scores;
404 if (*count == *size)
405 {
406 ptrdiff_t newsize = *size;
407 if (newsize <= 0)
408 newsize = 1;
409 else if (newsize <= MAX_SCORES / 2)
410 newsize *= 2;
411 else if (newsize < MAX_SCORES)
412 newsize = MAX_SCORES;
413 else
414 {
415 errno = ENOMEM;
416 return -1;
417 }
418 newscores = realloc (newscores, sizeof *newscores * newsize);
419 if (!newscores)
420 return -1;
421 *scores = newscores;
422 *size = newsize;
423 }
424 newscores[*count] = *newscore;
2f1de3dd 425 (*count) += 1;
2f1de3dd
CW
426 return 0;
427}
177c0ea7 428
b23b5a5b 429static void
d70efef4 430sort_scores (struct score_entry *scores, ptrdiff_t count, bool reverse)
2f1de3dd 431{
d70efef4
PE
432 qsort (scores, count, sizeof *scores,
433 reverse ? score_compare_reverse : score_compare);
2f1de3dd
CW
434}
435
b23b5a5b 436static int
d70efef4
PE
437write_scores (const char *filename, const struct score_entry *scores,
438 ptrdiff_t count)
2f1de3dd 439{
e0fdb694 440 int fd;
177c0ea7 441 FILE *f;
d70efef4 442 ptrdiff_t i;
a5d107f3 443 char *tempfile = malloc (strlen (filename) + strlen (".tempXXXXXX") + 1);
2f1de3dd
CW
444 if (!tempfile)
445 return -1;
a5d107f3
RS
446 strcpy (tempfile, filename);
447 strcat (tempfile, ".tempXXXXXX");
e0fdb694
PE
448 fd = mkostemp (tempfile, 0);
449 if (fd < 0)
450 return -1;
451 f = fdopen (fd, "w");
452 if (! f)
2f1de3dd
CW
453 return -1;
454 for (i = 0; i < count; i++)
d70efef4
PE
455 if (fprintf (f, "%"PRIdMAX" %s %s\n",
456 scores[i].score, scores[i].username, scores[i].data)
457 < 0)
2f1de3dd 458 return -1;
a5d107f3
RS
459 fclose (f);
460 if (rename (tempfile, filename) < 0)
2f1de3dd 461 return -1;
a5d107f3 462 if (chmod (filename, 0644) < 0)
2f1de3dd 463 return -1;
8eec804f 464 return 0;
2f1de3dd 465}
177c0ea7 466
b23b5a5b 467static int
873fbd0b 468lock_file (const char *filename, void **state)
2f1de3dd
CW
469{
470 int fd;
7c4f6873 471 struct stat buf;
2f1de3dd 472 int attempts = 0;
988e88ab 473 const char *lockext = ".lockfile";
a5d107f3 474 char *lockpath = malloc (strlen (filename) + strlen (lockext) + 60);
2f1de3dd
CW
475 if (!lockpath)
476 return -1;
a5d107f3
RS
477 strcpy (lockpath, filename);
478 strcat (lockpath, lockext);
2f1de3dd
CW
479 *state = lockpath;
480 trylock:
481 attempts++;
7c4f6873 482 /* If the lock is over an hour old, delete it. */
a5d107f3
RS
483 if (stat (lockpath, &buf) == 0
484 && (difftime (buf.st_ctime, time (NULL) > 60*60)))
485 unlink (lockpath);
00a7e408
RS
486 fd = open (lockpath, O_CREAT | O_EXCL, 0600);
487 if (fd < 0)
2f1de3dd
CW
488 {
489 if (errno == EEXIST)
490 {
491 /* Break the lock; we won't corrupt the file, but we might
492 lose some scores. */
493 if (attempts > MAX_ATTEMPTS)
7c4f6873 494 {
a5d107f3 495 unlink (lockpath);
7c4f6873
CW
496 attempts = 0;
497 }
a5d107f3 498 sleep ((rand () % 2)+1);
2f1de3dd
CW
499 goto trylock;
500 }
501 else
502 return -1;
503 }
a5d107f3 504 close (fd);
2f1de3dd
CW
505 return 0;
506}
177c0ea7 507
b23b5a5b 508static int
873fbd0b 509unlock_file (const char *filename, void *state)
2f1de3dd
CW
510{
511 char *lockpath = (char *) state;
2f1de3dd 512 int saved_errno = errno;
d70efef4
PE
513 int ret = unlink (lockpath);
514 int unlink_errno = errno;
a5d107f3 515 free (lockpath);
d70efef4 516 errno = ret < 0 ? unlink_errno : saved_errno;
2f1de3dd
CW
517 return ret;
518}
ab5796a9 519
65396510 520/* update-game-score.c ends here */