home *** CD-ROM | disk | FTP | other *** search
/ InfoMagic Internet Tools 1993 July / Internet Tools.iso / RockRidge / mail / pine / imap-3.0 / ANSI / c-client / os_nxt.c < prev    next >
Encoding:
C/C++ Source or Header  |  1993-05-18  |  16.7 KB  |  602 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:    19 May 1993
  14.  *
  15.  * Copyright 1993 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 "mail.h"
  56. #include "osdep.h"
  57. #include <sys/time.h>
  58. #include <sys/socket.h>
  59. #include <netinet/in.h>
  60. #include <netdb.h>
  61. #include <ctype.h>
  62. #include <errno.h>
  63. extern int errno;        /* just in case */
  64. #include <pwd.h>
  65. #include <syslog.h>
  66. #include "misc.h"
  67. extern char *crypt();
  68.  
  69. /* Write current time in RFC 822 format
  70.  * Accepts: destination string
  71.  */
  72.  
  73. char *days[] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
  74.  
  75. void rfc822_date (char *date)
  76. {
  77.   int zone;
  78.   char *zonename;
  79.   struct tm *t;
  80.   struct timeval tv;
  81.   struct timezone tz;
  82.   gettimeofday (&tv,&tz);    /* get time and timezone poop */
  83.   t = localtime (&tv.tv_sec);    /* convert to individual items */
  84.   zone = t->tm_gmtoff/60;    /* get timezone from TZ environment stuff */
  85.   zonename = t->tm_zone;
  86.                 /* and output it */
  87.   sprintf (date,"%s, %d %s %d %02d:%02d:%02d %+03d%02d (%s)",
  88.        days[t->tm_wday],t->tm_mday,months[t->tm_mon],t->tm_year+1900,
  89.        t->tm_hour,t->tm_min,t->tm_sec,zone/60,abs (zone) % 60,zonename);
  90. }
  91.  
  92. /* Get a block of free storage
  93.  * Accepts: size of desired block
  94.  * Returns: free storage block
  95.  */
  96.  
  97. void *fs_get (size_t size)
  98. {
  99.   void *block = malloc (size);
  100.   if (!block) fatal ("Out of free storage");
  101.   return (block);
  102. }
  103.  
  104.  
  105. /* Resize a block of free storage
  106.  * Accepts: ** pointer to current block
  107.  *        new size
  108.  */
  109.  
  110. void fs_resize (void **block,size_t size)
  111. {
  112.   if (!(*block = realloc (*block,size))) fatal ("Can't resize free storage");
  113. }
  114.  
  115.  
  116. /* Return a block of free storage
  117.  * Accepts: ** pointer to free storage block
  118.  */
  119.  
  120. void fs_give (void **block)
  121. {
  122.   free (*block);
  123.   *block = NIL;
  124. }
  125.  
  126.  
  127. /* Report a fatal error
  128.  * Accepts: string to output
  129.  */
  130.  
  131. void fatal (char *string)
  132. {
  133.   mm_fatal (string);        /* pass up the string */
  134.   syslog (LOG_ALERT,"IMAP C-Client crash: %s",string);
  135.   abort ();            /* die horribly */
  136. }
  137.  
  138. /* Copy string with CRLF newlines
  139.  * Accepts: destination string
  140.  *        pointer to size of destination string
  141.  *        source string
  142.  *        length of source string
  143.  */
  144.  
  145. char *strcrlfcpy (char **dst,unsigned long *dstl,char *src,unsigned long srcl)
  146. {
  147.   long i,j;
  148.   char *d = src;
  149.                 /* count number of LF's in source string(s) */
  150.   for (i = srcl,j = 0; j < srcl; j++) if (*d++ == '\012') i++;
  151.   if (i > *dstl) {        /* resize if not enough space */
  152.     fs_give ((void **) dst);    /* fs_resize does an unnecessary copy */
  153.     *dst = (char *) fs_get ((*dstl = i) + 1);
  154.   }
  155.   d = *dst;            /* destination string */
  156.                 /* copy strings, inserting CR's before LF's */
  157.   while (srcl--) switch (*src) {
  158.   case '\015':            /* unlikely carriage return */
  159.     *d++ = *src++;        /* copy it and any succeeding linefeed */
  160.     if (srcl && *src == '\012') {
  161.       *d++ = *src++;
  162.       srcl--;
  163.     }
  164.     break;
  165.   case '\012':            /* line feed? */
  166.     *d++ ='\015';        /* yes, prepend a CR, drop into default case */
  167.   default:            /* ordinary chararacter */
  168.     *d++ = *src++;        /* just copy character */
  169.     break;
  170.   }
  171.   *d = '\0';            /* tie off destination */
  172.   return *dst;            /* return destination */
  173. }
  174.  
  175.  
  176. /* Length of string after strcrlfcpy applied
  177.  * Accepts: source string
  178.  *        length of source string
  179.  */
  180.  
  181. unsigned long strcrlflen (STRING *s)
  182. {
  183.   unsigned long pos = GETPOS (s);
  184.   unsigned long i = SIZE (s);
  185.   unsigned long j = i;
  186.   while (j--) switch (SNX (s)) {/* search for newlines */
  187.   case '\015':            /* unlikely carriage return */
  188.     if (j && (CHR (s) == '\012')) {
  189.       SNX (s);            /* eat the line feed */
  190.       j--;
  191.     }
  192.     break;
  193.   case '\012':            /* line feed? */
  194.     i++;
  195.   default:            /* ordinary chararacter */
  196.     break;
  197.   }
  198.   SETPOS (s,pos);        /* restore old position */
  199.   return i;
  200. }
  201.  
  202. /* Server log in
  203.  * Accepts: user name string
  204.  *        password string
  205.  *        optional place to return home directory
  206.  * Returns: T if password validated, NIL otherwise
  207.  */
  208.  
  209. long server_login (char *user,char *pass,char **home,int argc,char *argv[])
  210. {
  211.   struct passwd *pw = getpwnam (lcase (user));
  212.                 /* no entry for this user or root */
  213.   if (!(pw && pw->pw_uid)) return NIL;
  214.                 /* validate password */
  215.   if (strcmp (pw->pw_passwd,(char *) crypt (pass,pw->pw_passwd))) return NIL;
  216.   setgid (pw->pw_gid);        /* all OK, login in as that user */
  217.   initgroups (user,pw->pw_gid);    /* initialize groups */
  218.   setuid (pw->pw_uid);
  219.                 /* note home directory */
  220.   if (home) *home = cpystr (pw->pw_dir);
  221.   return T;
  222. }
  223.  
  224. /* Return my user name
  225.  * Returns: my user name
  226.  */
  227.  
  228. char *uname = NIL;
  229.  
  230. char *myusername ()
  231. {
  232.   return uname ? uname : (uname = cpystr (getpwuid (geteuid ())->pw_name));
  233. }
  234.  
  235.  
  236. /* Return my home directory name
  237.  * Returns: my home directory name
  238.  */
  239.  
  240. char *hdname = NIL;
  241.  
  242. char *myhomedir ()
  243. {
  244.   return hdname ? hdname : (hdname = cpystr (getpwuid (geteuid ())->pw_dir));
  245. }
  246.  
  247.  
  248. /* Build status lock file name
  249.  * Accepts: scratch buffer
  250.  *        file name
  251.  * Returns: name of file to lock
  252.  */
  253.  
  254. char *lockname (char *tmp,char *fname)
  255. {
  256.   int i;
  257.   sprintf (tmp,"/tmp/.%s",fname);
  258.   for (i = 6; i < strlen (tmp); ++i) if (tmp[i] == '/') tmp[i] = '\\';
  259.   return tmp;            /* note name for later */
  260. }
  261.   
  262. /* TCP/IP open
  263.  * Accepts: host name
  264.  *        contact port number
  265.  * Returns: TCP/IP stream if success else NIL
  266.  */
  267.  
  268. TCPSTREAM *tcp_open (char *host,int port)
  269. {
  270.   TCPSTREAM *stream = NIL;
  271.   int sock;
  272.   char *s;
  273.   struct sockaddr_in sin;
  274.   struct hostent *host_name;
  275.   char hostname[MAILTMPLEN];
  276.   char tmp[MAILTMPLEN];
  277.   /* The domain literal form is used (rather than simply the dotted decimal
  278.      as with other Unix programs) because it has to be a valid "host name"
  279.      in mailsystem terminology. */
  280.                 /* look like domain literal? */
  281.   if (host[0] == '[' && host[(strlen (host))-1] == ']') {
  282.     strcpy (hostname,host+1);    /* yes, copy number part */
  283.     hostname[(strlen (hostname))-1] = '\0';
  284.     if ((sin.sin_addr.s_addr = inet_addr (hostname)) != -1) {
  285.       sin.sin_family = AF_INET;    /* family is always Internet */
  286.       strcpy (hostname,host);    /* hostname is user's argument */
  287.     }
  288.     else {
  289.       sprintf (tmp,"Bad format domain-literal: %.80s",host);
  290.       mm_log (tmp,ERROR);
  291.       return NIL;
  292.     }
  293.   }
  294.  
  295.   else {            /* lookup host name, note that brain-dead Unix
  296.                    requires lowercase! */
  297.     strcpy (hostname,host);    /* in case host is in write-protected memory */
  298.     if ((host_name = gethostbyname (lcase (hostname)))) {
  299.                 /* copy address type */
  300.       sin.sin_family = host_name->h_addrtype;
  301.                 /* copy host name */
  302.       strcpy (hostname,host_name->h_name);
  303.                 /* copy host addresses */
  304.       memcpy (&sin.sin_addr,host_name->h_addr,host_name->h_length);
  305.     }
  306.     else {
  307.       switch (h_errno) {
  308.     case HOST_NOT_FOUND:    /* authoritative error */
  309.       s = "No such host as %.80s";
  310.       break;
  311.     case TRY_AGAIN:        /* non-authoritative error */
  312.       s = "Transient error for host %.80s, try again";
  313.       break;
  314.     case NO_RECOVERY:    /* non-recoverable errors */
  315.       s = "Non-recoverable error looking up host %.80s";
  316.       break;
  317.     case NO_DATA:        /* no data record of requested type */
  318.       s = "No IP address known for host %.80s";
  319.       break;
  320.     default:
  321.       s = "Unknown error for host %.80s";
  322.       break;
  323.       }
  324.       sprintf (tmp,s,host);
  325.       mm_log (tmp,ERROR);
  326.       return NIL;
  327.     }
  328.   }
  329.  
  330.                 /* copy port number in network format */
  331.   if (!(sin.sin_port = htons (port))) fatal ("Bad port argument to tcp_open");
  332.                 /* get a TCP stream */
  333.   if ((sock = socket (sin.sin_family,SOCK_STREAM,0)) < 0) {
  334.     sprintf (tmp,"Unable to create TCP socket: %s",strerror (errno));
  335.     mm_log (tmp,ERROR);
  336.     return NIL;
  337.   }
  338.                 /* open connection */
  339.   if (connect (sock,(struct sockaddr *)&sin,sizeof (sin)) < 0) {
  340.     sprintf (tmp,"Can't connect to %.80s,%d: %s",hostname,port,
  341.          strerror (errno));
  342.     mm_log (tmp,ERROR);
  343.     return NIL;
  344.   }
  345.                 /* create TCP/IP stream */
  346.   stream = (TCPSTREAM *) fs_get (sizeof (TCPSTREAM));
  347.                 /* copy official host name */
  348.   stream->host = cpystr (hostname);
  349.                 /* get local name */
  350.   gethostname (tmp,MAILTMPLEN-1);
  351.   stream->localhost = cpystr ((host_name = gethostbyname (tmp)) ?
  352.                   host_name->h_name : tmp);
  353.                 /* init sockets */
  354.   stream->tcpsi = stream->tcpso = sock;
  355.   stream->ictr = 0;        /* init input counter */
  356.   return stream;        /* return success */
  357. }
  358.   
  359. /* TCP/IP authenticated open
  360.  * Accepts: host name
  361.  *        service name
  362.  * Returns: TCP/IP stream if success else NIL
  363.  */
  364.  
  365. TCPSTREAM *tcp_aopen (char *host,char *service)
  366. {
  367.   TCPSTREAM *stream = NIL;
  368.   struct hostent *host_name;
  369.   char hostname[MAILTMPLEN];
  370.   int i;
  371.   int pipei[2],pipeo[2];
  372.   /* The domain literal form is used (rather than simply the dotted decimal
  373.      as with other Unix programs) because it has to be a valid "host name"
  374.      in mailsystem terminology. */
  375.                 /* look like domain literal? */
  376.   if (host[0] == '[' && host[i = (strlen (host))-1] == ']') {
  377.     strcpy (hostname,host+1);    /* yes, copy without brackets */
  378.     hostname[i-1] = '\0';
  379.   }
  380.                 /* note that Unix requires lowercase! */
  381.   else if (host_name = gethostbyname (lcase (strcpy (hostname,host))))
  382.     strcpy (hostname,host_name->h_name);
  383.                 /* make command pipes */
  384.   if (pipe (pipei) < 0) return NIL;
  385.   if (pipe (pipeo) < 0) {
  386.     close (pipei[0]); close (pipei[1]);
  387.     return NIL;
  388.   }
  389.   if ((i = fork ()) < 0) {    /* make inferior process */
  390.     close (pipei[0]); close (pipei[1]);
  391.     close (pipeo[0]); close (pipeo[1]);
  392.     return NIL;
  393.   }
  394.   if (i) {            /* parent? */
  395.     close (pipei[1]);        /* close child's side of the pipes */
  396.     close (pipeo[0]);
  397.   }
  398.   else {            /* child */
  399.     dup2 (pipei[1],1);        /* parent's input is my output */
  400.     dup2 (pipei[1],2);        /* parent's input is my error output too */
  401.     close (pipei[0]); close (pipei[1]);
  402.     dup2 (pipeo[0],0);        /* parent's output is my input */
  403.     close (pipeo[0]); close (pipeo[1]);
  404.                 /* now run it */
  405.     execl ("/usr/ucb/rsh","rsh",hostname,"exec",service,0);
  406.     _exit (1);            /* spazzed */
  407.   }
  408.  
  409.                 /* create TCP/IP stream */
  410.   stream = (TCPSTREAM *) fs_get (sizeof (TCPSTREAM));
  411.                 /* copy official host name */
  412.   stream->host = cpystr (hostname);
  413.                 /* get local name */
  414.   gethostname (hostname,MAILTMPLEN-1);
  415.   stream->localhost = cpystr ((host_name = gethostbyname (hostname)) ?
  416.                   host_name->h_name : hostname);
  417.   stream->tcpsi = pipei[0];    /* init sockets */
  418.   stream->tcpso = pipeo[1];
  419.   stream->ictr = 0;        /* init input counter */
  420.   return stream;        /* return success */
  421. }
  422.  
  423. /* TCP/IP receive line
  424.  * Accepts: TCP/IP stream
  425.  * Returns: text line string or NIL if failure
  426.  */
  427.  
  428. char *tcp_getline (TCPSTREAM *stream)
  429. {
  430.   int n,m;
  431.   char *st,*ret,*stp;
  432.   char c = '\0';
  433.   char d;
  434.                 /* make sure have data */
  435.   if (!tcp_getdata (stream)) return NIL;
  436.   st = stream->iptr;        /* save start of string */
  437.   n = 0;            /* init string count */
  438.   while (stream->ictr--) {    /* look for end of line */
  439.     d = *stream->iptr++;    /* slurp another character */
  440.     if ((c == '\015') && (d == '\012')) {
  441.       ret = (char *) fs_get (n--);
  442.       memcpy (ret,st,n);    /* copy into a free storage string */
  443.       ret[n] = '\0';        /* tie off string with null */
  444.       return ret;
  445.     }
  446.     n++;            /* count another character searched */
  447.     c = d;            /* remember previous character */
  448.   }
  449.                 /* copy partial string from buffer */
  450.   memcpy ((ret = stp = (char *) fs_get (n)),st,n);
  451.                 /* get more data from the net */
  452.   if (!tcp_getdata (stream)) return NIL;
  453.                 /* special case of newline broken by buffer */
  454.   if ((c == '\015') && (*stream->iptr == '\012')) {
  455.     stream->iptr++;        /* eat the line feed */
  456.     stream->ictr--;
  457.     ret[n - 1] = '\0';        /* tie off string with null */
  458.   }
  459.                 /* else recurse to get remainder */
  460.   else if (st = tcp_getline (stream)) {
  461.     ret = (char *) fs_get (n + 1 + (m = strlen (st)));
  462.     memcpy (ret,stp,n);        /* copy first part */
  463.     memcpy (ret + n,st,m);    /* and second part */
  464.     fs_give ((void **) &stp);    /* flush first part */
  465.     fs_give ((void **) &st);    /* flush second part */
  466.     ret[n + m] = '\0';        /* tie off string with null */
  467.   }
  468.   return ret;
  469. }
  470.  
  471. /* TCP/IP receive buffer
  472.  * Accepts: TCP/IP stream
  473.  *        size in bytes
  474.  *        buffer to read into
  475.  * Returns: T if success, NIL otherwise
  476.  */
  477.  
  478. long tcp_getbuffer (TCPSTREAM *stream,unsigned long size,char *buffer)
  479. {
  480.   unsigned long n;
  481.   char *bufptr = buffer;
  482.   while (size > 0) {        /* until request satisfied */
  483.     if (!tcp_getdata (stream)) return NIL;
  484.     n = min (size,stream->ictr);/* number of bytes to transfer */
  485.                 /* do the copy */
  486.     memcpy (bufptr,stream->iptr,n);
  487.     bufptr += n;        /* update pointer */
  488.     stream->iptr +=n;
  489.     size -= n;            /* update # of bytes to do */
  490.     stream->ictr -=n;
  491.   }
  492.   bufptr[0] = '\0';        /* tie off string */
  493.   return T;
  494. }
  495.  
  496.  
  497. /* TCP/IP receive data
  498.  * Accepts: TCP/IP stream
  499.  * Returns: T if success, NIL otherwise
  500.  */
  501.  
  502. long tcp_getdata (TCPSTREAM *stream)
  503. {
  504.   fd_set fds;
  505.   FD_ZERO (&fds);        /* initialize selection vector */
  506.   if (stream->tcpsi < 0) return NIL;
  507.   while (stream->ictr < 1) {    /* if nothing in the buffer */
  508.     FD_SET (stream->tcpsi,&fds);/* set bit in selection vector */
  509.                 /* block and read */
  510.     if ((select (stream->tcpsi+1,&fds,0,0,0) < 0) ||
  511.     ((stream->ictr = read (stream->tcpsi,stream->ibuf,BUFLEN)) < 1)) {
  512.       close (stream->tcpsi);    /* nuke the socket */
  513.       if (stream->tcpsi != stream->tcpso) close (stream->tcpso);
  514.       stream->tcpsi = stream->tcpso = -1;
  515.       return NIL;
  516.     }
  517.     stream->iptr = stream->ibuf;/* point at TCP buffer */
  518.   }
  519.   return T;
  520. }
  521.  
  522. /* TCP/IP send string as record
  523.  * Accepts: TCP/IP stream
  524.  *        string pointer
  525.  * Returns: T if success else NIL
  526.  */
  527.  
  528. long tcp_soutr (TCPSTREAM *stream,char *string)
  529. {
  530.   return tcp_sout (stream,string,(unsigned long) strlen (string));
  531. }
  532.  
  533.  
  534. /* TCP/IP send string
  535.  * Accepts: TCP/IP stream
  536.  *        string pointer
  537.  *        byte count
  538.  * Returns: T if success else NIL
  539.  */
  540.  
  541. long tcp_sout (TCPSTREAM *stream,char *string,unsigned long size)
  542. {
  543.   int i;
  544.   fd_set fds;
  545.   FD_ZERO (&fds);        /* initialize selection vector */
  546.   if (stream->tcpso < 0) return NIL;
  547.   while (size > 0) {        /* until request satisfied */
  548.     FD_SET (stream->tcpso,&fds);/* set bit in selection vector */
  549.     if ((select (stream->tcpso+1,0,&fds,0,0) < 0) ||
  550.     ((i = write (stream->tcpso,string,size)) < 0)) {
  551.       puts (strerror (errno));
  552.       close (stream->tcpsi);    /* nuke the socket */
  553.       if (stream->tcpsi != stream->tcpso) close (stream->tcpso);
  554.       stream->tcpsi = stream->tcpso = -1;
  555.       return NIL;
  556.     }
  557.     size -= i;            /* count this size */
  558.     string += i;
  559.   }
  560.   return T;            /* all done */
  561. }
  562.  
  563. /* TCP/IP close
  564.  * Accepts: TCP/IP stream
  565.  */
  566.  
  567. void tcp_close (TCPSTREAM *stream)
  568. {
  569.  
  570.   if (stream->tcpsi >= 0) {    /* no-op if no socket */
  571.     close (stream->tcpsi);    /* nuke the socket */
  572.     if (stream->tcpsi != stream->tcpso) close (stream->tcpso);
  573.     stream->tcpsi = stream->tcpso = -1;
  574.   }
  575.                 /* flush host names */
  576.   fs_give ((void **) &stream->host);
  577.   fs_give ((void **) &stream->localhost);
  578.   fs_give ((void **) &stream);    /* flush the stream */
  579. }
  580.  
  581.  
  582. /* TCP/IP get host name
  583.  * Accepts: TCP/IP stream
  584.  * Returns: host name for this stream
  585.  */
  586.  
  587. char *tcp_host (TCPSTREAM *stream)
  588. {
  589.   return stream->host;        /* return host name */
  590. }
  591.  
  592.  
  593. /* TCP/IP get local host name
  594.  * Accepts: TCP/IP stream
  595.  * Returns: local host name
  596.  */
  597.  
  598. char *tcp_localhost (TCPSTREAM *stream)
  599. {
  600.   return stream->localhost;    /* return local host name */
  601. }
  602.