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