update-game-score.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509
  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 either setuid or setgid, owned
  17. by an appropriate user or group 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, mode_t mode,
  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 privileged, const char *user_prefix)
  102. {
  103. if (privileged)
  104. {
  105. #ifdef HAVE_SHARED_GAME_DIR
  106. return HAVE_SHARED_GAME_DIR;
  107. #else
  108. lose ("This program was compiled without HAVE_SHARED_GAME_DIR,\n"
  109. "and should not run with elevated privileges.");
  110. #endif
  111. }
  112. if (user_prefix == NULL)
  113. lose ("Not using a shared game directory, and no prefix given.");
  114. return user_prefix;
  115. }
  116. static char *
  117. normalize_integer (char *num)
  118. {
  119. bool neg;
  120. char *p;
  121. while (*num != '\n' && isspace (*num))
  122. num++;
  123. neg = *num == '-';
  124. num += neg || *num == '-';
  125. if (*num == '0')
  126. {
  127. while (*++num == '0')
  128. continue;
  129. neg &= !!*num;
  130. num -= !*num;
  131. }
  132. for (p = num; '0' <= *p && *p <= '9'; p++)
  133. continue;
  134. if (*p || p == num)
  135. {
  136. errno = 0;
  137. return 0;
  138. }
  139. if (neg)
  140. *--num = '-';
  141. return num;
  142. }
  143. int
  144. main (int argc, char **argv)
  145. {
  146. int c;
  147. bool running_suid, running_sgid;
  148. void *lockstate;
  149. char *scorefile;
  150. char *end, *nl, *user, *data;
  151. const char *prefix, *user_prefix = NULL;
  152. struct score_entry *scores;
  153. struct score_entry newscore;
  154. bool reverse = false;
  155. ptrdiff_t scorecount, scorealloc;
  156. ptrdiff_t max_scores = MAX_SCORES;
  157. srand (time (0));
  158. while ((c = getopt (argc, argv, "hrm:d:")) != -1)
  159. switch (c)
  160. {
  161. case 'h':
  162. usage (EXIT_SUCCESS);
  163. break;
  164. case 'd':
  165. user_prefix = optarg;
  166. break;
  167. case 'r':
  168. reverse = 1;
  169. break;
  170. case 'm':
  171. {
  172. intmax_t m = strtoimax (optarg, &end, 10);
  173. if (optarg == end || *end || m < 0)
  174. usage (EXIT_FAILURE);
  175. max_scores = min (m, MAX_SCORES);
  176. }
  177. break;
  178. default:
  179. usage (EXIT_FAILURE);
  180. }
  181. if (argc - optind != 3)
  182. usage (EXIT_FAILURE);
  183. running_suid = (getuid () != geteuid ());
  184. running_sgid = (getgid () != getegid ());
  185. if (running_suid && running_sgid)
  186. lose ("This program can run either suid or sgid, but not both.");
  187. prefix = get_prefix (running_suid || running_sgid, user_prefix);
  188. scorefile = malloc (strlen (prefix) + strlen (argv[optind]) + 2);
  189. if (!scorefile)
  190. lose_syserr ("Couldn't allocate score file");
  191. char *z = stpcpy (scorefile, prefix);
  192. *z++ = '/';
  193. strcpy (z, argv[optind]);
  194. newscore.score = normalize_integer (argv[optind + 1]);
  195. if (! newscore.score)
  196. {
  197. fprintf (stderr, "%s: Invalid score\n", argv[optind + 1]);
  198. return EXIT_FAILURE;
  199. }
  200. user = get_user_id ();
  201. if (! user)
  202. lose_syserr ("Couldn't determine user id");
  203. data = argv[optind + 2];
  204. if (strlen (data) > MAX_DATA_LEN)
  205. data[MAX_DATA_LEN] = '\0';
  206. nl = strchr (data, '\n');
  207. if (nl)
  208. *nl = '\0';
  209. newscore.user_data = malloc (strlen (user) + 1 + strlen (data) + 1);
  210. if (! newscore.user_data
  211. || sprintf (newscore.user_data, "%s %s", user, data) < 0)
  212. lose_syserr ("Memory exhausted");
  213. if (lock_file (scorefile, &lockstate) < 0)
  214. lose_syserr ("Failed to lock scores file");
  215. if (read_scores (scorefile, &scores, &scorecount, &scorealloc) < 0)
  216. {
  217. unlock_file (scorefile, lockstate);
  218. lose_syserr ("Failed to read scores file");
  219. }
  220. if (push_score (&scores, &scorecount, &scorealloc, &newscore) < 0)
  221. {
  222. unlock_file (scorefile, lockstate);
  223. lose_syserr ("Failed to add score");
  224. }
  225. sort_scores (scores, scorecount, reverse);
  226. /* Limit the number of scores. If we're using reverse sorting, then
  227. also increment the beginning of the array, to skip over the
  228. *smallest* scores. Otherwise, just decrementing the number of
  229. scores suffices, since the smallest is at the end. */
  230. if (scorecount > max_scores)
  231. {
  232. if (reverse)
  233. scores += scorecount - max_scores;
  234. scorecount = max_scores;
  235. }
  236. if (write_scores (scorefile, running_sgid ? 0664 : 0644,
  237. scores, scorecount) < 0)
  238. {
  239. unlock_file (scorefile, lockstate);
  240. lose_syserr ("Failed to write scores file");
  241. }
  242. if (unlock_file (scorefile, lockstate) < 0)
  243. lose_syserr ("Failed to unlock scores file");
  244. exit (EXIT_SUCCESS);
  245. }
  246. static char *
  247. read_score (char *p, struct score_entry *score)
  248. {
  249. score->score = p;
  250. p = strchr (p, ' ');
  251. if (!p)
  252. return p;
  253. *p++ = 0;
  254. score->user_data = p;
  255. p = strchr (p, '\n');
  256. if (!p)
  257. return p;
  258. *p++ = 0;
  259. return p;
  260. }
  261. static int
  262. read_scores (const char *filename, struct score_entry **scores,
  263. ptrdiff_t *count, ptrdiff_t *alloc)
  264. {
  265. char *p, *filedata;
  266. ptrdiff_t filesize, nread;
  267. struct stat st;
  268. FILE *f = fopen (filename, "r");
  269. if (!f)
  270. return -1;
  271. if (fstat (fileno (f), &st) != 0)
  272. return -1;
  273. if (! (0 <= st.st_size && st.st_size < min (PTRDIFF_MAX, SIZE_MAX)))
  274. {
  275. errno = EOVERFLOW;
  276. return -1;
  277. }
  278. filesize = st.st_size;
  279. filedata = malloc (filesize + 1);
  280. if (! filedata)
  281. return -1;
  282. nread = fread (filedata, 1, filesize + 1, f);
  283. if (filesize < nread)
  284. {
  285. errno = 0;
  286. return -1;
  287. }
  288. if (nread < filesize)
  289. filesize = nread;
  290. if (ferror (f) || fclose (f) != 0)
  291. return -1;
  292. filedata[filesize] = 0;
  293. if (strlen (filedata) != filesize)
  294. {
  295. errno = 0;
  296. return -1;
  297. }
  298. *scores = 0;
  299. *count = *alloc = 0;
  300. for (p = filedata; p < filedata + filesize; )
  301. {
  302. struct score_entry entry;
  303. p = read_score (p, &entry);
  304. if (!p)
  305. {
  306. errno = 0;
  307. return -1;
  308. }
  309. if (push_score (scores, count, alloc, &entry) < 0)
  310. return -1;
  311. }
  312. return 0;
  313. }
  314. static int
  315. score_compare (const void *a, const void *b)
  316. {
  317. const struct score_entry *sa = (const struct score_entry *) a;
  318. const struct score_entry *sb = (const struct score_entry *) b;
  319. char *sca = sa->score;
  320. char *scb = sb->score;
  321. size_t lena, lenb;
  322. bool nega = *sca == '-';
  323. bool negb = *scb == '-';
  324. int diff = nega - negb;
  325. if (diff)
  326. return diff;
  327. if (nega)
  328. {
  329. char *tmp = sca;
  330. sca = scb + 1;
  331. scb = tmp + 1;
  332. }
  333. lena = strlen (sca);
  334. lenb = strlen (scb);
  335. if (lena != lenb)
  336. return lenb < lena ? -1 : 1;
  337. return strcmp (scb, sca);
  338. }
  339. static int
  340. score_compare_reverse (const void *a, const void *b)
  341. {
  342. return score_compare (b, a);
  343. }
  344. int
  345. push_score (struct score_entry **scores, ptrdiff_t *count, ptrdiff_t *size,
  346. struct score_entry const *newscore)
  347. {
  348. struct score_entry *newscores = *scores;
  349. if (*count == *size)
  350. {
  351. ptrdiff_t newsize = *size;
  352. if (newsize <= 0)
  353. newsize = 1;
  354. else if (newsize <= MAX_SCORES / 2)
  355. newsize *= 2;
  356. else if (newsize < MAX_SCORES)
  357. newsize = MAX_SCORES;
  358. else
  359. {
  360. errno = ENOMEM;
  361. return -1;
  362. }
  363. newscores = realloc (newscores, sizeof *newscores * newsize);
  364. if (!newscores)
  365. return -1;
  366. *scores = newscores;
  367. *size = newsize;
  368. }
  369. newscores[*count] = *newscore;
  370. (*count) += 1;
  371. return 0;
  372. }
  373. static void
  374. sort_scores (struct score_entry *scores, ptrdiff_t count, bool reverse)
  375. {
  376. qsort (scores, count, sizeof *scores,
  377. reverse ? score_compare_reverse : score_compare);
  378. }
  379. static int
  380. write_scores (const char *filename, mode_t mode,
  381. const struct score_entry *scores, ptrdiff_t count)
  382. {
  383. int fd;
  384. FILE *f;
  385. ptrdiff_t i;
  386. char *tempfile = malloc (strlen (filename) + strlen (".tempXXXXXX") + 1);
  387. if (!tempfile)
  388. return -1;
  389. strcpy (stpcpy (tempfile, filename), ".tempXXXXXX");
  390. fd = mkostemp (tempfile, 0);
  391. if (fd < 0)
  392. return -1;
  393. #ifndef DOS_NT
  394. if (fchmod (fd, mode) != 0)
  395. return -1;
  396. #endif
  397. f = fdopen (fd, "w");
  398. if (! f)
  399. return -1;
  400. for (i = 0; i < count; i++)
  401. if (fprintf (f, "%s %s\n", scores[i].score, scores[i].user_data) < 0)
  402. return -1;
  403. if (fclose (f) != 0)
  404. return -1;
  405. if (rename (tempfile, filename) != 0)
  406. return -1;
  407. return 0;
  408. }
  409. static int
  410. lock_file (const char *filename, void **state)
  411. {
  412. int fd;
  413. struct stat buf;
  414. int attempts = 0;
  415. const char *lockext = ".lockfile";
  416. char *lockpath = malloc (strlen (filename) + strlen (lockext) + 60);
  417. if (!lockpath)
  418. return -1;
  419. strcpy (stpcpy (lockpath, filename), lockext);
  420. *state = lockpath;
  421. while ((fd = open (lockpath, O_CREAT | O_EXCL, 0600)) < 0)
  422. {
  423. if (errno != EEXIST)
  424. return -1;
  425. attempts++;
  426. /* Break the lock if it is over an hour old, or if we've tried
  427. more than MAX_ATTEMPTS times. We won't corrupt the file, but
  428. we might lose some scores. */
  429. if (MAX_ATTEMPTS < attempts
  430. || (stat (lockpath, &buf) == 0 && 60 * 60 < time (0) - buf.st_ctime))
  431. {
  432. if (unlink (lockpath) != 0 && errno != ENOENT)
  433. return -1;
  434. attempts = 0;
  435. }
  436. sleep ((rand () & 1) + 1);
  437. }
  438. close (fd);
  439. return 0;
  440. }
  441. static int
  442. unlock_file (const char *filename, void *state)
  443. {
  444. char *lockpath = (char *) state;
  445. int saved_errno = errno;
  446. int ret = unlink (lockpath);
  447. int unlink_errno = errno;
  448. free (lockpath);
  449. errno = ret < 0 ? unlink_errno : saved_errno;
  450. return ret;
  451. }
  452. /* update-game-score.c ends here */