* Clean up some function definitions to comply with strict
[alpine.git] / imap / src / osdep / amiga / mbx.c
blobbf3aa0acf6c2559756822ead84ce4394ea2bd235
1 /* ========================================================================
2 * Copyright 1988-2012 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: MBX mail routines
17 * Author: 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 October 1995
26 * Last Edited: 21 February 2012
30 /* FILE TIME SEMANTICS
32 * The atime is the last read time of the file.
33 * The mtime is the last flags update time of the file.
34 * The ctime is the last write time of the file.
37 #include <stdio.h>
38 #include <ctype.h>
39 #include <errno.h>
40 #ifndef errno
41 extern int errno; /* just in case */
42 #endif
43 #include "mail.h"
44 #include "osdep.h"
45 #include <pwd.h>
46 #include <sys/stat.h>
47 #include <sys/time.h>
48 #include "misc.h"
49 #include "dummy.h"
50 #include "fdstring.h"
53 /* Build parameters */
55 #define HDRSIZE 2048
58 /* Kludge to make Cygwin happy */
60 #ifndef O_BINARY
61 #define O_BINARY 0
62 #endif
64 /* MBX I/O stream local data */
66 typedef struct mbx_local {
67 unsigned int flagcheck: 1; /* if ping should sweep for flags */
68 unsigned int expok: 1; /* if expunging OK in ping */
69 unsigned int expunged : 1; /* if one or more expunged messages */
70 int fd; /* file descriptor for I/O */
71 int ld; /* lock file descriptor */
72 int ffuserflag; /* first free user flag */
73 off_t filesize; /* file size parsed */
74 time_t filetime; /* last file time */
75 time_t lastsnarf; /* last snarf time */
76 unsigned long lastpid; /* PID of last writer */
77 unsigned char *buf; /* temporary buffer */
78 unsigned long buflen; /* current size of temporary buffer */
79 char lock[MAILTMPLEN]; /* buffer to write lock name */
80 } MBXLOCAL;
83 /* Convenient access to local data */
85 #define LOCAL ((MBXLOCAL *) stream->local)
87 /* Function prototypes */
89 DRIVER *mbx_valid (char *name);
90 int mbx_isvalid (MAILSTREAM **stream,char *name,char *tmp,int *ld,char *lock,
91 long flags);
92 void *mbx_parameters (long function,void *value);
93 void mbx_scan (MAILSTREAM *stream,char *ref,char *pat,char *contents);
94 void mbx_list (MAILSTREAM *stream,char *ref,char *pat);
95 void mbx_lsub (MAILSTREAM *stream,char *ref,char *pat);
96 long mbx_create (MAILSTREAM *stream,char *mailbox);
97 long mbx_delete (MAILSTREAM *stream,char *mailbox);
98 long mbx_rename (MAILSTREAM *stream,char *old,char *newname);
99 long mbx_status (MAILSTREAM *stream,char *mbx,long flags);
100 MAILSTREAM *mbx_open (MAILSTREAM *stream);
101 void mbx_close (MAILSTREAM *stream,long options);
102 void mbx_abort (MAILSTREAM *stream);
103 void mbx_flags (MAILSTREAM *stream,char *sequence,long flags);
104 char *mbx_header (MAILSTREAM *stream,unsigned long msgno,unsigned long *length,
105 long flags);
106 long mbx_text (MAILSTREAM *stream,unsigned long msgno,STRING *bs,long flags);
107 void mbx_flag (MAILSTREAM *stream,char *sequence,char *flag,long flags);
108 void mbx_flagmsg (MAILSTREAM *stream,MESSAGECACHE *elt);
109 long mbx_ping (MAILSTREAM *stream);
110 void mbx_check (MAILSTREAM *stream);
111 long mbx_expunge (MAILSTREAM *stream,char *sequence,long options);
112 void mbx_snarf (MAILSTREAM *stream);
113 long mbx_copy (MAILSTREAM *stream,char *sequence,char *mailbox,long options);
114 long mbx_append (MAILSTREAM *stream,char *mailbox,append_t af,void *data);
116 char *mbx_file (char *dst,char *name);
117 long mbx_parse (MAILSTREAM *stream);
118 MESSAGECACHE *mbx_elt (MAILSTREAM *stream,unsigned long msgno,long expok);
119 unsigned long mbx_read_flags (MAILSTREAM *stream,MESSAGECACHE *elt);
120 void mbx_update_header (MAILSTREAM *stream);
121 void mbx_update_status (MAILSTREAM *stream,unsigned long msgno,long flags);
122 unsigned long mbx_hdrpos (MAILSTREAM *stream,unsigned long msgno,
123 unsigned long *size,char **hdr);
124 unsigned long mbx_rewrite (MAILSTREAM *stream,unsigned long *reclaimed,
125 long flags);
126 long mbx_flaglock (MAILSTREAM *stream);
128 /* MBX mail routines */
131 /* Driver dispatch used by MAIL */
133 DRIVER mbxdriver = {
134 "mbx", /* driver name */
135 DR_LOCAL|DR_MAIL|DR_CRLF|DR_LOCKING,
136 /* driver flags */
137 (DRIVER *) NIL, /* next driver */
138 mbx_valid, /* mailbox is valid for us */
139 mbx_parameters, /* manipulate parameters */
140 mbx_scan, /* scan mailboxes */
141 mbx_list, /* list mailboxes */
142 mbx_lsub, /* list subscribed mailboxes */
143 NIL, /* subscribe to mailbox */
144 NIL, /* unsubscribe from mailbox */
145 mbx_create, /* create mailbox */
146 mbx_delete, /* delete mailbox */
147 mbx_rename, /* rename mailbox */
148 mbx_status, /* status of mailbox */
149 mbx_open, /* open mailbox */
150 mbx_close, /* close mailbox */
151 mbx_flags, /* fetch message "fast" attributes */
152 mbx_flags, /* fetch message flags */
153 NIL, /* fetch overview */
154 NIL, /* fetch message envelopes */
155 mbx_header, /* fetch message header */
156 mbx_text, /* fetch message body */
157 NIL, /* fetch partial message text */
158 NIL, /* unique identifier */
159 NIL, /* message number */
160 mbx_flag, /* modify flags */
161 mbx_flagmsg, /* per-message modify flags */
162 NIL, /* search for message based on criteria */
163 NIL, /* sort messages */
164 NIL, /* thread messages */
165 mbx_ping, /* ping mailbox to see if still alive */
166 mbx_check, /* check for new messages */
167 mbx_expunge, /* expunge deleted messages */
168 mbx_copy, /* copy messages to another mailbox */
169 mbx_append, /* append string message to mailbox */
170 NIL /* garbage collect stream */
173 /* prototype stream */
174 MAILSTREAM mbxproto = {&mbxdriver};
176 /* MBX mail validate mailbox
177 * Accepts: mailbox name
178 * Returns: our driver if name is valid, NIL otherwise
181 DRIVER *mbx_valid (char *name)
183 char tmp[MAILTMPLEN];
184 int fd = mbx_isvalid (NIL,name,tmp,NIL,NIL,NIL);
185 if (fd < 0) return NIL;
186 close (fd); /* don't need the fd now */
187 return &mbxdriver;
191 /* MBX mail test for valid mailbox
192 * Accepts: returned stream with valid mailbox keywords
193 * mailbox name
194 * scratch buffer
195 * returned lock fd
196 * returned lock name
197 * RW flags or NIL for readonly
198 * Returns: file descriptor if valid, NIL otherwise
201 #define MBXISVALIDNOUID 0x1 /* RW, don't do UID action */
202 #define MBXISVALIDUID 0x2 /* RW, do UID action */
204 int mbx_isvalid (MAILSTREAM **stream,char *name,char *tmp,int *ld,char *lock,
205 long flags)
207 int fd,upd;
208 int ret = -1;
209 unsigned long i;
210 long j,k;
211 off_t pos;
212 char c,*s,*t,hdr[HDRSIZE];
213 struct stat sbuf;
214 time_t tp[2];
215 int error = EINVAL; /* assume invalid argument */
216 if (ld) *ld = -1; /* initially no lock */
217 if ((s = mbx_file (tmp,name)) && !stat (s,&sbuf) &&
218 ((fd = open (tmp,(flags ? O_RDWR : O_RDONLY)|O_BINARY,NIL)) >= 0)) {
219 error = -1; /* bogus format */
220 /* I love cretinous C compilers -- don't you? */
221 if (read (fd,hdr,HDRSIZE) == HDRSIZE)
222 if ((hdr[0] == '*') && (hdr[1] == 'm') && (hdr[2] == 'b') &&
223 (hdr[3] == 'x') && (hdr[4] == '*') && (hdr[5] == '\015') &&
224 (hdr[6] == '\012') && isxdigit (hdr[7]) && isxdigit (hdr[8]))
225 if (isxdigit (hdr[9]) && isxdigit (hdr[10]) && isxdigit (hdr[11]) &&
226 isxdigit (hdr[12]) && isxdigit (hdr[13]) && isxdigit (hdr[14]) &&
227 isxdigit (c = hdr[15]) && isxdigit (hdr[16]))
228 if (isxdigit (hdr[17]) && isxdigit (hdr[18]) &&
229 isxdigit (hdr[19]) && isxdigit (hdr[20]) &&
230 isxdigit (hdr[21]) && isxdigit (hdr[22]) &&
231 (hdr[23] == '\015') && (hdr[24] == '\012')) {
232 ret = fd; /* mbx format */
234 if (stream) { /* lock if making mini-stream */
235 if (flock (fd,LOCK_SH) ||
236 (flags && ((*ld = lockfd (fd,lock,LOCK_EX)) < 0))) ret = -1;
237 /* reread data now that locked */
238 else if (lseek (fd,0,L_SET) ||
239 (read (fd,hdr,HDRSIZE) != HDRSIZE)) ret = -1;
240 else {
241 *stream = (MAILSTREAM *) memset (fs_get (sizeof (MAILSTREAM)),
242 0,sizeof (MAILSTREAM));
243 hdr[15] = '\0'; /* tie off UIDVALIDITY */
244 (*stream)->uid_validity = strtoul (hdr+7,NIL,16);
245 hdr[15] = c; /* now get UIDLAST */
246 (*stream)->uid_last = strtoul (hdr+15,NIL,16);
247 /* parse user flags */
248 for (i = 0, s = hdr + 25;
249 (i < NUSERFLAGS) && (t = strchr (s,'\015')) && (t - s);
250 i++, s = t + 2) {
251 *t = '\0'; /* tie off flag */
252 if (strlen (s) <= MAXUSERFLAG)
253 (*stream)->user_flags[i] = cpystr (s);
255 /* make sure have true UIDLAST */
256 if (flags & MBXISVALIDUID) {
257 for (upd = NIL,pos = 2048, k = 0; pos < sbuf.st_size;
258 pos += (j + k)) {
259 /* read header for this message */
260 lseek (fd,pos,L_SET);
261 if ((j = read (fd,hdr,64)) >= 0) {
262 hdr[j] = '\0';
263 if ((s = strchr (hdr,'\015')) && (s[1] == '\012')) {
264 *s = '\0';
265 k = s + 2 - hdr;
266 if ((s = strchr (hdr,',')) &&
267 (j = strtol (s+1,&s,10)) && (*s == ';') &&
268 (s = strchr (s+1,'-'))) {
269 /* get UID if there is any */
270 i = strtoul (++s,&t,16);
271 if (!*t && (t == (s + 8)) &&
272 (i <= (*stream)->uid_last)) {
273 if (!i) {
274 lseek (fd,pos + s - hdr,L_SET);
275 sprintf (hdr,"%08lx",++(*stream)->uid_last);
276 write (fd,hdr,8);
277 upd = T;
279 continue;
283 ret = -1; /* error, give up */
284 *stream = mail_close (*stream);
285 pos = sbuf.st_size + 1;
286 j = k = 0;
290 if (upd) { /* need to update hdr with new UIDLAST? */
291 lseek (fd,15,L_SET);
292 sprintf (hdr,"%08lx",(*stream)->uid_last);
293 write (fd,hdr,8);
299 if (ret != fd) close (fd); /* close the file */
300 else lseek (fd,0,L_SET); /* else rewind to start */
301 /* \Marked status? */
302 if (sbuf.st_ctime > sbuf.st_atime) {
303 tp[0] = sbuf.st_atime; /* preserve atime and mtime */
304 tp[1] = sbuf.st_mtime;
305 utime (tmp,tp); /* set the times */
308 /* in case INBOX but not mbx format */
309 else if (((error = errno) == ENOENT) && !compare_cstring (name,"INBOX"))
310 error = -1;
311 if ((ret < 0) && ld && (*ld >= 0)) {
312 unlockfd (*ld,lock);
313 *ld = -1;
315 errno = error; /* return as last error */
316 return ret; /* return what we should */
319 /* MBX manipulate driver parameters
320 * Accepts: function code
321 * function-dependent value
322 * Returns: function-dependent return value
325 void *mbx_parameters (long function,void *value)
327 void *ret = NIL;
328 switch ((int) function) {
329 case GET_INBOXPATH:
330 if (value) ret = mbx_file ((char *) value,"INBOX");
331 break;
332 case SET_ONETIMEEXPUNGEATPING:
333 if (value) ((MBXLOCAL *) ((MAILSTREAM *) value)->local)->expok = T;
334 case GET_ONETIMEEXPUNGEATPING:
335 if (value) ret = (void *)
336 (((MBXLOCAL *) ((MAILSTREAM *) value)->local)->expok ? VOIDT : NIL);
337 break;
339 return ret;
343 /* MBX mail scan mailboxes
344 * Accepts: mail stream
345 * reference
346 * pattern to search
347 * string to scan
350 void mbx_scan (MAILSTREAM *stream,char *ref,char *pat,char *contents)
352 if (stream) dummy_scan (NIL,ref,pat,contents);
356 /* MBX mail list mailboxes
357 * Accepts: mail stream
358 * reference
359 * pattern to search
362 void mbx_list (MAILSTREAM *stream,char *ref,char *pat)
364 if (stream) dummy_list (NIL,ref,pat);
368 /* MBX mail list subscribed mailboxes
369 * Accepts: mail stream
370 * reference
371 * pattern to search
374 void mbx_lsub (MAILSTREAM *stream,char *ref,char *pat)
376 if (stream) dummy_lsub (NIL,ref,pat);
379 /* MBX mail create mailbox
380 * Accepts: MAIL stream
381 * mailbox name to create
382 * Returns: T on success, NIL on failure
385 long mbx_create (MAILSTREAM *stream,char *mailbox)
387 char *s,*t,mbx[MAILTMPLEN],tmp[HDRSIZE];
388 long ret = NIL;
389 int i,fd;
390 if (!(s = mbx_file (mbx,mailbox))) {
391 sprintf (mbx,"Can't create %.80s: invalid name",mailbox);
392 MM_LOG (mbx,ERROR);
394 /* create underlying file */
395 else if (dummy_create_path (stream,s,get_dir_protection (mailbox))) {
396 /* done if made directory */
397 if ((s = strrchr (s,'/')) && !s[1]) return T;
398 if ((fd = open (mbx,O_WRONLY|O_BINARY,NIL)) < 0) {
399 sprintf (tmp,"Can't reopen mailbox node %.80s: %s",mbx,strerror (errno));
400 MM_LOG (tmp,ERROR);
401 unlink (mbx); /* delete the file */
403 else {
404 memset (tmp,'\0',HDRSIZE);/* initialize header */
405 sprintf (s = tmp,"*mbx*\015\012%08lx00000000\015\012",
406 (unsigned long) time (0));
407 for (i = 0; i < NUSERFLAGS; ++i) {
408 t = (stream && stream->user_flags[i]) ? stream->user_flags[i] :
409 ((t = default_user_flag (i)) ? t : "");
410 sprintf (s += strlen (s),"%s\015\012",t);
412 if (write (fd,tmp,HDRSIZE) != HDRSIZE) {
413 sprintf (tmp,"Can't initialize mailbox node %.80s: %s",
414 mbx,strerror (errno));
415 MM_LOG (tmp,ERROR);
416 unlink (mbx); /* delete the file */
418 else ret = T; /* success */
419 close (fd); /* close file */
422 /* set proper protections */
423 return ret ? set_mbx_protections (mailbox,mbx) : NIL;
427 /* MBX mail delete mailbox
428 * Accepts: MAIL stream
429 * mailbox name to delete
430 * Returns: T on success, NIL on failure
433 long mbx_delete (MAILSTREAM *stream,char *mailbox)
435 return mbx_rename (stream,mailbox,NIL);
438 /* MBX mail rename mailbox
439 * Accepts: MAIL stream
440 * old mailbox name
441 * new mailbox name (or NIL for delete)
442 * Returns: T on success, NIL on failure
445 long mbx_rename (MAILSTREAM *stream,char *old,char *newname)
447 long ret = LONGT;
448 char c,*s,tmp[MAILTMPLEN],file[MAILTMPLEN],lock[MAILTMPLEN];
449 int fd,ld;
450 struct stat sbuf;
451 if (!mbx_file (file,old) ||
452 (newname && (!((s = mailboxfile (tmp,newname)) && *s) ||
453 ((s = strrchr (tmp,'/')) && !s[1])))) {
454 sprintf (tmp,newname ?
455 "Can't rename mailbox %.80s to %.80s: invalid name" :
456 "Can't delete mailbox %.80s: invalid name",
457 old,newname);
458 MM_LOG (tmp,ERROR);
459 return NIL;
461 else if ((fd = open (file,O_RDWR|O_BINARY,NIL)) < 0) {
462 sprintf (tmp,"Can't open mailbox %.80s: %s",old,strerror (errno));
463 MM_LOG (tmp,ERROR);
464 return NIL;
466 /* get parse/append permission */
467 if ((ld = lockfd (fd,lock,LOCK_EX)) < 0) {
468 MM_LOG ("Unable to lock rename mailbox",ERROR);
469 return NIL;
471 /* lock out other users */
472 if (flock (fd,LOCK_EX|LOCK_NB)) {
473 close (fd); /* couldn't lock, give up on it then */
474 sprintf (tmp,"Mailbox %.80s is in use by another process",old);
475 MM_LOG (tmp,ERROR);
476 unlockfd (ld,lock); /* release exclusive parse/append permission */
477 return NIL;
480 if (newname) { /* want rename? */
481 /* found superior to destination name? */
482 if (s = strrchr (tmp,'/')) {
483 c = *++s; /* remember first character of inferior */
484 *s = '\0'; /* tie off to get just superior */
485 /* superior name doesn't exist, create it */
486 if ((stat (tmp,&sbuf) || ((sbuf.st_mode & S_IFMT) != S_IFDIR)) &&
487 !dummy_create_path (stream,tmp,get_dir_protection (newname)))
488 ret = NIL;
489 else *s = c; /* restore full name */
491 /* rename the file */
492 if (ret && rename (file,tmp)) {
493 sprintf (tmp,"Can't rename mailbox %.80s to %.80s: %s",old,newname,
494 strerror (errno));
495 MM_LOG (tmp,ERROR);
496 ret = NIL; /* set failure */
499 else if (unlink (file)) {
500 sprintf (tmp,"Can't delete mailbox %.80s: %s",old,strerror (errno));
501 MM_LOG (tmp,ERROR);
502 ret = NIL; /* set failure */
504 flock (fd,LOCK_UN); /* release lock on the file */
505 unlockfd (ld,lock); /* release exclusive parse/append permission */
506 close (fd); /* close the file */
507 /* recreate file if renamed INBOX */
508 if (ret && !compare_cstring (old,"INBOX")) mbx_create (NIL,"INBOX");
509 return ret; /* return success */
512 /* MBX Mail status
513 * Accepts: mail stream
514 * mailbox name
515 * status flags
516 * Returns: T on success, NIL on failure
519 long mbx_status (MAILSTREAM *stream,char *mbx,long flags)
521 MAILSTATUS status;
522 unsigned long i;
523 MAILSTREAM *tstream = NIL;
524 MAILSTREAM *systream = NIL;
525 /* make temporary stream (unless this mbx) */
526 if (!stream && !(stream = tstream =
527 mail_open (NIL,mbx,OP_READONLY|OP_SILENT)))
528 return NIL;
529 status.flags = flags; /* return status values */
530 status.messages = stream->nmsgs;
531 status.recent = stream->recent;
532 if (flags & SA_UNSEEN) /* must search to get unseen messages */
533 for (i = 1,status.unseen = 0; i <= stream->nmsgs; i++)
534 if (!mail_elt (stream,i)->seen) status.unseen++;
535 status.uidnext = stream->uid_last + 1;
536 status.uidvalidity = stream->uid_validity;
537 /* calculate post-snarf results */
538 if (!status.recent && stream->inbox &&
539 (systream = mail_open (NIL,sysinbox (),OP_READONLY|OP_SILENT))) {
540 status.messages += systream->nmsgs;
541 status.recent += systream->recent;
542 if (flags & SA_UNSEEN) /* must search to get unseen messages */
543 for (i = 1; i <= systream->nmsgs; i++)
544 if (!mail_elt (systream,i)->seen) status.unseen++;
545 /* kludge but probably good enough */
546 status.uidnext += systream->nmsgs;
548 MM_STATUS(stream,mbx,&status);/* pass status to main program */
549 if (tstream) mail_close (tstream);
550 if (systream) mail_close (systream);
551 return T; /* success */
554 /* MBX mail open
555 * Accepts: stream to open
556 * Returns: stream on success, NIL on failure
559 MAILSTREAM *mbx_open (MAILSTREAM *stream)
561 int fd,ld;
562 short silent;
563 char tmp[MAILTMPLEN];
564 blocknotify_t bn = (blocknotify_t) mail_parameters (NIL,GET_BLOCKNOTIFY,NIL);
565 /* return prototype for OP_PROTOTYPE call */
566 if (!stream) return user_flags (&mbxproto);
567 if (stream->local) fatal ("mbx recycle stream");
568 /* canonicalize the mailbox name */
569 if (!mbx_file (tmp,stream->mailbox)) {
570 sprintf (tmp,"Can't open - invalid name: %.80s",stream->mailbox);
571 MM_LOG (tmp,ERROR);
573 if (stream->rdonly ||
574 (fd = open (tmp,O_RDWR|O_BINARY,NIL)) < 0) {
575 if ((fd = open (tmp,O_RDONLY|O_BINARY,NIL)) < 0) {
576 sprintf (tmp,"Can't open mailbox: %s",strerror (errno));
577 MM_LOG (tmp,ERROR);
578 return NIL;
580 else if (!stream->rdonly) { /* got it, but readonly */
581 MM_LOG ("Can't get write access to mailbox, access is readonly",WARN);
582 stream->rdonly = T;
586 stream->local = memset (fs_get (sizeof (MBXLOCAL)),NIL,sizeof (MBXLOCAL));
587 LOCAL->fd = fd; /* bind the file */
588 LOCAL->ld = -1; /* no flaglock */
589 LOCAL->buf = (char *) fs_get (CHUNKSIZE);
590 LOCAL->buflen = CHUNKSIZE - 1;
591 /* note if an INBOX or not */
592 stream->inbox = !compare_cstring (stream->mailbox,"INBOX");
593 fs_give ((void **) &stream->mailbox);
594 stream->mailbox = cpystr (tmp);
595 /* get parse/append permission */
596 if ((ld = lockfd (LOCAL->fd,tmp,LOCK_EX)) < 0) {
597 MM_LOG ("Unable to lock open mailbox",ERROR);
598 return NIL;
600 (*bn) (BLOCK_FILELOCK,NIL);
601 flock (LOCAL->fd,LOCK_SH); /* lock the file */
602 (*bn) (BLOCK_NONE,NIL);
603 unlockfd (ld,tmp); /* release shared parse permission */
604 LOCAL->filesize = HDRSIZE; /* initialize parsed file size */
605 /* time not set up yet */
606 LOCAL->lastsnarf = LOCAL->filetime = 0;
607 LOCAL->expok = LOCAL->flagcheck = NIL;
608 stream->sequence++; /* bump sequence number */
609 /* parse mailbox */
610 stream->nmsgs = stream->recent = 0;
611 silent = stream->silent; /* defer events */
612 stream->silent = T;
613 if (mbx_ping (stream) && !stream->nmsgs)
614 MM_LOG ("Mailbox is empty",(long) NIL);
615 stream->silent = silent; /* now notify upper level */
616 mail_exists (stream,stream->nmsgs);
617 mail_recent (stream,stream->recent);
618 if (!LOCAL) return NIL; /* failure if stream died */
619 stream->perm_seen = stream->perm_deleted = stream->perm_flagged =
620 stream->perm_answered = stream->perm_draft = stream->rdonly ? NIL : T;
621 stream->perm_user_flags = stream->rdonly ? NIL : 0xffffffff;
622 stream->kwd_create = (stream->user_flags[NUSERFLAGS-1] || stream->rdonly) ?
623 NIL : T; /* can we create new user flags? */
624 return stream; /* return stream to caller */
627 /* MBX mail close
628 * Accepts: MAIL stream
629 * close options
632 void mbx_close (MAILSTREAM *stream,long options)
634 if (stream && LOCAL) { /* only if a file is open */
635 int silent = stream->silent;
636 stream->silent = T; /* note this stream is dying */
637 /* do an expunge if requested */
638 if (options & CL_EXPUNGE) mbx_expunge (stream,NIL,NIL);
639 else { /* otherwise do a checkpoint to purge */
640 LOCAL->expok = T; /* possible expunged messages */
641 mbx_ping (stream);
643 stream->silent = silent; /* restore previous status */
644 mbx_abort (stream);
649 /* MBX mail abort stream
650 * Accepts: MAIL stream
653 void mbx_abort (MAILSTREAM *stream)
655 if (stream && LOCAL) { /* only if a file is open */
656 flock (LOCAL->fd,LOCK_UN); /* unlock local file */
657 close (LOCAL->fd); /* close the local file */
658 /* free local text buffer */
659 if (LOCAL->buf) fs_give ((void **) &LOCAL->buf);
660 /* nuke the local data */
661 fs_give ((void **) &stream->local);
662 stream->dtb = NIL; /* log out the DTB */
667 /* MBX mail fetch flags
668 * Accepts: MAIL stream
669 * sequence
670 * option flags
671 * Sniffs at file to see if some other process changed the flags
674 void mbx_flags (MAILSTREAM *stream,char *sequence,long flags)
676 MESSAGECACHE *elt;
677 unsigned long i;
678 if (mbx_ping (stream) && /* ping mailbox, get new status for messages */
679 ((flags & FT_UID) ? mail_uid_sequence (stream,sequence) :
680 mail_sequence (stream,sequence)))
681 for (i = 1; i <= stream->nmsgs; i++)
682 if ((elt = mail_elt (stream,i))->sequence && !elt->valid)
683 mbx_elt (stream,i,NIL);
686 /* MBX mail fetch message header
687 * Accepts: MAIL stream
688 * message # to fetch
689 * pointer to returned header text length
690 * option flags
691 * Returns: message header in RFC822 format
694 char *mbx_header (MAILSTREAM *stream,unsigned long msgno,unsigned long *length,
695 long flags)
697 unsigned long i;
698 char *s;
699 *length = 0; /* default to empty */
700 if (flags & FT_UID) return "";/* UID call "impossible" */
701 /* get header position, possibly header */
702 i = mbx_hdrpos (stream,msgno,length,&s);
703 if (!s) { /* mbx_hdrpos() returned header? */
704 lseek (LOCAL->fd,i,L_SET); /* no, get to header position */
705 /* is buffer big enough? */
706 if (*length > LOCAL->buflen) {
707 fs_give ((void **) &LOCAL->buf);
708 LOCAL->buf = (char *) fs_get ((LOCAL->buflen = *length) + 1);
710 /* slurp the data */
711 read (LOCAL->fd,s = LOCAL->buf,*length);
713 s[*length] = '\0'; /* tie off string */
714 return s;
717 /* MBX mail fetch message text (body only)
718 * Accepts: MAIL stream
719 * message # to fetch
720 * pointer to returned header text length
721 * option flags
722 * Returns: T on success, NIL on failure
725 long mbx_text (MAILSTREAM *stream,unsigned long msgno,STRING *bs,long flags)
727 FDDATA d;
728 unsigned long i,j;
729 MESSAGECACHE *elt;
730 /* UID call "impossible" */
731 if (flags & FT_UID) return NIL;
732 /* get message status */
733 elt = mbx_elt (stream,msgno,NIL);
734 /* if message not seen */
735 if (!(flags & FT_PEEK) && !elt->seen && mbx_flaglock (stream)) {
736 elt->seen = T; /* mark message as seen */
737 /* recalculate status */
738 mbx_update_status (stream,msgno,NIL);
739 MM_FLAGS (stream,msgno);
740 /* update flags */
741 mbx_flag (stream,NIL,NIL,NIL);
743 if (!LOCAL) return NIL; /* mbx_flaglock() could have aborted */
744 /* find header position */
745 i = mbx_hdrpos (stream,msgno,&j,NIL);
746 d.fd = LOCAL->fd; /* set up file descriptor */
747 d.pos = i + j;
748 d.chunk = LOCAL->buf; /* initial buffer chunk */
749 d.chunksize = CHUNKSIZE;
750 INIT (bs,fd_string,&d,elt->rfc822_size - j);
751 return LONGT; /* success */
754 /* MBX mail modify flags
755 * Accepts: MAIL stream
756 * sequence
757 * flag(s)
758 * option flags
759 * Unlocks flag lock
762 void mbx_flag (MAILSTREAM *stream,char *sequence,char *flag,long flags)
764 time_t tp[2];
765 struct stat sbuf;
766 unsigned long oldpid = LOCAL->lastpid;
767 /* make sure the update takes */
768 if (!stream->rdonly && LOCAL && (LOCAL->fd >= 0) && (LOCAL->ld >= 0)) {
769 fsync (LOCAL->fd);
770 fstat (LOCAL->fd,&sbuf); /* get current write time */
771 tp[1] = LOCAL->filetime = sbuf.st_mtime;
772 /* we are the last flag updater */
773 LOCAL->lastpid = (unsigned long) getpid ();
774 /* update header if needed */
775 if (((LOCAL->ffuserflag < NUSERFLAGS) &&
776 stream->user_flags[LOCAL->ffuserflag]) || (oldpid != LOCAL->lastpid))
777 mbx_update_header (stream);
778 tp[0] = time (0); /* make sure read comes after all that */
779 utime (stream->mailbox,tp);
781 if (LOCAL->ld >= 0) { /* unlock now */
782 unlockfd (LOCAL->ld,LOCAL->lock);
783 LOCAL->ld = -1;
788 /* MBX mail per-message modify flags
789 * Accepts: MAIL stream
790 * message cache element
793 void mbx_flagmsg (MAILSTREAM *stream,MESSAGECACHE *elt)
795 if (mbx_flaglock (stream)) mbx_update_status (stream,elt->msgno,NIL);
798 /* MBX mail ping mailbox
799 * Accepts: MAIL stream
800 * Returns: T if stream still alive, NIL if not
803 long mbx_ping (MAILSTREAM *stream)
805 unsigned long i,pos;
806 long ret = NIL;
807 int ld;
808 char lock[MAILTMPLEN];
809 MESSAGECACHE *elt;
810 struct stat sbuf;
811 if (stream && LOCAL) { /* only if stream already open */
812 int snarf = stream->inbox && !stream->rdonly;
813 ret = LONGT; /* assume OK */
814 fstat (LOCAL->fd,&sbuf); /* get current file poop */
815 /* allow expunge if permitted at ping */
816 if (mail_parameters (NIL,GET_EXPUNGEATPING,NIL)) LOCAL->expok = T;
817 /* if external modification */
818 if (LOCAL->filetime && (LOCAL->filetime < sbuf.st_mtime))
819 LOCAL->flagcheck = T; /* upgrade to flag checking */
820 /* new mail or flagcheck handling needed? */
821 if (((sbuf.st_size - LOCAL->filesize) || LOCAL->flagcheck ||
822 !stream->nmsgs || snarf) &&
823 ((ld = lockfd (LOCAL->fd,lock,LOCK_EX)) >= 0)) {
824 /* reparse header if not flagchecking */
825 if (!LOCAL->flagcheck) ret = mbx_parse (stream);
826 /* sweep mailbox for changed message status */
827 else if (ret = mbx_parse (stream)) {
828 unsigned long recent = 0;
829 LOCAL->filetime = sbuf.st_mtime;
830 for (i = 1; i <= stream->nmsgs; )
831 if (elt = mbx_elt (stream,i,LOCAL->expok)) {
832 if (elt->recent) ++recent;
833 ++i;
835 mail_recent (stream,recent);
836 LOCAL->flagcheck = NIL; /* got all the updates */
838 /* always reparse header at least */
839 if (ret && snarf) { /* snarf new messages if still OK */
840 mbx_snarf (stream);
841 /* parse snarfed messages */
842 ret = mbx_parse (stream);
844 unlockfd (ld,lock); /* release shared parse/append permission */
846 if (ret) { /* must still be alive */
847 if (!LOCAL->expunged) /* look for holes if none known yet */
848 for (i = 1, pos = HDRSIZE;
849 !LOCAL->expunged && (i <= stream->nmsgs);
850 i++, pos += elt->private.special.text.size + elt->rfc822_size)
851 if ((elt = mail_elt (stream,i))->private.special.offset != pos)
852 LOCAL->expunged = T;/* found a hole */
853 /* burp any holes */
854 if (LOCAL->expunged && !stream->rdonly) {
855 if (mbx_rewrite (stream,&i,NIL)) fatal ("expunge on check");
856 if (i) { /* any space reclaimed? */
857 LOCAL->expunged = NIL;/* no more pending expunge */
858 sprintf (LOCAL->buf,"Reclaimed %lu bytes of expunged space",i);
859 MM_LOG (LOCAL->buf,(long) NIL);
862 LOCAL->expok = NIL; /* no more expok */
865 return ret; /* return result of the parse */
868 /* MBX mail check mailbox (reparses status too)
869 * Accepts: MAIL stream
872 void mbx_check (MAILSTREAM *stream)
874 if (LOCAL) LOCAL->expok = T; /* mark that a check is desired */
875 if (mbx_ping (stream)) MM_LOG ("Check completed",(long) NIL);
879 /* MBX mail expunge mailbox
880 * Accepts: MAIL stream
881 * sequence to expunge if non-NIL
882 * expunge options
883 * Returns: T if success, NIL if failure
886 long mbx_expunge (MAILSTREAM *stream,char *sequence,long options)
888 long ret;
889 unsigned long nexp,reclaimed;
890 if (ret = sequence ? ((options & EX_UID) ?
891 mail_uid_sequence (stream,sequence) :
892 mail_sequence (stream,sequence)) : LONGT) {
893 if (!mbx_ping (stream)); /* do nothing if stream dead */
894 else if (stream->rdonly) /* won't do on readonly files! */
895 MM_LOG ("Expunge ignored on readonly mailbox",WARN);
896 /* if expunged any messages */
897 else if (nexp = mbx_rewrite (stream,&reclaimed,sequence ? -1 : 1)) {
898 sprintf (LOCAL->buf,"Expunged %lu messages",nexp);
899 MM_LOG (LOCAL->buf,(long) NIL);
901 else if (reclaimed) { /* or if any prior expunged space reclaimed */
902 sprintf (LOCAL->buf,"Reclaimed %lu bytes of expunged space",reclaimed);
903 MM_LOG (LOCAL->buf,(long) NIL);
905 else MM_LOG ("No messages deleted, so no update needed",(long) NIL);
907 return ret;
910 /* MBX mail snarf messages from system inbox
911 * Accepts: MAIL stream, already locked
914 void mbx_snarf (MAILSTREAM *stream)
916 unsigned long i = 0;
917 unsigned long j,r,hdrlen,txtlen;
918 struct stat sbuf;
919 char *hdr,*txt,tmp[MAILTMPLEN];
920 MESSAGECACHE *elt;
921 MAILSTREAM *sysibx = NIL;
922 /* give up if can't get exclusive permission */
923 if ((time (0) >= (LOCAL->lastsnarf +
924 (long) mail_parameters (NIL,GET_SNARFINTERVAL,NIL))) &&
925 strcmp (sysinbox (),stream->mailbox)) {
926 MM_CRITICAL (stream); /* go critical */
927 /* sizes match and anything in sysinbox? */
928 if (!stat (sysinbox (),&sbuf) && sbuf.st_size &&
929 !fstat (LOCAL->fd,&sbuf) && (sbuf.st_size == LOCAL->filesize) &&
930 (sysibx = mail_open (sysibx,sysinbox (),OP_SILENT)) &&
931 (!sysibx->rdonly) && (r = sysibx->nmsgs)) {
932 /* yes, go to end of file in our mailbox */
933 lseek (LOCAL->fd,sbuf.st_size,L_SET);
934 /* for each message in sysibx mailbox */
935 while (r && (++i <= sysibx->nmsgs)) {
936 /* snarf message from system INBOX */
937 hdr = cpystr (mail_fetchheader_full (sysibx,i,NIL,&hdrlen,NIL));
938 txt = mail_fetchtext_full (sysibx,i,&txtlen,FT_PEEK);
939 /* if have a message */
940 if (j = hdrlen + txtlen) {
941 /* build header line */
942 mail_date (LOCAL->buf,elt = mail_elt (sysibx,i));
943 sprintf (LOCAL->buf + strlen (LOCAL->buf),
944 ",%lu;00000000%04x-00000000\015\012",j,(unsigned)
945 ((fSEEN * elt->seen) +
946 (fDELETED * elt->deleted) + (fFLAGGED * elt->flagged) +
947 (fANSWERED * elt->answered) + (fDRAFT * elt->draft)));
948 /* copy message */
949 if ((write (LOCAL->fd,LOCAL->buf,strlen (LOCAL->buf)) < 0) ||
950 (write (LOCAL->fd,hdr,hdrlen) < 0) ||
951 (write (LOCAL->fd,txt,txtlen) < 0)) r = 0;
953 fs_give ((void **) &hdr);
956 /* make sure all the updates take */
957 if (fsync (LOCAL->fd)) r = 0;
958 if (r) { /* delete all the messages we copied */
959 if (r == 1) strcpy (tmp,"1");
960 else sprintf (tmp,"1:%lu",r);
961 mail_setflag (sysibx,tmp,"\\Deleted");
962 mail_expunge (sysibx); /* now expunge all those messages */
964 else {
965 sprintf (LOCAL->buf,"Can't copy new mail: %s",strerror (errno));
966 MM_LOG (LOCAL->buf,WARN);
967 ftruncate (LOCAL->fd,sbuf.st_size);
969 fstat (LOCAL->fd,&sbuf); /* yes, get current file size */
970 LOCAL->filetime = sbuf.st_mtime;
972 if (sysibx) mail_close (sysibx);
973 MM_NOCRITICAL (stream); /* release critical */
974 LOCAL->lastsnarf = time (0);/* note time of last snarf */
978 /* MBX mail copy message(s)
979 * Accepts: MAIL stream
980 * sequence
981 * destination mailbox
982 * copy options
983 * Returns: T if success, NIL if failed
986 long mbx_copy (MAILSTREAM *stream,char *sequence,char *mailbox,long options)
988 struct stat sbuf;
989 time_t tp[2];
990 MESSAGECACHE *elt;
991 unsigned long i,j,k,m;
992 long ret = LONGT;
993 int fd,ld;
994 char *s,*t,file[MAILTMPLEN],lock[MAILTMPLEN];
995 mailproxycopy_t pc =
996 (mailproxycopy_t) mail_parameters (stream,GET_MAILPROXYCOPY,NIL);
997 copyuid_t cu = (copyuid_t) mail_parameters (NIL,GET_COPYUID,NIL);
998 SEARCHSET *source = cu ? mail_newsearchset () : NIL;
999 SEARCHSET *dest = cu ? mail_newsearchset () : NIL;
1000 MAILSTREAM *dstream = NIL;
1001 if (!((options & CP_UID) ? mail_uid_sequence (stream,sequence) :
1002 mail_sequence (stream,sequence))) return NIL;
1003 /* make sure valid mailbox */
1004 if ((fd = mbx_isvalid (&dstream,mailbox,file,&ld,lock,
1005 cu ? MBXISVALIDUID : MBXISVALIDNOUID)) < 0)
1006 switch (errno) {
1007 case ENOENT: /* no such file? */
1008 MM_NOTIFY (stream,"[TRYCREATE] Must create mailbox before copy",NIL);
1009 return NIL;
1010 case EACCES: /* file protected */
1011 sprintf (LOCAL->buf,"Can't access destination: %.80s",mailbox);
1012 MM_LOG (LOCAL->buf,ERROR);
1013 return NIL;
1014 case EINVAL:
1015 if (pc) return (*pc) (stream,sequence,mailbox,options);
1016 sprintf (LOCAL->buf,"Invalid MBX-format mailbox name: %.80s",mailbox);
1017 MM_LOG (LOCAL->buf,ERROR);
1018 return NIL;
1019 default:
1020 if (pc) return (*pc) (stream,sequence,mailbox,options);
1021 sprintf (LOCAL->buf,"Not a MBX-format mailbox: %.80s",mailbox);
1022 MM_LOG (LOCAL->buf,ERROR);
1023 return NIL;
1025 MM_CRITICAL (stream); /* go critical */
1026 fstat (fd,&sbuf); /* get current file size */
1027 lseek (fd,sbuf.st_size,L_SET);/* move to end of file */
1029 /* for each requested message */
1030 for (i = 1; ret && (i <= stream->nmsgs); i++)
1031 if ((elt = mail_elt (stream,i))->sequence) {
1032 lseek (LOCAL->fd,elt->private.special.offset +
1033 elt->private.special.text.size,L_SET);
1034 mail_date(LOCAL->buf,elt);/* build target header */
1035 /* get target keyword mask */
1036 for (j = elt->user_flags, k = 0; j; )
1037 if (s = stream->user_flags[find_rightmost_bit (&j)])
1038 for (m = 0; (m < NUSERFLAGS) && (t = dstream->user_flags[m]); m++)
1039 if (!compare_cstring (s,t) && (k |= 1 << m)) break;
1040 sprintf (LOCAL->buf+strlen(LOCAL->buf),",%lu;%08lx%04x-%08lx\015\012",
1041 elt->rfc822_size,k,(unsigned)
1042 ((fSEEN * elt->seen) + (fDELETED * elt->deleted) +
1043 (fFLAGGED * elt->flagged) + (fANSWERED * elt->answered) +
1044 (fDRAFT * elt->draft)),cu ? ++dstream->uid_last : 0);
1045 /* write target header */
1046 if (ret = (write (fd,LOCAL->buf,strlen (LOCAL->buf)) > 0)) {
1047 for (k = elt->rfc822_size; ret && (j = min (k,LOCAL->buflen)); k -= j){
1048 read (LOCAL->fd,LOCAL->buf,j);
1049 ret = write (fd,LOCAL->buf,j) >= 0;
1051 if (cu) { /* need to pass back new UID? */
1052 mail_append_set (source,mail_uid (stream,i));
1053 mail_append_set (dest,dstream->uid_last);
1058 /* make sure all the updates take */
1059 if (!(ret && (ret = !fsync (fd)))) {
1060 sprintf (LOCAL->buf,"Unable to write message: %s",strerror (errno));
1061 MM_LOG (LOCAL->buf,ERROR);
1062 ftruncate (fd,sbuf.st_size);
1064 if (cu && ret) { /* return sets if doing COPYUID */
1065 (*cu) (stream,mailbox,dstream->uid_validity,source,dest);
1066 lseek (fd,15,L_SET); /* update UIDLAST */
1067 sprintf (LOCAL->buf,"%08lx",dstream->uid_last);
1068 write (fd,LOCAL->buf,8);
1070 else { /* flush any sets we may have built */
1071 mail_free_searchset (&source);
1072 mail_free_searchset (&dest);
1074 if (ret) tp[0] = time (0) - 1;/* set atime to now-1 if successful copy */
1075 /* else preserve \Marked status */
1076 else tp[0] = (sbuf.st_ctime > sbuf.st_atime) ? sbuf.st_atime : time(0);
1077 tp[1] = sbuf.st_mtime; /* preserve mtime */
1078 utime (file,tp); /* set the times */
1079 close (fd); /* close the file */
1080 MM_NOCRITICAL (stream); /* release critical */
1081 unlockfd (ld,lock); /* release exclusive parse/append permission */
1082 /* delete all requested messages */
1083 if (ret && (options & CP_MOVE) && mbx_flaglock (stream)) {
1084 for (i = 1; i <= stream->nmsgs; i++) if (mail_elt (stream,i)->sequence) {
1085 /* mark message deleted */
1086 mbx_elt (stream,i,NIL)->deleted = T;
1087 /* recalculate status */
1088 mbx_update_status (stream,i,NIL);
1090 /* update flags */
1091 mbx_flag (stream,NIL,NIL,NIL);
1093 if (dstream != stream) mail_close (dstream);
1094 return ret;
1097 /* MBX mail append message from stringstruct
1098 * Accepts: MAIL stream
1099 * destination mailbox
1100 * append callback
1101 * data for callback
1102 * Returns: T if append successful, else NIL
1105 long mbx_append (MAILSTREAM *stream,char *mailbox,append_t af,void *data)
1107 struct stat sbuf;
1108 int fd,ld;
1109 char *flags,*date,tmp[MAILTMPLEN],file[MAILTMPLEN],lock[MAILTMPLEN];
1110 time_t tp[2];
1111 FILE *df;
1112 MESSAGECACHE elt;
1113 long f;
1114 unsigned long i,uf;
1115 STRING *message;
1116 long ret = NIL;
1117 MAILSTREAM *dstream = NIL;
1118 appenduid_t au = (appenduid_t) mail_parameters (NIL,GET_APPENDUID,NIL);
1119 SEARCHSET *dst = au ? mail_newsearchset () : NIL;
1120 /* make sure valid mailbox */
1121 if ((fd = mbx_isvalid (&dstream,mailbox,file,&ld,lock,
1122 au ? MBXISVALIDUID : MBXISVALIDNOUID)) < 0)
1123 switch (errno) {
1124 case ENOENT: /* no such file? */
1125 if (compare_cstring (mailbox,"INBOX")) {
1126 MM_NOTIFY (stream,"[TRYCREATE] Must create mailbox before append",NIL);
1127 return NIL;
1129 /* can create INBOX here */
1130 mbx_create (dstream = stream ? stream : user_flags (&mbxproto),"INBOX");
1131 if ((fd = mbx_isvalid (&dstream,mailbox,file,&ld,lock,
1132 au ? MBXISVALIDUID : MBXISVALIDNOUID)) >= 0)
1133 break;
1134 case EACCES: /* file protected */
1135 sprintf (tmp,"Can't access destination: %.80s",mailbox);
1136 MM_LOG (tmp,ERROR);
1137 return NIL;
1138 case EINVAL:
1139 sprintf (tmp,"Invalid MBX-format mailbox name: %.80s",mailbox);
1140 MM_LOG (tmp,ERROR);
1141 return NIL;
1142 default:
1143 sprintf (tmp,"Not a MBX-format mailbox: %.80s",mailbox);
1144 MM_LOG (tmp,ERROR);
1145 return NIL;
1148 /* get first message */
1149 if (!MM_APPEND (af) (dstream,data,&flags,&date,&message)) close (fd);
1150 else if (!(df = fdopen (fd,"r+b"))) {
1151 MM_LOG ("Unable to reopen append mailbox",ERROR);
1152 close (fd);
1154 else {
1155 MM_CRITICAL (dstream); /* go critical */
1156 fstat (fd,&sbuf); /* get current file size */
1157 fseek (df,sbuf.st_size,SEEK_SET);
1158 errno = 0;
1159 for (ret = LONGT; ret && message; ) {
1160 if (!SIZE (message)) { /* guard against zero-length */
1161 MM_LOG ("Append of zero-length message",ERROR);
1162 ret = NIL;
1163 break;
1165 f = mail_parse_flags (dstream,flags,&uf);
1166 if (date) { /* parse date if given */
1167 if (!mail_parse_date (&elt,date)) {
1168 sprintf (tmp,"Bad date in append: %.80s",date);
1169 MM_LOG (tmp,ERROR);
1170 ret = NIL; /* mark failure */
1171 break;
1173 mail_date (tmp,&elt); /* write preserved date */
1175 else internal_date (tmp); /* get current date in IMAP format */
1176 /* write header */
1177 if (fprintf (df,"%s,%lu;%08lx%04lx-%08lx\015\012",tmp,i = SIZE (message),
1178 uf,(unsigned long) f,au ? ++dstream->uid_last : 0) < 0)
1179 ret = NIL;
1180 else { /* write message */
1181 size_t j;
1182 if (!message->cursize) SETPOS (message,GETPOS (message));
1183 for (errno = 0; !errno && i &&
1184 (j = fwrite (message->curpos,1,message->cursize,df)); i -= j) {
1185 SETPOS (message,GETPOS (message) + j);
1187 /* get next message */
1188 if (i || !MM_APPEND (af) (dstream,data,&flags,&date,&message))
1189 ret = NIL;
1190 else if (au) mail_append_set (dst,dstream->uid_last);
1194 /* if error... */
1195 if (!ret || (fflush (df) == EOF)) {
1196 /* revert file */
1197 ftruncate (fd,sbuf.st_size);
1198 close (fd); /* make sure fclose() doesn't corrupt us */
1199 if (errno) {
1200 sprintf (tmp,"Message append failed: %s",strerror (errno));
1201 MM_LOG (tmp,ERROR);
1203 ret = NIL;
1205 if (au && ret) { /* return sets if doing APPENDUID */
1206 (*au) (mailbox,dstream->uid_validity,dst);
1207 fseek (df,15,SEEK_SET); /* update UIDLAST */
1208 fprintf (df,"%08lx",dstream->uid_last);
1210 else mail_free_searchset (&dst);
1211 /* set atime to now-1 if successful copy */
1212 if (ret) tp[0] = time (0) - 1;
1213 /* else preserve \Marked status */
1214 else tp[0] = (sbuf.st_ctime > sbuf.st_atime) ? sbuf.st_atime : time(0);
1215 tp[1] = sbuf.st_mtime; /* preserve mtime */
1216 utime (file,tp); /* set the times */
1217 fclose (df); /* close the file */
1218 MM_NOCRITICAL (dstream); /* release critical */
1220 unlockfd (ld,lock); /* release exclusive parse/append permission */
1221 if (dstream != stream) mail_close (dstream);
1222 return ret;
1225 /* Internal routines */
1228 /* MBX mail generate file string
1229 * Accepts: temporary buffer to write into
1230 * mailbox name string
1231 * Returns: local file string or NIL if failure
1234 char *mbx_file (char *dst,char *name)
1236 char *s = mailboxfile (dst,name);
1237 return (s && !*s) ? mailboxfile (dst,"~/INBOX") : s;
1240 /* MBX mail parse mailbox
1241 * Accepts: MAIL stream
1242 * Returns: T if parse OK
1243 * NIL if failure, stream aborted
1246 long mbx_parse (MAILSTREAM *stream)
1248 struct stat sbuf;
1249 MESSAGECACHE *elt = NIL;
1250 unsigned char c,*s,*t,*x;
1251 char tmp[MAILTMPLEN];
1252 unsigned long i,j,k,m;
1253 off_t curpos = LOCAL->filesize;
1254 unsigned long nmsgs = stream->nmsgs;
1255 unsigned long recent = stream->recent;
1256 unsigned long lastuid = 0;
1257 short dirty = NIL;
1258 short added = NIL;
1259 short silent = stream->silent;
1260 short uidwarn = T;
1261 fstat (LOCAL->fd,&sbuf); /* get status */
1262 if (sbuf.st_size < curpos) { /* sanity check */
1263 sprintf (tmp,"Mailbox shrank from %lu to %lu!",
1264 (unsigned long) curpos,(unsigned long) sbuf.st_size);
1265 MM_LOG (tmp,ERROR);
1266 mbx_abort (stream);
1267 return NIL;
1269 lseek (LOCAL->fd,0,L_SET); /* rewind file */
1270 /* read internal header */
1271 read (LOCAL->fd,LOCAL->buf,HDRSIZE);
1272 LOCAL->buf[HDRSIZE] = '\0'; /* tie off header */
1273 c = LOCAL->buf[15]; /* save first character of last UID */
1274 LOCAL->buf[15] = '\0';
1275 /* parse UID validity */
1276 stream->uid_validity = strtoul (LOCAL->buf + 7,NIL,16);
1277 LOCAL->buf[15] = c; /* restore first character of last UID */
1278 /* parse last UID */
1279 i = strtoul (LOCAL->buf + 15,NIL,16);
1280 stream->uid_last = stream->rdonly ? max (i,stream->uid_last) : i;
1281 /* parse user flags */
1282 for (i = 0, s = LOCAL->buf + 25;
1283 (i < NUSERFLAGS) && (t = strchr (s,'\015')) && (t - s);
1284 i++, s = t + 2) {
1285 *t = '\0'; /* tie off flag */
1286 if (!stream->user_flags[i] && (strlen (s) <= MAXUSERFLAG))
1287 stream->user_flags[i] = cpystr (s);
1289 LOCAL->ffuserflag = (int) i; /* first free user flag */
1291 /* get current last flag updater PID */
1292 i = (isxdigit (LOCAL->buf[HDRSIZE-10]) && isxdigit (LOCAL->buf[HDRSIZE-9]) &&
1293 isxdigit (LOCAL->buf[HDRSIZE-8]) && isxdigit (LOCAL->buf[HDRSIZE-7]) &&
1294 isxdigit (LOCAL->buf[HDRSIZE-6]) && isxdigit (LOCAL->buf[HDRSIZE-5]) &&
1295 isxdigit (LOCAL->buf[HDRSIZE-4]) && isxdigit (LOCAL->buf[HDRSIZE-3]) &&
1296 (LOCAL->buf[HDRSIZE-2] == '\015') && (LOCAL->buf[HDRSIZE-1] == '\012'))?
1297 strtoul (LOCAL->buf + HDRSIZE - 8,NIL,16) : 0;
1298 /* set flagcheck if lastpid changed */
1299 if (LOCAL->lastpid && (LOCAL->lastpid != i)) LOCAL->flagcheck = T;
1300 LOCAL->lastpid = i; /* set as last PID */
1301 stream->silent = T; /* don't pass up exists events yet */
1302 while (sbuf.st_size - curpos){/* while there is stuff to parse */
1303 /* get to that position in the file */
1304 lseek (LOCAL->fd,curpos,L_SET);
1305 if ((i = read (LOCAL->fd,LOCAL->buf,64)) <= 0) {
1306 sprintf (tmp,"Unable to read internal header at %lu, size = %lu: %s",
1307 (unsigned long) curpos,(unsigned long) sbuf.st_size,
1308 i ? strerror (errno) : "no data read");
1309 MM_LOG (tmp,ERROR);
1310 mbx_abort (stream);
1311 return NIL;
1313 LOCAL->buf[i] = '\0'; /* tie off buffer just in case */
1314 if (!((s = strchr (LOCAL->buf,'\015')) && (s[1] == '\012'))) {
1315 sprintf (tmp,"Unable to find CRLF at %lu in %lu bytes, text: %.80s",
1316 (unsigned long) curpos,i,(char *) LOCAL->buf);
1317 MM_LOG (tmp,ERROR);
1318 mbx_abort (stream);
1319 return NIL;
1321 *s = '\0'; /* tie off header line */
1322 i = (s + 2) - LOCAL->buf; /* note start of text offset */
1323 if (!((s = strchr (LOCAL->buf,',')) && (t = strchr (s+1,';')))) {
1324 sprintf (tmp,"Unable to parse internal header at %lu: %.80s",
1325 (unsigned long) curpos,(char *) LOCAL->buf);
1326 MM_LOG (tmp,ERROR);
1327 mbx_abort (stream);
1328 return NIL;
1330 if (!(isxdigit (t[1]) && isxdigit (t[2]) && isxdigit (t[3]) &&
1331 isxdigit (t[4]) && isxdigit (t[5]) && isxdigit (t[6]) &&
1332 isxdigit (t[7]) && isxdigit (t[8]) && isxdigit (t[9]) &&
1333 isxdigit (t[10]) && isxdigit (t[11]) && isxdigit (t[12]))) {
1334 sprintf (tmp,"Unable to parse message flags at %lu: %.80s",
1335 (unsigned long) curpos,(char *) LOCAL->buf);
1336 MM_LOG (tmp,ERROR);
1337 mbx_abort (stream);
1338 return NIL;
1340 if ((t[13] != '-') || t[22] ||
1341 !(isxdigit (t[14]) && isxdigit (t[15]) && isxdigit (t[16]) &&
1342 isxdigit (t[17]) && isxdigit (t[18]) && isxdigit (t[19]) &&
1343 isxdigit (t[20]) && isxdigit (t[21]))) {
1344 sprintf (tmp,"Unable to parse message UID at %lu: %.80s",
1345 (unsigned long) curpos,(char *) LOCAL->buf);
1346 MM_LOG (tmp,ERROR);
1347 mbx_abort (stream);
1348 return NIL;
1351 *s++ = '\0'; *t++ = '\0'; /* break up fields */
1352 /* get message size */
1353 if (!(j = strtoul (s,(char **) &x,10)) && (!(x && *x))) {
1354 sprintf (tmp,"Unable to parse message size at %lu: %.80s,%.80s;%.80s",
1355 (unsigned long) curpos,(char *) LOCAL->buf,(char *) s,
1356 (char *) t);
1357 MM_LOG (tmp,ERROR);
1358 mbx_abort (stream);
1359 return NIL;
1361 /* make sure didn't run off end of file */
1362 if (((off_t) (curpos + i + j)) > sbuf.st_size) {
1363 sprintf (tmp,"Last message (at %lu) runs past end of file (%lu > %lu)",
1364 (unsigned long) curpos,(unsigned long) (curpos + i + j),
1365 (unsigned long) sbuf.st_size);
1366 MM_LOG (tmp,ERROR);
1367 mbx_abort (stream);
1368 return NIL;
1370 /* parse UID */
1371 if ((m = strtoul (t+13,NIL,16)) &&
1372 ((m <= lastuid) || (m > stream->uid_last))) {
1373 if (uidwarn) {
1374 sprintf (tmp,"Invalid UID %08lx in message %lu, rebuilding UIDs",
1375 m,nmsgs+1);
1376 MM_LOG (tmp,WARN);
1377 uidwarn = NIL;
1378 /* restart UID validity */
1379 stream->uid_validity = time (0);
1381 m = 0; /* lose this UID */
1382 dirty = T; /* mark dirty, set new lastuid */
1383 stream->uid_last = lastuid;
1386 t[12] = '\0'; /* parse system flags */
1387 if ((k = strtoul (t+8,NIL,16)) & fEXPUNGED) {
1388 if (m) lastuid = m; /* expunge message, update last UID seen */
1389 else { /* no UID assigned? */
1390 lastuid = ++stream->uid_last;
1391 dirty = T;
1394 else { /* not expunged, swell the cache */
1395 added = T; /* note that a new message was added */
1396 mail_exists (stream,++nmsgs);
1397 /* instantiate an elt for this message */
1398 (elt = mail_elt (stream,nmsgs))->valid = T;
1399 /* parse the date */
1400 if (!mail_parse_date (elt,LOCAL->buf)) {
1401 sprintf (tmp,"Unable to parse message date at %lu: %.80s",
1402 (unsigned long) curpos,(char *) LOCAL->buf);
1403 MM_LOG (tmp,ERROR);
1404 mbx_abort (stream);
1405 return NIL;
1407 /* note file offset of header */
1408 elt->private.special.offset = curpos;
1409 /* and internal header size */
1410 elt->private.special.text.size = i;
1411 /* header size not known yet */
1412 elt->private.msg.header.text.size = 0;
1413 elt->rfc822_size = j; /* note message size */
1414 /* calculate system flags */
1415 if (k & fSEEN) elt->seen = T;
1416 if (k & fDELETED) elt->deleted = T;
1417 if (k & fFLAGGED) elt->flagged = T;
1418 if (k & fANSWERED) elt->answered = T;
1419 if (k & fDRAFT) elt->draft = T;
1420 t[8] = '\0'; /* get user flags value */
1421 elt->user_flags = strtoul (t,NIL,16);
1422 /* UID already assigned? */
1423 if (!(elt->private.uid = m) || !(k & fOLD)) {
1424 elt->recent = T; /* no, mark as recent */
1425 ++recent; /* count up a new recent message */
1426 dirty = T; /* and must rewrite header */
1427 /* assign new UID */
1428 if (!elt->private.uid) elt->private.uid = ++stream->uid_last;
1429 mbx_update_status (stream,elt->msgno,NIL);
1431 /* update last parsed UID */
1432 lastuid = elt->private.uid;
1434 curpos += i + j; /* update position */
1437 if (dirty && !stream->rdonly){/* update header */
1438 mbx_update_header (stream);
1439 fsync (LOCAL->fd); /* make sure all the UID updates take */
1441 /* update parsed file size and time */
1442 LOCAL->filesize = sbuf.st_size;
1443 fstat (LOCAL->fd,&sbuf); /* get status again to ensure time is right */
1444 LOCAL->filetime = sbuf.st_mtime;
1445 if (added && !stream->rdonly){/* make sure atime updated */
1446 time_t tp[2];
1447 tp[0] = time (0);
1448 tp[1] = LOCAL->filetime;
1449 utime (stream->mailbox,tp);
1451 stream->silent = silent; /* can pass up events now */
1452 mail_exists (stream,nmsgs); /* notify upper level of new mailbox size */
1453 mail_recent (stream,recent); /* and of change in recent messages */
1454 return LONGT; /* return the winnage */
1457 /* MBX get cache element with status updating from file
1458 * Accepts: MAIL stream
1459 * message number
1460 * expunge OK flag
1461 * Returns: cache element
1464 MESSAGECACHE *mbx_elt (MAILSTREAM *stream,unsigned long msgno,long expok)
1466 MESSAGECACHE *elt = mail_elt (stream,msgno);
1467 struct { /* old flags */
1468 unsigned int seen : 1;
1469 unsigned int deleted : 1;
1470 unsigned int flagged : 1;
1471 unsigned int answered : 1;
1472 unsigned int draft : 1;
1473 unsigned long user_flags;
1474 } old;
1475 old.seen = elt->seen; old.deleted = elt->deleted; old.flagged = elt->flagged;
1476 old.answered = elt->answered; old.draft = elt->draft;
1477 old.user_flags = elt->user_flags;
1478 /* get new flags */
1479 if (mbx_read_flags (stream,elt) && expok) {
1480 mail_expunged (stream,elt->msgno);
1481 return NIL; /* return this message was expunged */
1483 if ((old.seen != elt->seen) || (old.deleted != elt->deleted) ||
1484 (old.flagged != elt->flagged) || (old.answered != elt->answered) ||
1485 (old.draft != elt->draft) || (old.user_flags != elt->user_flags))
1486 MM_FLAGS (stream,msgno); /* let top level know */
1487 return elt;
1490 /* MBX read flags from file
1491 * Accepts: MAIL stream
1492 * cache element
1493 * Returns: non-NIL if message expunged
1496 unsigned long mbx_read_flags (MAILSTREAM *stream,MESSAGECACHE *elt)
1498 unsigned long i;
1499 struct stat sbuf;
1500 fstat (LOCAL->fd,&sbuf); /* get status */
1501 /* make sure file size is good */
1502 if (sbuf.st_size < LOCAL->filesize) {
1503 sprintf (LOCAL->buf,"Mailbox shrank from %lu to %lu in flag read!",
1504 (unsigned long) LOCAL->filesize,(unsigned long) sbuf.st_size);
1505 fatal (LOCAL->buf);
1507 /* set the seek pointer */
1508 lseek (LOCAL->fd,(off_t) elt->private.special.offset +
1509 elt->private.special.text.size - 24,L_SET);
1510 /* read the new flags */
1511 if (read (LOCAL->fd,LOCAL->buf,14) < 0) {
1512 sprintf (LOCAL->buf,"Unable to read new status: %s",strerror (errno));
1513 fatal (LOCAL->buf);
1515 if ((LOCAL->buf[0] != ';') || (LOCAL->buf[13] != '-')) {
1516 LOCAL->buf[14] = '\0'; /* tie off buffer for error message */
1517 sprintf (LOCAL->buf+50,"Invalid flags for message %lu (%lu %lu): %s",
1518 elt->msgno,elt->private.special.offset,
1519 elt->private.special.text.size,(char *) LOCAL->buf);
1520 fatal (LOCAL->buf+50);
1522 LOCAL->buf[13] = '\0'; /* tie off buffer */
1523 /* calculate system flags */
1524 i = strtoul (LOCAL->buf+9,NIL,16);
1525 elt->seen = i & fSEEN ? T : NIL;
1526 elt->deleted = i & fDELETED ? T : NIL;
1527 elt->flagged = i & fFLAGGED ? T : NIL;
1528 elt->answered = i & fANSWERED ? T : NIL;
1529 elt->draft = i & fDRAFT ? T : NIL;
1530 LOCAL->expunged |= i & fEXPUNGED ? T : NIL;
1531 LOCAL->buf[9] = '\0'; /* tie off flags */
1532 /* get user flags value */
1533 elt->user_flags = strtoul (LOCAL->buf+1,NIL,16);
1534 elt->valid = T; /* have valid flags now */
1535 return i & fEXPUNGED;
1538 /* MBX update header
1539 * Accepts: MAIL stream
1542 #ifndef CYGKLUDGEOFFSET
1543 #define CYGKLUDGEOFFSET 0
1544 #endif
1546 void mbx_update_header (MAILSTREAM *stream)
1548 int i;
1549 char *s = LOCAL->buf;
1550 memset (s,'\0',HDRSIZE); /* initialize header */
1551 sprintf (s,"*mbx*\015\012%08lx%08lx\015\012",
1552 stream->uid_validity,stream->uid_last);
1553 for (i = 0; (i < NUSERFLAGS) && stream->user_flags[i]; ++i)
1554 sprintf (s += strlen (s),"%s\015\012",stream->user_flags[i]);
1555 LOCAL->ffuserflag = i; /* first free user flag */
1556 /* can we create more user flags? */
1557 stream->kwd_create = (i < NUSERFLAGS) ? T : NIL;
1558 /* write reserved lines */
1559 while (i++ < NUSERFLAGS) strcat (s,"\015\012");
1560 sprintf (LOCAL->buf + HDRSIZE - 10,"%08lx\015\012",LOCAL->lastpid);
1561 while (T) { /* rewind file */
1562 lseek (LOCAL->fd,CYGKLUDGEOFFSET,L_SET);
1563 /* write new header */
1564 if (write (LOCAL->fd,LOCAL->buf + CYGKLUDGEOFFSET,
1565 HDRSIZE - CYGKLUDGEOFFSET) > 0) break;
1566 MM_NOTIFY (stream,strerror (errno),WARN);
1567 MM_DISKERROR (stream,errno,T);
1571 /* MBX update status string
1572 * Accepts: MAIL stream
1573 * message number
1574 * flags
1577 void mbx_update_status (MAILSTREAM *stream,unsigned long msgno,long flags)
1579 struct stat sbuf;
1580 MESSAGECACHE *elt = mail_elt (stream,msgno);
1581 /* readonly */
1582 if (stream->rdonly || !elt->valid) mbx_read_flags (stream,elt);
1583 else { /* readwrite */
1584 fstat (LOCAL->fd,&sbuf); /* get status */
1585 /* make sure file size is good */
1586 if (sbuf.st_size < LOCAL->filesize) {
1587 sprintf (LOCAL->buf,"Mailbox shrank from %lu to %lu in flag update!",
1588 (unsigned long) LOCAL->filesize,(unsigned long) sbuf.st_size);
1589 fatal (LOCAL->buf);
1591 /* set the seek pointer */
1592 lseek (LOCAL->fd,(off_t) elt->private.special.offset +
1593 elt->private.special.text.size - 24,L_SET);
1594 /* read the new flags */
1595 if (read (LOCAL->fd,LOCAL->buf,14) < 0) {
1596 sprintf (LOCAL->buf,"Unable to read old status: %s",strerror (errno));
1597 fatal (LOCAL->buf);
1599 if ((LOCAL->buf[0] != ';') || (LOCAL->buf[13] != '-')) {
1600 LOCAL->buf[14] = '\0'; /* tie off buffer for error message */
1601 sprintf (LOCAL->buf+50,"Invalid flags for message %lu (%lu %lu): %s",
1602 elt->msgno,elt->private.special.offset,
1603 elt->private.special.text.size,(char *) LOCAL->buf);
1604 fatal (LOCAL->buf+50);
1606 /* print new flag string */
1607 sprintf (LOCAL->buf,"%08lx%04x-%08lx",elt->user_flags,(unsigned)
1608 (((elt->deleted && flags) ?
1609 fEXPUNGED : (strtoul (LOCAL->buf+9,NIL,16)) & fEXPUNGED) +
1610 (fSEEN * elt->seen) + (fDELETED * elt->deleted) +
1611 (fFLAGGED * elt->flagged) + (fANSWERED * elt->answered) +
1612 (fDRAFT * elt->draft) + fOLD),elt->private.uid);
1613 while (T) { /* get to that place in the file */
1614 lseek (LOCAL->fd,(off_t) elt->private.special.offset +
1615 elt->private.special.text.size - 23,L_SET);
1616 /* write new flags and UID */
1617 if (write (LOCAL->fd,LOCAL->buf,21) > 0) break;
1618 MM_NOTIFY (stream,strerror (errno),WARN);
1619 MM_DISKERROR (stream,errno,T);
1624 /* MBX locate header for a message
1625 * Accepts: MAIL stream
1626 * message number
1627 * pointer to returned header size
1628 * pointer to possible returned header
1629 * Returns: position of header in file
1632 #define HDRBUFLEN 16384 /* good enough for most headers */
1633 #define SLOP 4 /* CR LF CR LF */
1635 unsigned long mbx_hdrpos (MAILSTREAM *stream,unsigned long msgno,
1636 unsigned long *size,char **hdr)
1638 unsigned long siz,done;
1639 long i;
1640 unsigned char *s,*t,*te;
1641 MESSAGECACHE *elt = mail_elt (stream,msgno);
1642 unsigned long ret = elt->private.special.offset +
1643 elt->private.special.text.size;
1644 if (hdr) *hdr = NIL; /* assume no header returned */
1645 /* is header size known? */
1646 if (*size = elt->private.msg.header.text.size) return ret;
1647 /* paranoia check */
1648 if (LOCAL->buflen < (HDRBUFLEN + SLOP))
1649 fatal ("LOCAL->buf smaller than HDRBUFLEN");
1650 lseek (LOCAL->fd,ret,L_SET); /* get to header position */
1651 /* read HDRBUFLEN chunks with 4 byte slop */
1652 for (done = siz = 0, s = LOCAL->buf;
1653 (i = min ((long) (elt->rfc822_size - done),(long) HDRBUFLEN)) &&
1654 (read (LOCAL->fd,s,i) == i);
1655 done += i, siz += (t - LOCAL->buf) - SLOP, s = LOCAL->buf + SLOP) {
1656 te = (t = s + i) - 12; /* calculate end of fast scan */
1657 /* fast scan for CR */
1658 for (s = LOCAL->buf; s < te;)
1659 if (((*s++ == '\015') || (*s++ == '\015') || (*s++ == '\015') ||
1660 (*s++ == '\015') || (*s++ == '\015') || (*s++ == '\015') ||
1661 (*s++ == '\015') || (*s++ == '\015') || (*s++ == '\015') ||
1662 (*s++ == '\015') || (*s++ == '\015') || (*s++ == '\015')) &&
1663 (*s == '\012') && (*++s == '\015') && (*++s == '\012')) {
1664 *size = elt->private.msg.header.text.size = siz + (++s - LOCAL->buf);
1665 if (hdr) *hdr = LOCAL->buf;
1666 return ret;
1668 for (te = t - 3; (s < te);) /* final character-at-a-time scan */
1669 if ((*s++ == '\015') && (*s == '\012') && (*++s == '\015') &&
1670 (*++s == '\012')) {
1671 *size = elt->private.msg.header.text.size = siz + (++s - LOCAL->buf);
1672 if (hdr) *hdr = LOCAL->buf;
1673 return ret;
1675 if (i <= SLOP) break; /* end of data */
1676 /* slide over last 4 bytes */
1677 memmove (LOCAL->buf,t - SLOP,SLOP);
1678 hdr = NIL; /* can't return header this way */
1680 /* not found: header consumes entire message */
1681 elt->private.msg.header.text.size = *size = elt->rfc822_size;
1682 if (hdr) *hdr = LOCAL->buf; /* possibly return header too */
1683 return ret;
1686 /* MBX mail rewrite mailbox
1687 * Accepts: MAIL stream
1688 * pointer to return reclaimed size
1689 * flags (0 = no expunge, 1 = expunge deleted, -1 = expunge sequence)
1690 * Returns: number of expunged messages
1693 unsigned long mbx_rewrite (MAILSTREAM *stream,unsigned long *reclaimed,
1694 long flags)
1696 time_t tp[2];
1697 struct stat sbuf;
1698 off_t pos,ppos;
1699 int ld;
1700 unsigned long i,j,k,m,delta;
1701 unsigned long n = *reclaimed = 0;
1702 unsigned long recent = 0;
1703 char lock[MAILTMPLEN];
1704 MESSAGECACHE *elt;
1705 blocknotify_t bn = (blocknotify_t) mail_parameters (NIL,GET_BLOCKNOTIFY,NIL);
1706 /* The cretins who designed flock() created a window of vulnerability in
1707 * upgrading locks from shared to exclusive or downgrading from exclusive
1708 * to shared. Rather than maintain the lock at shared status at a minimum,
1709 * flock() actually *releases* the former lock. Obviously they never talked
1710 * to any database guys. Fortunately, we have the parse/append permission
1711 * lock. If we require this lock before going exclusive on the mailbox,
1712 * another process can not sneak in and steal the exclusive mailbox lock on
1713 * us, because it will block on trying to get parse/append permission first.
1715 /* get parse/append permission */
1716 if ((ld = lockfd (LOCAL->fd,lock,LOCK_EX)) < 0) {
1717 MM_LOG ("Unable to lock mailbox for rewrite",ERROR);
1718 return 0;
1720 fstat (LOCAL->fd,&sbuf); /* get current write time */
1721 if (LOCAL->filetime && !LOCAL->flagcheck &&
1722 (LOCAL->filetime < sbuf.st_mtime)) LOCAL->flagcheck = T;
1723 if (!mbx_parse (stream)) { /* make sure see any newly-arrived messages */
1724 unlockfd (ld,lock); /* failed?? */
1725 return 0;
1727 if (LOCAL->flagcheck) { /* sweep flags if need flagcheck */
1728 LOCAL->filetime = sbuf.st_mtime;
1729 for (i = 1; i <= stream->nmsgs; ++i) mbx_elt (stream,i,NIL);
1730 LOCAL->flagcheck = NIL;
1733 /* get exclusive access */
1734 if (!flock (LOCAL->fd,LOCK_EX|LOCK_NB)) {
1735 MM_CRITICAL (stream); /* go critical */
1736 for (i = 1,delta = 0,pos = ppos = HDRSIZE; i <= stream->nmsgs; ) {
1737 /* note if message not at predicted location */
1738 if (m = (elt = mbx_elt (stream,i,NIL))->private.special.offset - ppos) {
1739 ppos = elt->private.special.offset;
1740 *reclaimed += m; /* note reclaimed message space */
1741 delta += m; /* and as expunge delta */
1743 /* number of bytes to smash or preserve */
1744 ppos += (k = elt->private.special.text.size + elt->rfc822_size);
1745 /* if need to expunge this message*/
1746 if (flags && elt->deleted && ((flags > 0) || elt->sequence)) {
1747 delta += k; /* number of bytes to delete */
1748 mail_expunged(stream,i);/* notify upper levels */
1749 n++; /* count up one more expunged message */
1751 else { /* preserved message */
1752 i++; /* count this message */
1753 if (elt->recent) ++recent;
1754 if (delta) { /* moved, note first byte to preserve */
1755 j = elt->private.special.offset;
1756 do { /* read from source position */
1757 m = min (k,LOCAL->buflen);
1758 lseek (LOCAL->fd,j,L_SET);
1759 read (LOCAL->fd,LOCAL->buf,m);
1760 pos = j - delta; /* write to destination position */
1761 while (T) {
1762 lseek (LOCAL->fd,pos,L_SET);
1763 if (write (LOCAL->fd,LOCAL->buf,m) > 0) break;
1764 MM_NOTIFY (stream,strerror (errno),WARN);
1765 MM_DISKERROR (stream,errno,T);
1767 pos += m; /* new position */
1768 j += m; /* next chunk, perhaps */
1769 } while (k -= m); /* until done */
1770 /* note the new address of this text */
1771 elt->private.special.offset -= delta;
1773 /* preserved but no deleted messages yet */
1774 else pos = elt->private.special.offset + k;
1777 /* deltaed file size match position? */
1778 if (m = (LOCAL->filesize -= delta) - pos) {
1779 *reclaimed += m; /* probably an fEXPUNGED msg */
1780 LOCAL->filesize = pos; /* set correct size */
1782 /* truncate file after last message */
1783 ftruncate (LOCAL->fd,LOCAL->filesize);
1784 fsync (LOCAL->fd); /* force disk update */
1785 MM_NOCRITICAL (stream); /* release critical */
1786 (*bn) (BLOCK_FILELOCK,NIL);
1787 flock (LOCAL->fd,LOCK_SH); /* allow sharers again */
1788 (*bn) (BLOCK_NONE,NIL);
1791 else { /* can't get exclusive */
1792 (*bn) (BLOCK_FILELOCK,NIL);
1793 flock (LOCAL->fd,LOCK_SH); /* recover previous shared mailbox lock */
1794 (*bn) (BLOCK_NONE,NIL);
1795 /* do hide-expunge when shared */
1796 if (flags) for (i = 1; i <= stream->nmsgs; ) {
1797 if (elt = mbx_elt (stream,i,T)) {
1798 /* make the message invisible */
1799 if (elt->deleted && ((flags > 0) || elt->sequence)) {
1800 mbx_update_status (stream,elt->msgno,LONGT);
1801 /* notify upper levels */
1802 mail_expunged (stream,i);
1803 n++; /* count up one more expunged message */
1805 else {
1806 i++; /* preserved message */
1807 if (elt->recent) ++recent;
1810 else n++; /* count up one more expunged message */
1812 fsync (LOCAL->fd); /* force disk update */
1814 fstat (LOCAL->fd,&sbuf); /* get new write time */
1815 tp[1] = LOCAL->filetime = sbuf.st_mtime;
1816 tp[0] = time (0); /* reset atime to now */
1817 utime (stream->mailbox,tp);
1818 unlockfd (ld,lock); /* release exclusive parse/append permission */
1819 /* notify upper level of new mailbox size */
1820 mail_exists (stream,stream->nmsgs);
1821 mail_recent (stream,recent);
1822 return n; /* return number of expunged messages */
1825 /* MBX mail lock for flag updating
1826 * Accepts: stream
1827 * Returns: T if successful, NIL if failure
1830 long mbx_flaglock (MAILSTREAM *stream)
1832 struct stat sbuf;
1833 unsigned long i;
1834 int ld;
1835 char lock[MAILTMPLEN];
1836 /* no-op if readonly or already locked */
1837 if (!stream->rdonly && LOCAL && (LOCAL->fd >= 0) && (LOCAL->ld < 0)) {
1838 /* lock now */
1839 if ((ld = lockfd (LOCAL->fd,lock,LOCK_EX)) < 0) return NIL;
1840 if (!LOCAL->flagcheck) { /* don't do this if flagcheck already needed */
1841 if (LOCAL->filetime) { /* know previous time? */
1842 fstat (LOCAL->fd,&sbuf);/* get current write time */
1843 if (LOCAL->filetime < sbuf.st_mtime) LOCAL->flagcheck = T;
1844 LOCAL->filetime = 0; /* don't do this test for any other messages */
1846 if (!mbx_parse (stream)) {/* parse mailbox */
1847 unlockfd (ld,lock); /* shouldn't happen */
1848 return NIL;
1850 if (LOCAL->flagcheck) /* invalidate cache if flagcheck */
1851 for (i = 1; i <= stream->nmsgs; ++i) mail_elt (stream,i)->valid = NIL;
1853 LOCAL->ld = ld; /* copy to stream for subsequent calls */
1854 memcpy (LOCAL->lock,lock,MAILTMPLEN);
1856 return LONGT;