imapext-2007

view src/osdep/os2/mbxnt.c @ 0:ada5e610ab86

imap-2007e
author yuuji@gentei.org
date Mon, 14 Sep 2009 15:17:45 +0900
parents
children
line source
1 /* ========================================================================
2 * Copyright 1988-2007 University of Washington
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 *
11 * ========================================================================
12 */
14 /*
15 * Program: MBX mail routines
16 *
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
24 *
25 * Date: 3 October 1995
26 * Last Edited: 28 September 2007
27 */
30 /* FILE TIME SEMANTICS
31 *
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.
35 */
37 #include <stdio.h>
38 #include <ctype.h>
39 #include <errno.h>
40 extern int errno; /* just in case */
41 #include "mail.h"
42 #include "osdep.h"
43 #include <fcntl.h>
44 #include <time.h>
45 #include <sys/stat.h>
46 #include <sys/utime.h>
47 #include "misc.h"
48 #include "dummy.h"
49 #include "fdstring.h"
52 /* Build parameters */
54 #define HDRSIZE 2048
56 /* MBX I/O stream local data */
58 typedef struct mbx_local {
59 unsigned int flagcheck: 1; /* if ping should sweep for flags */
60 unsigned int expok: 1; /* if expunging OK in ping */
61 unsigned int expunged : 1; /* if one or more expunged messages */
62 int fd; /* file descriptor for I/O */
63 int ld; /* lock file descriptor */
64 int ffuserflag; /* first free user flag */
65 off_t filesize; /* file size parsed */
66 time_t filetime; /* last file time */
67 time_t lastsnarf; /* last snarf time */
68 unsigned char *buf; /* temporary buffer */
69 unsigned long buflen; /* current size of temporary buffer */
70 char lock[MAILTMPLEN]; /* buffer to write lock name */
71 } MBXLOCAL;
74 /* Convenient access to local data */
76 #define LOCAL ((MBXLOCAL *) stream->local)
78 /* Function prototypes */
80 DRIVER *mbx_valid (char *name);
81 int mbx_isvalid (MAILSTREAM **stream,char *name,char *file,int *ld,char *lock,
82 long flags);
83 void *mbx_parameters (long function,void *value);
84 void mbx_scan (MAILSTREAM *stream,char *ref,char *pat,char *contents);
85 void mbx_list (MAILSTREAM *stream,char *ref,char *pat);
86 void mbx_lsub (MAILSTREAM *stream,char *ref,char *pat);
87 long mbx_create (MAILSTREAM *stream,char *mailbox);
88 long mbx_delete (MAILSTREAM *stream,char *mailbox);
89 long mbx_rename (MAILSTREAM *stream,char *old,char *newname);
90 long mbx_status (MAILSTREAM *stream,char *mbx,long flags);
91 MAILSTREAM *mbx_open (MAILSTREAM *stream);
92 void mbx_close (MAILSTREAM *stream,long options);
93 void mbx_abort (MAILSTREAM *stream);
94 void mbx_flags (MAILSTREAM *stream,char *sequence,long flags);
95 char *mbx_header (MAILSTREAM *stream,unsigned long msgno,unsigned long *length,
96 long flags);
97 long mbx_text (MAILSTREAM *stream,unsigned long msgno,STRING *bs,long flags);
98 void mbx_flag (MAILSTREAM *stream,char *sequence,char *flag,long flags);
99 void mbx_flagmsg (MAILSTREAM *stream,MESSAGECACHE *elt);
100 long mbx_ping (MAILSTREAM *stream);
101 void mbx_check (MAILSTREAM *stream);
102 long mbx_expunge (MAILSTREAM *stream,char *sequence,long options);
103 void mbx_snarf (MAILSTREAM *stream);
104 long mbx_copy (MAILSTREAM *stream,char *sequence,char *mailbox,long options);
105 long mbx_append (MAILSTREAM *stream,char *mailbox,append_t af,void *data);
107 long mbx_parse (MAILSTREAM *stream);
108 MESSAGECACHE *mbx_elt (MAILSTREAM *stream,unsigned long msgno,long expok);
109 unsigned long mbx_read_flags (MAILSTREAM *stream,MESSAGECACHE *elt);
110 void mbx_update_header (MAILSTREAM *stream);
111 void mbx_update_status (MAILSTREAM *stream,unsigned long msgno,long flags);
112 unsigned long mbx_hdrpos (MAILSTREAM *stream,unsigned long msgno,
113 unsigned long *size,char **hdr);
114 unsigned long mbx_rewrite (MAILSTREAM *stream,unsigned long *reclaimed,
115 long flags);
116 long mbx_flaglock (MAILSTREAM *stream);
118 /* MBX mail routines */
121 /* Driver dispatch used by MAIL */
123 DRIVER mbxdriver = {
124 "mbx", /* driver name */
125 DR_LOCAL|DR_MAIL|DR_CRLF|DR_LOCKING,
126 /* driver flags */
127 (DRIVER *) NIL, /* next driver */
128 mbx_valid, /* mailbox is valid for us */
129 mbx_parameters, /* manipulate parameters */
130 mbx_scan, /* scan mailboxes */
131 mbx_list, /* list mailboxes */
132 mbx_lsub, /* list subscribed mailboxes */
133 NIL, /* subscribe to mailbox */
134 NIL, /* unsubscribe from mailbox */
135 mbx_create, /* create mailbox */
136 mbx_delete, /* delete mailbox */
137 mbx_rename, /* rename mailbox */
138 mail_status_default, /* status of mailbox */
139 mbx_open, /* open mailbox */
140 mbx_close, /* close mailbox */
141 mbx_flags, /* fetch message "fast" attributes */
142 mbx_flags, /* fetch message flags */
143 NIL, /* fetch overview */
144 NIL, /* fetch message envelopes */
145 mbx_header, /* fetch message header */
146 mbx_text, /* fetch message body */
147 NIL, /* fetch partial message text */
148 NIL, /* unique identifier */
149 NIL, /* message number */
150 mbx_flag, /* modify flags */
151 mbx_flagmsg, /* per-message modify flags */
152 NIL, /* search for message based on criteria */
153 NIL, /* sort messages */
154 NIL, /* thread messages */
155 mbx_ping, /* ping mailbox to see if still alive */
156 mbx_check, /* check for new messages */
157 mbx_expunge, /* expunge deleted messages */
158 mbx_copy, /* copy messages to another mailbox */
159 mbx_append, /* append string message to mailbox */
160 NIL /* garbage collect stream */
161 };
163 /* prototype stream */
164 MAILSTREAM mbxproto = {&mbxdriver};
166 /* MBX mail validate mailbox
167 * Accepts: mailbox name
168 * Returns: our driver if name is valid, NIL otherwise
169 */
171 DRIVER *mbx_valid (char *name)
172 {
173 char tmp[MAILTMPLEN];
174 int fd = mbx_isvalid (NIL,name,tmp,NIL,NIL,NIL);
175 if (fd < 0) return NIL;
176 close (fd); /* don't need the fd now */
177 return &mbxdriver;
178 }
181 /* MBX mail test for valid mailbox
182 * Accepts: returned stream with valid mailbox keywords
183 * mailbox name
184 * buffer to write file name
185 * returned lock fd
186 * returned lock name
187 * RW flags or NIL for readonly
188 * Returns: file descriptor if valid, NIL otherwise
189 */
191 #define MBXISVALIDNOUID 0x1 /* RW, don't do UID action */
192 #define MBXISVALIDUID 0x2 /* RW, do UID action */
194 int mbx_isvalid (MAILSTREAM **stream,char *name,char *file,int *ld,char *lock,
195 long flags)
196 {
197 int fd,upd;
198 int ret = -1;
199 unsigned long i;
200 long j,k;
201 off_t pos;
202 char c,*s,*t,hdr[HDRSIZE];
203 struct stat sbuf;
204 struct utimbuf times;
205 int error = EINVAL; /* assume invalid argument */
206 if (ld) *ld = -1; /* initially no lock */
207 /* if file, get its status */
208 if ((s = dummy_file (file,name)) && !stat (s,&sbuf) &&
209 ((sbuf.st_mode & S_IFMT) == S_IFREG) &&
210 ((fd = open (file,(flags ? O_RDWR : O_RDONLY)|O_BINARY,NIL)) >= 0)) {
211 error = -1; /* assume bogus format */
212 if (((((j = read (fd,hdr,HDRSIZE)) == HDRSIZE) && (hdr[0] == '*')) ||
213 /* locked, set byte 0 to "*", read rest */
214 ((j < 0) && (lseek (fd,1,L_SET) == 1) &&
215 (read (fd,hdr+1,HDRSIZE-1) == (HDRSIZE-1)) && (hdr[0] = '*'))) &&
216 (hdr[1] == 'm') && (hdr[2] == 'b') && (hdr[3] == 'x') &&
217 (hdr[4] == '*') && (hdr[5] == '\015') && (hdr[6] == '\012') &&
218 isxdigit (hdr[7]) && isxdigit (hdr[8]) && isxdigit (hdr[9]) &&
219 isxdigit (hdr[10]) && isxdigit (hdr[11]) && isxdigit (hdr[12]) &&
220 isxdigit (hdr[13]) && isxdigit (hdr[14]) && isxdigit (c = hdr[15]) &&
221 isxdigit (hdr[16]) && isxdigit (hdr[17]) && isxdigit (hdr[18]) &&
222 isxdigit (hdr[19]) && isxdigit (hdr[20]) && isxdigit (hdr[21]) &&
223 isxdigit (hdr[22]) && (hdr[23] == '\015') && (hdr[24] == '\012')) {
224 ret = fd; /* mbx format */
226 if (stream) { /* lock if making a mini-stream */
227 if (flock (fd,LOCK_SH) ||
228 (flags && ((*ld = lockname (lock,file,LOCK_EX)) < 0))) ret = -1;
229 /* reread data now that locked */
230 else if (lseek (fd,0,L_SET) ||
231 (read (fd,hdr+1,HDRSIZE-1) != (HDRSIZE-1))) ret = -1;
232 else {
233 *stream = (MAILSTREAM *) memset (fs_get (sizeof (MAILSTREAM)),0,
234 sizeof (MAILSTREAM));
235 hdr[15] = '\0'; /* tie off UIDVALIDITY */
236 (*stream)->uid_validity = strtoul (hdr+7,NIL,16);
237 hdr[15] = c; /* now get UIDLAST */
238 (*stream)->uid_last = strtoul (hdr+15,NIL,16);
239 /* parse user flags */
240 for (i = 0, s = hdr + 25;
241 (i < NUSERFLAGS) && (t = strchr (s,'\015')) && (t - s);
242 i++, s = t + 2) {
243 *t = '\0'; /* tie off flag */
244 if (strlen (s) <= MAXUSERFLAG)
245 (*stream)->user_flags[i] = cpystr (s);
246 }
247 /* make sure have true UIDLAST */
248 if (flags & MBXISVALIDUID) {
249 for (upd = NIL,pos = 2048, k = 0; pos < sbuf.st_size;
250 pos += (j + k)) {
251 /* read header for this message */
252 lseek (fd,pos,L_SET);
253 if ((j = read (fd,hdr,64)) >= 0) {
254 hdr[j] = '\0';
255 if ((s = strchr (hdr,'\015')) && (s[1] == '\012')) {
256 *s = '\0';
257 k = s + 2 - hdr;
258 if ((s = strchr (hdr,',')) && (j = strtol (s+1,&s,10)) &&
259 (*s == ';') && (s = strchr (s+1,'-'))) {
260 /* get UID if there is any */
261 i = strtoul (++s,&t,16);
262 if (!*t && (t == (s + 8)) && (i <= (*stream)->uid_last)) {
263 if (!i) {
264 lseek (fd,pos + s - hdr,L_SET);
265 sprintf (hdr,"%08lx",++(*stream)->uid_last);
266 write (fd,hdr,8);
267 upd = T;
268 }
269 continue;
270 }
271 }
272 }
273 ret = -1; /* error, give up */
274 *stream = mail_close (*stream);
275 pos = sbuf.st_size + 1;
276 j = k = 0;
277 }
278 }
280 if (upd) { /* need to update hdr with new UIDLAST? */
281 lseek (fd,15,L_SET);
282 sprintf (hdr,"%08lx",(*stream)->uid_last);
283 write (fd,hdr,8);
284 }
285 }
286 }
287 }
288 }
289 if (ret != fd) close (fd); /* close the file */
290 else lseek (fd,0,L_SET); /* else rewind to start */
291 /* \Marked status? */
292 if (sbuf.st_ctime > sbuf.st_atime) {
293 /* preserve atime and mtime */
294 times.actime = sbuf.st_atime;
295 times.modtime = sbuf.st_mtime;
296 utime (file,&times); /* set the times */
297 }
298 }
299 /* in case INBOX but not mbx format */
300 else if (((error = errno) == ENOENT) && !compare_cstring (name,"INBOX"))
301 error = -1;
302 if ((ret < 0) && ld && (*ld >= 0)) {
303 unlockfd (*ld,lock);
304 *ld = -1;
305 }
306 errno = error; /* return as last error */
307 return ret; /* return what we should */
308 }
310 /* MBX manipulate driver parameters
311 * Accepts: function code
312 * function-dependent value
313 * Returns: function-dependent return value
314 */
316 void *mbx_parameters (long function,void *value)
317 {
318 void *ret = NIL;
319 switch ((int) function) {
320 case SET_ONETIMEEXPUNGEATPING:
321 if (value) ((MBXLOCAL *) ((MAILSTREAM *) value)->local)->expok = T;
322 case GET_ONETIMEEXPUNGEATPING:
323 if (value) ret = (void *)
324 (((MBXLOCAL *) ((MAILSTREAM *) value)->local)->expok ? VOIDT : NIL);
325 break;
326 }
327 return ret;
328 }
331 /* MBX mail scan mailboxes
332 * Accepts: mail stream
333 * reference
334 * pattern to search
335 * string to scan
336 */
338 void mbx_scan (MAILSTREAM *stream,char *ref,char *pat,char *contents)
339 {
340 if (stream) dummy_scan (NIL,ref,pat,contents);
341 }
344 /* MBX mail list mailboxes
345 * Accepts: mail stream
346 * reference
347 * pattern to search
348 */
350 void mbx_list (MAILSTREAM *stream,char *ref,char *pat)
351 {
352 if (stream) dummy_list (NIL,ref,pat);
353 }
356 /* MBX mail list subscribed mailboxes
357 * Accepts: mail stream
358 * reference
359 * pattern to search
360 */
362 void mbx_lsub (MAILSTREAM *stream,char *ref,char *pat)
363 {
364 if (stream) dummy_lsub (NIL,ref,pat);
365 }
367 /* MBX mail create mailbox
368 * Accepts: MAIL stream
369 * mailbox name to create
370 * Returns: T on success, NIL on failure
371 */
373 long mbx_create (MAILSTREAM *stream,char *mailbox)
374 {
375 char *s,mbx[MAILTMPLEN],tmp[HDRSIZE];
376 long ret = NIL;
377 int i,fd;
378 if (!(s = dummy_file (mbx,mailbox))) {
379 sprintf (mbx,"Can't create %.80s: invalid name",mailbox);
380 mm_log (mbx,ERROR);
381 }
382 /* create underlying file */
383 else if (dummy_create (stream,s)) {
384 /* done if made directory */
385 if ((s = strrchr (s,'\\')) && !s[1]) return T;
386 if ((fd = open (mbx,O_WRONLY|O_BINARY,NIL)) < 0) {
387 sprintf (tmp,"Can't reopen mailbox node %.80s: %s",mbx,strerror (errno));
388 mm_log (tmp,ERROR);
389 unlink (mbx); /* delete the file */
390 }
391 else {
392 memset (tmp,'\0',HDRSIZE);/* initialize header */
393 sprintf (s = tmp,"*mbx*\015\012%08lx00000000\015\012",
394 (unsigned long) time (0));
395 for (i = 0; i < NUSERFLAGS; ++i)
396 sprintf (s += strlen (s),"%s\015\012",
397 (stream && stream->user_flags[i]) ? stream->user_flags[i] :
398 "");
399 if (write (fd,tmp,HDRSIZE) != HDRSIZE) {
400 sprintf (tmp,"Can't initialize mailbox node %.80s: %s",
401 mbx,strerror (errno));
402 mm_log (tmp,ERROR);
403 unlink (mbx); /* delete the file */
404 }
405 else ret = T; /* success */
406 close (fd); /* close file */
407 }
408 }
409 return ret;
410 }
413 /* MBX mail delete mailbox
414 * Accepts: MAIL stream
415 * mailbox name to delete
416 * Returns: T on success, NIL on failure
417 */
419 long mbx_delete (MAILSTREAM *stream,char *mailbox)
420 {
421 return mbx_rename (stream,mailbox,NIL);
422 }
424 /* MBX mail rename mailbox
425 * Accepts: MAIL stream
426 * old mailbox name
427 * new mailbox name (or NIL for delete)
428 * Returns: T on success, NIL on failure
429 */
431 long mbx_rename (MAILSTREAM *stream,char *old,char *newname)
432 {
433 long ret = LONGT;
434 char c,*s,tmp[MAILTMPLEN],file[MAILTMPLEN],lock[MAILTMPLEN];
435 int fd,ld;
436 struct stat sbuf;
437 if (!dummy_file (file,old) ||
438 (newname && (!((s = mailboxfile (tmp,newname)) && *s) ||
439 ((s = strrchr (tmp,'\\')) && !s[1])))) {
440 sprintf (tmp,newname ?
441 "Can't rename mailbox %.80s to %.80s: invalid name" :
442 "Can't delete mailbox %.80s: invalid name",
443 old,newname);
444 mm_log (tmp,ERROR);
445 return NIL;
446 }
447 else if ((fd = open (file,O_RDWR|O_BINARY,NIL)) < 0) {
448 sprintf (tmp,"Can't open mailbox %.80s: %s",old,strerror (errno));
449 mm_log (tmp,ERROR);
450 return NIL;
451 }
452 /* get parse/append permission */
453 if ((ld = lockname (lock,file,LOCK_EX)) < 0) {
454 mm_log ("Unable to lock rename mailbox",ERROR);
455 return NIL;
456 }
457 /* lock out other users */
458 if (flock (fd,LOCK_EX|LOCK_NB)) {
459 close (fd); /* couldn't lock, give up on it then */
460 sprintf (tmp,"Mailbox %.80s is in use by another process",old);
461 mm_log (tmp,ERROR);
462 unlockfd (ld,lock); /* release exclusive parse/append permission */
463 return NIL;
464 }
466 if (newname) { /* want rename? */
467 /* found superior to destination name? */
468 if ((s = strrchr (tmp,'\\')) && (s != tmp) &&
469 ((tmp[1] != ':') || (s != tmp + 2))) {
470 c = s[1]; /* remember character after delimiter */
471 *s = s[1] = '\0'; /* tie off name at delimiter */
472 /* name doesn't exist, create it */
473 if (stat (tmp,&sbuf) || ((sbuf.st_mode & S_IFMT) != S_IFDIR)) {
474 *s = '\\'; /* restore delimiter */
475 if (!dummy_create (stream,tmp)) ret = NIL;
476 }
477 else *s = '\\'; /* restore delimiter */
478 s[1] = c; /* restore character after delimiter */
479 }
480 flock (fd,LOCK_UN); /* release lock on the file */
481 close (fd); /* pacify NTFS */
482 /* rename the file */
483 if (ret && rename (file,tmp)) {
484 sprintf (tmp,"Can't rename mailbox %.80s to %.80s: %s",old,newname,
485 strerror (errno));
486 mm_log (tmp,ERROR);
487 ret = NIL; /* set failure */
488 }
489 }
490 else {
491 flock (fd,LOCK_UN); /* release lock on the file */
492 close (fd); /* pacify NTFS */
493 if (unlink (file)) {
494 sprintf (tmp,"Can't delete mailbox %.80s: %s",old,strerror (errno));
495 mm_log (tmp,ERROR);
496 ret = NIL; /* set failure */
497 }
498 }
499 unlockfd (ld,lock); /* release exclusive parse/append permission */
500 /* recreate file if renamed INBOX */
501 if (ret && !compare_cstring (old,"INBOX")) mbx_create (NIL,"INBOX");
502 return ret; /* return success */
503 }
505 /* MBX mail open
506 * Accepts: stream to open
507 * Returns: stream on success, NIL on failure
508 */
510 MAILSTREAM *mbx_open (MAILSTREAM *stream)
511 {
512 int fd,ld;
513 short silent;
514 char tmp[MAILTMPLEN];
515 if (!stream) return &mbxproto;/* return prototype for OP_PROTOTYPE call */
516 if (stream->local) fatal ("mbx recycle stream");
517 /* canonicalize the mailbox name */
518 if (!dummy_file (tmp,stream->mailbox)) {
519 sprintf (tmp,"Can't open - invalid name: %.80s",stream->mailbox);
520 mm_log (tmp,ERROR);
521 }
522 if (stream->rdonly ||
523 (fd = open (tmp,O_RDWR|O_BINARY,NIL)) < 0) {
524 if ((fd = open (tmp,O_RDONLY|O_BINARY,NIL)) < 0) {
525 sprintf (tmp,"Can't open mailbox: %s",strerror (errno));
526 mm_log (tmp,ERROR);
527 return NIL;
528 }
529 else if (!stream->rdonly) { /* got it, but readonly */
530 mm_log ("Can't get write access to mailbox, access is readonly",WARN);
531 stream->rdonly = T;
532 }
533 }
535 stream->local = memset (fs_get (sizeof (MBXLOCAL)),NIL,sizeof (MBXLOCAL));
536 LOCAL->fd = fd; /* bind the file */
537 LOCAL->ld = -1; /* no flaglock */
538 LOCAL->buf = (char *) fs_get (CHUNKSIZE);
539 LOCAL->buflen = CHUNKSIZE - 1;
540 /* note if an INBOX or not */
541 stream->inbox = !compare_cstring (stream->mailbox,"INBOX");
542 fs_give ((void **) &stream->mailbox);
543 stream->mailbox = cpystr (tmp);
544 /* get parse/append permission */
545 if ((ld = lockname (tmp,stream->mailbox,LOCK_EX)) < 0) {
546 mm_log ("Unable to lock open mailbox",ERROR);
547 return NIL;
548 }
549 flock (LOCAL->fd,LOCK_SH); /* lock the file */
550 unlockfd (ld,tmp); /* release shared parse permission */
551 LOCAL->filesize = HDRSIZE; /* initialize parsed file size */
552 LOCAL->filetime = 0; /* time not set up yet */
553 LOCAL->expok = LOCAL->flagcheck = NIL;
554 stream->sequence++; /* bump sequence number */
555 /* parse mailbox */
556 stream->nmsgs = stream->recent = 0;
557 silent = stream->silent; /* defer events */
558 stream->silent = T;
559 if (mbx_ping (stream) && !stream->nmsgs)
560 mm_log ("Mailbox is empty",(long) NIL);
561 stream->silent = silent; /* now notify upper level */
562 mail_exists (stream,stream->nmsgs);
563 mail_recent (stream,stream->recent);
564 if (!LOCAL) return NIL; /* failure if stream died */
565 stream->perm_seen = stream->perm_deleted = stream->perm_flagged =
566 stream->perm_answered = stream->perm_draft = stream->rdonly ? NIL : T;
567 stream->perm_user_flags = stream->rdonly ? NIL : 0xffffffff;
568 stream->kwd_create = (stream->user_flags[NUSERFLAGS-1] || stream->rdonly) ?
569 NIL : T; /* can we create new user flags? */
570 return stream; /* return stream to caller */
571 }
573 /* MBX mail close
574 * Accepts: MAIL stream
575 * close options
576 */
578 void mbx_close (MAILSTREAM *stream,long options)
579 {
580 if (stream && LOCAL) { /* only if a file is open */
581 int silent = stream->silent;
582 stream->silent = T; /* note this stream is dying */
583 /* do an expunge if requested */
584 if (options & CL_EXPUNGE) mbx_expunge (stream,NIL,NIL);
585 else { /* otherwise do a checkpoint to purge */
586 LOCAL->expok = T; /* possible expunged messages */
587 mbx_ping (stream);
588 }
589 stream->silent = silent; /* restore previous status */
590 mbx_abort (stream);
591 }
592 }
595 /* MBX mail abort stream
596 * Accepts: MAIL stream
597 */
599 void mbx_abort (MAILSTREAM *stream)
600 {
601 if (stream && LOCAL) { /* only if a file is open */
602 flock (LOCAL->fd,LOCK_UN); /* unlock local file */
603 close (LOCAL->fd); /* close the local file */
604 /* free local text buffer */
605 if (LOCAL->buf) fs_give ((void **) &LOCAL->buf);
606 /* nuke the local data */
607 fs_give ((void **) &stream->local);
608 stream->dtb = NIL; /* log out the DTB */
609 }
610 }
613 /* MBX mail fetch flags
614 * Accepts: MAIL stream
615 * sequence
616 * option flags
617 * Sniffs at file to see if some other process changed the flags
618 */
620 void mbx_flags (MAILSTREAM *stream,char *sequence,long flags)
621 {
622 MESSAGECACHE *elt;
623 unsigned long i;
624 if (mbx_ping (stream) && /* ping mailbox, get new status for messages */
625 ((flags & FT_UID) ? mail_uid_sequence (stream,sequence) :
626 mail_sequence (stream,sequence)))
627 for (i = 1; i <= stream->nmsgs; i++)
628 if ((elt = mail_elt (stream,i))->sequence && !elt->valid)
629 mbx_elt (stream,i,NIL);
630 }
632 /* MBX mail fetch message header
633 * Accepts: MAIL stream
634 * message # to fetch
635 * pointer to returned header text length
636 * option flags
637 * Returns: message header in RFC822 format
638 */
640 char *mbx_header (MAILSTREAM *stream,unsigned long msgno,unsigned long *length,
641 long flags)
642 {
643 unsigned long i;
644 char *s;
645 *length = 0; /* default to empty */
646 if (flags & FT_UID) return "";/* UID call "impossible" */
647 /* get header position, possibly header */
648 i = mbx_hdrpos (stream,msgno,length,&s);
649 if (!s) { /* mbx_hdrpos() returned header? */
650 lseek (LOCAL->fd,i,L_SET); /* no, get to header position */
651 /* is buffer big enough? */
652 if (*length > LOCAL->buflen) {
653 fs_give ((void **) &LOCAL->buf);
654 LOCAL->buf = (char *) fs_get ((LOCAL->buflen = *length) + 1);
655 }
656 /* slurp the data */
657 read (LOCAL->fd,s = LOCAL->buf,*length);
658 }
659 s[*length] = '\0'; /* tie off string */
660 return s;
661 }
663 /* MBX mail fetch message text (body only)
664 * Accepts: MAIL stream
665 * message # to fetch
666 * pointer to returned header text length
667 * option flags
668 * Returns: T on success, NIL on failure
669 */
671 long mbx_text (MAILSTREAM *stream,unsigned long msgno,STRING *bs,long flags)
672 {
673 FDDATA d;
674 unsigned long i,j;
675 MESSAGECACHE *elt;
676 /* UID call "impossible" */
677 if (flags & FT_UID) return NIL;
678 /* get message status */
679 elt = mbx_elt (stream,msgno,NIL);
680 /* if message not seen */
681 if (!(flags & FT_PEEK) && !elt->seen && mbx_flaglock (stream)) {
682 elt->seen = T; /* mark message as seen */
683 /* recalculate status */
684 mbx_update_status (stream,msgno,NIL);
685 mm_flags (stream,msgno);
686 /* update flags */
687 mbx_flag (stream,NIL,NIL,NIL);
688 }
689 if (!LOCAL) return NIL; /* mbx_flaglock() could have aborted */
690 /* find header position */
691 i = mbx_hdrpos (stream,msgno,&j,NIL);
692 d.fd = LOCAL->fd; /* set up file descriptor */
693 d.pos = i + j;
694 d.chunk = LOCAL->buf; /* initial buffer chunk */
695 d.chunksize = CHUNKSIZE;
696 INIT (bs,fd_string,&d,elt->rfc822_size - j);
697 return LONGT; /* success */
698 }
700 /* MBX mail modify flags
701 * Accepts: MAIL stream
702 * sequence
703 * flag(s)
704 * option flags
705 * Unlocks flag lock
706 */
708 void mbx_flag (MAILSTREAM *stream,char *sequence,char *flag,long flags)
709 {
710 struct utimbuf times;
711 struct stat sbuf;
712 /* make sure the update takes */
713 if (!stream->rdonly && LOCAL && (LOCAL->fd >= 0) && (LOCAL->ld >= 0)) {
714 fsync (LOCAL->fd);
715 fstat (LOCAL->fd,&sbuf); /* get current write time */
716 times.modtime = LOCAL->filetime = sbuf.st_mtime;
717 /* update header */
718 if ((LOCAL->ffuserflag < NUSERFLAGS) &&
719 stream->user_flags[LOCAL->ffuserflag]) mbx_update_header (stream);
720 times.actime = time (0); /* make sure read comes after all that */
721 utime (stream->mailbox,&times);
722 }
723 if (LOCAL->ld >= 0) { /* unlock now */
724 unlockfd (LOCAL->ld,LOCAL->lock);
725 LOCAL->ld = -1;
726 }
727 }
730 /* MBX mail per-message modify flags
731 * Accepts: MAIL stream
732 * message cache element
733 */
735 void mbx_flagmsg (MAILSTREAM *stream,MESSAGECACHE *elt)
736 {
737 if (mbx_flaglock (stream)) mbx_update_status (stream,elt->msgno,NIL);
738 }
740 /* MBX mail ping mailbox
741 * Accepts: MAIL stream
742 * Returns: T if stream still alive, NIL if not
743 */
745 long mbx_ping (MAILSTREAM *stream)
746 {
747 unsigned long i,pos;
748 long ret = NIL;
749 int ld;
750 char lock[MAILTMPLEN];
751 MESSAGECACHE *elt;
752 struct stat sbuf;
753 if (stream && LOCAL) { /* only if stream already open */
754 ret = LONGT; /* assume OK */
755 fstat (LOCAL->fd,&sbuf); /* get current file poop */
756 /* allow expunge if permitted at ping */
757 if (mail_parameters (NIL,GET_EXPUNGEATPING,NIL)) LOCAL->expok = T;
758 /* if external modification */
759 if (LOCAL->filetime && (LOCAL->filetime < sbuf.st_mtime))
760 LOCAL->flagcheck = T; /* upgrade to flag checking */
761 /* new mail or flagcheck handling needed? */
762 if (((sbuf.st_size - LOCAL->filesize) || LOCAL->flagcheck ||
763 !stream->nmsgs) &&
764 ((ld = lockname (lock,stream->mailbox,LOCK_EX)) >= 0)) {
765 if (!LOCAL->flagcheck) ret = mbx_parse (stream);
766 /* sweep mailbox for changed message status */
767 else if (ret = mbx_parse (stream)) {
768 unsigned long recent = 0;
769 LOCAL->filetime = sbuf.st_mtime;
770 for (i = 1; i <= stream->nmsgs; )
771 if (elt = mbx_elt (stream,i,LOCAL->expok)) {
772 if (elt->recent) ++recent;
773 ++i;
774 }
775 mail_recent (stream,recent);
776 LOCAL->flagcheck = NIL; /* got all the updates */
777 }
778 unlockfd (ld,lock); /* release shared parse/append permission */
779 }
780 if (ret) { /* must still be alive */
781 if (!LOCAL->expunged) /* look for holes if none known yet */
782 for (i = 1, pos = HDRSIZE;
783 !LOCAL->expunged && (i <= stream->nmsgs);
784 i++, pos += elt->private.special.text.size + elt->rfc822_size)
785 if ((elt = mail_elt (stream,i))->private.special.offset != pos)
786 LOCAL->expunged = T;/* found a hole */
787 /* burp any holes */
788 if (LOCAL->expunged && !stream->rdonly) {
789 if (mbx_rewrite (stream,&i,NIL)) fatal ("expunge on check");
790 if (i) { /* any space reclaimed? */
791 LOCAL->expunged = NIL;/* no more pending expunge */
792 sprintf (LOCAL->buf,"Reclaimed %lu bytes of expunged space",i);
793 mm_log (LOCAL->buf,(long) NIL);
794 }
795 }
796 LOCAL->expok = NIL; /* no more expok */
797 }
798 }
799 return ret; /* return result of the parse */
800 }
802 /* MBX mail check mailbox (reparses status too)
803 * Accepts: MAIL stream
804 */
806 void mbx_check (MAILSTREAM *stream)
807 {
808 if (LOCAL) LOCAL->expok = T; /* mark that a check is desired */
809 if (mbx_ping (stream)) mm_log ("Check completed",(long) NIL);
810 }
813 /* MBX mail expunge mailbox
814 * Accepts: MAIL stream
815 * sequence to expunge if non-NIL
816 * expunge options
817 * Returns: T if success, NIL if failure
818 */
820 long mbx_expunge (MAILSTREAM *stream,char *sequence,long options)
821 {
822 long ret;
823 unsigned long nexp,reclaimed;
824 if (ret = sequence ? ((options & EX_UID) ?
825 mail_uid_sequence (stream,sequence) :
826 mail_sequence (stream,sequence)) : LONGT) {
827 if (!mbx_ping (stream)); /* do nothing if stream dead */
828 else if (stream->rdonly) /* won't do on readonly files! */
829 mm_log ("Expunge ignored on readonly mailbox",WARN);
830 /* if expunged any messages */
831 else if (nexp = mbx_rewrite (stream,&reclaimed,sequence ? -1 : 1)) {
832 sprintf (LOCAL->buf,"Expunged %lu messages",nexp);
833 mm_log (LOCAL->buf,(long) NIL);
834 }
835 else if (reclaimed) { /* or if any prior expunged space reclaimed */
836 sprintf (LOCAL->buf,"Reclaimed %lu bytes of expunged space",reclaimed);
837 mm_log (LOCAL->buf,(long) NIL);
838 }
839 else mm_log ("No messages deleted, so no update needed",(long) NIL);
840 }
841 return ret;
842 }
844 /* MBX mail copy message(s)
845 * Accepts: MAIL stream
846 * sequence
847 * destination mailbox
848 * copy options
849 * Returns: T if success, NIL if failed
850 */
852 long mbx_copy (MAILSTREAM *stream,char *sequence,char *mailbox,long options)
853 {
854 struct stat sbuf;
855 struct utimbuf times;
856 MESSAGECACHE *elt;
857 unsigned long i,j,k,m;
858 long ret = LONGT;
859 int fd,ld;
860 char *s,*t,file[MAILTMPLEN],lock[MAILTMPLEN];
861 mailproxycopy_t pc =
862 (mailproxycopy_t) mail_parameters (stream,GET_MAILPROXYCOPY,NIL);
863 copyuid_t cu = (copyuid_t) mail_parameters (NIL,GET_COPYUID,NIL);
864 SEARCHSET *source = cu ? mail_newsearchset () : NIL;
865 SEARCHSET *dest = cu ? mail_newsearchset () : NIL;
866 MAILSTREAM *dstream = NIL;
867 if (!((options & CP_UID) ? mail_uid_sequence (stream,sequence) :
868 mail_sequence (stream,sequence))) return NIL;
869 /* make sure valid mailbox */
870 if ((fd = mbx_isvalid (&dstream,mailbox,file,&ld,lock,
871 cu ? MBXISVALIDUID : MBXISVALIDNOUID)) < 0)
872 switch (errno) {
873 case ENOENT: /* no such file? */
874 mm_notify (stream,"[TRYCREATE] Must create mailbox before copy",NIL);
875 return NIL;
876 case EACCES: /* file protected */
877 sprintf (LOCAL->buf,"Can't access destination: %.80s",mailbox);
878 MM_LOG (LOCAL->buf,ERROR);
879 return NIL;
880 case EINVAL:
881 if (pc) return (*pc) (stream,sequence,mailbox,options);
882 sprintf (LOCAL->buf,"Invalid MBX-format mailbox name: %.80s",mailbox);
883 mm_log (LOCAL->buf,ERROR);
884 return NIL;
885 default:
886 if (pc) return (*pc) (stream,sequence,mailbox,options);
887 sprintf (LOCAL->buf,"Not a MBX-format mailbox: %.80s",mailbox);
888 mm_log (LOCAL->buf,ERROR);
889 return NIL;
890 }
891 /* got file? */
892 if ((fd = open (dummy_file (file,mailbox),O_RDWR|O_CREAT|O_BINARY,
893 S_IREAD|S_IWRITE)) < 0) {
894 sprintf (LOCAL->buf,"Unable to open copy mailbox: %s",strerror (errno));
895 mm_log (LOCAL->buf,ERROR);
896 return NIL;
897 }
898 mm_critical (stream); /* go critical */
899 fstat (fd,&sbuf); /* get current file size */
900 lseek (fd,sbuf.st_size,L_SET);/* move to end of file */
902 /* for each requested message */
903 for (i = 1; ret && (i <= stream->nmsgs); i++)
904 if ((elt = mail_elt (stream,i))->sequence) {
905 lseek (LOCAL->fd,elt->private.special.offset +
906 elt->private.special.text.size,L_SET);
907 mail_date(LOCAL->buf,elt);/* build target header */
908 /* get target keyword mask */
909 for (j = elt->user_flags, k = 0; j; )
910 if (s = stream->user_flags[find_rightmost_bit (&j)])
911 for (m = 0; (m < NUSERFLAGS) && (t = dstream->user_flags[m]); m++)
912 if (!compare_cstring (s,t) && (k |= 1 << m)) break;
913 sprintf (LOCAL->buf+strlen(LOCAL->buf),",%lu;%08lx%04x-%08lx\015\012",
914 elt->rfc822_size,k,(unsigned)
915 ((fSEEN * elt->seen) + (fDELETED * elt->deleted) +
916 (fFLAGGED * elt->flagged) + (fANSWERED * elt->answered) +
917 (fDRAFT * elt->draft)),cu ? ++dstream->uid_last : 0);
918 /* write target header */
919 if (ret = (write (fd,LOCAL->buf,strlen (LOCAL->buf)) > 0)) {
920 for (k = elt->rfc822_size; ret && (j = min (k,LOCAL->buflen)); k -= j){
921 read (LOCAL->fd,LOCAL->buf,j);
922 ret = write (fd,LOCAL->buf,j) >= 0;
923 }
924 if (cu) { /* need to pass back new UID? */
925 mail_append_set (source,mail_uid (stream,i));
926 mail_append_set (dest,dstream->uid_last);
927 }
928 }
929 }
931 /* make sure all the updates take */
932 if (!(ret && (ret = !fsync (fd)))) {
933 sprintf (LOCAL->buf,"Unable to write message: %s",strerror (errno));
934 mm_log (LOCAL->buf,ERROR);
935 ftruncate (fd,sbuf.st_size);
936 }
937 if (cu && ret) { /* return sets if doing COPYUID */
938 (*cu) (stream,mailbox,dstream->uid_validity,source,dest);
939 lseek (fd,15,L_SET); /* update UIDLAST */
940 sprintf (LOCAL->buf,"%08lx",dstream->uid_last);
941 write (fd,LOCAL->buf,8);
942 }
943 else { /* flush any sets we may have built */
944 mail_free_searchset (&source);
945 mail_free_searchset (&dest);
946 }
947 /* set atime to now-1 if successful copy */
948 if (ret) times.actime = time (0) - 1;
949 /* else preserved \Marked status */
950 else times.actime = (sbuf.st_ctime > sbuf.st_atime) ?
951 sbuf.st_atime : time (0);
952 times.modtime = sbuf.st_mtime;/* preserve mtime */
953 utime (file,&times); /* set the times */
954 close (fd); /* close the file */
955 mm_nocritical (stream); /* release critical */
956 unlockfd (ld,lock); /* release exclusive parse/append permission */
957 /* delete all requested messages */
958 if (ret && (options & CP_MOVE) && mbx_flaglock (stream)) {
959 for (i = 1; i <= stream->nmsgs; i++) if (mail_elt (stream,i)->sequence) {
960 /* mark message deleted */
961 mbx_elt (stream,i,NIL)->deleted = T;
962 /* recalculate status */
963 mbx_update_status (stream,i,NIL);
964 }
965 /* update flags */
966 mbx_flag (stream,NIL,NIL,NIL);
967 }
968 if (dstream != stream) mail_close (dstream);
969 return ret;
970 }
972 /* MBX mail append message from stringstruct
973 * Accepts: MAIL stream
974 * destination mailbox
975 * append callback
976 * data for callback
977 * Returns: T if append successful, else NIL
978 */
980 long mbx_append (MAILSTREAM *stream,char *mailbox,append_t af,void *data)
981 {
982 struct stat sbuf;
983 int fd,ld;
984 char *flags,*date,tmp[MAILTMPLEN],file[MAILTMPLEN],lock[MAILTMPLEN];
985 struct utimbuf times;
986 FILE *df;
987 MESSAGECACHE elt;
988 long f;
989 unsigned long i,uf;
990 STRING *message;
991 long ret = NIL;
992 MAILSTREAM *dstream = NIL;
993 appenduid_t au = (appenduid_t) mail_parameters (NIL,GET_APPENDUID,NIL);
994 SEARCHSET *dst = au ? mail_newsearchset () : NIL;
995 /* make sure valid mailbox */
996 /* make sure valid mailbox */
997 if ((fd = mbx_isvalid (&dstream,mailbox,file,&ld,lock,
998 au ? MBXISVALIDUID : MBXISVALIDNOUID)) < 0)
999 switch (errno) {
1000 case ENOENT: /* no such file? */
1001 if (compare_cstring (mailbox,"INBOX")) {
1002 mm_notify (stream,"[TRYCREATE] Must create mailbox before append",NIL);
1003 return NIL;
1005 /* can create INBOX here */
1006 mbx_create (dstream = stream ? stream : &mbxproto,"INBOX");
1007 if ((fd = mbx_isvalid (&dstream,mailbox,file,&ld,lock,
1008 au ? MBXISVALIDUID : MBXISVALIDNOUID)) < 0)
1009 break;
1010 case EACCES: /* file protected */
1011 sprintf (tmp,"Can't access destination: %.80s",mailbox);
1012 MM_LOG (tmp,ERROR);
1013 return NIL;
1014 case EINVAL:
1015 sprintf (tmp,"Invalid MBX-format mailbox name: %.80s",mailbox);
1016 mm_log (tmp,ERROR);
1017 return NIL;
1018 default:
1019 sprintf (tmp,"Not a MBX-format mailbox: %.80s",mailbox);
1020 mm_log (tmp,ERROR);
1021 return NIL;
1024 /* get first message */
1025 if (!(*af) (dstream,data,&flags,&date,&message)) close (fd);
1026 else if (!(df = fdopen (fd,"r+b"))) {
1027 MM_LOG ("Unable to reopen append mailbox",ERROR);
1028 close (fd);
1030 else {
1031 mm_critical (dstream); /* go critical */
1032 fstat (fd,&sbuf); /* get current file size */
1033 fseek (df,sbuf.st_size,SEEK_SET);
1034 errno = 0;
1035 for (ret = LONGT; ret && message; ) {
1036 if (!SIZE (message)) { /* guard against zero-length */
1037 mm_log ("Append of zero-length message",ERROR);
1038 ret = NIL;
1039 break;
1041 f = mail_parse_flags (dstream,flags,&uf);
1042 if (date) { /* parse date if given */
1043 if (!mail_parse_date (&elt,date)) {
1044 sprintf (tmp,"Bad date in append: %.80s",date);
1045 mm_log (tmp,ERROR);
1046 ret = NIL; /* mark failure */
1047 break;
1049 mail_date (tmp,&elt); /* write preseved date */
1051 else internal_date (tmp); /* get current date in IMAP format */
1052 /* write header */
1053 if (fprintf (df,"%s,%lu;%08lx%04lx-%08lx\015\012",tmp,i = SIZE (message),
1054 uf,(unsigned long) f,au ? ++dstream->uid_last : 0) < 0)
1055 ret = NIL;
1056 else { /* write message */
1057 size_t j;
1058 if (!message->cursize) SETPOS (message,GETPOS (message));
1059 while (i && (j = fwrite (message->curpos,1,message->cursize,df))) {
1060 i -= j;
1061 SETPOS (message,GETPOS (message) + j);
1063 /* get next message */
1064 if (i || !(*af) (dstream,data,&flags,&date,&message)) ret = NIL;
1065 else if (au) mail_append_set (dst,dstream->uid_last);
1069 /* if error... */
1070 if (!ret || (fflush (df) == EOF)) {
1071 /* revert file */
1072 ftruncate (fd,sbuf.st_size);
1073 close (fd); /* make sure fclose() doesn't corrupt us */
1074 if (errno) {
1075 sprintf (tmp,"Message append failed: %s",strerror (errno));
1076 mm_log (tmp,ERROR);
1078 ret = NIL;
1080 if (au && ret) { /* return sets if doing APPENDUID */
1081 (*au) (mailbox,dstream->uid_validity,dst);
1082 fseek (df,15,SEEK_SET); /* update UIDLAST */
1083 fprintf (df,"%08lx",dstream->uid_last);
1085 else mail_free_searchset (&dst);
1086 if (ret) times.actime = time (0) - 1;
1087 /* else preserve \Marked status */
1088 else times.actime = (sbuf.st_ctime > sbuf.st_atime) ?
1089 sbuf.st_atime : time (0);
1090 /* preserve mtime */
1091 times.modtime = sbuf.st_mtime;
1092 utime (file,&times); /* set the times */
1093 fclose (df); /* close the file */
1094 mm_nocritical (dstream); /* release critical */
1096 unlockfd (ld,lock); /* release exclusive parse/append permission */
1097 if (dstream != stream) mail_close (dstream);
1098 return ret;
1101 /* Internal routines */
1104 /* MBX mail parse mailbox
1105 * Accepts: MAIL stream
1106 * Returns: T if parse OK
1107 * NIL if failure, stream aborted
1108 */
1110 long mbx_parse (MAILSTREAM *stream)
1112 struct stat sbuf;
1113 MESSAGECACHE *elt = NIL;
1114 unsigned char c,*s,*t,*x;
1115 char tmp[MAILTMPLEN];
1116 unsigned long i,j,k,m;
1117 off_t curpos = LOCAL->filesize;
1118 unsigned long nmsgs = stream->nmsgs;
1119 unsigned long recent = stream->recent;
1120 unsigned long lastuid = 0;
1121 short dirty = NIL;
1122 short added = NIL;
1123 short silent = stream->silent;
1124 short uidwarn = T;
1125 fstat (LOCAL->fd,&sbuf); /* get status */
1126 if (sbuf.st_size < curpos) { /* sanity check */
1127 sprintf (tmp,"Mailbox shrank from %lu to %lu!",
1128 (unsigned long) curpos,(unsigned long) sbuf.st_size);
1129 mm_log (tmp,ERROR);
1130 mbx_abort (stream);
1131 return NIL;
1133 lseek (LOCAL->fd,0,L_SET); /* rewind file */
1134 /* read internal header */
1135 read (LOCAL->fd,LOCAL->buf,HDRSIZE);
1136 LOCAL->buf[HDRSIZE] = '\0'; /* tie off header */
1137 c = LOCAL->buf[15]; /* save first character of last UID */
1138 LOCAL->buf[15] = '\0';
1139 /* parse UID validity */
1140 stream->uid_validity = strtoul (LOCAL->buf + 7,NIL,16);
1141 LOCAL->buf[15] = c; /* restore first character of last UID */
1142 /* parse last UID */
1143 i = strtoul (LOCAL->buf + 15,NIL,16);
1144 stream->uid_last = stream->rdonly ? max (i,stream->uid_last) : i;
1145 /* parse user flags */
1146 for (i = 0, s = LOCAL->buf + 25;
1147 (i < NUSERFLAGS) && (t = strchr (s,'\015')) && (t - s);
1148 i++, s = t + 2) {
1149 *t = '\0'; /* tie off flag */
1150 if (!stream->user_flags[i] && (strlen (s) <= MAXUSERFLAG))
1151 stream->user_flags[i] = cpystr (s);
1153 LOCAL->ffuserflag = (int) i; /* first free user flag */
1155 stream->silent = T; /* don't pass up mm_exists() events yet */
1156 while (sbuf.st_size - curpos){/* while there is stuff to parse */
1157 /* get to that position in the file */
1158 lseek (LOCAL->fd,curpos,L_SET);
1159 if ((i = read (LOCAL->fd,LOCAL->buf,64)) <= 0) {
1160 sprintf (tmp,"Unable to read internal header at %lu, size = %lu: %s",
1161 (unsigned long) curpos,(unsigned long) sbuf.st_size,
1162 i ? strerror (errno) : "no data read");
1163 mm_log (tmp,ERROR);
1164 mbx_abort (stream);
1165 return NIL;
1167 LOCAL->buf[i] = '\0'; /* tie off buffer just in case */
1168 if (!((s = strchr (LOCAL->buf,'\015')) && (s[1] == '\012'))) {
1169 sprintf (tmp,"Unable to find CRLF at %lu in %lu bytes, text: %.80s",
1170 (unsigned long) curpos,i,(char *) LOCAL->buf);
1171 mm_log (tmp,ERROR);
1172 mbx_abort (stream);
1173 return NIL;
1175 *s = '\0'; /* tie off header line */
1176 i = (s + 2) - LOCAL->buf; /* note start of text offset */
1177 if (!((s = strchr (LOCAL->buf,',')) && (t = strchr (s+1,';')))) {
1178 sprintf (tmp,"Unable to parse internal header at %lu: %.80s",
1179 (unsigned long) curpos,(char *) LOCAL->buf);
1180 mm_log (tmp,ERROR);
1181 mbx_abort (stream);
1182 return NIL;
1184 if (!(isxdigit (t[1]) && isxdigit (t[2]) && isxdigit (t[3]) &&
1185 isxdigit (t[4]) && isxdigit (t[5]) && isxdigit (t[6]) &&
1186 isxdigit (t[7]) && isxdigit (t[8]) && isxdigit (t[9]) &&
1187 isxdigit (t[10]) && isxdigit (t[11]) && isxdigit (t[12]))) {
1188 sprintf (tmp,"Unable to parse message flags at %lu: %.80s",
1189 (unsigned long) curpos,(char *) LOCAL->buf);
1190 mm_log (tmp,ERROR);
1191 mbx_abort (stream);
1192 return NIL;
1194 if ((t[13] != '-') || t[22] ||
1195 !(isxdigit (t[14]) && isxdigit (t[15]) && isxdigit (t[16]) &&
1196 isxdigit (t[17]) && isxdigit (t[18]) && isxdigit (t[19]) &&
1197 isxdigit (t[20]) && isxdigit (t[21]))) {
1198 sprintf (tmp,"Unable to parse message UID at %lu: %.80s",
1199 (unsigned long) curpos,(char *) LOCAL->buf);
1200 mm_log (tmp,ERROR);
1201 mbx_abort (stream);
1202 return NIL;
1205 *s++ = '\0'; *t++ = '\0'; /* break up fields */
1206 /* get message size */
1207 if (!(j = strtoul (s,(char **) &x,10)) && (!(x && *x))) {
1208 sprintf (tmp,"Unable to parse message size at %lu: %.80s,%.80s;%.80s",
1209 (unsigned long) curpos,(char *) LOCAL->buf,(char *) s,
1210 (char *) t);
1211 mm_log (tmp,ERROR);
1212 mbx_abort (stream);
1213 return NIL;
1215 /* make sure didn't run off end of file */
1216 if (((off_t) (curpos + i + j)) > sbuf.st_size) {
1217 sprintf (tmp,"Last message (at %lu) runs past end of file (%lu > %lu)",
1218 (unsigned long) curpos,(unsigned long) (curpos + i + j),
1219 (unsigned long) sbuf.st_size);
1220 mm_log (tmp,ERROR);
1221 mbx_abort (stream);
1222 return NIL;
1224 /* parse UID */
1225 if ((m = strtoul (t+13,NIL,16)) &&
1226 ((m <= lastuid) || (m > stream->uid_last))) {
1227 if (uidwarn) {
1228 sprintf (tmp,"Invalid UID %08lx in message %lu, rebuilding UIDs",
1229 m,nmsgs+1);
1230 mm_log (tmp,WARN);
1231 uidwarn = NIL;
1232 /* restart UID validity */
1233 stream->uid_validity = (unsigned long) time (0);
1235 m = 0; /* lose this UID */
1236 dirty = T; /* mark dirty, set new lastuid */
1237 stream->uid_last = lastuid;
1240 t[12] = '\0'; /* parse system flags */
1241 if ((k = strtoul (t+8,NIL,16)) & fEXPUNGED) {
1242 if (m) lastuid = m; /* expunge message, update last UID seen */
1243 else { /* no UID assigned? */
1244 lastuid = ++stream->uid_last;
1245 dirty = T;
1248 else { /* not expunged, swell the cache */
1249 added = T; /* note that a new message was added */
1250 mail_exists (stream,++nmsgs);
1251 /* instantiate an elt for this message */
1252 (elt = mail_elt (stream,nmsgs))->valid = T;
1253 /* parse the date */
1254 if (!mail_parse_date (elt,LOCAL->buf)) {
1255 sprintf (tmp,"Unable to parse message date at %lu: %.80s",
1256 (unsigned long) curpos,(char *) LOCAL->buf);
1257 mm_log (tmp,ERROR);
1258 mbx_abort (stream);
1259 return NIL;
1261 /* note file offset of header */
1262 elt->private.special.offset = curpos;
1263 /* and internal header size */
1264 elt->private.special.text.size = i;
1265 /* header size not known yet */
1266 elt->private.msg.header.text.size = 0;
1267 elt->rfc822_size = j; /* note message size */
1268 /* calculate system flags */
1269 if (k & fSEEN) elt->seen = T;
1270 if (k & fDELETED) elt->deleted = T;
1271 if (k & fFLAGGED) elt->flagged = T;
1272 if (k & fANSWERED) elt->answered = T;
1273 if (k & fDRAFT) elt->draft = T;
1274 t[8] = '\0'; /* get user flags value */
1275 elt->user_flags = strtoul (t,NIL,16);
1276 /* UID already assigned? */
1277 if (!(elt->private.uid = m) || !(k & fOLD)) {
1278 elt->recent = T; /* no, mark as recent */
1279 ++recent; /* count up a new recent message */
1280 dirty = T; /* and must rewrite header */
1281 /* assign new UID */
1282 if (!elt->private.uid) elt->private.uid = ++stream->uid_last;
1283 mbx_update_status (stream,elt->msgno,NIL);
1285 /* update last parsed UID */
1286 lastuid = elt->private.uid;
1288 curpos += i + j; /* update position */
1291 if (dirty && !stream->rdonly){/* update header */
1292 mbx_update_header (stream);
1293 fsync (LOCAL->fd); /* make sure all the UID updates take */
1295 /* update parsed file size and time */
1296 LOCAL->filesize = sbuf.st_size;
1297 fstat (LOCAL->fd,&sbuf); /* get status again to ensure time is right */
1298 LOCAL->filetime = sbuf.st_mtime;
1299 if (added && !stream->rdonly){/* make sure atime updated */
1300 struct utimbuf times;
1301 times.actime = time (0);
1302 times.modtime = LOCAL->filetime;
1303 utime (stream->mailbox,&times);
1305 stream->silent = silent; /* can pass up events now */
1306 mail_exists (stream,nmsgs); /* notify upper level of new mailbox size */
1307 mail_recent (stream,recent); /* and of change in recent messages */
1308 return LONGT; /* return the winnage */
1311 /* MBX get cache element with status updating from file
1312 * Accepts: MAIL stream
1313 * message number
1314 * expunge OK flag
1315 * Returns: cache element
1316 */
1318 MESSAGECACHE *mbx_elt (MAILSTREAM *stream,unsigned long msgno,long expok)
1320 MESSAGECACHE *elt = mail_elt (stream,msgno);
1321 struct { /* old flags */
1322 unsigned int seen : 1;
1323 unsigned int deleted : 1;
1324 unsigned int flagged : 1;
1325 unsigned int answered : 1;
1326 unsigned int draft : 1;
1327 unsigned long user_flags;
1328 } old;
1329 old.seen = elt->seen; old.deleted = elt->deleted; old.flagged = elt->flagged;
1330 old.answered = elt->answered; old.draft = elt->draft;
1331 old.user_flags = elt->user_flags;
1332 /* get new flags */
1333 if (mbx_read_flags (stream,elt) && expok) {
1334 mail_expunged (stream,elt->msgno);
1335 return NIL; /* return this message was expunged */
1337 if ((old.seen != elt->seen) || (old.deleted != elt->deleted) ||
1338 (old.flagged != elt->flagged) || (old.answered != elt->answered) ||
1339 (old.draft != elt->draft) || (old.user_flags != elt->user_flags))
1340 mm_flags (stream,msgno); /* let top level know */
1341 return elt;
1344 /* MBX read flags from file
1345 * Accepts: MAIL stream
1346 * cache element
1347 * Returns: non-NIL if message expunged
1348 */
1350 unsigned long mbx_read_flags (MAILSTREAM *stream,MESSAGECACHE *elt)
1352 unsigned long i;
1353 struct stat sbuf;
1354 fstat (LOCAL->fd,&sbuf); /* get status */
1355 /* make sure file size is good */
1356 if (sbuf.st_size < LOCAL->filesize) {
1357 sprintf (LOCAL->buf,"Mailbox shrank from %lu to %lu in flag read!",
1358 (unsigned long) LOCAL->filesize,(unsigned long) sbuf.st_size);
1359 fatal (LOCAL->buf);
1361 /* set the seek pointer */
1362 lseek (LOCAL->fd,(off_t) elt->private.special.offset +
1363 elt->private.special.text.size - 24,L_SET);
1364 /* read the new flags */
1365 if (read (LOCAL->fd,LOCAL->buf,14) < 0) {
1366 sprintf (LOCAL->buf,"Unable to read new status: %s",strerror (errno));
1367 fatal (LOCAL->buf);
1369 if ((LOCAL->buf[0] != ';') || (LOCAL->buf[13] != '-')) {
1370 LOCAL->buf[14] = '\0'; /* tie off buffer for error message */
1371 sprintf (LOCAL->buf+50,"Invalid flags for message %lu (%lu %lu): %s",
1372 elt->msgno,elt->private.special.offset,
1373 elt->private.special.text.size,(char *) LOCAL->buf);
1374 fatal (LOCAL->buf+50);
1376 LOCAL->buf[13] = '\0'; /* tie off buffer */
1377 /* calculate system flags */
1378 i = strtoul (LOCAL->buf+9,NIL,16);
1379 elt->seen = i & fSEEN ? T : NIL;
1380 elt->deleted = i & fDELETED ? T : NIL;
1381 elt->flagged = i & fFLAGGED ? T : NIL;
1382 elt->answered = i & fANSWERED ? T : NIL;
1383 elt->draft = i & fDRAFT ? T : NIL;
1384 LOCAL->expunged |= i & fEXPUNGED ? T : NIL;
1385 LOCAL->buf[9] = '\0'; /* tie off flags */
1386 /* get user flags value */
1387 elt->user_flags = strtoul (LOCAL->buf+1,NIL,16);
1388 elt->valid = T; /* have valid flags now */
1389 return i & fEXPUNGED;
1392 /* MBX update header
1393 * Accepts: MAIL stream
1394 */
1396 #define NTKLUDGEOFFSET 7
1398 void mbx_update_header (MAILSTREAM *stream)
1400 int i;
1401 char *s = LOCAL->buf;
1402 memset (s,'\0',HDRSIZE); /* initialize header */
1403 sprintf (s,"*mbx*\015\012%08lx%08lx\015\012",
1404 stream->uid_validity,stream->uid_last);
1405 for (i = 0; (i < NUSERFLAGS) && stream->user_flags[i]; ++i)
1406 sprintf (s += strlen (s),"%s\015\012",stream->user_flags[i]);
1407 LOCAL->ffuserflag = i; /* first free user flag */
1408 /* can we create more user flags? */
1409 stream->kwd_create = (i < NUSERFLAGS) ? T : NIL;
1410 /* write reserved lines */
1411 while (i++ < NUSERFLAGS) strcat (s,"\015\012");
1412 while (T) { /* rewind file */
1413 lseek (LOCAL->fd,NTKLUDGEOFFSET,L_SET);
1414 /* write new header */
1415 if (write (LOCAL->fd,LOCAL->buf + NTKLUDGEOFFSET,
1416 HDRSIZE - NTKLUDGEOFFSET) > 0) break;
1417 mm_notify (stream,strerror (errno),WARN);
1418 mm_diskerror (stream,errno,T);
1422 /* MBX update status string
1423 * Accepts: MAIL stream
1424 * message number
1425 * flags
1426 */
1428 void mbx_update_status (MAILSTREAM *stream,unsigned long msgno,long flags)
1430 struct stat sbuf;
1431 MESSAGECACHE *elt = mail_elt (stream,msgno);
1432 /* readonly */
1433 if (stream->rdonly || !elt->valid) mbx_read_flags (stream,elt);
1434 else { /* readwrite */
1435 fstat (LOCAL->fd,&sbuf); /* get status */
1436 /* make sure file size is good */
1437 if (sbuf.st_size < LOCAL->filesize) {
1438 sprintf (LOCAL->buf,"Mailbox shrank from %lu to %lu in flag update!",
1439 (unsigned long) LOCAL->filesize,(unsigned long) sbuf.st_size);
1440 fatal (LOCAL->buf);
1442 /* set the seek pointer */
1443 lseek (LOCAL->fd,(off_t) elt->private.special.offset +
1444 elt->private.special.text.size - 24,L_SET);
1445 /* read the new flags */
1446 if (read (LOCAL->fd,LOCAL->buf,14) < 0) {
1447 sprintf (LOCAL->buf,"Unable to read old status: %s",strerror (errno));
1448 fatal (LOCAL->buf);
1450 if ((LOCAL->buf[0] != ';') || (LOCAL->buf[13] != '-')) {
1451 LOCAL->buf[14] = '\0'; /* tie off buffer for error message */
1452 sprintf (LOCAL->buf+50,"Invalid flags for message %lu (%lu %lu): %s",
1453 elt->msgno,elt->private.special.offset,
1454 elt->private.special.text.size,(char *) LOCAL->buf);
1455 fatal (LOCAL->buf+50);
1457 /* print new flag string */
1458 sprintf (LOCAL->buf,"%08lx%04x-%08lx",elt->user_flags,(unsigned)
1459 (((elt->deleted && flags) ?
1460 fEXPUNGED : (strtoul (LOCAL->buf+9,NIL,16)) & fEXPUNGED) +
1461 (fSEEN * elt->seen) + (fDELETED * elt->deleted) +
1462 (fFLAGGED * elt->flagged) + (fANSWERED * elt->answered) +
1463 (fDRAFT * elt->draft) + fOLD),elt->private.uid);
1464 while (T) { /* get to that place in the file */
1465 lseek (LOCAL->fd,(off_t) elt->private.special.offset +
1466 elt->private.special.text.size - 23,L_SET);
1467 /* write new flags and UID */
1468 if (write (LOCAL->fd,LOCAL->buf,21) > 0) break;
1469 mm_notify (stream,strerror (errno),WARN);
1470 mm_diskerror (stream,errno,T);
1475 /* MBX locate header for a message
1476 * Accepts: MAIL stream
1477 * message number
1478 * pointer to returned header size
1479 * pointer to possible returned header
1480 * Returns: position of header in file
1481 */
1483 #define HDRBUFLEN 16384 /* good enough for most headers */
1484 #define SLOP 4 /* CR LF CR LF */
1486 unsigned long mbx_hdrpos (MAILSTREAM *stream,unsigned long msgno,
1487 unsigned long *size,char **hdr)
1489 unsigned long siz,done;
1490 long i;
1491 unsigned char *s,*t,*te;
1492 MESSAGECACHE *elt = mail_elt (stream,msgno);
1493 unsigned long ret = elt->private.special.offset +
1494 elt->private.special.text.size;
1495 if (hdr) *hdr = NIL; /* assume no header returned */
1496 /* is header size known? */
1497 if (*size = elt->private.msg.header.text.size) return ret;
1498 /* paranoia check */
1499 if (LOCAL->buflen < (HDRBUFLEN + SLOP))
1500 fatal ("LOCAL->buf smaller than HDRBUFLEN");
1501 lseek (LOCAL->fd,ret,L_SET); /* get to header position */
1502 /* read HDRBUFLEN chunks with 4 byte slop */
1503 for (done = siz = 0, s = LOCAL->buf;
1504 (i = min ((long) (elt->rfc822_size - done),(long) HDRBUFLEN)) &&
1505 (read (LOCAL->fd,s,i) == i);
1506 done += i, siz += (t - LOCAL->buf) - SLOP, s = LOCAL->buf + SLOP) {
1507 te = (t = s + i) - 12; /* calculate end of fast scan */
1508 /* fast scan for CR */
1509 for (s = LOCAL->buf; s < te;)
1510 if (((*s++ == '\015') || (*s++ == '\015') || (*s++ == '\015') ||
1511 (*s++ == '\015') || (*s++ == '\015') || (*s++ == '\015') ||
1512 (*s++ == '\015') || (*s++ == '\015') || (*s++ == '\015') ||
1513 (*s++ == '\015') || (*s++ == '\015') || (*s++ == '\015')) &&
1514 (*s == '\012') && (*++s == '\015') && (*++s == '\012')) {
1515 *size = elt->private.msg.header.text.size = siz + (++s - LOCAL->buf);
1516 if (hdr) *hdr = LOCAL->buf;
1517 return ret;
1519 for (te = t - 3; (s < te);) /* final character-at-a-time scan */
1520 if ((*s++ == '\015') && (*s == '\012') && (*++s == '\015') &&
1521 (*++s == '\012')) {
1522 *size = elt->private.msg.header.text.size = siz + (++s - LOCAL->buf);
1523 if (hdr) *hdr = LOCAL->buf;
1524 return ret;
1526 if (i <= SLOP) break; /* end of data */
1527 /* slide over last 4 bytes */
1528 memmove (LOCAL->buf,t - SLOP,SLOP);
1529 hdr = NIL; /* can't return header this way */
1531 /* not found: header consumes entire message */
1532 elt->private.msg.header.text.size = *size = elt->rfc822_size;
1533 if (hdr) *hdr = LOCAL->buf; /* possibly return header too */
1534 return ret;
1537 /* MBX mail rewrite mailbox
1538 * Accepts: MAIL stream
1539 * pointer to return reclaimed size
1540 * flags (0 = no expunge, 1 = expunge deleted, -1 = expunge sequence)
1541 * Returns: number of expunged messages
1542 */
1544 unsigned long mbx_rewrite (MAILSTREAM *stream,unsigned long *reclaimed,
1545 long flags)
1547 struct utimbuf times;
1548 struct stat sbuf;
1549 off_t pos,ppos;
1550 int ld;
1551 unsigned long i,j,k,m,delta;
1552 unsigned long n = *reclaimed = 0;
1553 unsigned long recent = 0;
1554 char lock[MAILTMPLEN];
1555 MESSAGECACHE *elt;
1556 /* get parse/append permission */
1557 if ((ld = lockname (lock,stream->mailbox,LOCK_EX)) < 0) {
1558 mm_log ("Unable to lock expunge mailbox",ERROR);
1559 return 0;
1561 fstat (LOCAL->fd,&sbuf); /* get current write time */
1562 if (LOCAL->filetime && !LOCAL->flagcheck &&
1563 (LOCAL->filetime < sbuf.st_mtime)) LOCAL->flagcheck = T;
1564 if (!mbx_parse (stream)) { /* make sure see any newly-arrived messages */
1565 unlockfd (ld,lock); /* failed?? */
1566 return 0;
1568 if (LOCAL->flagcheck) { /* sweep flags if need flagcheck */
1569 LOCAL->filetime = sbuf.st_mtime;
1570 for (i = 1; i <= stream->nmsgs; ++i) mbx_elt (stream,i,NIL);
1571 LOCAL->flagcheck = NIL;
1574 /* get exclusive access */
1575 if (!flock (LOCAL->fd,LOCK_EX|LOCK_NB)) {
1576 mm_critical (stream); /* go critical */
1577 for (i = 1,delta = 0,pos = ppos = HDRSIZE; i <= stream->nmsgs; ) {
1578 /* note if message not at predicted location */
1579 if (m = (elt = mbx_elt (stream,i,NIL))->private.special.offset - ppos) {
1580 ppos = elt->private.special.offset;
1581 *reclaimed += m; /* note reclaimed message space */
1582 delta += m; /* and as expunge delta */
1584 /* number of bytes to smash or preserve */
1585 ppos += (k = elt->private.special.text.size + elt->rfc822_size);
1586 /* if need to expunge this message*/
1587 if (flags && elt->deleted && ((flags > 0) || elt->sequence)) {
1588 delta += k; /* number of bytes to delete */
1589 mail_expunged(stream,i);/* notify upper levels */
1590 n++; /* count up one more expunged message */
1592 else { /* preserved message */
1593 i++; /* count this message */
1594 if (elt->recent) ++recent;
1595 if (delta) { /* moved, note first byte to preserve */
1596 j = elt->private.special.offset;
1597 do { /* read from source position */
1598 m = min (k,LOCAL->buflen);
1599 lseek (LOCAL->fd,j,L_SET);
1600 read (LOCAL->fd,LOCAL->buf,m);
1601 pos = j - delta; /* write to destination position */
1602 while (T) {
1603 lseek (LOCAL->fd,pos,L_SET);
1604 if (write (LOCAL->fd,LOCAL->buf,m) > 0) break;
1605 mm_notify (stream,strerror (errno),WARN);
1606 mm_diskerror (stream,errno,T);
1608 pos += m; /* new position */
1609 j += m; /* next chunk, perhaps */
1610 } while (k -= m); /* until done */
1611 /* note the new address of this text */
1612 elt->private.special.offset -= delta;
1614 /* preserved but no deleted messages yet */
1615 else pos = elt->private.special.offset + k;
1618 /* deltaed file size match position? */
1619 if (m = (LOCAL->filesize -= delta) - pos) {
1620 *reclaimed += m; /* probably an fEXPUNGED msg */
1621 LOCAL->filesize = pos; /* set correct size */
1623 /* truncate file after last message */
1624 ftruncate (LOCAL->fd,LOCAL->filesize);
1625 fsync (LOCAL->fd); /* force disk update */
1626 mm_nocritical (stream); /* release critical */
1627 flock (LOCAL->fd,LOCK_SH); /* allow sharers again */
1630 else { /* can't get exclusive */
1631 flock (LOCAL->fd,LOCK_SH); /* recover previous shared mailbox lock */
1632 /* do hide-expunge when shared */
1633 if (flags) for (i = 1; i <= stream->nmsgs; ) {
1634 if (elt = mbx_elt (stream,i,T)) {
1635 /* make the message invisible */
1636 if (elt->deleted && ((flags > 0) || elt->sequence)) {
1637 mbx_update_status (stream,elt->msgno,LONGT);
1638 /* notify upper levels */
1639 mail_expunged (stream,i);
1640 n++; /* count up one more expunged message */
1642 else {
1643 i++; /* preserved message */
1644 if (elt->recent) ++recent;
1647 else n++; /* count up one more expunged message */
1649 fsync (LOCAL->fd); /* force disk update */
1651 fstat (LOCAL->fd,&sbuf); /* get new write time */
1652 times.modtime = LOCAL->filetime = sbuf.st_mtime;
1653 times.actime = time (0); /* reset atime to now */
1654 utime (stream->mailbox,&times);
1655 unlockfd (ld,lock); /* release exclusive parse/append permission */
1656 /* notify upper level of new mailbox size */
1657 mail_exists (stream,stream->nmsgs);
1658 mail_recent (stream,recent);
1659 return n; /* return number of expunged messages */
1662 /* MBX mail lock for flag updating
1663 * Accepts: stream
1664 * Returns: T if successful, NIL if failure
1665 */
1667 long mbx_flaglock (MAILSTREAM *stream)
1669 struct stat sbuf;
1670 unsigned long i;
1671 int ld;
1672 char lock[MAILTMPLEN];
1673 /* no-op if readonly or already locked */
1674 if (!stream->rdonly && LOCAL && (LOCAL->fd >= 0) && (LOCAL->ld < 0)) {
1675 /* lock now */
1676 if ((ld = lockname (lock,stream->mailbox,LOCK_EX)) < 0) return NIL;
1677 if (!LOCAL->flagcheck) { /* don't do this if flagcheck already needed */
1678 if (LOCAL->filetime) { /* know previous time? */
1679 fstat (LOCAL->fd,&sbuf);/* get current write time */
1680 if (LOCAL->filetime < sbuf.st_mtime) LOCAL->flagcheck = T;
1681 LOCAL->filetime = 0; /* don't do this test for any other messages */
1683 if (!mbx_parse (stream)) {/* parse mailbox */
1684 unlockfd (ld,lock); /* shouldn't happen */
1685 return NIL;
1687 if (LOCAL->flagcheck) /* invalidate cache if flagcheck */
1688 for (i = 1; i <= stream->nmsgs; ++i) mail_elt (stream,i)->valid = NIL;
1690 LOCAL->ld = ld; /* copy to stream for subsequent calls */
1691 memcpy (LOCAL->lock,lock,MAILTMPLEN);
1693 return LONGT;

UW-IMAP'd extensions by yuuji