update-game-score.c 11 KB

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