root/lib-src/update-game-score.c

/* [<][>][^][v][top][bottom][index][help] */

DEFINITIONS

This source file includes following definitions.
  1. usage
  2. lose
  3. lose_syserr
  4. get_user_id
  5. get_prefix
  6. normalize_integer
  7. main
  8. read_score
  9. read_scores
  10. score_compare
  11. score_compare_reverse
  12. push_score
  13. sort_scores
  14. write_scores
  15. lock_file
  16. unlock_file

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

/* [<][>][^][v][top][bottom][index][help] */