view lib-src/update-game-score.c @ 94414:d86cb59eea9f

2008-04-27 Carsten Dominik <dominik@science.uva.nl> * org/org.el (org-html-level-start): Always have id's in HTML (org-export-as-html): Use `org-link-protocols' to retrieve the export form of the link. (org-add-link-type): Final parameter renamed from PUBLISH. Better documentation of how it is to be used. Avoid double entries for the same link type. (org-add-link-props): New function. (org-modules-loaded): New variable. (org-load-modules-maybe, org-set-modules): New function. (org-modules): New option. (org-mode, org-cycle, orgstruct-mode, org-run-like-in-org-mode) (orgtbl-mode, org-store-link, org-insert-link-global) (org-open-at-point): Call `org-load-modules-maybe'. (org-search-view): Add more text properties. (org-agenda-schedule, org-agenda-deadline): Allow also in search-type agendas. (org-search-view): Order of arguments has been changed. Interpret prefix-arg as TODO-ONLY. (org-agenda, org-run-agenda-series, org-agenda-manipulate-query): Take new argument order of `org-search-view' into account. (org-todo-only): New variable. (org-search-syntax-table): New variable and function. (org-search-view): Do the search with the special syntax table. (define-obsolete-function-alias): Make work with XEmacs. (org-add-planning-info): Use old date as default when modifying an existing deadline or scheduled item. (org-agenda-compute-time-span): Make argument N optional. (org-agenda-format-date-aligned): Require `cal-iso'. (org-agenda-list): Include week into into agenda heading, don't list it at each date (only on Mondays). (org-read-date-analyze): Define local variable `iso-date'. (org-agenda-format-date-aligned): Remove dependency on `calendar-time-from-absolute'. (org-remember-apply-template, org-go-to-remember-target): Interpret filenames relative to `org-directory'. (org-complete): Silently fail when trying to complete keywords that don't have a default value. (org-get-current-options): Added a #+DATE: option. (org-additional-option-like-keywords): Removed "DATE:" from the list of additional keywords. (org-export-as-html): Removed (current-time) as unnecessary second argument of `format-time-string'. (org-clock-find-position): Handle special case at end of buffer. (org-agenda-day-view): New argument DAY-OF-YEAR, pass it on to `org-agenda-change-time-span'. (org-agenda-week-view): New argument ISO-WEEK, pass it on to `org-agenda-change-time-span'. (org-agenda-month-view): New argument MONTH, pass it on to `org-agenda-change-time-span'. (org-agenda-year-view): New argument YEAR, pass it on to `org-agenda-change-time-span'. (org-agenda-change-time-span): New optional argument N, pass it on to `org-agenda-compute-time-span'. (org-agenda-compute-time-span): New argument N, interpret it by changing the starting day. (org-small-year-to-year): New function. (org-scheduled-past-days): Respect `org-scheduled-past-days'. (org-auto-repeat-maybe): Make sure that repeating dates are pushed into the future, and that the shift is at least one interval, never 0. (org-update-checkbox-count): Fix bug with checkbox counting. (org-add-note): New command. (org-add-log-setup): Renamed from `org-add-log-maybe'. (org-log-note-headings): New entry for plain notes (i.e. notes not related to state changes or clocking). (org-get-org-file): Check for availability of `remember-data-file'. (org-cached-entry-get): Allow a regexp value for `org-use-property-inheritance'. (org-use-property-inheritance): Allow regexp value. Fix bug in customization type. (org-use-tag-inheritance): Allow a list and a regexp value for this variable. (org-scan-tags, org-get-tags-at): Implement selective tag inheritance. (org-entry-get): Respect value `selective' for the INHERIT argument. (org-tag-inherit-p, org-property-inherit-p): New functions. (org-agenda-format-date-aligned): Allow 10 characters for weekday, to acomodate German locale. (org-add-archive-files): New function. (org-agenda-files): New argument `ext', to get archive files as well. (org-tbl-menu): Protect the use of variables that are only available when org-table.el gets loaded. (org-read-agenda-file-list): Error if `org-agenda-files' is a single directory. (org-open-file): Allow a batch process to trigger waiting after executing a system command. (org-store-link): Link to headline when there is not target and no region in an org-mode buffer when creating a link. (org-link-types-re): New variable. (org-make-link-regexps): Compute `org-link-types-re'. (org-make-link-description-function): New option. (org-agenda-date, org-agenda-date-weekend): New faces. (org-archive-sibling-heading): New option. (org-archive-to-archive-sibling): New function. (org-iswitchb): New command. (org-buffer-list): New function. (org-agenda-columns): Also try the #+COLUMNS line in the buffer associated with the entry at point (or with the first entry in the agenda view). (org-modules): Add entry for org-bibtex.el. (org-completion-fallback-command): Moved into `org-completion' group. (org-clock-heading-function): Moved to `org-progress' group. (org-auto-repeat-maybe): Make sure that a note can be enforces if `org-log-repeat' is `note'. (org-modules): Allow additional symbols for external packages. (org-ctrl-c-ctrl-c): Allow for `org-clock-overlays' to be undefined. (org-clock-goto): Hide drawers after showing an entry with `org-clock-goto.' (org-shiftup, org-shiftdown, org-shiftright, org-shiftleft): Try also a clocktable block shift. (org-clocktable-try-shift): New function. (org-columns-hscoll-title): New function. (org-columns-previous-hscroll): New variable. (org-columns-full-header-line-format): New variable. (org-columns-display-here-title, org-columns-remove-overlays): Install `org-columns-hscoll-title' in post-command-hook. * org/org.el: Split into many small files. * org/org-agenda.el: New file, split off from org.el. * org/org-archive.el: New file, split off from org.el. * org/org-bbdb.el: New file. * org/org-bibtex.el: New file, split off from org.el. * org/org-clock.el: New file, split off from org.el. * org/org-colview.el: New file, split off from org.el. * org/org-compat.el: New file, split off from org.el. * org/org-exp.el: New file, split off from org.el. * org/org-faces.el: New file, split off from org.el. * org/org-gnus.el: New file, split off from org.el. * org/org-info.el: New file, split off from org.el. * org/org-infojs.el: New file. * org/org-irc.el: New file. * org/org-macs.el: New file, split off from org.el. * org/org-mew.el: New file. * org/org-mhe.el: New file, split off from org.el. * org/org-publish.el: New file, split off from org.el. * org/org-remember.el: New file, split off from org.el. * org/org-rmail.el: New file, split off from org.el. * org/org-table.el: New file, split off from org.el. * org/org-vm.el: New file, split off from org.el. * org/org-wl.el: New file, split off from org.el. 2008-04-27 Jason Riedy <jason@acm.org> * lisp/org-table.el (orgtbl-to-generic): Add a :remove-nil-lines parameter that supresses lines that evaluate to NIL. (orgtbl-get-fmt): New inline function for picking apart formats that may be lists. (orgtbl-apply-fmt): New inline function for applying formats that may be functions. (orgtbl-eval-str): New inline function for strings that may be functions. (orgtbl-format-line, orgtbl-to-generic): Use and document. (orgtbl-to-latex, orgtbl-to-texinfo): Document. (*orgtbl-llfmt*, *orgtbl-llstart*) (*orgtbl-llend*): Dynamic variables for last-line formatting. (orgtbl-format-section): Shift formatting to support detecting the last line and formatting it specially. (orgtbl-to-generic): Document :ll* formats. Set to the non-ll formats unless overridden. (orgtbl-to-latex): Suggest using :llend to suppress the final \\. (*orgtbl-table*, *orgtbl-rtn*): Dynamically bound variables to hold the input collection of lines and output formatted text. (*orgtbl-hline*, *orgtbl-sep*, *orgtbl-fmt*, *orgtbl-efmt*, (*orgtbl-lfmt*, *orgtbl-lstart*, *orgtbl-lend*): Dynamically bound format parameters. (orgtbl-format-line): New function encapsulating formatting for a single line. (orgtbl-format-section): Similar for each section. Rebinding the dynamic vars customizes the formatting for each section. (orgtbl-to-generic): Use orgtbl-format-line and orgtbl-format-section. (org-get-param): Now unused, so delete. (orgtbl-gather-send-defs): New function to gather all the SEND definitions before a table. (orgtbl-send-replace-tbl): New function to find the RECEIVE corresponding to the current name. (orgtbl-send-table): Use the previous two functions and implement multiple destinations for each table. * doc/org.texi (A LaTeX example): Note that fmt may be a one-argument function, and efmt may be a two-argument function. (Radio tables): Document multiple destinations. 2008-04-27 Carsten Dominik <dominik@science.uva.nl> * org/org-agenda.el (org-add-to-diary-list): New function. (org-prefix-has-effort): New variable. (org-sort-agenda-noeffort-is-high): New option. (org-agenda-columns-show-summaries) (org-agenda-columns-compute-summary-properties): New options. (org-format-agenda-item): Compute the duration of the item. (org-agenda-weekend-days): New variable. (org-agenda-list, org-timeline): Use the proper faces for dates in the agenda and timeline buffers. (org-agenda-archive-to-archive-sibling): New command. (org-agenda-start-with-clockreport-mode): New option. (org-agenda-clockreport-parameter-plist): New option. (org-agenda-clocktable-mode): New variable. (org-agenda-deadline-leaders): Allow a function value for the deadline leader. (org-agenda-get-deadlines): Deal with new function value. * lisp/org-clock.el (org-clock): New customization group. (org-clock-into-drawer, org-clock-out-when-done) (org-clock-in-switch-to-state, org-clock-heading-function): Moved into the new group. (org-clock-out-remove-zero-time-clocks): New option. (org-clock-out): Use `org-clock-out-remove-zero-time-clocks'. (org-dblock-write:clocktable): Allow a Lisp form for the scope parameter. (org-dblock-write:clocktable): Fixed bug with total time calculation. (org-dblock-write:clocktable): Request the unrestricted list of files. (org-get-clocktable): New function. (org-dblock-write:clocktable): Make sure :tstart and :tend can not only be strings but also integers (an absolute day number) and lists (m d y). * org/org-colview.el (org-columns-next-allowed-value) (org-columns-edit-value): Limit the effort for updatig in the agenda to recomputing a single file. (org-columns-compute): Only write property value if it has changed. This avoids raising the buffer-change-flag unnecessarily. (org-agenda-colview-summarize) (org-agenda-colview-compute): New functions. (org-agenda-columns): Call `org-agenda-colview-summarize'. * org/org-exp.el (org-export-run-in-background): New option. (org-export-icalendar): Allow a batch process to trigger waiting after executing a system command. (org-export-preprocess-string): Renamed-from `org-cleaned-string-for-export'. (org-export-html-style): Made target class look like normal text. (org-export-as-html): Make use of the better proprocessing in `org-cleaned-string-for-export'. (org-cleaned-string-for-export): Better treatment of heuristic targets, many more internal links will now work in HTML export. (org-get-current-options): Incorporate LINK_UP, LINK_HOME, and INFOJS. (org-export-inbuffer-options-extra): New variable. (org-export-options-filters): New hook. (org-infile-export-plist): Find also the settings keywords in `org-export-inbuffer-options-extra'. (org-infile-export-plist): Allow multiple #+OPTIONS lines and multiple #+INFOJS_OPT lines. (org-export-html-handle-js-options): New function. (org-export-html-infojs-setup): New option. (org-export-as-html): Call `org-export-html-handle-js-options'. Add autoload to all entry points. (org-skip-comments): Function removed. * org/org-table.el (org-table-make-reference): Extra parenthesis around single fields, to make sure that algebraic formulas get correctly interpreted by calc. (org-table-current-column): No longer interactive. * org/org-export-latex.el (org-export-latex-preprocess): Renamed from `org-export-latex-cleaned-string'. 2008-04-27 Bastien Guerry <bzg@altern.org> * org/org-publish.el (org-publish-get-base-files-1): New function. (org-publish-get-base-files): Use it. (org-publish-temp-files): New variable. Don't require 'dired-aux anymore. (org-publish-initial-buffer): New variable. (org-publish-org-to, org-publish): Use it. (org-publish-get-base-files-1): Bug fix: get the proper list of files when recursing thru a directory. (org-publish-get-base-files): Use the :exclude property to skip both files and directories.
author Carsten Dominik <dominik@science.uva.nl>
date Sun, 27 Apr 2008 18:33:39 +0000
parents 5714ff101fd9
children 606f2d163a64 3a4bc081639c
line wrap: on
line source

/* update-game-score.c --- Update a score file
   Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007, 2008
     Free Software Foundation, Inc.

This file is part of GNU Emacs.

GNU Emacs is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3, or (at your option)
any later version.

GNU Emacs is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with GNU Emacs; see the file COPYING.  If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.  */

/* This program is allows a game to securely and atomically update a
   score file.  It should be installed setuid, owned by an appropriate
   user like `games'.

   Alternatively, it can be compiled without HAVE_SHARED_GAME_DIR
   defined, and in that case it will store scores in the user's home
   directory (it should NOT be setuid).

   Created 2002/03/22, by Colin Walters <walters@debian.org>
*/

#include <config.h>

#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#include <errno.h>
#ifdef HAVE_STRING_H
#include <string.h>
#endif
#ifdef HAVE_STDLIB_H
#include <stdlib.h>
#endif
#include <stdio.h>
#include <time.h>
#include <pwd.h>
#include <ctype.h>
#ifdef HAVE_FCNTL_H
#include <fcntl.h>
#endif
#ifdef STDC_HEADERS
#include <stdarg.h>
#endif
#include <sys/stat.h>

/* Needed for SunOS4, for instance.  */
extern char *optarg;
extern int optind, opterr;

#define MAX_ATTEMPTS 5
#define MAX_SCORES 200
#define MAX_DATA_LEN 1024

/* Declare the prototype for a general external function.  */
#if defined (PROTOTYPES) || defined (WINDOWSNT)
#define P_(proto) proto
#else
#define P_(proto) ()
#endif

#ifndef HAVE_DIFFTIME
/* OK on POSIX (time_t is arithmetic type) modulo overflow in subtraction.  */
#define difftime(t1, t0) (double)((t1) - (t0))
#endif

int
usage (err)
     int err;
{
  fprintf (stdout, "Usage: update-game-score [-m MAX ] [ -r ] game/scorefile SCORE DATA\n");
  fprintf (stdout, "       update-game-score -h\n");
  fprintf (stdout, " -h\t\tDisplay this help.\n");
  fprintf (stdout, " -m MAX\t\tLimit the maximum number of scores to MAX.\n");
  fprintf (stdout, " -r\t\tSort the scores in increasing order.\n");
  fprintf (stdout, " -d DIR\t\tStore scores in DIR (only if not setuid).\n");
  exit (err);
}

int lock_file P_ ((const char *filename, void **state));
int unlock_file P_ ((const char *filename, void *state));

struct score_entry
{
  long score;
  char *username;
  char *data;
};

int read_scores P_ ((const char *filename, struct score_entry **scores,
		     int *count));
int push_score P_ ((struct score_entry **scores, int *count,
		    int newscore, char *username, char *newdata));
void sort_scores P_ ((struct score_entry *scores, int count, int reverse));
int write_scores P_ ((const char *filename, const struct score_entry *scores,
		      int count));

void lose P_ ((const char *msg)) NO_RETURN;

void
lose (msg)
     const char *msg;
{
  fprintf (stderr, "%s\n", msg);
  exit (EXIT_FAILURE);
}

void lose_syserr P_ ((const char *msg)) NO_RETURN;

/* Taken from sysdep.c.  */
#ifndef HAVE_STRERROR
#ifndef WINDOWSNT
char *
strerror (errnum)
     int errnum;
{
  extern char *sys_errlist[];
  extern int sys_nerr;

  if (errnum >= 0 && errnum < sys_nerr)
    return sys_errlist[errnum];
  return (char *) "Unknown error";
}
#endif /* not WINDOWSNT */
#endif /* ! HAVE_STRERROR */

void
lose_syserr (msg)
     const char *msg;
{
  fprintf (stderr, "%s: %s\n", msg, strerror (errno));
  exit (EXIT_FAILURE);
}

char *
get_user_id P_ ((void))
{
  char *name;
  struct passwd *buf = getpwuid (getuid ());
  if (!buf)
    {
      int count = 1;
      int uid = (int) getuid ();
      int tuid = uid;
      while (tuid /= 10)
	count++;
      name = malloc (count+1);
      if (!name)
	return NULL;
      sprintf (name, "%d", uid);
      return name;
    }
  return buf->pw_name;
}

char *
get_prefix (running_suid, user_prefix)
     int running_suid;
     char *user_prefix;
{
  if (!running_suid && user_prefix == NULL)
    lose ("Not using a shared game directory, and no prefix given.");
  if (running_suid)
    {
#ifdef HAVE_SHARED_GAME_DIR
      return HAVE_SHARED_GAME_DIR;
#else
      lose ("This program was compiled without HAVE_SHARED_GAME_DIR,\n and should not be suid.");
#endif
    }
  return user_prefix;
}

int
main (argc, argv)
     int argc;
     char **argv;
{
  int c, running_suid;
  void *lockstate;
  char *user_id, *scorefile, *prefix, *user_prefix = NULL;
  struct stat buf;
  struct score_entry *scores;
  int newscore, scorecount, reverse = 0, max = MAX_SCORES;
  char *newdata;

  srand (time (0));

  while ((c = getopt (argc, argv, "hrm:d:")) != -1)
    switch (c)
      {
      case 'h':
	usage (EXIT_SUCCESS);
	break;
      case 'd':
	user_prefix = optarg;
	break;
      case 'r':
	reverse = 1;
	break;
      case 'm':
	max = atoi (optarg);
	if (max > MAX_SCORES)
	  max = MAX_SCORES;
	break;
      default:
	usage (EXIT_FAILURE);
      }

  if (optind+3 != argc)
    usage (EXIT_FAILURE);

  running_suid = (getuid () != geteuid ());

  prefix = get_prefix (running_suid, user_prefix);

  scorefile = malloc (strlen (prefix) + strlen (argv[optind]) + 2);
  if (!scorefile)
    lose_syserr ("Couldn't allocate score file");

  strcpy (scorefile, prefix);
  strcat (scorefile, "/");
  strcat (scorefile, argv[optind]);
  newscore = atoi (argv[optind+1]);
  newdata = argv[optind+2];
  if (strlen (newdata) > MAX_DATA_LEN)
    newdata[MAX_DATA_LEN] = '\0';

  user_id = get_user_id ();
  if (user_id == NULL)
    lose_syserr ("Couldn't determine user id");

  if (stat (scorefile, &buf) < 0)
    lose_syserr ("Failed to access scores file");

  if (lock_file (scorefile, &lockstate) < 0)
    lose_syserr ("Failed to lock scores file");

  if (read_scores (scorefile, &scores, &scorecount) < 0)
    {
      unlock_file (scorefile, lockstate);
      lose_syserr ("Failed to read scores file");
    }
  push_score (&scores, &scorecount, newscore, user_id, newdata);
  /* Limit the number of scores.  If we're using reverse sorting, then
     we should increment the beginning of the array, to skip over the
     *smallest* scores.  Otherwise, we just decrement the number of
     scores, since the smallest will be at the end. */
  if (scorecount > MAX_SCORES)
    scorecount -= (scorecount - MAX_SCORES);
    if (reverse)
      scores += (scorecount - MAX_SCORES);
  sort_scores (scores, scorecount, reverse);
  if (write_scores (scorefile, scores, scorecount) < 0)
    {
      unlock_file (scorefile, lockstate);
      lose_syserr ("Failed to write scores file");
    }
  unlock_file (scorefile, lockstate);
  exit (EXIT_SUCCESS);
}

int
read_score (f, score)
     FILE *f;
     struct score_entry *score;
{
  int c;
  if (feof (f))
    return 1;
  while ((c = getc (f)) != EOF
	 && isdigit (c))
    {
      score->score *= 10;
      score->score += (c-48);
    }
  while ((c = getc (f)) != EOF
	 && isspace (c))
    ;
  if (c == EOF)
    return -1;
  ungetc (c, f);
#ifdef HAVE_GETDELIM
  {
    size_t count = 0;
    if (getdelim (&score->username, &count, ' ', f) < 1
	|| score->username == NULL)
      return -1;
    /* Trim the space */
    score->username[strlen (score->username)-1] = '\0';
  }
#else
  {
    int unameread = 0;
    int unamelen = 30;
    char *username = malloc (unamelen);
    if (!username)
      return -1;

    while ((c = getc (f)) != EOF
	   && !isspace (c))
      {
	if (unameread >= unamelen-1)
	  if (!(username = realloc (username, unamelen *= 2)))
	    return -1;
	username[unameread] = c;
	unameread++;
      }
    if (c == EOF)
      return -1;
    username[unameread] = '\0';
    score->username = username;
  }
#endif
#ifdef HAVE_GETLINE
  score->data = NULL;
  errno = 0;
  {
    size_t len;
    if (getline (&score->data, &len, f) < 0)
      return -1;
    score->data[strlen (score->data)-1] = '\0';
  }
#else
  {
    int cur = 0;
    int len = 16;
    char *buf = malloc (len);
    if (!buf)
      return -1;
    while ((c = getc (f)) != EOF
	   && c != '\n')
      {
	if (cur >= len-1)
	  {
	    if (!(buf = realloc (buf, len *= 2)))
	      return -1;
	  }
	buf[cur] = c;
	cur++;
      }
    score->data = buf;
    score->data[cur] = '\0';
  }
#endif
  return 0;
}

int
read_scores (filename, scores, count)
     const char *filename;
     struct score_entry **scores;
     int *count;
{
  int readval, scorecount, cursize;
  struct score_entry *ret;
  FILE *f = fopen (filename, "r");
  if (!f)
    return -1;
  scorecount = 0;
  cursize = 16;
  ret = (struct score_entry *) malloc (sizeof (struct score_entry) * cursize);
  if (!ret)
    return -1;
  while ((readval = read_score (f, &ret[scorecount])) == 0)
    {
      /* We encoutered an error */
      if (readval < 0)
	return -1;
      scorecount++;
      if (scorecount >= cursize)
	{
	  cursize *= 2;
	  ret = (struct score_entry *)
	    realloc (ret, (sizeof (struct score_entry) * cursize));
	  if (!ret)
	    return -1;
	}
    }
  *count = scorecount;
  *scores = ret;
  return 0;
}

int
score_compare (a, b)
     const void *a;
     const void *b;
{
  const struct score_entry *sa = (const struct score_entry *) a;
  const struct score_entry *sb = (const struct score_entry *) b;
  return (sb->score > sa->score) - (sb->score < sa->score);
}

int
score_compare_reverse (a, b)
     const void *a;
     const void *b;
{
  const struct score_entry *sa = (const struct score_entry *) a;
  const struct score_entry *sb = (const struct score_entry *) b;
  return (sa->score > sb->score) - (sa->score < sb->score);
}

int
push_score (scores, count, newscore, username, newdata)
     struct score_entry **scores;
     int *count; int newscore;
     char *username;
     char *newdata;
{
 struct score_entry *newscores
   = (struct score_entry *) realloc (*scores,
				     sizeof (struct score_entry) * ((*count) + 1));
  if (!newscores)
    return -1;
  newscores[*count].score = newscore;
  newscores[*count].username = username;
  newscores[*count].data = newdata;
  (*count) += 1;
  *scores = newscores;
  return 0;
}

void
sort_scores (scores, count, reverse)
     struct score_entry *scores;
     int count;
     int reverse;
{
  qsort (scores, count, sizeof (struct score_entry),
	reverse ? score_compare_reverse : score_compare);
}

int
write_scores (filename, scores, count)
     const char *filename;
     const struct score_entry * scores;
     int count;
{
  FILE *f;
  int i;
  char *tempfile = malloc (strlen (filename) + strlen (".tempXXXXXX") + 1);
  if (!tempfile)
    return -1;
  strcpy (tempfile, filename);
  strcat (tempfile, ".tempXXXXXX");
#ifdef HAVE_MKSTEMP
  if (mkstemp (tempfile) < 0
#else
  if (mktemp (tempfile) != tempfile
#endif
      || !(f = fopen (tempfile, "w")))
    return -1;
  for (i = 0; i < count; i++)
    if (fprintf (f, "%ld %s %s\n", scores[i].score, scores[i].username,
		scores[i].data) < 0)
      return -1;
  fclose (f);
  if (rename (tempfile, filename) < 0)
    return -1;
  if (chmod (filename, 0644) < 0)
    return -1;
  return 0;
}

int
lock_file (filename, state)
  const char *filename;
  void **state;
{
  int fd;
  struct stat buf;
  int attempts = 0;
  char *lockext = ".lockfile";
  char *lockpath = malloc (strlen (filename) + strlen (lockext) + 60);
  if (!lockpath)
    return -1;
  strcpy (lockpath, filename);
  strcat (lockpath, lockext);
  *state = lockpath;
 trylock:
  attempts++;
  /* If the lock is over an hour old, delete it. */
  if (stat (lockpath, &buf) == 0
      && (difftime (buf.st_ctime, time (NULL) > 60*60)))
    unlink (lockpath);
  fd = open (lockpath, O_CREAT | O_EXCL, 0600);
  if (fd < 0)
    {
      if (errno == EEXIST)
	{
	  /* Break the lock; we won't corrupt the file, but we might
	     lose some scores. */
	  if (attempts > MAX_ATTEMPTS)
	    {
	      unlink (lockpath);
	      attempts = 0;
	    }
	  sleep ((rand () % 2)+1);
	  goto trylock;
	}
      else
	return -1;
    }
  close (fd);
  return 0;
}

int
unlock_file (filename, state)
  const char *filename;
 void *state;
{
  char *lockpath = (char *) state;
  int ret = unlink (lockpath);
  int saved_errno = errno;
  free (lockpath);
  errno = saved_errno;
  return ret;
}

/* arch-tag: 2bf5c52e-4beb-463a-954e-c58b9c64736b
   (do not change this comment) */

/* update-game-score.c ends here */