home *** CD-ROM | disk | FTP | other *** search
/ InfoMagic Internet Tools 1993 July / Internet Tools.iso / RockRidge / mail / pine / pine3.07 / c-client / os_nxt.c < prev    next >
Encoding:
C/C++ Source or Header  |  1992-05-14  |  15.8 KB  |  545 lines

  1. /*
  2.  * Program:    Operating-system dependent routines -- NeXT version
  3.  *
  4.  * Author:    Mark Crispin
  5.  *        Networks and Distributed Computing
  6.  *        Computing & Communications
  7.  *        University of Washington
  8.  *        Administration Building, AG-44
  9.  *        Seattle, WA  98195
  10.  *        Internet: MRC@CAC.Washington.EDU
  11.  *
  12.  * Date:    11 May 1989
  13.  * Last Edited:    14 May 1992
  14.  *
  15.  * Copyright 1992 by the University of Washington.
  16.  *
  17.  *  Permission to use, copy, modify, and distribute this software and its
  18.  * documentation for any purpose and without fee is hereby granted, provided
  19.  * that the above copyright notice appears in all copies and that both the
  20.  * above copyright notice and this permission notice appear in supporting
  21.  * documentation, and that the name of the University of Washington not be
  22.  * used in advertising or publicity pertaining to distribution of the software
  23.  * without specific, written prior permission.  This software is made available
  24.  * "as is", and
  25.  * THE UNIVERSITY OF WASHINGTON DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED,
  26.  * WITH REGARD TO THIS SOFTWARE, INCLUDING WITHOUT LIMITATION ALL IMPLIED
  27.  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, AND IN
  28.  * NO EVENT SHALL THE UNIVERSITY OF WASHINGTON BE LIABLE FOR ANY SPECIAL,
  29.  * INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  30.  * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, TORT
  31.  * (INCLUDING NEGLIGENCE) OR STRICT LIABILITY, ARISING OUT OF OR IN CONNECTION
  32.  * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  33.  *
  34.  */
  35.  
  36. /* TCP input buffer */
  37.  
  38. #define BUFLEN 8192
  39.  
  40.  
  41. /* TCP I/O stream (must be before osdep.h is included) */
  42.  
  43. #define TCPSTREAM struct tcp_stream
  44. TCPSTREAM {
  45.   char *host;            /* host name */
  46.   char *localhost;        /* local host name */
  47.   int tcpsi;            /* input socket */
  48.   int tcpso;            /* output socket */
  49.   int ictr;            /* input counter */
  50.   char *iptr;            /* input pointer */
  51.   char ibuf[BUFLEN];        /* input buffer */
  52. };
  53.  
  54.  
  55. #include <sys/types.h>
  56. #include <sys/time.h>
  57. #include <sys/socket.h>
  58. #include <netinet/in.h>
  59. #include <netdb.h>
  60. #include <ctype.h>
  61. #include <errno.h>
  62. extern int errno;        /* just in case */
  63. #include <pwd.h>
  64. #include <syslog.h>
  65. #include "osdep.h"
  66. #include "mail.h"
  67. #include "misc.h"
  68. extern char *crypt();
  69.  
  70. /* Write current time in RFC 822 format
  71.  * Accepts: destination string
  72.  */
  73.  
  74. char *days[] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
  75. char *months[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
  76.         "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
  77.  
  78. void rfc822_date (char *date)
  79. {
  80.   int zone;
  81.   char *zonename;
  82.   struct tm *t;
  83.   struct timeval tv;
  84.   struct timezone tz;
  85.   gettimeofday (&tv,&tz);    /* get time and timezone poop */
  86.   t = localtime (&tv.tv_sec);    /* convert to individual items */
  87.   zone = t->tm_gmtoff/60;    /* get timezone from TZ environment stuff */
  88.   zonename = t->tm_zone;
  89.                 /* and output it */
  90.   sprintf (date,"%s, %d %s %d %02d:%02d:%02d %+03d%02d (%s)",
  91.        days[t->tm_wday],t->tm_mday,months[t->tm_mon],t->tm_year+1900,
  92.        t->tm_hour,t->tm_min,t->tm_sec,zone/60,abs (zone) % 60,zonename);
  93. }
  94.  
  95. /* Get a block of free storage
  96.  * Accepts: size of desired block
  97.  * Returns: free storage block
  98.  */
  99.  
  100. void *fs_get (size_t size)
  101. {
  102.   void *block = malloc (size);
  103.   if (!block) fatal ("Out of free storage");
  104.   return (block);
  105. }
  106.  
  107.  
  108. /* Resize a block of free storage
  109.  * Accepts: ** pointer to current block
  110.  *        new size
  111.  */
  112.  
  113. void fs_resize (void **block,size_t size)
  114. {
  115.   if (!(*block = realloc (*block,size))) fatal ("Can't resize free storage");
  116. }
  117.  
  118.  
  119. /* Return a block of free storage
  120.  * Accepts: ** pointer to free storage block
  121.  */
  122.  
  123. void fs_give (void **block)
  124. {
  125.   free (*block);
  126.   *block = NIL;
  127. }
  128.  
  129.  
  130. /* Report a fatal error
  131.  * Accepts: string to output
  132.  */
  133.  
  134. void fatal (char *string)
  135. {
  136.   mm_fatal (string);        /* pass up the string */
  137.   syslog (LOG_ALERT,"IMAP C-Client crash: %s",string);
  138.   abort ();            /* die horribly */
  139. }
  140.  
  141. /* Copy string with CRLF newlines
  142.  * Accepts: destination string
  143.  *        pointer to size of destination string
  144.  *        source string
  145.  *        length of source string
  146.  */
  147.  
  148. char *strcrlfcpy (char **dst,unsigned long *dstl,char *src,unsigned long srcl)
  149. {
  150.   long i,j;
  151.   char *d = src;
  152.                 /* count number of LF's in source string(s) */
  153.   for (i = srcl,j = 0; j < srcl; j++) if (*d++ == '\012') i++;
  154.   if (i > *dstl) {        /* resize if not enough space */
  155.     fs_give ((void **) dst);    /* fs_resize does an unnecessary copy */
  156.     *dst = (char *) fs_get ((*dstl = i) + 1);
  157.   }
  158.   d = *dst;            /* destination string */
  159.                 /* copy strings, inserting CR's before LF's */
  160.   while (srcl--) switch (*src) {
  161.   case '\015':            /* unlikely carriage return */
  162.     *d++ = *src++;        /* copy it and any succeeding linefeed */
  163.     if (srcl && *src == '\012') {
  164.       *d++ = *src++;
  165.       srcl--;
  166.     }
  167.     break;
  168.   case '\012':            /* line feed? */
  169.     *d++ ='\015';        /* yes, prepend a CR, drop into default case */
  170.   default:            /* ordinary chararacter */
  171.     *d++ = *src++;        /* just copy character */
  172.     break;
  173.   }
  174.   *d = '\0';            /* tie off destination */
  175.   return *dst;            /* return destination */
  176. }
  177.  
  178.  
  179. /* Length of string after strcrlflen applied
  180.  * Accepts: source string
  181.  *        length of source string
  182.  */
  183.  
  184. unsigned long strcrlflen (char *src,unsigned long srcl)
  185. {
  186.   long i = srcl;        /* look for LF's */
  187.   while (srcl--) switch (*src++) {
  188.   case '\015':            /* unlikely carriage return */
  189.     if (srcl && *src == '\012') { src++; srcl--; }
  190.     break;
  191.   case '\012':            /* line feed? */
  192.     i++;
  193.   default:            /* ordinary chararacter */
  194.     break;
  195.   }
  196.   return i;
  197. }
  198.  
  199. /* Server log in
  200.  * Accepts: user name string
  201.  *        password string
  202.  *        optional place to return home directory
  203.  * Returns: T if password validated, NIL otherwise
  204.  */
  205.  
  206. long server_login (char *user,char *pass,char **home)
  207. {
  208.   struct passwd *pw = getpwnam (lcase (user));
  209.                 /* no entry for this user or root */
  210.   if (!(pw && pw->pw_uid)) return NIL;
  211.                 /* validate password */
  212.   if (strcmp (pw->pw_passwd,(char *) crypt (pass,pw->pw_passwd))) return NIL;
  213.   setgid (pw->pw_gid);        /* all OK, login in as that user */
  214.   setuid (pw->pw_uid);
  215.                 /* note home directory */
  216.   if (home) *home = cpystr (pw->pw_dir);
  217.   return T;
  218. }
  219.   
  220. /* TCP/IP open
  221.  * Accepts: host name
  222.  *        contact port number
  223.  * Returns: TCP/IP stream if success else NIL
  224.  */
  225.  
  226. TCPSTREAM *tcp_open (char *host,int port)
  227. {
  228.   TCPSTREAM *stream = NIL;
  229.   int sock;
  230.   char *s;
  231.   struct sockaddr_in sin;
  232.   struct hostent *host_name;
  233.   char hostname[MAILTMPLEN];
  234.   char tmp[MAILTMPLEN];
  235.   /* The domain literal form is used (rather than simply the dotted decimal
  236.      as with other Unix programs) because it has to be a valid "host name"
  237.      in mailsystem terminology. */
  238.                 /* look like domain literal? */
  239.   if (host[0] == '[' && host[(strlen (host))-1] == ']') {
  240.     strcpy (hostname,host+1);    /* yes, copy number part */
  241.     hostname[(strlen (hostname))-1] = '\0';
  242.     if ((sin.sin_addr.s_addr = inet_addr (hostname)) != -1) {
  243.       sin.sin_family = AF_INET;    /* family is always Internet */
  244.       strcpy (hostname,host);    /* hostname is user's argument */
  245.     }
  246.     else {
  247.       sprintf (tmp,"Bad format domain-literal: %.80s",host);
  248.       mm_log (tmp,ERROR);
  249.       return NIL;
  250.     }
  251.   }
  252.  
  253.   else {            /* lookup host name, note that brain-dead Unix
  254.                    requires lowercase! */
  255.     strcpy (hostname,host);    /* in case host is in write-protected memory */
  256.     if ((host_name = gethostbyname (lcase (hostname)))) {
  257.                 /* copy address type */
  258.       sin.sin_family = host_name->h_addrtype;
  259.                 /* copy host name */
  260.       strcpy (hostname,host_name->h_name);
  261.                 /* copy host addresses */
  262.       memcpy (&sin.sin_addr,host_name->h_addr,host_name->h_length);
  263.     }
  264.     else {
  265.       switch (h_errno) {
  266.     case HOST_NOT_FOUND:    /* authoritative error */
  267.       s = "No such host as %.80s";
  268.       break;
  269.     case TRY_AGAIN:        /* non-authoritative error */
  270.       s = "Transient error for host %.80s, try again";
  271.       break;
  272.     case NO_RECOVERY:    /* non-recoverable errors */
  273.       s = "Non-recoverable error looking up host %.80s";
  274.       break;
  275.     case NO_DATA:        /* no data record of requested type */
  276.       s = "No IP address known for host %.80s";
  277.       break;
  278.     default:
  279.       s = "Unknown error for host %.80s";
  280.       break;
  281.       }
  282.       sprintf (tmp,s,host);
  283.       mm_log (tmp,ERROR);
  284.       return NIL;
  285.     }
  286.   }
  287.  
  288.                 /* copy port number in network format */
  289.   if (!(sin.sin_port = htons (port))) fatal ("Bad port argument to tcp_open");
  290.                 /* get a TCP stream */
  291.   if ((sock = socket (sin.sin_family,SOCK_STREAM,0)) < 0) {
  292.     sprintf (tmp,"Unable to create TCP socket: %s",strerror (errno));
  293.     mm_log (tmp,ERROR);
  294.     return NIL;
  295.   }
  296.                 /* open connection */
  297.   if (connect (sock,(struct sockaddr *)&sin,sizeof (sin)) < 0) {
  298.     sprintf (tmp,"Can't connect to %.80s,%d: %s",hostname,port,
  299.          strerror (errno));
  300.     mm_log (tmp,ERROR);
  301.     return NIL;
  302.   }
  303.                 /* create TCP/IP stream */
  304.   stream = (TCPSTREAM *) fs_get (sizeof (TCPSTREAM));
  305.                 /* copy official host name */
  306.   stream->host = cpystr (hostname);
  307.                 /* get local name */
  308.   gethostname (tmp,MAILTMPLEN-1);
  309.   stream->localhost = cpystr ((host_name = gethostbyname (tmp)) ?
  310.                   host_name->h_name : tmp);
  311.                 /* init sockets */
  312.   stream->tcpsi = stream->tcpso = sock;
  313.   stream->ictr = 0;        /* init input counter */
  314.   return stream;        /* return success */
  315. }
  316.   
  317. /* TCP/IP authenticated open
  318.  * Accepts: host name
  319.  *        service name
  320.  * Returns: TCP/IP stream if success else NIL
  321.  */
  322.  
  323. TCPSTREAM *tcp_aopen (char *host,char *service)
  324. {
  325.   TCPSTREAM *stream = NIL;
  326.   struct hostent *host_name;
  327.   char hostname[MAILTMPLEN];
  328.   int i;
  329.   int pipei[2],pipeo[2];
  330.   /* The domain literal form is used (rather than simply the dotted decimal
  331.      as with other Unix programs) because it has to be a valid "host name"
  332.      in mailsystem terminology. */
  333.                 /* look like domain literal? */
  334.   if (host[0] == '[' && host[i = (strlen (host))-1] == ']') {
  335.     strcpy (hostname,host+1);    /* yes, copy without brackets */
  336.     hostname[i-1] = '\0';
  337.   }
  338.                 /* note that Unix requires lowercase! */
  339.   else if (host_name = gethostbyname (lcase (strcpy (hostname,host))))
  340.     strcpy (hostname,host_name->h_name);
  341.                 /* make command pipes */
  342.   if (pipe (pipei) < 0) return NIL;
  343.   if (pipe (pipeo) < 0) {
  344.     close (pipei[0]); close (pipei[1]);
  345.     return NIL;
  346.   }
  347.   if ((i = fork ()) < 0) {    /* make inferior process */
  348.     close (pipei[0]); close (pipei[1]);
  349.     close (pipeo[0]); close (pipeo[1]);
  350.     return NIL;
  351.   }
  352.   if (i) {            /* parent? */
  353.     close (pipei[1]);        /* close child's side of the pipes */
  354.     close (pipeo[0]);
  355.   }
  356.   else {            /* child */
  357.     dup2 (pipei[1],1);        /* parent's input is my output */
  358.     dup2 (pipei[1],2);        /* parent's input is my error output too */
  359.     close (pipei[0]); close (pipei[1]);
  360.     dup2 (pipeo[0],0);        /* parent's output is my input */
  361.     close (pipeo[0]); close (pipeo[1]);
  362.                 /* now run it */
  363.     execl ("/usr/ucb/rsh","rsh",hostname,"exec",service,0);
  364.     _exit (1);            /* spazzed */
  365.   }
  366.  
  367.                 /* create TCP/IP stream */
  368.   stream = (TCPSTREAM *) fs_get (sizeof (TCPSTREAM));
  369.                 /* copy official host name */
  370.   stream->host = cpystr (hostname);
  371.                 /* get local name */
  372.   gethostname (hostname,MAILTMPLEN-1);
  373.   stream->localhost = cpystr ((host_name = gethostbyname (hostname)) ?
  374.                   host_name->h_name : hostname);
  375.   stream->tcpsi = pipei[0];    /* init sockets */
  376.   stream->tcpso = pipeo[1];
  377.   stream->ictr = 0;        /* init input counter */
  378.   return stream;        /* return success */
  379. }
  380.  
  381. /* TCP/IP receive line
  382.  * Accepts: TCP/IP stream
  383.  * Returns: text line string or NIL if failure
  384.  */
  385.  
  386. char *tcp_getline (TCPSTREAM *stream)
  387. {
  388.   int n,m;
  389.   char *st;
  390.   char *ret;
  391.   char *stp;
  392.   char tmp[2];
  393.   fd_set fds;
  394.   FD_ZERO (&fds);        /* initialize selection vector */
  395.   if (stream->tcpsi < 0) return NIL;
  396.   while (stream->ictr < 1) {    /* if nothing in the buffer */
  397.     FD_SET (stream->tcpsi,&fds);/* set bit in selection vector */
  398.                 /* block and read */
  399.     if ((select (stream->tcpsi+1,&fds,0,0,0) < 0) ||
  400.     ((stream->ictr = read (stream->tcpsi,stream->ibuf,BUFLEN)) < 1)) {
  401.       close (stream->tcpsi);    /* nuke the socket */
  402.       if (stream->tcpsi != stream->tcpso) close (stream->tcpso);
  403.       stream->tcpsi = stream->tcpso = -1;
  404.       return NIL;
  405.     }
  406.     stream->iptr = stream->ibuf;/* point at TCP buffer */
  407.   }
  408.   st = stream->iptr;        /* save start of string */
  409.   n = 0;            /* init string count */
  410.   while (stream->ictr--) {    /* look for end of line */
  411.                 /* saw the trailing CR? */
  412.     if (stream->iptr++[0] == '\015') {
  413.       ret = (char *) fs_get (n+1);
  414.       memcpy (ret,st,n);    /* copy into a free storage string */
  415.       ret[n] = '\0';        /* tie off string with null */
  416.                 /* eat the line feed */
  417.       tcp_getbuffer (stream,1,tmp);
  418.       return ret;        /* return it to caller */
  419.     }
  420.     ++n;            /* else count and try next character */
  421.   }
  422.   stp = (char *) fs_get (n);    /* copy first part of string */
  423.   memcpy (stp,st,n);
  424.                 /* recurse to get remainder */
  425.   if (st = tcp_getline (stream)) {
  426.                 /* build total string */
  427.     ret = (char *) fs_get (n+1+(m = strlen (st)));
  428.     memcpy (ret,stp,n);        /* copy first part */
  429.     memcpy (ret+n,st,m);    /* and second part */
  430.     ret[n+m] = '\0';        /* tie off string with null */
  431.     fs_give ((void **) &st);    /* flush partial string */
  432.     fs_give ((void **) &stp);    /* flush initial fragment */
  433.   }
  434.   else ret = stp;        /* return the fragment */
  435.   return ret;
  436. }
  437.  
  438. /* TCP/IP receive buffer
  439.  * Accepts: TCP/IP stream
  440.  *        size in bytes
  441.  *        buffer to read into
  442.  * Returns: T if success, NIL otherwise
  443.  */
  444.  
  445. long tcp_getbuffer (TCPSTREAM *stream,unsigned long size,char *buffer)
  446. {
  447.   unsigned long n;
  448.   char *bufptr = buffer;
  449.   fd_set fds;
  450.   FD_ZERO (&fds);        /* initialize selection vector */
  451.   if (stream->tcpsi < 0) return NIL;
  452.   while (size > 0) {        /* until request satisfied */
  453.     while (stream->ictr < 1) {    /* if nothing in the buffer */
  454.       FD_SET (stream->tcpsi,&fds);
  455.                 /* block and read */
  456.       if ((select (stream->tcpsi+1,&fds,0,0,0) < 0) ||
  457.       ((stream->ictr = read (stream->tcpsi,stream->ibuf,BUFLEN)) < 1)) {
  458.     close (stream->tcpsi);    /* nuke the socket */
  459.     if (stream->tcpsi != stream->tcpso) close (stream->tcpso);
  460.     stream->tcpsi = stream->tcpso = -1;
  461.     return NIL;
  462.       }
  463.                 /* point at TCP buffer */
  464.       stream->iptr = stream->ibuf;
  465.     }
  466.     n = min (size,stream->ictr);/* number of bytes to transfer */
  467.                 /* do the copy */
  468.     memcpy (bufptr,stream->iptr,n);
  469.     bufptr += n;        /* update pointer */
  470.     stream->iptr +=n;
  471.     size -= n;            /* update # of bytes to do */
  472.     stream->ictr -=n;
  473.   }
  474.   bufptr[0] = '\0';        /* tie off string */
  475.   return T;
  476. }
  477.  
  478. /* TCP/IP send string as record
  479.  * Accepts: TCP/IP stream
  480.  * Returns: T if success else NIL
  481.  */
  482.  
  483. long tcp_soutr (TCPSTREAM *stream,char *string)
  484. {
  485.   int i;
  486.   unsigned long size = strlen (string);
  487.   fd_set fds;
  488.   FD_ZERO (&fds);        /* initialize selection vector */
  489.   if (stream->tcpso < 0) return NIL;
  490.   while (size > 0) {        /* until request satisfied */
  491.     FD_SET (stream->tcpso,&fds);/* set bit in selection vector */
  492.     if ((select (stream->tcpso+1,0,&fds,0,0) < 0) ||
  493.     ((i = write (stream->tcpso,string,size)) < 0)) {
  494.       puts (strerror (errno));
  495.       close (stream->tcpsi);    /* nuke the socket */
  496.       if (stream->tcpsi != stream->tcpso) close (stream->tcpso);
  497.       stream->tcpsi = stream->tcpso = -1;
  498.       return NIL;
  499.     }
  500.     size -= i;            /* count this size */
  501.     string += i;
  502.   }
  503.   return T;            /* all done */
  504. }
  505.  
  506.  
  507. /* TCP/IP close
  508.  * Accepts: TCP/IP stream
  509.  */
  510.  
  511. void tcp_close (TCPSTREAM *stream)
  512. {
  513.  
  514.   if (stream->tcpsi >= 0) {    /* no-op if no socket */
  515.     close (stream->tcpsi);    /* nuke the socket */
  516.     if (stream->tcpsi != stream->tcpso) close (stream->tcpso);
  517.     stream->tcpsi = stream->tcpso = -1;
  518.   }
  519.                 /* flush host names */
  520.   fs_give ((void **) &stream->host);
  521.   fs_give ((void **) &stream->localhost);
  522.   fs_give ((void **) &stream);    /* flush the stream */
  523. }
  524.  
  525. /* TCP/IP get host name
  526.  * Accepts: TCP/IP stream
  527.  * Returns: host name for this stream
  528.  */
  529.  
  530. char *tcp_host (TCPSTREAM *stream)
  531. {
  532.   return stream->host;        /* return host name */
  533. }
  534.  
  535.  
  536. /* TCP/IP get local host name
  537.  * Accepts: TCP/IP stream
  538.  * Returns: local host name
  539.  */
  540.  
  541. char *tcp_localhost (TCPSTREAM *stream)
  542. {
  543.   return stream->localhost;    /* return local host name */
  544. }
  545.