/* Copyright 1990, Daniel J. Bernstein. All rights reserved. */

#include "config.h"
#include "logs.h"
#include "file.h"
#include <utmp.h>
#include <strings.h>

/* utmp and wtmp are about as sensible as /etc/passwd. */

/* We never bother to shrink /etc/utmp. */

extern long time();

long now()
{
 return time((long *) 0);
}

int utmp(line,name,host,date)
char *line;
char *name;
char *host;
long date;
{
 struct utmp ut;
 struct utmp xt;
 int fd;
 int i;
 int j;

 /* only use of strncpy, ever */
 (void) strncpy(ut.ut_line,line,sizeof(ut.ut_line));
 (void) strncpy(ut.ut_name,name,sizeof(ut.ut_name));
 (void) strncpy(ut.ut_host,host,sizeof(ut.ut_host));
 ut.ut_time = date;

 fd = open(PTYUTMP_FILE,O_RDWR);
 if (fd == -1)
   return -1;
 j = i = 0;
 while (read(fd,(char *) &xt,sizeof(xt)) == sizeof(xt))
  {
   i++;
   if (strncmp(xt.ut_line,ut.ut_line,sizeof(ut.ut_line)) == 0)
    {
     j = i;
     break;
    }
  }
 if (j)
  {
   if (lseek(fd,(long) ((j - 1) * sizeof(xt)),L_SET) == -1)
    {
     (void) close(fd);
     return -1;
    }
  }
 else
  {
   /* We have to reopen to avoid a race with other end-of-utmp entries. */
   (void) close(fd);
   if ((fd = open(PTYUTMP_FILE,O_RDWR | O_APPEND)) == -1)
     return -1;
  }
 if (write(fd,(char *) &ut,sizeof(ut)) < sizeof(ut))
  {
   (void) close(fd);
   return -1;
  }
 (void) close(fd);
 return 0;
}

int wtmp(line,name,host,date)
char *line;
char *name;
char *host;
long date;
{
 struct utmp wt;
 int fd;

 (void) strncpy(wt.ut_line,line,sizeof(wt.ut_line));
 (void) strncpy(wt.ut_name,name,sizeof(wt.ut_name));
 (void) strncpy(wt.ut_host,host,sizeof(wt.ut_host));
 wt.ut_time = date;

 fd = open(PTYWTMP_FILE,O_WRONLY | O_APPEND);
 if (fd == -1)
   return -1;
 if (write(fd,(char *) &wt,sizeof(wt)) < sizeof(wt))
  {
   (void) close(fd);
   return -1;
  }
 (void) close(fd);
 return 0;
}
