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