update-game-score.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508
  1. /* update-game-score.c --- Update a score file
  2. Copyright (C) 2002-2016 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 (at
  8. 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 <string.h>
  29. #include <stdlib.h>
  30. #include <stdio.h>
  31. #include <time.h>
  32. #include <pwd.h>
  33. #include <ctype.h>
  34. #include <fcntl.h>
  35. #include <sys/stat.h>
  36. #include <getopt.h>
  37. #ifdef WINDOWSNT
  38. #include "ntlib.h"
  39. #endif
  40. #ifndef min
  41. # define min(a,b) ((a) < (b) ? (a) : (b))
  42. #endif
  43. #define MAX_ATTEMPTS 5
  44. #define MAX_DATA_LEN 1024
  45. static _Noreturn void
  46. usage (int err)
  47. {
  48. fprintf (stdout, "Usage: update-game-score [-m MAX] [-r] [-d DIR] game/scorefile SCORE DATA\n");
  49. fprintf (stdout, " update-game-score -h\n");
  50. fprintf (stdout, " -h\t\tDisplay this help.\n");
  51. fprintf (stdout, " -m MAX\t\tLimit the maximum number of scores to MAX.\n");
  52. fprintf (stdout, " -r\t\tSort the scores in increasing order.\n");
  53. fprintf (stdout, " -d DIR\t\tStore scores in DIR (only if not setuid).\n");
  54. exit (err);
  55. }
  56. static int lock_file (const char *filename, void **state);
  57. static int unlock_file (const char *filename, void *state);
  58. struct score_entry
  59. {
  60. char *score;
  61. char *user_data;
  62. };
  63. #define MAX_SCORES min (PTRDIFF_MAX, SIZE_MAX / sizeof (struct score_entry))
  64. static int read_scores (const char *filename, struct score_entry **scores,
  65. ptrdiff_t *count, ptrdiff_t *alloc);
  66. static int push_score (struct score_entry **scores, ptrdiff_t *count,
  67. ptrdiff_t *size, struct score_entry const *newscore);
  68. static void sort_scores (struct score_entry *scores, ptrdiff_t count,
  69. bool reverse);
  70. static int write_scores (const char *filename, mode_t mode,
  71. const struct score_entry *scores, ptrdiff_t count);
  72. static _Noreturn void
  73. lose (const char *msg)
  74. {
  75. fprintf (stderr, "%s\n", msg);
  76. exit (EXIT_FAILURE);
  77. }
  78. static _Noreturn void
  79. lose_syserr (const char *msg)
  80. {
  81. fprintf (stderr, "%s: %s\n", msg,
  82. errno ? strerror (errno) : "Invalid data in score file");
  83. exit (EXIT_FAILURE);
  84. }
  85. static char *
  86. get_user_id (void)
  87. {
  88. struct passwd *buf = getpwuid (getuid ());
  89. if (!buf || strchr (buf->pw_name, ' ') || strchr (buf->pw_name, '\n'))
  90. {
  91. intmax_t uid = getuid ();
  92. char *name = malloc (sizeof uid * CHAR_BIT / 3 + 4);
  93. if (name)
  94. sprintf (name, "%"PRIdMAX, uid);
  95. return name;
  96. }
  97. return buf->pw_name;
  98. }
  99. static const char *
  100. get_prefix (bool privileged, const char *user_prefix)
  101. {
  102. if (privileged)
  103. {
  104. #ifdef HAVE_SHARED_GAME_DIR
  105. return HAVE_SHARED_GAME_DIR;
  106. #else
  107. lose ("This program was compiled without HAVE_SHARED_GAME_DIR,\n"
  108. "and should not run with elevated privileges.");
  109. #endif
  110. }
  111. if (user_prefix == NULL)
  112. lose ("Not using a shared game directory, and no prefix given.");
  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, running_sgid;
  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. running_sgid = (getgid () != getegid ());
  184. if (running_suid && running_sgid)
  185. lose ("This program can run either suid or sgid, but not both.");
  186. prefix = get_prefix (running_suid || running_sgid, user_prefix);
  187. scorefile = malloc (strlen (prefix) + strlen (argv[optind]) + 2);
  188. if (!scorefile)
  189. lose_syserr ("Couldn't allocate score file");
  190. char *z = stpcpy (scorefile, prefix);
  191. *z++ = '/';
  192. strcpy (z, argv[optind]);
  193. newscore.score = normalize_integer (argv[optind + 1]);
  194. if (! newscore.score)
  195. {
  196. fprintf (stderr, "%s: Invalid score\n", argv[optind + 1]);
  197. return EXIT_FAILURE;
  198. }
  199. user = get_user_id ();
  200. if (! user)
  201. lose_syserr ("Couldn't determine user id");
  202. data = argv[optind + 2];
  203. if (strlen (data) > MAX_DATA_LEN)
  204. data[MAX_DATA_LEN] = '\0';
  205. nl = strchr (data, '\n');
  206. if (nl)
  207. *nl = '\0';
  208. newscore.user_data = malloc (strlen (user) + 1 + strlen (data) + 1);
  209. if (! newscore.user_data
  210. || sprintf (newscore.user_data, "%s %s", user, data) < 0)
  211. lose_syserr ("Memory exhausted");
  212. if (lock_file (scorefile, &lockstate) < 0)
  213. lose_syserr ("Failed to lock scores file");
  214. if (read_scores (scorefile, &scores, &scorecount, &scorealloc) < 0)
  215. {
  216. unlock_file (scorefile, lockstate);
  217. lose_syserr ("Failed to read scores file");
  218. }
  219. if (push_score (&scores, &scorecount, &scorealloc, &newscore) < 0)
  220. {
  221. unlock_file (scorefile, lockstate);
  222. lose_syserr ("Failed to add score");
  223. }
  224. sort_scores (scores, scorecount, reverse);
  225. /* Limit the number of scores. If we're using reverse sorting, then
  226. also increment the beginning of the array, to skip over the
  227. *smallest* scores. Otherwise, just decrementing the number of
  228. scores suffices, since the smallest is at the end. */
  229. if (scorecount > max_scores)
  230. {
  231. if (reverse)
  232. scores += scorecount - max_scores;
  233. scorecount = max_scores;
  234. }
  235. if (write_scores (scorefile, running_sgid ? 0664 : 0644,
  236. scores, scorecount) < 0)
  237. {
  238. unlock_file (scorefile, lockstate);
  239. lose_syserr ("Failed to write scores file");
  240. }
  241. if (unlock_file (scorefile, lockstate) < 0)
  242. lose_syserr ("Failed to unlock scores file");
  243. exit (EXIT_SUCCESS);
  244. }
  245. static char *
  246. read_score (char *p, struct score_entry *score)
  247. {
  248. score->score = p;
  249. p = strchr (p, ' ');
  250. if (!p)
  251. return p;
  252. *p++ = 0;
  253. score->user_data = p;
  254. p = strchr (p, '\n');
  255. if (!p)
  256. return p;
  257. *p++ = 0;
  258. return p;
  259. }
  260. static int
  261. read_scores (const char *filename, struct score_entry **scores,
  262. ptrdiff_t *count, ptrdiff_t *alloc)
  263. {
  264. char *p, *filedata;
  265. ptrdiff_t filesize, nread;
  266. struct stat st;
  267. FILE *f = fopen (filename, "r");
  268. if (!f)
  269. return -1;
  270. if (fstat (fileno (f), &st) != 0)
  271. return -1;
  272. if (! (0 <= st.st_size && st.st_size < min (PTRDIFF_MAX, SIZE_MAX)))
  273. {
  274. errno = EOVERFLOW;
  275. return -1;
  276. }
  277. filesize = st.st_size;
  278. filedata = malloc (filesize + 1);
  279. if (! filedata)
  280. return -1;
  281. nread = fread (filedata, 1, filesize + 1, f);
  282. if (filesize < nread)
  283. {
  284. errno = 0;
  285. return -1;
  286. }
  287. if (nread < filesize)
  288. filesize = nread;
  289. if (ferror (f) || fclose (f) != 0)
  290. return -1;
  291. filedata[filesize] = 0;
  292. if (strlen (filedata) != filesize)
  293. {
  294. errno = 0;
  295. return -1;
  296. }
  297. *scores = 0;
  298. *count = *alloc = 0;
  299. for (p = filedata; p < filedata + filesize; )
  300. {
  301. struct score_entry entry;
  302. p = read_score (p, &entry);
  303. if (!p)
  304. {
  305. errno = 0;
  306. return -1;
  307. }
  308. if (push_score (scores, count, alloc, &entry) < 0)
  309. return -1;
  310. }
  311. return 0;
  312. }
  313. static int
  314. score_compare (const void *a, const void *b)
  315. {
  316. const struct score_entry *sa = (const struct score_entry *) a;
  317. const struct score_entry *sb = (const struct score_entry *) b;
  318. char *sca = sa->score;
  319. char *scb = sb->score;
  320. size_t lena, lenb;
  321. bool nega = *sca == '-';
  322. bool negb = *scb == '-';
  323. int diff = nega - negb;
  324. if (diff)
  325. return diff;
  326. if (nega)
  327. {
  328. char *tmp = sca;
  329. sca = scb + 1;
  330. scb = tmp + 1;
  331. }
  332. lena = strlen (sca);
  333. lenb = strlen (scb);
  334. if (lena != lenb)
  335. return lenb < lena ? -1 : 1;
  336. return strcmp (scb, sca);
  337. }
  338. static int
  339. score_compare_reverse (const void *a, const void *b)
  340. {
  341. return score_compare (b, a);
  342. }
  343. int
  344. push_score (struct score_entry **scores, ptrdiff_t *count, ptrdiff_t *size,
  345. struct score_entry const *newscore)
  346. {
  347. struct score_entry *newscores = *scores;
  348. if (*count == *size)
  349. {
  350. ptrdiff_t newsize = *size;
  351. if (newsize <= 0)
  352. newsize = 1;
  353. else if (newsize <= MAX_SCORES / 2)
  354. newsize *= 2;
  355. else if (newsize < MAX_SCORES)
  356. newsize = MAX_SCORES;
  357. else
  358. {
  359. errno = ENOMEM;
  360. return -1;
  361. }
  362. newscores = realloc (newscores, sizeof *newscores * newsize);
  363. if (!newscores)
  364. return -1;
  365. *scores = newscores;
  366. *size = newsize;
  367. }
  368. newscores[*count] = *newscore;
  369. (*count) += 1;
  370. return 0;
  371. }
  372. static void
  373. sort_scores (struct score_entry *scores, ptrdiff_t count, bool reverse)
  374. {
  375. qsort (scores, count, sizeof *scores,
  376. reverse ? score_compare_reverse : score_compare);
  377. }
  378. static int
  379. write_scores (const char *filename, mode_t mode,
  380. const struct score_entry *scores, ptrdiff_t count)
  381. {
  382. int fd;
  383. FILE *f;
  384. ptrdiff_t i;
  385. char *tempfile = malloc (strlen (filename) + strlen (".tempXXXXXX") + 1);
  386. if (!tempfile)
  387. return -1;
  388. strcpy (stpcpy (tempfile, filename), ".tempXXXXXX");
  389. fd = mkostemp (tempfile, 0);
  390. if (fd < 0)
  391. return -1;
  392. #ifndef DOS_NT
  393. if (fchmod (fd, mode) != 0)
  394. return -1;
  395. #endif
  396. f = fdopen (fd, "w");
  397. if (! f)
  398. return -1;
  399. for (i = 0; i < count; i++)
  400. if (fprintf (f, "%s %s\n", scores[i].score, scores[i].user_data) < 0)
  401. return -1;
  402. if (fclose (f) != 0)
  403. return -1;
  404. if (rename (tempfile, filename) != 0)
  405. return -1;
  406. return 0;
  407. }
  408. static int
  409. lock_file (const char *filename, void **state)
  410. {
  411. int fd;
  412. struct stat buf;
  413. int attempts = 0;
  414. const char *lockext = ".lockfile";
  415. char *lockpath = malloc (strlen (filename) + strlen (lockext) + 60);
  416. if (!lockpath)
  417. return -1;
  418. strcpy (stpcpy (lockpath, filename), lockext);
  419. *state = lockpath;
  420. while ((fd = open (lockpath, O_CREAT | O_EXCL, 0600)) < 0)
  421. {
  422. if (errno != EEXIST)
  423. return -1;
  424. attempts++;
  425. /* Break the lock if it is over an hour old, or if we've tried
  426. more than MAX_ATTEMPTS times. We won't corrupt the file, but
  427. we might lose some scores. */
  428. if (MAX_ATTEMPTS < attempts
  429. || (stat (lockpath, &buf) == 0 && 60 * 60 < time (0) - buf.st_ctime))
  430. {
  431. if (unlink (lockpath) != 0 && errno != ENOENT)
  432. return -1;
  433. attempts = 0;
  434. }
  435. sleep ((rand () & 1) + 1);
  436. }
  437. close (fd);
  438. return 0;
  439. }
  440. static int
  441. unlock_file (const char *filename, void *state)
  442. {
  443. char *lockpath = (char *) state;
  444. int saved_errno = errno;
  445. int ret = unlink (lockpath);
  446. int unlink_errno = errno;
  447. free (lockpath);
  448. errno = ret < 0 ? unlink_errno : saved_errno;
  449. return ret;
  450. }
  451. /* update-game-score.c ends here */