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