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