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