Merge changes from emacs-24 branch
[bpt/emacs.git] / lib-src / update-game-score.c
CommitLineData
2f1de3dd 1/* update-game-score.c --- Update a score file
294981c7 2
acaf905b 3Copyright (C) 2002-2012 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>
0c6d656d 38#include <limits.h>
2f1de3dd
CW
39#include <string.h>
40#include <stdlib.h>
41#include <stdio.h>
42#include <time.h>
cd553ffb 43#include <pwd.h>
2f1de3dd 44#include <ctype.h>
5b400482 45#ifdef HAVE_FCNTL_H
2f1de3dd 46#include <fcntl.h>
5b400482 47#endif
2f1de3dd 48#include <sys/stat.h>
15142f27 49#include <getopt.h>
5b400482 50
b23b5a5b 51static int usage (int err) NO_RETURN;
68441b90 52
2f1de3dd 53#define MAX_ATTEMPTS 5
8eec804f
CW
54#define MAX_SCORES 200
55#define MAX_DATA_LEN 1024
5795b420 56
1d28afaf
DL
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
61
b23b5a5b 62static int
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{
79 long score;
cd553ffb 80 char *username;
2f1de3dd
CW
81 char *data;
82};
83
b23b5a5b
PE
84static int read_scores (const char *filename, struct score_entry **scores,
85 int *count);
86static int push_score (struct score_entry **scores, int *count,
87 int newscore, char *username, char *newdata);
88static void sort_scores (struct score_entry *scores, int count, int reverse);
89static int write_scores (const char *filename,
90 const struct score_entry *scores, int count);
cf398788 91
b23b5a5b 92static void lose (const char *msg) NO_RETURN;
cf398788 93
b23b5a5b 94static void
873fbd0b 95lose (const char *msg)
cf398788 96{
a5d107f3 97 fprintf (stderr, "%s\n", msg);
65396510 98 exit (EXIT_FAILURE);
cf398788 99}
2f1de3dd 100
b23b5a5b 101static void lose_syserr (const char *msg) NO_RETURN;
d99fabf0 102
1d28afaf
DL
103/* Taken from sysdep.c. */
104#ifndef HAVE_STRERROR
105#ifndef WINDOWSNT
106char *
ec3b5374 107strerror (int errnum)
1d28afaf
DL
108{
109 extern char *sys_errlist[];
110 extern int sys_nerr;
111
112 if (errnum >= 0 && errnum < sys_nerr)
113 return sys_errlist[errnum];
114 return (char *) "Unknown error";
115}
116#endif /* not WINDOWSNT */
117#endif /* ! HAVE_STRERROR */
118
b23b5a5b 119static void
873fbd0b 120lose_syserr (const char *msg)
d99fabf0 121{
a5d107f3 122 fprintf (stderr, "%s: %s\n", msg, strerror (errno));
65396510 123 exit (EXIT_FAILURE);
d99fabf0
CW
124}
125
b23b5a5b 126static char *
f57e2426 127get_user_id (void)
cd553ffb 128{
a5d107f3 129 struct passwd *buf = getpwuid (getuid ());
cd553ffb
CW
130 if (!buf)
131 {
0c6d656d
PE
132 long uid = getuid ();
133 char *name = malloc (sizeof uid * CHAR_BIT / 3 + 1);
134 if (name)
135 sprintf (name, "%ld", uid);
cd553ffb
CW
136 return name;
137 }
138 return buf->pw_name;
139}
140
b23b5a5b 141static const char *
988e88ab 142get_prefix (int running_suid, const char *user_prefix)
8eec804f 143{
d99fabf0 144 if (!running_suid && user_prefix == NULL)
a5d107f3 145 lose ("Not using a shared game directory, and no prefix given.");
d99fabf0
CW
146 if (running_suid)
147 {
148#ifdef HAVE_SHARED_GAME_DIR
149 return HAVE_SHARED_GAME_DIR;
150#else
a5d107f3 151 lose ("This program was compiled without HAVE_SHARED_GAME_DIR,\n and should not be suid.");
d99fabf0
CW
152#endif
153 }
154 return user_prefix;
8eec804f
CW
155}
156
2f1de3dd 157int
873fbd0b 158main (int argc, char **argv)
2f1de3dd 159{
d99fabf0 160 int c, running_suid;
2f1de3dd 161 void *lockstate;
988e88ab
J
162 char *user_id, *scorefile;
163 const char *prefix, *user_prefix = NULL;
2f1de3dd
CW
164 struct stat buf;
165 struct score_entry *scores;
8eec804f 166 int newscore, scorecount, reverse = 0, max = MAX_SCORES;
2f1de3dd
CW
167 char *newdata;
168
a5d107f3 169 srand (time (0));
2f1de3dd 170
a5d107f3 171 while ((c = getopt (argc, argv, "hrm:d:")) != -1)
2f1de3dd
CW
172 switch (c)
173 {
174 case 'h':
65396510 175 usage (EXIT_SUCCESS);
2f1de3dd 176 break;
d99fabf0
CW
177 case 'd':
178 user_prefix = optarg;
179 break;
2f1de3dd
CW
180 case 'r':
181 reverse = 1;
182 break;
183 case 'm':
a5d107f3 184 max = atoi (optarg);
8eec804f
CW
185 if (max > MAX_SCORES)
186 max = MAX_SCORES;
2f1de3dd
CW
187 break;
188 default:
65396510 189 usage (EXIT_FAILURE);
2f1de3dd
CW
190 }
191
192 if (optind+3 != argc)
65396510 193 usage (EXIT_FAILURE);
5795b420 194
a5d107f3 195 running_suid = (getuid () != geteuid ());
5795b420 196
a5d107f3 197 prefix = get_prefix (running_suid, user_prefix);
8eec804f 198
a5d107f3 199 scorefile = malloc (strlen (prefix) + strlen (argv[optind]) + 2);
2f1de3dd 200 if (!scorefile)
a5d107f3 201 lose_syserr ("Couldn't allocate score file");
8eec804f 202
a5d107f3
RS
203 strcpy (scorefile, prefix);
204 strcat (scorefile, "/");
205 strcat (scorefile, argv[optind]);
206 newscore = atoi (argv[optind+1]);
2f1de3dd 207 newdata = argv[optind+2];
a5d107f3 208 if (strlen (newdata) > MAX_DATA_LEN)
8eec804f 209 newdata[MAX_DATA_LEN] = '\0';
d99fabf0 210
00a7e408
RS
211 user_id = get_user_id ();
212 if (user_id == NULL)
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
a5d107f3 221 if (read_scores (scorefile, &scores, &scorecount) < 0)
2f1de3dd 222 {
a5d107f3
RS
223 unlock_file (scorefile, lockstate);
224 lose_syserr ("Failed to read scores file");
2f1de3dd 225 }
a5d107f3 226 push_score (&scores, &scorecount, newscore, user_id, newdata);
24e9e996 227 sort_scores (scores, scorecount, reverse);
8eec804f 228 /* Limit the number of scores. If we're using reverse sorting, then
f0d80d43
PE
229 also increment the beginning of the array, to skip over the
230 *smallest* scores. Otherwise, just decrementing the number of
231 scores suffices, since the smallest is at the end. */
8eec804f 232 if (scorecount > MAX_SCORES)
f0d80d43
PE
233 {
234 if (reverse)
235 scores += (scorecount - MAX_SCORES);
236 scorecount = MAX_SCORES;
237 }
a5d107f3 238 if (write_scores (scorefile, scores, scorecount) < 0)
2f1de3dd 239 {
a5d107f3
RS
240 unlock_file (scorefile, lockstate);
241 lose_syserr ("Failed to write scores file");
2f1de3dd 242 }
a5d107f3 243 unlock_file (scorefile, lockstate);
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;
a5d107f3 251 if (feof (f))
2f1de3dd 252 return 1;
a5d107f3
RS
253 while ((c = getc (f)) != EOF
254 && isdigit (c))
cd553ffb
CW
255 {
256 score->score *= 10;
257 score->score += (c-48);
258 }
a5d107f3
RS
259 while ((c = getc (f)) != EOF
260 && isspace (c))
cd553ffb
CW
261 ;
262 if (c == EOF)
263 return -1;
a5d107f3 264 ungetc (c, f);
cd553ffb
CW
265#ifdef HAVE_GETDELIM
266 {
7605f1bd 267 size_t count = 0;
a5d107f3 268 if (getdelim (&score->username, &count, ' ', f) < 1
cd553ffb
CW
269 || score->username == NULL)
270 return -1;
1d4328ff 271 /* Trim the space */
a5d107f3 272 score->username[strlen (score->username)-1] = '\0';
2f1de3dd 273 }
cd553ffb
CW
274#else
275 {
276 int unameread = 0;
277 int unamelen = 30;
a5d107f3 278 char *username = malloc (unamelen);
f5bceaf8
CW
279 if (!username)
280 return -1;
177c0ea7 281
a5d107f3
RS
282 while ((c = getc (f)) != EOF
283 && !isspace (c))
cd553ffb 284 {
8eec804f 285 if (unameread >= unamelen-1)
a5d107f3 286 if (!(username = realloc (username, unamelen *= 2)))
8eec804f 287 return -1;
cd553ffb
CW
288 username[unameread] = c;
289 unameread++;
290 }
177c0ea7 291 if (c == EOF)
f5bceaf8
CW
292 return -1;
293 username[unameread] = '\0';
cd553ffb
CW
294 score->username = username;
295 }
296#endif
2f1de3dd
CW
297#ifdef HAVE_GETLINE
298 score->data = NULL;
7605f1bd 299 errno = 0;
2f1de3dd 300 {
7605f1bd 301 size_t len;
a5d107f3 302 if (getline (&score->data, &len, f) < 0)
2f1de3dd 303 return -1;
a5d107f3 304 score->data[strlen (score->data)-1] = '\0';
2f1de3dd
CW
305 }
306#else
cd553ffb
CW
307 {
308 int cur = 0;
309 int len = 16;
a5d107f3 310 char *buf = malloc (len);
cd553ffb
CW
311 if (!buf)
312 return -1;
a5d107f3 313 while ((c = getc (f)) != EOF
f5bceaf8 314 && c != '\n')
cd553ffb
CW
315 {
316 if (cur >= len-1)
317 {
a5d107f3 318 if (!(buf = realloc (buf, len *= 2)))
cd553ffb
CW
319 return -1;
320 }
321 buf[cur] = c;
322 cur++;
323 }
324 score->data = buf;
5795b420 325 score->data[cur] = '\0';
cd553ffb 326 }
2f1de3dd 327#endif
2f1de3dd
CW
328 return 0;
329}
330
b23b5a5b 331static int
873fbd0b 332read_scores (const char *filename, struct score_entry **scores, int *count)
2f1de3dd
CW
333{
334 int readval, scorecount, cursize;
335 struct score_entry *ret;
a5d107f3 336 FILE *f = fopen (filename, "r");
177c0ea7 337 if (!f)
2f1de3dd
CW
338 return -1;
339 scorecount = 0;
340 cursize = 16;
00a7e408 341 ret = (struct score_entry *) malloc (sizeof (struct score_entry) * cursize);
177c0ea7 342 if (!ret)
2f1de3dd 343 return -1;
a5d107f3 344 while ((readval = read_score (f, &ret[scorecount])) == 0)
2f1de3dd 345 {
4c36be58 346 /* We encountered an error. */
2f1de3dd
CW
347 if (readval < 0)
348 return -1;
349 scorecount++;
350 if (scorecount >= cursize)
351 {
ee435bae
JB
352 cursize *= 2;
353 ret = (struct score_entry *)
354 realloc (ret, (sizeof (struct score_entry) * cursize));
2f1de3dd
CW
355 if (!ret)
356 return -1;
357 }
358 }
359 *count = scorecount;
360 *scores = ret;
361 return 0;
362}
363
b23b5a5b 364static int
873fbd0b 365score_compare (const void *a, const void *b)
2f1de3dd
CW
366{
367 const struct score_entry *sa = (const struct score_entry *) a;
368 const struct score_entry *sb = (const struct score_entry *) b;
369 return (sb->score > sa->score) - (sb->score < sa->score);
370}
371
b23b5a5b 372static int
873fbd0b 373score_compare_reverse (const void *a, const void *b)
2f1de3dd
CW
374{
375 const struct score_entry *sa = (const struct score_entry *) a;
376 const struct score_entry *sb = (const struct score_entry *) b;
377 return (sa->score > sb->score) - (sa->score < sb->score);
378}
379
380int
873fbd0b 381push_score (struct score_entry **scores, int *count, int newscore, char *username, char *newdata)
2f1de3dd 382{
a5d107f3 383 struct score_entry *newscores
00a7e408
RS
384 = (struct score_entry *) realloc (*scores,
385 sizeof (struct score_entry) * ((*count) + 1));
2f1de3dd
CW
386 if (!newscores)
387 return -1;
388 newscores[*count].score = newscore;
cd553ffb 389 newscores[*count].username = username;
2f1de3dd
CW
390 newscores[*count].data = newdata;
391 (*count) += 1;
392 *scores = newscores;
393 return 0;
394}
177c0ea7 395
b23b5a5b 396static void
873fbd0b 397sort_scores (struct score_entry *scores, int count, int reverse)
2f1de3dd 398{
a5d107f3 399 qsort (scores, count, sizeof (struct score_entry),
2f1de3dd
CW
400 reverse ? score_compare_reverse : score_compare);
401}
402
b23b5a5b 403static int
873fbd0b 404write_scores (const char *filename, const struct score_entry *scores, int count)
2f1de3dd 405{
177c0ea7 406 FILE *f;
2f1de3dd 407 int i;
a5d107f3 408 char *tempfile = malloc (strlen (filename) + strlen (".tempXXXXXX") + 1);
2f1de3dd
CW
409 if (!tempfile)
410 return -1;
a5d107f3
RS
411 strcpy (tempfile, filename);
412 strcat (tempfile, ".tempXXXXXX");
8eec804f 413#ifdef HAVE_MKSTEMP
a5d107f3 414 if (mkstemp (tempfile) < 0
8eec804f 415#else
a5d107f3 416 if (mktemp (tempfile) != tempfile
8eec804f 417#endif
a5d107f3 418 || !(f = fopen (tempfile, "w")))
2f1de3dd
CW
419 return -1;
420 for (i = 0; i < count; i++)
a5d107f3 421 if (fprintf (f, "%ld %s %s\n", scores[i].score, scores[i].username,
cd553ffb 422 scores[i].data) < 0)
2f1de3dd 423 return -1;
a5d107f3
RS
424 fclose (f);
425 if (rename (tempfile, filename) < 0)
2f1de3dd 426 return -1;
a5d107f3 427 if (chmod (filename, 0644) < 0)
2f1de3dd 428 return -1;
8eec804f 429 return 0;
2f1de3dd 430}
177c0ea7 431
b23b5a5b 432static int
873fbd0b 433lock_file (const char *filename, void **state)
2f1de3dd
CW
434{
435 int fd;
7c4f6873 436 struct stat buf;
2f1de3dd 437 int attempts = 0;
988e88ab 438 const char *lockext = ".lockfile";
a5d107f3 439 char *lockpath = malloc (strlen (filename) + strlen (lockext) + 60);
2f1de3dd
CW
440 if (!lockpath)
441 return -1;
a5d107f3
RS
442 strcpy (lockpath, filename);
443 strcat (lockpath, lockext);
2f1de3dd
CW
444 *state = lockpath;
445 trylock:
446 attempts++;
7c4f6873 447 /* If the lock is over an hour old, delete it. */
a5d107f3
RS
448 if (stat (lockpath, &buf) == 0
449 && (difftime (buf.st_ctime, time (NULL) > 60*60)))
450 unlink (lockpath);
00a7e408
RS
451 fd = open (lockpath, O_CREAT | O_EXCL, 0600);
452 if (fd < 0)
2f1de3dd
CW
453 {
454 if (errno == EEXIST)
455 {
456 /* Break the lock; we won't corrupt the file, but we might
457 lose some scores. */
458 if (attempts > MAX_ATTEMPTS)
7c4f6873 459 {
a5d107f3 460 unlink (lockpath);
7c4f6873
CW
461 attempts = 0;
462 }
a5d107f3 463 sleep ((rand () % 2)+1);
2f1de3dd
CW
464 goto trylock;
465 }
466 else
467 return -1;
468 }
a5d107f3 469 close (fd);
2f1de3dd
CW
470 return 0;
471}
177c0ea7 472
b23b5a5b 473static int
873fbd0b 474unlock_file (const char *filename, void *state)
2f1de3dd
CW
475{
476 char *lockpath = (char *) state;
a5d107f3 477 int ret = unlink (lockpath);
2f1de3dd 478 int saved_errno = errno;
a5d107f3 479 free (lockpath);
2f1de3dd
CW
480 errno = saved_errno;
481 return ret;
482}
ab5796a9 483
65396510
TTN
484
485/* update-game-score.c ends here */