Merge from trunk.
[bpt/emacs.git] / lib-src / update-game-score.c
1 /* update-game-score.c --- Update a score file
2
3 Copyright (C) 2002-2011 Free Software Foundation, Inc.
4
5 Author: Colin Walters <walters@debian.org>
6
7 This file is part of GNU Emacs.
8
9 GNU Emacs is free software: you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation, either version 3 of the License, or
12 (at your option) any later version.
13
14 GNU Emacs is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 GNU General Public License for more details.
18
19 You should have received a copy of the GNU General Public License
20 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
21
22
23 /* This program allows a game to securely and atomically update a
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).
30
31 Created 2002/03/22.
32 */
33
34 #include <config.h>
35
36 #include <unistd.h>
37 #include <errno.h>
38 #include <string.h>
39 #include <stdlib.h>
40 #include <stdio.h>
41 #include <time.h>
42 #include <pwd.h>
43 #include <ctype.h>
44 #ifdef HAVE_FCNTL_H
45 #include <fcntl.h>
46 #endif
47 #include <sys/stat.h>
48
49 /* Needed for SunOS4, for instance. */
50 extern char *optarg;
51 extern int optind, opterr;
52
53 static int usage (int err) NO_RETURN;
54
55 #define MAX_ATTEMPTS 5
56 #define MAX_SCORES 200
57 #define MAX_DATA_LEN 1024
58
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
64 static int
65 usage (int err)
66 {
67 fprintf (stdout, "Usage: update-game-score [-m MAX] [-r] [-d DIR] game/scorefile SCORE DATA\n");
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);
74 }
75
76 static int lock_file (const char *filename, void **state);
77 static int unlock_file (const char *filename, void *state);
78
79 struct score_entry
80 {
81 long score;
82 char *username;
83 char *data;
84 };
85
86 static int read_scores (const char *filename, struct score_entry **scores,
87 int *count);
88 static int push_score (struct score_entry **scores, int *count,
89 int newscore, char *username, char *newdata);
90 static void sort_scores (struct score_entry *scores, int count, int reverse);
91 static int write_scores (const char *filename,
92 const struct score_entry *scores, int count);
93
94 static void lose (const char *msg) NO_RETURN;
95
96 static void
97 lose (const char *msg)
98 {
99 fprintf (stderr, "%s\n", msg);
100 exit (EXIT_FAILURE);
101 }
102
103 static void lose_syserr (const char *msg) NO_RETURN;
104
105 /* Taken from sysdep.c. */
106 #ifndef HAVE_STRERROR
107 #ifndef WINDOWSNT
108 char *
109 strerror (int errnum)
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
121 static void
122 lose_syserr (const char *msg)
123 {
124 fprintf (stderr, "%s: %s\n", msg, strerror (errno));
125 exit (EXIT_FAILURE);
126 }
127
128 static char *
129 get_user_id (void)
130 {
131 char *name;
132 struct passwd *buf = getpwuid (getuid ());
133 if (!buf)
134 {
135 int count = 1;
136 int uid = (int) getuid ();
137 int tuid = uid;
138 while (tuid /= 10)
139 count++;
140 name = malloc (count+1);
141 if (!name)
142 return NULL;
143 sprintf (name, "%d", uid);
144 return name;
145 }
146 return buf->pw_name;
147 }
148
149 static const char *
150 get_prefix (int running_suid, const char *user_prefix)
151 {
152 if (!running_suid && user_prefix == NULL)
153 lose ("Not using a shared game directory, and no prefix given.");
154 if (running_suid)
155 {
156 #ifdef HAVE_SHARED_GAME_DIR
157 return HAVE_SHARED_GAME_DIR;
158 #else
159 lose ("This program was compiled without HAVE_SHARED_GAME_DIR,\n and should not be suid.");
160 #endif
161 }
162 return user_prefix;
163 }
164
165 int
166 main (int argc, char **argv)
167 {
168 int c, running_suid;
169 void *lockstate;
170 char *user_id, *scorefile;
171 const char *prefix, *user_prefix = NULL;
172 struct stat buf;
173 struct score_entry *scores;
174 int newscore, scorecount, reverse = 0, max = MAX_SCORES;
175 char *newdata;
176
177 srand (time (0));
178
179 while ((c = getopt (argc, argv, "hrm:d:")) != -1)
180 switch (c)
181 {
182 case 'h':
183 usage (EXIT_SUCCESS);
184 break;
185 case 'd':
186 user_prefix = optarg;
187 break;
188 case 'r':
189 reverse = 1;
190 break;
191 case 'm':
192 max = atoi (optarg);
193 if (max > MAX_SCORES)
194 max = MAX_SCORES;
195 break;
196 default:
197 usage (EXIT_FAILURE);
198 }
199
200 if (optind+3 != argc)
201 usage (EXIT_FAILURE);
202
203 running_suid = (getuid () != geteuid ());
204
205 prefix = get_prefix (running_suid, user_prefix);
206
207 scorefile = malloc (strlen (prefix) + strlen (argv[optind]) + 2);
208 if (!scorefile)
209 lose_syserr ("Couldn't allocate score file");
210
211 strcpy (scorefile, prefix);
212 strcat (scorefile, "/");
213 strcat (scorefile, argv[optind]);
214 newscore = atoi (argv[optind+1]);
215 newdata = argv[optind+2];
216 if (strlen (newdata) > MAX_DATA_LEN)
217 newdata[MAX_DATA_LEN] = '\0';
218
219 user_id = get_user_id ();
220 if (user_id == NULL)
221 lose_syserr ("Couldn't determine user id");
222
223 if (stat (scorefile, &buf) < 0)
224 lose_syserr ("Failed to access scores file");
225
226 if (lock_file (scorefile, &lockstate) < 0)
227 lose_syserr ("Failed to lock scores file");
228
229 if (read_scores (scorefile, &scores, &scorecount) < 0)
230 {
231 unlock_file (scorefile, lockstate);
232 lose_syserr ("Failed to read scores file");
233 }
234 push_score (&scores, &scorecount, newscore, user_id, newdata);
235 sort_scores (scores, scorecount, reverse);
236 /* Limit the number of scores. If we're using reverse sorting, then
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. */
240 if (scorecount > MAX_SCORES)
241 {
242 if (reverse)
243 scores += (scorecount - MAX_SCORES);
244 scorecount = MAX_SCORES;
245 }
246 if (write_scores (scorefile, scores, scorecount) < 0)
247 {
248 unlock_file (scorefile, lockstate);
249 lose_syserr ("Failed to write scores file");
250 }
251 unlock_file (scorefile, lockstate);
252 exit (EXIT_SUCCESS);
253 }
254
255 static int
256 read_score (FILE *f, struct score_entry *score)
257 {
258 int c;
259 if (feof (f))
260 return 1;
261 while ((c = getc (f)) != EOF
262 && isdigit (c))
263 {
264 score->score *= 10;
265 score->score += (c-48);
266 }
267 while ((c = getc (f)) != EOF
268 && isspace (c))
269 ;
270 if (c == EOF)
271 return -1;
272 ungetc (c, f);
273 #ifdef HAVE_GETDELIM
274 {
275 size_t count = 0;
276 if (getdelim (&score->username, &count, ' ', f) < 1
277 || score->username == NULL)
278 return -1;
279 /* Trim the space */
280 score->username[strlen (score->username)-1] = '\0';
281 }
282 #else
283 {
284 int unameread = 0;
285 int unamelen = 30;
286 char *username = malloc (unamelen);
287 if (!username)
288 return -1;
289
290 while ((c = getc (f)) != EOF
291 && !isspace (c))
292 {
293 if (unameread >= unamelen-1)
294 if (!(username = realloc (username, unamelen *= 2)))
295 return -1;
296 username[unameread] = c;
297 unameread++;
298 }
299 if (c == EOF)
300 return -1;
301 username[unameread] = '\0';
302 score->username = username;
303 }
304 #endif
305 #ifdef HAVE_GETLINE
306 score->data = NULL;
307 errno = 0;
308 {
309 size_t len;
310 if (getline (&score->data, &len, f) < 0)
311 return -1;
312 score->data[strlen (score->data)-1] = '\0';
313 }
314 #else
315 {
316 int cur = 0;
317 int len = 16;
318 char *buf = malloc (len);
319 if (!buf)
320 return -1;
321 while ((c = getc (f)) != EOF
322 && c != '\n')
323 {
324 if (cur >= len-1)
325 {
326 if (!(buf = realloc (buf, len *= 2)))
327 return -1;
328 }
329 buf[cur] = c;
330 cur++;
331 }
332 score->data = buf;
333 score->data[cur] = '\0';
334 }
335 #endif
336 return 0;
337 }
338
339 static int
340 read_scores (const char *filename, struct score_entry **scores, int *count)
341 {
342 int readval, scorecount, cursize;
343 struct score_entry *ret;
344 FILE *f = fopen (filename, "r");
345 if (!f)
346 return -1;
347 scorecount = 0;
348 cursize = 16;
349 ret = (struct score_entry *) malloc (sizeof (struct score_entry) * cursize);
350 if (!ret)
351 return -1;
352 while ((readval = read_score (f, &ret[scorecount])) == 0)
353 {
354 /* We encoutered an error */
355 if (readval < 0)
356 return -1;
357 scorecount++;
358 if (scorecount >= cursize)
359 {
360 cursize *= 2;
361 ret = (struct score_entry *)
362 realloc (ret, (sizeof (struct score_entry) * cursize));
363 if (!ret)
364 return -1;
365 }
366 }
367 *count = scorecount;
368 *scores = ret;
369 return 0;
370 }
371
372 static int
373 score_compare (const void *a, const void *b)
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
380 static int
381 score_compare_reverse (const void *a, const void *b)
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
388 int
389 push_score (struct score_entry **scores, int *count, int newscore, char *username, char *newdata)
390 {
391 struct score_entry *newscores
392 = (struct score_entry *) realloc (*scores,
393 sizeof (struct score_entry) * ((*count) + 1));
394 if (!newscores)
395 return -1;
396 newscores[*count].score = newscore;
397 newscores[*count].username = username;
398 newscores[*count].data = newdata;
399 (*count) += 1;
400 *scores = newscores;
401 return 0;
402 }
403
404 static void
405 sort_scores (struct score_entry *scores, int count, int reverse)
406 {
407 qsort (scores, count, sizeof (struct score_entry),
408 reverse ? score_compare_reverse : score_compare);
409 }
410
411 static int
412 write_scores (const char *filename, const struct score_entry *scores, int count)
413 {
414 FILE *f;
415 int i;
416 char *tempfile = malloc (strlen (filename) + strlen (".tempXXXXXX") + 1);
417 if (!tempfile)
418 return -1;
419 strcpy (tempfile, filename);
420 strcat (tempfile, ".tempXXXXXX");
421 #ifdef HAVE_MKSTEMP
422 if (mkstemp (tempfile) < 0
423 #else
424 if (mktemp (tempfile) != tempfile
425 #endif
426 || !(f = fopen (tempfile, "w")))
427 return -1;
428 for (i = 0; i < count; i++)
429 if (fprintf (f, "%ld %s %s\n", scores[i].score, scores[i].username,
430 scores[i].data) < 0)
431 return -1;
432 fclose (f);
433 if (rename (tempfile, filename) < 0)
434 return -1;
435 if (chmod (filename, 0644) < 0)
436 return -1;
437 return 0;
438 }
439
440 static int
441 lock_file (const char *filename, void **state)
442 {
443 int fd;
444 struct stat buf;
445 int attempts = 0;
446 const char *lockext = ".lockfile";
447 char *lockpath = malloc (strlen (filename) + strlen (lockext) + 60);
448 if (!lockpath)
449 return -1;
450 strcpy (lockpath, filename);
451 strcat (lockpath, lockext);
452 *state = lockpath;
453 trylock:
454 attempts++;
455 /* If the lock is over an hour old, delete it. */
456 if (stat (lockpath, &buf) == 0
457 && (difftime (buf.st_ctime, time (NULL) > 60*60)))
458 unlink (lockpath);
459 fd = open (lockpath, O_CREAT | O_EXCL, 0600);
460 if (fd < 0)
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)
467 {
468 unlink (lockpath);
469 attempts = 0;
470 }
471 sleep ((rand () % 2)+1);
472 goto trylock;
473 }
474 else
475 return -1;
476 }
477 close (fd);
478 return 0;
479 }
480
481 static int
482 unlock_file (const char *filename, void *state)
483 {
484 char *lockpath = (char *) state;
485 int ret = unlink (lockpath);
486 int saved_errno = errno;
487 free (lockpath);
488 errno = saved_errno;
489 return ret;
490 }
491
492
493 /* update-game-score.c ends here */