1 /* ========================================================================
2  * Copyright 1988-2008 University of Washington
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  *
11  * ========================================================================
12  */
13 
14 /*
15  * Program:	MX mail routines
16  *
17  * Author(s):	Mark Crispin
18  *		Networks and Distributed Computing
19  *		Computing & Communications
20  *		University of Washington
21  *		Administration Building, AG-44
22  *		Seattle, WA  98195
23  *		Internet: MRC@CAC.Washington.EDU
24  *
25  * Date:	3 May 1996
26  * Last Edited:	6 January 2008
27  */
28 
29 
30 #include <stdio.h>
31 #include <ctype.h>
32 #include <errno.h>
33 extern int errno;		/* just in case */
34 #include "mail.h"
35 #include "osdep.h"
36 #include <pwd.h>
37 #include <sys/stat.h>
38 #include <sys/time.h>
39 #include "misc.h"
40 #include "dummy.h"
41 #include "fdstring.h"
42 
43 /* Index file */
44 
45 #define MXINDEXNAME "/.mxindex"
46 #define MXINDEX(d,s) strcat (mx_file (d,s),MXINDEXNAME)
47 
48 
49 /* MX I/O stream local data */
50 
51 typedef struct mx_local {
52   int fd;			/* file descriptor of open index */
53   unsigned char *buf;		/* temporary buffer */
54   unsigned long buflen;		/* current size of temporary buffer */
55   unsigned long cachedtexts;	/* total size of all cached texts */
56   time_t scantime;		/* last time directory scanned */
57 } MXLOCAL;
58 
59 
60 /* Convenient access to local data */
61 
62 #define LOCAL ((MXLOCAL *) stream->local)
63 
64 
65 /* Function prototypes */
66 
67 DRIVER *mx_valid (char *name);
68 int mx_isvalid (char *name,char *tmp);
69 int mx_namevalid (char *name);
70 void *mx_parameters (long function,void *value);
71 long mx_dirfmttest (char *name);
72 void mx_scan (MAILSTREAM *stream,char *ref,char *pat,char *contents);
73 long mx_scan_contents (char *name,char *contents,unsigned long csiz,
74 		       unsigned long fsiz);
75 void mx_list (MAILSTREAM *stream,char *ref,char *pat);
76 void mx_lsub (MAILSTREAM *stream,char *ref,char *pat);
77 long mx_subscribe (MAILSTREAM *stream,char *mailbox);
78 long mx_unsubscribe (MAILSTREAM *stream,char *mailbox);
79 long mx_create (MAILSTREAM *stream,char *mailbox);
80 long mx_delete (MAILSTREAM *stream,char *mailbox);
81 long mx_rename (MAILSTREAM *stream,char *old,char *newname);
82 int mx_rename_work (char *src,size_t srcl,char *dst,size_t dstl,char *name);
83 MAILSTREAM *mx_open (MAILSTREAM *stream);
84 void mx_close (MAILSTREAM *stream,long options);
85 void mx_fast (MAILSTREAM *stream,char *sequence,long flags);
86 char *mx_fast_work (MAILSTREAM *stream,MESSAGECACHE *elt);
87 char *mx_header (MAILSTREAM *stream,unsigned long msgno,unsigned long *length,
88 		 long flags);
89 long mx_text (MAILSTREAM *stream,unsigned long msgno,STRING *bs,long flags);
90 void mx_flag (MAILSTREAM *stream,char *sequence,char *flag,long flags);
91 void mx_flagmsg (MAILSTREAM *stream,MESSAGECACHE *elt);
92 long mx_ping (MAILSTREAM *stream);
93 void mx_check (MAILSTREAM *stream);
94 long mx_expunge (MAILSTREAM *stream,char *sequence,long options);
95 long mx_copy (MAILSTREAM *stream,char *sequence,char *mailbox,
96 	      long options);
97 long mx_append (MAILSTREAM *stream,char *mailbox,append_t af,void *data);
98 long mx_append_msg (MAILSTREAM *stream,char *flags,MESSAGECACHE *elt,
99 		    STRING *st,SEARCHSET *set);
100 
101 int mx_select (struct direct *name);
102 int mx_numsort (const void *d1,const void *d2);
103 char *mx_file (char *dst,char *name);
104 long mx_lockindex (MAILSTREAM *stream);
105 void mx_unlockindex (MAILSTREAM *stream);
106 void mx_setdate (char *file,MESSAGECACHE *elt);
107 
108 
109 /* MX mail routines */
110 
111 
112 /* Driver dispatch used by MAIL */
113 
114 DRIVER mxdriver = {
115   "mx",				/* driver name */
116 				/* driver flags */
117   DR_MAIL|DR_LOCAL|DR_NOFAST|DR_CRLF|DR_LOCKING|DR_DIRFMT,
118   (DRIVER *) NIL,		/* next driver */
119   mx_valid,			/* mailbox is valid for us */
120   mx_parameters,		/* manipulate parameters */
121   mx_scan,			/* scan mailboxes */
122   mx_list,			/* find mailboxes */
123   mx_lsub,			/* find subscribed mailboxes */
124   mx_subscribe,			/* subscribe to mailbox */
125   mx_unsubscribe,		/* unsubscribe from mailbox */
126   mx_create,			/* create mailbox */
127   mx_delete,			/* delete mailbox */
128   mx_rename,			/* rename mailbox */
129   mail_status_default,		/* status of mailbox */
130   mx_open,			/* open mailbox */
131   mx_close,			/* close mailbox */
132   mx_fast,			/* fetch message "fast" attributes */
133   NIL,				/* fetch message flags */
134   NIL,				/* fetch overview */
135   NIL,				/* fetch message envelopes */
136   mx_header,			/* fetch message header only */
137   mx_text,			/* fetch message body only */
138   NIL,				/* fetch partial message test */
139   NIL,				/* unique identifier */
140   NIL,				/* message number */
141   mx_flag,			/* modify flags */
142   mx_flagmsg,			/* per-message modify flags */
143   NIL,				/* search for message based on criteria */
144   NIL,				/* sort messages */
145   NIL,				/* thread messages */
146   mx_ping,			/* ping mailbox to see if still alive */
147   mx_check,			/* check for new messages */
148   mx_expunge,			/* expunge deleted messages */
149   mx_copy,			/* copy messages to another mailbox */
150   mx_append,			/* append string message to mailbox */
151   NIL,				/* garbage collect stream */
152   NIL				/* renew stream */
153 };
154 
155 				/* prototype stream */
156 MAILSTREAM mxproto = {&mxdriver};
157 
158 /* MX mail validate mailbox
159  * Accepts: mailbox name
160  * Returns: our driver if name is valid, NIL otherwise
161  */
162 
mx_valid(char * name)163 DRIVER *mx_valid (char *name)
164 {
165   char tmp[MAILTMPLEN];
166   return mx_isvalid (name,tmp) ? &mxdriver : NIL;
167 }
168 
169 
170 /* MX mail test for valid mailbox
171  * Accepts: mailbox name
172  *	    temporary buffer to use
173  * Returns: T if valid, NIL otherwise with errno holding dir stat error
174  */
175 
mx_isvalid(char * name,char * tmp)176 int mx_isvalid (char *name,char *tmp)
177 {
178   struct stat sbuf;
179   errno = NIL;			/* zap error */
180   if ((strlen (name) <= NETMAXMBX) && *mx_file (tmp,name) &&
181       !stat (tmp,&sbuf) && ((sbuf.st_mode & S_IFMT) == S_IFDIR)) {
182 				/* name is directory; is it mx? */
183     if (!stat (MXINDEX (tmp,name),&sbuf) &&
184 	((sbuf.st_mode & S_IFMT) == S_IFREG)) return T;
185     errno = NIL;		/* directory but not mx */
186   }
187   else if (!compare_cstring (name,"INBOX")) errno = NIL;
188   return NIL;
189 }
190 
191 
192 /* MX mail test for valid mailbox
193  * Accepts: mailbox name
194  * Returns: T if valid, NIL otherwise
195  */
196 
mx_namevalid(char * name)197 int mx_namevalid (char *name)
198 {
199   char *s = (*name == '/') ? name + 1 : name;
200   while (s && *s) {		/* make sure valid name */
201     if (isdigit (*s)) s++;	/* digit, check this node further... */
202     else if (*s == '/') break;	/* all digit node, barf */
203 				/* non-digit, skip to next node or return */
204     else if (!((s = strchr (s+1,'/')) && *++s)) return T;
205   }
206   return NIL;			/* all numeric or empty node */
207 }
208 
209 /* MX manipulate driver parameters
210  * Accepts: function code
211  *	    function-dependent value
212  * Returns: function-dependent return value
213  */
214 
mx_parameters(long function,void * value)215 void *mx_parameters (long function,void *value)
216 {
217   void *ret = NIL;
218   switch ((int) function) {
219   case GET_INBOXPATH:
220     if (value) ret = mailboxfile ((char *) value,"~/INBOX");
221     break;
222   case GET_DIRFMTTEST:
223     ret = (void *) mx_dirfmttest;
224     break;
225   case GET_SCANCONTENTS:
226     ret = (void *) mx_scan_contents;
227     break;
228   }
229   return ret;
230 }
231 
232 
233 /* MX test for directory format internal node
234  * Accepts: candidate node name
235  * Returns: T if internal name, NIL otherwise
236  */
237 
mx_dirfmttest(char * name)238 long mx_dirfmttest (char *name)
239 {
240   int c;
241 				/* success if index name or all-numberic */
242   if (strcmp (name,MXINDEXNAME+1))
243     while ((c = *name++) != '\0') if (!isdigit (c)) return NIL;
244   return LONGT;
245 }
246 
247 /* MX scan mailboxes
248  * Accepts: mail stream
249  *	    reference
250  *	    pattern to search
251  *	    string to scan
252  */
253 
mx_scan(MAILSTREAM * stream,char * ref,char * pat,char * contents)254 void mx_scan (MAILSTREAM *stream,char *ref,char *pat,char *contents)
255 {
256   if (stream) dummy_scan (NIL,ref,pat,contents);
257 }
258 
259 
260 /* MX scan mailbox for contents
261  * Accepts: mailbox name
262  *	    desired contents
263  *	    contents size
264  *	    file size (ignored)
265  * Returns: NIL if contents not found, T if found
266  */
267 
mx_scan_contents(char * name,char * contents,unsigned long csiz,unsigned long fsiz)268 long mx_scan_contents (char *name,char *contents,unsigned long csiz,
269 			unsigned long fsiz)
270 {
271   long i,nfiles;
272   void *a;
273   char *s;
274   long ret = NIL;
275   size_t namelen = strlen (name);
276   struct stat sbuf;
277   struct direct **names = NIL;
278   if ((nfiles = scandir (name,&names,mx_select,mx_numsort)) > 0)
279     for (i = 0; i < nfiles; ++i) {
280       if (!ret) {
281 	sprintf (s = (char *) fs_get (namelen + strlen (names[i]->d_name) + 2),
282 		 "%s/%s",name,names[i]->d_name);
283 	if (!stat (s,&sbuf) && (csiz <= sbuf.st_size))
284 	  ret = dummy_scan_contents (s,contents,csiz,sbuf.st_size);
285 	fs_give ((void **) &s);
286       }
287       fs_give ((void **) &names[i]);
288     }
289 				/* free directory list */
290   if ((a = (void *) names) != NULL) fs_give ((void **) &a);
291   return ret;
292 }
293 
294 /* MX list mailboxes
295  * Accepts: mail stream
296  *	    reference
297  *	    pattern to search
298  */
299 
mx_list(MAILSTREAM * stream,char * ref,char * pat)300 void mx_list (MAILSTREAM *stream,char *ref,char *pat)
301 {
302   if (stream) dummy_list (NIL,ref,pat);
303 }
304 
305 
306 /* MX list subscribed mailboxes
307  * Accepts: mail stream
308  *	    reference
309  *	    pattern to search
310  */
311 
mx_lsub(MAILSTREAM * stream,char * ref,char * pat)312 void mx_lsub (MAILSTREAM *stream,char *ref,char *pat)
313 {
314   if (stream) dummy_lsub (NIL,ref,pat);
315 }
316 
317 /* MX mail subscribe to mailbox
318  * Accepts: mail stream
319  *	    mailbox to add to subscription list
320  * Returns: T on success, NIL on failure
321  */
322 
mx_subscribe(MAILSTREAM * stream,char * mailbox)323 long mx_subscribe (MAILSTREAM *stream,char *mailbox)
324 {
325   return sm_subscribe (mailbox);
326 }
327 
328 
329 /* MX mail unsubscribe to mailbox
330  * Accepts: mail stream
331  *	    mailbox to delete from subscription list
332  * Returns: T on success, NIL on failure
333  */
334 
mx_unsubscribe(MAILSTREAM * stream,char * mailbox)335 long mx_unsubscribe (MAILSTREAM *stream,char *mailbox)
336 {
337   return sm_unsubscribe (mailbox);
338 }
339 
340 /* MX mail create mailbox
341  * Accepts: mail stream
342  *	    mailbox name to create
343  * Returns: T on success, NIL on failure
344  */
345 
mx_create(MAILSTREAM * stream,char * mailbox)346 long mx_create (MAILSTREAM *stream,char *mailbox)
347 {
348   DRIVER *test;
349   int fd;
350   char *s,tmp[MAILTMPLEN];
351   int mask = umask (0);
352   long ret = NIL;
353   if (!mx_namevalid (mailbox))	/* validate name */
354     sprintf (tmp,"Can't create mailbox %.80s: invalid MX-format name",mailbox);
355 				/* must not already exist */
356   else if ((test = mail_valid (NIL,mailbox,NIL)) &&
357 	   strcmp (test->name,"dummy"))
358     sprintf (tmp,"Can't create mailbox %.80s: mailbox already exists",mailbox);
359 				/* create directory */
360   else if (!dummy_create_path (stream,MXINDEX (tmp,mailbox),
361 			       get_dir_protection (mailbox)))
362     sprintf (tmp,"Can't create mailbox %.80s: %s",mailbox,strerror (errno));
363   else {			/* success */
364 				/* set index protection */
365     set_mbx_protections (mailbox,tmp);
366 				/* tie off directory name */
367     *(s = strrchr (tmp,'/') + 1) = '\0';
368 				/* set directory protection */
369     set_mbx_protections (mailbox,tmp);
370     ret = LONGT;
371   }
372   umask (mask);			/* restore mask */
373   if (!ret) MM_LOG (tmp,ERROR);	/* some error */
374   return ret;
375 }
376 
377 /* MX mail delete mailbox
378  *	    mailbox name to delete
379  * Returns: T on success, NIL on failure
380  */
381 
mx_delete(MAILSTREAM * stream,char * mailbox)382 long mx_delete (MAILSTREAM *stream,char *mailbox)
383 {
384   DIR *dirp;
385   struct direct *d;
386   char *s;
387   char tmp[MAILTMPLEN];
388   if (!mx_isvalid (mailbox,tmp))
389     sprintf (tmp,"Can't delete mailbox %.80s: no such mailbox",mailbox);
390 				/* delete index */
391   else if (unlink (MXINDEX (tmp,mailbox)))
392     sprintf (tmp,"Can't delete mailbox %.80s index: %s",
393 	     mailbox,strerror (errno));
394   else {			/* get directory name */
395     *(s = strrchr (tmp,'/')) = '\0';
396     if ((dirp = opendir (tmp)) != NULL) {	/* open directory */
397       *s++ = '/';		/* restore delimiter */
398 				/* massacre messages */
399       while ((d = readdir (dirp)) != NULL) if (mx_select (d)) {
400 	strcpy (s,d->d_name);	/* make path */
401 	unlink (tmp);		/* sayonara */
402       }
403       closedir (dirp);		/* flush directory */
404       *(s = strrchr (tmp,'/')) = '\0';
405       if (rmdir (tmp)) {	/* try to remove the directory */
406 	sprintf (tmp,"Can't delete name %.80s: %s",mailbox,strerror (errno));
407 	MM_LOG (tmp,WARN);
408       }
409     }
410     return T;			/* always success */
411   }
412   MM_LOG (tmp,ERROR);		/* something failed */
413   return NIL;
414 }
415 
416 /* MX mail rename mailbox
417  * Accepts: MX mail stream
418  *	    old mailbox name
419  *	    new mailbox name
420  * Returns: T on success, NIL on failure
421  */
422 
mx_rename(MAILSTREAM * stream,char * old,char * newname)423 long mx_rename (MAILSTREAM *stream,char *old,char *newname)
424 {
425   char c,*s,tmp[MAILTMPLEN],tmp1[MAILTMPLEN];
426   struct stat sbuf;
427   if (!mx_isvalid (old,tmp))
428     sprintf (tmp,"Can't rename mailbox %.80s: no such mailbox",old);
429   else if (!mx_namevalid (newname))
430     sprintf (tmp,"Can't rename to mailbox %.80s: invalid MX-format name",
431 	     newname);
432 				/* new mailbox name must not be valid */
433   else if (mx_isvalid (newname,tmp))
434     sprintf (tmp,"Can't rename to mailbox %.80s: destination already exists",
435 	     newname);
436   else {
437     mx_file (tmp,old);		/* build old directory name */
438     mx_file (tmp1,newname);	/* and new directory name */
439 				/* easy if not INBOX */
440     if (compare_cstring (old,"INBOX")) {
441 				/* found superior to destination name? */
442       if ((s = strrchr (mx_file (tmp1,newname),'/')) != NULL) {
443 	c = *++s;	    /* remember first character of inferior */
444 	*s = '\0';		/* tie off to get just superior */
445 				/* name doesn't exist, create it */
446 	if ((stat (tmp1,&sbuf) || ((sbuf.st_mode & S_IFMT) != S_IFDIR)) &&
447 	    !dummy_create_path (stream,tmp1,get_dir_protection (newname)))
448 	  return NIL;
449 	*s = c;			/* restore full name */
450       }
451       if (!rename (tmp,tmp1)) return LONGT;
452     }
453 
454 				/* RFC 3501 requires this */
455     else if (dummy_create_path (stream,strcat (tmp1,"/"),
456 				get_dir_protection (newname))) {
457       void *a;
458       int i,n,lasterror;
459       struct direct **names = NIL;
460       size_t srcl = strlen (tmp);
461       size_t dstl = strlen (tmp1);
462 				/* rename each mx file to new directory */
463       for (i = lasterror = 0,n = scandir (tmp,&names,mx_select,mx_numsort);
464 	   i < n; ++i) {
465 	if (mx_rename_work (tmp,srcl,tmp1,dstl,names[i]->d_name))
466 	  lasterror = errno;
467 	fs_give ((void **) &names[i]);
468       }
469 				/* free directory list */
470       if ((a = (void *) names) != NULL) fs_give ((void **) &a);
471       if (lasterror || mx_rename_work (tmp,srcl,tmp1,dstl,MXINDEXNAME+1))
472 	errno = lasterror;
473       else return mx_create (NIL,"INBOX");
474     }
475     sprintf (tmp,"Can't rename mailbox %.80s to %.80s: %s",
476 	     old,newname,strerror (errno));
477   }
478   MM_LOG (tmp,ERROR);		/* something failed */
479   return NIL;
480 }
481 
482 
483 /* MX rename worker routine
484  * Accepts: source directory name
485  *	    source directory name length
486  *	    destination directory name
487  *	    destination directory name length
488  *	    name of node to move
489  * Returns: zero if success, non-zero if error
490  */
491 
mx_rename_work(char * src,size_t srcl,char * dst,size_t dstl,char * name)492 int mx_rename_work (char *src,size_t srcl,char *dst,size_t dstl,char *name)
493 {
494   int ret;
495   size_t len = strlen (name);
496   char *s = (char *) fs_get (srcl + len + 2);
497   char *d = (char *) fs_get (dstl + len + 1);
498   sprintf (s,"%s/%s",src,name);
499   sprintf (d,"%s%s",dst,name);
500   ret = rename (s,d);
501   fs_give ((void **) &s);
502   fs_give ((void **) &d);
503   return ret;
504 }
505 
506 /* MX mail open
507  * Accepts: stream to open
508  * Returns: stream on success, NIL on failure
509  */
510 
mx_open(MAILSTREAM * stream)511 MAILSTREAM *mx_open (MAILSTREAM *stream)
512 {
513   char tmp[MAILTMPLEN];
514 				/* return prototype for OP_PROTOTYPE call */
515   if (!stream) return user_flags (&mxproto);
516   if (stream->local) fatal ("mx recycle stream");
517   stream->local = fs_get (sizeof (MXLOCAL));
518 				/* note if an INBOX or not */
519   stream->inbox = !compare_cstring (stream->mailbox,"INBOX");
520   mx_file (tmp,stream->mailbox);/* get directory name */
521 				/* canonicalize mailbox name */
522   fs_give ((void **) &stream->mailbox);
523   stream->mailbox = cpystr (tmp);
524 				/* make temporary buffer */
525   LOCAL->buf = (char *) fs_get (CHUNKSIZE);
526   LOCAL->buflen = CHUNKSIZE - 1;
527   LOCAL->scantime = 0;		/* not scanned yet */
528   LOCAL->fd = -1;		/* no index yet */
529   LOCAL->cachedtexts = 0;	/* no cached texts */
530   stream->sequence++;		/* bump sequence number */
531 				/* parse mailbox */
532   stream->nmsgs = stream->recent = 0;
533   if (mx_ping (stream) && !(stream->nmsgs || stream->silent))
534     MM_LOG ("Mailbox is empty",(long) NIL);
535   stream->perm_seen = stream->perm_deleted = stream->perm_flagged =
536     stream->perm_answered = stream->perm_draft = stream->rdonly ? NIL : T;
537   stream->perm_user_flags = stream->rdonly ? NIL : 0xffffffff;
538   stream->kwd_create = (stream->user_flags[NUSERFLAGS-1] || stream->rdonly) ?
539     NIL : T;			/* can we create new user flags? */
540   return stream;		/* return stream to caller */
541 }
542 
543 /* MX mail close
544  * Accepts: MAIL stream
545  *	    close options
546  */
547 
mx_close(MAILSTREAM * stream,long options)548 void mx_close (MAILSTREAM *stream,long options)
549 {
550   if (LOCAL) {			/* only if a file is open */
551     int silent = stream->silent;
552     stream->silent = T;		/* note this stream is dying */
553     if (options & CL_EXPUNGE) mx_expunge (stream,NIL,NIL);
554 				/* free local scratch buffer */
555     if (LOCAL->buf) fs_give ((void **) &LOCAL->buf);
556 				/* nuke the local data */
557     fs_give ((void **) &stream->local);
558     stream->dtb = NIL;		/* log out the DTB */
559     stream->silent = silent;	/* reset silent state */
560   }
561 }
562 
563 /* MX mail fetch fast information
564  * Accepts: MAIL stream
565  *	    sequence
566  *	    option flags
567  */
568 
mx_fast(MAILSTREAM * stream,char * sequence,long flags)569 void mx_fast (MAILSTREAM *stream,char *sequence,long flags)
570 {
571   unsigned long i;
572   MESSAGECACHE *elt;
573   if (stream && LOCAL &&
574       ((flags & FT_UID) ? mail_uid_sequence (stream,sequence) :
575        mail_sequence (stream,sequence)))
576     for (i = 1; i <= stream->nmsgs; i++)
577       if ((elt = mail_elt (stream,i))->sequence) mx_fast_work (stream,elt);
578 }
579 
580 
581 /* MX mail fetch fast information
582  * Accepts: MAIL stream
583  *	    message cache element
584  * Returns: name of message file
585  */
586 
mx_fast_work(MAILSTREAM * stream,MESSAGECACHE * elt)587 char *mx_fast_work (MAILSTREAM *stream,MESSAGECACHE *elt)
588 {
589   struct stat sbuf;
590   struct tm *tm;
591 				/* build message file name */
592   sprintf (LOCAL->buf,"%s/%lu",stream->mailbox,elt->private.uid);
593 				/* have size yet? */
594   if (!elt->rfc822_size && !stat (LOCAL->buf,&sbuf)) {
595 				/* make plausible IMAPish date string */
596     tm = gmtime (&sbuf.st_mtime);
597     elt->day = tm->tm_mday; elt->month = tm->tm_mon + 1;
598     elt->year = tm->tm_year + 1900 - BASEYEAR;
599     elt->hours = tm->tm_hour; elt->minutes = tm->tm_min;
600     elt->seconds = tm->tm_sec;
601     elt->zhours = 0; elt->zminutes = 0; elt->zoccident = 0;
602     elt->rfc822_size = sbuf.st_size;
603   }
604   return (char *) LOCAL->buf;	/* return file name */
605 }
606 
607 /* MX mail fetch message header
608  * Accepts: MAIL stream
609  *	    message # to fetch
610  *	    pointer to returned header text length
611  *	    option flags
612  * Returns: message header in RFC822 format
613  */
614 
mx_header(MAILSTREAM * stream,unsigned long msgno,unsigned long * length,long flags)615 char *mx_header (MAILSTREAM *stream,unsigned long msgno,unsigned long *length,
616 		 long flags)
617 {
618   unsigned long i;
619   int fd;
620   MESSAGECACHE *elt;
621   *length = 0;			/* default to empty */
622   if (flags & FT_UID) return "";/* UID call "impossible" */
623   elt = mail_elt (stream,msgno);/* get elt */
624   if (!elt->private.msg.header.text.data) {
625 				/* purge cache if too big */
626     if (LOCAL->cachedtexts > max (stream->nmsgs * 4096,2097152)) {
627       mail_gc (stream,GC_TEXTS);/* just can't keep that much */
628       LOCAL->cachedtexts = 0;
629     }
630     if ((fd = open (mx_fast_work (stream,elt),O_RDONLY,NIL)) < 0) return "";
631 				/* is buffer big enough? */
632     if (elt->rfc822_size > LOCAL->buflen) {
633       fs_give ((void **) &LOCAL->buf);
634       LOCAL->buf = (char *) fs_get ((LOCAL->buflen = elt->rfc822_size) + 1);
635     }
636 				/* slurp message */
637     read (fd,LOCAL->buf,elt->rfc822_size);
638 				/* tie off file */
639     LOCAL->buf[elt->rfc822_size] = '\0';
640     close (fd);			/* flush message file */
641 				/* find end of header */
642     if (elt->rfc822_size < 4) i = 0;
643     else for (i = 4; (i < elt->rfc822_size) &&
644 	      !((LOCAL->buf[i - 4] == '\015') &&
645 		(LOCAL->buf[i - 3] == '\012') &&
646 		(LOCAL->buf[i - 2] == '\015') &&
647 		(LOCAL->buf[i - 1] == '\012')); i++);
648 				/* copy header */
649     cpytxt (&elt->private.msg.header.text,LOCAL->buf,i);
650     cpytxt (&elt->private.msg.text.text,LOCAL->buf+i,elt->rfc822_size - i);
651 				/* add to cached size */
652     LOCAL->cachedtexts += elt->rfc822_size;
653   }
654   *length = elt->private.msg.header.text.size;
655   return (char *) elt->private.msg.header.text.data;
656 }
657 
658 /* MX mail fetch message text (body only)
659  * Accepts: MAIL stream
660  *	    message # to fetch
661  *	    pointer to returned stringstruct
662  *	    option flags
663  * Returns: T on success, NIL on failure
664  */
665 
mx_text(MAILSTREAM * stream,unsigned long msgno,STRING * bs,long flags)666 long mx_text (MAILSTREAM *stream,unsigned long msgno,STRING *bs,long flags)
667 {
668   unsigned long i;
669   MESSAGECACHE *elt;
670 				/* UID call "impossible" */
671   if (flags & FT_UID) return NIL;
672   elt = mail_elt (stream,msgno);
673 				/* snarf message if don't have it yet */
674   if (!elt->private.msg.text.text.data) {
675     mx_header (stream,msgno,&i,flags);
676     if (!elt->private.msg.text.text.data) return NIL;
677   }
678 				/* mark as seen */
679   if (!(flags & FT_PEEK) && mx_lockindex (stream)) {
680     elt->seen = T;
681     mx_unlockindex (stream);
682     MM_FLAGS (stream,msgno);
683   }
684   INIT (bs,mail_string,elt->private.msg.text.text.data,
685 	elt->private.msg.text.text.size);
686   return T;
687 }
688 
689 /* MX mail modify flags
690  * Accepts: MAIL stream
691  *	    sequence
692  *	    flag(s)
693  *	    option flags
694  */
695 
mx_flag(MAILSTREAM * stream,char * sequence,char * flag,long flags)696 void mx_flag (MAILSTREAM *stream,char *sequence,char *flag,long flags)
697 {
698   mx_unlockindex (stream);	/* finished with index */
699 }
700 
701 
702 /* MX per-message modify flags
703  * Accepts: MAIL stream
704  *	    message cache element
705  */
706 
mx_flagmsg(MAILSTREAM * stream,MESSAGECACHE * elt)707 void mx_flagmsg (MAILSTREAM *stream,MESSAGECACHE *elt)
708 {
709   mx_lockindex (stream);	/* lock index if not already locked */
710 }
711 
712 /* MX mail ping mailbox
713  * Accepts: MAIL stream
714  * Returns: T if stream alive, else NIL
715  */
716 
mx_ping(MAILSTREAM * stream)717 long mx_ping (MAILSTREAM *stream)
718 {
719   MAILSTREAM *sysibx = NIL;
720   MESSAGECACHE *elt,*selt;
721   struct stat sbuf;
722   char *s,tmp[MAILTMPLEN];
723   int fd;
724   unsigned long i,j,r,old;
725   long nmsgs = stream->nmsgs;
726   long recent = stream->recent;
727   int silent = stream->silent;
728   if (stat (stream->mailbox,&sbuf)) return NIL;
729   stream->silent = T;		/* don't pass up exists events yet */
730   if (sbuf.st_ctime != LOCAL->scantime) {
731     struct direct **names = NIL;
732     long nfiles = scandir (stream->mailbox,&names,mx_select,mx_numsort);
733     if (nfiles < 0) nfiles = 0;	/* in case error */
734     old = stream->uid_last;
735 				/* note scanned now */
736     LOCAL->scantime = sbuf.st_ctime;
737 				/* scan directory */
738     for (i = 0; i < nfiles; ++i) {
739 				/* if newly seen, add to list */
740       if ((j = atoi (names[i]->d_name)) > old) {
741 				/* swell the cache */
742 	mail_exists (stream,++nmsgs);
743 	stream->uid_last = (elt = mail_elt (stream,nmsgs))->private.uid = j;
744 	elt->valid = T;		/* note valid flags */
745 	if (old) {		/* other than the first pass? */
746 	  elt->recent = T;	/* yup, mark as recent */
747 	  recent++;		/* bump recent count */
748 	}
749       }
750       fs_give ((void **) &names[i]);
751     }
752 				/* free directory */
753     if ((s = (void *) names) != NULL) fs_give ((void **) &s);
754   }
755   stream->nmsgs = nmsgs;	/* don't upset mail_uid() */
756 
757 				/* if INBOX, snarf from system INBOX  */
758   if (mx_lockindex (stream) && stream->inbox &&
759       !strcmp (sysinbox (),stream->mailbox)) {
760     old = stream->uid_last;
761     MM_CRITICAL (stream);	/* go critical */
762 				/* see if anything in system inbox */
763     if (!stat (sysinbox (),&sbuf) && sbuf.st_size &&
764 	(sysibx = mail_open (sysibx,sysinbox (),OP_SILENT)) &&
765 	!sysibx->rdonly && (r = sysibx->nmsgs)) {
766       for (i = 1; i <= r; ++i) {/* for each message in sysinbox mailbox */
767 				/* build file name we will use */
768 	sprintf (LOCAL->buf,"%s/%lu",stream->mailbox,++old);
769 				/* snarf message from Berkeley mailbox */
770 	selt = mail_elt (sysibx,i);
771 	if (((fd = open (LOCAL->buf,O_WRONLY|O_CREAT|O_EXCL,
772 			 (long) mail_parameters (NIL,GET_MBXPROTECTION,NIL)))
773 	     >= 0) &&
774 	    (s = mail_fetchheader_full (sysibx,i,NIL,&j,FT_PEEK)) &&
775 	    (write (fd,s,j) == j) &&
776 	    (s = mail_fetchtext_full (sysibx,i,&j,FT_PEEK)) &&
777 	    (write (fd,s,j) == j) && !fsync (fd) && !close (fd)) {
778 				/* swell the cache */
779 	  mail_exists (stream,++nmsgs);
780 	  stream->uid_last =	/* create new elt, note its file number */
781 	    (elt = mail_elt (stream,nmsgs))->private.uid = old;
782 	  recent++;		/* bump recent count */
783 				/* set up initial flags and date */
784 	  elt->valid = elt->recent = T;
785 	  elt->seen = selt->seen;
786 	  elt->deleted = selt->deleted;
787 	  elt->flagged = selt->flagged;
788 	  elt->answered = selt->answered;
789 	  elt->draft = selt->draft;
790 	  elt->day = selt->day;elt->month = selt->month;elt->year = selt->year;
791 	  elt->hours = selt->hours;elt->minutes = selt->minutes;
792 	  elt->seconds = selt->seconds;
793 	  elt->zhours = selt->zhours; elt->zminutes = selt->zminutes;
794 	  elt->zoccident = selt->zoccident;
795 	  mx_setdate (LOCAL->buf,elt);
796 	  sprintf (tmp,"%lu",i);/* delete it from the sysinbox */
797 	  mail_flag (sysibx,tmp,"\\Deleted",ST_SET);
798 	}
799 	else {			/* failed to snarf */
800 	  if (fd) {		/* did it ever get opened? */
801 	    close (fd);		/* close descriptor */
802 	    unlink (LOCAL->buf);/* flush this file */
803 	  }
804 	  sprintf (tmp,"Message copy to MX mailbox failed: %.80s",
805 		   strerror (errno));
806 	  MM_LOG (tmp,ERROR);
807 	  r = 0;		/* stop the snarf in its tracks */
808 	}
809       }
810 				/* update scan time */
811       if (!stat (stream->mailbox,&sbuf)) LOCAL->scantime = sbuf.st_ctime;
812       mail_expunge (sysibx);	/* now expunge all those messages */
813     }
814     if (sysibx) mail_close (sysibx);
815     MM_NOCRITICAL (stream);	/* release critical */
816   }
817   mx_unlockindex (stream);	/* done with index */
818   stream->silent = silent;	/* can pass up events now */
819   mail_exists (stream,nmsgs);	/* notify upper level of mailbox size */
820   mail_recent (stream,recent);
821   return T;			/* return that we are alive */
822 }
823 
824 /* MX mail check mailbox
825  * Accepts: MAIL stream
826  */
827 
mx_check(MAILSTREAM * stream)828 void mx_check (MAILSTREAM *stream)
829 {
830   if (mx_ping (stream)) MM_LOG ("Check completed",(long) NIL);
831 }
832 
833 
834 /* MX mail expunge mailbox
835  * Accepts: MAIL stream
836  *	    sequence to expunge if non-NIL
837  *	    expunge options
838  * Returns: T, always
839  */
840 
mx_expunge(MAILSTREAM * stream,char * sequence,long options)841 long mx_expunge (MAILSTREAM *stream,char *sequence,long options)
842 {
843   long ret;
844   MESSAGECACHE *elt;
845   unsigned long i = 1;
846   unsigned long n = 0;
847   unsigned long recent = stream->recent;
848   if ((ret = (sequence ? ((options & EX_UID) ?
849 			 mail_uid_sequence (stream,sequence) :
850 			 mail_sequence (stream,sequence)) : LONGT) != 0L) &&
851       mx_lockindex (stream)) {	/* lock the index */
852     MM_CRITICAL (stream);	/* go critical */
853     while (i <= stream->nmsgs) {/* for each message */
854       elt = mail_elt (stream,i);/* if deleted, need to trash it */
855       if (elt->deleted && (sequence ? elt->sequence : T)) {
856 	sprintf (LOCAL->buf,"%s/%lu",stream->mailbox,elt->private.uid);
857 	if (unlink (LOCAL->buf)) {/* try to delete the message */
858 	  sprintf (LOCAL->buf,"Expunge of message %lu failed, aborted: %s",i,
859 		   strerror (errno));
860 	  MM_LOG (LOCAL->buf,(long) NIL);
861 	  break;
862 	}
863 				/* note uncached */
864 	LOCAL->cachedtexts -= ((elt->private.msg.header.text.data ?
865 				elt->private.msg.header.text.size : 0) +
866 			       (elt->private.msg.text.text.data ?
867 				elt->private.msg.text.text.size : 0));
868 	mail_gc_msg (&elt->private.msg,GC_ENV | GC_TEXTS);
869 	if(elt->recent)--recent;/* if recent, note one less recent message */
870 	mail_expunged(stream,i);/* notify upper levels */
871 	n++;			/* count up one more expunged message */
872       }
873       else i++;			/* otherwise try next message */
874     }
875     if (n) {			/* output the news if any expunged */
876       sprintf (LOCAL->buf,"Expunged %lu messages",n);
877       MM_LOG (LOCAL->buf,(long) NIL);
878     }
879     else MM_LOG ("No messages deleted, so no update needed",(long) NIL);
880     MM_NOCRITICAL (stream);	/* release critical */
881     mx_unlockindex (stream);	/* finished with index */
882 				/* notify upper level of new mailbox size */
883     mail_exists (stream,stream->nmsgs);
884     mail_recent (stream,recent);
885   }
886   return ret;
887 }
888 
889 /* MX mail copy message(s)
890  * Accepts: MAIL stream
891  *	    sequence
892  *	    destination mailbox
893  *	    copy options
894  * Returns: T if copy successful, else NIL
895  */
896 
mx_copy(MAILSTREAM * stream,char * sequence,char * mailbox,long options)897 long mx_copy (MAILSTREAM *stream,char *sequence,char *mailbox,long options)
898 {
899   FDDATA d;
900   STRING st;
901   MESSAGECACHE *elt;
902   MAILSTREAM *astream;
903   struct stat sbuf;
904   int fd;
905   unsigned long i,j,uid,uidv;
906   char *t,tmp[MAILTMPLEN];
907   long ret;
908   mailproxycopy_t pc =
909     (mailproxycopy_t) mail_parameters (stream,GET_MAILPROXYCOPY,NIL);
910 				/* make sure valid mailbox */
911   if (!mx_valid (mailbox)) switch (errno) {
912   case NIL:			/* no error in stat() */
913     if (pc) return (*pc) (stream,sequence,mailbox,options);
914     sprintf (LOCAL->buf,"Not a MX-format mailbox: %.80s",mailbox);
915     MM_LOG (LOCAL->buf,ERROR);
916     return NIL;
917   default:			/* some stat() error */
918     MM_NOTIFY (stream,"[TRYCREATE] Must create mailbox before copy",NIL);
919     return NIL;
920   }
921 				/* copy the messages */
922   if (!(ret = ((options & CP_UID) ? mail_uid_sequence (stream,sequence) :
923 	       mail_sequence (stream,sequence))));
924 				/* acquire stream to append to */
925   else if (!(astream = mail_open (NIL,mailbox,OP_SILENT))) {
926     MM_LOG ("Can't open copy mailbox",ERROR);
927     ret = NIL;
928   }
929   else {
930     MM_CRITICAL (stream);	/* go critical */
931     if (!(ret = mx_lockindex (astream)))
932       MM_LOG ("Message copy failed: unable to lock index",ERROR);
933     else {
934 
935       copyuid_t cu = (copyuid_t) mail_parameters (NIL,GET_COPYUID,NIL);
936       SEARCHSET *source = cu ? mail_newsearchset () : NIL;
937       SEARCHSET *dest = cu ? mail_newsearchset () : NIL;
938       for (i = 1,uid = uidv = 0; ret && (i <= stream->nmsgs); i++)
939       if ((elt = mail_elt (stream,i))->sequence) {
940 	if ((ret = ((fd = open (mx_fast_work (stream,elt),O_RDONLY,NIL))
941 		   >= 0)) != 0L) {
942 	  fstat (fd,&sbuf);	/* get size of message */
943 	  d.fd = fd;		/* set up file descriptor */
944 	  d.pos = 0;		/* start of file */
945 	  d.chunk = LOCAL->buf;
946 	  d.chunksize = CHUNKSIZE;
947 	  INIT (&st,fd_string,&d,sbuf.st_size);
948 				/* init flag string */
949 	  tmp[0] = tmp[1] = '\0';
950 	  if ((j = elt->user_flags) != 0L) do
951 	    if ((t = stream->user_flags[find_rightmost_bit (&j)]) != NULL)
952 	      strcat (strcat (tmp," "),t);
953 	  while (j);
954 	  if (elt->seen) strcat (tmp," \\Seen");
955 	  if (elt->deleted) strcat (tmp," \\Deleted");
956 	  if (elt->flagged) strcat (tmp," \\Flagged");
957 	  if (elt->answered) strcat (tmp," \\Answered");
958 	  if (elt->draft) strcat (tmp," \\Draft");
959 	  tmp[0] = '(';		/* open list */
960 	  strcat (tmp,")");	/* close list */
961 	  if ((ret = mx_append_msg (astream,tmp,elt,&st,dest)) != 0L) {
962 				/* add to source set if needed */
963 	    if (source) mail_append_set (source,mail_uid (stream,i));
964 				/* delete if doing a move */
965 	    if (options & CP_MOVE) elt->deleted = T;
966 	  }
967 	}
968       }
969 				/* return sets if doing COPYUID */
970       if (cu && ret) (*cu) (stream,mailbox,astream->uid_validity,source,dest);
971       else {			/* flush any sets we may have built */
972 	mail_free_searchset (&source);
973 	mail_free_searchset (&dest);
974       }
975       mx_unlockindex (astream);	/* unlock index */
976     }
977     MM_NOCRITICAL (stream);
978     mail_close (astream);	/* finished with append stream */
979   }
980   return ret;			/* return success */
981 }
982 
983 /* MX mail append message from stringstruct
984  * Accepts: MAIL stream
985  *	    destination mailbox
986  *	    append callback
987  *	    data for callback
988  * Returns: T if append successful, else NIL
989  */
990 
mx_append(MAILSTREAM * stream,char * mailbox,append_t af,void * data)991 long mx_append (MAILSTREAM *stream,char *mailbox,append_t af,void *data)
992 {
993   MESSAGECACHE elt;
994   MAILSTREAM *astream;
995   char *flags,*date,tmp[MAILTMPLEN];
996   STRING *message;
997   long ret = LONGT;
998 				/* default stream to prototype */
999   if (!stream) stream = user_flags (&mxproto);
1000 				/* N.B.: can't use LOCAL->buf for tmp */
1001 				/* make sure valid mailbox */
1002   if (!mx_isvalid (mailbox,tmp)) switch (errno) {
1003   case ENOENT:			/* no such file? */
1004     if (!compare_cstring (mailbox,"INBOX")) mx_create (NIL,"INBOX");
1005     else {
1006       MM_NOTIFY (stream,"[TRYCREATE] Must create mailbox before append",NIL);
1007       return NIL;
1008     }
1009 				/* falls through */
1010   case 0:			/* merely empty file? */
1011     break;
1012   case EINVAL:
1013     sprintf (tmp,"Invalid MX-format mailbox name: %.80s",mailbox);
1014     MM_LOG (tmp,ERROR);
1015     return NIL;
1016   default:
1017     sprintf (tmp,"Not a MX-format mailbox: %.80s",mailbox);
1018     MM_LOG (tmp,ERROR);
1019     return NIL;
1020   }
1021 
1022 				/* get first message */
1023   if (!MM_APPEND (af) (stream,data,&flags,&date,&message)) return NIL;
1024   if (!(astream = mail_open (NIL,mailbox,OP_SILENT))) {
1025     MM_LOG ("Can't open append mailbox",ERROR);
1026     return NIL;
1027   }
1028   MM_CRITICAL (astream);	/* go critical */
1029 				/* lock the index */
1030   if (!(ret = mx_lockindex (astream)))
1031     MM_LOG ("Message append failed: unable to lock index",ERROR);
1032   else {
1033     appenduid_t au = (appenduid_t) mail_parameters (NIL,GET_APPENDUID,NIL);
1034     SEARCHSET *dst = au ? mail_newsearchset () : NIL;
1035     do {
1036 				/* guard against zero-length */
1037       if (!(ret = SIZE (message)))
1038 	MM_LOG ("Append of zero-length message",ERROR);
1039       else if (date && !(ret = mail_parse_date (&elt,date))) {
1040 	sprintf (tmp,"Bad date in append: %.80s",date);
1041 	MM_LOG (tmp,ERROR);
1042       }
1043       else ret = mx_append_msg (astream,flags,date ? &elt : NIL,message,dst)&&
1044 	     MM_APPEND (af) (stream,data,&flags,&date,&message);
1045     } while (ret && message);
1046 				/* return sets if doing APPENDUID */
1047     if (au && ret) (*au) (mailbox,astream->uid_validity,dst);
1048     else mail_free_searchset (&dst);
1049     mx_unlockindex (astream);	/* unlock index */
1050   }
1051   MM_NOCRITICAL (astream);	/* release critical */
1052   mail_close (astream);
1053   return ret;
1054 }
1055 
1056 /* MX mail append single message
1057  * Accepts: MAIL stream
1058  *	    flags for new message if non-NIL
1059  *	    elt with source date if non-NIL
1060  *	    stringstruct of message text
1061  *	    searchset to place UID
1062  * Returns: T if success, NIL if failure
1063  */
1064 
mx_append_msg(MAILSTREAM * stream,char * flags,MESSAGECACHE * elt,STRING * st,SEARCHSET * set)1065 long mx_append_msg (MAILSTREAM *stream,char *flags,MESSAGECACHE *elt,
1066 		    STRING *st,SEARCHSET *set)
1067 {
1068   char tmp[MAILTMPLEN];
1069   int fd;
1070   unsigned long uf;
1071   long f = mail_parse_flags (stream,flags,&uf);
1072 				/* make message file name */
1073   sprintf (tmp,"%s/%lu",stream->mailbox,++stream->uid_last);
1074   if ((fd = open (tmp,O_WRONLY|O_CREAT|O_EXCL,
1075 		  (long) mail_parameters (NIL,GET_MBXPROTECTION,NIL))) < 0) {
1076     sprintf (tmp,"Can't create append message: %s",strerror (errno));
1077     MM_LOG (tmp,ERROR);
1078     return NIL;
1079   }
1080   while (SIZE (st)) {		/* copy the file */
1081     if (st->cursize && (write (fd,st->curpos,st->cursize) < 0)) {
1082       unlink (tmp);		/* delete file */
1083       close (fd);		/* close the file */
1084       sprintf (tmp,"Message append failed: %s",strerror (errno));
1085       MM_LOG (tmp,ERROR);
1086       return NIL;
1087     }
1088     SETPOS (st,GETPOS (st) + st->cursize);
1089   }
1090   close (fd);			/* close the file */
1091   if (elt) mx_setdate (tmp,elt);/* set file date */
1092 				/* swell the cache */
1093   mail_exists (stream,++stream->nmsgs);
1094 				/* copy flags */
1095   mail_append_set (set,(elt = mail_elt (stream,stream->nmsgs))->private.uid =
1096 		   stream->uid_last);
1097   if (f&fSEEN) elt->seen = T;
1098   if (f&fDELETED) elt->deleted = T;
1099   if (f&fFLAGGED) elt->flagged = T;
1100   if (f&fANSWERED) elt->answered = T;
1101   if (f&fDRAFT) elt->draft = T;
1102   elt->user_flags |= uf;
1103   return LONGT;
1104 }
1105 
1106 /* Internal routines */
1107 
1108 
1109 /* MX file name selection test
1110  * Accepts: candidate directory entry
1111  * Returns: T to use file name, NIL to skip it
1112  */
1113 
mx_select(struct direct * name)1114 int mx_select (struct direct *name)
1115 {
1116   char c;
1117   char *s = name->d_name;
1118   while ((c = *s++) != '\0') if (!isdigit (c)) return NIL;
1119   return T;
1120 }
1121 
1122 
1123 /* MX file name comparison
1124  * Accepts: first candidate directory entry
1125  *	    second candidate directory entry
1126  * Returns: negative if d1 < d2, 0 if d1 == d2, positive if d1 > d2
1127  */
1128 
mx_numsort(const void * d1,const void * d2)1129 int mx_numsort (const void *d1,const void *d2)
1130 {
1131   return atoi ((*(struct direct **) d1)->d_name) -
1132     atoi ((*(struct direct **) d2)->d_name);
1133 }
1134 
1135 
1136 /* MX mail build file name
1137  * Accepts: destination string
1138  *          source
1139  * Returns: destination
1140  */
1141 
mx_file(char * dst,char * name)1142 char *mx_file (char *dst,char *name)
1143 {
1144   char *s;
1145 				/* empty string if mailboxfile fails */
1146   if (!mailboxfile (dst,name)) *dst = '\0';
1147 				/* driver-selected INBOX  */
1148   else if (!*dst) mailboxfile (dst,"~/INBOX");
1149 				/* tie off unnecessary trailing / */
1150   else if ((s = strrchr (dst,'/')) && !s[1]) *s = '\0';
1151   return dst;
1152 }
1153 
1154 /* MX read and lock index
1155  * Accepts: MAIL stream
1156  * Returns: T if success, NIL if failure
1157  */
1158 
mx_lockindex(MAILSTREAM * stream)1159 long mx_lockindex (MAILSTREAM *stream)
1160 {
1161   unsigned long uf,sf,uid;
1162   int k = 0;
1163   unsigned long msgno = 1;
1164   struct stat sbuf;
1165   char *s,*t,*idx,tmp[2*MAILTMPLEN];
1166   MESSAGECACHE *elt;
1167   blocknotify_t bn = (blocknotify_t) mail_parameters (NIL,GET_BLOCKNOTIFY,NIL);
1168   if ((LOCAL->fd < 0) &&	/* get index file, no-op if already have it */
1169       (LOCAL->fd = open (strcat (strcpy (tmp,stream->mailbox),MXINDEXNAME),
1170 			 O_RDWR|O_CREAT,
1171 			 (long) mail_parameters (NIL,GET_MBXPROTECTION,NIL)))
1172       >= 0) {
1173     (*bn) (BLOCK_FILELOCK,NIL);
1174     flock (LOCAL->fd,LOCK_EX);	/* get exclusive lock */
1175     (*bn) (BLOCK_NONE,NIL);
1176     fstat (LOCAL->fd,&sbuf);	/* get size of index */
1177 				/* slurp index */
1178     read (LOCAL->fd,s = idx = (char *) fs_get (sbuf.st_size + 1),sbuf.st_size);
1179     idx[sbuf.st_size] = '\0';	/* tie off index */
1180 				/* parse index */
1181     if (sbuf.st_size) while (s && *s) switch (*s) {
1182     case 'V':			/* UID validity record */
1183       stream->uid_validity = strtoul (s+1,&s,16);
1184       break;
1185     case 'L':			/* UID last record */
1186       stream->uid_last = strtoul (s+1,&s,16);
1187       break;
1188     case 'K':			/* keyword */
1189 				/* find end of keyword */
1190       if ((s = strchr (t = ++s,'\n')) != NULL) {
1191 	*s++ = '\0';		/* tie off keyword */
1192 				/* copy keyword */
1193 	if ((k < NUSERFLAGS) && !stream->user_flags[k] &&
1194 	    (strlen (t) <= MAXUSERFLAG)) stream->user_flags[k] = cpystr (t);
1195 	k++;			/* one more keyword */
1196       }
1197       break;
1198 
1199     case 'M':			/* message status record */
1200       uid = strtoul (s+1,&s,16);/* get UID for this message */
1201       if (*s == ';') {		/* get user flags */
1202 	uf = strtoul (s+1,&s,16);
1203 	if (*s == '.') {	/* get system flags */
1204 	  sf = strtoul (s+1,&s,16);
1205 	  while ((msgno <= stream->nmsgs) && (mail_uid (stream,msgno) < uid))
1206 	    msgno++;		/* find message number for this UID */
1207 	  if ((msgno <= stream->nmsgs) && (mail_uid (stream,msgno) == uid)) {
1208 	    (elt = mail_elt (stream,msgno))->valid = T;
1209 	    elt->user_flags=uf; /* set user and system flags in elt */
1210 	    if (sf & fSEEN) elt->seen = T;
1211 	    if (sf & fDELETED) elt->deleted = T;
1212 	    if (sf & fFLAGGED) elt->flagged = T;
1213 	    if (sf & fANSWERED) elt->answered = T;
1214 	    if (sf & fDRAFT) elt->draft = T;
1215 	  }
1216 	  break;
1217 	}
1218       }
1219     default:			/* bad news */
1220       sprintf (tmp,"Error in index: %.80s",s);
1221       MM_LOG (tmp,ERROR);
1222       *s = NIL;			/* ignore remainder of index */
1223     }
1224     else {			/* new index */
1225       stream->uid_validity = time (0);
1226       user_flags (stream);	/* init stream with default user flags */
1227     }
1228     fs_give ((void **) &idx);	/* flush index */
1229   }
1230   return (LOCAL->fd >= 0) ? T : NIL;
1231 }
1232 
1233 /* MX write and unlock index
1234  * Accepts: MAIL stream
1235  */
1236 
1237 #define MXIXBUFLEN 2048
1238 
mx_unlockindex(MAILSTREAM * stream)1239 void mx_unlockindex (MAILSTREAM *stream)
1240 {
1241   unsigned long i,j;
1242   off_t size = 0;
1243   char *s,tmp[MXIXBUFLEN + 64];
1244   MESSAGECACHE *elt;
1245   if (LOCAL->fd >= 0) {
1246     lseek (LOCAL->fd,0,L_SET);	/* rewind file */
1247 				/* write header */
1248     sprintf (s = tmp,"V%08lxL%08lx",stream->uid_validity,stream->uid_last);
1249     for (i = 0; (i < NUSERFLAGS) && stream->user_flags[i]; ++i)
1250       sprintf (s += strlen (s),"K%s\n",stream->user_flags[i]);
1251 				/* write messages */
1252     for (i = 1; i <= stream->nmsgs; i++) {
1253 				/* filled buffer? */
1254       if (((s += strlen (s)) - tmp) > MXIXBUFLEN) {
1255 	write (LOCAL->fd,tmp,j = s - tmp);
1256 	size += j;
1257 	*(s = tmp) = '\0';	/* dump out and restart buffer */
1258       }
1259       elt = mail_elt (stream,i);
1260       sprintf(s,"M%08lx;%08lx.%04x",elt->private.uid,elt->user_flags,(unsigned)
1261 	      ((fSEEN * elt->seen) + (fDELETED * elt->deleted) +
1262 	       (fFLAGGED * elt->flagged) + (fANSWERED * elt->answered) +
1263 	       (fDRAFT * elt->draft)));
1264     }
1265 				/* write tail end of buffer */
1266     if ((s += strlen (s)) != tmp) {
1267       write (LOCAL->fd,tmp,j = s - tmp);
1268       size += j;
1269     }
1270     ftruncate (LOCAL->fd,size);
1271     flock (LOCAL->fd,LOCK_UN);	/* unlock the index */
1272     close (LOCAL->fd);		/* finished with file */
1273     LOCAL->fd = -1;		/* no index now */
1274   }
1275 }
1276 
1277 /* Set date for message
1278  * Accepts: file name
1279  *	    elt containing date
1280  */
1281 
mx_setdate(char * file,MESSAGECACHE * elt)1282 void mx_setdate (char *file,MESSAGECACHE *elt)
1283 {
1284   time_t tp[2];
1285   tp[0] = time (0);		/* atime is now */
1286   tp[1] = mail_longdate (elt);	/* modification time */
1287   utime (file,tp);		/* set the times */
1288 }
1289