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