/* lock.c

   Routines to lock and unlock the tty... */

/*
 * Copyright (c) 1995 RadioMail Corporation.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. Neither the name of RadioMail Corporation nor the names of its
 *    contributors may be used to endorse or promote products derived
 *    from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY RADIOMAIL CORPORATION AND CONTRIBUTORS
 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL
 * RADIOMAIL CORPORATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 * OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * This software was written for RadioMail Corporation by Ted Lemon
 * under a contract with Vixie Enterprises, and is based on an earlier
 * design by Paul Vixie.
 */

#ifndef lint
static char copyright[] =
"@(#) Copyright (c) 1995 RadioMail Corporation.  All rights reserved.\n";
#endif /* not lint */

#include "osdep.h"
#include "cdefs.h"
#include "global.h"
#include <stdio.h>
#include <fcntl.h>
#include <syslog.h>
#include "mcap.h"
#include "ttio.h"

static char lockbuf [PATH_MAX];
static int havelock = 0;

/* Acquire a lock for the specified tty.  If it's already locked and
   waitp is nonzero, wait until it's unlocked and then exit.  This
   keeps init from endlessly spawning new copies of modemd to try the
   lock, but allows modemd to follow an easily predictable sequence in
   initializing and answering the modem.  ttnewlock initializes a
   static name buffer and then calls ttgetlock which does the rest of
   the work.   Subsequent calls to ttunlock and ttgetlock will release
   and re-acquire the same lock. */

int ttnewlock (name, waitp)
     char *name;
     int waitp;
{
  sprintf (lockbuf, _PATH_TTYLOCK, name);
  return ttgetlock (waitp);
}

int ttgetlock (waitp)
     int waitp;
{
  int fd;
  int pid;
  int status;

  /* Make sure lock can be world readable... */
  umask (02);

  /* Try to grab the lock. */
  while ((fd = open (lockbuf, O_CREAT | O_EXCL | O_WRONLY, 0664)) < 0)
    {
      /* If we couldn't grab it fairly, try seeing if the pid that wrote
	 it is still alive.    The pid will be in the file as a raw int
	 value. */
      if ((fd = open (lockbuf, O_RDONLY, 0)) < 0)
	error ("Can't open tty lock file %s for reading: %m.", lockbuf);

      if ((status = read (fd, &pid, sizeof pid)) < 0)
	error ("Can't read tty lock pid: %m.");
      else if (status != sizeof pid)
	error ("Short read on tty lock pid: %d bytes out of %d.",
	       status, sizeof pid);

      /* If we can send it a signal zero and either succeed or get
	 an error other than ESRCH, the process is still running. */
      if (!kill (pid, 0) || errno != ESRCH)
	{	
	  close (fd);

	  if (!waitp)
	    return 0;

	  /* Keep watching the lock file until it goes away... */
	  while ((fd = open (lockbuf, O_RDONLY, 0)) > 0)
	    {
	      close (fd);
	      /* If the process has died, remove the lock and break out. */
	      if (kill (pid, 0) && errno != EPERM)
		{
		  unlink (lockbuf);
		  break;
		}
	      sleep (5);
	    }
	  error ("ttlock: %s was already locked.", lockbuf);
	}
      /* Remove the lock file, then loop and try to get it again... */
      unlink (lockbuf);
    }

  /* Remember that we have the lock now. */
  havelock = 1;

  /* Write our pid into the file. */
  pid = getpid ();
  if ((status = write (fd, &pid, sizeof pid)) < 0)
    error ("Can't write pid to tty lock file: %m");
  else if (status < sizeof pid)
    error ("Short write on lock pid: %d bytes instead of %d\n",
	   status, sizeof pid);
  return 1;
}

/* Release the lock if we're holding it.   This can be safely called
   even if we're not holding a lock. */

void ttunlock ()
{
  if (!havelock)
    return;
  if (!unlink (lockbuf))
    havelock = 0;
  else
    warn ("Unable to release tty lock: %m");
}
