update-game-score.c 12 KB

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