/*
   axgetmail
   (c) 1999 by Radek Burget OK2JBG

   This program 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
   2 of the license, or (at your option) any later version.

   auth: execute the authorization script
*/

#include <stdio.h>
#include <unistd.h>
#include <signal.h>
#include <errno.h>
#include <sys/fcntl.h>
#include "common.h"
#include "auth.h"

#define BUFSIZE 1024

/* run the authorization agent and wait until it exits */
void exec_auth_agent(FILE *bbs_stream, char *mycall, char *bbscall)
{
  int pid;
  int pipe_in[2], pipe_out[2];

  signal(SIGPIPE, SIG_IGN);
  pipe(pipe_in);
  pipe(pipe_out);
  pid = fork();
  if (pid == -1) perror("Cannot fork()");

  if (pid == 0) /* child process */
  {
    close(pipe_in[0]);
    dup2(pipe_in[1], 1); //stdout
    close(pipe_out[1]);
    dup2(pipe_out[0], 0); //stdin;
    execlp(AUTH_AGENT, AUTH_AGENT, bbscall, mycall, NULL);
    perror("execlp");
    exit(1);
  }
  else /* parent process */
  {
    char buf[BUFSIZE];
    int r1, r2, i;
    int descin, descout;
    
    message(MSG_DEBUG, "redirecting authorization data\n");
    close(pipe_in[1]);
    close(pipe_out[0]);
    fcntl(pipe_in[0], F_SETFL, O_NONBLOCK);
    descin = descout = fileno(bbs_stream);
    while (1)
    {
      r1 = read(pipe_in[0], buf, BUFSIZE);
      for (i = 0; i < r1; i++) if (buf[i] == '\n') buf[i] = '\r';
      if (r1 > 0) write(descout, buf, r1);
      else if (r1 == 0 || errno != EAGAIN) break;

      if (r1 != -1) //don't read data from BBS until we're sure we'll do
                    //some authorization
      {
        r2 = read(descin, buf, BUFSIZE);
        for (i = 0; i < r2; i++) if (buf[i] == '\r') buf[i] = '\n';
        if (r2 > 0) write(pipe_out[1], buf, r2);
        else if (r2 == 0 || errno != EAGAIN) break;
      }
    }
    kill(pid, SIGTERM);
  }
}

