home *** CD-ROM | disk | FTP | other *** search
/ InfoMagic Internet Tools 1993 July / Internet Tools.iso / RockRidge / mail / pine / imap-3.0 / non-ANSI / c-client / os_dyn.c < prev    next >
Encoding:
C/C++ Source or Header  |  1993-05-18  |  22.6 KB  |  865 lines

  1. /*
  2.  * Program:    Operating-system dependent routines -- Dynix 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.  *
  11.  * Date:    11 May 1989
  12.  * Last Edited:    19 May 1993
  13.  *
  14.  * Copyright 1993 by the University of Washington
  15.  *
  16.  *  Permission to use, copy, modify, and distribute this software and its
  17.  * documentation for any purpose and without fee is hereby granted, provided
  18.  * that the above copyright notice appears in all copies and that both the
  19.  * above copyright notice and this permission notice appear in supporting
  20.  * documentation, and that the name of the University of Washington not be
  21.  * used in advertising or publicity pertaining to distribution of the software
  22.  * without specific, written prior permission.  This software is made
  23.  * available "as is", and
  24.  * THE UNIVERSITY OF WASHINGTON DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED,
  25.  * WITH REGARD TO THIS SOFTWARE, INCLUDING WITHOUT LIMITATION ALL IMPLIED
  26.  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, AND IN
  27.  * NO EVENT SHALL THE UNIVERSITY OF WASHINGTON BE LIABLE FOR ANY SPECIAL,
  28.  * INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  29.  * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, TORT
  30.  * (INCLUDING NEGLIGENCE) OR STRICT LIABILITY, ARISING OUT OF OR IN CONNECTION
  31.  * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  32.  *
  33.  */
  34.  
  35. /* TCP input buffer */
  36.  
  37. #define BUFLEN 8192
  38.  
  39.  
  40. /* TCP I/O stream (must be before osdep.h is included) */
  41.  
  42. #define TCPSTREAM struct tcp_stream
  43. TCPSTREAM {
  44.   char *host;            /* host name */
  45.   char *localhost;        /* local host name */
  46.   int tcpsi;            /* input socket */
  47.   int tcpso;            /* output socket */
  48.   int ictr;            /* input counter */
  49.   char *iptr;            /* input pointer */
  50.   char ibuf[BUFLEN];        /* input buffer */
  51. };
  52.  
  53.  
  54. #include "osdep.h"
  55. #include <ctype.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 "mail.h"
  66. #include "misc.h"
  67.  
  68. extern char *timezone  ();
  69. extern int sys_nerr;
  70. extern char *sys_errlist[];
  71.  
  72. #define toint(c)    ((c)-'0')
  73. #define isodigit(c)    (((unsigned)(c)>=060)&((unsigned)(c)<=067))
  74.  
  75. /* Write current time in RFC 822 format
  76.  * Accepts: destination string
  77.  */
  78.  
  79. char *days[] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
  80.  
  81. void rfc822_date (date)
  82.     char *date;
  83. {
  84.   int zone;
  85.   char *zonename;
  86.   struct tm *t;
  87.   struct timeval tv;
  88.   struct timezone tz;
  89.   gettimeofday (&tv,&tz);    /* get time and timezone poop */
  90.   t = localtime (&tv.tv_sec);    /* convert to individual items */
  91.                 /* use this for older systems */
  92.   zone = (t->tm_isdst ? 60 : 0) -tz.tz_minuteswest;
  93.   zonename = timezone (tz.tz_minuteswest,t->tm_isdst);
  94.                 /* and output it */
  95.   sprintf (date,"%s, %d %s %d %02d:%02d:%02d %+03d%02d (%s)",
  96.        days[t->tm_wday],t->tm_mday,months[t->tm_mon],t->tm_year+1900,
  97.        t->tm_hour,t->tm_min,t->tm_sec,zone/60,abs (zone) % 60,zonename);
  98. }
  99.  
  100. /* Get a block of free storage
  101.  * Accepts: size of desired block
  102.  * Returns: free storage block
  103.  */
  104.  
  105. void *fs_get (size)
  106.     size_t size;
  107. {
  108.   void *block = malloc (size);
  109.   if (!block) fatal ("Out of free storage");
  110.   return (block);
  111. }
  112.  
  113.  
  114. /* Resize a block of free storage
  115.  * Accepts: ** pointer to current block
  116.  *        new size
  117.  */
  118.  
  119. void fs_resize (block,size)
  120.     void **block;
  121.     size_t size;
  122. {
  123.   if (!(*block = realloc (*block,size))) fatal ("Can't resize free storage");
  124. }
  125.  
  126.  
  127. /* Return a block of free storage
  128.  * Accepts: ** pointer to free storage block
  129.  */
  130.  
  131. void fs_give (block)
  132.     void **block;
  133. {
  134.   free (*block);
  135.   *block = NIL;
  136. }
  137.  
  138.  
  139. /* Report a fatal error
  140.  * Accepts: string to output
  141.  */
  142.  
  143. void fatal (string)
  144.     char *string;
  145. {
  146.   mm_fatal (string);        /* output the string */
  147.   syslog (LOG_ALERT,"IMAP C-Client crash: %s",string);
  148.   abort ();            /* die horribly */
  149. }
  150.  
  151. /* Copy string with CRLF newlines
  152.  * Accepts: destination string
  153.  *        pointer to size of destination string
  154.  *        source string
  155.  *        length of source string
  156.  */
  157.  
  158. char *strcrlfcpy (dst,dstl,src,srcl)
  159.     char **dst;
  160.     unsigned long *dstl;
  161.     char *src;
  162.     unsigned long srcl;
  163. {
  164.   long i,j;
  165.   char *d = src;
  166.                 /* count number of LF's in source string(s) */
  167.   for (i = srcl,j = 0; j < srcl; j++) if (*d++ == '\012') i++;
  168.   if (i > *dstl) {        /* resize if not enough space */
  169.     fs_give ((void **) dst);    /* fs_resize does an unnecessary copy */
  170.     *dst = (char *) fs_get ((*dstl = i) + 1);
  171.   }
  172.   d = *dst;            /* destination string */
  173.                 /* copy strings, inserting CR's before LF's */
  174.   while (srcl--) switch (*src) {
  175.   case '\015':            /* unlikely carriage return */
  176.     *d++ = *src++;        /* copy it and any succeeding linefeed */
  177.     if (srcl && *src == '\012') {
  178.       *d++ = *src++;
  179.       srcl--;
  180.     }
  181.     break;
  182.   case '\012':            /* line feed? */
  183.     *d++ ='\015';        /* yes, prepend a CR, drop into default case */
  184.   default:            /* ordinary chararacter */
  185.     *d++ = *src++;        /* just copy character */
  186.     break;
  187.   }
  188.   *d = '\0';            /* tie off destination */
  189.   return *dst;            /* return destination */
  190. }
  191.  
  192.  
  193. /* Length of string after strcrlfcpy applied
  194.  * Accepts: source string
  195.  *        length of source string
  196.  */
  197.  
  198. unsigned long strcrlflen (s)
  199.     STRING *s;
  200. {
  201.   unsigned long pos = GETPOS (s);
  202.   unsigned long i = SIZE (s);
  203.   unsigned long j = i;
  204.   while (j--) switch (SNX (s)) {/* search for newlines */
  205.   case '\015':            /* unlikely carriage return */
  206.     if (j && (CHR (s) == '\012')) {
  207.       SNX (s);            /* eat the line feed */
  208.       j--;
  209.     }
  210.     break;
  211.   case '\012':            /* line feed? */
  212.     i++;
  213.   default:            /* ordinary chararacter */
  214.     break;
  215.   }
  216.   SETPOS (s,pos);        /* restore old position */
  217.   return i;
  218. }
  219.  
  220. /* Server log in
  221.  * Accepts: user name string
  222.  *        password string
  223.  *        optional place to return home directory
  224.  * Returns: T if password validated, NIL otherwise
  225.  */
  226.  
  227. long server_login (user,pass,home,argc,argv)
  228.     char *user;
  229.     char *pass;
  230.     char **home;
  231.     int argc;
  232.     char *argv[];
  233. {
  234.   struct passwd *pw = getpwnam (lcase (user));
  235.                 /* no entry for this user or root */
  236.   if (!(pw && pw->pw_uid)) return NIL;
  237.                 /* validate password */
  238.   if (strcmp (pw->pw_passwd,(char *) crypt (pass,pw->pw_passwd))) return NIL;
  239.   setgid (pw->pw_gid);        /* all OK, login in as that user */
  240.   initgroups (user,pw->pw_gid);    /* initialize groups */
  241.   setuid (pw->pw_uid);
  242.                 /* note home directory */
  243.   if (home) *home = cpystr (pw->pw_dir);
  244.   return T;
  245. }
  246.  
  247. /* Return my user name
  248.  * Returns: my user name
  249.  */
  250.  
  251. char *uname = NIL;
  252.  
  253. char *myusername ()
  254. {
  255.   return uname ? uname : (uname = cpystr (getpwuid (geteuid ())->pw_name));
  256. }
  257.  
  258.  
  259. /* Return my home directory name
  260.  * Returns: my home directory name
  261.  */
  262.  
  263. char *hdname = NIL;
  264.  
  265. char *myhomedir ()
  266. {
  267.   return hdname ? hdname : (hdname = cpystr (getpwuid (geteuid ())->pw_dir));
  268. }
  269.  
  270.  
  271. /* Build status lock file name
  272.  * Accepts: scratch buffer
  273.  *        file name
  274.  * Returns: name of file to lock
  275.  */
  276.  
  277. char *lockname (tmp,fname)
  278.     char *tmp;
  279.     char *fname;
  280. {
  281.   int i;
  282.   sprintf (tmp,"/tmp/.%s",fname);
  283.   for (i = 6; i < strlen (tmp); ++i) if (tmp[i] == '/') tmp[i] = '\\';
  284.   return tmp;            /* note name for later */
  285. }
  286.  
  287. /* TCP/IP open
  288.  * Accepts: host name
  289.  *        contact port number
  290.  * Returns: TCP/IP stream if success else NIL
  291.  */
  292.  
  293. TCPSTREAM *tcp_open (host,port)
  294.     char *host;
  295.     long port;
  296. {
  297.   TCPSTREAM *stream = NIL;
  298.   int sock;
  299.   char *s;
  300.   struct sockaddr_in sin;
  301.   struct hostent *host_name;
  302.   char hostname[MAILTMPLEN];
  303.   char tmp[MAILTMPLEN];
  304.   /* The domain literal form is used (rather than simply the dotted decimal
  305.      as with other Unix programs) because it has to be a valid "host name"
  306.      in mailsystem terminology. */
  307.                 /* look like domain literal? */
  308.   if (host[0] == '[' && host[(strlen (host))-1] == ']') {
  309.     strcpy (hostname,host+1);    /* yes, copy number part */
  310.     hostname[(strlen (hostname))-1] = '\0';
  311.     if ((sin.sin_addr.s_addr = inet_addr (hostname)) != -1) {
  312.       sin.sin_family = AF_INET;    /* family is always Internet */
  313.       strcpy (hostname,host);    /* hostname is user's argument */
  314.     }
  315.     else {
  316.       sprintf (tmp,"Bad format domain-literal: %.80s",host);
  317.       mm_log (tmp,ERROR);
  318.       return NIL;
  319.     }
  320.   }
  321.  
  322.   else {            /* lookup host name, note that brain-dead Unix
  323.                    requires lowercase! */
  324.     strcpy (hostname,host);    /* in case host is in write-protected memory */
  325.     if ((host_name = gethostbyname (lcase (hostname)))) {
  326.                 /* copy address type */
  327.       sin.sin_family = host_name->h_addrtype;
  328.                 /* copy host name */
  329.       strcpy (hostname,host_name->h_name);
  330.                 /* copy host addresses */
  331.       memcpy (&sin.sin_addr,host_name->h_addr,host_name->h_length);
  332.     }
  333.     else {
  334.       sprintf (tmp,"No such host as %.80s",host);
  335.       mm_log (tmp,ERROR);
  336.       return NIL;
  337.     }
  338.   }
  339.  
  340.                 /* copy port number in network format */
  341.   if (!(sin.sin_port = htons (port))) fatal ("Bad port argument to tcp_open");
  342.                 /* get a TCP stream */
  343.   if ((sock = socket (sin.sin_family,SOCK_STREAM,0)) < 0) {
  344.     sprintf (tmp,"Unable to create TCP socket: %s",strerror (errno));
  345.     mm_log (tmp,ERROR);
  346.     return NIL;
  347.   }
  348.                 /* open connection */
  349.   if (connect (sock,(struct sockaddr *)&sin,sizeof (sin)) < 0) {
  350.     sprintf (tmp,"Can't connect to %.80s,%d: %s",hostname,port,
  351.          strerror (errno));
  352.     mm_log (tmp,ERROR);
  353.     return NIL;
  354.   }
  355.                 /* create TCP/IP stream */
  356.   stream = (TCPSTREAM *) fs_get (sizeof (TCPSTREAM));
  357.                 /* copy official host name */
  358.   stream->host = cpystr (hostname);
  359.                 /* get local name */
  360.   gethostname (tmp,MAILTMPLEN-1);
  361.   stream->localhost = cpystr ((host_name = gethostbyname (tmp)) ?
  362.                   host_name->h_name : tmp);
  363.                 /* init sockets */
  364.   stream->tcpsi = stream->tcpso = sock;
  365.   stream->ictr = 0;        /* init input counter */
  366.   return stream;        /* return success */
  367. }
  368.  
  369. /* TCP/IP authenticated open
  370.  * Accepts: host name
  371.  *        service name
  372.  * Returns: TCP/IP stream if success else NIL
  373.  */
  374.  
  375. TCPSTREAM *tcp_aopen (host,service)
  376.     char *host;
  377.     char *service;
  378. {
  379.   TCPSTREAM *stream = NIL;
  380.   struct hostent *host_name;
  381.   char hostname[MAILTMPLEN];
  382.   int i;
  383.   int pipei[2],pipeo[2];
  384.   /* The domain literal form is used (rather than simply the dotted decimal
  385.      as with other Unix programs) because it has to be a valid "host name"
  386.      in mailsystem terminology. */
  387.                 /* look like domain literal? */
  388.   if (host[0] == '[' && host[i = (strlen (host))-1] == ']') {
  389.     strcpy (hostname,host+1);    /* yes, copy without brackets */
  390.     hostname[i-1] = '\0';
  391.   }
  392.                 /* note that Unix requires lowercase! */
  393.   else if (host_name = gethostbyname (lcase (strcpy (hostname,host))))
  394.     strcpy (hostname,host_name->h_name);
  395.                 /* make command pipes */
  396.   if (pipe (pipei) < 0) return NIL;
  397.   if (pipe (pipeo) < 0) {
  398.     close (pipei[0]); close (pipei[1]);
  399.     return NIL;
  400.   }
  401.   if ((i = fork ()) < 0) {    /* make inferior process */
  402.     close (pipei[0]); close (pipei[1]);
  403.     close (pipeo[0]); close (pipeo[1]);
  404.     return NIL;
  405.   }
  406.   if (i) {            /* parent? */
  407.     close (pipei[1]);        /* close child's side of the pipes */
  408.     close (pipeo[0]);
  409.   }
  410.   else {            /* child */
  411.     dup2 (pipei[1],1);        /* parent's input is my output */
  412.     dup2 (pipei[1],2);        /* parent's input is my error output too */
  413.     close (pipei[0]); close (pipei[1]);
  414.     dup2 (pipeo[0],0);        /* parent's output is my input */
  415.     close (pipeo[0]); close (pipeo[1]);
  416.                 /* now run it */
  417.     execl ("/usr/ucb/rsh","rsh",hostname,"exec",service,0);
  418.     _exit (1);            /* spazzed */
  419.   }
  420.  
  421.                 /* create TCP/IP stream */
  422.   stream = (TCPSTREAM *) fs_get (sizeof (TCPSTREAM));
  423.                 /* copy official host name */
  424.   stream->host = cpystr (hostname);
  425.                 /* get local name */
  426.   gethostname (hostname,MAILTMPLEN-1);
  427.   stream->localhost = cpystr ((host_name = gethostbyname (hostname)) ?
  428.                   host_name->h_name : hostname);
  429.   stream->tcpsi = pipei[0];    /* init sockets */
  430.   stream->tcpso = pipeo[1];
  431.   stream->ictr = 0;        /* init input counter */
  432.   return stream;        /* return success */
  433. }
  434.  
  435. /* TCP/IP receive line
  436.  * Accepts: TCP/IP stream
  437.  * Returns: text line string or NIL if failure
  438.  */
  439.  
  440. char *tcp_getline (stream)
  441.     TCPSTREAM *stream;
  442. {
  443.   int n,m;
  444.   char *st,*ret,*stp;
  445.   char c = '\0';
  446.   char d;
  447.                 /* make sure have data */
  448.   if (!tcp_getdata (stream)) return NIL;
  449.   st = stream->iptr;        /* save start of string */
  450.   n = 0;            /* init string count */
  451.   while (stream->ictr--) {    /* look for end of line */
  452.     d = *stream->iptr++;    /* slurp another character */
  453.     if ((c == '\015') && (d == '\012')) {
  454.       ret = (char *) fs_get (n--);
  455.       memcpy (ret,st,n);    /* copy into a free storage string */
  456.       ret[n] = '\0';        /* tie off string with null */
  457.       return ret;
  458.     }
  459.     n++;            /* count another character searched */
  460.     c = d;            /* remember previous character */
  461.   }
  462.                 /* copy partial string from buffer */
  463.   memcpy ((ret = stp = (char *) fs_get (n)),st,n);
  464.                 /* get more data from the net */
  465.   if (!tcp_getdata (stream)) return NIL;
  466.                 /* special case of newline broken by buffer */
  467.   if ((c == '\015') && (*stream->iptr == '\012')) {
  468.     stream->iptr++;        /* eat the line feed */
  469.     stream->ictr--;
  470.     ret[n - 1] = '\0';        /* tie off string with null */
  471.   }
  472.                 /* else recurse to get remainder */
  473.   else if (st = tcp_getline (stream)) {
  474.     ret = (char *) fs_get (n + 1 + (m = strlen (st)));
  475.     memcpy (ret,stp,n);        /* copy first part */
  476.     memcpy (ret + n,st,m);    /* and second part */
  477.     fs_give ((void **) &stp);    /* flush first part */
  478.     fs_give ((void **) &st);    /* flush second part */
  479.     ret[n + m] = '\0';        /* tie off string with null */
  480.   }
  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. long 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.   while (size > 0) {        /* until request satisfied */
  499.     if (!tcp_getdata (stream)) return NIL;
  500.     n = min (size,stream->ictr);/* number of bytes to transfer */
  501.                 /* do the copy */
  502.     memcpy (bufptr,stream->iptr,n);
  503.     bufptr += n;        /* update pointer */
  504.     stream->iptr +=n;
  505.     size -= n;            /* update # of bytes to do */
  506.     stream->ictr -=n;
  507.   }
  508.   bufptr[0] = '\0';        /* tie off string */
  509.   return T;
  510. }
  511.  
  512.  
  513. /* TCP/IP receive data
  514.  * Accepts: TCP/IP stream
  515.  * Returns: T if success, NIL otherwise
  516.  */
  517.  
  518. long tcp_getdata (stream)
  519.     TCPSTREAM *stream;
  520. {
  521.   fd_set fds;
  522.   FD_ZERO (&fds);        /* initialize selection vector */
  523.   if (stream->tcpsi < 0) return NIL;
  524.   while (stream->ictr < 1) {    /* if nothing in the buffer */
  525.     FD_SET (stream->tcpsi,&fds);/* set bit in selection vector */
  526.                 /* block and read */
  527.     if ((select (stream->tcpsi+1,&fds,0,0,0) < 0) ||
  528.     ((stream->ictr = read (stream->tcpsi,stream->ibuf,BUFLEN)) < 1)) {
  529.       close (stream->tcpsi);    /* nuke the socket */
  530.       if (stream->tcpsi != stream->tcpso) close (stream->tcpso);
  531.       stream->tcpsi = stream->tcpso = -1;
  532.       return NIL;
  533.     }
  534.     stream->iptr = stream->ibuf;/* point at TCP buffer */
  535.   }
  536.   return T;
  537. }
  538.  
  539. /* TCP/IP send string as record
  540.  * Accepts: TCP/IP stream
  541.  *        string pointer
  542.  * Returns: T if success else NIL
  543.  */
  544.  
  545. long tcp_soutr (stream,string)
  546.     TCPSTREAM *stream;
  547.     char *string;
  548. {
  549.   return tcp_sout (stream,string,(unsigned long) strlen (string));
  550. }
  551.  
  552.  
  553. /* TCP/IP send string
  554.  * Accepts: TCP/IP stream
  555.  *        string pointer
  556.  *        byte count
  557.  * Returns: T if success else NIL
  558.  */
  559.  
  560. long tcp_sout (stream,string,size)
  561.     TCPSTREAM *stream;
  562.     char *string;
  563.     unsigned long size;
  564. {
  565.   int i;
  566.   fd_set fds;
  567.   FD_ZERO (&fds);        /* initialize selection vector */
  568.   if (stream->tcpso < 0) return NIL;
  569.   while (size > 0) {        /* until request satisfied */
  570.     FD_SET (stream->tcpso,&fds);/* set bit in selection vector */
  571.     if ((select (stream->tcpso+1,0,&fds,0,0) < 0) ||
  572.     ((i = write (stream->tcpso,string,size)) < 0)) {
  573.       puts (strerror (errno));
  574.       close (stream->tcpsi);    /* nuke the socket */
  575.       if (stream->tcpsi != stream->tcpso) close (stream->tcpso);
  576.       stream->tcpsi = stream->tcpso = -1;
  577.       return NIL;
  578.     }
  579.     size -= i;            /* count this size */
  580.     string += i;
  581.   }
  582.   return T;            /* all done */
  583. }
  584.  
  585. /* TCP/IP close
  586.  * Accepts: TCP/IP stream
  587.  */
  588.  
  589. void tcp_close (stream)
  590.     TCPSTREAM *stream;
  591. {
  592.  
  593.   if (stream->tcpsi >= 0) {    /* no-op if no socket */
  594.     close (stream->tcpsi);    /* nuke the socket */
  595.     if (stream->tcpsi != stream->tcpso) close (stream->tcpso);
  596.     stream->tcpsi = stream->tcpso = -1;
  597.   }
  598.                 /* flush host names */
  599.   fs_give ((void **) &stream->host);
  600.   fs_give ((void **) &stream->localhost);
  601.   fs_give ((void **) &stream);    /* flush the stream */
  602. }
  603.  
  604.  
  605. /* TCP/IP get host name
  606.  * Accepts: TCP/IP stream
  607.  * Returns: host name for this stream
  608.  */
  609.  
  610. char *tcp_host (stream)
  611.     TCPSTREAM *stream;
  612. {
  613.   return stream->host;        /* return host name */
  614. }
  615.  
  616.  
  617. /* TCP/IP get local host name
  618.  * Accepts: TCP/IP stream
  619.  * Returns: local host name
  620.  */
  621.  
  622. char *tcp_localhost (stream)
  623.     TCPSTREAM *stream;
  624. {
  625.   return stream->localhost;    /* return local host name */
  626. }
  627.  
  628. /* Find token in string
  629.  * Accepts: source pointer or NIL to use previous source
  630.  *        vector of token delimiters pointer
  631.  * Returns: pointer to next token
  632.  */
  633.  
  634. char *ts = NIL;            /* string to locate tokens */
  635.  
  636. char *strtok (s,ct)
  637.      char *s;
  638.      char *ct;
  639. {
  640.   char *t;
  641.   if (!s) s = ts;        /* use previous token if none specified */
  642.   if (!(s && *s)) return NIL;    /* no tokens */
  643.                 /* find any leading delimiters */
  644.   do for (t = ct, ts = NIL; *t; t++) if (*t == *s) {
  645.     if (*(ts = ++s)) break;    /* yes, restart seach if more in string */
  646.     return ts = NIL;        /* else no more tokens */
  647.   } while (ts);            /* continue until no more leading delimiters */
  648.                 /* can we find a new delimiter? */
  649.   for (ts = s; *ts; ts++) for (t = ct; *t; t++) if (*t == *ts) {
  650.     *ts++ = '\0';        /* yes, tie off token at that point */
  651.     return s;            /* return our token */
  652.   }
  653.   ts = NIL;            /* no more tokens */
  654.   return s;            /* return final token */
  655. }
  656.  
  657.  
  658. /* Find first occurance of character in string
  659.  * Accepts: source pointer
  660.  *        character to search
  661.  * Returns: pointer to character or NIL if none
  662.  */
  663.  
  664. char *strchr (cs,c)
  665.      char *cs;
  666.      char c;
  667. {
  668.   return index (cs,c);        /* they should have this one */
  669. }
  670.  
  671.  
  672. /* Find last occurance of character in string
  673.  * Accepts: source pointer
  674.  *        character to search
  675.  * Returns: pointer to character or NIL if none
  676.  */
  677.  
  678. char *strrchr (cs,c)
  679.      char *cs;
  680.      char c;
  681. {
  682.   return rindex (cs,c);        /* they should have this one */
  683. }
  684.  
  685. /* Return pointer to first occurance in string of a substring
  686.  * Accepts: source pointer
  687.  *        substring pointer
  688.  * Returns: pointer to substring in source or NIL if not found
  689.  */
  690.  
  691. char *strstr (cs,ct)
  692.      char *cs;
  693.      char *ct;
  694. {
  695.   char *s;
  696.   char *t;
  697.   while (cs = index (cs,*ct)) {    /* for each occurance of the first character */
  698.                 /* see if remainder of string matches */
  699.     for (s = cs + 1, t = ct + 1; *t && *s == *t; s++, t++);
  700.     if (!*t) return cs;        /* if ran out of substring then have match */
  701.     cs++;            /* try from next character */
  702.   }
  703.   return NIL;            /* not found */
  704. }
  705.  
  706.  
  707. /* Return pointer to first occurance in string of any delimiter
  708.  * Accepts: source pointer
  709.  *        vector of delimiters pointer
  710.  * Returns: pointer to delimiter or NIL if not found
  711.  */
  712.  
  713. char *strpbrk (cs,ct)
  714.      char *cs;
  715.      char *ct;
  716. {
  717.   char *s;
  718.                 /* search for delimiter until end of string */
  719.   for (; *cs; cs++) for (s = ct; *s; s++) if (*s == *cs) return cs;
  720.   return NIL;            /* not found */
  721. }
  722.  
  723.  
  724. /* Return implementation-defined string corresponding to error
  725.  * Accepts: error number
  726.  * Returns: string for that error
  727.  */
  728.  
  729. char *strerror (n)
  730.      int n;
  731. {
  732.   return (n >= 0 && n < sys_nerr) ? sys_errlist[n] : NIL;
  733. }
  734.  
  735. /* Copy memory block
  736.  * Accepts: destination pointer
  737.  *        source pointer
  738.  *        length
  739.  * Returns: destination pointer
  740.  */
  741.  
  742. char *memcpy (s,ct,n)
  743.      char *s;
  744.      char *ct;
  745.      int n;
  746. {
  747.   bcopy (ct,s,n);        /* they should have this one */
  748.   return ct;
  749. }
  750.  
  751.  
  752. /* Copy memory block
  753.  * Accepts: destination pointer
  754.  *        source pointer
  755.  *        length
  756.  * Returns: destination pointer
  757.  */
  758.  
  759. char *memmove (s,ct,n)
  760.      char *s;
  761.      char *ct;
  762.      int n;
  763. {
  764.   bcopy (ct,s,n);        /* they should have this one */
  765.   return ct;
  766. }
  767.  
  768.  
  769. /* Set a block of memory
  770.  * Accepts: destination pointer
  771.  *        value to set
  772.  *        length
  773.  * Returns: destination pointer
  774.  */
  775.  
  776. char *memset (s,c,n)
  777.      char *s;
  778.      char c;
  779.      int n;
  780. {
  781.   if (c) while (n) s[--n] = c;    /* this way if non-zero */
  782.   else bzero (s,n);        /* they should have this one */
  783.   return s;
  784. }
  785.  
  786. /*
  787.  * Turn a string long into the real thing
  788.  * Accepts: source string
  789.  *        pointer to place to return end pointer
  790.  *        base
  791.  * Returns: parsed long integer, end pointer is updated
  792.  */
  793.  
  794. long strtol (s,endp,base)
  795.      char *s;
  796.      char **endp;
  797.      int base;
  798. {
  799.   long value = 0;        /* the accumulated value */
  800.   int negative = 0;        /* this a negative number? */
  801.   int ok;            /* true while valid chars for number */
  802.   char c;
  803.                 /* insist upon valid base */
  804.   if (base && (base < 2 || base > 36)) return NIL;
  805.   while (isspace (*s)) s++;    /* skip leading whitespace */
  806.   if (!base) {            /* if base = 0, */
  807.     if (*s == '-') {        /* integer constants are allowed a */
  808.       negative = 1;        /* leading unary minus, but not */
  809.       s++;            /* unary plus. */
  810.     }
  811.     else negative = 0;
  812.     if (*s == '0') {        /* if it starts with 0, its either */
  813.                 /* 0X, which marks a hex constant, */
  814.       if (toupper (*++s) == 'X') {
  815.     s++;            /* skip the X */
  816.            base = 16;        /* base is hex 16 */
  817.       }
  818.       else base = 8;        /* leading 0 means octal number */
  819.     }
  820.     else base = 10;        /* otherwise, decimal. */
  821.     do {
  822.       switch (base) {        /* char has to be valid for base */
  823.       case 8:            /* this digit ok? */
  824.     ok = isodigit(*s);
  825.     break;
  826.       case 10:
  827.     ok = isdigit(*s);
  828.     break;
  829.       case 16:
  830.     ok = isxdigit(*s);
  831.     break;
  832.       default:            /* it's good form you know */
  833.     return NIL;
  834.       }
  835.                 /* if valid char, accumulate */
  836.       if (ok) value = value * base + toint(*s++);
  837.     } while (ok);
  838.     if (toupper(*s) == 'L') s++;/* ignore 'l' or 'L' marker */
  839.     if (endp) *endp = s;    /* set user pointer to after num */
  840.     return (negative) ? -value : value;
  841.   }
  842.  
  843.   switch (*s) {            /* check for leading sign char */
  844.   case '-':
  845.     negative = 1;        /* yes, negative #.  fall into '+' */
  846.   case '+':
  847.     s++;            /* skip the sign character */
  848.   }
  849.                 /* allow hex prefix "0x" */
  850.   if (base == 16 && *s == '0' && toupper (*(s + 1)) == 'X') s += 2;
  851.   do {
  852.                 /* convert to numeric form if digit*/
  853.     if (isdigit (*s)) c = toint (*s);
  854.                 /* alphabetic conversion */
  855.     else if (isalpha (*s)) c = *s - (isupper (*s) ? 'A' : 'a') + 10;
  856.     else break;            /* else no way it's valid */
  857.     if (c >= base) break;    /* digit out of range for base? */
  858.     value = value * base + c;    /* accumulate the digit */
  859.   } while (*++s);        /* loop until non-numeric character */
  860.   if (endp) *endp = s;        /* save users endp to after number */
  861.                 /* negate number if needed */
  862.   return (negative) ? -value : value;
  863. }
  864.  
  865.