/**********************************************************************
 * ti library's connection routine
 *
 * $Author: brlewis $
 * $Source: /afs/net.mit.edu/dev/project/techinfodev/src/libti/RCS/connect.c,v $
 * $Header: /afs/net.mit.edu/dev/project/techinfodev/src/libti/RCS/connect.c,v 2.2 93/02/25 10:04:32 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/dev/project/techinfodev/src/libti/RCS/connect.c,v 2.2 93/02/25 10:04:32 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 *tp)
 *
 * - connects to server
 * - fills in banner
 * - returns error code
 **********************************************************************/

long
ti_connect(tp)
     TI *tp;
{
  long code;
  char buf[BUFSIZ+1];

  /* if this is a reconnection, close before reopening */
  if (tp->links && tp->sock > 0)
    {
      close(tp->sock);
    }

  /* create a new network socket */
  tp->sock = socket(PF_INET, SOCK_STREAM, 0);
  if (tp->sock < 0)
    {
      strcpy(ti_context, "creating socket");
      return((long) errno);
    }

  /* make a connection to the specified server on the socket */
  if (connect(tp->sock, &(tp->sname), sizeof(tp->sname)) < 0)
    {
      strcpy(ti_context, ti_host(tp));
      return((long) errno);
    }

  /* get the banner message */
  if (code=_ti_recvmsg(tp, buf, BUFSIZ))
    {
      strcpy(ti_context, ti_host(tp));
      return(code);
    }

  /* handle motd or error */
  switch(atoi(buf))
    {
    case 0:			/* success */
      break;
    case 100:			/* error */
      ti_close(tp);
      strcpy(ti_context, buf+4);
      return(TI_ERR_SRV);
    default:			/* motd (101-199) */
      tp->flags |= TI_FMOTD;
      strcpy(buf, buf+4);
    }

  /* Success!  Get banner. */
  if (ti_banner(tp)) free(ti_banner(tp));
  TI_MEM(ti_banner(tp) = newstring(buf+2));
  strcpy(ti_banner(tp), buf+2);

  /* tell server not to lie about flag field */
  _ti_talk(tp, "O:2", 3, buf, BUFSIZ);

  /* reauthenticate if appropriate */
  if (ti_user(tp))
    return(ti_auth(tp,
		   ti_user(tp),
		   ti_password(tp)));
  return(0L);
}
