/*--------------------------------------------------------------------------*/
/*																			*/
/*																			*/
/*		------------		 Bit-Bucket Software, Co.						*/
/*		\ 10001101 /		 Writers and Distributors of					*/
/*		 \ 011110 / 		 Freely Available<tm> Software. 				*/
/*		  \ 1011 /															*/
/*		   ------															*/
/*																			*/
/*	(C) Copyright 1987-90, Bit Bucket Software Co., a Delaware Corporation. */
/*																			*/
/*																			*/
/*				  This module was written by Vince Perriello				*/
/*																			*/
/*																			*/
/*					 BinkleyTerm Mail Session Initiator 					*/
/*																			*/
/*																			*/
/*	  For complete	details  of the licensing restrictions, please refer	*/
/*	  to the License  agreement,  which  is published in its entirety in	*/
/*	  the MAKEFILE and BT.C, and also contained in the file LICENSE.240.	*/
/*																			*/
/*	  USE  OF THIS FILE IS SUBJECT TO THE  RESTRICTIONS CONTAINED IN THE	*/
/*	  BINKLEYTERM  LICENSING  AGREEMENT.  IF YOU DO NOT FIND THE TEXT OF	*/
/*	  THIS	AGREEMENT IN ANY OF THE  AFOREMENTIONED FILES,	OR IF YOU DO	*/
/*	  NOT HAVE THESE FILES,  YOU  SHOULD  IMMEDIATELY CONTACT BIT BUCKET	*/
/*	  SOFTWARE CO.	AT ONE OF THE  ADDRESSES  LISTED BELOW.  IN NO EVENT	*/
/*	  SHOULD YOU  PROCEED TO USE THIS FILE	WITHOUT HAVING	ACCEPTED THE	*/
/*	  TERMS  OF  THE  BINKLEYTERM  LICENSING  AGREEMENT,  OR  SUCH OTHER	*/
/*	  AGREEMENT AS YOU ARE ABLE TO REACH WITH BIT BUCKET SOFTWARE, CO.		*/
/*																			*/
/*																			*/
/* You can contact Bit Bucket Software Co. at any one of the following		*/
/* addresses:																*/
/*																			*/
/* Bit Bucket Software Co.		  FidoNet  1:104/501, 1:132/491, 1:141/491	*/
/* P.O. Box 460398				  AlterNet 7:491/0							*/
/* Aurora, CO 80046 			  BBS-Net  86:2030/1						*/
/*								  Internet f491.n132.z1.fidonet.org 		*/
/*																			*/
/* Please feel free to contact us at any time to share your comments about	*/
/* our software and/or licensing policies.									*/
/*																			*/
/*--------------------------------------------------------------------------*/

#include <stdio.h>
#ifdef __TURBOC__
#include <mem.h>
#else
#include <memory.h>
#endif
#include <time.h>

#define WAZOO_SECTION
#define MATRIX_SECTION

#include "com.h"
#include "xfer.h"
#include "zmodem.h"
#include "keybd.h"
#include "sbuf.h"
#include "sched.h"
#include "externs.h"
#include "prototyp.h"
#include "defines.h"

extern int CallerSendSync (void);
extern int CalledRecvSync (void);

void b_session (was_initiator)
int was_initiator;
{
   int i;
   ADDR tmp;

   tmp.Zone = 0;
   tmp.Net = 0;
   tmp.Node = 0;
   tmp.Point = 0;
   tmp.Domain = NULL;
   CurrentNetFiles = DEFAULT.sc_Inbound;

   mail_finished = 0;

   time (&etm);

   freq_accum.bytes = 0L;
   freq_accum.files = 0;

   if (un_attended && fullscreen) {
	  do_ready (msgtxt[M_READY_CONNECT]);
   }

   /* Remove the old .REQ and .RSP files */

   for (i = 0; i < 10; i++) {

	  if (alias[i].Net == 0)
		 break;
	  (void) sprintf (junk, "%s%s.REQ", CurrentNetFiles, Hex_Addr_Str (&(alias[i])));
	  (void) unlink (junk);

	  (void) sprintf (junk, "%s.RSP", Hex_Addr_Str (&(alias[i])));
	  (void) unlink (junk);
   }

   remote_capabilities = 0;
   (void) flag_file (SET_SESSION_FLAG, &called_addr, 0);
   if (was_initiator) {

/*
 *	  OUTBOUND -- meaning call was made by us.
 */

	  last_type (1, &remote_addr);
	  if (Whack_CR ()) {
		 return;
	  }

	  switch (i = CallerSendSync()) {

		 case 1:
			FTSC_sender (0);
			break;

		 case 2:
			if (YooHoo_Sender ()) { 			 /* Send Hello packet,	 */
			   WaZOO (1);
			}
			break;

		 default:
			break;

	  } /* end switch */

   } else {

/*
 *	  INBOUND -- meaning we were connected to by another system.
 */

	  switch (i = CalledRecvSync()) {

		 case 1:								 /* ESCape or Timeout	 */
			if (CARRIER && !mail_only) {
			   last_type (3, &tmp);
			   (void) flag_file (CLEAR_SESSION_FLAG, &called_addr, 0);
			   BBSexit ();
			}
			break;

		 case 2:								 /* FTSC Netmail Session */
			if (CARRIER) {
			   tmp.Zone = -1000;
			   last_type (2, &tmp);
			   tmp.Zone = 0;
			   ++hist.mail_calls;
			   if (un_attended && fullscreen)
				   {
				   sb_move (historywin, HIST_MAIL_ROW, HIST_COL);
				   (void) sprintf (junk, "%d/%d", hist.bbs_calls, hist.mail_calls);
				   sb_puts (historywin, (unsigned char *) junk);
				   sb_show ();
				   }
			   (void) FTSC_receiver (0);
			}
			break;

		 case 3:								 /* WaZOO Netmail Session*/
			if (YooHoo_Receiver ()) {
			   last_type (1, &remote_addr);
			   ++hist.mail_calls;
			   if (un_attended && fullscreen)
				  {
				  sb_move (historywin, HIST_MAIL_ROW, HIST_COL);
				  (void) sprintf (junk, "%d/%d", hist.bbs_calls, hist.mail_calls);
				  sb_puts (historywin, (unsigned char *) junk);
				  }
			   WaZOO (0);						 /* do WaZOO!!! 		 */
			}
			break;

		 default:
			if ((i >= 5) && (i < (5 + num_ext_mail))) { /*See if ext mail*/
			   if (CARRIER) {
				  last_type (4, &tmp);
				  (void) flag_file (CLEAR_SESSION_FLAG, &called_addr, 0);
				  UUCPexit (lev_ext_mail[i-5]);
			   }
			}
			break;

	  } /* end switch */

   } /* end if (was_initiator) */

   (void) flag_file (CLEAR_SESSION_FLAG, &called_addr, 0);
   return;
}


void b_init () {
   got_arcmail = got_packet = got_mail = sent_mail = 0;
   remote_addr.Zone = remote_addr.Net = remote_addr.Node = remote_addr.Point = 0;
   remote_addr.Domain = NULL;
   Netmail_Session = remote_capabilities = mail_finished = 0;
   CurrentNetFiles = DEFAULT.sc_Inbound;
}


/*
 * Send banner-type lines to remote. Since strange modems like Courier HST
 * have a propensity for thinking they are connected when talking to a dial
 * tone (but do leave CTS down just to screw us up) we have to use a timeout
 * to figure out if we are in trouble, and if so, we drop DTR to make the
 * bogus carrier go away.
 *
 * This routine is used in modules B_BBS.C and RECVSYNC.C, both of which
 * are called from this module only.
 *
 */

int SendBanner (string)
char *string;
{
   long t1;
   register char c;

   t1 = timerset (600); 						/* 60 seconds max to put out
												 * banner */

   while (!timeup (t1) && CARRIER) {

	  if (got_ESC ())							/* Manual abort?	 */
			break;								/* Use failure logic */

	  if (!OUT_FULL ()) {

		 c = *string++;
		 if (!c || c == 0x1a)					/* Test for end 	 */
			return (1); 						/* Yes, success 	 */
		 SENDBYTE ((unsigned char) c);
	  }
   }

   /*
	* If we get here we had trouble. Drop DTR now to hopefully get out of
	* this trouble. Flush outbound. Pause for 1 second.
	*/

   DTR_OFF ();
   CLEAR_OUTBOUND ();

   timer (10);

   CLEAR_INBOUND ();

   return (0);
}


int flag_file (function, address, do_stat)
int function;
ADDR *address;
int do_stat;
{

   FILE *fptr;
   char *HoldName;
   static ADDR last_set;
   char flagname[128];
   char tmpname[128];

   if (!TaskNumber)
	  return (FALSE);

   HoldName = HoldAreaNameMunge (address);

   switch (function)
	  {
	  case INITIALIZE:
	  last_set.Zone = -1;
	  break;

	  case SET_SESSION_FLAG:
	  /* At the start of a session, set up the task number */
	  if (flag_dir)
		 {
		 sprintf (flagname, "%sTask.%d",
							   flag_dir, TaskNumber);
		 fptr = fopen (flagname, "wb");
		 fclose (fptr);
		 }
	  return (FALSE);

	  case CLEAR_SESSION_FLAG:
	  /* At the end of a session, delete the task file */
	  if (flag_dir)
		 {
		 sprintf (flagname, "%sTask.%d",
							   flag_dir, TaskNumber);
		 unlink (flagname);
		 }
	  return (FALSE);

	  case TEST_AND_SET:

   /*
	* First see if we already HAVE this lock! If so, return now.
	*
	*/

	  if (memcmp (&last_set, address, sizeof (ADDR)) == 0)
		 return (FALSE);

   /*
	* Check for the INMAIL.$$$ file.
	*
	*/

	  if (flag_dir != NULL)
		 {
		 sprintf (tmpname, "%sINMAIL.$$$",flag_dir);

		 if ((fptr = fopen (tmpname, "rb")) != NULL)
			{
			fclose (fptr);
			if (!CARRIER)
			   if (do_stat)
				  status_line (":Other Node Processing Mail");
			return (TRUE);
			}
		 }

   /*
	* Next create a file using a temporary name.
	*
	*/

	  sprintf (tmpname, "%sBINK%04x.BSY",HoldName,TaskNumber);
	  fptr = fopen (tmpname, "wb");
	  if (fptr == NULL)
		 {
		 if (do_stat)
			status_line (msgtxt[M_FAILED_CREATE_FLAG],tmpname);
		 return (TRUE);
		 }
	  fclose (fptr);

   /*
	* Now the test&set. Attempt to rename the file.
	* If we succeed, we have the lock. If we do not,
	* delete the temp file.
	*
	*/

	  sprintf (flagname, "%s%04x%04x.BSY",
							HoldName, address->Net,address->Node);
	  if (!rename (tmpname, flagname))
		 {
		 if (do_stat)
			status_line (msgtxt[M_CREATED_FLAGFILE],flagname);
		 memcpy (&last_set, address, sizeof (ADDR));
		 return (FALSE);
		 }
	  if (do_stat)
		 status_line (msgtxt[M_THIS_ADDRESS_LOCKED], Full_Addr_Str (address));
	  unlink (tmpname);
	  return (TRUE);

	  case CLEAR_FLAG:

   /*
	* Make sure we need to clear something.
	* Zone should be something other than -1 if that's the case.
	*
	*/
	  if (last_set.Zone == -1)
		 return (TRUE);

   /*
	* Next compare what we want to clear with what we think we have.
	*
	*/

	  if (memcmp (&last_set, address, sizeof (ADDR)) != 0)
		 {
		 if (do_stat)
			status_line (msgtxt[M_BAD_CLEAR_FLAGFILE],
							Full_Addr_Str (address));
		 return (TRUE);
		 }
   /*
	* We match. Unlink the flag file. If we're successful, jam a -1
	* into our saved Zone.
	*
	*/

	  sprintf (flagname, "%s%04x%04x.BSY",
							HoldName, address->Net,address->Node);
	  if (!unlink (flagname))
		 {
		 if (do_stat)
			status_line (msgtxt[M_CLEARED_FLAGFILE], flagname);
		 last_set.Zone = -1;
		 return (TRUE);
		 }

	  if (do_stat)
		 status_line (msgtxt[M_FAILED_CLEAR_FLAG],flagname);
	  return (FALSE);

	  default:
	  break;
	  }

   return (TRUE);
}

