#include <sys/stat.h>
#include "error.h"
#include "pathexec.h"
#include "prot.h"
#include "stralloc.h"
#include "openreadclose.h"
#include "env.h"

#include "global.h"
#include "md5.h"
#include "hmac_md5.h"

#include "auto_maildir.h"
#include "auto_password.h"
#include "auto_patrn.h"

#include <pwd.h>
static struct passwd *pw;

static char up[513];
static int uplen;
static char hextab[]="0123456789abcdef";

static stralloc stored = {0};
static stralloc pwfile = {0};

void cleanup()
{
  int i;
  for (i = 0;i < sizeof(up);++i) up[i] = 0;
  for (i = 0;i < stored.len;++i) stored.s[i] = 0;
}

void die(int x)
{
  cleanup();
  _exit(x);
}

int doit(unsigned char *password, unsigned char *login, unsigned char *challenge, unsigned char *response)
{
  unsigned char digest[16];
  unsigned char digascii[33];
  unsigned char h;
  int j;

  hmac_md5(challenge, strlen(challenge), password, strlen(password), digest);

  digascii[32]=0;
  for (j=0; j<16; j++)
    {
      h=digest[j] >> 4;
      digascii[2*j]=hextab[h];
      h=digest[j] & 0x0f;
      digascii[(2*j)+1]=hextab[h];
    }
  return(strcmp(digascii,response) && strcmp(password,challenge));
}

void main(int argc,char **argv)
{
  char *login;
  char *password;
  char *response;
  char *challenge;
  struct stat st;
  int r;
  int i;
 
  if (!argv[1]) _exit(2);
 
  uplen = 0;
  for (;;) {
    do
      r = read(3,up + uplen,sizeof(up) - uplen);
    while ((r == -1) && (errno == error_intr));
    if (r == -1) _exit(111);
    if (r == 0) break;
    uplen += r;
    if (uplen >= sizeof(up)) _exit(1);
  }
  close(3);

  i = 0;
  login = up + i;
  while (up[i++]) if (i == uplen) _exit(2);
  challenge = up + i;
  if (i == uplen) _exit(2);
  while (up[i++]) if (i == uplen) _exit(2);
  response = up + i;

  i = 0;
  pw = getpwnam(login);
  if (!pw) die(111);
  if (prot_gid((int) pw->pw_gid) != 0) die(1);
  if (prot_uid((int) pw->pw_uid) != 0) die(1);
  if (chdir(pw->pw_dir) != 0) die(111);

  if (!stralloc_copys(&pwfile, auto_maildir)) die(111);
  if (!stralloc_append(&pwfile, "/")) die(111);
  if (!stralloc_cats(&pwfile, auto_password)) die(111);
  if (!stralloc_0(&pwfile)) die(111);
  if (stat(pwfile.s,&st) == -1) die(1);
  if (st.st_uid != pw->pw_uid) die(1);
  if (st.st_mode & auto_patrn) die(111);
  if (openreadclose(pwfile.s,&stored,32) != 1) die(111);
  if (!stralloc_0(&stored)) die(111);
  stored.s[str_chr(stored.s,'\n')] = 0;

  if (!*stored.s || doit(stored.s,login,challenge,response)) die(1);

  if (!pathexec_env("USER",pw->pw_name)) die(111);
  if (!pathexec_env("HOME",pw->pw_dir)) die(111);
  if (!pathexec_env("SHELL",pw->pw_shell)) die(111);
  cleanup();
  pathexec(argv + 1);
  _exit(111);
}
