home *** CD-ROM | disk | FTP | other *** search
/ vsiftp.vmssoftware.com / VSIPUBLIC@vsiftp.vmssoftware.com.tar / FREEWARE / FREEWARE40.ZIP / pine / c-client / bezerk.c next >
C/C++ Source or Header  |  1994-01-09  |  69KB  |  2,277 lines

  1. /*
  2.  * Program:    Berkeley mail routines
  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:    20 December 1989
  13.  * Last Edited:    18 November 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.  
  37. /* Dedication:
  38.  *  This file is dedicated with affection to those Merry Marvels of Musical
  39.  * Madness . . .
  40.  *  ->  The Incomparable Leland Stanford Junior University Marching Band  <-
  41.  * who entertain, awaken, and outrage Stanford fans in the fact of repeated
  42.  * losing seasons and shattered Rose Bowl dreams [Cardinal just don't have
  43.  * HUSKY FEVER!!!].
  44.  *
  45.  */
  46.  
  47. #include <stdio.h>
  48. #include <ctype.h>
  49. #include <netdb.h>
  50. #include <errno.h>
  51. extern int errno;        /* just in case */
  52. #include <signal.h>
  53. #include <sys/time.h>        /* must be before osdep.h */
  54. #include "mail.h"
  55. #include "osdep.h"
  56. #include <pwd.h>
  57. #include <sys/file.h>
  58. #include <sys/stat.h>
  59. #include "bezerk.h"
  60. #include "rfc822.h"
  61. #include "misc.h"
  62. #include "dummy.h"
  63.  
  64. /* Berkeley mail routines */
  65.  
  66.  
  67. /* Driver dispatch used by MAIL */
  68.  
  69. DRIVER bezerkdriver = {
  70.   "bezerk",            /* driver name */
  71.   (DRIVER *) NIL,        /* next driver */
  72.   bezerk_valid,            /* mailbox is valid for us */
  73.   bezerk_parameters,        /* manipulate parameters */
  74.   bezerk_find,            /* find mailboxes */
  75.   bezerk_find_bboards,        /* find bboards */
  76.   bezerk_find_all,        /* find all mailboxes */
  77.   bezerk_find_all_bboards,    /* find all bboards */
  78.   bezerk_subscribe,        /* subscribe to mailbox */
  79.   bezerk_unsubscribe,        /* unsubscribe from mailbox */
  80.   bezerk_subscribe_bboard,    /* subscribe to bboard */
  81.   bezerk_unsubscribe_bboard,    /* unsubscribe from bboard */
  82.   bezerk_create,        /* create mailbox */
  83.   bezerk_delete,        /* delete mailbox */
  84.   bezerk_rename,        /* rename mailbox */
  85.   bezerk_open,            /* open mailbox */
  86.   bezerk_close,            /* close mailbox */
  87.   bezerk_fetchfast,        /* fetch message "fast" attributes */
  88.   bezerk_fetchflags,        /* fetch message flags */
  89.   bezerk_fetchstructure,    /* fetch message envelopes */
  90.   bezerk_fetchheader,        /* fetch message header only */
  91.   bezerk_fetchtext,        /* fetch message body only */
  92.   bezerk_fetchbody,        /* fetch message body section */
  93.   bezerk_setflag,        /* set message flag */
  94.   bezerk_clearflag,        /* clear message flag */
  95.   bezerk_search,        /* search for message based on criteria */
  96.   bezerk_ping,            /* ping mailbox to see if still alive */
  97.   bezerk_check,            /* check for new messages */
  98.   bezerk_expunge,        /* expunge deleted messages */
  99.   bezerk_copy,            /* copy messages to another mailbox */
  100.   bezerk_move,            /* move messages to another mailbox */
  101.   bezerk_append,        /* append string message to mailbox */
  102.   bezerk_gc            /* garbage collect stream */
  103. };
  104.  
  105.                 /* prototype stream */
  106. MAILSTREAM bezerkproto = {&bezerkdriver};
  107.                 /* standard driver's prototype */
  108. MAILSTREAM *mailstd_proto = &bezerkproto;
  109.  
  110. /* Berkeley mail validate mailbox
  111.  * Accepts: mailbox name
  112.  * Returns: our driver if name is valid, NIL otherwise
  113.  */
  114.  
  115. DRIVER *bezerk_valid (name)
  116.     char *name;
  117. {
  118.   char tmp[MAILTMPLEN];
  119.   return bezerk_isvalid (name,tmp) ? &bezerkdriver : NIL;
  120. }
  121.  
  122.  
  123. /* Berkeley mail test for valid mailbox
  124.  * Accepts: mailbox name
  125.  * Returns: T if valid, NIL otherwise
  126.  */
  127.  
  128. int bezerk_isvalid (name,tmp)
  129.     char *name;
  130.     char *tmp;
  131. {
  132.   int i,fd,ti,zn;
  133.   int ret = NIL;
  134.   char *s = tmp,*t;
  135.   struct stat sbuf;
  136.   struct hostent *host_name;
  137.   if (!lhostn) {        /* have local host yet? */
  138.     gethostname(tmp,MAILTMPLEN);/* get local host name */
  139.     lhostn = cpystr ((host_name = gethostbyname (tmp)) ?
  140.              host_name->h_name : tmp);
  141.   }
  142.                 /* INBOX is always accepted */
  143.   if (!strcmp (ucase (strcpy (tmp,name)),"INBOX")) return T;
  144.                 /* if file, get its status */
  145.   if ((*name != '{') && !((*name == '*') && (name[1] == '{')) &&
  146.       (stat (bezerk_file (tmp,name),&sbuf) == 0) &&
  147.       ((fd = open (tmp,O_RDONLY,NIL)) >= 0)) {
  148.     if (sbuf.st_size == 0) {     /* allow empty file if not .TxT */
  149.       if ((i = strlen (tmp)) < 4 || strcmp (tmp + i - 4 ,".TxT"))
  150.     return LONGT;
  151.     }
  152.     else if ((read (fd,tmp,MAILTMPLEN-1) >= 0) &&
  153.          (tmp[0] == 'F') && VALID (s,t,ti,zn)) ret = T;
  154.     close (fd);            /* close the file */
  155.   }
  156.   return ret;            /* return what we should */
  157. }
  158.  
  159. /* Berkeley manipulate driver parameters
  160.  * Accepts: function code
  161.  *        function-dependent value
  162.  * Returns: function-dependent return value
  163.  */
  164.  
  165. void *bezerk_parameters (function,value)
  166.     long function;
  167.     void *value;
  168. {
  169.   fatal ("Invalid bezerk_parameters function");
  170.   return NIL;
  171. }
  172.  
  173. /* Berkeley mail find list of mailboxes
  174.  * Accepts: mail stream
  175.  *        pattern to search
  176.  */
  177.  
  178. void bezerk_find (stream,pat)
  179.     MAILSTREAM *stream;
  180.     char *pat;
  181. {
  182.   if (stream) dummy_find (NIL,pat);
  183. }
  184.  
  185.  
  186. /* Berkeley mail find list of bboards
  187.  * Accepts: mail stream
  188.  *        pattern to search
  189.  */
  190.  
  191. void bezerk_find_bboards (stream,pat)
  192.     MAILSTREAM *stream;
  193.     char *pat;
  194. {
  195.   if (stream) dummy_find_bboards (NIL,pat);
  196. }
  197.  
  198.  
  199. /* Berkeley mail find list of all mailboxes
  200.  * Accepts: mail stream
  201.  *        pattern to search
  202.  */
  203.  
  204. void bezerk_find_all (stream,pat)
  205.     MAILSTREAM *stream;
  206.     char *pat;
  207. {
  208.   if (stream) dummy_find_all (NIL,pat);
  209. }
  210.  
  211.  
  212. /* Berkeley mail find list of all bboards
  213.  * Accepts: mail stream
  214.  *        pattern to search
  215.  */
  216.  
  217. void bezerk_find_all_bboards (stream,pat)
  218.     MAILSTREAM *stream;
  219.     char *pat;
  220. {
  221.   if (stream) dummy_find_all_bboards (NIL,pat);
  222. }
  223.  
  224. /* Berkeley mail subscribe to mailbox
  225.  * Accepts: mail stream
  226.  *        mailbox to add to subscription list
  227.  * Returns: T on success, NIL on failure
  228.  */
  229.  
  230. long bezerk_subscribe (stream,mailbox)
  231.     MAILSTREAM *stream;
  232.     char *mailbox;
  233. {
  234.   char tmp[MAILTMPLEN];
  235.   return sm_subscribe (bezerk_file (tmp,mailbox));
  236. }
  237.  
  238.  
  239. /* Berkeley mail unsubscribe to mailbox
  240.  * Accepts: mail stream
  241.  *        mailbox to delete from subscription list
  242.  * Returns: T on success, NIL on failure
  243.  */
  244.  
  245. long bezerk_unsubscribe (stream,mailbox)
  246.     MAILSTREAM *stream;
  247.     char *mailbox;
  248. {
  249.   char tmp[MAILTMPLEN];
  250.   return sm_unsubscribe (bezerk_file (tmp,mailbox));
  251. }
  252.  
  253.  
  254. /* Berkeley mail subscribe to bboard
  255.  * Accepts: mail stream
  256.  *        bboard to add to subscription list
  257.  * Returns: T on success, NIL on failure
  258.  */
  259.  
  260. long bezerk_subscribe_bboard (stream,mailbox)
  261.     MAILSTREAM *stream;
  262.     char *mailbox;
  263. {
  264.   return NIL;            /* never valid for Bezerk */
  265. }
  266.  
  267.  
  268. /* Berkeley mail unsubscribe to bboard
  269.  * Accepts: mail stream
  270.  *        bboard to delete from subscription list
  271.  * Returns: T on success, NIL on failure
  272.  */
  273.  
  274. long bezerk_unsubscribe_bboard (stream,mailbox)
  275.     MAILSTREAM *stream;
  276.     char *mailbox;
  277. {
  278.   return NIL;            /* never valid for Bezerk */
  279. }
  280.  
  281. /* Berkeley mail create mailbox
  282.  * Accepts: MAIL stream
  283.  *        mailbox name to create
  284.  * Returns: T on success, NIL on failure
  285.  */
  286.  
  287. long bezerk_create (stream,mailbox)
  288.     MAILSTREAM *stream;
  289.     char *mailbox;
  290. {
  291.   char tmp[MAILTMPLEN];
  292.   int i,fd;
  293.                 /* must not be a ".TxT" file */
  294.   if ((i = strlen (mailbox)) > 4 && !strcmp (mailbox + i - 4 ,".TxT")) {
  295.     mm_log ("Can't create mailbox: name must not end with .TxT",ERROR);
  296.     return NIL;
  297.   }
  298.   if ((fd = open (bezerk_file (tmp,mailbox),O_WRONLY|O_CREAT|O_EXCL,0600))<0) {
  299.     sprintf (tmp,"Can't create mailbox %s: %s",mailbox,strerror (errno));
  300.     mm_log (tmp,ERROR);
  301.     return NIL;
  302.   }
  303.   close (fd);            /* close the file */
  304.   return T;            /* return success */
  305. }
  306.  
  307.  
  308. /* Berkeley mail delete mailbox
  309.  * Accepts: MAIL stream
  310.  *        mailbox name to delete
  311.  * Returns: T on success, NIL on failure
  312.  */
  313.  
  314. long bezerk_delete (stream,mailbox)
  315.     MAILSTREAM *stream;
  316.     char *mailbox;
  317. {
  318.   return bezerk_rename (stream,mailbox,NIL);
  319. }
  320.  
  321. /* Berkeley mail rename mailbox
  322.  * Accepts: MAIL stream
  323.  *        old mailbox name
  324.  *        new mailbox name (or NIL for delete)
  325.  * Returns: T on success, NIL on failure
  326.  */
  327.  
  328. long bezerk_rename (stream,old,new)
  329.     MAILSTREAM *stream;
  330.     char *old;
  331.     char *new;
  332. {
  333.   long ret = T;
  334.   char tmp[MAILTMPLEN],file[MAILTMPLEN],lock[MAILTMPLEN],lockx[MAILTMPLEN];
  335.   int fd,ld;
  336.                 /* get the c-client lock */
  337.   if ((ld = open (lockname (lock,bezerk_file (file,old)),O_RDWR|O_CREAT,0666))
  338.       < 0) {
  339.     sprintf (tmp,"Can't get lock for mailbox %s: %s",old,strerror (errno));
  340.     mm_log (tmp,ERROR);
  341.     return NIL;
  342.   }
  343.                 /* lock out other c-clients */
  344.   if (flock (ld,LOCK_EX|LOCK_NB)) {
  345.     close (ld);            /* couldn't lock, give up on it then */
  346.     sprintf (tmp,"Mailbox %s is in use by another process",old);
  347.     mm_log (tmp,ERROR);
  348.     return NIL;
  349.   }
  350.                 /* lock out non c-client applications */
  351.   if ((fd = bezerk_lock (file,O_RDONLY,S_IREAD|S_IWRITE,lockx,LOCK_EX)) < 0) {
  352.     sprintf (tmp,"Can't lock mailbox %s: %s",old,strerror (errno));
  353.     mm_log (tmp,ERROR);
  354.     return NIL;
  355.   }
  356.                 /* do the rename or delete operation */
  357.   if (new ? rename (file,bezerk_file (tmp,new)) : unlink (file)) {
  358.     sprintf (tmp,"Can't %s mailbox %s: %s",new ? "rename" : "delete",old,
  359.          strerror (errno));
  360.     mm_log (tmp,ERROR);
  361.     ret = NIL;            /* set failure */
  362.   }
  363.   bezerk_unlock (fd,NIL,lockx);    /* unlock and close mailbox */
  364.   flock (ld,LOCK_UN);        /* release c-client lock lock */
  365.   close (ld);            /* close c-client lock */
  366.   unlink (lock);        /* and delete it */
  367.   return ret;            /* return success */
  368. }
  369.  
  370. /* Berkeley mail open
  371.  * Accepts: Stream to open
  372.  * Returns: Stream on success, NIL on failure
  373.  */
  374.  
  375. MAILSTREAM *bezerk_open (stream)
  376.     MAILSTREAM *stream;
  377. {
  378.   long i;
  379.   int fd;
  380.   char tmp[MAILTMPLEN];
  381.   struct stat sbuf;
  382.   long retry;
  383.                 /* return prototype for OP_PROTOTYPE call */
  384.   if (!stream) return &bezerkproto;
  385.   retry = stream->silent ? 1 : KODRETRY;
  386.   if (LOCAL) {            /* close old file if stream being recycled */
  387.     bezerk_close (stream);    /* dump and save the changes */
  388.     stream->dtb = &bezerkdriver;/* reattach this driver */
  389.     mail_free_cache (stream);    /* clean up cache */
  390.   }
  391.   stream->local = fs_get (sizeof (BEZERKLOCAL));
  392.                 /* canonicalize the stream mailbox name */
  393.   bezerk_file (tmp,stream->mailbox);
  394.                 /* force readonly if bboard */
  395.   if (*stream->mailbox == '*') stream->readonly = T;
  396.   else {            /* canonicalize name */
  397.     fs_give ((void **) &stream->mailbox);
  398.     stream->mailbox = cpystr (tmp);
  399.   }
  400.   /* You may wonder why LOCAL->name is needed.  It isn't at all obvious from
  401.    * the code.  The problem is that when a stream is recycled with another
  402.    * mailbox of the same type, the driver's close method isn't called because
  403.    * it could be IMAP and closing then would defeat the entire point of
  404.    * recycling.  Hence there is code in the file drivers to call the close
  405.    * method such as what appears above.  The problem is, by this point,
  406.    * mail_open() has already changed the stream->mailbox name to point to the
  407.    * new name, and bezerk_close() needs the old name.
  408.    */
  409.   LOCAL->name = cpystr (tmp);    /* local copy for recycle case */
  410.                 /* build name of our lock file */
  411.   LOCAL->lname = cpystr (lockname (tmp,LOCAL->name));
  412.   LOCAL->ld = NIL;        /* no state locking yet */
  413.   LOCAL->filesize = 0;        /* initialize file information */
  414.   LOCAL->filetime = 0;
  415.   LOCAL->msgs = NIL;        /* no cache yet */
  416.   LOCAL->cachesize = 0;
  417.   LOCAL->buf = (char *) fs_get ((LOCAL->buflen = CHUNK) + 1);
  418.   stream->sequence++;        /* bump sequence number */
  419.  
  420.   LOCAL->dirty = NIL;        /* no update yet */
  421.                 /* make lock for read/write access */
  422.   if (!stream->readonly) while (retry) {
  423.                 /* get a new file handle each time */
  424.     if ((fd = open (LOCAL->lname,O_RDWR|O_CREAT,0666)) < 0)
  425.       mm_log ("Can't open mailbox lock, access is readonly",WARN);
  426.                 /* can get the lock? */
  427.     if (flock (fd,LOCK_EX|LOCK_NB)) {
  428.       if (retry-- == KODRETRY) {/* no, first time through? */
  429.                 /* yes, get other process' PID */
  430.     if (!fstat (fd,&sbuf) && (i = min (sbuf.st_size,MAILTMPLEN)) &&
  431.         (read (fd,tmp,i) == i) && (i = atol (tmp))) {
  432.       kill (i,SIGUSR2);    /* send the Kiss Of Death */
  433.       sprintf (tmp,"Trying to get mailbox lock from process %ld",i);
  434.       mm_log (tmp,WARN);
  435.     }
  436.     else retry = 0;        /* give up */
  437.       }
  438.       close (fd);        /* get a new handle next time around */
  439.       if (!stream->silent) {    /* nothing if silent stream */
  440.     if (retry) sleep (1);    /* wait a second before trying again */
  441.     else mm_log ("Mailbox is open by another process, access is readonly",
  442.              WARN);
  443.       }
  444.     }
  445.     else {            /* got the lock, nobody else can alter state */
  446.       LOCAL->ld = fd;        /* note lock's fd */
  447.       chmod (LOCAL->lname,0666);/* make sure mode OK (don't use fchmod()) */
  448.       if (stream->silent) i = 0;/* silent streams won't accept KOD */
  449.       else {            /* note our PID in the lock */
  450.     sprintf (tmp,"%d",getpid ());
  451.     write (fd,tmp,(i = strlen (tmp))+1);
  452.       }
  453.       ftruncate (fd,i);        /* make sure tied off */
  454.       fsync (fd);        /* make sure it's available */
  455.       retry = 0;        /* no more need to try */
  456.     }
  457.   }
  458.  
  459.                 /* parse mailbox */
  460.   stream->nmsgs = stream->recent = 0;
  461.                 /* will we be able to get write access? */
  462.   if (LOCAL->ld && access (LOCAL->name,W_OK) && (errno == EACCES)) {
  463.     mm_log ("Can't get write access to mailbox, access is readonly",WARN);
  464.     flock (LOCAL->ld,LOCK_UN);    /* release the lock */
  465.     close (LOCAL->ld);        /* close the lock file */
  466.     LOCAL->ld = NIL;        /* no more lock fd */
  467.     unlink (LOCAL->lname);    /* delete it */
  468.     fs_give ((void **) &LOCAL->lname);
  469.   }
  470.                 /* abort if can't get RW silent stream */
  471.   if (stream->silent && !stream->readonly && !LOCAL->ld) bezerk_abort (stream);
  472.                 /* parse mailbox */
  473.   else if ((fd = bezerk_parse (stream,tmp,LOCK_SH)) >= 0) {
  474.     bezerk_unlock (fd,stream,tmp);
  475.     mail_unlock (stream);
  476.   }
  477.   if (!LOCAL) return NIL;    /* failure if stream died */
  478.   stream->readonly = !LOCAL->ld;/* make sure upper level knows readonly */
  479.                 /* notify about empty mailbox */
  480.   if (!(stream->nmsgs || stream->silent)) mm_log ("Mailbox is empty",NIL);
  481.   return stream;        /* return stream alive to caller */
  482. }
  483.  
  484. /* Berkeley mail close
  485.  * Accepts: MAIL stream
  486.  */
  487.  
  488. void bezerk_close (stream)
  489.     MAILSTREAM *stream;
  490. {
  491.   int fd;
  492.   int silent = stream->silent;
  493.   char lock[MAILTMPLEN];
  494.   if (LOCAL && LOCAL->ld) {    /* is stream alive? */
  495.     stream->silent = T;        /* note this stream is dying */
  496.                 /* lock mailbox and parse new messages */
  497.     if (LOCAL->dirty && (fd = bezerk_parse (stream,lock,LOCK_EX)) >= 0) {
  498.                 /* dump any changes not saved yet */
  499.       if (bezerk_extend    (stream,fd,"Close failed to update mailbox"))
  500.     bezerk_save (stream,fd);
  501.                 /* flush locks */
  502.       bezerk_unlock (fd,stream,lock);
  503.       mail_unlock (stream);
  504.     }
  505.     stream->silent = silent;    /* restore previous status */
  506.   }
  507.   bezerk_abort (stream);    /* now punt the file and local data */
  508. }
  509.  
  510.  
  511. /* Berkeley mail fetch fast information
  512.  * Accepts: MAIL stream
  513.  *        sequence
  514.  */
  515.  
  516. void bezerk_fetchfast (stream,sequence)
  517.     MAILSTREAM *stream;
  518.     char *sequence;
  519. {
  520.   return;            /* no-op for local mail */
  521. }
  522.  
  523.  
  524. /* Berkeley mail fetch flags
  525.  * Accepts: MAIL stream
  526.  *        sequence
  527.  */
  528.  
  529. void bezerk_fetchflags (stream,sequence)
  530.     MAILSTREAM *stream;
  531.     char *sequence;
  532. {
  533.   return;            /* no-op for local mail */
  534. }
  535.  
  536. /* Berkeley mail fetch structure
  537.  * Accepts: MAIL stream
  538.  *        message # to fetch
  539.  *        pointer to return body
  540.  * Returns: envelope of this message, body returned in body value
  541.  *
  542.  * Fetches the "fast" information as well
  543.  */
  544.  
  545. ENVELOPE *bezerk_fetchstructure (stream,msgno,body)
  546.     MAILSTREAM *stream;
  547.     long msgno;
  548.     BODY **body;
  549. {
  550.   ENVELOPE **env;
  551.   BODY **b;
  552.   STRING bs;
  553.   LONGCACHE *lelt;
  554.   FILECACHE *m = LOCAL->msgs[msgno - 1];
  555.   long i = max (m->headersize,m->bodysize);
  556.   if (stream->scache) {        /* short cache */
  557.     if (msgno != stream->msgno){/* flush old poop if a different message */
  558.       mail_free_envelope (&stream->env);
  559.       mail_free_body (&stream->body);
  560.     }
  561.     stream->msgno = msgno;
  562.     env = &stream->env;        /* get pointers to envelope and body */
  563.     b = &stream->body;
  564.   }
  565.   else {            /* long cache */
  566.     lelt = mail_lelt (stream,msgno);
  567.     env = &lelt->env;        /* get pointers to envelope and body */
  568.     b = &lelt->body;
  569.   }
  570.   if ((body && !*b) || !*env) {    /* have the poop we need? */
  571.     mail_free_envelope (env);    /* flush old envelope and body */
  572.     mail_free_body (b);
  573.     if (i > LOCAL->buflen) {    /* make sure enough buffer space */
  574.       fs_give ((void **) &LOCAL->buf);
  575.       LOCAL->buf = (char *) fs_get ((LOCAL->buflen = i) + 1);
  576.     }
  577.     INIT (&bs,mail_string,(void *) m->body,m->bodysize);
  578.                 /* parse envelope and body */
  579.     rfc822_parse_msg (env,body ? b : NIL,m->header,m->headersize,&bs,lhostn,
  580.               LOCAL->buf);
  581.   }
  582.   if (body) *body = *b;        /* return the body */
  583.   return *env;            /* return the envelope */
  584. }
  585.  
  586. /* Berkeley mail snarf message, only for Tenex driver
  587.  * Accepts: MAIL stream
  588.  *        message # to snarf
  589.  *        pointer to size to return
  590.  * Returns: message text in RFC822 format
  591.  */
  592.  
  593. char *bezerk_snarf (stream,msgno,size)
  594.     MAILSTREAM *stream;
  595.     long msgno;
  596.     long *size;
  597. {
  598.   MESSAGECACHE *elt = mail_elt (stream,msgno);
  599.   FILECACHE *m = LOCAL->msgs[msgno - 1];
  600.   if (((*size = m->headersize + m->bodysize) > LOCAL->buflen) ||
  601.       LOCAL->buflen > CHUNK) {    /* make sure stream can hold the text */
  602.                 /* fs_resize would do an unnecessary copy */
  603.     fs_give ((void **) &LOCAL->buf);
  604.     LOCAL->buf = (char *) fs_get((LOCAL->buflen = max (*size,(long) CHUNK))+1);
  605.   }
  606.                 /* copy the text */
  607.   if (m->headersize) memcpy (LOCAL->buf,m->header,m->headersize);
  608.   if (m->bodysize) memcpy (LOCAL->buf + m->headersize,m->body,m->bodysize);
  609.   LOCAL->buf[*size] = '\0';    /* tie off string */
  610.   return LOCAL->buf;
  611. }
  612.  
  613. /* Berkeley mail fetch message header
  614.  * Accepts: MAIL stream
  615.  *        message # to fetch
  616.  * Returns: message header in RFC822 format
  617.  */
  618.  
  619. char *bezerk_fetchheader (stream,msgno)
  620.     MAILSTREAM *stream;
  621.     long msgno;
  622. {
  623.   FILECACHE *m = LOCAL->msgs[msgno - 1];
  624.                 /* copy the string */
  625.   strcrlfcpy (&LOCAL->buf,&LOCAL->buflen,m->header,m->headersize);
  626.   return LOCAL->buf;
  627. }
  628.  
  629.  
  630. /* Berkeley mail fetch message text (only)
  631.     body only;
  632.  * Accepts: MAIL stream
  633.  *        message # to fetch
  634.  * Returns: message text in RFC822 format
  635.  */
  636.  
  637. char *bezerk_fetchtext (stream,msgno)
  638.     MAILSTREAM *stream;
  639.     long msgno;
  640. {
  641.   MESSAGECACHE *elt = mail_elt (stream,msgno);
  642.   FILECACHE *m = LOCAL->msgs[msgno - 1];
  643.   if (!elt->seen) {        /* if message not seen */
  644.     elt->seen = T;        /* mark message as seen */
  645.                 /* recalculate Status/X-Status lines */
  646.     bezerk_update_status (m->status,elt);
  647.     LOCAL->dirty = T;        /* note stream is now dirty */
  648.   }
  649.   strcrlfcpy (&LOCAL->buf,&LOCAL->buflen,m->body,m->bodysize);
  650.   return LOCAL->buf;
  651. }
  652.  
  653. /* Berkeley fetch message body as a structure
  654.  * Accepts: Mail stream
  655.  *        message # to fetch
  656.  *        section specifier
  657.  *        pointer to length
  658.  * Returns: pointer to section of message body
  659.  */
  660.  
  661. char *bezerk_fetchbody (stream,m,s,len)
  662.     MAILSTREAM *stream;
  663.     long m;
  664.     char *s;
  665.     unsigned long *len;
  666. {
  667.   BODY *b;
  668.   PART *pt;
  669.   unsigned long i;
  670.   char *base = LOCAL->msgs[m - 1]->body;
  671.   unsigned long offset = 0;
  672.   MESSAGECACHE *elt = mail_elt (stream,m);
  673.                 /* make sure have a body */
  674.   if (!(bezerk_fetchstructure (stream,m,&b) && b && s && *s &&
  675.     ((i = strtol (s,&s,10)) > 0))) return NIL;
  676.   do {                /* until find desired body part */
  677.                 /* multipart content? */
  678.     if (b->type == TYPEMULTIPART) {
  679.       pt = b->contents.part;    /* yes, find desired part */
  680.       while (--i && (pt = pt->next));
  681.       if (!pt) return NIL;    /* bad specifier */
  682.                 /* note new body, check valid nesting */
  683.       if (((b = &pt->body)->type == TYPEMULTIPART) && !*s) return NIL;
  684.       offset = pt->offset;    /* get new offset */
  685.     }
  686.     else if (i != 1) return NIL;/* otherwise must be section 1 */
  687.                 /* need to go down further? */
  688.     if (i = *s) switch (b->type) {
  689.     case TYPEMESSAGE:        /* embedded message */
  690.       offset = b->contents.msg.offset;
  691.       b = b->contents.msg.body;    /* get its body, drop into multipart case */
  692.     case TYPEMULTIPART:        /* multipart, get next section */
  693.       if ((*s++ == '.') && (i = strtol (s,&s,10)) > 0) break;
  694.     default:            /* bogus subpart specification */
  695.       return NIL;
  696.     }
  697.   } while (i);
  698.                 /* lose if body bogus */
  699.   if ((!b) || b->type == TYPEMULTIPART) return NIL;
  700.   if (!elt->seen) {        /* if message not seen */
  701.     elt->seen = T;        /* mark message as seen */
  702.                 /* recalculate Status/X-Status lines */
  703.     bezerk_update_status (LOCAL->msgs[m - 1]->status,elt);
  704.     LOCAL->dirty = T;        /* note stream is now dirty */
  705.   }
  706.   return rfc822_contents (&LOCAL->buf,&LOCAL->buflen,len,base + offset,
  707.               b->size.ibytes,b->encoding);
  708. }
  709.  
  710. /* Berkeley mail set flag
  711.  * Accepts: MAIL stream
  712.  *        sequence
  713.  *        flag(s)
  714.  */
  715.  
  716. void bezerk_setflag (stream,sequence,flag)
  717.     MAILSTREAM *stream;
  718.     char *sequence;
  719.     char *flag;
  720. {
  721.   MESSAGECACHE *elt;
  722.   long i;
  723.   short f = bezerk_getflags (stream,flag);
  724.   if (!f) return;        /* no-op if no flags to modify */
  725.                 /* get sequence and loop on it */
  726.   if (mail_sequence (stream,sequence)) for (i = 1; i <= stream->nmsgs; i++)
  727.     if ((elt = mail_elt (stream,i))->sequence) {
  728.                 /* set all requested flags */
  729.       if (f&fSEEN) elt->seen = T;
  730.       if (f&fDELETED) elt->deleted = T;
  731.       if (f&fFLAGGED) elt->flagged = T;
  732.       if (f&fANSWERED) elt->answered = T;
  733.                 /* recalculate Status/X-Status lines */
  734.       bezerk_update_status (LOCAL->msgs[i - 1]->status,elt);
  735.       LOCAL->dirty = T;        /* note stream is now dirty */
  736.     }
  737. }
  738.  
  739.  
  740. /* Berkeley mail clear flag
  741.  * Accepts: MAIL stream
  742.  *        sequence
  743.  *        flag(s)
  744.  */
  745.  
  746. void bezerk_clearflag (stream,sequence,flag)
  747.     MAILSTREAM *stream;
  748.     char *sequence;
  749.     char *flag;
  750. {
  751.   MESSAGECACHE *elt;
  752.   long i;
  753.   short f = bezerk_getflags (stream,flag);
  754.   if (!f) return;        /* no-op if no flags to modify */
  755.                 /* get sequence and loop on it */
  756.   if (mail_sequence (stream,sequence)) for (i = 1; i <= stream->nmsgs; i++)
  757.     if ((elt = mail_elt (stream,i))->sequence) {
  758.                 /* clear all requested flags */
  759.       if (f&fSEEN) elt->seen = NIL;
  760.       if (f&fDELETED) elt->deleted = NIL;
  761.       if (f&fFLAGGED) elt->flagged = NIL;
  762.       if (f&fANSWERED) elt->answered = NIL;
  763.                 /* recalculate Status/X-Status lines */
  764.       bezerk_update_status (LOCAL->msgs[i - 1]->status,elt);
  765.       LOCAL->dirty = T;        /* note stream is now dirty */
  766.     }
  767. }
  768.  
  769. /* Berkeley mail search for messages
  770.  * Accepts: MAIL stream
  771.  *        search criteria
  772.  */
  773.  
  774. void bezerk_search (stream,criteria)
  775.     MAILSTREAM *stream;
  776.     char *criteria;
  777. {
  778.   long i,n;
  779.   char *d;
  780.   search_t f;
  781.                 /* initially all searched */
  782.   for (i = 1; i <= stream->nmsgs; ++i) mail_elt (stream,i)->searched = T;
  783.                 /* get first criterion */
  784.   if (criteria && (criteria = strtok (criteria," "))) {
  785.                 /* for each criterion */
  786.     for (; criteria; (criteria = strtok (NIL," "))) {
  787.       f = NIL; d = NIL; n = 0;    /* init then scan the criterion */
  788.       switch (*ucase (criteria)) {
  789.       case 'A':            /* possible ALL, ANSWERED */
  790.     if (!strcmp (criteria+1,"LL")) f = bezerk_search_all;
  791.     else if (!strcmp (criteria+1,"NSWERED")) f = bezerk_search_answered;
  792.     break;
  793.       case 'B':            /* possible BCC, BEFORE, BODY */
  794.     if (!strcmp (criteria+1,"CC"))
  795.       f = bezerk_search_string (bezerk_search_bcc,&d,&n);
  796.     else if (!strcmp (criteria+1,"EFORE"))
  797.       f = bezerk_search_date (bezerk_search_before,&n);
  798.     else if (!strcmp (criteria+1,"ODY"))
  799.       f = bezerk_search_string (bezerk_search_body,&d,&n);
  800.     break;
  801.       case 'C':            /* possible CC */
  802.     if (!strcmp (criteria+1,"C"))
  803.       f = bezerk_search_string (bezerk_search_cc,&d,&n);
  804.     break;
  805.       case 'D':            /* possible DELETED */
  806.     if (!strcmp (criteria+1,"ELETED")) f = bezerk_search_deleted;
  807.     break;
  808.       case 'F':            /* possible FLAGGED, FROM */
  809.     if (!strcmp (criteria+1,"LAGGED")) f = bezerk_search_flagged;
  810.     else if (!strcmp (criteria+1,"ROM"))
  811.       f = bezerk_search_string (bezerk_search_from,&d,&n);
  812.     break;
  813.       case 'K':            /* possible KEYWORD */
  814.     if (!strcmp (criteria+1,"EYWORD"))
  815.       f = bezerk_search_flag (bezerk_search_keyword,&d);
  816.     break;
  817.       case 'N':            /* possible NEW */
  818.     if (!strcmp (criteria+1,"EW")) f = bezerk_search_new;
  819.     break;
  820.  
  821.       case 'O':            /* possible OLD, ON */
  822.     if (!strcmp (criteria+1,"LD")) f = bezerk_search_old;
  823.     else if (!strcmp (criteria+1,"N"))
  824.       f = bezerk_search_date (bezerk_search_on,&n);
  825.     break;
  826.       case 'R':            /* possible RECENT */
  827.     if (!strcmp (criteria+1,"ECENT")) f = bezerk_search_recent;
  828.     break;
  829.       case 'S':            /* possible SEEN, SINCE, SUBJECT */
  830.     if (!strcmp (criteria+1,"EEN")) f = bezerk_search_seen;
  831.     else if (!strcmp (criteria+1,"INCE"))
  832.       f = bezerk_search_date (bezerk_search_since,&n);
  833.     else if (!strcmp (criteria+1,"UBJECT"))
  834.       f = bezerk_search_string (bezerk_search_subject,&d,&n);
  835.     break;
  836.       case 'T':            /* possible TEXT, TO */
  837.     if (!strcmp (criteria+1,"EXT"))
  838.       f = bezerk_search_string (bezerk_search_text,&d,&n);
  839.     else if (!strcmp (criteria+1,"O"))
  840.       f = bezerk_search_string (bezerk_search_to,&d,&n);
  841.     break;
  842.       case 'U':            /* possible UN* */
  843.     if (criteria[1] == 'N') {
  844.       if (!strcmp (criteria+2,"ANSWERED")) f = bezerk_search_unanswered;
  845.       else if (!strcmp (criteria+2,"DELETED")) f = bezerk_search_undeleted;
  846.       else if (!strcmp (criteria+2,"FLAGGED")) f = bezerk_search_unflagged;
  847.       else if (!strcmp (criteria+2,"KEYWORD"))
  848.         f = bezerk_search_flag (bezerk_search_unkeyword,&d);
  849.       else if (!strcmp (criteria+2,"SEEN")) f = bezerk_search_unseen;
  850.     }
  851.     break;
  852.       default:            /* we will barf below */
  853.     break;
  854.       }
  855.       if (!f) {            /* if can't determine any criteria */
  856.     sprintf (LOCAL->buf,"Unknown search criterion: %.30s",criteria);
  857.     mm_log (LOCAL->buf,ERROR);
  858.     return;
  859.       }
  860.                 /* run the search criterion */
  861.       for (i = 1; i <= stream->nmsgs; ++i)
  862.     if (mail_elt (stream,i)->searched && !(*f) (stream,i,d,n))
  863.       mail_elt (stream,i)->searched = NIL;
  864.     }
  865.                 /* report search results to main program */
  866.     for (i = 1; i <= stream->nmsgs; ++i)
  867.       if (mail_elt (stream,i)->searched) mail_searched (stream,i);
  868.   }
  869. }
  870.  
  871. /* Berkeley mail ping mailbox
  872.  * Accepts: MAIL stream
  873.  * Returns: T if stream alive, else NIL
  874.  * No-op for readonly files, since read/writer can expunge it from under us!
  875.  */
  876.  
  877. long bezerk_ping (stream)
  878.     MAILSTREAM *stream;
  879. {
  880.   char lock[MAILTMPLEN];
  881.   struct stat sbuf;
  882.   int fd;
  883.                 /* does he want to give up readwrite? */
  884.   if (stream->readonly && LOCAL->ld) {
  885.     flock (LOCAL->ld,LOCK_UN);    /* yes, release the lock */
  886.     close (LOCAL->ld);        /* close the lock file */
  887.     LOCAL->ld = NIL;        /* no more lock fd */
  888.     unlink (LOCAL->lname);    /* delete it */
  889.     fs_give ((void **) &LOCAL->lname);
  890.   }
  891.                 /* make sure it is alright to do this at all */
  892.   if (LOCAL && LOCAL->ld && !stream->lock) {
  893.                 /* get current mailbox size */
  894.     stat (LOCAL->name,&sbuf);    /* parse if mailbox changed */
  895.     if ((sbuf.st_size != LOCAL->filesize) &&
  896.     ((fd = bezerk_parse (stream,lock,LOCK_SH)) >= 0)) {
  897.                 /* unlock mailbox */
  898.       bezerk_unlock (fd,stream,lock);
  899.       mail_unlock (stream);    /* and stream */
  900.     }
  901.   }
  902.   return LOCAL ? T : NIL;    /* return if still alive */
  903. }
  904.  
  905. /* Berkeley mail check mailbox
  906.  * Accepts: MAIL stream
  907.  * No-op for readonly files, since read/writer can expunge it from under us!
  908.  */
  909.  
  910. void bezerk_check (stream)
  911.     MAILSTREAM *stream;
  912. {
  913.   char lock[MAILTMPLEN];
  914.   int fd;
  915.                 /* parse and lock mailbox */
  916.   if (LOCAL && LOCAL->ld && ((fd = bezerk_parse (stream,lock,LOCK_EX)) >= 0)) {
  917.     if (LOCAL->dirty && bezerk_extend (stream,fd,"Unable to update mailbox"))
  918.       bezerk_save (stream,fd);    /* dump checkpoint if needed */
  919.                 /* flush locks */
  920.     bezerk_unlock (fd,stream,lock);
  921.     mail_unlock (stream);
  922.   }
  923.   if (LOCAL && LOCAL->ld) mm_log ("Check completed",NIL);
  924. }
  925.  
  926. /* Berkeley mail expunge mailbox
  927.  * Accepts: MAIL stream
  928.  */
  929.  
  930. void bezerk_expunge (stream)
  931.     MAILSTREAM *stream;
  932. {
  933.   int fd,j;
  934.   long i = 1;
  935.   long n = 0;
  936.   unsigned long recent;
  937.   MESSAGECACHE *elt;
  938.   char *r = "No messages deleted, so no update needed";
  939.   char lock[MAILTMPLEN];
  940.   if (LOCAL && LOCAL->ld) {    /* parse and lock mailbox */
  941.     if ((fd = bezerk_parse (stream,lock,LOCK_EX)) >= 0) {
  942.       recent = stream->recent;    /* get recent now that new ones parsed */
  943.       while ((j = (i<=stream->nmsgs)) && !(elt = mail_elt (stream,i))->deleted)
  944.     i++;            /* find first deleted message */
  945.       if (j) {            /* found one? */
  946.                 /* make sure we can do the worst case thing */
  947.     if (bezerk_extend (stream,fd,"Unable to expunge mailbox")) {
  948.       do {            /* flush deleted messages */
  949.         if ((elt = mail_elt (stream,i))->deleted) {
  950.                 /* if recent, note one less recent message */
  951.           if (elt->recent) --recent;
  952.                 /* flush local cache entry */
  953.           fs_give ((void **) &LOCAL->msgs[i - 1]);
  954.           for (j = i; j < stream->nmsgs; j++)
  955.         LOCAL->msgs[j - 1] = LOCAL->msgs[j];
  956.           LOCAL->msgs[stream->nmsgs - 1] = NIL;
  957.                 /* notify upper levels */
  958.           mail_expunged (stream,i);
  959.           n++;        /* count another expunged message */
  960.         }
  961.         else i++;        /* otherwise try next message */
  962.       } while (i <= stream->nmsgs);
  963.                 /* dump checkpoint of the results */
  964.       bezerk_save (stream,fd);
  965.       sprintf ((r = LOCAL->buf),"Expunged %d messages",n);
  966.     }
  967.       }
  968.                 /* notify upper level, free locks */
  969.       mail_exists (stream,stream->nmsgs);
  970.       mail_recent (stream,recent);
  971.       bezerk_unlock (fd,stream,lock);
  972.       mail_unlock (stream);
  973.     }
  974.   }
  975.   else r = "Expunge ignored on readonly mailbox";
  976.   if (LOCAL && !stream->silent) mm_log (r,NIL);
  977. }
  978.  
  979. /* Berkeley mail copy message(s)
  980.     s;
  981.  * Accepts: MAIL stream
  982.  *        sequence
  983.  *        destination mailbox
  984.  * Returns: T if copy successful, else NIL
  985.  */
  986.  
  987. long bezerk_copy (stream,sequence,mailbox)
  988.     MAILSTREAM *stream;
  989.     char *sequence;
  990.     char *mailbox;
  991. {
  992.                 /* copy the messages */
  993.   return (mail_sequence (stream,sequence)) ?
  994.     bezerk_copy_messages (stream,mailbox) : NIL;
  995. }
  996.  
  997.  
  998. /* Berkeley mail move message(s)
  999.     s;
  1000.  * Accepts: MAIL stream
  1001.  *        sequence
  1002.  *        destination mailbox
  1003.  * Returns: T if move successful, else NIL
  1004.  */
  1005.  
  1006. long bezerk_move (stream,sequence,mailbox)
  1007.     MAILSTREAM *stream;
  1008.     char *sequence;
  1009.     char *mailbox;
  1010. {
  1011.   long i;
  1012.   MESSAGECACHE *elt;
  1013.   if (!(mail_sequence (stream,sequence) &&
  1014.     bezerk_copy_messages (stream,mailbox))) return NIL;
  1015.                 /* delete all requested messages */
  1016.   for (i = 1; i <= stream->nmsgs; i++)
  1017.     if ((elt = mail_elt (stream,i))->sequence) {
  1018.       elt->deleted = T;        /* mark message deleted */
  1019.                 /* recalculate Status/X-Status lines */
  1020.       bezerk_update_status (LOCAL->msgs[i - 1]->status,elt);
  1021.       LOCAL->dirty = T;        /* note stream is now dirty */
  1022.     }
  1023.   return T;
  1024. }
  1025.  
  1026. /* Berkeley mail append message from stringstruct
  1027.  * Accepts: MAIL stream
  1028.  *        destination mailbox
  1029.  *        stringstruct of messages to append
  1030.  * Returns: T if append successful, else NIL
  1031.  */
  1032.  
  1033. #define BUFLEN 8*MAILTMPLEN
  1034.  
  1035. long bezerk_append (stream,mailbox,message)
  1036.     MAILSTREAM *stream;
  1037.     char *mailbox;
  1038.     STRING *message;
  1039. {
  1040.   struct stat sbuf;
  1041.   int fd,i;
  1042.   char buf[BUFLEN],lock[MAILTMPLEN];
  1043.   char c = '\n';
  1044.   long ok = T;
  1045.   unsigned long t = time (0);
  1046.   long size = SIZE (message);
  1047.   if ((fd = bezerk_lock (bezerk_file (buf,mailbox),O_WRONLY|O_APPEND|O_CREAT,
  1048.              S_IREAD|S_IWRITE,lock,LOCK_EX)) < 0) {
  1049.     sprintf (buf,"Can't open append mailbox: %s",strerror (errno));
  1050.     mm_log (buf,ERROR);
  1051.     return NIL;
  1052.   }
  1053.   mm_critical (stream);        /* go critical */
  1054.   fstat (fd,&sbuf);        /* get current file size */
  1055.   sprintf (buf,"From %s@%s %s",myusername (),lhostn,ctime (&t));
  1056.   i = strlen (buf);        /* initial buffer space used */
  1057.   while (ok && size--) {    /* copy text, tossing out CR's */
  1058.     if (c == '\n') {        /* if at start of line */
  1059.       t = GETPOS (message);    /* prepend a broket if needed */
  1060.       if ((SNX (message) == 'F') && (SNX (message) == 'r') &&
  1061.       (SNX (message) == 'o') && (SNX (message) == 'm') &&
  1062.       (SNX (message) == ' ')) ok = bezerk_append_putc (fd,buf,&i,'>');
  1063.       SETPOS (message,t);    /* restore position as needed */
  1064.     }
  1065.                 /* copy another character */
  1066.     if ((c = SNX (message)) != '\015') ok = bezerk_append_putc (fd,buf,&i,c);
  1067.   }
  1068.                 /* write trailing newline */
  1069.   if (ok) ok = bezerk_append_putc (fd,buf,&i,'\n');
  1070.   if (!(ok && (ok = (write (fd,buf,i) >= 0)))) {
  1071.     sprintf (buf,"Message append failed: %s",strerror (errno));
  1072.     mm_log (buf,ERROR);
  1073.     ftruncate (fd,sbuf.st_size);
  1074.   }
  1075.   fsync (fd);            /* force out the update */
  1076.   bezerk_unlock (fd,NIL,lock);    /* unlock and close mailbox */
  1077.   mm_nocritical (stream);    /* release critical */
  1078.   return ok;            /* return success */
  1079. }
  1080.  
  1081. /* Berkeley mail append character
  1082.  * Accepts: file descriptor
  1083.  *        output buffer
  1084.  *        pointer to current size of output buffer
  1085.  *        character to append
  1086.  * Returns: T if append successful, else NIL
  1087.  */
  1088.  
  1089. long bezerk_append_putc (fd,s,i,c)
  1090.     int fd;
  1091.     char *s;
  1092.     int *i;
  1093.     char c;
  1094. {
  1095.   s[(*i)++] = c;
  1096.   if (*i == BUFLEN) {        /* dump if buffer filled */
  1097.     if (write (fd,s,*i) < 0) return NIL;
  1098.     *i = 0;            /* reset */
  1099.   }
  1100.   return T;
  1101. }
  1102.  
  1103. /* Berkeley garbage collect stream
  1104.  * Accepts: Mail stream
  1105.  *        garbage collection flags
  1106.  */
  1107.  
  1108. void bezerk_gc (stream,gcflags)
  1109.     MAILSTREAM *stream;
  1110.     long gcflags;
  1111. {
  1112.   /* nothing here for now */
  1113. }
  1114.  
  1115. /* Internal routines */
  1116.  
  1117.  
  1118. /* Berkeley mail abort stream
  1119.  * Accepts: MAIL stream
  1120.  */
  1121.  
  1122. void bezerk_abort (stream)
  1123.     MAILSTREAM *stream;
  1124. {
  1125.   long i;
  1126.   if (LOCAL) {            /* only if a file is open */
  1127.     if (LOCAL->name) fs_give ((void **) &LOCAL->name);
  1128.     if (LOCAL->ld) {        /* have a mailbox lock? */
  1129.       flock (LOCAL->ld,LOCK_UN);/* yes, release the lock */
  1130.       close (LOCAL->ld);    /* close the lock file */
  1131.       unlink (LOCAL->lname);    /* and delete it */
  1132.     }
  1133.     fs_give ((void **) &LOCAL->lname);
  1134.     if (LOCAL->msgs) {        /* free local cache */
  1135.       for (i = 0; i < stream->nmsgs; ++i) fs_give ((void **) &LOCAL->msgs[i]);
  1136.       fs_give ((void **) &LOCAL->msgs);
  1137.     }
  1138.                 /* free local text buffers */
  1139.     if (LOCAL->buf) fs_give ((void **) &LOCAL->buf);
  1140.                 /* nuke the local data */
  1141.     fs_give ((void **) &stream->local);
  1142.     stream->dtb = NIL;        /* log out the DTB */
  1143.   }
  1144. }
  1145.  
  1146. /* Berkeley mail generate file string
  1147.  * Accepts: temporary buffer to write into
  1148.  *        mailbox name string
  1149.  * Returns: local file string
  1150.  */
  1151.  
  1152.  
  1153. char *bezerk_file (dst,name)
  1154.     char *dst;
  1155.     char *name;
  1156. {
  1157.   struct passwd *pw;
  1158.   char *s,*t,tmp[MAILTMPLEN];
  1159.   switch (*name) {
  1160.   case '*':            /* bboard? */
  1161.     sprintf (tmp,"~ftp/%s",(name[1] == '/') ? name+2 : name+1);
  1162.     dst = bezerk_file (dst,tmp);/* recurse to get result */
  1163.     break;
  1164.   case '/':            /* absolute file path */
  1165.     strcpy (dst,name);        /* copy the mailbox name */
  1166.     break;
  1167.   case '~':            /* home directory */
  1168.     if (name[1] == '/') t = myhomedir ();
  1169.     else {
  1170.       strcpy (tmp,name + 1);    /* copy user name */
  1171.       if (s = strchr (tmp,'/')) *s = '\0';
  1172.       t = ((pw = getpwnam (tmp)) && pw->pw_dir) ? pw->pw_dir : "/NOSUCHUSER";
  1173.     }
  1174.     sprintf (dst,"%s%s",t,(s = strchr (name,'/')) ? s : "");
  1175.     break;
  1176.   default:            /* other name */
  1177.     if (strcmp (ucase (strcpy (dst,name)),"INBOX"))
  1178.       sprintf (dst,"%s/%s",myhomedir (),name);
  1179.                 /* INBOX becomes mail spool directory file */
  1180.     else sprintf (dst,MAILFILE,myusername ());
  1181.   }
  1182.   return dst;
  1183. }
  1184.  
  1185. /* Berkeley open and lock mailbox
  1186.  * Accepts: file name to open/lock
  1187.  *        file open mode
  1188.  *        destination buffer for lock file name
  1189.  *        type of locking operation (LOCK_SH or LOCK_EX)
  1190.  */
  1191.  
  1192. int bezerk_lock (file,flags,mode,lock,op)
  1193.     char *file;
  1194.     int flags;
  1195.     int mode;
  1196.     char *lock;
  1197.     int op;
  1198. {
  1199.   int fd,ld,j;
  1200.   int i = LOCKTIMEOUT * 60 - 1;
  1201.   char tmp[MAILTMPLEN];
  1202.   struct timeval tp;
  1203.   struct stat sb;
  1204.                 /* build lock filename */
  1205.   strcat (bezerk_file (lock,file),".lock");
  1206.   do {                /* until OK or out of tries */
  1207.     gettimeofday (&tp,NIL);    /* get the time now */
  1208. #ifdef NFSKLUDGE
  1209.   /* SUN-OS had an NFS, As kludgy as an albatross;
  1210.    * And everywhere that it was installed, It was a total loss.  -- MRC 9/25/91
  1211.    */
  1212.                 /* build hitching post file name */
  1213.     sprintf (tmp,"%s.%d.%d.",lock,time (0),getpid ());
  1214.     j = strlen (tmp);        /* append local host name */
  1215.     gethostname (tmp + j,(MAILTMPLEN - j) - 1);
  1216.                 /* try to get hitching-post file */
  1217.     if ((ld = open (tmp,O_WRONLY|O_CREAT|O_EXCL,0666)) < 0) {
  1218.                 /* prot fail & non-ex, don't use lock files */
  1219.       if ((errno == EACCES) && (stat (tmp,&sb))) *lock = '\0';
  1220.       else {            /* otherwise something strange is going on */
  1221.     sprintf (tmp,"Error creating %s: %s",lock,strerror (errno));
  1222.     mm_log (tmp,WARN);    /* this is probably not good */
  1223.                 /* don't use lock files if not one of these */
  1224.     if ((errno != EEXIST) && (errno != EACCES)) *lock = '\0';
  1225.       }
  1226.     }
  1227.     else {            /* got a hitching-post */
  1228.       chmod (tmp,0666);        /* make sure others can break the lock */
  1229.       close (ld);        /* close the hitching-post */
  1230.       link (tmp,lock);        /* tie hitching-post to lock, ignore failure */
  1231.       stat (tmp,&sb);        /* get its data */
  1232.       unlink (tmp);        /* flush hitching post */
  1233.       /* If link count .ne. 2, hitch failed.  Set ld to -1 as if open() failed
  1234.      so we try again.  If extant lock file and time now is .gt. file time
  1235.      plus timeout interval, flush the lock so can win next time around. */
  1236.       if ((ld = (sb.st_nlink != 2) ? -1 : 0) && (!stat (lock,&sb)) &&
  1237.       (tp.tv_sec > sb.st_ctime + LOCKTIMEOUT * 60)) unlink (lock);
  1238.     }
  1239.  
  1240. #else
  1241.   /* This works on modern Unix systems which are not afflicted with NFS mail.
  1242.    * "Modern" means that O_EXCL works.  I think that NFS mail is a terrible
  1243.    * idea -- that's what IMAP is for -- but some people insist upon losing...
  1244.    */
  1245.                 /* try to get the lock */
  1246.     if ((ld = open (lock,O_WRONLY|O_CREAT|O_EXCL,0666)) < 0) switch (errno) {
  1247.     case EEXIST:        /* if extant and old, grab it for ourselves */
  1248.       if ((!stat (lock,&sb)) && tp.tv_sec > sb.st_ctime + LOCKTIMEOUT * 60)
  1249.     ld = open (lock,O_WRONLY|O_CREAT,0666);
  1250.       break;
  1251.     case EACCES:        /* protection fail, ignore if non-ex or old */
  1252.       if (stat (lock,&sb) || (tp.tv_sec > sb.st_ctime + LOCKTIMEOUT * 60))
  1253.     *lock = '\0';        /* assume no world write mail spool dir */
  1254.       break;
  1255.     default:            /* some other failure */
  1256.       sprintf (tmp,"Error creating %s: %s",lock,strerror (errno));
  1257.       mm_log (tmp,WARN);    /* this is probably not good */
  1258.       *lock = '\0';        /* don't use lock files */
  1259.       break;
  1260.     }
  1261.     if (ld >= 0) {        /* if made a lock file */
  1262.       chmod (lock,0666);    /* make sure others can break the lock */
  1263.       close (ld);        /* close the lock file */
  1264.     }
  1265. #endif
  1266.     if ((ld < 0) && *lock) {    /* if failed to make lock file and retry OK */
  1267.       if (!(i%15)) {
  1268.     sprintf (tmp,"Mailbox %s is locked, will override in %d seconds...",
  1269.          file,i);
  1270.     mm_log (tmp,WARN);
  1271.       }
  1272.       sleep (1);        /* wait 1 second before next try */
  1273.     }
  1274.   } while (i-- && ld < 0 && *lock);
  1275.                 /* open file */
  1276.   if ((fd = open (file,flags,mode)) >= 0) flock (fd,op);
  1277.   else {            /* open failed */
  1278.     j = errno;            /* preserve error code */
  1279.     if (*lock) unlink (lock);    /* flush the lock file if any */
  1280.     errno = j;            /* restore error code */
  1281.   }
  1282.   return fd;
  1283. }
  1284.  
  1285. /* Berkeley unlock and close mailbox
  1286.  * Accepts: file descriptor
  1287.  *        (optional) mailbox stream to check atime/mtime
  1288.  *        (optional) lock file name
  1289.  */
  1290.  
  1291. void bezerk_unlock (fd,stream,lock)
  1292.     int fd;
  1293.     MAILSTREAM *stream;
  1294.     char *lock;
  1295. {
  1296.   struct stat sbuf;
  1297.   struct timeval tp[2];
  1298.   fstat (fd,&sbuf);        /* get file times */
  1299.                 /* if stream and csh would think new mail */
  1300.   if (stream && (sbuf.st_atime <= sbuf.st_mtime)) {
  1301.     gettimeofday (&tp[0],NIL);    /* set atime to now */
  1302.                 /* set mtime to (now - 1) if necessary */
  1303.     tp[1].tv_sec = tp[0].tv_sec > sbuf.st_mtime ? sbuf.st_mtime :
  1304.       tp[0].tv_sec - 1;
  1305.     tp[1].tv_usec = 0;        /* oh well */
  1306.                 /* set the times, note change */
  1307.     if (!utimes (LOCAL->name,tp)) LOCAL->filetime = tp[1].tv_sec;
  1308.   }
  1309.   flock (fd,LOCK_UN);        /* release flock'ers */
  1310.   close (fd);            /* close the file */
  1311.                 /* flush the lock file if any */
  1312.   if (lock && *lock) unlink (lock);
  1313. }
  1314.  
  1315. /* Berkeley mail parse and lock mailbox
  1316.  * Accepts: MAIL stream
  1317.  *        space to write lock file name
  1318.  *        type of locking operation
  1319.  * Returns: file descriptor if parse OK, mailbox is locked shared
  1320.  *        -1 if failure, stream aborted
  1321.  */
  1322.  
  1323. int bezerk_parse (stream,lock,op)
  1324.     MAILSTREAM *stream;
  1325.     char *lock;
  1326.     int op;
  1327. {
  1328.   int fd;
  1329.   long delta,i,j,is,is1;
  1330.   char *s,*s1,*t = NIL,*e;
  1331.   int ti = 0,zn = 0;
  1332.   int first = T;
  1333.   long nmsgs = stream->nmsgs;
  1334.   long recent = stream->recent;
  1335.   struct stat sbuf;
  1336.   MESSAGECACHE *elt;
  1337.   FILECACHE *m = NIL,*n = NIL;
  1338.   mail_lock (stream);        /* guard against recursion or pingers */
  1339.                 /* open and lock mailbox (shared OK) */
  1340.   if ((fd = bezerk_lock (LOCAL->name,LOCAL->ld ? O_RDWR : O_RDONLY,NIL,
  1341.              lock,op)) < 0) {
  1342.                 /* failed, OK for non-ex file? */
  1343.     if ((errno != ENOENT) || LOCAL->filesize) {
  1344.       sprintf (LOCAL->buf,"Mailbox open failed, aborted: %s",strerror (errno));
  1345.       mm_log (LOCAL->buf,ERROR);
  1346.       bezerk_abort (stream);
  1347.     }
  1348.     else {            /* this is to allow for non-ex INBOX */
  1349.       mail_exists (stream,0);    /* make sure upper level sees this as empty */
  1350.       mail_recent (stream,0);
  1351.     }
  1352.     mail_unlock (stream);
  1353.     return -1;
  1354.   }
  1355.   fstat (fd,&sbuf);        /* get status */
  1356.                 /* calculate change in size */
  1357.   if ((delta = sbuf.st_size - LOCAL->filesize) < 0) {
  1358.     sprintf (LOCAL->buf,"Mailbox shrank from %d to %d bytes, aborted",
  1359.          LOCAL->filesize,sbuf.st_size);
  1360.     mm_log (LOCAL->buf,ERROR);    /* this is pretty bad */
  1361.     bezerk_unlock (fd,stream,lock);
  1362.     bezerk_abort (stream);
  1363.     mail_unlock (stream);
  1364.     return -1;
  1365.   }
  1366.  
  1367.   else if (delta) {        /* get to that position in the file */
  1368.     lseek (fd,LOCAL->filesize,L_SET);
  1369.     s = s1 = LOCAL->buf;    /* initial read-in location */
  1370.     i = 0;            /* initial unparsed read-in count */
  1371.     do {
  1372.       i = min (CHUNK,delta);    /* calculate read-in size */
  1373.                 /* increase the read-in buffer if necessary */
  1374.       if ((j = i + (s1 - s)) >= LOCAL->buflen) {
  1375.     is = s - LOCAL->buf;    /* note former start of message position */
  1376.     is1 = s1 - LOCAL->buf;    /* and start of new data position */
  1377.     if (s1 - s) fs_resize ((void **) &LOCAL->buf,(LOCAL->buflen = j) + 1);
  1378.     else {            /* fs_resize would do an unnecessary copy */
  1379.       fs_give ((void **) &LOCAL->buf);
  1380.       LOCAL->buf = (char *) fs_get ((LOCAL->buflen = j) + 1);
  1381.     }
  1382.     s = LOCAL->buf + is;    /* new start of message */
  1383.     s1 = LOCAL->buf + is1;    /* new start of new data */
  1384.       }
  1385.       s1[i] = '\0';        /* tie off chunk */
  1386.       if (read (fd,s1,i) < 0) {    /* read a chunk of new text */
  1387.     sprintf (LOCAL->buf,"Error reading mail file: %s",strerror (errno));
  1388.     mm_log (LOCAL->buf,ERROR);
  1389.     bezerk_unlock (fd,stream,lock);
  1390.     bezerk_abort (stream);
  1391.     mail_unlock (stream);
  1392.     return -1;
  1393.       }
  1394.       delta -= i;        /* account for data read in */
  1395.                 /* validate newly-appended data */
  1396.       if (first) {        /* only do this first time! */
  1397.     if (!((*s =='F') && VALID (s,t,ti,zn))) {
  1398.       mm_log ("Mailbox format invalidated (consult an expert), aborted",
  1399.           ERROR);
  1400.       bezerk_unlock (fd,stream,lock);
  1401.       bezerk_abort (stream);
  1402.       mail_unlock (stream);
  1403.       return -1;
  1404.     }
  1405.     first = NIL;        /* don't do this again */
  1406.       }
  1407.  
  1408.                 /* found end of message or end of data? */
  1409.       while ((e = bezerk_eom (s,s1,i)) || !delta) {
  1410.     nmsgs++;        /* yes, have a new message */
  1411.                 /* calculate message length */
  1412.     j = ((e ? e : s1 + i) - s) - 1;
  1413.     if (m) {        /* new cache needed, have previous data? */
  1414.       n->header = (char *) fs_get (sizeof (FILECACHE) + j + 1);
  1415.       n = (FILECACHE *) n->header;
  1416.     }
  1417.     else m = n = (FILECACHE *) fs_get (sizeof (FILECACHE) + j + 1);
  1418.                 /* copy message data */
  1419.     memcpy (n->internal,s,j);
  1420.     n->internal[j] = '\0';
  1421.     n->header = NIL;    /* initially no link */
  1422.     n->headersize = j;    /* stash away buffer length */
  1423.     if (e) {        /* saw end of message? */
  1424.       i -= e - s1;        /* new unparsed data count */
  1425.       s = s1 = e;        /* advance to new message */
  1426.     }
  1427.     else break;        /* else punt this loop */
  1428.       }
  1429.       if (delta) {        /* end of message not found? */
  1430.     s1 += i;        /* end of unparsed data */
  1431.     if (s != LOCAL->buf){    /* message doesn't begin at buffer? */
  1432.       i = s1 - s;        /* length of message so far */
  1433.       memmove (LOCAL->buf,s,i);
  1434.       s = LOCAL->buf;    /* message now starts at buffer origin */
  1435.       s1 = s + i;        /* calculate new end of unparsed data */
  1436.     }
  1437.       }
  1438.     } while (delta);        /* until nothing more new to read */
  1439.   }
  1440.   else {            /* no change, don't babble if never got time */
  1441.     if (LOCAL->filetime && LOCAL->filetime != sbuf.st_mtime)
  1442.       mm_log ("New mailbox modification time but apparently no changes",WARN);
  1443.   }
  1444.                 /* expand the primary cache */
  1445.   (*mailcache) (stream,nmsgs,CH_SIZE);
  1446.   if (LOCAL->msgs) {        /* have a cache yet? */
  1447.     if (nmsgs >= LOCAL->cachesize)
  1448.       fs_resize ((void **) &LOCAL->msgs,
  1449.          (LOCAL->cachesize += CACHEINCREMENT) * sizeof (FILECACHE *));
  1450.   }
  1451.   else LOCAL->msgs = (FILECACHE **)
  1452.     fs_get ((LOCAL->cachesize = nmsgs + CACHEINCREMENT) *sizeof (FILECACHE *));
  1453.  
  1454.   if (LOCAL->buflen > CHUNK) {    /* maybe move where the buffer is in memory*/
  1455.     fs_give ((void **) &LOCAL->buf);
  1456.     LOCAL->buf = (char *) fs_get ((LOCAL->buflen = CHUNK) + 1);
  1457.   }
  1458.   for (i = stream->nmsgs, n = m; i < nmsgs; i++) {
  1459.     LOCAL->msgs[i] = m = n;    /* set cache, and next cache pointer */
  1460.     n = (FILECACHE *) n->header;
  1461.     /* This is a bugtrap for bogons in the new message cache, which may happen
  1462.      * if memory is corrupted.  Note that in the case of a totally empty
  1463.      * message, a newline is appended and counts adjusted.
  1464.      */
  1465.     if (!((s = m->internal) && VALID (s,t,ti,zn)))
  1466.       if (!(s && !strchr (s,'\n') && strcat (s,"\n") && VALID (s,t,ti,zn) &&
  1467.         m->headersize++))
  1468.     fatal ("Bogus entry in new cache list");
  1469.                 /* pointer to message header */
  1470.     m->header = s = strchr (t++,'\n') + 1;
  1471.     m->headersize -= m->header - m->internal;
  1472.     m->body = NIL;        /* assume no body as yet */
  1473.     m->bodysize = 0;
  1474.     recent++;            /* assume recent by default */
  1475.     (elt = mail_elt (stream,i+1))->recent = T;
  1476.                 /* calculate initial Status/X-Status lines */
  1477.     bezerk_update_status (m->status,elt);
  1478.                 /* generate plausable IMAPish date string */
  1479.     LOCAL->buf[2] = LOCAL->buf[6] = LOCAL->buf[20] = '-';
  1480.     LOCAL->buf[11] = ' ';
  1481.     LOCAL->buf[14] = LOCAL->buf[17] = ':';
  1482.                 /* dd */
  1483.     LOCAL->buf[0] = t[ti - 3]; LOCAL->buf[1] = t[ti - 2];
  1484.                 /* mmm */
  1485.     LOCAL->buf[3] = t[ti - 7]; LOCAL->buf[4] = t[ti - 6];
  1486.     LOCAL->buf[5] = t[ti - 5];
  1487.                 /* hh */
  1488.     LOCAL->buf[12] = t[ti]; LOCAL->buf[13] = t[ti + 1];
  1489.                 /* mm */
  1490.     LOCAL->buf[15] = t[ti + 3]; LOCAL->buf[16] = t[ti + 4];
  1491.     if (t[ti += 5] == ':') {    /* ss if present */
  1492.       LOCAL->buf[18] = t[++ti];
  1493.       LOCAL->buf[19] = t[++ti];
  1494.       ti++;            /* move to space */
  1495.     }
  1496.     else LOCAL->buf[18] = LOCAL->buf[19] = '0';
  1497.                 /* yy -- advance over timezone if necessary */
  1498.     if (zn == ++ti) ti += (((t[zn] == '+') || (t[zn] == '-')) ? 6 : 4);
  1499.     LOCAL->buf[7] = t[ti]; LOCAL->buf[8] = t[ti + 1];
  1500.     LOCAL->buf[9] = t[ti + 2]; LOCAL->buf[10] = t[ti + 3];
  1501.                 /* zzz */
  1502.     t = zn ? (t + zn) : "LCL";
  1503.     LOCAL->buf[21] = *t++; LOCAL->buf[22] = *t++; LOCAL->buf[23] = *t++;
  1504.     if ((LOCAL->buf[21] != '+') && (LOCAL->buf[21] != '-'))
  1505.       LOCAL->buf[24] = '\0';
  1506.     else {            /* numeric time zone */
  1507.       LOCAL->buf[24] = *t++; LOCAL->buf[25] = *t++;
  1508.       LOCAL->buf[26] = '\0'; LOCAL->buf[20] = ' ';
  1509.     }
  1510.                 /* set internal date */
  1511.     if (!mail_parse_date (elt,LOCAL->buf)) mm_log ("Unparsable date",WARN);
  1512.  
  1513.     is = 0;            /* initialize newline count */
  1514.     e = NIL;            /* no status stuff yet */
  1515.     do switch (*(t = s)) {    /* look at header lines */
  1516.     case 'X':            /* possible X-Status: line */
  1517.       if (s[1] == '-' && s[2] == 'S') s += 2;
  1518.       else {
  1519.     is++;            /* count another newline */
  1520.     break;            /* this is uninteresting after all */
  1521.       }
  1522.     case 'S':            /* possible Status: line */
  1523.       if (s[1] == 't' && s[2] == 'a' && s[3] == 't' && s[4] == 'u' &&
  1524.       s[5] == 's' && s[6] == ':') {
  1525.     if (!e) e = t;        /* note deletion point */
  1526.     s += 6;            /* advance to status flags */
  1527.     do switch (*s++) {    /* parse flags */
  1528.     case 'R':        /* message read */
  1529.       elt->seen = T;
  1530.       break;
  1531.     case 'O':        /* message old */
  1532.       if (elt->recent) {    /* don't do this more than once! */
  1533.         elt->recent = NIL;
  1534.         recent--;        /* not recent any longer... */
  1535.       }
  1536.       break;
  1537.     case 'D':        /* message deleted */
  1538.       elt->deleted = T;
  1539.       break;
  1540.     case 'F':        /* message flagged */
  1541.       elt ->flagged = T;
  1542.       break;
  1543.     case 'A':        /* message answered */
  1544.       elt ->answered = T;
  1545.       break;
  1546.     default:        /* some other crap */
  1547.       break;
  1548.     } while (*s && *s != '\n');
  1549.                 /* recalculate Status/X-Status lines */
  1550.     bezerk_update_status (m->status,elt);
  1551.       }
  1552.       else is++;        /* otherwise random line */
  1553.       break;
  1554.  
  1555.     case '\n':            /* end of header */
  1556.       m->body = ++s;        /* start of body is here */
  1557.       j = m->body - m->header;    /* new header size */
  1558.                 /* calculate body size */
  1559.       m->bodysize = m->headersize - j;
  1560.       if (e) {            /* saw status poop? */
  1561.     *e++ = '\n';        /* patch in trailing newline */
  1562.     m->headersize = e - m->header;
  1563.       }
  1564.       else m->headersize = j;    /* set header size */
  1565.       s = NIL;            /* don't scan any further */
  1566.       is++;            /* count a newline */
  1567.       break;
  1568.     case '\0':            /* end of message */
  1569.       if (e) {            /* saw status poop? */
  1570.     *e++ = '\n';        /* patch in trailing newline */
  1571.     m->headersize = e - m->header;
  1572.       }
  1573.       is++;            /* count an extra newline here */
  1574.       break;
  1575.     default:            /* anything else is uninteresting */
  1576.       if (e) {            /* have status stuff to worry about? */
  1577.     j = s - e;        /* yuck!!  calculate size of delete area */
  1578.                 /* blat remaining number of bytes down */
  1579.     memmove (e,s,m->header + m->headersize - s);
  1580.     m->headersize -= j;    /* update for new size */
  1581.     e = NIL;        /* no more delete area */
  1582.                 /* tie off old cruft */
  1583.     *(m->header + m->headersize) = '\0';
  1584.       }
  1585.       is++;
  1586.       break;
  1587.     } while (s && (s = strchr (s,'\n')) && s++);
  1588.                 /* count newlines in body */
  1589.     if (s = m->body) while (*s) if (*s++ == '\n') is++;
  1590.     elt->rfc822_size = m->headersize + m->bodysize + is;
  1591.   }
  1592.   if (n) fatal ("Cache link-list inconsistency");
  1593.   while (i < LOCAL->cachesize) LOCAL->msgs[i++] = NIL;
  1594.                 /* update parsed file size and time */
  1595.   LOCAL->filesize = sbuf.st_size;
  1596.   LOCAL->filetime = sbuf.st_mtime;
  1597.   mail_exists (stream,nmsgs);    /* notify upper level of new mailbox size */
  1598.   mail_recent (stream,recent);    /* and of change in recent messages */
  1599.   if (recent) LOCAL->dirty = T;    /* mark dirty so O flags are set */
  1600.   return fd;            /* return the winnage */
  1601. }
  1602.  
  1603. /* Berkeley search for end of message
  1604.  * Accepts: start of message
  1605.  *        start of new data
  1606.  *        size of new data
  1607.  * Returns: pointer to start of new message if one found
  1608.  */
  1609.  
  1610. #define Word unsigned long
  1611.  
  1612. char *bezerk_eom (som,sod,i)
  1613.     char *som;
  1614.     char *sod;
  1615.     long i;
  1616. {
  1617.   char *s = (sod > som) ? sod - 1 : sod;
  1618.   char *t;
  1619.   int ti,zn;
  1620.   union {
  1621.     unsigned long wd;
  1622.     char ch[9];
  1623.   } wdtest;
  1624.   strcpy (wdtest.ch,"AAAA1234");/* constant for word testing */
  1625.   while ((s > som) && *s-- != '\n');
  1626.   if (wdtest.wd != 0x41414141) {/* not a 32-bit word machine? */
  1627.     while (s = strstr (s,"\nFrom ")) if (s++ && VALID (s,t,ti,zn)) return s;
  1628.   }
  1629.   else {            /* can do it faster this way */
  1630.     register Word m = 0x0a0a0a0a;
  1631.     while ((long) s & 3)    /* any characters before word boundary? */
  1632.       if ((*s++ == '\n') && s[0] == 'F' && VALID (s,t,ti,zn)) return s;
  1633.     i = (sod + i) - s;        /* total number of tries */
  1634.     do {            /* fast search for newline */
  1635.       if (0x80808080 & (0x01010101 + (0x7f7f7f7f & ~(m ^ *(Word *) s)))) {
  1636.                 /* interesting word, check it closer */
  1637.     if (*s++ == '\n' && s[0] == 'F' && VALID (s,t,ti,zn)) return s;
  1638.     else if (*s++ == '\n' && s[0] == 'F' && VALID (s,t,ti,zn)) return s;
  1639.     else if (*s++ == '\n' && s[0] == 'F' && VALID (s,t,ti,zn)) return s;
  1640.     else if (*s++ == '\n' && s[0] == 'F' && VALID (s,t,ti,zn)) return s;
  1641.       }
  1642.       else s += 4;        /* try next word */
  1643.       i -= 4;            /* count a word checked */
  1644.     } while (i > 24);        /* continue until end of plausible string */
  1645.   }
  1646.   return NIL;
  1647. }
  1648.  
  1649. /* Berkeley extend mailbox to reserve worst-case space for expansion
  1650.  * Accepts: MAIL stream
  1651.  *        file descriptor
  1652.  *        error string
  1653.  * Returns: T if extend OK and have gone critical, NIL if should abort
  1654.  */
  1655.  
  1656. int bezerk_extend (stream,fd,error)
  1657.     MAILSTREAM *stream;
  1658.     int fd;
  1659.     char *error;
  1660. {
  1661.   struct stat sbuf;
  1662.   FILECACHE *m;
  1663.   char tmp[MAILTMPLEN];
  1664.   int i,ok;
  1665.   long f;
  1666.   char *s;
  1667.   int retry;
  1668.                 /* calculate estimated size of mailbox */
  1669.   for (i = 0,f = 0; i < stream->nmsgs; i++) {
  1670.     m = LOCAL->msgs[i];        /* get cache pointer */
  1671.     f += (m->header - m->internal) + m->headersize + sizeof (STATUS) +
  1672.       m->bodysize + 1;        /* update guesstimate */
  1673.     }
  1674.   mm_critical (stream);        /* go critical */
  1675.                 /* return now if file large enough */
  1676.   if (f <= LOCAL->filesize) return T;
  1677.   s = (char *) fs_get (f -= LOCAL->filesize);
  1678.   memset (s,0,f);        /* get a block of nulls */
  1679.                 /* get to end of file */
  1680.   lseek (fd,LOCAL->filesize,L_SET);
  1681.   do {
  1682.     retry = NIL;        /* no retry yet */
  1683.     if (!(ok = (write (fd,s,f) >= 0))) {
  1684.       i = errno;        /* note error before doing ftruncate */
  1685.                 /* restore prior file size */
  1686.       ftruncate (fd,LOCAL->filesize);
  1687.       fsync (fd);        /* is this necessary? */
  1688.       fstat (fd,&sbuf);        /* now get updated file time */
  1689.       LOCAL->filetime = sbuf.st_mtime;
  1690.                 /* punt if that's what main program wants */
  1691.       if (mm_diskerror (stream,i,NIL)) {
  1692.     mm_nocritical (stream);    /* exit critical */
  1693.     sprintf (tmp,"%s: %s",error,strerror (i));
  1694.     mm_notify (stream,tmp,WARN);
  1695.       }
  1696.       else retry = T;        /* set to retry */
  1697.     }
  1698.   } while (retry);        /* repeat if need to try again */
  1699.   fs_give ((void **) &s);    /* flush buffer of nulls */
  1700.   return ok;            /* return status */
  1701. }
  1702.  
  1703. /* Berkeley save mailbox
  1704.  * Accepts: MAIL stream
  1705.  *        mailbox file descriptor
  1706.  *
  1707.  * Mailbox must be readwrite and locked for exclusive access.
  1708.  */
  1709.  
  1710. void bezerk_save (stream,fd)
  1711.     MAILSTREAM *stream;
  1712.     int fd;
  1713. {
  1714.   struct stat sbuf;
  1715.   struct iovec iov[16];
  1716.   int iovc;
  1717.   long i;
  1718.   int e;
  1719.   int retry;
  1720.   do {                /* restart point if failure */
  1721.     retry = NIL;        /* no need to retry yet */
  1722.                 /* start at beginning of file */
  1723.     lseek (fd,LOCAL->filesize = 0,L_SET);
  1724.                 /* loop through all messages */
  1725.     for (i = 1,iovc = 0; i <= stream->nmsgs; i++) {
  1726.                 /* set up iov's for this message */
  1727.       bezerk_write_message (iov,&iovc,LOCAL->msgs[i-1]);
  1728.                 /* filled up iovec or end of messages? */
  1729.       if ((iovc == 16) || (i == stream->nmsgs)) {
  1730.                 /* write messages */
  1731.     if ((e = writev (fd,iov,iovc)) < 0) {
  1732.       sprintf (LOCAL->buf,"Unable to rewrite mailbox: %s",
  1733.            strerror (e = errno));
  1734.       mm_log (LOCAL->buf,WARN);
  1735.       mm_diskerror (stream,e,T);
  1736.       retry = T;        /* must retry */
  1737.       break;        /* abort this particular try */
  1738.     }
  1739.     else {            /* won */
  1740.       iovc = 0;        /* restart iovec */
  1741.       LOCAL->filesize += e;    /* count these bytes in data */
  1742.     }
  1743.       }
  1744.     }
  1745.   } while (retry);        /* repeat if need to try again */
  1746.   fsync (fd);            /* make sure the disk has the update */
  1747.                 /* nuke any cruft after that */
  1748.   ftruncate (fd,LOCAL->filesize);
  1749.   fsync (fd);            /* is this necessary? */
  1750.   fstat (fd,&sbuf);        /* now get updated file time */
  1751.   LOCAL->filetime = sbuf.st_mtime;
  1752.   LOCAL->dirty = NIL;        /* stream no longer dirty */
  1753.   mm_nocritical (stream);    /* exit critical */
  1754. }
  1755.  
  1756. /* Berkeley copy messages
  1757.  * Accepts: MAIL stream
  1758.  *        mailbox name
  1759.  * Returns: T if copy successful else NIL
  1760.  */
  1761.  
  1762. int bezerk_copy_messages (stream,mailbox)
  1763.     MAILSTREAM *stream;
  1764.     char *mailbox;
  1765. {
  1766.   char file[MAILTMPLEN];
  1767.   char lock[MAILTMPLEN];
  1768.   struct iovec iov[16];
  1769.   int fd,iovc;
  1770.   struct stat sbuf;
  1771.   long i;
  1772.   int ok = T;
  1773.                 /* make sure valid mailbox */
  1774.   if (!bezerk_isvalid (mailbox,file)) {
  1775.     if (errno == ENOENT)    /* failed, was it no such file? */
  1776.       mm_notify (stream,"[TRYCREATE] Must create mailbox before append",NIL);
  1777.     else {
  1778.       sprintf (LOCAL->buf,"Not a Berkeley-format mailbox: %s",mailbox);
  1779.       mm_log (LOCAL->buf,ERROR);
  1780.     }
  1781.     return NIL;
  1782.   }
  1783.   if ((fd = bezerk_lock (bezerk_file (file,mailbox),O_WRONLY|O_APPEND|O_CREAT,
  1784.              S_IREAD|S_IWRITE,lock,LOCK_EX)) < 0) {
  1785.     sprintf (LOCAL->buf,"Can't open destination mailbox: %s",strerror (errno));
  1786.     mm_log (LOCAL->buf,ERROR);
  1787.     return NIL;
  1788.   }
  1789.   mm_critical (stream);        /* go critical */
  1790.   fstat (fd,&sbuf);        /* get current file size */
  1791.                 /* write all requested messages to mailbox */
  1792.   for (i = 1,iovc = 0; ok && i <= stream->nmsgs; i++) {
  1793.                 /* set up iov's if message selected */
  1794.     if (mail_elt (stream,i)->sequence)
  1795.       bezerk_write_message (iov,&iovc,LOCAL->msgs[i - 1]);
  1796.                 /* filled up iovec or end of messages? */
  1797.     if (iovc && ((iovc == 16) || (i == stream->nmsgs))) {
  1798.       if (ok = (writev (fd,iov,iovc) >= 0)) iovc = 0;
  1799.       else {
  1800.     sprintf (LOCAL->buf,"Message copy failed: %s",strerror (errno));
  1801.     mm_log (LOCAL->buf,ERROR);
  1802.     ftruncate (fd,sbuf.st_size);
  1803.     break;
  1804.       }
  1805.     }
  1806.   }
  1807.   fsync (fd);            /* force out the update */
  1808.   bezerk_unlock (fd,NIL,lock);    /* unlock and close mailbox */
  1809.   mm_nocritical (stream);    /* release critical */
  1810.   return ok;            /* return whether or not succeeded */
  1811. }
  1812.  
  1813. /* Berkeley write message to mailbox
  1814.  * Accepts: I/O vector
  1815.  *        I/O vector index
  1816.  *        local cache for this message
  1817.  *
  1818.  * This routine is the reason why the local cache has a copy of the status.
  1819.  * We can be called to dump out the mailbox as part of a stream recycle, since
  1820.  * we don't write out the mailbox when flags change and hence an update may be
  1821.  * needed.  However, at this point the elt has already become history, so we
  1822.  * can't use any information other than what is local to us.
  1823.  */
  1824.  
  1825. void bezerk_write_message (iov,i,m)
  1826.     struct iovec iov[];
  1827.     int *i;
  1828.     FILECACHE *m;
  1829. {
  1830.   iov[*i].iov_base =m->internal;/* pointer/counter to headers */
  1831.                 /* length of internal + message headers */
  1832.   iov[*i].iov_len = (m->header + m->headersize) - m->internal;
  1833.                 /* suppress extra newline if present */
  1834.   if ((iov[*i].iov_base)[iov[*i].iov_len - 2] == '\n') iov[(*i)++].iov_len--;
  1835.   else (*i)++;            /* unlikely but... */
  1836.   iov[*i].iov_base = m->status;    /* pointer/counter to status */
  1837.   iov[(*i)++].iov_len = strlen (m->status);
  1838.   iov[*i].iov_base = m->body;    /* pointer/counter to text body */
  1839.   iov[(*i)++].iov_len = m->bodysize;
  1840.   iov[*i].iov_base = "\n";    /* pointer/counter to extra newline */
  1841.   iov[(*i)++].iov_len = 1;
  1842. }
  1843.  
  1844. /* Berkeley update status string
  1845.  * Accepts: destination string to write
  1846.  *        message cache entry
  1847.  */
  1848.  
  1849. void bezerk_update_status (status,elt)
  1850.     char *status;
  1851.     MESSAGECACHE *elt;
  1852. {
  1853.   /* This used to be an sprintf(), but thanks to certain cretinous C libraries
  1854.      with horribly slow implementations of sprintf() I had to change it to this
  1855.      mess.  At least it should be fast. */
  1856.   char *t = status + 8;
  1857.   status[0] = 'S'; status[1] = 't'; status[2] = 'a'; status[3] = 't';
  1858.   status[4] = 'u'; status[5] = 's'; status[6] = ':';  status[7] = ' ';
  1859.   if (elt->seen) *t++ = 'R'; *t++ = 'O'; *t++ = '\n';
  1860.   *t++ = 'X'; *t++ = '-'; *t++ = 'S'; *t++ = 't'; *t++ = 'a'; *t++ = 't';
  1861.   *t++ = 'u'; *t++ = 's'; *t++ = ':'; *t++ = ' ';
  1862.   if (elt->deleted) *t++ = 'D'; if (elt->flagged) *t++ = 'F';
  1863.   if (elt->answered) *t++ = 'A';
  1864.   *t++ = '\n'; *t++ = '\n'; *t++ = '\0';
  1865. }
  1866.  
  1867. /* Parse flag list
  1868.  * Accepts: MAIL stream
  1869.  *        flag list as a character string
  1870.  * Returns: flag command list
  1871.  */
  1872.  
  1873.  
  1874. short bezerk_getflags (stream,flag)
  1875.     MAILSTREAM *stream;
  1876.     char *flag;
  1877. {
  1878.   char *t;
  1879.   short f = 0;
  1880.   short i,j;
  1881.   if (flag && *flag) {        /* no-op if no flag string */
  1882.                 /* check if a list and make sure valid */
  1883.     if ((i = (*flag == '(')) ^ (flag[strlen (flag)-1] == ')')) {
  1884.       mm_log ("Bad flag list",ERROR);
  1885.       return NIL;
  1886.     }
  1887.                 /* copy the flag string w/o list construct */
  1888.     strncpy (LOCAL->buf,flag+i,(j = strlen (flag) - (2*i)));
  1889.     LOCAL->buf[j] = '\0';
  1890.     t = ucase (LOCAL->buf);    /* uppercase only from now on */
  1891.  
  1892.     while (*t) {        /* parse the flags */
  1893.       if (*t == '\\') {        /* system flag? */
  1894.     switch (*++t) {        /* dispatch based on first character */
  1895.     case 'S':        /* possible \Seen flag */
  1896.       if (t[1] == 'E' && t[2] == 'E' && t[3] == 'N') i = fSEEN;
  1897.       t += 4;        /* skip past flag name */
  1898.       break;
  1899.     case 'D':        /* possible \Deleted flag */
  1900.       if (t[1] == 'E' && t[2] == 'L' && t[3] == 'E' && t[4] == 'T' &&
  1901.           t[5] == 'E' && t[6] == 'D') i = fDELETED;
  1902.       t += 7;        /* skip past flag name */
  1903.       break;
  1904.     case 'F':        /* possible \Flagged flag */
  1905.       if (t[1] == 'L' && t[2] == 'A' && t[3] == 'G' && t[4] == 'G' &&
  1906.           t[5] == 'E' && t[6] == 'D') i = fFLAGGED;
  1907.       t += 7;        /* skip past flag name */
  1908.       break;
  1909.     case 'A':        /* possible \Answered flag */
  1910.       if (t[1] == 'N' && t[2] == 'S' && t[3] == 'W' && t[4] == 'E' &&
  1911.           t[5] == 'R' && t[6] == 'E' && t[7] == 'D') i = fANSWERED;
  1912.       t += 8;        /* skip past flag name */
  1913.       break;
  1914.     default:        /* unknown */
  1915.       i = 0;
  1916.       break;
  1917.     }
  1918.                 /* add flag to flags list */
  1919.     if (i && ((*t == '\0') || (*t++ == ' '))) f |= i;
  1920.     else {            /* bitch about bogus flag */
  1921.       mm_log ("Unknown system flag",ERROR);
  1922.       return NIL;
  1923.     }
  1924.       }
  1925.       else {            /* no user flags yet */
  1926.     mm_log ("Unknown flag",ERROR);
  1927.     return NIL;
  1928.       }
  1929.     }
  1930.   }
  1931.   return f;
  1932. }
  1933.  
  1934. /* Search support routines
  1935.  * Accepts: MAIL stream
  1936.  *        message number
  1937.  *        pointer to additional data
  1938.  * Returns: T if search matches, else NIL
  1939.  */
  1940.  
  1941.  
  1942. char bezerk_search_all (stream,msgno,d,n)
  1943.     MAILSTREAM *stream;
  1944.     long msgno;
  1945.     char *d;
  1946.     long n;
  1947. {
  1948.   return T;            /* ALL always succeeds */
  1949. }
  1950.  
  1951.  
  1952. char bezerk_search_answered (stream,msgno,d,n)
  1953.     MAILSTREAM *stream;
  1954.     long msgno;
  1955.     char *d;
  1956.     long n;
  1957. {
  1958.   return mail_elt (stream,msgno)->answered ? T : NIL;
  1959. }
  1960.  
  1961.  
  1962. char bezerk_search_deleted (stream,msgno,d,n)
  1963.     MAILSTREAM *stream;
  1964.     long msgno;
  1965.     char *d;
  1966.     long n;
  1967. {
  1968.   return mail_elt (stream,msgno)->deleted ? T : NIL;
  1969. }
  1970.  
  1971.  
  1972. char bezerk_search_flagged (stream,msgno,d,n)
  1973.     MAILSTREAM *stream;
  1974.     long msgno;
  1975.     char *d;
  1976.     long n;
  1977. {
  1978.   return mail_elt (stream,msgno)->flagged ? T : NIL;
  1979. }
  1980.  
  1981.  
  1982. char bezerk_search_keyword (stream,msgno,d,n)
  1983.     MAILSTREAM *stream;
  1984.     long msgno;
  1985.     char *d;
  1986.     long n;
  1987. {
  1988.   return NIL;            /* keywords not supported yet */
  1989. }
  1990.  
  1991.  
  1992. char bezerk_search_new (stream,msgno,d,n)
  1993.     MAILSTREAM *stream;
  1994.     long msgno;
  1995.     char *d;
  1996.     long n;
  1997. {
  1998.   MESSAGECACHE *elt = mail_elt (stream,msgno);
  1999.   return (elt->recent && !elt->seen) ? T : NIL;
  2000. }
  2001.  
  2002. char bezerk_search_old (stream,msgno,d,n)
  2003.     MAILSTREAM *stream;
  2004.     long msgno;
  2005.     char *d;
  2006.     long n;
  2007. {
  2008.   return mail_elt (stream,msgno)->recent ? NIL : T;
  2009. }
  2010.  
  2011.  
  2012. char bezerk_search_recent (stream,msgno,d,n)
  2013.     MAILSTREAM *stream;
  2014.     long msgno;
  2015.     char *d;
  2016.     long n;
  2017. {
  2018.   return mail_elt (stream,msgno)->recent ? T : NIL;
  2019. }
  2020.  
  2021.  
  2022. char bezerk_search_seen (stream,msgno,d,n)
  2023.     MAILSTREAM *stream;
  2024.     long msgno;
  2025.     char *d;
  2026.     long n;
  2027. {
  2028.   return mail_elt (stream,msgno)->seen ? T : NIL;
  2029. }
  2030.  
  2031.  
  2032. char bezerk_search_unanswered (stream,msgno,d,n)
  2033.     MAILSTREAM *stream;
  2034.     long msgno;
  2035.     char *d;
  2036.     long n;
  2037. {
  2038.   return mail_elt (stream,msgno)->answered ? NIL : T;
  2039. }
  2040.  
  2041.  
  2042. char bezerk_search_undeleted (stream,msgno,d,n)
  2043.     MAILSTREAM *stream;
  2044.     long msgno;
  2045.     char *d;
  2046.     long n;
  2047. {
  2048.   return mail_elt (stream,msgno)->deleted ? NIL : T;
  2049. }
  2050.  
  2051.  
  2052. char bezerk_search_unflagged (stream,msgno,d,n)
  2053.     MAILSTREAM *stream;
  2054.     long msgno;
  2055.     char *d;
  2056.     long n;
  2057. {
  2058.   return mail_elt (stream,msgno)->flagged ? NIL : T;
  2059. }
  2060.  
  2061.  
  2062. char bezerk_search_unkeyword (stream,msgno,d,n)
  2063.     MAILSTREAM *stream;
  2064.     long msgno;
  2065.     char *d;
  2066.     long n;
  2067. {
  2068.   return T;            /* keywords not supported yet */
  2069. }
  2070.  
  2071.  
  2072. char bezerk_search_unseen (stream,msgno,d,n)
  2073.     MAILSTREAM *stream;
  2074.     long msgno;
  2075.     char *d;
  2076.     long n;
  2077. {
  2078.   return mail_elt (stream,msgno)->seen ? NIL : T;
  2079. }
  2080.  
  2081. char bezerk_search_before (stream,msgno,d,n)
  2082.     MAILSTREAM *stream;
  2083.     long msgno;
  2084.     char *d;
  2085.     long n;
  2086. {
  2087.   MESSAGECACHE *elt = mail_elt (stream,msgno);
  2088.   return (char) ((long) ((elt->year << 9) + (elt->month << 5) + elt->day) < n);
  2089. }
  2090.  
  2091.  
  2092. char bezerk_search_on (stream,msgno,d,n)
  2093.     MAILSTREAM *stream;
  2094.     long msgno;
  2095.     char *d;
  2096.     long n;
  2097. {
  2098.   MESSAGECACHE *elt = mail_elt (stream,msgno);
  2099.   return (char) (((elt->year << 9) + (elt->month << 5) + elt->day) == n);
  2100. }
  2101.  
  2102.  
  2103. char bezerk_search_since (stream,msgno,d,n)
  2104.     MAILSTREAM *stream;
  2105.     long msgno;
  2106.     char *d;
  2107.     long n;
  2108. {
  2109.                 /* everybody interprets "since" as .GE. */
  2110.   MESSAGECACHE *elt = mail_elt (stream,msgno);
  2111.   return (char)((long) ((elt->year << 9) + (elt->month << 5) + elt->day) >= n);
  2112. }
  2113.  
  2114.  
  2115. char bezerk_search_body (stream,msgno,d,n)
  2116.     MAILSTREAM *stream;
  2117.     long msgno;
  2118.     char *d;
  2119.     long n;
  2120. {
  2121.   FILECACHE *m = LOCAL->msgs[msgno - 1];
  2122.   return search (m->body,m->bodysize,d,n);
  2123. }
  2124.  
  2125.  
  2126. char bezerk_search_subject (stream,msgno,d,n)
  2127.     MAILSTREAM *stream;
  2128.     long msgno;
  2129.     char *d;
  2130.     long n;
  2131. {
  2132.   char *s = bezerk_fetchstructure (stream,msgno,NIL)->subject;
  2133.   return s ? search (s,strlen (s),d,n) : NIL;
  2134. }
  2135.  
  2136.  
  2137. char bezerk_search_text (stream,msgno,d,n)
  2138.     MAILSTREAM *stream;
  2139.     long msgno;
  2140.     char *d;
  2141.     long n;
  2142. {
  2143.   FILECACHE *m = LOCAL->msgs[msgno - 1];
  2144.   return search (m->header,m->headersize,d,n) ||
  2145.     bezerk_search_body (stream,msgno,d,n);
  2146. }
  2147.  
  2148. char bezerk_search_bcc (stream,msgno,d,n)
  2149.     MAILSTREAM *stream;
  2150.     long msgno;
  2151.     char *d;
  2152.     long n;
  2153. {
  2154.   ADDRESS *a = bezerk_fetchstructure (stream,msgno,NIL)->bcc;
  2155.   LOCAL->buf[0] = '\0';        /* initially empty string */
  2156.                 /* get text for address */
  2157.   rfc822_write_address (LOCAL->buf,a);
  2158.   return search (LOCAL->buf,(long) strlen (LOCAL->buf),d,n);
  2159. }
  2160.  
  2161.  
  2162. char bezerk_search_cc (stream,msgno,d,n)
  2163.     MAILSTREAM *stream;
  2164.     long msgno;
  2165.     char *d;
  2166.     long n;
  2167. {
  2168.   ADDRESS *a = bezerk_fetchstructure (stream,msgno,NIL)->cc;
  2169.   LOCAL->buf[0] = '\0';        /* initially empty string */
  2170.                 /* get text for address */
  2171.   rfc822_write_address (LOCAL->buf,a);
  2172.   return search (LOCAL->buf,(long) strlen (LOCAL->buf),d,n);
  2173. }
  2174.  
  2175.  
  2176. char bezerk_search_from (stream,msgno,d,n)
  2177.     MAILSTREAM *stream;
  2178.     long msgno;
  2179.     char *d;
  2180.     long n;
  2181. {
  2182.   ADDRESS *a = bezerk_fetchstructure (stream,msgno,NIL)->from;
  2183.   LOCAL->buf[0] = '\0';        /* initially empty string */
  2184.                 /* get text for address */
  2185.   rfc822_write_address (LOCAL->buf,a);
  2186.   return search (LOCAL->buf,(long) strlen (LOCAL->buf),d,n);
  2187. }
  2188.  
  2189.  
  2190. char bezerk_search_to (stream,msgno,d,n)
  2191.     MAILSTREAM *stream;
  2192.     long msgno;
  2193.     char *d;
  2194.     long n;
  2195. {
  2196.   ADDRESS *a = bezerk_fetchstructure (stream,msgno,NIL)->to;
  2197.   LOCAL->buf[0] = '\0';        /* initially empty string */
  2198.                 /* get text for address */
  2199.   rfc822_write_address (LOCAL->buf,a);
  2200.   return search (LOCAL->buf,(long) strlen (LOCAL->buf),d,n);
  2201. }
  2202.  
  2203. /* Search parsers */
  2204.  
  2205.  
  2206. /* Parse a date
  2207.  * Accepts: function to return
  2208.  *        pointer to date integer to return
  2209.  * Returns: function to return
  2210.  */
  2211.  
  2212. search_t bezerk_search_date (f,n)
  2213.     search_t f;
  2214.     long *n;
  2215. {
  2216.   long i;
  2217.   char *s;
  2218.   MESSAGECACHE elt;
  2219.                 /* parse the date and return fn if OK */
  2220.   return (bezerk_search_string (f,&s,&i) && mail_parse_date (&elt,s) &&
  2221.       (*n = (elt.year << 9) + (elt.month << 5) + elt.day)) ? f : NIL;
  2222. }
  2223.  
  2224. /* Parse a flag
  2225.  * Accepts: function to return
  2226.  *        pointer to string to return
  2227.  * Returns: function to return
  2228.  */
  2229.  
  2230. search_t bezerk_search_flag (f,d)
  2231.     search_t f;
  2232.     char **d;
  2233. {
  2234.                 /* get a keyword, return if OK */
  2235.   return (*d = strtok (NIL," ")) ? f : NIL;
  2236. }
  2237.  
  2238.  
  2239. /* Parse a string
  2240.  * Accepts: function to return
  2241.  *        pointer to string to return
  2242.  *        pointer to string length to return
  2243.  * Returns: function to return
  2244.  */
  2245.  
  2246.  
  2247. search_t bezerk_search_string (f,d,n)
  2248.     search_t f;
  2249.     char **d;
  2250.     long *n;
  2251. {
  2252.   char *c = strtok (NIL,"");    /* remainder of criteria */
  2253.   if (c) {            /* better be an argument */
  2254.     switch (*c) {        /* see what the argument is */
  2255.     case '\0':            /* catch bogons */
  2256.     case ' ':
  2257.       return NIL;
  2258.     case '"':            /* quoted string */
  2259.       if (!(strchr (c+1,'"') && (*d = strtok (c,"\"")) && (*n = strlen (*d))))
  2260.     return NIL;
  2261.       break;
  2262.     case '{':            /* literal string */
  2263.       *n = strtol (c+1,&c,10);    /* get its length */
  2264.       if (*c++ != '}' || *c++ != '\015' || *c++ != '\012' ||
  2265.       *n > strlen (*d = c)) return NIL;
  2266.       c[*n] = '\255';        /* write new delimiter */
  2267.       strtok (c,"\255");    /* reset the strtok mechanism */
  2268.       break;
  2269.     default:            /* atomic string */
  2270.       *n = strlen (*d = strtok (c," "));
  2271.       break;
  2272.     }
  2273.     return f;
  2274.   }
  2275.   else return NIL;
  2276. }
  2277.