home *** CD-ROM | disk | FTP | other *** search
/ vsiftp.vmssoftware.com / VSIPUBLIC@vsiftp.vmssoftware.com.tar / FREEWARE / FREEWARE40.ZIP / pine / c-client / os_sv4.c < prev    next >
C/C++ Source or Header  |  1994-01-09  |  22KB  |  809 lines

  1. /*
  2.  * Program:    Operating-system dependent routines -- SVR4 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:    10 April 1992
  13.  * Last Edited:    3 October 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
  24.  * available "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 "osdep.h"
  56. #include <ctype.h>
  57. #include <sys/tiuser.h>
  58. #include <sys/stropts.h>
  59. #include <sys/select.h>
  60. #include <netinet/in.h>
  61. #include <netdb.h>
  62. #include <ctype.h>
  63. #include <regexpr.h>
  64. #include <errno.h>
  65. #include <pwd.h>
  66. #include <shadow.h>
  67. #include <syslog.h>
  68. #include <sys/file.h>
  69. #include <sys/stat.h>
  70. #include <sys/socket.h>
  71. #include "mail.h"
  72. #include "misc.h"
  73.  
  74. extern int sys_nerr;
  75. extern char *sys_errlist[];
  76.  
  77. #define toint(c)    ((c)-'0')
  78. #define isodigit(c)    (((unsigned)(c)>=060)&((unsigned)(c)<=067))
  79.  
  80. /* Write current time in RFC 822 format
  81.  * Accepts: destination string
  82.  */
  83.  
  84. char *days[] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
  85.  
  86. void rfc822_date (date)
  87.     char *date;
  88. {
  89.   int zone,dstnow;
  90.   struct tm *t;
  91.   time_t time_sec = time (0);
  92.   t = localtime (&time_sec);    /* convert to individual items */
  93.   tzset ();            /* initialize timezone/daylight variables */
  94.                 /* see if it is DST now */
  95.   dstnow = daylight && t->tm_isdst;
  96.                 /* get timezone value */
  97.   zone = - (dstnow ? altzone : timezone) / 60;
  98.                 /* and output it */
  99.   sprintf (date,"%s, %d %s %d %02d:%02d:%02d %+03d%02d (%s)",
  100.        days[t->tm_wday],t->tm_mday,months[t->tm_mon],t->tm_year+1900,
  101.        t->tm_hour,t->tm_min,t->tm_sec,zone/60,abs (zone) % 60,
  102.        tzname[dstnow]);
  103. }
  104.  
  105. /* Get a block of free storage
  106.  * Accepts: size of desired block
  107.  * Returns: free storage block
  108.  */
  109.  
  110. void *fs_get (size)
  111.     size_t size;
  112. {
  113.   void *block = malloc (size);
  114.   if (!block) fatal ("Out of free storage");
  115.   return (block);
  116. }
  117.  
  118.  
  119. /* Resize a block of free storage
  120.  * Accepts: ** pointer to current block
  121.  *        new size
  122.  */
  123.  
  124. void fs_resize (block,size)
  125.     void **block;
  126.     size_t size;
  127. {
  128.   if (!(*block = realloc (*block,size))) fatal ("Can't resize free storage");
  129. }
  130.  
  131.  
  132. /* Return a block of free storage
  133.  * Accepts: ** pointer to free storage block
  134.  */
  135.  
  136. void fs_give (block)
  137.     void **block;
  138. {
  139.   free (*block);
  140.   *block = NIL;
  141. }
  142.  
  143.  
  144. /* Report a fatal error
  145.  * Accepts: string to output
  146.  */
  147.  
  148. void fatal (string)
  149.     char *string;
  150. {
  151.   mm_fatal (string);        /* output the string */
  152.   syslog (LOG_ALERT,"IMAP C-Client crash: %s",string);
  153.   abort ();            /* die horribly */
  154. }
  155.  
  156. /* Copy string with CRLF newlines
  157.  * Accepts: destination string
  158.  *        pointer to size of destination string
  159.  *        source string
  160.  *        length of source string
  161.  * Returns: length of copied string
  162.  */
  163.  
  164. unsigned long strcrlfcpy (dst,dstl,src,srcl)
  165.     char **dst;
  166.     unsigned long *dstl;
  167.     char *src;
  168.     unsigned long srcl;
  169. {
  170.   long i,j;
  171.   char *d = src;
  172.                 /* count number of LF's in source string(s) */
  173.   for (i = srcl,j = 0; j < srcl; j++) if (*d++ == '\012') i++;
  174.   if (i > *dstl) {        /* resize if not enough space */
  175.     fs_give ((void **) dst);    /* fs_resize does an unnecessary copy */
  176.     *dst = (char *) fs_get ((*dstl = i) + 1);
  177.   }
  178.   d = *dst;            /* destination string */
  179.                 /* copy strings, inserting CR's before LF's */
  180.   while (srcl--) switch (*src) {
  181.   case '\015':            /* unlikely carriage return */
  182.     *d++ = *src++;        /* copy it and any succeeding linefeed */
  183.     if (srcl && *src == '\012') {
  184.       *d++ = *src++;
  185.       srcl--;
  186.     }
  187.     break;
  188.   case '\012':            /* line feed? */
  189.     *d++ ='\015';        /* yes, prepend a CR, drop into default case */
  190.   default:            /* ordinary chararacter */
  191.     *d++ = *src++;        /* just copy character */
  192.     break;
  193.   }
  194.   *d = '\0';            /* tie off destination */
  195.   return d - *dst;        /* return length */
  196. }
  197.  
  198.  
  199. /* Length of string after strcrlflen applied
  200.  * Accepts: source string
  201.  * Returns: length of string
  202.  */
  203.  
  204. unsigned long strcrlflen (s)
  205.     STRING *s;
  206. {
  207.   unsigned long pos = GETPOS (s);
  208.   unsigned long i = SIZE (s);
  209.   unsigned long j = i;
  210.   while (j--) switch (SNX (s)) {/* search for newlines */
  211.   case '\015':            /* unlikely carriage return */
  212.     if (j && (CHR (s) == '\012')) {
  213.       SNX (s);            /* eat the line feed */
  214.       j--;
  215.     }
  216.     break;
  217.   case '\012':            /* line feed? */
  218.     i++;
  219.   default:            /* ordinary chararacter */
  220.     break;
  221.   }
  222.   SETPOS (s,pos);        /* restore old position */
  223.   return i;
  224. }
  225.  
  226. /* Server log in
  227.  * Accepts: user name string
  228.  *        password string
  229.  *        optional place to return home directory
  230.  * Returns: T if password validated, NIL otherwise
  231.  */
  232.  
  233. long server_login (user,pass,home,argc,argv)
  234.     char *user;
  235.     char *pass;
  236.     char **home;
  237.     int argc;
  238.     char *argv[];
  239. {
  240.   struct passwd *pw = getpwnam (lcase (user));
  241.   struct spwd *sp;
  242.                 /* no entry for this user or root */
  243.   if (!(pw && pw->pw_uid)) return NIL;
  244.                 /* validate password and password aging */
  245.   sp = getspnam (pw->pw_name);
  246.   if (strcmp (sp->sp_pwdp, (char *) crypt (pass,sp->sp_pwdp))) return NIL;
  247.   else if ((sp->sp_lstchg > 0) && (sp->sp_max > 0) &&
  248.        ((sp->sp_lstchg + sp->sp_max) < (time (0) / (60*60*24))))
  249.     return NIL;
  250.   setgid (pw->pw_gid);        /* all OK, login in as that user */
  251.   initgroups (user,pw->pw_gid);    /* initialize groups */
  252.   setuid (pw->pw_uid);
  253.                 /* note home directory */
  254.   if (home) *home = cpystr (pw->pw_dir);
  255.   return T;
  256. }
  257.  
  258. /* Return my user name
  259.  * Returns: my user name
  260.  */
  261.  
  262. char *myuname = NIL;
  263.  
  264. char *myusername ()
  265. {
  266.   return myuname ? myuname : (myuname = cpystr(getpwuid(geteuid ())->pw_name));
  267. }
  268.  
  269.  
  270. /* Return my home directory name
  271.  * Returns: my home directory name
  272.  */
  273.  
  274. char *hdname = NIL;
  275.  
  276. char *myhomedir ()
  277. {
  278.   return hdname ? hdname : (hdname = cpystr (getpwuid (geteuid ())->pw_dir));
  279. }
  280.  
  281.  
  282. /* Build status lock file name
  283.  * Accepts: scratch buffer
  284.  *        file name
  285.  * Returns: name of file to lock
  286.  */
  287.  
  288. char *lockname (tmp,fname)
  289.     char *tmp;
  290.     char *fname;
  291. {
  292.   int i;
  293.   sprintf (tmp,"/tmp/.%s",fname);
  294.   for (i = 6; i < strlen (tmp); ++i) if (tmp[i] == '/') tmp[i] = '\\';
  295.   return tmp;            /* note name for later */
  296. }
  297.  
  298. /* TCP/IP open
  299.  * Accepts: host name
  300.  *        contact port number
  301.  * Returns: TCP/IP stream if success else NIL
  302.  */
  303.  
  304. TCPSTREAM *tcp_open (host,port)
  305.     char *host;
  306.     int port;
  307. {
  308.   TCPSTREAM *stream = NIL;
  309.   int sock;
  310.   char *s;
  311.   struct sockaddr_in sin;
  312.   struct hostent *host_name;
  313.   char hostname[MAILTMPLEN];
  314.   char tmp[MAILTMPLEN];
  315.     extern int t_errno;
  316.     extern char *t_errlist[];
  317.     struct t_call *sndcall;
  318.  
  319.   /* The domain literal form is used (rather than simply the dotted decimal
  320.      as with other Unix programs) because it has to be a valid "host name"
  321.      in mailsystem terminology. */
  322.                 /* look like domain literal? */
  323.   if (host[0] == '[' && host[(strlen (host))-1] == ']') {
  324.     strcpy (hostname,host+1);    /* yes, copy number part */
  325.     hostname[(strlen (hostname))-1] = '\0';
  326.     if ((sin.sin_addr.s_addr = inet_addr (hostname)) != -1) {
  327.       sin.sin_family = AF_INET;    /* family is always Internet */
  328.       strcpy (hostname,host);    /* hostname is user's argument */
  329.     }
  330.     else {
  331.       sprintf (tmp,"Bad format domain-literal: %.80s",host);
  332.       mm_log (tmp,ERROR);
  333.       return NIL;
  334.     }
  335.   }
  336.  
  337.   else {            /* lookup host name, note that brain-dead Unix
  338.                    requires lowercase! */
  339.     strcpy (hostname,host);    /* in case host is in write-protected memory */
  340.     if ((host_name = gethostbyname (lcase (hostname)))) {
  341.                 /* copy address type */
  342.       sin.sin_family = host_name->h_addrtype;
  343.                 /* copy host name */
  344.       strcpy (hostname,host_name->h_name);
  345.                 /* copy host addresses */
  346.       memcpy (&sin.sin_addr,host_name->h_addr,host_name->h_length);
  347.     }
  348.     else {
  349.       sprintf (tmp,"No such host as %.80s",host);
  350.       mm_log (tmp,ERROR);
  351.       return NIL;
  352.     }
  353.   }
  354.  
  355.                 /* copy port number in network format */
  356.   if (!(sin.sin_port = htons (port))) fatal ("Bad port argument to tcp_open");
  357.  
  358.                 /* get a TCP stream */
  359.   t_errno = 0;
  360.   if (((sock = t_open ("/dev/tcp", O_RDWR, 0)) < 0) ||
  361.       (t_bind (sock, 0, 0) < 0) ||
  362.       ((sndcall = (struct t_call *) t_alloc (sock, T_CALL, T_ADDR)) == 0))
  363.   {
  364.     sprintf (tmp,"Unable to create TCP socket: %s",t_errlist[t_errno]);
  365.     mm_log (tmp,ERROR);
  366.     return NIL;
  367.   }
  368.                 /* connect to address. */
  369.   sndcall->addr.len = sndcall->addr.maxlen = sizeof (sin);
  370.   sndcall->addr.buf = (char *) &sin;
  371.   sndcall->opt.len = 0;
  372.   sndcall->udata.len = 0;
  373.   if (t_connect (sock, sndcall, 0) < 0) {
  374.     sprintf (tmp,"Can't connect to %.80s,%d: %s",hostname,port,
  375.          t_errlist[t_errno]);
  376.     mm_log (tmp,ERROR);
  377.     return NIL;
  378.   }
  379.                 /* push streams module for read()/write(). */
  380.   if (ioctl (sock, I_PUSH, "tirdwr") < 0) {
  381.     sprintf (tmp,"Unable to create TCP socket: %s",t_errlist[t_errno]);
  382.     mm_log (tmp,ERROR);
  383.     return NIL;
  384.   }
  385.                 /* create TCP/IP stream */
  386.   stream = (TCPSTREAM *) fs_get (sizeof (TCPSTREAM));
  387.                 /* copy official host name */
  388.   stream->host = cpystr (hostname);
  389.                 /* get local name */
  390.   gethostname (tmp,MAILTMPLEN-1);
  391.   stream->localhost = cpystr ((host_name = gethostbyname (tmp)) ?
  392.                   host_name->h_name : tmp);
  393.                 /* init sockets */
  394.   stream->tcpsi = stream->tcpso = sock;
  395.   stream->ictr = 0;        /* init input counter */
  396.   return stream;        /* return success */
  397. }
  398.  
  399. /* TCP/IP authenticated open
  400.  * Accepts: host name
  401.  *        service name
  402.  * Returns: TCP/IP stream if success else NIL
  403.  */
  404.  
  405. TCPSTREAM *tcp_aopen (host,service)
  406.     char *host;
  407.     char *service;
  408. {
  409.   TCPSTREAM *stream = NIL;
  410.   struct hostent *host_name;
  411.   char hostname[MAILTMPLEN];
  412.   int i;
  413.   int pipei[2],pipeo[2];
  414.   /* The domain literal form is used (rather than simply the dotted decimal
  415.      as with other Unix programs) because it has to be a valid "host name"
  416.      in mailsystem terminology. */
  417.                 /* look like domain literal? */
  418.   if (host[0] == '[' && host[i = (strlen (host))-1] == ']') {
  419.     strcpy (hostname,host+1);    /* yes, copy without brackets */
  420.     hostname[i-1] = '\0';
  421.   }
  422.                 /* note that Unix requires lowercase! */
  423.   else if (host_name = gethostbyname (lcase (strcpy (hostname,host))))
  424.     strcpy (hostname,host_name->h_name);
  425.                 /* make command pipes */
  426.   if (pipe (pipei) < 0) return NIL;
  427.   if (pipe (pipeo) < 0) {
  428.     close (pipei[0]); close (pipei[1]);
  429.     return NIL;
  430.   }
  431.   if ((i = fork ()) < 0) {    /* make inferior process */
  432.     close (pipei[0]); close (pipei[1]);
  433.     close (pipeo[0]); close (pipeo[1]);
  434.     return NIL;
  435.   }
  436.   if (i) {            /* parent? */
  437.     close (pipei[1]);        /* close child's side of the pipes */
  438.     close (pipeo[0]);
  439.   }
  440.   else {            /* child */
  441.     dup2 (pipei[1],1);        /* parent's input is my output */
  442.     dup2 (pipei[1],2);        /* parent's input is my error output too */
  443.     close (pipei[0]); close (pipei[1]);
  444.     dup2 (pipeo[0],0);        /* parent's output is my input */
  445.     close (pipeo[0]); close (pipeo[1]);
  446.                 /* now run it */
  447.     execl (RSHPATH,RSH,hostname,"exec",service,0);
  448.     _exit (1);            /* spazzed */
  449.   }
  450.  
  451.                 /* create TCP/IP stream */
  452.   stream = (TCPSTREAM *) fs_get (sizeof (TCPSTREAM));
  453.                 /* copy official host name */
  454.   stream->host = cpystr (hostname);
  455.                 /* get local name */
  456.   gethostname (hostname,MAILTMPLEN-1);
  457.   stream->localhost = cpystr ((host_name = gethostbyname (hostname)) ?
  458.                   host_name->h_name : hostname);
  459.   stream->tcpsi = pipei[0];    /* init sockets */
  460.   stream->tcpso = pipeo[1];
  461.   stream->ictr = 0;        /* init input counter */
  462.   return stream;        /* return success */
  463. }
  464.  
  465. /* TCP/IP receive line
  466.  * Accepts: TCP/IP stream
  467.  * Returns: text line string or NIL if failure
  468.  */
  469.  
  470. char *tcp_getline (stream)
  471.     TCPSTREAM *stream;
  472. {
  473.   int n,m;
  474.   char *st,*ret,*stp;
  475.   char c = '\0';
  476.   char d;
  477.                 /* make sure have data */
  478.   if (!tcp_getdata (stream)) return NIL;
  479.   st = stream->iptr;        /* save start of string */
  480.   n = 0;            /* init string count */
  481.   while (stream->ictr--) {    /* look for end of line */
  482.     d = *stream->iptr++;    /* slurp another character */
  483.     if ((c == '\015') && (d == '\012')) {
  484.       ret = (char *) fs_get (n--);
  485.       memcpy (ret,st,n);    /* copy into a free storage string */
  486.       ret[n] = '\0';        /* tie off string with null */
  487.       return ret;
  488.     }
  489.     n++;            /* count another character searched */
  490.     c = d;            /* remember previous character */
  491.   }
  492.                 /* copy partial string from buffer */
  493.   memcpy ((ret = stp = (char *) fs_get (n)),st,n);
  494.                 /* get more data from the net */
  495.   if (!tcp_getdata (stream)) return NIL;
  496.                 /* special case of newline broken by buffer */
  497.   if ((c == '\015') && (*stream->iptr == '\012')) {
  498.     stream->iptr++;        /* eat the line feed */
  499.     stream->ictr--;
  500.     ret[n - 1] = '\0';        /* tie off string with null */
  501.   }
  502.                 /* else recurse to get remainder */
  503.   else if (st = tcp_getline (stream)) {
  504.     ret = (char *) fs_get (n + 1 + (m = strlen (st)));
  505.     memcpy (ret,stp,n);        /* copy first part */
  506.     memcpy (ret + n,st,m);    /* and second part */
  507.     fs_give ((void **) &stp);    /* flush first part */
  508.     fs_give ((void **) &st);    /* flush second part */
  509.     ret[n + m] = '\0';        /* tie off string with null */
  510.   }
  511.   return ret;
  512. }
  513.  
  514. /* TCP/IP receive buffer
  515.  * Accepts: TCP/IP stream
  516.  *        size in bytes
  517.  *        buffer to read into
  518.  * Returns: T if success, NIL otherwise
  519.  */
  520.  
  521. long tcp_getbuffer (stream,size,buffer)
  522.     TCPSTREAM *stream;
  523.     unsigned long size;
  524.     char *buffer;
  525. {
  526.   unsigned long n;
  527.   char *bufptr = buffer;
  528.   while (size > 0) {        /* until request satisfied */
  529.     if (!tcp_getdata (stream)) return NIL;
  530.     n = min (size,stream->ictr);/* number of bytes to transfer */
  531.                 /* do the copy */
  532.     memcpy (bufptr,stream->iptr,n);
  533.     bufptr += n;        /* update pointer */
  534.     stream->iptr +=n;
  535.     size -= n;            /* update # of bytes to do */
  536.     stream->ictr -=n;
  537.   }
  538.   bufptr[0] = '\0';        /* tie off string */
  539.   return T;
  540. }
  541.  
  542.  
  543.  
  544. long tcp_abort ();
  545.  
  546. /* TCP/IP receive data
  547.  * Accepts: TCP/IP stream
  548.  * Returns: T if success, NIL otherwise
  549.  */
  550.  
  551. long tcp_getdata (stream)
  552.     TCPSTREAM *stream;
  553. {
  554.   int i;
  555.   fd_set fds;
  556.   FD_ZERO (&fds);        /* initialize selection vector */
  557.   if (stream->tcpsi < 0) return NIL;
  558.   while (stream->ictr < 1) {    /* if nothing in the buffer */
  559.     FD_SET (stream->tcpsi,&fds);/* set bit in selection vector */
  560.     errno = NIL;        /* block and read */
  561.     while (((i = select (stream->tcpsi+1,&fds,0,0,0)) < 0) &&
  562.        (errno == EINTR));
  563.     if (i < 0) return tcp_abort (stream);
  564.     while (((i = read (stream->tcpsi,stream->ibuf,BUFLEN)) < 1) &&
  565.        (errno == EINTR));
  566.     if (i < 1) return tcp_abort (stream);
  567.     stream->ictr = i;        /* set new byte count */
  568.     stream->iptr = stream->ibuf;/* point at TCP buffer */
  569.   }
  570.   return T;
  571. }
  572.  
  573. /* TCP/IP send string as record
  574.  * Accepts: TCP/IP stream
  575.  *        string pointer
  576.  * Returns: T if success else NIL
  577.  */
  578.  
  579. long tcp_soutr (stream,string)
  580.     TCPSTREAM *stream;
  581.     char *string;
  582. {
  583.   return tcp_sout (stream,string,(unsigned long) strlen (string));
  584. }
  585.  
  586.  
  587. /* TCP/IP send string
  588.  * Accepts: TCP/IP stream
  589.  *        string pointer
  590.  *        byte count
  591.  * Returns: T if success else NIL
  592.  */
  593.  
  594. long tcp_sout (stream,string,size)
  595.     TCPSTREAM *stream;
  596.     char *string;
  597.     unsigned long size;
  598. {
  599.   int i;
  600.   fd_set fds;
  601.   FD_ZERO (&fds);        /* initialize selection vector */
  602.   if (stream->tcpso < 0) return NIL;
  603.   while (size > 0) {        /* until request satisfied */
  604.     FD_SET (stream->tcpso,&fds);/* set bit in selection vector */
  605.     errno = NIL;        /* block and wrtie */
  606.     while (((i = select (stream->tcpso+1,0,&fds,0,0)) < 0) &&
  607.        (errno == EINTR));
  608.     if (i < 0) return tcp_abort (stream);
  609.     while (((i = write (stream->tcpso,string,size)) < 0) &&
  610.        (errno == EINTR));
  611.     if (i < 0) return tcp_abort (stream);
  612.     size -= i;            /* how much we sent */
  613.     string += i;
  614.   }
  615.   return T;            /* all done */
  616. }
  617.  
  618. /* TCP/IP close
  619.  * Accepts: TCP/IP stream
  620.  */
  621.  
  622. void tcp_close (stream)
  623.     TCPSTREAM *stream;
  624. {
  625.   tcp_abort (stream);        /* nuke the stream */
  626.                 /* flush host names */
  627.   fs_give ((void **) &stream->host);
  628.   fs_give ((void **) &stream->localhost);
  629.   fs_give ((void **) &stream);    /* flush the stream */
  630. }
  631.  
  632.  
  633. /* TCP/IP abort stream
  634.  * Accepts: TCP/IP stream
  635.  * Returns: NIL always
  636.  */
  637.  
  638. long tcp_abort (stream)
  639.      TCPSTREAM *stream;
  640. {
  641.   if (stream->tcpsi >= 0) {    /* no-op if no socket */
  642.     close (stream->tcpsi);    /* nuke the socket */
  643.     if (stream->tcpsi != stream->tcpso) close (stream->tcpso);
  644.     stream->tcpsi = stream->tcpso = -1;
  645.   }
  646.   return NIL;
  647. }
  648.  
  649. /* TCP/IP get host name
  650.  * Accepts: TCP/IP stream
  651.  * Returns: host name for this stream
  652.  */
  653.  
  654. char *tcp_host (stream)
  655.     TCPSTREAM *stream;
  656. {
  657.   return stream->host;        /* return host name */
  658. }
  659.  
  660.  
  661. /* TCP/IP get local host name
  662.  * Accepts: TCP/IP stream
  663.  * Returns: local host name
  664.  */
  665.  
  666. char *tcp_localhost (stream)
  667.     TCPSTREAM *stream;
  668. {
  669.   return stream->localhost;    /* return local host name */
  670. }
  671.  
  672. /* Emulator for BSD gethostid() call
  673.  * Returns: unique identifier for this machine
  674.  */
  675.  
  676. long gethostid ()
  677. {
  678.   /* No gethostid() here, so just fake it and hope things turn out okay. */
  679.   return (0L);
  680. }
  681.  
  682.  
  683. /* Emulator for BSD random() call
  684.  * Returns: long random number
  685.  */
  686.  
  687. long random ()
  688. {
  689.   static int beenhere = 0;
  690.   if (!beenhere) {
  691.     beenhere = 1;
  692.     srand48 (getpid ());
  693.   }
  694.   return lrand48 ();
  695. }
  696.  
  697. /* Emulator for BSD scandir() call
  698.  * Accepts: directory name
  699.  *        destination pointer of names array
  700.  *        selection function
  701.  *        comparison function
  702.  * Returns: number of elements in the array or -1 if error
  703.  */
  704.  
  705. #define DIRSIZ(d) d->d_reclen
  706.  
  707. int scandir (dirname,namelist,select,compar)
  708.     char *dirname;
  709.     struct dirent ***namelist;
  710.     int (*select) ();
  711.     int (*compar) ();
  712. {
  713.   struct dirent *p,*d,**names;
  714.   int nitems;
  715.   struct stat stb;
  716.   long nlmax;
  717.   DIR *dirp = opendir (dirname);/* open directory and get status poop */
  718.   if ((!dirp) || (fstat (dirp->dd_fd,&stb) < 0)) return -1;
  719.   nlmax = stb.st_size / 24;    /* guesstimate at number of files */
  720.   names = (struct dirent **) fs_get (nlmax * sizeof (struct dirent *));
  721.   nitems = 0;            /* initially none found */
  722.   while (d = readdir (dirp)) {    /* read directory item */
  723.                 /* matches select criterion? */
  724.     if (select && !(*select) (d)) continue;
  725.                 /* get size of dirent record for this file */
  726.     p = (struct dirent *) fs_get (DIRSIZ (d));
  727.     p->d_ino = d->d_ino;    /* copy the poop */
  728.     p->d_off = d->d_off;
  729.     p->d_reclen = d->d_reclen;
  730.     strcpy (p->d_name,d->d_name);
  731.     if (++nitems >= nlmax) {    /* if out of space, try bigger guesstimate */
  732.       nlmax *= 2;        /* double it */
  733.       fs_resize ((void **) names,nlmax * sizeof (struct dirent *));
  734.     }
  735.     names[nitems - 1] = p;    /* store this file there */
  736.   }
  737.   closedir (dirp);        /* done with directory */
  738.                 /* sort if necessary */
  739.   if (nitems && compar) qsort (names,nitems,sizeof (struct dirent *),compar);
  740.   *namelist = names;        /* return directory */
  741.   return nitems;        /* and size */
  742. }
  743.  
  744. /* Emulator for BSD flock() call
  745.  * Accepts: file descriptor
  746.  *        operation bitmask
  747.  * Returns: 0 if successful, -1 if failure
  748.  * Note: this emulator does not handle shared locks
  749.  */
  750.  
  751. int flock (fd, operation)
  752.     int fd;
  753.     int operation;
  754. {
  755.   int func;
  756.   off_t offset = lseek (fd,0,L_INCR);
  757.   switch (operation & ~LOCK_NB){/* translate to lockf() operation */
  758.   case LOCK_EX:            /* exclusive */
  759.   case LOCK_SH:            /* shared */
  760.     func = (operation & LOCK_NB) ? F_TLOCK : F_LOCK;
  761.     break;
  762.   case LOCK_UN:            /* unlock */
  763.     func = F_ULOCK;
  764.     break;
  765.   default:            /* default */
  766.     errno = EINVAL;
  767.     return -1;
  768.   }
  769.   lseek (fd,0,L_SET);        /* position to start of the file */
  770.   func = lockf (fd,func,0);    /* do the lockf() */
  771.   lseek (fd,offset,L_SET);    /* restore prior position */
  772.   return func;
  773. }
  774.  
  775.  
  776. /* Emulator for BSD gettimeofday() call
  777.  * Accepts: address where to write timeval information
  778.  *        address where to write timezone information
  779.  * Returns: 0 if successful, -1 if failure
  780.  */
  781.  
  782. int gettimeofday (tp,tzp)
  783.     struct timeval *tp;
  784.     struct timezone *tzp;
  785. {
  786.   tp->tv_sec = time (0);    /* time since 1-Jan-70 00:00:00 GMT in secs */
  787.                 /* others aren't used in current code */
  788.   if (tzp) tzp->tz_minuteswest = tzp->tz_dsttime = 0;
  789.   tp->tv_usec = 0;
  790.   return 0;
  791. }
  792.  
  793.  
  794. /* Emulator for BSD utimes() call
  795.  * Accepts: file name
  796.  *        timeval vector for access and updated time
  797.  * Returns: 0 if successful, -1 if failure
  798.  */
  799.  
  800. int utimes (file,tvp)
  801.     char *file;
  802.     struct timeval tvp[2];
  803. {
  804.   struct utimbuf tb;
  805.   tb.actime = tvp[0].tv_sec;    /* accessed time */
  806.   tb.modtime = tvp[1].tv_sec;    /* updated time */
  807.   return utime (file,&tb);
  808. }
  809.