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