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