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