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

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