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