/**********************************************************************
 * ti library's connection routine
 *
 * $Author: brlewis $
 * $Source: /afs/net.mit.edu/dapps/project/techinfodev/src/libti/RCS/connect.c,v $
 * $Header: /afs/net.mit.edu/dapps/project/techinfodev/src/libti/RCS/connect.c,v 0.2 92/07/09 17:09:29 brlewis Exp $
 *
 * Copyright 1991 by the Massachusetts Institute of Technology.
 *
 * For copying and distribution information, please see the file
 * <mit-copyright.h>.
 **********************************************************************/

#include <mit-copyright.h>

#ifndef lint
static char rcsid_ti_connect_c[] = "$Header: /afs/net.mit.edu/dapps/project/techinfodev/src/libti/RCS/connect.c,v 0.2 92/07/09 17:09:29 brlewis Exp $";
#endif /* lint */

#include <sys/types.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <ti/memory.h>
#include <ti/ti.h>

/**********************************************************************
 * ti_connect(TI_H *hti)
 *
 * - connects to server
 * - fills in banner
 * - returns error code
 **********************************************************************/

/* jms 7/9/92 -- windows-izing begun. */

long
ti_connect(hti)
     TI_H hti;
{
  long code;
  char buf[BUFSIZ+1];
  TI_LP lpti;

  lpti = (TI_LP)TI_DEREFERENCE(hti);

  /* if this is a reconnection, close before reopening */
  if (lpti->links && lpti->sock > 0)
    {
      close(lpti->sock);
    }

  /* create a new network socket */
  lpti->sock = socket(PF_INET, SOCK_STREAM, 0);
  if (lpti->sock < 0)
    {
      strcpy(ti_context, "creating socket");
      CLEANUP_AND_RETURN((long) errno)
    }

  /* make a connection to the specified server on the socket */
  if (connect(lpti->sock, &(lpti->sname), sizeof(lpti->sname)) < 0)
    {
      strcpy(ti_context, "connecting");
      CLEANUP_AND_RETURN((long) errno)
    }

  /* get the banner message */
  if (code=_ti_recvmsg(hti, buf, BUFSIZ))
    {
      strcpy(ti_context, "reading banner message");
      CLEANUP_AND_RETURN(code)
    }

  /* handle motd or error */
  switch(atoi(buf))
    {
    case 0:			/* success */
      break;
    case 100:			/* error */
      ti_close(hti);
      strcpy(ti_context, buf+4);
      CLEANUP_AND_RETURN(TI_ERR_SRV)
    default:			/* motd (101-199) */
      lpti->flags |= TI_FMOTD;
      strcpy(buf, buf+4);
    }

/* !!! */
  if (ti_banner(lpti)) free(ti_banner(lpti));
  TI_MEM(ti_banner(lpti) = newstring(buf));
  strcpy(ti_banner(lpti), buf);

  /* reauthenticate if appropriate */
  if (ti_user(lpti))
    CLEANUP_AND_RETURN(ti_auth(lpti, ti_user(lpti), ti_password(lpti)))

CLEANUP:
  TI_REMOVE_DEREFERENCE(hti);
  return(code);
}
