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