Fix pty handling on FreeBSD 8.0 (tiny change)
[emacs.git] / lib-src / update-game-score.c
blob40397536fad4f65b91e30690a54fb26850bcf193
1 /* update-game-score.c --- Update a score file
3 Copyright (C) 2002-2012 Free Software Foundation, Inc.
5 Author: Colin Walters <walters@debian.org>
7 This file is part of GNU Emacs.
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.
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.
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/>. */
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'.
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).
31 Created 2002/03/22.
34 #include <config.h>
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>
51 #define MAX_ATTEMPTS 5
52 #define MAX_SCORES 200
53 #define MAX_DATA_LEN 1024
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
60 static _Noreturn void
61 usage (int err)
63 fprintf (stdout, "Usage: update-game-score [-m MAX] [-r] [-d DIR] game/scorefile SCORE DATA\n");
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);
72 static int lock_file (const char *filename, void **state);
73 static int unlock_file (const char *filename, void *state);
75 struct score_entry
77 long score;
78 char *username;
79 char *data;
82 static int read_scores (const char *filename, struct score_entry **scores,
83 int *count);
84 static int push_score (struct score_entry **scores, int *count,
85 int newscore, char *username, char *newdata);
86 static void sort_scores (struct score_entry *scores, int count, int reverse);
87 static int write_scores (const char *filename,
88 const struct score_entry *scores, int count);
90 static _Noreturn void
91 lose (const char *msg)
93 fprintf (stderr, "%s\n", msg);
94 exit (EXIT_FAILURE);
97 static _Noreturn void
98 lose_syserr (const char *msg)
100 fprintf (stderr, "%s: %s\n", msg, strerror (errno));
101 exit (EXIT_FAILURE);
104 static char *
105 get_user_id (void)
107 struct passwd *buf = getpwuid (getuid ());
108 if (!buf)
110 long uid = getuid ();
111 char *name = malloc (sizeof uid * CHAR_BIT / 3 + 1);
112 if (name)
113 sprintf (name, "%ld", uid);
114 return name;
116 return buf->pw_name;
119 static const char *
120 get_prefix (int running_suid, const char *user_prefix)
122 if (!running_suid && user_prefix == NULL)
123 lose ("Not using a shared game directory, and no prefix given.");
124 if (running_suid)
126 #ifdef HAVE_SHARED_GAME_DIR
127 return HAVE_SHARED_GAME_DIR;
128 #else
129 lose ("This program was compiled without HAVE_SHARED_GAME_DIR,\n and should not be suid.");
130 #endif
132 return user_prefix;
136 main (int argc, char **argv)
138 int c, running_suid;
139 void *lockstate;
140 char *user_id, *scorefile;
141 const char *prefix, *user_prefix = NULL;
142 struct stat buf;
143 struct score_entry *scores;
144 int newscore, scorecount, reverse = 0, max = MAX_SCORES;
145 char *newdata;
147 srand (time (0));
149 while ((c = getopt (argc, argv, "hrm:d:")) != -1)
150 switch (c)
152 case 'h':
153 usage (EXIT_SUCCESS);
154 break;
155 case 'd':
156 user_prefix = optarg;
157 break;
158 case 'r':
159 reverse = 1;
160 break;
161 case 'm':
162 max = atoi (optarg);
163 if (max > MAX_SCORES)
164 max = MAX_SCORES;
165 break;
166 default:
167 usage (EXIT_FAILURE);
170 if (optind+3 != argc)
171 usage (EXIT_FAILURE);
173 running_suid = (getuid () != geteuid ());
175 prefix = get_prefix (running_suid, user_prefix);
177 scorefile = malloc (strlen (prefix) + strlen (argv[optind]) + 2);
178 if (!scorefile)
179 lose_syserr ("Couldn't allocate score file");
181 strcpy (scorefile, prefix);
182 strcat (scorefile, "/");
183 strcat (scorefile, argv[optind]);
184 newscore = atoi (argv[optind+1]);
185 newdata = argv[optind+2];
186 if (strlen (newdata) > MAX_DATA_LEN)
187 newdata[MAX_DATA_LEN] = '\0';
189 user_id = get_user_id ();
190 if (user_id == NULL)
191 lose_syserr ("Couldn't determine user id");
193 if (stat (scorefile, &buf) < 0)
194 lose_syserr ("Failed to access scores file");
196 if (lock_file (scorefile, &lockstate) < 0)
197 lose_syserr ("Failed to lock scores file");
199 if (read_scores (scorefile, &scores, &scorecount) < 0)
201 unlock_file (scorefile, lockstate);
202 lose_syserr ("Failed to read scores file");
204 push_score (&scores, &scorecount, newscore, user_id, newdata);
205 sort_scores (scores, scorecount, reverse);
206 /* Limit the number of scores. If we're using reverse sorting, then
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. */
210 if (scorecount > MAX_SCORES)
212 if (reverse)
213 scores += (scorecount - MAX_SCORES);
214 scorecount = MAX_SCORES;
216 if (write_scores (scorefile, scores, scorecount) < 0)
218 unlock_file (scorefile, lockstate);
219 lose_syserr ("Failed to write scores file");
221 unlock_file (scorefile, lockstate);
222 exit (EXIT_SUCCESS);
225 static int
226 read_score (FILE *f, struct score_entry *score)
228 int c;
229 if (feof (f))
230 return 1;
231 while ((c = getc (f)) != EOF
232 && isdigit (c))
234 score->score *= 10;
235 score->score += (c-48);
237 while ((c = getc (f)) != EOF
238 && isspace (c))
240 if (c == EOF)
241 return -1;
242 ungetc (c, f);
243 #ifdef HAVE_GETDELIM
245 size_t count = 0;
246 if (getdelim (&score->username, &count, ' ', f) < 1
247 || score->username == NULL)
248 return -1;
249 /* Trim the space */
250 score->username[strlen (score->username)-1] = '\0';
252 #else
254 int unameread = 0;
255 int unamelen = 30;
256 char *username = malloc (unamelen);
257 if (!username)
258 return -1;
260 while ((c = getc (f)) != EOF
261 && !isspace (c))
263 if (unameread >= unamelen-1)
264 if (!(username = realloc (username, unamelen *= 2)))
265 return -1;
266 username[unameread] = c;
267 unameread++;
269 if (c == EOF)
270 return -1;
271 username[unameread] = '\0';
272 score->username = username;
274 #endif
275 #ifdef HAVE_GETLINE
276 score->data = NULL;
277 errno = 0;
279 size_t len;
280 if (getline (&score->data, &len, f) < 0)
281 return -1;
282 score->data[strlen (score->data)-1] = '\0';
284 #else
286 int cur = 0;
287 int len = 16;
288 char *buf = malloc (len);
289 if (!buf)
290 return -1;
291 while ((c = getc (f)) != EOF
292 && c != '\n')
294 if (cur >= len-1)
296 if (!(buf = realloc (buf, len *= 2)))
297 return -1;
299 buf[cur] = c;
300 cur++;
302 score->data = buf;
303 score->data[cur] = '\0';
305 #endif
306 return 0;
309 static int
310 read_scores (const char *filename, struct score_entry **scores, int *count)
312 int readval, scorecount, cursize;
313 struct score_entry *ret;
314 FILE *f = fopen (filename, "r");
315 if (!f)
316 return -1;
317 scorecount = 0;
318 cursize = 16;
319 ret = (struct score_entry *) malloc (sizeof (struct score_entry) * cursize);
320 if (!ret)
321 return -1;
322 while ((readval = read_score (f, &ret[scorecount])) == 0)
324 /* We encountered an error. */
325 if (readval < 0)
326 return -1;
327 scorecount++;
328 if (scorecount >= cursize)
330 cursize *= 2;
331 ret = (struct score_entry *)
332 realloc (ret, (sizeof (struct score_entry) * cursize));
333 if (!ret)
334 return -1;
337 *count = scorecount;
338 *scores = ret;
339 return 0;
342 static int
343 score_compare (const void *a, const void *b)
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);
350 static int
351 score_compare_reverse (const void *a, const void *b)
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);
359 push_score (struct score_entry **scores, int *count, int newscore, char *username, char *newdata)
361 struct score_entry *newscores
362 = (struct score_entry *) realloc (*scores,
363 sizeof (struct score_entry) * ((*count) + 1));
364 if (!newscores)
365 return -1;
366 newscores[*count].score = newscore;
367 newscores[*count].username = username;
368 newscores[*count].data = newdata;
369 (*count) += 1;
370 *scores = newscores;
371 return 0;
374 static void
375 sort_scores (struct score_entry *scores, int count, int reverse)
377 qsort (scores, count, sizeof (struct score_entry),
378 reverse ? score_compare_reverse : score_compare);
381 static int
382 write_scores (const char *filename, const struct score_entry *scores, int count)
384 FILE *f;
385 int i;
386 char *tempfile = malloc (strlen (filename) + strlen (".tempXXXXXX") + 1);
387 if (!tempfile)
388 return -1;
389 strcpy (tempfile, filename);
390 strcat (tempfile, ".tempXXXXXX");
391 #ifdef HAVE_MKSTEMP
392 if (mkstemp (tempfile) < 0
393 #else
394 if (mktemp (tempfile) != tempfile
395 #endif
396 || !(f = fopen (tempfile, "w")))
397 return -1;
398 for (i = 0; i < count; i++)
399 if (fprintf (f, "%ld %s %s\n", scores[i].score, scores[i].username,
400 scores[i].data) < 0)
401 return -1;
402 fclose (f);
403 if (rename (tempfile, filename) < 0)
404 return -1;
405 if (chmod (filename, 0644) < 0)
406 return -1;
407 return 0;
410 static int
411 lock_file (const char *filename, void **state)
413 int fd;
414 struct stat buf;
415 int attempts = 0;
416 const char *lockext = ".lockfile";
417 char *lockpath = malloc (strlen (filename) + strlen (lockext) + 60);
418 if (!lockpath)
419 return -1;
420 strcpy (lockpath, filename);
421 strcat (lockpath, lockext);
422 *state = lockpath;
423 trylock:
424 attempts++;
425 /* If the lock is over an hour old, delete it. */
426 if (stat (lockpath, &buf) == 0
427 && (difftime (buf.st_ctime, time (NULL) > 60*60)))
428 unlink (lockpath);
429 fd = open (lockpath, O_CREAT | O_EXCL, 0600);
430 if (fd < 0)
432 if (errno == EEXIST)
434 /* Break the lock; we won't corrupt the file, but we might
435 lose some scores. */
436 if (attempts > MAX_ATTEMPTS)
438 unlink (lockpath);
439 attempts = 0;
441 sleep ((rand () % 2)+1);
442 goto trylock;
444 else
445 return -1;
447 close (fd);
448 return 0;
451 static int
452 unlock_file (const char *filename, void *state)
454 char *lockpath = (char *) state;
455 int ret = unlink (lockpath);
456 int saved_errno = errno;
457 free (lockpath);
458 errno = saved_errno;
459 return ret;
463 /* update-game-score.c ends here */