Simplify by avoiding confusing use of strncpy etc.
[emacs.git] / lib-src / update-game-score.c
blob94de662e58902e3b5ece7e3b0ac6a9a7c5d785c5
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 /* Taken from sysdep.c. */
98 #ifndef HAVE_STRERROR
99 #ifndef WINDOWSNT
100 char *
101 strerror (int errnum)
103 extern char *sys_errlist[];
104 extern int sys_nerr;
106 if (errnum >= 0 && errnum < sys_nerr)
107 return sys_errlist[errnum];
108 return (char *) "Unknown error";
110 #endif /* not WINDOWSNT */
111 #endif /* ! HAVE_STRERROR */
113 static _Noreturn void
114 lose_syserr (const char *msg)
116 fprintf (stderr, "%s: %s\n", msg, strerror (errno));
117 exit (EXIT_FAILURE);
120 static char *
121 get_user_id (void)
123 struct passwd *buf = getpwuid (getuid ());
124 if (!buf)
126 long uid = getuid ();
127 char *name = malloc (sizeof uid * CHAR_BIT / 3 + 1);
128 if (name)
129 sprintf (name, "%ld", uid);
130 return name;
132 return buf->pw_name;
135 static const char *
136 get_prefix (int running_suid, const char *user_prefix)
138 if (!running_suid && user_prefix == NULL)
139 lose ("Not using a shared game directory, and no prefix given.");
140 if (running_suid)
142 #ifdef HAVE_SHARED_GAME_DIR
143 return HAVE_SHARED_GAME_DIR;
144 #else
145 lose ("This program was compiled without HAVE_SHARED_GAME_DIR,\n and should not be suid.");
146 #endif
148 return user_prefix;
152 main (int argc, char **argv)
154 int c, running_suid;
155 void *lockstate;
156 char *user_id, *scorefile;
157 const char *prefix, *user_prefix = NULL;
158 struct stat buf;
159 struct score_entry *scores;
160 int newscore, scorecount, reverse = 0, max = MAX_SCORES;
161 char *newdata;
163 srand (time (0));
165 while ((c = getopt (argc, argv, "hrm:d:")) != -1)
166 switch (c)
168 case 'h':
169 usage (EXIT_SUCCESS);
170 break;
171 case 'd':
172 user_prefix = optarg;
173 break;
174 case 'r':
175 reverse = 1;
176 break;
177 case 'm':
178 max = atoi (optarg);
179 if (max > MAX_SCORES)
180 max = MAX_SCORES;
181 break;
182 default:
183 usage (EXIT_FAILURE);
186 if (optind+3 != argc)
187 usage (EXIT_FAILURE);
189 running_suid = (getuid () != geteuid ());
191 prefix = get_prefix (running_suid, user_prefix);
193 scorefile = malloc (strlen (prefix) + strlen (argv[optind]) + 2);
194 if (!scorefile)
195 lose_syserr ("Couldn't allocate score file");
197 strcpy (scorefile, prefix);
198 strcat (scorefile, "/");
199 strcat (scorefile, argv[optind]);
200 newscore = atoi (argv[optind+1]);
201 newdata = argv[optind+2];
202 if (strlen (newdata) > MAX_DATA_LEN)
203 newdata[MAX_DATA_LEN] = '\0';
205 user_id = get_user_id ();
206 if (user_id == NULL)
207 lose_syserr ("Couldn't determine user id");
209 if (stat (scorefile, &buf) < 0)
210 lose_syserr ("Failed to access scores file");
212 if (lock_file (scorefile, &lockstate) < 0)
213 lose_syserr ("Failed to lock scores file");
215 if (read_scores (scorefile, &scores, &scorecount) < 0)
217 unlock_file (scorefile, lockstate);
218 lose_syserr ("Failed to read scores file");
220 push_score (&scores, &scorecount, newscore, user_id, newdata);
221 sort_scores (scores, scorecount, reverse);
222 /* Limit the number of scores. If we're using reverse sorting, then
223 also increment the beginning of the array, to skip over the
224 *smallest* scores. Otherwise, just decrementing the number of
225 scores suffices, since the smallest is at the end. */
226 if (scorecount > MAX_SCORES)
228 if (reverse)
229 scores += (scorecount - MAX_SCORES);
230 scorecount = MAX_SCORES;
232 if (write_scores (scorefile, scores, scorecount) < 0)
234 unlock_file (scorefile, lockstate);
235 lose_syserr ("Failed to write scores file");
237 unlock_file (scorefile, lockstate);
238 exit (EXIT_SUCCESS);
241 static int
242 read_score (FILE *f, struct score_entry *score)
244 int c;
245 if (feof (f))
246 return 1;
247 while ((c = getc (f)) != EOF
248 && isdigit (c))
250 score->score *= 10;
251 score->score += (c-48);
253 while ((c = getc (f)) != EOF
254 && isspace (c))
256 if (c == EOF)
257 return -1;
258 ungetc (c, f);
259 #ifdef HAVE_GETDELIM
261 size_t count = 0;
262 if (getdelim (&score->username, &count, ' ', f) < 1
263 || score->username == NULL)
264 return -1;
265 /* Trim the space */
266 score->username[strlen (score->username)-1] = '\0';
268 #else
270 int unameread = 0;
271 int unamelen = 30;
272 char *username = malloc (unamelen);
273 if (!username)
274 return -1;
276 while ((c = getc (f)) != EOF
277 && !isspace (c))
279 if (unameread >= unamelen-1)
280 if (!(username = realloc (username, unamelen *= 2)))
281 return -1;
282 username[unameread] = c;
283 unameread++;
285 if (c == EOF)
286 return -1;
287 username[unameread] = '\0';
288 score->username = username;
290 #endif
291 #ifdef HAVE_GETLINE
292 score->data = NULL;
293 errno = 0;
295 size_t len;
296 if (getline (&score->data, &len, f) < 0)
297 return -1;
298 score->data[strlen (score->data)-1] = '\0';
300 #else
302 int cur = 0;
303 int len = 16;
304 char *buf = malloc (len);
305 if (!buf)
306 return -1;
307 while ((c = getc (f)) != EOF
308 && c != '\n')
310 if (cur >= len-1)
312 if (!(buf = realloc (buf, len *= 2)))
313 return -1;
315 buf[cur] = c;
316 cur++;
318 score->data = buf;
319 score->data[cur] = '\0';
321 #endif
322 return 0;
325 static int
326 read_scores (const char *filename, struct score_entry **scores, int *count)
328 int readval, scorecount, cursize;
329 struct score_entry *ret;
330 FILE *f = fopen (filename, "r");
331 if (!f)
332 return -1;
333 scorecount = 0;
334 cursize = 16;
335 ret = (struct score_entry *) malloc (sizeof (struct score_entry) * cursize);
336 if (!ret)
337 return -1;
338 while ((readval = read_score (f, &ret[scorecount])) == 0)
340 /* We encountered an error. */
341 if (readval < 0)
342 return -1;
343 scorecount++;
344 if (scorecount >= cursize)
346 cursize *= 2;
347 ret = (struct score_entry *)
348 realloc (ret, (sizeof (struct score_entry) * cursize));
349 if (!ret)
350 return -1;
353 *count = scorecount;
354 *scores = ret;
355 return 0;
358 static int
359 score_compare (const void *a, const void *b)
361 const struct score_entry *sa = (const struct score_entry *) a;
362 const struct score_entry *sb = (const struct score_entry *) b;
363 return (sb->score > sa->score) - (sb->score < sa->score);
366 static int
367 score_compare_reverse (const void *a, const void *b)
369 const struct score_entry *sa = (const struct score_entry *) a;
370 const struct score_entry *sb = (const struct score_entry *) b;
371 return (sa->score > sb->score) - (sa->score < sb->score);
375 push_score (struct score_entry **scores, int *count, int newscore, char *username, char *newdata)
377 struct score_entry *newscores
378 = (struct score_entry *) realloc (*scores,
379 sizeof (struct score_entry) * ((*count) + 1));
380 if (!newscores)
381 return -1;
382 newscores[*count].score = newscore;
383 newscores[*count].username = username;
384 newscores[*count].data = newdata;
385 (*count) += 1;
386 *scores = newscores;
387 return 0;
390 static void
391 sort_scores (struct score_entry *scores, int count, int reverse)
393 qsort (scores, count, sizeof (struct score_entry),
394 reverse ? score_compare_reverse : score_compare);
397 static int
398 write_scores (const char *filename, const struct score_entry *scores, int count)
400 FILE *f;
401 int i;
402 char *tempfile = malloc (strlen (filename) + strlen (".tempXXXXXX") + 1);
403 if (!tempfile)
404 return -1;
405 strcpy (tempfile, filename);
406 strcat (tempfile, ".tempXXXXXX");
407 #ifdef HAVE_MKSTEMP
408 if (mkstemp (tempfile) < 0
409 #else
410 if (mktemp (tempfile) != tempfile
411 #endif
412 || !(f = fopen (tempfile, "w")))
413 return -1;
414 for (i = 0; i < count; i++)
415 if (fprintf (f, "%ld %s %s\n", scores[i].score, scores[i].username,
416 scores[i].data) < 0)
417 return -1;
418 fclose (f);
419 if (rename (tempfile, filename) < 0)
420 return -1;
421 if (chmod (filename, 0644) < 0)
422 return -1;
423 return 0;
426 static int
427 lock_file (const char *filename, void **state)
429 int fd;
430 struct stat buf;
431 int attempts = 0;
432 const char *lockext = ".lockfile";
433 char *lockpath = malloc (strlen (filename) + strlen (lockext) + 60);
434 if (!lockpath)
435 return -1;
436 strcpy (lockpath, filename);
437 strcat (lockpath, lockext);
438 *state = lockpath;
439 trylock:
440 attempts++;
441 /* If the lock is over an hour old, delete it. */
442 if (stat (lockpath, &buf) == 0
443 && (difftime (buf.st_ctime, time (NULL) > 60*60)))
444 unlink (lockpath);
445 fd = open (lockpath, O_CREAT | O_EXCL, 0600);
446 if (fd < 0)
448 if (errno == EEXIST)
450 /* Break the lock; we won't corrupt the file, but we might
451 lose some scores. */
452 if (attempts > MAX_ATTEMPTS)
454 unlink (lockpath);
455 attempts = 0;
457 sleep ((rand () % 2)+1);
458 goto trylock;
460 else
461 return -1;
463 close (fd);
464 return 0;
467 static int
468 unlock_file (const char *filename, void *state)
470 char *lockpath = (char *) state;
471 int ret = unlink (lockpath);
472 int saved_errno = errno;
473 free (lockpath);
474 errno = saved_errno;
475 return ret;
479 /* update-game-score.c ends here */