update-game-score.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504
  1. /* update-game-score.c --- Update a score file
  2. Copyright (C) 2002-2015 Free Software Foundation, Inc.
  3. Author: Colin Walters <walters@debian.org>
  4. This file is part of GNU Emacs.
  5. GNU Emacs is free software: you can redistribute it and/or modify
  6. it under the terms of the GNU General Public License as published by
  7. the Free Software Foundation, either version 3 of the License, or
  8. (at your option) any later version.
  9. GNU Emacs is distributed in the hope that it will be useful,
  10. but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. GNU General Public License for more details.
  13. You should have received a copy of the GNU General Public License
  14. along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
  15. /* This program allows a game to securely and atomically update a
  16. score file. It should be installed setuid, owned by an appropriate
  17. user like `games'.
  18. Alternatively, it can be compiled without HAVE_SHARED_GAME_DIR
  19. defined, and in that case it will store scores in the user's home
  20. directory (it should NOT be setuid).
  21. Created 2002/03/22.
  22. */
  23. #include <config.h>
  24. #include <unistd.h>
  25. #include <errno.h>
  26. #include <inttypes.h>
  27. #include <limits.h>
  28. #include <stdbool.h>
  29. #include <string.h>
  30. #include <stdlib.h>
  31. #include <stdio.h>
  32. #include <time.h>
  33. #include <pwd.h>
  34. #include <ctype.h>
  35. #include <fcntl.h>
  36. #include <sys/stat.h>
  37. #include <getopt.h>
  38. #ifdef WINDOWSNT
  39. #include "ntlib.h"
  40. #endif
  41. #ifndef min
  42. # define min(a,b) ((a) < (b) ? (a) : (b))
  43. #endif
  44. #define MAX_ATTEMPTS 5
  45. #define MAX_DATA_LEN 1024
  46. static _Noreturn void
  47. usage (int err)
  48. {
  49. fprintf (stdout, "Usage: update-game-score [-m MAX] [-r] [-d DIR] game/scorefile SCORE DATA\n");
  50. fprintf (stdout, " update-game-score -h\n");
  51. fprintf (stdout, " -h\t\tDisplay this help.\n");
  52. fprintf (stdout, " -m MAX\t\tLimit the maximum number of scores to MAX.\n");
  53. fprintf (stdout, " -r\t\tSort the scores in increasing order.\n");
  54. fprintf (stdout, " -d DIR\t\tStore scores in DIR (only if not setuid).\n");
  55. exit (err);
  56. }
  57. static int lock_file (const char *filename, void **state);
  58. static int unlock_file (const char *filename, void *state);
  59. struct score_entry
  60. {
  61. char *score;
  62. char *user_data;
  63. };
  64. #define MAX_SCORES min (PTRDIFF_MAX, SIZE_MAX / sizeof (struct score_entry))
  65. static int read_scores (const char *filename, struct score_entry **scores,
  66. ptrdiff_t *count, ptrdiff_t *alloc);
  67. static int push_score (struct score_entry **scores, ptrdiff_t *count,
  68. ptrdiff_t *size, struct score_entry const *newscore);
  69. static void sort_scores (struct score_entry *scores, ptrdiff_t count,
  70. bool reverse);
  71. static int write_scores (const char *filename,
  72. const struct score_entry *scores, ptrdiff_t count);
  73. static _Noreturn void
  74. lose (const char *msg)
  75. {
  76. fprintf (stderr, "%s\n", msg);
  77. exit (EXIT_FAILURE);
  78. }
  79. static _Noreturn void
  80. lose_syserr (const char *msg)
  81. {
  82. fprintf (stderr, "%s: %s\n", msg,
  83. errno ? strerror (errno) : "Invalid data in score file");
  84. exit (EXIT_FAILURE);
  85. }
  86. static char *
  87. get_user_id (void)
  88. {
  89. struct passwd *buf = getpwuid (getuid ());
  90. if (!buf || strchr (buf->pw_name, ' ') || strchr (buf->pw_name, '\n'))
  91. {
  92. intmax_t uid = getuid ();
  93. char *name = malloc (sizeof uid * CHAR_BIT / 3 + 4);
  94. if (name)
  95. sprintf (name, "%"PRIdMAX, uid);
  96. return name;
  97. }
  98. return buf->pw_name;
  99. }
  100. static const char *
  101. get_prefix (bool running_suid, const char *user_prefix)
  102. {
  103. if (!running_suid && user_prefix == NULL)
  104. lose ("Not using a shared game directory, and no prefix given.");
  105. if (running_suid)
  106. {
  107. #ifdef HAVE_SHARED_GAME_DIR
  108. return HAVE_SHARED_GAME_DIR;
  109. #else
  110. lose ("This program was compiled without HAVE_SHARED_GAME_DIR,\n and should not be suid.");
  111. #endif
  112. }
  113. return user_prefix;
  114. }
  115. static char *
  116. normalize_integer (char *num)
  117. {
  118. bool neg;
  119. char *p;
  120. while (*num != '\n' && isspace (*num))
  121. num++;
  122. neg = *num == '-';
  123. num += neg || *num == '-';
  124. if (*num == '0')
  125. {
  126. while (*++num == '0')
  127. continue;
  128. neg &= !!*num;
  129. num -= !*num;
  130. }
  131. for (p = num; '0' <= *p && *p <= '9'; p++)
  132. continue;
  133. if (*p || p == num)
  134. {
  135. errno = 0;
  136. return 0;
  137. }
  138. if (neg)
  139. *--num = '-';
  140. return num;
  141. }
  142. int
  143. main (int argc, char **argv)
  144. {
  145. int c;
  146. bool running_suid;
  147. void *lockstate;
  148. char *scorefile;
  149. char *end, *nl, *user, *data;
  150. const char *prefix, *user_prefix = NULL;
  151. struct score_entry *scores;
  152. struct score_entry newscore;
  153. bool reverse = false;
  154. ptrdiff_t scorecount, scorealloc;
  155. ptrdiff_t max_scores = MAX_SCORES;
  156. srand (time (0));
  157. while ((c = getopt (argc, argv, "hrm:d:")) != -1)
  158. switch (c)
  159. {
  160. case 'h':
  161. usage (EXIT_SUCCESS);
  162. break;
  163. case 'd':
  164. user_prefix = optarg;
  165. break;
  166. case 'r':
  167. reverse = 1;
  168. break;
  169. case 'm':
  170. {
  171. intmax_t m = strtoimax (optarg, &end, 10);
  172. if (optarg == end || *end || m < 0)
  173. usage (EXIT_FAILURE);
  174. max_scores = min (m, MAX_SCORES);
  175. }
  176. break;
  177. default:
  178. usage (EXIT_FAILURE);
  179. }
  180. if (argc - optind != 3)
  181. usage (EXIT_FAILURE);
  182. running_suid = (getuid () != geteuid ());
  183. prefix = get_prefix (running_suid, user_prefix);
  184. scorefile = malloc (strlen (prefix) + strlen (argv[optind]) + 2);
  185. if (!scorefile)
  186. lose_syserr ("Couldn't allocate score file");
  187. char *z = stpcpy (scorefile, prefix);
  188. *z++ = '/';
  189. strcpy (z, argv[optind]);
  190. newscore.score = normalize_integer (argv[optind + 1]);
  191. if (! newscore.score)
  192. {
  193. fprintf (stderr, "%s: Invalid score\n", argv[optind + 1]);
  194. return EXIT_FAILURE;
  195. }
  196. user = get_user_id ();
  197. if (! user)
  198. lose_syserr ("Couldn't determine user id");
  199. data = argv[optind + 2];
  200. if (strlen (data) > MAX_DATA_LEN)
  201. data[MAX_DATA_LEN] = '\0';
  202. nl = strchr (data, '\n');
  203. if (nl)
  204. *nl = '\0';
  205. newscore.user_data = malloc (strlen (user) + 1 + strlen (data) + 1);
  206. if (! newscore.user_data
  207. || sprintf (newscore.user_data, "%s %s", user, data) < 0)
  208. lose_syserr ("Memory exhausted");
  209. if (lock_file (scorefile, &lockstate) < 0)
  210. lose_syserr ("Failed to lock scores file");
  211. if (read_scores (scorefile, &scores, &scorecount, &scorealloc) < 0)
  212. {
  213. unlock_file (scorefile, lockstate);
  214. lose_syserr ("Failed to read scores file");
  215. }
  216. if (push_score (&scores, &scorecount, &scorealloc, &newscore) < 0)
  217. {
  218. unlock_file (scorefile, lockstate);
  219. lose_syserr ("Failed to add score");
  220. }
  221. sort_scores (scores, scorecount, reverse);
  222. /* Limit the number of scores. If we're using reverse sorting, then
  223. also increment the beginning of the array, to skip over the
  224. *smallest* scores. Otherwise, just decrementing the number of
  225. scores suffices, since the smallest is at the end. */
  226. if (scorecount > max_scores)
  227. {
  228. if (reverse)
  229. scores += scorecount - max_scores;
  230. scorecount = max_scores;
  231. }
  232. if (write_scores (scorefile, scores, scorecount) < 0)
  233. {
  234. unlock_file (scorefile, lockstate);
  235. lose_syserr ("Failed to write scores file");
  236. }
  237. if (unlock_file (scorefile, lockstate) < 0)
  238. lose_syserr ("Failed to unlock scores file");
  239. exit (EXIT_SUCCESS);
  240. }
  241. static char *
  242. read_score (char *p, struct score_entry *score)
  243. {
  244. score->score = p;
  245. p = strchr (p, ' ');
  246. if (!p)
  247. return p;
  248. *p++ = 0;
  249. score->user_data = p;
  250. p = strchr (p, '\n');
  251. if (!p)
  252. return p;
  253. *p++ = 0;
  254. return p;
  255. }
  256. static int
  257. read_scores (const char *filename, struct score_entry **scores,
  258. ptrdiff_t *count, ptrdiff_t *alloc)
  259. {
  260. char *p, *filedata;
  261. ptrdiff_t filesize, nread;
  262. struct stat st;
  263. FILE *f = fopen (filename, "r");
  264. if (!f)
  265. return -1;
  266. if (fstat (fileno (f), &st) != 0)
  267. return -1;
  268. if (! (0 <= st.st_size && st.st_size < min (PTRDIFF_MAX, SIZE_MAX)))
  269. {
  270. errno = EOVERFLOW;
  271. return -1;
  272. }
  273. filesize = st.st_size;
  274. filedata = malloc (filesize + 1);
  275. if (! filedata)
  276. return -1;
  277. nread = fread (filedata, 1, filesize + 1, f);
  278. if (filesize < nread)
  279. {
  280. errno = 0;
  281. return -1;
  282. }
  283. if (nread < filesize)
  284. filesize = nread;
  285. if (ferror (f) || fclose (f) != 0)
  286. return -1;
  287. filedata[filesize] = 0;
  288. if (strlen (filedata) != filesize)
  289. {
  290. errno = 0;
  291. return -1;
  292. }
  293. *scores = 0;
  294. *count = *alloc = 0;
  295. for (p = filedata; p < filedata + filesize; )
  296. {
  297. struct score_entry entry;
  298. p = read_score (p, &entry);
  299. if (!p)
  300. {
  301. errno = 0;
  302. return -1;
  303. }
  304. if (push_score (scores, count, alloc, &entry) < 0)
  305. return -1;
  306. }
  307. return 0;
  308. }
  309. static int
  310. score_compare (const void *a, const void *b)
  311. {
  312. const struct score_entry *sa = (const struct score_entry *) a;
  313. const struct score_entry *sb = (const struct score_entry *) b;
  314. char *sca = sa->score;
  315. char *scb = sb->score;
  316. size_t lena, lenb;
  317. bool nega = *sca == '-';
  318. bool negb = *scb == '-';
  319. int diff = nega - negb;
  320. if (diff)
  321. return diff;
  322. if (nega)
  323. {
  324. char *tmp = sca;
  325. sca = scb + 1;
  326. scb = tmp + 1;
  327. }
  328. lena = strlen (sca);
  329. lenb = strlen (scb);
  330. if (lena != lenb)
  331. return lenb < lena ? -1 : 1;
  332. return strcmp (scb, sca);
  333. }
  334. static int
  335. score_compare_reverse (const void *a, const void *b)
  336. {
  337. return score_compare (b, a);
  338. }
  339. int
  340. push_score (struct score_entry **scores, ptrdiff_t *count, ptrdiff_t *size,
  341. struct score_entry const *newscore)
  342. {
  343. struct score_entry *newscores = *scores;
  344. if (*count == *size)
  345. {
  346. ptrdiff_t newsize = *size;
  347. if (newsize <= 0)
  348. newsize = 1;
  349. else if (newsize <= MAX_SCORES / 2)
  350. newsize *= 2;
  351. else if (newsize < MAX_SCORES)
  352. newsize = MAX_SCORES;
  353. else
  354. {
  355. errno = ENOMEM;
  356. return -1;
  357. }
  358. newscores = realloc (newscores, sizeof *newscores * newsize);
  359. if (!newscores)
  360. return -1;
  361. *scores = newscores;
  362. *size = newsize;
  363. }
  364. newscores[*count] = *newscore;
  365. (*count) += 1;
  366. return 0;
  367. }
  368. static void
  369. sort_scores (struct score_entry *scores, ptrdiff_t count, bool reverse)
  370. {
  371. qsort (scores, count, sizeof *scores,
  372. reverse ? score_compare_reverse : score_compare);
  373. }
  374. static int
  375. write_scores (const char *filename, const struct score_entry *scores,
  376. ptrdiff_t count)
  377. {
  378. int fd;
  379. FILE *f;
  380. ptrdiff_t i;
  381. char *tempfile = malloc (strlen (filename) + strlen (".tempXXXXXX") + 1);
  382. if (!tempfile)
  383. return -1;
  384. strcpy (stpcpy (tempfile, filename), ".tempXXXXXX");
  385. fd = mkostemp (tempfile, 0);
  386. if (fd < 0)
  387. return -1;
  388. #ifndef DOS_NT
  389. if (fchmod (fd, 0644) != 0)
  390. return -1;
  391. #endif
  392. f = fdopen (fd, "w");
  393. if (! f)
  394. return -1;
  395. for (i = 0; i < count; i++)
  396. if (fprintf (f, "%s %s\n", scores[i].score, scores[i].user_data) < 0)
  397. return -1;
  398. if (fclose (f) != 0)
  399. return -1;
  400. if (rename (tempfile, filename) != 0)
  401. return -1;
  402. return 0;
  403. }
  404. static int
  405. lock_file (const char *filename, void **state)
  406. {
  407. int fd;
  408. struct stat buf;
  409. int attempts = 0;
  410. const char *lockext = ".lockfile";
  411. char *lockpath = malloc (strlen (filename) + strlen (lockext) + 60);
  412. if (!lockpath)
  413. return -1;
  414. strcpy (stpcpy (lockpath, filename), lockext);
  415. *state = lockpath;
  416. while ((fd = open (lockpath, O_CREAT | O_EXCL, 0600)) < 0)
  417. {
  418. if (errno != EEXIST)
  419. return -1;
  420. attempts++;
  421. /* Break the lock if it is over an hour old, or if we've tried
  422. more than MAX_ATTEMPTS times. We won't corrupt the file, but
  423. we might lose some scores. */
  424. if (MAX_ATTEMPTS < attempts
  425. || (stat (lockpath, &buf) == 0 && 60 * 60 < time (0) - buf.st_ctime))
  426. {
  427. if (unlink (lockpath) != 0 && errno != ENOENT)
  428. return -1;
  429. attempts = 0;
  430. }
  431. sleep ((rand () & 1) + 1);
  432. }
  433. close (fd);
  434. return 0;
  435. }
  436. static int
  437. unlock_file (const char *filename, void *state)
  438. {
  439. char *lockpath = (char *) state;
  440. int saved_errno = errno;
  441. int ret = unlink (lockpath);
  442. int unlink_errno = errno;
  443. free (lockpath);
  444. errno = ret < 0 ? unlink_errno : saved_errno;
  445. return ret;
  446. }
  447. /* update-game-score.c ends here */