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