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