home *** CD-ROM | disk | FTP | other *** search
/ InfoMagic Internet Tools 1993 July / Internet Tools.iso / RockRidge / mail / pine / pine3.07 / c-client / os_ptx.c < prev    next >
Encoding:
C/C++ Source or Header  |  1993-03-29  |  21.6 KB  |  799 lines

  1. /*
  2.  * Program:    Operating-system dependent routines -- PTX version
  3.  *
  4.  * Author:    Donn Cave/Mark Crispin
  5.  *        University Computing Services, JE-30
  6.  *        University of Washington
  7.  *        Seattle, WA 98195
  8.  *        Internet: donn@cac.washington.edu
  9.  *
  10.  * Date:    10 April 1992
  11.  * Last Edited:    14 May 1992
  12.  *
  13.  * Copyright 1992 by the University of Washington
  14.  *
  15.  *  Permission to use, copy, modify, and distribute this software and its
  16.  * documentation for any purpose and without fee is hereby granted, provided
  17.  * that the above copyright notice appears in all copies and that both the
  18.  * above copyright notice and this permission notice appear in supporting
  19.  * documentation, and that the name of the University of Washington not be
  20.  * used in advertising or publicity pertaining to distribution of the software
  21.  * without specific, written prior permission.  This software is made
  22.  * available "as is", and
  23.  * THE UNIVERSITY OF WASHINGTON DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED,
  24.  * WITH REGARD TO THIS SOFTWARE, INCLUDING WITHOUT LIMITATION ALL IMPLIED
  25.  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, AND IN
  26.  * NO EVENT SHALL THE UNIVERSITY OF WASHINGTON BE LIABLE FOR ANY SPECIAL,
  27.  * INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  28.  * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, TORT
  29.  * (INCLUDING NEGLIGENCE) OR STRICT LIABILITY, ARISING OUT OF OR IN CONNECTION
  30.  * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  31.  *
  32.  */
  33.  
  34. /* TCP input buffer */
  35.  
  36. #define BUFLEN 8192
  37.  
  38.  
  39. /* TCP I/O stream (must be before osdep.h is included) */
  40.  
  41. #define TCPSTREAM struct tcp_stream
  42. TCPSTREAM {
  43.   char *host;            /* host name */
  44.   char *localhost;        /* local host name */
  45.   int tcpsi;            /* input socket */
  46.   int tcpso;            /* output socket */
  47.   int ictr;            /* input counter */
  48.   char *iptr;            /* input pointer */
  49.   char ibuf[BUFLEN];        /* input buffer */
  50. };
  51.  
  52.  
  53. #include <ctype.h>
  54. #include <sys/types.h>
  55. #include <sys/time.h>
  56. #include <sys/tiuser.h>
  57. #include <sys/stropts.h>
  58. #include <sys/poll.h>
  59. #include <netinet/in.h>
  60. #include <netdb.h>
  61. #include <ctype.h>
  62. #include <regexpr.h>
  63. #include <errno.h>
  64. #include <pwd.h>
  65. #include <shadow.h>
  66. #include <syslog.h>
  67. #include <sys/file.h>
  68. #include <sys/stat.h>
  69. #include <dirent.h>
  70. #include "osdep.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. char *months[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
  86.         "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
  87.  
  88. void rfc822_date (date)
  89.     char *date;
  90. {
  91.   int zone,dstnow;
  92.   char *zonename;
  93.   struct tm *t;
  94.   int time_sec;
  95.  
  96.   time_sec = time (0);
  97.   t = localtime (&time_sec);    /* convert to individual items */
  98.                 /* use this for older systems */
  99.   tzset ();
  100.   dstnow = daylight && t->tm_isdst;
  101.                                 /* get timezone value */
  102.   zone = - (dstnow ? altzone : timezone) / 60;
  103.                                 /* and output it */
  104.  
  105.   sprintf (date,"%s, %d %s %d %02d:%02d:%02d %+03d%02d (%s)",
  106.        days[t->tm_wday],t->tm_mday,months[t->tm_mon],t->tm_year+1900,
  107.        t->tm_hour,t->tm_min,t->tm_sec,zone/60,abs (zone) % 60,
  108.            tzname[dstnow]);
  109. }
  110.  
  111. /* Get a block of free storage
  112.  * Accepts: size of desired block
  113.  * Returns: free storage block
  114.  */
  115.  
  116. void *fs_get (size)
  117.     size_t size;
  118. {
  119.   void *block = malloc (size);
  120.   if (!block) fatal ("Out of free storage");
  121.   return (block);
  122. }
  123.  
  124.  
  125. /* Resize a block of free storage
  126.  * Accepts: ** pointer to current block
  127.  *        new size
  128.  */
  129.  
  130. void fs_resize (block,size)
  131.     void **block;
  132.     size_t size;
  133. {
  134.   if (!(*block = realloc (*block,size))) fatal ("Can't resize free storage");
  135. }
  136.  
  137.  
  138. /* Return a block of free storage
  139.  * Accepts: ** pointer to free storage block
  140.  */
  141.  
  142. void fs_give (block)
  143.     void **block;
  144. {
  145.   free (*block);
  146.   *block = NIL;
  147. }
  148.  
  149.  
  150. /* Report a fatal error
  151.  * Accepts: string to output
  152.  */
  153.  
  154. void fatal (string)
  155.     char *string;
  156. {
  157.   mm_fatal (string);        /* output the string */
  158.   syslog (LOG_ALERT,"IMAP C-Client crash: %s",string);
  159.   abort ();            /* die horribly */
  160. }
  161.  
  162. /* Copy string with CRLF newlines
  163.  * Accepts: destination string
  164.  *        pointer to size of destination string
  165.  *        source string
  166.  *        length of source string
  167.  */
  168.  
  169. char *strcrlfcpy (dst,dstl,src,srcl)
  170.     char **dst;
  171.     unsigned long *dstl;
  172.     char *src;
  173.     unsigned long srcl;
  174. {
  175.   long i,j;
  176.   char *d = src;
  177.                 /* count number of LF's in source string(s) */
  178.   for (i = srcl,j = 0; j < srcl; j++) if (*d++ == '\012') i++;
  179.   if (i > *dstl) {        /* resize if not enough space */
  180.     fs_give ((void **) dst);    /* fs_resize does an unnecessary copy */
  181.     *dst = (char *) fs_get ((*dstl = i) + 1);
  182.   }
  183.   d = *dst;            /* destination string */
  184.                 /* copy strings, inserting CR's before LF's */
  185.   while (srcl--) switch (*src) {
  186.   case '\015':            /* unlikely carriage return */
  187.     *d++ = *src++;        /* copy it and any succeeding linefeed */
  188.     if (srcl && *src == '\012') {
  189.       *d++ = *src++;
  190.       srcl--;
  191.     }
  192.     break;
  193.   case '\012':            /* line feed? */
  194.     *d++ ='\015';        /* yes, prepend a CR, drop into default case */
  195.   default:            /* ordinary chararacter */
  196.     *d++ = *src++;        /* just copy character */
  197.     break;
  198.   }
  199.   *d = '\0';            /* tie off destination */
  200.   return *dst;            /* return destination */
  201. }
  202.  
  203.  
  204. /* Length of string after strcrlflen applied
  205.  * Accepts: source string
  206.  *        length of source string
  207.  */
  208.  
  209. unsigned long strcrlflen (src,srcl)
  210.     char *src;
  211.     unsigned long srcl;
  212. {
  213.   long i = srcl;        /* look for LF's */
  214.   while (srcl--) switch (*src++) {
  215.   case '\015':            /* unlikely carriage return */
  216.     if (srcl && *src == '\012') { src++; srcl--; }
  217.     break;
  218.   case '\012':            /* line feed? */
  219.     i++;
  220.   default:            /* ordinary chararacter */
  221.     break;
  222.   }
  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. int server_login (user,pass,home)
  234.     char *user;
  235.     char *pass;
  236.     char **home;
  237. {
  238.   struct passwd *pw = getpwnam (lcase (user));
  239.   struct spwd *sp;
  240.                 /* no entry for this user or root */
  241.   if (!(pw && pw->pw_uid)) return NIL;
  242.                 /* validate password and password aging */
  243.   sp = getspnam (pw->pw_name);
  244.   if (strcmp (sp->sp_pwdp, (char *) crypt (pass,sp->sp_pwdp))) return NIL;
  245.   else if ((sp->sp_lstchg > 0) && (sp->sp_max > 0) &&
  246.        ((sp->sp_lstchg + sp->sp_max) < (time (0) / (60*60*24))))
  247.     return NIL;
  248.   setgid (pw->pw_gid);        /* all OK, login in as that user */
  249.   setuid (pw->pw_uid);
  250.                 /* note home directory */
  251.   if (home) *home = cpystr (pw->pw_dir);
  252.   return T;
  253. }
  254.  
  255. /* TCP/IP open
  256.  * Accepts: host name
  257.  *        contact port number
  258.  * Returns: TCP/IP stream if success else NIL
  259.  */
  260.  
  261. TCPSTREAM *tcp_open (host,port)
  262.     char *host;
  263.     int port;
  264. {
  265.   TCPSTREAM *stream = NIL;
  266.   int sock;
  267.   char *s;
  268.   struct sockaddr_in sin;
  269.   struct hostent *host_name;
  270.   char hostname[MAILTMPLEN];
  271.   char tmp[MAILTMPLEN];
  272.     extern int t_errno;
  273.     extern char *t_errlist[];
  274.     struct t_call *sndcall;
  275.  
  276.   /* The domain literal form is used (rather than simply the dotted decimal
  277.      as with other Unix programs) because it has to be a valid "host name"
  278.      in mailsystem terminology. */
  279.                 /* look like domain literal? */
  280.   if (host[0] == '[' && host[(strlen (host))-1] == ']') {
  281.     strcpy (hostname,host+1);    /* yes, copy number part */
  282.     hostname[(strlen (hostname))-1] = '\0';
  283.     if ((sin.sin_addr.s_addr = inet_addr (hostname)) != -1) {
  284.       sin.sin_family = AF_INET;    /* family is always Internet */
  285.       strcpy (hostname,host);    /* hostname is user's argument */
  286.     }
  287.     else {
  288.       sprintf (tmp,"Bad format domain-literal: %.80s",host);
  289.       mm_log (tmp,ERROR);
  290.       return NIL;
  291.     }
  292.   }
  293.  
  294.   else {            /* lookup host name, note that brain-dead Unix
  295.                    requires lowercase! */
  296.     strcpy (hostname,host);    /* in case host is in write-protected memory */
  297.     if ((host_name = gethostbyname (lcase (hostname)))) {
  298.                 /* copy address type */
  299.       sin.sin_family = host_name->h_addrtype;
  300.                 /* copy host name */
  301.       strcpy (hostname,host_name->h_name);
  302.                 /* copy host addresses */
  303.       memcpy (&sin.sin_addr,host_name->h_addr,host_name->h_length);
  304.     }
  305.     else {
  306.       sprintf (tmp,"No such host as %.80s",host);
  307.       mm_log (tmp,ERROR);
  308.       return NIL;
  309.     }
  310.   }
  311.  
  312.                 /* copy port number in network format */
  313.   if (!(sin.sin_port = htons (port))) fatal ("Bad port argument to tcp_open");
  314.  
  315.                 /* get a TCP stream */
  316.   t_errno = 0;
  317.   if (((sock = t_open (TLI_TCP, O_RDWR, 0)) < 0) ||
  318.       (t_bind (sock, 0, 0) < 0) ||
  319.       ((sndcall = (struct t_call *) t_alloc (sock, T_CALL, T_ADDR)) == 0))
  320.   {
  321.     sprintf (tmp,"Unable to create TCP socket: %s",t_errlist[t_errno]);
  322.     mm_log (tmp,ERROR);
  323.     return NIL;
  324.   }
  325.                 /* connect to address. */
  326.   sndcall->addr.len = sndcall->addr.maxlen = sizeof (sin);
  327.   sndcall->addr.buf = (char *) &sin;
  328.   sndcall->opt.len = 0;
  329.   sndcall->udata.len = 0;
  330.   if (t_connect (sock, sndcall, 0) < 0) {
  331.     sprintf (tmp,"Can't connect to %.80s,%d: %s",hostname,port,
  332.          t_errlist[t_errno]);
  333.     mm_log (tmp,ERROR);
  334.     return NIL;
  335.   }
  336.                 /* push streams module for read()/write(). */
  337.   if (ioctl (sock, I_PUSH, "tirdwr") < 0) {
  338.     sprintf (tmp,"Unable to create TCP socket: %s",t_errlist[t_errno]);
  339.     mm_log (tmp,ERROR);
  340.     return NIL;
  341.   }
  342.                 /* create TCP/IP stream */
  343.   stream = (TCPSTREAM *) fs_get (sizeof (TCPSTREAM));
  344.                 /* copy official host name */
  345.   stream->host = cpystr (hostname);
  346.                 /* get local name */
  347.   gethostname (tmp,MAILTMPLEN-1);
  348.   stream->localhost = cpystr ((host_name = gethostbyname (tmp)) ?
  349.                   host_name->h_name : tmp);
  350.                 /* init sockets */
  351.   stream->tcpsi = stream->tcpso = sock;
  352.   stream->ictr = 0;        /* init input counter */
  353.   return stream;        /* return success */
  354. }
  355.  
  356. /* TCP/IP authenticated open
  357.  * Accepts: host name
  358.  *        service name
  359.  * Returns: TCP/IP stream if success else NIL
  360.  */
  361.  
  362. TCPSTREAM *tcp_aopen (host,service)
  363.     char *host;
  364.     char *service;
  365. {
  366.   TCPSTREAM *stream = NIL;
  367.   struct hostent *host_name;
  368.   char hostname[MAILTMPLEN];
  369.   int i;
  370.   int pipei[2],pipeo[2];
  371.   /* The domain literal form is used (rather than simply the dotted decimal
  372.      as with other Unix programs) because it has to be a valid "host name"
  373.      in mailsystem terminology. */
  374.                 /* look like domain literal? */
  375.   if (host[0] == '[' && host[i = (strlen (host))-1] == ']') {
  376.     strcpy (hostname,host+1);    /* yes, copy without brackets */
  377.     hostname[i-1] = '\0';
  378.   }
  379.                 /* note that Unix requires lowercase! */
  380.   else if (host_name = gethostbyname (lcase (strcpy (hostname,host))))
  381.     strcpy (hostname,host_name->h_name);
  382.                 /* make command pipes */
  383.   if (pipe (pipei) < 0) return NIL;
  384.   if (pipe (pipeo) < 0) {
  385.     close (pipei[0]); close (pipei[1]);
  386.     return NIL;
  387.   }
  388.   if ((i = fork ()) < 0) {    /* make inferior process */
  389.     close (pipei[0]); close (pipei[1]);
  390.     close (pipeo[0]); close (pipeo[1]);
  391.     return NIL;
  392.   }
  393.   if (i) {            /* parent? */
  394.     close (pipei[1]);        /* close child's side of the pipes */
  395.     close (pipeo[0]);
  396.   }
  397.   else {            /* child */
  398.     dup2 (pipei[1],1);        /* parent's input is my output */
  399.     dup2 (pipei[1],2);        /* parent's input is my error output too */
  400.     close (pipei[0]); close (pipei[1]);
  401.     dup2 (pipeo[0],0);        /* parent's output is my input */
  402.     close (pipeo[0]); close (pipeo[1]);
  403.                 /* now run it */
  404.     execl ("/usr/bin/resh","resh",hostname,"exec",service,0);
  405.     _exit (1);            /* spazzed */
  406.   }
  407.  
  408.                 /* create TCP/IP stream */
  409.   stream = (TCPSTREAM *) fs_get (sizeof (TCPSTREAM));
  410.                 /* copy official host name */
  411.   stream->host = cpystr (hostname);
  412.                 /* get local name */
  413.   gethostname (hostname,MAILTMPLEN-1);
  414.   stream->localhost = cpystr ((host_name = gethostbyname (hostname)) ?
  415.                   host_name->h_name : hostname);
  416.   stream->tcpsi = pipei[0];    /* init sockets */
  417.   stream->tcpso = pipeo[1];
  418.   stream->ictr = 0;        /* init input counter */
  419.   return stream;        /* return success */
  420. }
  421.  
  422. /* TCP/IP receive line
  423.  * Accepts: TCP/IP stream
  424.  * Returns: text line string or NIL if failure
  425.  */
  426.  
  427. char *tcp_getline (stream)
  428.     TCPSTREAM *stream;
  429. {
  430.   int n,m;
  431.   char *st;
  432.   char *ret;
  433.   char *stp;
  434.   char tmp[2];
  435.   struct pollfd pollfd;
  436.   int pollstatus;
  437.   if (stream->tcpsi < 0) return NIL;
  438.   pollfd.fd = stream->tcpsi;    /* initialize selection vector */
  439.   while (stream->ictr < 1) {    /* if nothing in the buffer */
  440.                 /* block and read */
  441.     pollfd.events = POLLIN;
  442.     /* Note: am not sure here that it wouldn't also be a good idea to
  443.     restart poll() on EINTR, if SIGCHLD or whatever are expected.    DC */
  444.     while (((pollstatus = poll (&pollfd,1,-1)) < 0) && (errno == EAGAIN));
  445.     if (!pollstatus ||
  446.     ((stream->ictr = read (stream->tcpsi,stream->ibuf,BUFLEN)) < 1)) {
  447.       close (stream->tcpsi);    /* nuke the socket */
  448.       if (stream->tcpsi != stream->tcpso) close (stream->tcpso);
  449.       stream->tcpsi = stream->tcpso = -1;
  450.       return NIL;
  451.     }
  452.     stream->iptr = stream->ibuf;/* point at TCP buffer */
  453.   }
  454.   st = stream->iptr;        /* save start of string */
  455.   n = 0;            /* init string count */
  456.   while (stream->ictr--) {    /* look for end of line */
  457.                 /* saw the trailing CR? */
  458.     if (stream->iptr++[0] == '\015') {
  459.       ret = (char *) fs_get (n+1);
  460.       memcpy (ret,st,n);    /* copy into a free storage string */
  461.       ret[n] = '\0';        /* tie off string with null */
  462.                 /* eat the line feed */
  463.       tcp_getbuffer (stream,1,tmp);
  464.       return ret;        /* return it to caller */
  465.     }
  466.     ++n;            /* else count and try next character */
  467.   }
  468.   stp = (char *) fs_get (n);    /* copy first part of string */
  469.   memcpy (stp,st,n);
  470.                 /* recurse to get remainder */
  471.   if (st = tcp_getline (stream)) {
  472.                 /* build total string */
  473.     ret = (char *) fs_get (n+1+(m = strlen (st)));
  474.     memcpy (ret,stp,n);        /* copy first part */
  475.     memcpy (ret+n,st,m);    /* and second part */
  476.     ret[n+m] = '\0';        /* tie off string with null */
  477.     fs_give ((void **) &st);    /* flush partial string */
  478.     fs_give ((void **) &stp);    /* flush initial fragment */
  479.   }
  480.   else ret = stp;        /* return the fragment */
  481.   return ret;
  482. }
  483.  
  484. /* TCP/IP receive buffer
  485.  * Accepts: TCP/IP stream
  486.  *        size in bytes
  487.  *        buffer to read into
  488.  * Returns: T if success, NIL otherwise
  489.  */
  490.  
  491. int tcp_getbuffer (stream,size,buffer)
  492.     TCPSTREAM *stream;
  493.     unsigned long size;
  494.     char *buffer;
  495. {
  496.   unsigned long n;
  497.   char *bufptr = buffer;
  498.   struct pollfd pollfd;
  499.   int pollstatus;
  500.   pollfd.fd = stream->tcpsi;    /* initialize selection vector */
  501.   pollfd.events = POLLIN;
  502.   if (stream->tcpsi < 0) return NIL;
  503.   while (size > 0) {        /* until request satisfied */
  504.     while (stream->ictr < 1) {    /* if nothing in the buffer */
  505.       while (((pollstatus = poll (&pollfd,1,-1)) < 0) && (errno == EAGAIN));
  506.       if (!pollstatus ||
  507.       ((stream->ictr = read (stream->tcpsi,stream->ibuf,BUFLEN)) < 1)) {
  508.     close (stream->tcpsi);    /* nuke the socket */
  509.     if (stream->tcpsi != stream->tcpso) close (stream->tcpso);
  510.     stream->tcpsi = stream->tcpso = -1;
  511.     return NIL;
  512.       }
  513.                 /* point at TCP buffer */
  514.       stream->iptr = stream->ibuf;
  515.     }
  516.     n = min (size,stream->ictr);/* number of bytes to transfer */
  517.                 /* do the copy */
  518.     memcpy (bufptr,stream->iptr,n);
  519.     bufptr += n;        /* update pointer */
  520.     stream->iptr +=n;
  521.     size -= n;            /* update # of bytes to do */
  522.     stream->ictr -=n;
  523.   }
  524.   bufptr[0] = '\0';        /* tie off string */
  525.   return T;
  526. }
  527.  
  528. /* TCP/IP send string as record
  529.  * Accepts: TCP/IP stream
  530.  * Returns: T if success else NIL
  531.  */
  532.  
  533. int tcp_soutr (stream,string)
  534.     TCPSTREAM *stream;
  535.     char *string;
  536. {
  537.   int i;
  538.   unsigned long size = strlen (string);
  539.   struct pollfd pollfd;
  540.   int pollstatus;
  541.   pollfd.fd = stream->tcpso;    /* initialize selection vector */
  542.   pollfd.events = POLLOUT;
  543.   if (stream->tcpso < 0) return NIL;
  544.   while (size > 0) {        /* until request satisfied */
  545.     while (((pollstatus = poll (&pollfd,1,-1)) < 0) && (errno == EAGAIN));
  546.     if (!pollstatus ||
  547.     ((i = write (stream->tcpso,string,size)) < 0)) {
  548.       puts (strerror (errno));
  549.       close (stream->tcpsi);    /* nuke the socket */
  550.       if (stream->tcpsi != stream->tcpso) close (stream->tcpso);
  551.       stream->tcpsi = stream->tcpso = -1;
  552.       return NIL;
  553.     }
  554.     size -= i;            /* count this size */
  555.     string += i;
  556.   }
  557.   return T;            /* all done */
  558. }
  559.  
  560.  
  561. /* TCP/IP close
  562.  * Accepts: TCP/IP stream
  563.  */
  564.  
  565. void tcp_close (stream)
  566.     TCPSTREAM *stream;
  567. {
  568.  
  569.   if (stream->tcpsi >= 0) {    /* no-op if no socket */
  570.     close (stream->tcpsi);    /* nuke the socket */
  571.     if (stream->tcpsi != stream->tcpso) close (stream->tcpso);
  572.     stream->tcpsi = stream->tcpso = -1;
  573.   }
  574.                 /* flush host names */
  575.   fs_give ((void **) &stream->host);
  576.   fs_give ((void **) &stream->localhost);
  577.   fs_give ((void **) &stream);    /* flush the stream */
  578. }
  579.  
  580. /* TCP/IP get host name
  581.  * Accepts: TCP/IP stream
  582.  * Returns: host name for this stream
  583.  */
  584.  
  585. char *tcp_host (stream)
  586.     TCPSTREAM *stream;
  587. {
  588.   return stream->host;        /* return host name */
  589. }
  590.  
  591.  
  592. /* TCP/IP get local host name
  593.  * Accepts: TCP/IP stream
  594.  * Returns: local host name
  595.  */
  596.  
  597. char *tcp_localhost (stream)
  598.     TCPSTREAM *stream;
  599. {
  600.   return stream->localhost;    /* return local host name */
  601. }
  602.  
  603. /* Emulator for BSD gethostid() call
  604.  * Returns: unique identifier for this machine
  605.  */
  606.  
  607. long gethostid ()
  608. {
  609.   struct sockaddr_in sin;
  610.   int inet = t_open (TLI_TCP, O_RDWR, 0);
  611.   if (inet < 0) return 0;
  612.   getmyinaddr (inet,&sin,sizeof (sin));
  613.   close (inet);
  614.   return sin.sin_addr.s_addr;
  615. }
  616.  
  617.  
  618. /* Emulator for BSD random() call
  619.  * Returns: long random number
  620.  */
  621.  
  622. long random ()
  623. {
  624.   static int beenhere = 0;
  625.   if (!beenhere) {
  626.     beenhere = 1;
  627.     srand48 (getpid ());
  628.   }
  629.   return lrand48 ();
  630. }
  631.  
  632.  
  633. /* Copy memory block
  634.  * Accepts: destination pointer
  635.  *        source pointer
  636.  *        length
  637.  * Returns: destination pointer
  638.  */
  639.  
  640. void *memmove (s,ct,n)
  641.     void *s;
  642.     void *ct;
  643.     int n;
  644. {
  645.   char *dp, *sp;
  646.   int i;
  647.   unsigned long dest = (unsigned long) s;
  648.   unsigned long src = (unsigned long) ct;
  649.   if (((dest < src) && ((dest + n) < src)) ||
  650.       ((dest > src) && ((src + n) < dest))) return memcpy (s, ct, n);
  651.   dp = s;
  652.   sp = ct;
  653.   if (dest < src) for (i = 0; i < n; ++i) dp[i] = sp[i];
  654.   else if (dest > src) for (i = n - 1; i >= 0; --i) dp[i] = sp[i];
  655.   return s;
  656. }
  657.  
  658. /* Emulator for BSD re_comp() call
  659.  * Accepts: character string to compile
  660.  * Returns: 0 if successful, else error message
  661.  * Uses the regexpr(3X) libraries.
  662.  * Don't forget to link against /usr/lib/libgen.a
  663.  */
  664.  
  665. #define PATMAX 256
  666. static char re_space[PATMAX];
  667.  
  668. char *re_comp (str)
  669.     char *str;
  670. {
  671.   char *c;
  672.   static char *invalstr = "invalid string";
  673.   if (str) {            /* must have a string to compile */
  674.     c = compile (str,re_space,re_space + PATMAX);
  675.     if ((c >= re_space) && (c <= re_space + PATMAX)) return 0;
  676.   }
  677.   re_space[0] = 0;
  678.   return invalstr;
  679. }
  680.  
  681.  
  682. /* Emulator for BSD re_exec() call
  683.  * Accepts: string to match
  684.  * Returns: 1 if string matches, 0 if fails to match, -1 if re_comp() failed
  685.  */
  686.  
  687. long re_exec (str)
  688.     char *str;
  689. {
  690.   if (!re_space[0]) return -1;    /* re_comp() failed? */
  691.   return step (str,re_space) ? 1 : 0;
  692. }
  693.  
  694. /* Emulator for BSD scandir() call
  695.  * Accepts: directory name
  696.  *        destination pointer of names array
  697.  *        selection function
  698.  *        comparison function
  699.  * Returns: number of elements in the array or -1 if error
  700.  */
  701.  
  702. #define DIRSIZ(d) d->d_reclen
  703.  
  704. int scandir (dirname,namelist,select,compar)
  705.     char *dirname;
  706.     struct dirent ***namelist;
  707.     int (*select) ();
  708.     int (*compar) ();
  709. {
  710.   struct dirent *p,*d,**names;
  711.   int nitems;
  712.   struct stat stb;
  713.   long nlmax;
  714.   DIR *dirp = opendir (dirname);/* open directory and get status poop */
  715.   if ((!dirp) || (fstat (dirp->dd_fd,&stb) < 0)) return -1;
  716.   nlmax = stb.st_size / 24;    /* guesstimate at number of files */
  717.   names = (struct dirent **) fs_get (nlmax * sizeof (struct dirent *));
  718.   nitems = 0;            /* initially none found */
  719.   while (d = readdir (dirp)) {    /* read directory item */
  720.                 /* matches select criterion? */
  721.     if (select && !(*select) (d)) continue;
  722.                 /* get size of dirent record for this file */
  723.     p = (struct dirent *) fs_get (DIRSIZ (d));
  724.     p->d_ino = d->d_ino;    /* copy the poop */
  725.     p->d_off = d->d_off;
  726.     p->d_reclen = d->d_reclen;
  727.     strcpy (d->d_name,p->d_name);
  728.     if (++nitems >= nlmax) {    /* if out of space, try bigger guesstimate */
  729.       nlmax *= 2;        /* double it */
  730.       fs_resize ((void **) names,nlmax * sizeof (struct dirent *));
  731.     }
  732.     names[nitems - 1] = p;    /* store this file there */
  733.   }
  734.   closedir (dirp);        /* done with directory */
  735.                 /* sort if necessary */
  736.   if (nitems && compar) qsort (names,nitems,sizeof (struct dirent *),compar);
  737.   *namelist = names;        /* return directory */
  738.   return nitems;        /* and size */
  739. }
  740.  
  741. /* Emulator for BSD flock() call
  742.  * Accepts: file descriptor
  743.  *        operation bitmask
  744.  * Returns: 0 if successful, -1 if failure
  745.  * Note: this emulator does not handle shared locks
  746.  */
  747.  
  748. int flock (fd, operation)
  749.     int fd;
  750.     int operation;
  751. {
  752.   int func;
  753.                 /* translate to flock() operation */
  754.   if (operation & LOCK_UN) func = F_ULOCK;
  755.   else if (operation & (LOCK_EX|LOCK_SH))
  756.     func = (operation & LOCK_NB) ? F_TLOCK : F_LOCK;
  757.   else {
  758.     errno = EINVAL;
  759.     return -1;
  760.   }
  761.   return lockf (fd,func,0);    /* do the lockf() */
  762. }
  763.  
  764.  
  765. /* Emulator for BSD gettimeofday() call
  766.  * Accepts: address where to write timeval information
  767.  *        address where to write timezone information
  768.  * Returns: 0 if successful, -1 if failure
  769.  */
  770.  
  771. int gettimeofday (tp,tzp)
  772.     struct timeval *tp;
  773.     struct timezone *tzp;
  774. {
  775.   tp->tv_sec = time (0);    /* time since 1-Jan-70 00:00:00 GMT in secs */
  776.                 /* others aren't used in current code */
  777.   if (tzp) tzp->tz_minuteswest = tzp->tz_dsttime = 0;
  778.   tp->tv_usec = 0;
  779.   return 0;
  780. }
  781.  
  782.  
  783. /* Emulator for BSD utimes() call
  784.  * Accepts: file name
  785.  *        timeval vector for access and updated time
  786.  * Returns: 0 if successful, -1 if failure
  787.  */
  788.  
  789. int utimes (file,tvp)
  790.     char *file;
  791.     struct timeval tvp[2];
  792. {
  793.   struct utimbuf tb;
  794.   tb.actime = tvp[0].tv_sec;    /* accessed time */
  795.   tb.modtime = tvp[1].tv_sec;    /* updated time */
  796.   return utime (file,&tb);
  797. }
  798.  
  799.