This source file includes following definitions.
- usage
- lose
- lose_syserr
- get_user_id
- get_prefix
- normalize_integer
- main
- read_score
- read_scores
- score_compare
- score_compare_reverse
- push_score
- sort_scores
- write_scores
- lock_file
- unlock_file
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34 #include <config.h>
35
36 #include <unistd.h>
37 #include <errno.h>
38 #include <inttypes.h>
39 #include <limits.h>
40 #include <string.h>
41 #include <stdlib.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 #include <unlocked-io.h>
50
51 #ifdef WINDOWSNT
52 #include "ntlib.h"
53 #endif
54
55 #ifndef min
56 # define min(a,b) ((a) < (b) ? (a) : (b))
57 #endif
58
59 #define MAX_ATTEMPTS 5
60 #define MAX_DATA_LEN 1024
61
62 static _Noreturn void
63 usage (int err)
64 {
65 fprintf (stdout, "Usage: update-game-score [-m MAX] [-r] [-d DIR] game/scorefile SCORE DATA\n");
66 fprintf (stdout, " update-game-score -h\n");
67 fprintf (stdout, " -h\t\tDisplay this help.\n");
68 fprintf (stdout, " -m MAX\t\tLimit the maximum number of scores to MAX.\n");
69 fprintf (stdout, " -r\t\tSort the scores in increasing order.\n");
70 fprintf (stdout, " -d DIR\t\tStore scores in DIR (only if not setuid).\n");
71 exit (err);
72 }
73
74 static int lock_file (const char *filename, void **state);
75 static int unlock_file (const char *filename, void *state);
76
77 struct score_entry
78 {
79 char *score;
80 char *user_data;
81 };
82
83 #define MAX_SCORES min (PTRDIFF_MAX, SIZE_MAX / sizeof (struct score_entry))
84
85 static int read_scores (const char *filename, struct score_entry **scores,
86 ptrdiff_t *count, ptrdiff_t *alloc);
87 static int push_score (struct score_entry **scores, ptrdiff_t *count,
88 ptrdiff_t *size, struct score_entry const *newscore);
89 static void sort_scores (struct score_entry *scores, ptrdiff_t count,
90 bool reverse);
91 static int write_scores (const char *filename, mode_t mode,
92 const struct score_entry *scores, ptrdiff_t count);
93
94 static _Noreturn void
95 lose (const char *msg)
96 {
97 fprintf (stderr, "%s\n", msg);
98 exit (EXIT_FAILURE);
99 }
100
101 static _Noreturn void
102 lose_syserr (const char *msg)
103 {
104 fprintf (stderr, "%s: %s\n", msg,
105 errno ? strerror (errno) : "Invalid data in score file");
106 exit (EXIT_FAILURE);
107 }
108
109 static char *
110 get_user_id (void)
111 {
112 struct passwd *buf = getpwuid (getuid ());
113 if (!buf || strchr (buf->pw_name, ' ') || strchr (buf->pw_name, '\n'))
114 {
115 intmax_t uid = getuid ();
116 char *name = malloc (sizeof uid * CHAR_BIT / 3 + 4);
117 if (name)
118 sprintf (name, "%"PRIdMAX, uid);
119 return name;
120 }
121 return buf->pw_name;
122 }
123
124 static const char *
125 get_prefix (bool privileged, const char *user_prefix)
126 {
127 if (privileged)
128 {
129 #ifdef HAVE_SHARED_GAME_DIR
130 return HAVE_SHARED_GAME_DIR;
131 #else
132 lose ("This program was compiled without HAVE_SHARED_GAME_DIR,\n"
133 "and should not run with elevated privileges.");
134 #endif
135 }
136 if (user_prefix == NULL)
137 lose ("Not using a shared game directory, and no prefix given.");
138 return user_prefix;
139 }
140
141 static char *
142 normalize_integer (char *num)
143 {
144 bool neg;
145 char *p;
146 while (*num != '\n' && isspace (*num))
147 num++;
148 neg = *num == '-';
149 num += neg || *num == '-';
150
151 if (*num == '0')
152 {
153 while (*++num == '0')
154 continue;
155 neg &= !!*num;
156 num -= !*num;
157 }
158
159 for (p = num; '0' <= *p && *p <= '9'; p++)
160 continue;
161
162 if (*p || p == num)
163 {
164 errno = 0;
165 return 0;
166 }
167
168 if (neg)
169 *--num = '-';
170 return num;
171 }
172
173 int
174 main (int argc, char **argv)
175 {
176 int c;
177 bool running_suid, running_sgid;
178 void *lockstate;
179 char *scorefile;
180 char *end, *nl, *user, *data;
181 const char *prefix, *user_prefix = NULL;
182 struct score_entry *scores;
183 struct score_entry newscore;
184 bool reverse = false;
185 ptrdiff_t scorecount, scorealloc;
186 ptrdiff_t max_scores = MAX_SCORES;
187
188 while ((c = getopt (argc, argv, "hrm:d:")) != -1)
189 switch (c)
190 {
191 case 'h':
192 usage (EXIT_SUCCESS);
193 break;
194 case 'd':
195 user_prefix = optarg;
196 break;
197 case 'r':
198 reverse = 1;
199 break;
200 case 'm':
201 {
202 intmax_t m = strtoimax (optarg, &end, 10);
203 if (optarg == end || *end || m < 0)
204 usage (EXIT_FAILURE);
205 max_scores = min (m, MAX_SCORES);
206 }
207 break;
208 default:
209 usage (EXIT_FAILURE);
210 }
211
212 if (argc - optind != 3)
213 usage (EXIT_FAILURE);
214
215 running_suid = (getuid () != geteuid ());
216 running_sgid = (getgid () != getegid ());
217 if (running_suid && running_sgid)
218 lose ("This program can run either suid or sgid, but not both.");
219
220 prefix = get_prefix (running_suid || running_sgid, 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 char *z = stpcpy (scorefile, prefix);
227 *z++ = '/';
228 strcpy (z, argv[optind]);
229
230 newscore.score = normalize_integer (argv[optind + 1]);
231 if (! newscore.score)
232 {
233 fprintf (stderr, "%s: Invalid score\n", argv[optind + 1]);
234 return EXIT_FAILURE;
235 }
236
237 user = get_user_id ();
238 if (! user)
239 lose_syserr ("Couldn't determine user id");
240 data = argv[optind + 2];
241 if (strnlen (data, MAX_DATA_LEN + 1) == MAX_DATA_LEN + 1)
242 data[MAX_DATA_LEN] = '\0';
243 nl = strchr (data, '\n');
244 if (nl)
245 *nl = '\0';
246 newscore.user_data = malloc (strlen (user) + 1 + strlen (data) + 1);
247 if (! newscore.user_data
248 || sprintf (newscore.user_data, "%s %s", user, data) < 0)
249 lose_syserr ("Memory exhausted");
250
251 if (lock_file (scorefile, &lockstate) < 0)
252 lose_syserr ("Failed to lock scores file");
253
254 if (read_scores (scorefile, &scores, &scorecount, &scorealloc) < 0)
255 {
256 unlock_file (scorefile, lockstate);
257 lose_syserr ("Failed to read scores file");
258 }
259 if (push_score (&scores, &scorecount, &scorealloc, &newscore) < 0)
260 {
261 unlock_file (scorefile, lockstate);
262 lose_syserr ("Failed to add score");
263 }
264 sort_scores (scores, scorecount, reverse);
265
266
267
268
269 if (scorecount > max_scores)
270 {
271 if (reverse)
272 scores += scorecount - max_scores;
273 scorecount = max_scores;
274 }
275 if (write_scores (scorefile, running_sgid ? 0664 : 0644,
276 scores, scorecount) < 0)
277 {
278 unlock_file (scorefile, lockstate);
279 lose_syserr ("Failed to write scores file");
280 }
281 if (unlock_file (scorefile, lockstate) < 0)
282 lose_syserr ("Failed to unlock scores file");
283 exit (EXIT_SUCCESS);
284 }
285
286 static char *
287 read_score (char *p, struct score_entry *score)
288 {
289 score->score = p;
290 p = strchr (p, ' ');
291 if (!p)
292 return p;
293 *p++ = 0;
294 score->user_data = p;
295 p = strchr (p, '\n');
296 if (!p)
297 return p;
298 *p++ = 0;
299 return p;
300 }
301
302 static int
303 read_scores (const char *filename, struct score_entry **scores,
304 ptrdiff_t *count, ptrdiff_t *alloc)
305 {
306 char *p, *filedata;
307 ptrdiff_t filesize, nread;
308 struct stat st;
309 FILE *f = fopen (filename, "r");
310 if (!f)
311 return -1;
312 if (fstat (fileno (f), &st) != 0)
313 return -1;
314 if (! (0 <= st.st_size && st.st_size < min (PTRDIFF_MAX, SIZE_MAX)))
315 {
316 errno = EOVERFLOW;
317 return -1;
318 }
319 filesize = st.st_size;
320 filedata = malloc (filesize + 1);
321 if (! filedata)
322 return -1;
323 nread = fread (filedata, 1, filesize + 1, f);
324 if (filesize < nread)
325 {
326 errno = 0;
327 return -1;
328 }
329 if (nread < filesize)
330 filesize = nread;
331 if (ferror (f) || fclose (f) != 0)
332 return -1;
333 filedata[filesize] = 0;
334 if (strlen (filedata) != filesize)
335 {
336 errno = 0;
337 return -1;
338 }
339
340 *scores = 0;
341 *count = *alloc = 0;
342 for (p = filedata; p < filedata + filesize; )
343 {
344 struct score_entry entry;
345 p = read_score (p, &entry);
346 if (!p)
347 {
348 errno = 0;
349 return -1;
350 }
351 if (push_score (scores, count, alloc, &entry) < 0)
352 return -1;
353 }
354 return 0;
355 }
356
357 static int
358 score_compare (const void *a, const void *b)
359 {
360 const struct score_entry *sa = (const struct score_entry *) a;
361 const struct score_entry *sb = (const struct score_entry *) b;
362 char *sca = sa->score;
363 char *scb = sb->score;
364 size_t lena, lenb;
365 bool nega = *sca == '-';
366 bool negb = *scb == '-';
367 int diff = nega - negb;
368 if (diff)
369 return diff;
370 if (nega)
371 {
372 char *tmp = sca;
373 sca = scb + 1;
374 scb = tmp + 1;
375 }
376 lena = strlen (sca);
377 lenb = strlen (scb);
378 if (lena != lenb)
379 return lenb < lena ? -1 : 1;
380 return strcmp (scb, sca);
381 }
382
383 static int
384 score_compare_reverse (const void *a, const void *b)
385 {
386 return score_compare (b, a);
387 }
388
389 int
390 push_score (struct score_entry **scores, ptrdiff_t *count, ptrdiff_t *size,
391 struct score_entry const *newscore)
392 {
393 struct score_entry *newscores = *scores;
394 if (*count == *size)
395 {
396 ptrdiff_t newsize = *size;
397 if (newsize <= 0)
398 newsize = 1;
399 else if (newsize <= MAX_SCORES / 2)
400 newsize *= 2;
401 else if (newsize < MAX_SCORES)
402 newsize = MAX_SCORES;
403 else
404 {
405 errno = ENOMEM;
406 return -1;
407 }
408 newscores = realloc (newscores, sizeof *newscores * newsize);
409 if (!newscores)
410 return -1;
411 *scores = newscores;
412 *size = newsize;
413 }
414 newscores[*count] = *newscore;
415 (*count) += 1;
416 return 0;
417 }
418
419 static void
420 sort_scores (struct score_entry *scores, ptrdiff_t count, bool reverse)
421 {
422 qsort (scores, count, sizeof *scores,
423 reverse ? score_compare_reverse : score_compare);
424 }
425
426 static int
427 write_scores (const char *filename, mode_t mode,
428 const struct score_entry *scores, ptrdiff_t count)
429 {
430 int fd;
431 FILE *f;
432 ptrdiff_t i;
433 char *tempfile = malloc (strlen (filename) + strlen (".tempXXXXXX") + 1);
434 if (!tempfile)
435 return -1;
436 strcpy (stpcpy (tempfile, filename), ".tempXXXXXX");
437 fd = mkostemp (tempfile, 0);
438 if (fd < 0)
439 return -1;
440 #ifndef DOS_NT
441 if (fchmod (fd, mode) != 0)
442 return -1;
443 #endif
444 f = fdopen (fd, "w");
445 if (! f)
446 return -1;
447 for (i = 0; i < count; i++)
448 if (fprintf (f, "%s %s\n", scores[i].score, scores[i].user_data) < 0)
449 return -1;
450 if (fclose (f) != 0)
451 return -1;
452 if (rename (tempfile, filename) != 0)
453 return -1;
454 return 0;
455 }
456
457 static int
458 lock_file (const char *filename, void **state)
459 {
460 int fd;
461 struct stat buf;
462 int attempts = 0;
463 const char *lockext = ".lockfile";
464 char *lockpath = malloc (strlen (filename) + strlen (lockext) + 60);
465 if (!lockpath)
466 return -1;
467 strcpy (stpcpy (lockpath, filename), lockext);
468 *state = lockpath;
469
470 while ((fd = open (lockpath, O_CREAT | O_EXCL, 0600)) < 0)
471 {
472 if (errno != EEXIST)
473 return -1;
474 attempts++;
475
476
477
478
479 if (MAX_ATTEMPTS < attempts
480 || (stat (lockpath, &buf) == 0 && 60 * 60 < time (0) - buf.st_ctime))
481 {
482 if (unlink (lockpath) != 0 && errno != ENOENT)
483 return -1;
484 attempts = 0;
485 }
486 else
487 sleep (1);
488 }
489
490 close (fd);
491 return 0;
492 }
493
494 static int
495 unlock_file (const char *filename, void *state)
496 {
497 char *lockpath = (char *) state;
498 int saved_errno = errno;
499 int ret = unlink (lockpath);
500 if (0 <= ret)
501 errno = saved_errno;
502 free (lockpath);
503 return ret;
504 }
505
506