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