imapext-2007

view src/osdep/amiga/mmdf.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-2008 University of Washington
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 *
11 * ========================================================================
12 */
14 /*
15 * Program: MMDF mail routines
16 *
17 * Author: Mark Crispin
18 * UW Technology
19 * University of Washington
20 * Seattle, WA 98195
21 * Internet: MRC@Washington.EDU
22 *
23 * Date: 20 December 1989
24 * Last Edited: 27 March 2008
25 */
28 #include <stdio.h>
29 #include <ctype.h>
30 #include <errno.h>
31 extern int errno; /* just in case */
32 #include <signal.h>
33 #include "mail.h"
34 #include "osdep.h"
35 #include <time.h>
36 #include <sys/stat.h>
37 #include "pseudo.h"
38 #include "fdstring.h"
39 #include "misc.h"
40 #include "dummy.h"
42 /* Supposedly, this page has everything the MMDF driver needs to know about
43 * the MMDF delimiter. By changing these macros, the MMDF driver should
44 * change with it. Note that if you change the length of MMDFHDRTXT you
45 * also need to change the ISMMDF and RETIFMMDFWRD macros to reflect the new
46 * size.
47 */
50 /* Useful MMDF constants */
52 #define MMDFCHR '\01' /* MMDF character */
53 #define MMDFCHRS 0x01010101 /* MMDF header character spread in a word */
54 /* MMDF header text */
55 #define MMDFHDRTXT "\01\01\01\01\n"
56 /* length of MMDF header text */
57 #define MMDFHDRLEN (sizeof (MMDFHDRTXT) - 1)
60 /* Validate MMDF header
61 * Accepts: pointer to candidate string to validate as an MMDF header
62 * Returns: T if valid; else NIL
63 */
65 #define ISMMDF(s) \
66 ((*(s) == MMDFCHR) && ((s)[1] == MMDFCHR) && ((s)[2] == MMDFCHR) && \
67 ((s)[3] == MMDFCHR) && ((s)[4] == '\n'))
70 /* Return if a 32-bit word has the start of an MMDF header
71 * Accepts: pointer to word of four bytes to validate as an MMDF header
72 * Returns: pointer to MMDF header, else proceeds
73 */
75 #define RETIFMMDFWRD(s) { \
76 if (s[3] == MMDFCHR) { \
77 if ((s[4] == MMDFCHR) && (s[5] == MMDFCHR) && (s[6] == MMDFCHR) && \
78 (s[7] == '\n')) return s + 3; \
79 else if (s[2] == MMDFCHR) { \
80 if ((s[4] == MMDFCHR) && (s[5] == MMDFCHR) && (s[6] == '\n')) \
81 return s + 2; \
82 else if (s[1] == MMDFCHR) { \
83 if ((s[4] == MMDFCHR) && (s[5] == '\n')) return s + 1; \
84 else if ((*s == MMDFCHR) && (s[4] == '\n')) return s; \
85 } \
86 } \
87 } \
88 }
90 /* Validate line
91 * Accepts: pointer to candidate string to validate as a From header
92 * return pointer to end of date/time field
93 * return pointer to offset from t of time (hours of ``mmm dd hh:mm'')
94 * return pointer to offset from t of time zone (if non-zero)
95 * Returns: t,ti,zn set if valid From string, else ti is NIL
96 */
98 #define VALID(s,x,ti,zn) { \
99 ti = 0; \
100 if ((*s == 'F') && (s[1] == 'r') && (s[2] == 'o') && (s[3] == 'm') && \
101 (s[4] == ' ')) { \
102 for (x = s + 5; *x && *x != '\n'; x++); \
103 if (*x) { \
104 if (x - s >= 41) { \
105 for (zn = -1; x[zn] != ' '; zn--); \
106 if ((x[zn-1] == 'm') && (x[zn-2] == 'o') && (x[zn-3] == 'r') && \
107 (x[zn-4] == 'f') && (x[zn-5] == ' ') && (x[zn-6] == 'e') && \
108 (x[zn-7] == 't') && (x[zn-8] == 'o') && (x[zn-9] == 'm') && \
109 (x[zn-10] == 'e') && (x[zn-11] == 'r') && (x[zn-12] == ' '))\
110 x += zn - 12; \
111 } \
112 if (x - s >= 27) { \
113 if (x[-5] == ' ') { \
114 if (x[-8] == ':') zn = 0,ti = -5; \
115 else if (x[-9] == ' ') ti = zn = -9; \
116 else if ((x[-11] == ' ') && ((x[-10]=='+') || (x[-10]=='-'))) \
117 ti = zn = -11; \
118 } \
119 else if (x[-4] == ' ') { \
120 if (x[-9] == ' ') zn = -4,ti = -9; \
121 } \
122 else if (x[-6] == ' ') { \
123 if ((x[-11] == ' ') && ((x[-5] == '+') || (x[-5] == '-'))) \
124 zn = -6,ti = -11; \
125 } \
126 if (ti && !((x[ti - 3] == ':') && \
127 (x[ti -= ((x[ti - 6] == ':') ? 9 : 6)] == ' ') && \
128 (x[ti - 3] == ' ') && (x[ti - 7] == ' ') && \
129 (x[ti - 11] == ' '))) ti = 0; \
130 } \
131 } \
132 } \
133 }
135 /* You are not expected to understand this macro, but read the next page if
136 * you are not faint of heart.
137 *
138 * Known formats to the VALID macro are:
139 * From user Wed Dec 2 05:53 1992
140 * BSD From user Wed Dec 2 05:53:22 1992
141 * SysV From user Wed Dec 2 05:53 PST 1992
142 * rn From user Wed Dec 2 05:53:22 PST 1992
143 * From user Wed Dec 2 05:53 -0700 1992
144 * emacs From user Wed Dec 2 05:53:22 -0700 1992
145 * From user Wed Dec 2 05:53 1992 PST
146 * From user Wed Dec 2 05:53:22 1992 PST
147 * From user Wed Dec 2 05:53 1992 -0700
148 * Solaris From user Wed Dec 2 05:53:22 1992 -0700
149 *
150 * Plus all of the above with `` remote from xxx'' after it. Thank you very
151 * much, smail and Solaris, for making my life considerably more complicated.
152 */
154 /*
155 * What? You want to understand the VALID macro anyway? Alright, since you
156 * insist. Actually, it isn't really all that difficult, provided that you
157 * take it step by step.
158 *
159 * Line 1 Initializes the return ti value to failure (0);
160 * Lines 2-3 Validates that the 1st-5th characters are ``From ''.
161 * Lines 4-5 Validates that there is an end of line and points x at it.
162 * Lines 6-13 First checks to see if the line is at least 41 characters long.
163 * If so, it scans backwards to find the rightmost space. From
164 * that point, it scans backwards to see if the string matches
165 * `` remote from''. If so, it sets x to point to the space at
166 * the start of the string.
167 * Line 14 Makes sure that there are at least 27 characters in the line.
168 * Lines 15-20 Checks if the date/time ends with the year (there is a space
169 * five characters back). If there is a colon three characters
170 * further back, there is no timezone field, so zn is set to 0
171 * and ti is set in front of the year. Otherwise, there must
172 * either to be a space four characters back for a three-letter
173 * timezone, or a space six characters back followed by a + or -
174 * for a numeric timezone; in either case, zn and ti become the
175 * offset of the space immediately before it.
176 * Lines 21-23 Are the failure case for line 14. If there is a space four
177 * characters back, it is a three-letter timezone; there must be a
178 * space for the year nine characters back. zn is the zone
179 * offset; ti is the offset of the space.
180 * Lines 24-27 Are the failure case for line 20. If there is a space six
181 * characters back, it is a numeric timezone; there must be a
182 * space eleven characters back and a + or - five characters back.
183 * zn is the zone offset; ti is the offset of the space.
184 * Line 28-31 If ti is valid, make sure that the string before ti is of the
185 * form www mmm dd hh:mm or www mmm dd hh:mm:ss, otherwise
186 * invalidate ti. There must be a colon three characters back
187 * and a space six or nine characters back (depending upon
188 * whether or not the character six characters back is a colon).
189 * There must be a space three characters further back (in front
190 * of the day), one seven characters back (in front of the month),
191 * and one eleven characters back (in front of the day of week).
192 * ti is set to be the offset of the space before the time.
193 *
194 * Why a macro? It gets invoked a *lot* in a tight loop. On some of the
195 * newer pipelined machines it is faster being open-coded than it would be if
196 * subroutines are called.
197 *
198 * Why does it scan backwards from the end of the line, instead of doing the
199 * much easier forward scan? There is no deterministic way to parse the
200 * ``user'' field, because it may contain unquoted spaces! Yes, I tested it to
201 * see if unquoted spaces were possible. They are, and I've encountered enough
202 * evil mail to be totally unwilling to trust that ``it will never happen''.
203 */
205 /* Build parameters */
207 #define KODRETRY 15 /* kiss-of-death retry in seconds */
208 #define LOCKTIMEOUT 5 /* lock timeout in minutes */
211 /* MMDF I/O stream local data */
213 typedef struct mmdf_local {
214 unsigned int dirty : 1; /* disk copy needs updating */
215 unsigned int ddirty : 1; /* double-dirty, ping becomes checkpoint */
216 unsigned int pseudo : 1; /* uses a pseudo message */
217 unsigned int appending : 1; /* don't mark new messages as old */
218 int fd; /* mailbox file descriptor */
219 int ld; /* lock file descriptor */
220 char *lname; /* lock file name */
221 off_t filesize; /* file size parsed */
222 time_t filetime; /* last file time */
223 unsigned char *buf; /* temporary buffer */
224 unsigned long buflen; /* current size of temporary buffer */
225 unsigned long uid; /* current text uid */
226 SIZEDTEXT text; /* current text */
227 unsigned long textlen; /* current text length */
228 char *line; /* returned line */
229 char *linebuf; /* line readin buffer */
230 unsigned long linebuflen; /* current line readin buffer length */
231 } MMDFLOCAL;
234 /* Convenient access to local data */
236 #define LOCAL ((MMDFLOCAL *) stream->local)
239 /* MMDF protected file structure */
241 typedef struct mmdf_file {
242 MAILSTREAM *stream; /* current stream */
243 off_t curpos; /* current file position */
244 off_t protect; /* protected position */
245 off_t filepos; /* current last written file position */
246 char *buf; /* overflow buffer */
247 size_t buflen; /* current overflow buffer length */
248 char *bufpos; /* current buffer position */
249 } MMDFFILE;
251 /* Function prototypes */
253 DRIVER *mmdf_valid (char *name);
254 long mmdf_isvalid (char *name,char *tmp);
255 long mmdf_isvalid_fd (int fd,char *tmp);
256 void *mmdf_parameters (long function,void *value);
257 void mmdf_scan (MAILSTREAM *stream,char *ref,char *pat,char *contents);
258 void mmdf_list (MAILSTREAM *stream,char *ref,char *pat);
259 void mmdf_lsub (MAILSTREAM *stream,char *ref,char *pat);
260 long mmdf_create (MAILSTREAM *stream,char *mailbox);
261 long mmdf_delete (MAILSTREAM *stream,char *mailbox);
262 long mmdf_rename (MAILSTREAM *stream,char *old,char *newname);
263 MAILSTREAM *mmdf_open (MAILSTREAM *stream);
264 void mmdf_close (MAILSTREAM *stream,long options);
265 char *mmdf_header (MAILSTREAM *stream,unsigned long msgno,
266 unsigned long *length,long flags);
267 long mmdf_text (MAILSTREAM *stream,unsigned long msgno,STRING *bs,long flags);
268 char *mmdf_text_work (MAILSTREAM *stream,MESSAGECACHE *elt,
269 unsigned long *length,long flags);
270 void mmdf_flagmsg (MAILSTREAM *stream,MESSAGECACHE *elt);
271 long mmdf_ping (MAILSTREAM *stream);
272 void mmdf_check (MAILSTREAM *stream);
273 long mmdf_expunge (MAILSTREAM *stream,char *sequence,long options);
274 long mmdf_copy (MAILSTREAM *stream,char *sequence,char *mailbox,long options);
275 long mmdf_append (MAILSTREAM *stream,char *mailbox,append_t af,void *data);
276 int mmdf_collect_msg (MAILSTREAM *stream,FILE *sf,char *flags,char *date,
277 STRING *msg);
278 int mmdf_append_msgs (MAILSTREAM *stream,FILE *sf,FILE *df,SEARCHSET *set);
280 void mmdf_abort (MAILSTREAM *stream);
281 char *mmdf_file (char *dst,char *name);
282 int mmdf_lock (char *file,int flags,int mode,DOTLOCK *lock,int op);
283 void mmdf_unlock (int fd,MAILSTREAM *stream,DOTLOCK *lock);
284 int mmdf_parse (MAILSTREAM *stream,DOTLOCK *lock,int op);
285 char *mmdf_mbxline (MAILSTREAM *stream,STRING *bs,unsigned long *size);
286 unsigned long mmdf_pseudo (MAILSTREAM *stream,char *hdr);
287 unsigned long mmdf_xstatus (MAILSTREAM *stream,char *status,MESSAGECACHE *elt,
288 unsigned long uid,long flag);
289 long mmdf_rewrite (MAILSTREAM *stream,unsigned long *nexp,DOTLOCK *lock,
290 long flags);
291 long mmdf_extend (MAILSTREAM *stream,unsigned long size);
292 void mmdf_write (MMDFFILE *f,char *s,unsigned long i);
293 void mmdf_phys_write (MMDFFILE *f,char *buf,size_t size);
295 /* MMDF mail routines */
298 /* Driver dispatch used by MAIL */
300 DRIVER mmdfdriver = {
301 "mmdf", /* driver name */
302 /* driver flags */
303 DR_LOCAL|DR_MAIL|DR_LOCKING|DR_NONEWMAILRONLY|DR_XPOINT,
304 (DRIVER *) NIL, /* next driver */
305 mmdf_valid, /* mailbox is valid for us */
306 mmdf_parameters, /* manipulate parameters */
307 mmdf_scan, /* scan mailboxes */
308 mmdf_list, /* list mailboxes */
309 mmdf_lsub, /* list subscribed mailboxes */
310 NIL, /* subscribe to mailbox */
311 NIL, /* unsubscribe from mailbox */
312 mmdf_create, /* create mailbox */
313 mmdf_delete, /* delete mailbox */
314 mmdf_rename, /* rename mailbox */
315 mail_status_default, /* status of mailbox */
316 mmdf_open, /* open mailbox */
317 mmdf_close, /* close mailbox */
318 NIL, /* fetch message "fast" attributes */
319 NIL, /* fetch message flags */
320 NIL, /* fetch overview */
321 NIL, /* fetch message envelopes */
322 mmdf_header, /* fetch message header */
323 mmdf_text, /* fetch message text */
324 NIL, /* fetch partial message text */
325 NIL, /* unique identifier */
326 NIL, /* message number */
327 NIL, /* modify flags */
328 mmdf_flagmsg, /* per-message modify flags */
329 NIL, /* search for message based on criteria */
330 NIL, /* sort messages */
331 NIL, /* thread messages */
332 mmdf_ping, /* ping mailbox to see if still alive */
333 mmdf_check, /* check for new messages */
334 mmdf_expunge, /* expunge deleted messages */
335 mmdf_copy, /* copy messages to another mailbox */
336 mmdf_append, /* append string message to mailbox */
337 NIL /* garbage collect stream */
338 };
340 /* prototype stream */
341 MAILSTREAM mmdfproto = {&mmdfdriver};
343 char *mmdfhdr = MMDFHDRTXT; /* MMDF header */
345 /* MMDF mail validate mailbox
346 * Accepts: mailbox name
347 * Returns: our driver if name is valid, NIL otherwise
348 */
350 DRIVER *mmdf_valid (char *name)
351 {
352 char tmp[MAILTMPLEN];
353 return mmdf_isvalid (name,tmp) ? &mmdfdriver : NIL;
354 }
357 /* MMDF mail test for valid mailbox name
358 * Accepts: mailbox name
359 * scratch buffer
360 * Returns: T if valid, NIL otherwise
361 */
363 long mmdf_isvalid (char *name,char *tmp)
364 {
365 int fd;
366 int ret = NIL;
367 char *t,file[MAILTMPLEN];
368 struct stat sbuf;
369 time_t tp[2];
370 errno = EINVAL; /* assume invalid argument */
371 /* must be non-empty file */
372 if ((t = dummy_file (file,name)) && !stat (t,&sbuf)) {
373 if (!sbuf.st_size)errno = 0;/* empty file */
374 else if ((fd = open (file,O_RDONLY,NIL)) >= 0) {
375 /* error -1 for invalid format */
376 if (!(ret = mmdf_isvalid_fd (fd,tmp))) errno = -1;
377 close (fd); /* close the file */
378 /* \Marked status? */
379 if ((sbuf.st_ctime > sbuf.st_atime) || (sbuf.st_mtime > sbuf.st_atime)) {
380 tp[0] = sbuf.st_atime; /* preserve atime and mtime */
381 tp[1] = sbuf.st_mtime;
382 utime (file,tp); /* set the times */
383 }
384 }
385 }
386 return ret; /* return what we should */
387 }
389 /* MMDF mail test for valid mailbox
390 * Accepts: file descriptor
391 * scratch buffer
392 * Returns: T if valid, NIL otherwise
393 */
395 long mmdf_isvalid_fd (int fd,char *tmp)
396 {
397 int ret = NIL;
398 memset (tmp,'\0',MAILTMPLEN);
399 if (read (fd,tmp,MAILTMPLEN-1) >= 0) ret = ISMMDF (tmp) ? T : NIL;
400 return ret; /* return what we should */
401 }
404 /* MMDF manipulate driver parameters
405 * Accepts: function code
406 * function-dependent value
407 * Returns: function-dependent return value
408 */
410 void *mmdf_parameters (long function,void *value)
411 {
412 void *ret = NIL;
413 switch ((int) function) {
414 case GET_INBOXPATH:
415 if (value) ret = dummy_file ((char *) value,"INBOX");
416 break;
417 }
418 return ret;
419 }
421 /* MMDF mail scan mailboxes
422 * Accepts: mail stream
423 * reference
424 * pattern to search
425 * string to scan
426 */
428 void mmdf_scan (MAILSTREAM *stream,char *ref,char *pat,char *contents)
429 {
430 if (stream) dummy_scan (NIL,ref,pat,contents);
431 }
434 /* MMDF mail list mailboxes
435 * Accepts: mail stream
436 * reference
437 * pattern to search
438 */
440 void mmdf_list (MAILSTREAM *stream,char *ref,char *pat)
441 {
442 if (stream) dummy_list (NIL,ref,pat);
443 }
446 /* MMDF mail list subscribed mailboxes
447 * Accepts: mail stream
448 * reference
449 * pattern to search
450 */
452 void mmdf_lsub (MAILSTREAM *stream,char *ref,char *pat)
453 {
454 if (stream) dummy_lsub (NIL,ref,pat);
455 }
457 /* MMDF mail create mailbox
458 * Accepts: MAIL stream
459 * mailbox name to create
460 * Returns: T on success, NIL on failure
461 */
463 long mmdf_create (MAILSTREAM *stream,char *mailbox)
464 {
465 char *s,mbx[MAILTMPLEN],tmp[MAILTMPLEN];
466 long ret = NIL;
467 int i,fd;
468 time_t ti = time (0);
469 if (!(s = dummy_file (mbx,mailbox))) {
470 sprintf (tmp,"Can't create %.80s: invalid name",mailbox);
471 MM_LOG (tmp,ERROR);
472 }
473 /* create underlying file */
474 else if (dummy_create_path (stream,s,get_dir_protection (mailbox))) {
475 /* done if dir-only or whiner */
476 if (((s = strrchr (s,'/')) && !s[1]) ||
477 mail_parameters (NIL,GET_USERHASNOLIFE,NIL)) ret = T;
478 else if ((fd = open (mbx,O_WRONLY,
479 (long) mail_parameters (NIL,GET_MBXPROTECTION,NIL))) < 0) {
480 sprintf (tmp,"Can't reopen mailbox node %.80s: %s",mbx,strerror (errno));
481 MM_LOG (tmp,ERROR);
482 unlink (mbx); /* delete the file */
483 }
484 else { /* initialize header */
485 memset (tmp,'\0',MAILTMPLEN);
486 sprintf (tmp,"%sFrom %s %sDate: ",mmdfhdr,pseudo_from,ctime (&ti));
487 rfc822_date (s = tmp + strlen (tmp));
488 sprintf (s += strlen (s), /* write the pseudo-header */
489 "\nFrom: %s <%s@%s>\nSubject: %s\nX-IMAP: %010lu 0000000000",
490 pseudo_name,pseudo_from,mylocalhost (),pseudo_subject,
491 (unsigned long) ti);
492 for (i = 0; i < NUSERFLAGS; ++i) if (default_user_flag (i))
493 sprintf (s += strlen (s)," %s",default_user_flag (i));
494 sprintf (s += strlen (s),"\nStatus: RO\n\n%s\n%s",pseudo_msg,mmdfhdr);
495 if (write (fd,tmp,strlen (tmp)) > 0) ret = T;
496 else {
497 sprintf (tmp,"Can't initialize mailbox node %.80s: %s",mbx,
498 strerror (errno));
499 MM_LOG (tmp,ERROR);
500 unlink (mbx); /* delete the file */
501 }
502 close (fd); /* close file */
503 }
504 }
505 /* set proper protections */
506 return ret ? set_mbx_protections (mailbox,mbx) : NIL;
507 }
509 /* MMDF mail delete mailbox
510 * Accepts: MAIL stream
511 * mailbox name to delete
512 * Returns: T on success, NIL on failure
513 */
515 long mmdf_delete (MAILSTREAM *stream,char *mailbox)
516 {
517 return mmdf_rename (stream,mailbox,NIL);
518 }
521 /* MMDF mail rename mailbox
522 * Accepts: MAIL stream
523 * old mailbox name
524 * new mailbox name (or NIL for delete)
525 * Returns: T on success, NIL on failure
526 */
528 long mmdf_rename (MAILSTREAM *stream,char *old,char *newname)
529 {
530 long ret = NIL;
531 char c,*s = NIL;
532 char tmp[MAILTMPLEN],file[MAILTMPLEN],lock[MAILTMPLEN];
533 DOTLOCK lockx;
534 int fd,ld;
535 long i;
536 struct stat sbuf;
537 MM_CRITICAL (stream); /* get the c-client lock */
538 if (!dummy_file (file,old) ||
539 (newname && (!((s = mailboxfile (tmp,newname)) && *s) ||
540 ((s = strrchr (tmp,'/')) && !s[1]))))
541 sprintf (tmp,newname ?
542 "Can't rename mailbox %.80s to %.80s: invalid name" :
543 "Can't delete mailbox %.80s: invalid name",
544 old,newname);
545 /* lock out other c-clients */
546 else if ((ld = lockname (lock,file,LOCK_EX|LOCK_NB,&i)) < 0)
547 sprintf (tmp,"Mailbox %.80s is in use by another process",old);
549 else {
550 if ((fd = mmdf_lock (file,O_RDWR,
551 (long) mail_parameters (NIL,GET_MBXPROTECTION,NIL),
552 &lockx,LOCK_EX)) < 0)
553 sprintf (tmp,"Can't lock mailbox %.80s: %s",old,strerror (errno));
554 else {
555 if (newname) { /* want rename? */
556 /* found superior to destination name? */
557 if (s = strrchr (s,'/')) {
558 c = *++s; /* remember first character of inferior */
559 *s = '\0'; /* tie off to get just superior */
560 /* name doesn't exist, create it */
561 if ((stat (tmp,&sbuf) || ((sbuf.st_mode & S_IFMT) != S_IFDIR)) &&
562 !dummy_create_path (stream,tmp,get_dir_protection (newname))) {
563 mmdf_unlock (fd,NIL,&lockx);
564 mmdf_unlock (ld,NIL,NIL);
565 unlink (lock);
566 MM_NOCRITICAL (stream);
567 return ret; /* return success or failure */
568 }
569 *s = c; /* restore full name */
570 }
571 if (rename (file,tmp))
572 sprintf (tmp,"Can't rename mailbox %.80s to %.80s: %s",old,newname,
573 strerror (errno));
574 else ret = T; /* set success */
575 }
576 else if (unlink (file))
577 sprintf (tmp,"Can't delete mailbox %.80s: %s",old,strerror (errno));
578 else ret = T; /* set success */
579 mmdf_unlock (fd,NIL,&lockx);
580 }
581 mmdf_unlock (ld,NIL,NIL); /* flush the lock */
582 unlink (lock);
583 }
584 MM_NOCRITICAL (stream); /* no longer critical */
585 if (!ret) MM_LOG (tmp,ERROR); /* log error */
586 return ret; /* return success or failure */
587 }
589 /* MMDF mail open
590 * Accepts: Stream to open
591 * Returns: Stream on success, NIL on failure
592 */
594 MAILSTREAM *mmdf_open (MAILSTREAM *stream)
595 {
596 long i;
597 int fd;
598 char tmp[MAILTMPLEN];
599 DOTLOCK lock;
600 long retry;
601 /* return prototype for OP_PROTOTYPE call */
602 if (!stream) return user_flags (&mmdfproto);
603 retry = stream->silent ? 1 : KODRETRY;
604 if (stream->local) fatal ("mmdf recycle stream");
605 stream->local = memset (fs_get (sizeof (MMDFLOCAL)),0,sizeof (MMDFLOCAL));
606 /* note if an INBOX or not */
607 stream->inbox = !compare_cstring (stream->mailbox,"INBOX");
608 /* canonicalize the stream mailbox name */
609 if (!dummy_file (tmp,stream->mailbox)) {
610 sprintf (tmp,"Can't open - invalid name: %.80s",stream->mailbox);
611 MM_LOG (tmp,ERROR);
612 return NIL;
613 }
614 /* flush old name */
615 fs_give ((void **) &stream->mailbox);
616 /* save canonical name */
617 stream->mailbox = cpystr (tmp);
618 LOCAL->fd = LOCAL->ld = -1; /* no file or state locking yet */
619 LOCAL->buf = (char *) fs_get (CHUNKSIZE);
620 LOCAL->buflen = CHUNKSIZE - 1;
621 LOCAL->text.data = (unsigned char *) fs_get (CHUNKSIZE);
622 LOCAL->text.size = CHUNKSIZE - 1;
623 LOCAL->linebuf = (char *) fs_get (CHUNKSIZE);
624 LOCAL->linebuflen = CHUNKSIZE - 1;
625 stream->sequence++; /* bump sequence number */
627 /* make lock for read/write access */
628 if (!stream->rdonly) while (retry) {
629 /* try to lock file */
630 if ((fd = lockname (tmp,stream->mailbox,LOCK_EX|LOCK_NB,&i)) < 0) {
631 /* suppressing kiss-of-death? */
632 if (stream->nokod) retry = 0;
633 /* no, first time through? */
634 else if (retry-- == KODRETRY) {
635 /* learned other guy's PID and can signal? */
636 if (i && !kill ((int) i,SIGUSR2)) {
637 sprintf (tmp,"Trying to get mailbox lock from process %ld",i);
638 MM_LOG (tmp,WARN);
639 }
640 else retry = 0; /* give up */
641 }
642 if (!stream->silent) { /* nothing if silent stream */
643 if (retry) sleep (1); /* wait a second before trying again */
644 else MM_LOG ("Mailbox is open by another process, access is readonly",
645 WARN);
646 }
647 }
648 else { /* got the lock, nobody else can alter state */
649 LOCAL->ld = fd; /* note lock's fd and name */
650 LOCAL->lname = cpystr (tmp);
651 /* make sure mode OK (don't use fchmod()) */
652 chmod (LOCAL->lname,(long) mail_parameters (NIL,GET_LOCKPROTECTION,NIL));
653 if (stream->silent) i = 0;/* silent streams won't accept KOD */
654 else { /* note our PID in the lock */
655 sprintf (tmp,"%d",getpid ());
656 write (fd,tmp,(i = strlen (tmp))+1);
657 }
658 ftruncate (fd,i); /* make sure tied off */
659 fsync (fd); /* make sure it's available */
660 retry = 0; /* no more need to try */
661 }
662 }
664 /* parse mailbox */
665 stream->nmsgs = stream->recent = 0;
666 /* will we be able to get write access? */
667 if ((LOCAL->ld >= 0) && access (stream->mailbox,W_OK) && (errno == EACCES)) {
668 MM_LOG ("Can't get write access to mailbox, access is readonly",WARN);
669 flock (LOCAL->ld,LOCK_UN); /* release the lock */
670 close (LOCAL->ld); /* close the lock file */
671 LOCAL->ld = -1; /* no more lock fd */
672 unlink (LOCAL->lname); /* delete it */
673 }
674 /* reset UID validity */
675 stream->uid_validity = stream->uid_last = 0;
676 if (stream->silent && !stream->rdonly && (LOCAL->ld < 0))
677 mmdf_abort (stream); /* abort if can't get RW silent stream */
678 /* parse mailbox */
679 else if (mmdf_parse (stream,&lock,LOCK_SH)) {
680 mmdf_unlock (LOCAL->fd,stream,&lock);
681 mail_unlock (stream);
682 MM_NOCRITICAL (stream); /* done with critical */
683 }
684 if (!LOCAL) return NIL; /* failure if stream died */
685 /* make sure upper level knows readonly */
686 stream->rdonly = (LOCAL->ld < 0);
687 /* notify about empty mailbox */
688 if (!(stream->nmsgs || stream->silent)) MM_LOG ("Mailbox is empty",NIL);
689 if (!stream->rdonly) { /* flags stick if readwrite */
690 stream->perm_seen = stream->perm_deleted =
691 stream->perm_flagged = stream->perm_answered = stream->perm_draft = T;
692 if (!stream->uid_nosticky) {/* users with lives get permanent keywords */
693 stream->perm_user_flags = 0xffffffff;
694 /* and maybe can create them too! */
695 stream->kwd_create = stream->user_flags[NUSERFLAGS-1] ? NIL : T;
696 }
697 }
698 return stream; /* return stream alive to caller */
699 }
702 /* MMDF mail close
703 * Accepts: MAIL stream
704 * close options
705 */
707 void mmdf_close (MAILSTREAM *stream,long options)
708 {
709 int silent = stream->silent;
710 stream->silent = T; /* go silent */
711 /* expunge if requested */
712 if (options & CL_EXPUNGE) mmdf_expunge (stream,NIL,NIL);
713 /* else dump final checkpoint */
714 else if (LOCAL->dirty) mmdf_check (stream);
715 stream->silent = silent; /* restore old silence state */
716 mmdf_abort (stream); /* now punt the file and local data */
717 }
719 /* MMDF mail fetch message header
720 * Accepts: MAIL stream
721 * message # to fetch
722 * pointer to returned header text length
723 * option flags
724 * Returns: message header in RFC822 format
725 */
727 /* lines to filter from header */
728 static STRINGLIST *mmdf_hlines = NIL;
730 char *mmdf_header (MAILSTREAM *stream,unsigned long msgno,
731 unsigned long *length,long flags)
732 {
733 MESSAGECACHE *elt;
734 unsigned char *s,*t,*tl;
735 *length = 0; /* default to empty */
736 if (flags & FT_UID) return "";/* UID call "impossible" */
737 elt = mail_elt (stream,msgno);/* get cache */
738 if (!mmdf_hlines) { /* once only code */
739 STRINGLIST *lines = mmdf_hlines = mail_newstringlist ();
740 lines->text.size = strlen ((char *) (lines->text.data =
741 (unsigned char *) "Status"));
742 lines = lines->next = mail_newstringlist ();
743 lines->text.size = strlen ((char *) (lines->text.data =
744 (unsigned char *) "X-Status"));
745 lines = lines->next = mail_newstringlist ();
746 lines->text.size = strlen ((char *) (lines->text.data =
747 (unsigned char *) "X-Keywords"));
748 lines = lines->next = mail_newstringlist ();
749 lines->text.size = strlen ((char *) (lines->text.data =
750 (unsigned char *) "X-UID"));
751 lines = lines->next = mail_newstringlist ();
752 lines->text.size = strlen ((char *) (lines->text.data =
753 (unsigned char *) "X-IMAP"));
754 lines = lines->next = mail_newstringlist ();
755 lines->text.size = strlen ((char *) (lines->text.data =
756 (unsigned char *) "X-IMAPbase"));
757 }
758 /* go to header position */
759 lseek (LOCAL->fd,elt->private.special.offset +
760 elt->private.msg.header.offset,L_SET);
762 if (flags & FT_INTERNAL) { /* initial data OK? */
763 if (elt->private.msg.header.text.size > LOCAL->buflen) {
764 fs_give ((void **) &LOCAL->buf);
765 LOCAL->buf = (char *) fs_get ((LOCAL->buflen =
766 elt->private.msg.header.text.size) + 1);
767 }
768 /* read message */
769 read (LOCAL->fd,LOCAL->buf,elt->private.msg.header.text.size);
770 /* got text, tie off string */
771 LOCAL->buf[*length = elt->private.msg.header.text.size] = '\0';
772 /* squeeze out CRs (in case from PC) */
773 for (s = t = LOCAL->buf,tl = LOCAL->buf + *length; t < tl; t++)
774 if (*t != '\r') *s++ = *t;
775 *s = '\0';
776 *length = s - LOCAL->buf; /* adjust length */
777 }
778 else { /* need to make a CRLF version */
779 read (LOCAL->fd,s = (char *) fs_get (elt->private.msg.header.text.size+1),
780 elt->private.msg.header.text.size);
781 /* tie off string, and convert to CRLF */
782 s[elt->private.msg.header.text.size] = '\0';
783 *length = strcrlfcpy (&LOCAL->buf,&LOCAL->buflen,s,
784 elt->private.msg.header.text.size);
785 fs_give ((void **) &s); /* free readin buffer */
786 /* squeeze out spurious CRs */
787 for (s = t = LOCAL->buf,tl = LOCAL->buf + *length; t < tl; t++)
788 if ((*t != '\r') || (t[1] == '\n')) *s++ = *t;
789 *s = '\0';
790 *length = s - LOCAL->buf; /* adjust length */
791 }
792 *length = mail_filter (LOCAL->buf,*length,mmdf_hlines,FT_NOT);
793 return (char *) LOCAL->buf; /* return processed copy */
794 }
796 /* MMDF mail fetch message text
797 * Accepts: MAIL stream
798 * message # to fetch
799 * pointer to returned stringstruct
800 * option flags
801 * Returns: T on success, NIL if failure
802 */
804 long mmdf_text (MAILSTREAM *stream,unsigned long msgno,STRING *bs,long flags)
805 {
806 char *s;
807 unsigned long i;
808 MESSAGECACHE *elt;
809 /* UID call "impossible" */
810 if (flags & FT_UID) return NIL;
811 elt = mail_elt (stream,msgno);/* get cache element */
812 /* if message not seen */
813 if (!(flags & FT_PEEK) && !elt->seen) {
814 /* mark message seen and dirty */
815 elt->seen = elt->private.dirty = LOCAL->dirty = T;
816 MM_FLAGS (stream,msgno);
817 }
818 s = mmdf_text_work (stream,elt,&i,flags);
819 INIT (bs,mail_string,s,i); /* set up stringstruct */
820 return T; /* success */
821 }
823 /* MMDF mail fetch message text worker routine
824 * Accepts: MAIL stream
825 * message cache element
826 * pointer to returned header text length
827 * option flags
828 */
830 char *mmdf_text_work (MAILSTREAM *stream,MESSAGECACHE *elt,
831 unsigned long *length,long flags)
832 {
833 FDDATA d;
834 STRING bs;
835 unsigned char c,*s,*t,*tl,tmp[CHUNKSIZE];
836 /* go to text position */
837 lseek (LOCAL->fd,elt->private.special.offset +
838 elt->private.msg.text.offset,L_SET);
839 if (flags & FT_INTERNAL) { /* initial data OK? */
840 if (elt->private.msg.text.text.size > LOCAL->buflen) {
841 fs_give ((void **) &LOCAL->buf);
842 LOCAL->buf = (char *) fs_get ((LOCAL->buflen =
843 elt->private.msg.text.text.size) + 1);
844 }
845 /* read message */
846 read (LOCAL->fd,LOCAL->buf,elt->private.msg.text.text.size);
847 /* got text, tie off string */
848 LOCAL->buf[*length = elt->private.msg.text.text.size] = '\0';
849 /* squeeze out CRs (in case from PC) */
850 for (s = t = LOCAL->buf,tl = LOCAL->buf + *length; t < tl; t++)
851 if (*t != '\r') *s++ = *t;
852 *s = '\0';
853 *length = s - LOCAL->buf; /* adjust length */
854 return (char *) LOCAL->buf;
855 }
857 /* have it cached already? */
858 if (elt->private.uid != LOCAL->uid) {
859 /* not cached, cache it now */
860 LOCAL->uid = elt->private.uid;
861 /* is buffer big enough? */
862 if (elt->rfc822_size > LOCAL->text.size) {
863 /* excessively conservative, but the right thing is too hard to do */
864 fs_give ((void **) &LOCAL->text.data);
865 LOCAL->text.data = (unsigned char *)
866 fs_get ((LOCAL->text.size = elt->rfc822_size) + 1);
867 }
868 d.fd = LOCAL->fd; /* yes, set up file descriptor */
869 d.pos = elt->private.special.offset + elt->private.msg.text.offset;
870 d.chunk = tmp; /* initial buffer chunk */
871 d.chunksize = CHUNKSIZE; /* file chunk size */
872 INIT (&bs,fd_string,&d,elt->private.msg.text.text.size);
873 for (s = (char *) LOCAL->text.data; SIZE (&bs);) switch (c = SNX (&bs)) {
874 case '\r': /* carriage return seen */
875 break;
876 case '\n':
877 *s++ = '\r'; /* insert a CR */
878 default:
879 *s++ = c; /* copy characters */
880 }
881 *s = '\0'; /* tie off buffer */
882 /* calculate length of cached data */
883 LOCAL->textlen = s - LOCAL->text.data;
884 }
885 *length = LOCAL->textlen; /* return from cache */
886 return (char *) LOCAL->text.data;
887 }
889 /* MMDF per-message modify flag
890 * Accepts: MAIL stream
891 * message cache element
892 */
894 void mmdf_flagmsg (MAILSTREAM *stream,MESSAGECACHE *elt)
895 {
896 /* only after finishing */
897 if (elt->valid) elt->private.dirty = LOCAL->dirty = T;
898 }
901 /* MMDF mail ping mailbox
902 * Accepts: MAIL stream
903 * Returns: T if stream alive, else NIL
904 */
906 long mmdf_ping (MAILSTREAM *stream)
907 {
908 DOTLOCK lock;
909 struct stat sbuf;
910 long reparse;
911 /* big no-op if not readwrite */
912 if (LOCAL && (LOCAL->ld >= 0) && !stream->lock) {
913 if (stream->rdonly) { /* does he want to give up readwrite? */
914 /* checkpoint if we changed something */
915 if (LOCAL->dirty) mmdf_check (stream);
916 flock (LOCAL->ld,LOCK_UN);/* release readwrite lock */
917 close (LOCAL->ld); /* close the readwrite lock file */
918 LOCAL->ld = -1; /* no more readwrite lock fd */
919 unlink (LOCAL->lname); /* delete the readwrite lock file */
920 }
921 else { /* see if need to reparse */
922 if (!(reparse = (long) mail_parameters (NIL,GET_NETFSSTATBUG,NIL))) {
923 /* get current mailbox size */
924 if (LOCAL->fd >= 0) fstat (LOCAL->fd,&sbuf);
925 else if (stat (stream->mailbox,&sbuf)) {
926 sprintf (LOCAL->buf,"Mailbox stat failed, aborted: %s",
927 strerror (errno));
928 MM_LOG (LOCAL->buf,ERROR);
929 mmdf_abort (stream);
930 return NIL;
931 }
932 reparse = (sbuf.st_size != LOCAL->filesize);
933 }
934 /* parse if mailbox changed */
935 if ((LOCAL->ddirty || reparse) && mmdf_parse (stream,&lock,LOCK_EX)) {
936 /* force checkpoint if double-dirty */
937 if (LOCAL->ddirty) mmdf_rewrite (stream,NIL,&lock,NIL);
938 /* unlock mailbox */
939 else mmdf_unlock (LOCAL->fd,stream,&lock);
940 mail_unlock (stream); /* and stream */
941 /* done with critical */
942 MM_NOCRITICAL (stream);
943 }
944 }
945 }
946 return LOCAL ? LONGT : NIL; /* return if still alive */
947 }
949 /* MMDF mail check mailbox
950 * Accepts: MAIL stream
951 */
953 void mmdf_check (MAILSTREAM *stream)
954 {
955 DOTLOCK lock;
956 /* parse and lock mailbox */
957 if (LOCAL && (LOCAL->ld >= 0) && !stream->lock &&
958 mmdf_parse (stream,&lock,LOCK_EX)) {
959 /* any unsaved changes? */
960 if (LOCAL->dirty && mmdf_rewrite (stream,NIL,&lock,NIL)) {
961 if (!stream->silent) MM_LOG ("Checkpoint completed",NIL);
962 }
963 /* no checkpoint needed, just unlock */
964 else mmdf_unlock (LOCAL->fd,stream,&lock);
965 mail_unlock (stream); /* unlock the stream */
966 MM_NOCRITICAL (stream); /* done with critical */
967 }
968 }
971 /* MMDF mail expunge mailbox
972 * Accepts: MAIL stream
973 * sequence to expunge if non-NIL
974 * expunge options
975 * Returns: T, always
976 */
978 long mmdf_expunge (MAILSTREAM *stream,char *sequence,long options)
979 {
980 long ret;
981 unsigned long i;
982 DOTLOCK lock;
983 char *msg = NIL;
984 if (ret = (sequence ? ((options & EX_UID) ?
985 mail_uid_sequence (stream,sequence) :
986 mail_sequence (stream,sequence)) : LONGT) &&
987 LOCAL && (LOCAL->ld >= 0) && !stream->lock &&
988 mmdf_parse (stream,&lock,LOCK_EX)) {
989 /* check expunged messages if not dirty */
990 for (i = 1; !LOCAL->dirty && (i <= stream->nmsgs); i++) {
991 MESSAGECACHE *elt = mail_elt (stream,i);
992 if (mail_elt (stream,i)->deleted) LOCAL->dirty = T;
993 }
994 if (!LOCAL->dirty) { /* not dirty and no expunged messages */
995 mmdf_unlock (LOCAL->fd,stream,&lock);
996 msg = "No messages deleted, so no update needed";
997 }
998 else if (mmdf_rewrite (stream,&i,&lock,sequence ? LONGT : NIL)) {
999 if (i) sprintf (msg = LOCAL->buf,"Expunged %lu messages",i);
1000 else msg = "Mailbox checkpointed, but no messages expunged";
1002 /* rewrite failed */
1003 else mmdf_unlock (LOCAL->fd,stream,&lock);
1004 mail_unlock (stream); /* unlock the stream */
1005 MM_NOCRITICAL (stream); /* done with critical */
1006 if (msg && !stream->silent) MM_LOG (msg,NIL);
1008 else if (!stream->silent)
1009 MM_LOG ("Expunge ignored on readonly mailbox",WARN);
1010 return ret;
1013 /* MMDF mail copy message(s)
1014 * Accepts: MAIL stream
1015 * sequence
1016 * destination mailbox
1017 * copy options
1018 * Returns: T if copy successful, else NIL
1019 */
1021 long mmdf_copy (MAILSTREAM *stream,char *sequence,char *mailbox,long options)
1023 struct stat sbuf;
1024 int fd;
1025 char *s,file[MAILTMPLEN];
1026 DOTLOCK lock;
1027 time_t tp[2];
1028 unsigned long i,j;
1029 MESSAGECACHE *elt;
1030 long ret = T;
1031 mailproxycopy_t pc =
1032 (mailproxycopy_t) mail_parameters (stream,GET_MAILPROXYCOPY,NIL);
1033 copyuid_t cu = (copyuid_t) (mail_parameters (NIL,GET_USERHASNOLIFE,NIL) ?
1034 NIL : mail_parameters (NIL,GET_COPYUID,NIL));
1035 SEARCHSET *source = cu ? mail_newsearchset () : NIL;
1036 SEARCHSET *dest = cu ? mail_newsearchset () : NIL;
1037 MAILSTREAM *tstream = NIL;
1038 if (!((options & CP_UID) ? mail_uid_sequence (stream,sequence) :
1039 mail_sequence (stream,sequence))) return NIL;
1040 /* make sure destination is valid */
1041 if (!(mmdf_valid (mailbox) || !errno))
1042 switch (errno) {
1043 case ENOENT: /* no such file? */
1044 if (compare_cstring (mailbox,"INBOX")) {
1045 MM_NOTIFY (stream,"[TRYCREATE] Must create mailbox before copy",NIL);
1046 return NIL;
1048 if (pc) return (*pc) (stream,sequence,mailbox,options);
1049 mmdf_create (NIL,"INBOX");/* create empty INBOX */
1050 case EACCES: /* file protected */
1051 sprintf (LOCAL->buf,"Can't access destination: %.80s",mailbox);
1052 MM_LOG (LOCAL->buf,ERROR);
1053 return NIL;
1054 case EINVAL:
1055 if (pc) return (*pc) (stream,sequence,mailbox,options);
1056 sprintf (LOCAL->buf,"Invalid MMDF-format mailbox name: %.80s",mailbox);
1057 MM_LOG (LOCAL->buf,ERROR);
1058 return NIL;
1059 default:
1060 if (pc) return (*pc) (stream,sequence,mailbox,options);
1061 sprintf (LOCAL->buf,"Not a MMDF-format mailbox: %.80s",mailbox);
1062 MM_LOG (LOCAL->buf,ERROR);
1063 return NIL;
1066 /* try to open rewrite for UIDPLUS */
1067 if ((tstream = mail_open_work (&mmdfdriver,NIL,mailbox,
1068 OP_SILENT|OP_NOKOD)) && tstream->rdonly)
1069 tstream = mail_close (tstream);
1070 if (cu && !tstream) { /* wanted a COPYUID? */
1071 sprintf (LOCAL->buf,"Unable to write-open mailbox for COPYUID: %.80s",
1072 mailbox);
1073 MM_LOG (LOCAL->buf,WARN);
1074 cu = NIL; /* don't try to do COPYUID */
1076 LOCAL->buf[0] = '\0';
1077 MM_CRITICAL (stream); /* go critical */
1078 if ((fd = mmdf_lock (dummy_file (file,mailbox),O_WRONLY|O_APPEND,
1079 (long) mail_parameters (NIL,GET_MBXPROTECTION,NIL),
1080 &lock,LOCK_EX)) < 0) {
1081 MM_NOCRITICAL (stream); /* done with critical */
1082 sprintf (LOCAL->buf,"Can't open destination mailbox: %s",strerror (errno));
1083 MM_LOG (LOCAL->buf,ERROR); /* log the error */
1084 return NIL; /* failed */
1086 fstat (fd,&sbuf); /* get current file size */
1087 /* write all requested messages to mailbox */
1088 for (i = 1; ret && (i <= stream->nmsgs); i++)
1089 if ((elt = mail_elt (stream,i))->sequence) {
1090 lseek (LOCAL->fd,elt->private.special.offset,L_SET);
1091 read (LOCAL->fd,LOCAL->buf,elt->private.special.text.size);
1092 if (write (fd,LOCAL->buf,elt->private.special.text.size) < 0) ret = NIL;
1093 else { /* internal header succeeded */
1094 s = mmdf_header (stream,i,&j,FT_INTERNAL);
1095 /* header size, sans trailing newline */
1096 if (j && (s[j - 2] == '\n')) j--;
1097 if (write (fd,s,j) < 0) ret = NIL;
1098 else { /* message header succeeded */
1099 j = tstream ? /* write UIDPLUS data if have readwrite */
1100 mmdf_xstatus (stream,LOCAL->buf,elt,++(tstream->uid_last),LONGT) :
1101 mmdf_xstatus (stream,LOCAL->buf,elt,NIL,NIL);
1102 if (write (fd,LOCAL->buf,j) < 0) ret = NIL;
1103 else { /* message status succeeded */
1104 s = mmdf_text_work (stream,elt,&j,FT_INTERNAL);
1105 if ((write (fd,s,j) < 0) || (write (fd,mmdfhdr,MMDFHDRLEN) < 0))
1106 ret = NIL;
1107 else if (cu) { /* need to pass back new UID? */
1108 mail_append_set (source,mail_uid (stream,i));
1109 mail_append_set (dest,tstream->uid_last);
1116 if (!ret || fsync (fd)) { /* force out the update */
1117 sprintf (LOCAL->buf,"Message copy failed: %s",strerror (errno));
1118 ftruncate (fd,sbuf.st_size);
1119 ret = NIL;
1121 /* force UIDVALIDITY assignment now */
1122 if (tstream && !tstream->uid_validity) tstream->uid_validity = time (0);
1123 /* return sets if doing COPYUID */
1124 if (cu && ret) (*cu) (stream,mailbox,tstream->uid_validity,source,dest);
1125 else { /* flush any sets we may have built */
1126 mail_free_searchset (&source);
1127 mail_free_searchset (&dest);
1129 tp[1] = time (0); /* set mtime to now */
1130 if (ret) tp[0] = tp[1] - 1; /* set atime to now-1 if successful copy */
1131 else tp[0] = /* else preserve \Marked status */
1132 ((sbuf.st_ctime > sbuf.st_atime) || (sbuf.st_mtime > sbuf.st_atime)) ?
1133 sbuf.st_atime : tp[1];
1134 utime (file,tp); /* set the times */
1135 mmdf_unlock (fd,NIL,&lock); /* unlock and close mailbox */
1136 if (tstream) { /* update last UID if we can */
1137 MMDFLOCAL *local = (MMDFLOCAL *) tstream->local;
1138 local->dirty = T; /* do a rewrite */
1139 local->appending = T; /* but not at the cost of marking as old */
1140 tstream = mail_close (tstream);
1142 /* log the error */
1143 if (!ret) MM_LOG (LOCAL->buf,ERROR);
1144 /* delete if requested message */
1145 else if (options & CP_MOVE) for (i = 1; i <= stream->nmsgs; i++)
1146 if ((elt = mail_elt (stream,i))->sequence)
1147 elt->deleted = elt->private.dirty = LOCAL->dirty = T;
1148 MM_NOCRITICAL (stream); /* release critical */
1149 return ret;
1152 /* MMDF mail append message from stringstruct
1153 * Accepts: MAIL stream
1154 * destination mailbox
1155 * append callback
1156 * data for callback
1157 * Returns: T if append successful, else NIL
1158 */
1160 #define BUFLEN 8*MAILTMPLEN
1162 long mmdf_append (MAILSTREAM *stream,char *mailbox,append_t af,void *data)
1164 struct stat sbuf;
1165 int fd;
1166 unsigned long i;
1167 char *flags,*date,buf[BUFLEN],tmp[MAILTMPLEN],file[MAILTMPLEN];
1168 time_t tp[2];
1169 FILE *sf,*df;
1170 MESSAGECACHE elt;
1171 DOTLOCK lock;
1172 STRING *message;
1173 unsigned long uidlocation = 0;
1174 appenduid_t au = (appenduid_t)
1175 (mail_parameters (NIL,GET_USERHASNOLIFE,NIL) ? NIL :
1176 mail_parameters (NIL,GET_APPENDUID,NIL));
1177 SEARCHSET *dst = au ? mail_newsearchset () : NIL;
1178 long ret = LONGT;
1179 MAILSTREAM *tstream = NIL;
1180 /* default stream to prototype */
1181 if (!stream) { /* stream specified? */
1182 stream = &mmdfproto; /* no, default stream to prototype */
1183 for (i = 0; i < NUSERFLAGS && stream->user_flags[i]; ++i)
1184 fs_give ((void **) &stream->user_flags[i]);
1186 if (!mmdf_valid (mailbox)) switch (errno) {
1187 case ENOENT: /* no such file? */
1188 if (compare_cstring (mailbox,"INBOX")) {
1189 MM_NOTIFY (stream,"[TRYCREATE] Must create mailbox before append",NIL);
1190 return NIL;
1192 mmdf_create (NIL,"INBOX"); /* create empty INBOX */
1193 case 0: /* merely empty file? */
1194 tstream = stream;
1195 break;
1196 case EACCES: /* file protected */
1197 sprintf (tmp,"Can't access destination: %.80s",mailbox);
1198 MM_LOG (tmp,ERROR);
1199 return NIL;
1200 case EINVAL:
1201 sprintf (tmp,"Invalid MMDF-format mailbox name: %.80s",mailbox);
1202 MM_LOG (tmp,ERROR);
1203 return NIL;
1204 default:
1205 sprintf (tmp,"Not a MMDF-format mailbox: %.80s",mailbox);
1206 MM_LOG (tmp,ERROR);
1207 return NIL;
1209 /* get sniffing stream for keywords */
1210 else if (!(tstream = mail_open (NIL,mailbox,
1211 OP_READONLY|OP_SILENT|OP_NOKOD|OP_SNIFF))) {
1212 sprintf (tmp,"Unable to examine mailbox for APPEND: %.80s",mailbox);
1213 MM_LOG (tmp,ERROR);
1214 return NIL;
1217 /* get first message */
1218 if (!MM_APPEND (af) (tstream,data,&flags,&date,&message)) return NIL;
1219 if (!(sf = tmpfile ())) { /* must have scratch file */
1220 sprintf (tmp,".%lx.%lx",(unsigned long) time (0),(unsigned long)getpid ());
1221 if (!stat (tmp,&sbuf) || !(sf = fopen (tmp,"wb+"))) {
1222 sprintf (tmp,"Unable to create scratch file: %.80s",strerror (errno));
1223 MM_LOG (tmp,ERROR);
1224 return NIL;
1226 unlink (tmp);
1228 do { /* parse date */
1229 if (!date) rfc822_date (date = tmp);
1230 if (!mail_parse_date (&elt,date)) {
1231 sprintf (tmp,"Bad date in append: %.80s",date);
1232 MM_LOG (tmp,ERROR);
1234 else { /* user wants to suppress time zones? */
1235 if (mail_parameters (NIL,GET_NOTIMEZONES,NIL)) {
1236 time_t when = mail_longdate (&elt);
1237 date = ctime (&when); /* use traditional date */
1239 /* use POSIX-style date */
1240 else date = mail_cdate (tmp,&elt);
1241 if (!SIZE (message)) MM_LOG ("Append of zero-length message",ERROR);
1242 else if (!mmdf_collect_msg (tstream,sf,flags,date,message)) {
1243 sprintf (tmp,"Error writing scratch file: %.80s",strerror (errno));
1244 MM_LOG (tmp,ERROR);
1246 /* get next message */
1247 else if (MM_APPEND (af) (tstream,data,&flags,&date,&message)) continue;
1249 fclose (sf); /* punt scratch file */
1250 return NIL; /* give up */
1251 } while (message); /* until no more messages */
1252 if (fflush (sf)) {
1253 sprintf (tmp,"Error finishing scratch file: %.80s",strerror (errno));
1254 MM_LOG (tmp,ERROR);
1255 fclose (sf); /* punt scratch file */
1256 return NIL; /* give up */
1258 i = ftell (sf); /* size of scratch file */
1259 if (tstream != stream) tstream = mail_close (tstream);
1261 MM_CRITICAL (stream); /* go critical */
1262 /* try to open readwrite for UIDPLUS */
1263 if ((tstream = mail_open_work (&mmdfdriver,NIL,mailbox,
1264 OP_SILENT|OP_NOKOD)) && tstream->rdonly)
1265 tstream = mail_close (tstream);
1266 if (au && !tstream) { /* wanted an APPENDUID? */
1267 sprintf (tmp,"Unable to re-open mailbox for APPENDUID: %.80s",mailbox);
1268 MM_LOG (tmp,WARN);
1269 au = NIL;
1271 if (((fd = mmdf_lock (dummy_file (file,mailbox),O_WRONLY|O_APPEND,
1272 (long) mail_parameters (NIL,GET_MBXPROTECTION,NIL),
1273 &lock,LOCK_EX)) < 0) ||
1274 !(df = fdopen (fd,"ab"))) {
1275 MM_NOCRITICAL (stream); /* done with critical */
1276 sprintf (tmp,"Can't open append mailbox: %s",strerror (errno));
1277 MM_LOG (tmp,ERROR);
1278 return NIL;
1280 fstat (fd,&sbuf); /* get current file size */
1281 rewind (sf);
1282 tp[1] = time (0); /* set mtime to now */
1283 /* write all messages */
1284 if (!mmdf_append_msgs (tstream,sf,df,au ? dst : NIL) ||
1285 (fflush (df) == EOF) || fsync (fd)) {
1286 sprintf (buf,"Message append failed: %s",strerror (errno));
1287 MM_LOG (buf,ERROR);
1288 ftruncate (fd,sbuf.st_size);
1289 tp[0] = /* preserve \Marked status */
1290 ((sbuf.st_ctime > sbuf.st_atime) || (sbuf.st_mtime > sbuf.st_atime)) ?
1291 sbuf.st_atime : tp[1];
1292 ret = NIL; /* return error */
1294 else tp[0] = tp[1] - 1; /* set atime to now-1 if successful copy */
1295 utime (file,tp); /* set the times */
1296 fclose (sf); /* done with scratch file */
1297 /* force UIDVALIDITY assignment now */
1298 if (tstream && !tstream->uid_validity) tstream->uid_validity = time (0);
1299 /* return sets if doing APPENDUID */
1300 if (au && ret) (*au) (mailbox,tstream->uid_validity,dst);
1301 else mail_free_searchset (&dst);
1302 mmdf_unlock (fd,NIL,&lock); /* unlock and close mailbox */
1303 fclose (df);
1304 if (tstream) { /* update last UID if we can */
1305 MMDFLOCAL *local = (MMDFLOCAL *) tstream->local;
1306 local->dirty = T; /* do a rewrite */
1307 local->appending = T; /* but not at the cost of marking as old */
1308 tstream = mail_close (tstream);
1310 MM_NOCRITICAL (stream); /* release critical */
1311 return ret;
1314 /* Collect and write single message to append scratch file
1315 * Accepts: MAIL stream
1316 * scratch file
1317 * flags
1318 * date
1319 * message stringstruct
1320 * Returns: NIL if write error, else T
1321 */
1323 int mmdf_collect_msg (MAILSTREAM *stream,FILE *sf,char *flags,char *date,
1324 STRING *msg)
1326 unsigned char *s,*t;
1327 unsigned long uf;
1328 long f = mail_parse_flags (stream,flags,&uf);
1329 /* write metadata, note date ends with NL */
1330 if (fprintf (sf,"%ld %lu %s",f,SIZE (msg) + 1,date) < 0) return NIL;
1331 while (uf) /* write user flags */
1332 if ((s = stream->user_flags[find_rightmost_bit (&uf)]) &&
1333 (fprintf (sf," %s",s) < 0)) return NIL;
1334 if (putc ('\n',sf) == EOF) return NIL;
1335 while (SIZE (msg)) { /* copy text to scratch file */
1336 for (s = (unsigned char *) msg->curpos, t = s + msg->cursize; s < t; ++s)
1337 if (!*s) *s = 0x80; /* disallow NUL */
1338 /* write buffered text */
1339 if (fwrite (msg->curpos,1,msg->cursize,sf) == msg->cursize)
1340 SETPOS (msg,GETPOS (msg) + msg->cursize);
1341 else return NIL; /* failed */
1343 /* write trailing newline and return */
1344 return (putc ('\n',sf) == EOF) ? NIL : T;
1347 /* Append messages from scratch file to mailbox
1348 * Accepts: MAIL stream
1349 * source file
1350 * destination file
1351 * uidset to update if non-NIL
1352 * Returns: T if success, NIL if failure
1353 */
1355 int mmdf_append_msgs (MAILSTREAM *stream,FILE *sf,FILE *df,SEARCHSET *set)
1357 int c;
1358 long f;
1359 unsigned long i,j;
1360 char *x,tmp[MAILTMPLEN];
1361 int hdrp = T;
1362 /* get message metadata line */
1363 while (fgets (tmp,MAILTMPLEN,sf)) {
1364 if (!(isdigit (tmp[0]) && strchr (tmp,'\n'))) return NIL;
1365 f = strtol (tmp,&x,10); /* get flags */
1366 if (!((*x++ == ' ') && isdigit (*x))) return NIL;
1367 i = strtoul (x,&x,10); /* get message size */
1368 if ((*x++ != ' ') || /* build initial header */
1369 (fprintf (df,"%sFrom %s@%s %sStatus: ",mmdfhdr,myusername(),
1370 mylocalhost(),x) < 0) ||
1371 (f&fSEEN && (putc ('R',df) == EOF)) ||
1372 (fputs ("\nX-Status: ",df) == EOF) ||
1373 (f&fDELETED && (putc ('D',df) == EOF)) ||
1374 (f&fFLAGGED && (putc ('F',df) == EOF)) ||
1375 (f&fANSWERED && (putc ('A',df) == EOF)) ||
1376 (f&fDRAFT && (putc ('T',df) == EOF)) ||
1377 (fputs ("\nX-Keywords:",df) == EOF)) return NIL;
1378 /* copy keywords */
1379 while ((c = getc (sf)) != '\n') switch (c) {
1380 case EOF:
1381 return NIL;
1382 default:
1383 if (putc (c,df) == EOF) return NIL;
1385 if ((putc ('\n',df) == EOF) ||
1386 (set && (fprintf (df,"X-UID: %lu\n",++(stream->uid_last)) < 0)))
1387 return NIL;
1389 for (c = '\n'; i && fgets (tmp,MAILTMPLEN,sf); c = tmp[j-1]) {
1390 /* get read line length */
1391 if (i < (j = strlen (tmp))) fatal ("mmdf_append_msgs overrun");
1392 i -= j; /* number of bytes left */
1393 /* squish out ^A and CRs (note copies NUL) */
1394 for (x = tmp; x = strpbrk (x,"\01\r"); --j) memmove (x,x+1,j-(x-tmp));
1395 if (!j) continue; /* do nothing if line emptied */
1396 /* start of line? */
1397 if ((c == '\n')) switch (tmp[0]) {
1398 case 'S': case 's': /* possible "Status:" */
1399 if (hdrp && (j > 6) && ((tmp[1] == 't') || (tmp[1] == 'T')) &&
1400 ((tmp[2] == 'a') || (tmp[2] == 'A')) &&
1401 ((tmp[3] == 't') || (tmp[3] == 'T')) &&
1402 ((tmp[4] == 'u') || (tmp[4] == 'U')) &&
1403 ((tmp[5] == 's') || (tmp[5] == 'S')) && (tmp[6] == ':') &&
1404 (fputs ("X-Original-",df) == EOF)) return NIL;
1405 break;
1406 case 'X': case 'x': /* possible X-??? header */
1407 if (hdrp && (tmp[1] == '-') &&
1408 /* possible X-UID: */
1409 (((j > 5) && ((tmp[2] == 'U') || (tmp[2] == 'u')) &&
1410 ((tmp[3] == 'I') || (tmp[3] == 'i')) &&
1411 ((tmp[4] == 'D') || (tmp[4] == 'd')) && (tmp[5] == ':')) ||
1412 /* possible X-IMAP: */
1413 ((j > 6) && ((tmp[2] == 'I') || (tmp[2] == 'i')) &&
1414 ((tmp[3] == 'M') || (tmp[3] == 'm')) &&
1415 ((tmp[4] == 'A') || (tmp[4] == 'a')) &&
1416 ((tmp[5] == 'P') || (tmp[5] == 'p')) &&
1417 ((tmp[6] == ':') ||
1418 /* or X-IMAPbase: */
1419 ((j > 10) && ((tmp[6] == 'b') || (tmp[6] == 'B')) &&
1420 ((tmp[7] == 'a') || (tmp[7] == 'A')) &&
1421 ((tmp[8] == 's') || (tmp[8] == 'S')) &&
1422 ((tmp[9] == 'e') || (tmp[9] == 'E')) && (tmp[10] == ':')))) ||
1423 /* possible X-Status: */
1424 ((j > 8) && ((tmp[2] == 'S') || (tmp[2] == 's')) &&
1425 ((tmp[3] == 't') || (tmp[3] == 'T')) &&
1426 ((tmp[4] == 'a') || (tmp[4] == 'A')) &&
1427 ((tmp[5] == 't') || (tmp[5] == 'T')) &&
1428 ((tmp[6] == 'u') || (tmp[6] == 'U')) &&
1429 ((tmp[7] == 's') || (tmp[7] == 'S')) && (tmp[8] == ':')) ||
1430 /* possible X-Keywords: */
1431 ((j > 10) && ((tmp[2] == 'K') || (tmp[2] == 'k')) &&
1432 ((tmp[3] == 'e') || (tmp[3] == 'E')) &&
1433 ((tmp[4] == 'y') || (tmp[4] == 'Y')) &&
1434 ((tmp[5] == 'w') || (tmp[5] == 'W')) &&
1435 ((tmp[6] == 'o') || (tmp[6] == 'O')) &&
1436 ((tmp[7] == 'r') || (tmp[7] == 'R')) &&
1437 ((tmp[8] == 'd') || (tmp[8] == 'D')) &&
1438 ((tmp[9] == 's') || (tmp[9] == 'S')) && (tmp[10] == ':'))) &&
1439 (fputs ("X-Original-",df) == EOF)) return NIL;
1440 break;
1441 case '\n': /* blank line */
1442 hdrp = NIL;
1443 break;
1444 default: /* nothing to do */
1445 break;
1447 /* just write the line */
1448 if (fwrite (tmp,1,j,df) != j) return NIL;
1450 /* make sure read entire msg & wrote trailer */
1451 if (i || (fputs (mmdfhdr,df) == EOF)) return NIL;
1452 /* update set */
1453 if (stream) mail_append_set (set,stream->uid_last);
1455 return T;
1458 /* Internal routines */
1461 /* MMDF mail abort stream
1462 * Accepts: MAIL stream
1463 */
1465 void mmdf_abort (MAILSTREAM *stream)
1467 if (LOCAL) { /* only if a file is open */
1468 if (LOCAL->fd >= 0) close (LOCAL->fd);
1469 if (LOCAL->ld >= 0) { /* have a mailbox lock? */
1470 flock (LOCAL->ld,LOCK_UN);/* yes, release the lock */
1471 close (LOCAL->ld); /* close the lock file */
1472 unlink (LOCAL->lname); /* and delete it */
1474 if (LOCAL->lname) fs_give ((void **) &LOCAL->lname);
1475 /* free local text buffers */
1476 if (LOCAL->buf) fs_give ((void **) &LOCAL->buf);
1477 if (LOCAL->text.data) fs_give ((void **) &LOCAL->text.data);
1478 if (LOCAL->linebuf) fs_give ((void **) &LOCAL->linebuf);
1479 if (LOCAL->line) fs_give ((void **) &LOCAL->line);
1480 /* nuke the local data */
1481 fs_give ((void **) &stream->local);
1482 stream->dtb = NIL; /* log out the DTB */
1486 /* MMDF open and lock mailbox
1487 * Accepts: file name to open/lock
1488 * file open mode
1489 * destination buffer for lock file name
1490 * type of locking operation (LOCK_SH or LOCK_EX)
1491 */
1493 int mmdf_lock (char *file,int flags,int mode,DOTLOCK *lock,int op)
1495 int fd;
1496 blocknotify_t bn = (blocknotify_t) mail_parameters (NIL,GET_BLOCKNOTIFY,NIL);
1497 (*bn) (BLOCK_FILELOCK,NIL);
1498 /* try locking the easy way */
1499 if (dotlock_lock (file,lock,-1)) {
1500 /* got dotlock file, easy open */
1501 if ((fd = open (file,flags,mode)) >= 0) flock (fd,op);
1502 else dotlock_unlock (lock); /* open failed, free the dotlock */
1504 /* no dot lock file, open file now */
1505 else if ((fd = open (file,flags,mode)) >= 0) {
1506 /* try paranoid way to make a dot lock file */
1507 if (dotlock_lock (file,lock,fd)) {
1508 close (fd); /* get fresh fd in case of timing race */
1509 if ((fd = open (file,flags,mode)) >= 0) flock (fd,op);
1510 /* open failed, free the dotlock */
1511 else dotlock_unlock (lock);
1513 else flock (fd,op); /* paranoid way failed, just flock() it */
1515 (*bn) (BLOCK_NONE,NIL);
1516 return fd;
1519 /* MMDF unlock and close mailbox
1520 * Accepts: file descriptor
1521 * (optional) mailbox stream to check atime/mtime
1522 * (optional) lock file name
1523 */
1525 void mmdf_unlock (int fd,MAILSTREAM *stream,DOTLOCK *lock)
1527 if (stream) { /* need to muck with times? */
1528 struct stat sbuf;
1529 time_t tp[2];
1530 time_t now = time (0);
1531 fstat (fd,&sbuf); /* get file times */
1532 if (LOCAL->ld >= 0) { /* yes, readwrite session? */
1533 tp[0] = now; /* set atime to now */
1534 /* set mtime to (now - 1) if necessary */
1535 tp[1] = (now > sbuf.st_mtime) ? sbuf.st_mtime : now - 1;
1537 else if (stream->recent) { /* readonly with recent messages */
1538 if ((sbuf.st_atime >= sbuf.st_mtime) ||
1539 (sbuf.st_atime >= sbuf.st_ctime))
1540 /* keep past mtime, whack back atime */
1541 tp[0] = (tp[1] = (sbuf.st_mtime < now) ? sbuf.st_mtime : now) - 1;
1542 else now = 0; /* no time change needed */
1544 /* readonly with no recent messages */
1545 else if ((sbuf.st_atime < sbuf.st_mtime) ||
1546 (sbuf.st_atime < sbuf.st_ctime)) {
1547 tp[0] = now; /* set atime to now */
1548 /* set mtime to (now - 1) if necessary */
1549 tp[1] = (now > sbuf.st_mtime) ? sbuf.st_mtime : now - 1;
1551 else now = 0; /* no time change needed */
1552 /* set the times, note change */
1553 if (now && !utime (stream->mailbox,tp)) LOCAL->filetime = tp[1];
1555 flock (fd,LOCK_UN); /* release flock'ers */
1556 if (!stream) close (fd); /* close the file if no stream */
1557 dotlock_unlock (lock); /* flush the lock file if any */
1560 /* MMDF mail parse and lock mailbox
1561 * Accepts: MAIL stream
1562 * space to write lock file name
1563 * type of locking operation
1564 * Returns: T if parse OK, critical & mailbox is locked shared; NIL if failure
1565 */
1567 int mmdf_parse (MAILSTREAM *stream,DOTLOCK *lock,int op)
1569 int ti,zn,m;
1570 unsigned long i,j,k;
1571 unsigned char c,*s,*t,*u,tmp[MAILTMPLEN],date[30];
1572 int retain = T;
1573 unsigned long nmsgs = stream->nmsgs;
1574 unsigned long prevuid = nmsgs ? mail_elt (stream,nmsgs)->private.uid : 0;
1575 unsigned long recent = stream->recent;
1576 unsigned long oldnmsgs = stream->nmsgs;
1577 short silent = stream->silent;
1578 short pseudoseen = NIL;
1579 struct stat sbuf;
1580 STRING bs;
1581 FDDATA d;
1582 MESSAGECACHE *elt;
1583 mail_lock (stream); /* guard against recursion or pingers */
1584 /* toss out previous descriptor */
1585 if (LOCAL->fd >= 0) close (LOCAL->fd);
1586 MM_CRITICAL (stream); /* open and lock mailbox (shared OK) */
1587 if ((LOCAL->fd = mmdf_lock (stream->mailbox,(LOCAL->ld >= 0) ?
1588 O_RDWR : O_RDONLY,
1589 (long)mail_parameters(NIL,GET_MBXPROTECTION,NIL),
1590 lock,op)) < 0) {
1591 sprintf (tmp,"Mailbox open failed, aborted: %s",strerror (errno));
1592 MM_LOG (tmp,ERROR);
1593 mmdf_abort (stream);
1594 mail_unlock (stream);
1595 MM_NOCRITICAL (stream); /* done with critical */
1596 return NIL;
1598 fstat (LOCAL->fd,&sbuf); /* get status */
1599 /* validate change in size */
1600 if (sbuf.st_size < LOCAL->filesize) {
1601 sprintf (tmp,"Mailbox shrank from %lu to %lu bytes, aborted",
1602 (unsigned long) LOCAL->filesize,(unsigned long) sbuf.st_size);
1603 MM_LOG (tmp,ERROR); /* this is pretty bad */
1604 mmdf_unlock (LOCAL->fd,stream,lock);
1605 mmdf_abort (stream);
1606 mail_unlock (stream);
1607 MM_NOCRITICAL (stream); /* done with critical */
1608 return NIL;
1611 /* new data? */
1612 else if (i = sbuf.st_size - LOCAL->filesize) {
1613 d.fd = LOCAL->fd; /* yes, set up file descriptor */
1614 d.pos = LOCAL->filesize; /* get to that position in the file */
1615 d.chunk = LOCAL->buf; /* initial buffer chunk */
1616 d.chunksize = CHUNKSIZE; /* file chunk size */
1617 INIT (&bs,fd_string,&d,i); /* initialize stringstruct */
1618 /* skip leading whitespace for broken MTAs */
1619 while (((c = CHR (&bs)) == '\n') || (c == '\r') ||
1620 (c == ' ') || (c == '\t')) SNX (&bs);
1621 if (SIZE (&bs)) { /* read new data */
1622 /* remember internal header position */
1623 j = LOCAL->filesize + GETPOS (&bs);
1624 s = mmdf_mbxline (stream,&bs,&i);
1625 stream->silent = T; /* quell main program new message events */
1626 do { /* read MMDF header */
1627 if (!(i && ISMMDF (s))){/* see if valid MMDF header */
1628 sprintf (tmp,"Unexpected changes to mailbox (try restarting): %.20s",
1629 (char *) s);
1630 /* see if we can back up to a line */
1631 if (i && (j > MMDFHDRLEN)) {
1632 SETPOS (&bs,j -= MMDFHDRLEN);
1633 /* read previous line */
1634 s = mmdf_mbxline (stream,&bs,&i);
1635 /* kill the error if it looks good */
1636 if (i && ISMMDF (s)) tmp[0] = '\0';
1638 if (tmp[0]) {
1639 MM_LOG (tmp,ERROR);
1640 mmdf_unlock (LOCAL->fd,stream,lock);
1641 mmdf_abort (stream);
1642 mail_unlock (stream);
1643 MM_NOCRITICAL (stream);
1644 return NIL;
1647 /* instantiate first new message */
1648 mail_exists (stream,++nmsgs);
1649 (elt = mail_elt (stream,nmsgs))->valid = T;
1650 recent++; /* assume recent by default */
1651 elt->recent = T;
1652 /* note position/size of internal header */
1653 elt->private.special.offset = j;
1654 elt->private.special.text.size = i;
1656 s = mmdf_mbxline (stream,&bs,&i);
1657 ti = 0; /* assume not a valid date */
1658 zn = 0,t = NIL;
1659 if (i) VALID (s,t,ti,zn);
1660 if (ti) { /* generate plausible IMAPish date string */
1661 /* this is also part of header */
1662 elt->private.special.text.size += i;
1663 date[2] = date[6] = date[20] = '-'; date[11] = ' ';
1664 date[14] = date[17] = ':';
1665 /* dd */
1666 date[0] = t[ti - 2]; date[1] = t[ti - 1];
1667 /* mmm */
1668 date[3] = t[ti - 6]; date[4] = t[ti - 5]; date[5] = t[ti - 4];
1669 /* hh */
1670 date[12] = t[ti + 1]; date[13] = t[ti + 2];
1671 /* mm */
1672 date[15] = t[ti + 4]; date[16] = t[ti + 5];
1673 if (t[ti += 6]==':'){ /* ss */
1674 date[18] = t[++ti]; date[19] = t[++ti];
1675 ti++; /* move to space */
1677 else date[18] = date[19] = '0';
1678 /* yy -- advance over timezone if necessary */
1679 if (zn == ti) ti += (((t[zn+1] == '+') || (t[zn+1] == '-')) ? 6 : 4);
1680 date[7] = t[ti + 1]; date[8] = t[ti + 2];
1681 date[9] = t[ti + 3]; date[10] = t[ti + 4];
1682 /* zzz */
1683 t = zn ? (t + zn + 1) : (unsigned char *) "LCL";
1684 date[21] = *t++; date[22] = *t++; date[23] = *t++;
1685 if ((date[21] != '+') && (date[21] != '-')) date[24] = '\0';
1686 else { /* numeric time zone */
1687 date[24] = *t++; date[25] = *t++;
1688 date[26] = '\0'; date[20] = ' ';
1690 /* set internal date */
1691 if (!mail_parse_date (elt,date)) {
1692 sprintf (tmp,"Unable to parse internal date: %s",(char *) date);
1693 MM_LOG (tmp,WARN);
1696 else { /* make date from file date */
1697 struct tm *tm = gmtime (&sbuf.st_mtime);
1698 elt->day = tm->tm_mday; elt->month = tm->tm_mon + 1;
1699 elt->year = tm->tm_year + 1900 - BASEYEAR;
1700 elt->hours = tm->tm_hour; elt->minutes = tm->tm_min;
1701 elt->seconds = tm->tm_sec;
1702 elt->zhours = 0; elt->zminutes = 0;
1703 t = NIL; /* suppress line read */
1705 /* header starts here */
1706 elt->private.msg.header.offset = elt->private.special.text.size;
1708 do { /* look for message body */
1709 j = GETPOS (&bs); /* note position before line */
1710 if (t) s = t = mmdf_mbxline (stream,&bs,&i);
1711 else t = s; /* this line read was suppressed */
1712 if (ISMMDF (s)) { /* found terminator in header? */
1713 SETPOS (&bs,j); /* oops, back up before line */
1714 /* must insert a newline */
1715 elt->private.spare.data++;
1716 break; /* punt */
1718 /* this line is part of header */
1719 elt->private.msg.header.text.size += i;
1720 if (i) switch (*s) { /* check header lines */
1721 case 'X': /* possible X-???: line */
1722 if (s[1] == '-') { /* must be immediately followed by hyphen */
1723 /* X-Status: becomes Status: in S case */
1724 if (s[2] == 'S' && s[3] == 't' && s[4] == 'a' && s[5] == 't' &&
1725 s[6] == 'u' && s[7] == 's' && s[8] == ':') s += 2;
1726 /* possible X-Keywords */
1727 else if (s[2] == 'K' && s[3] == 'e' && s[4] == 'y' &&
1728 s[5] == 'w' && s[6] == 'o' && s[7] == 'r' &&
1729 s[8] == 'd' && s[9] == 's' && s[10] == ':') {
1730 SIZEDTEXT uf;
1731 retain = NIL; /* don't retain continuation */
1732 s += 11; /* flush leading whitespace */
1733 while (*s && (*s != '\n') && ((*s != '\r') || (s[1] != '\n'))){
1734 while (*s == ' ') s++;
1735 /* find end of keyword */
1736 if (!(u = strpbrk (s," \n\r"))) u = s + strlen (s);
1737 /* got a keyword? */
1738 if ((k = (u - s)) && (k <= MAXUSERFLAG)) {
1739 uf.data = (unsigned char *) s;
1740 uf.size = k;
1741 for (j = 0; (j < NUSERFLAGS) && stream->user_flags[j]; ++j)
1742 if (!compare_csizedtext (stream->user_flags[j],&uf)) {
1743 elt->user_flags |= ((long) 1) << j;
1744 break;
1747 s = u; /* advance to next keyword */
1749 break;
1752 /* possible X-IMAP */
1753 else if ((s[2] == 'I') && (s[3] == 'M') && (s[4] == 'A') &&
1754 (s[5] == 'P') && ((m = (s[6] == ':')) ||
1755 ((s[6] == 'b') && (s[7] == 'a') &&
1756 (s[8] == 's') && (s[9] == 'e') &&
1757 (s[10] == ':')))) {
1758 retain = NIL; /* don't retain continuation */
1759 if ((nmsgs == 1) && !stream->uid_validity) {
1760 /* advance to data */
1761 s += m ? 7 : 11;
1762 /* flush whitespace */
1763 while (*s == ' ') s++;
1764 j = 0; /* slurp UID validity */
1765 /* found a digit? */
1766 while (isdigit (*s)) {
1767 j *= 10; /* yes, add it in */
1768 j += *s++ - '0';
1770 /* flush whitespace */
1771 while (*s == ' ') s++;
1772 /* must have valid UID validity and UID last */
1773 if (j && isdigit (*s)) {
1774 /* pseudo-header seen if X-IMAP */
1775 if (m) pseudoseen = LOCAL->pseudo = T;
1776 /* save UID validity */
1777 stream->uid_validity = j;
1778 j = 0; /* slurp UID last */
1779 while (isdigit (*s)) {
1780 j *= 10; /* yes, add it in */
1781 j += *s++ - '0';
1783 /* save UID last */
1784 stream->uid_last = j;
1785 /* process keywords */
1786 for (j = 0; (*s != '\n') && ((*s != '\r')||(s[1] != '\n'));
1787 s = u,j++) {
1788 /* flush leading whitespace */
1789 while (*s == ' ') s++;
1790 u = strpbrk (s," \n\r");
1791 /* got a keyword? */
1792 if ((j < NUSERFLAGS) && (k = (u - s)) &&
1793 (k <= MAXUSERFLAG)) {
1794 if (stream->user_flags[j])
1795 fs_give ((void **) &stream->user_flags[j]);
1796 stream->user_flags[j] = (char *) fs_get (k + 1);
1797 strncpy (stream->user_flags[j],s,k);
1798 stream->user_flags[j][k] = '\0';
1803 break;
1806 /* possible X-UID */
1807 else if (s[2] == 'U' && s[3] == 'I' && s[4] == 'D' &&
1808 s[5] == ':') {
1809 retain = NIL; /* don't retain continuation */
1810 /* only believe if have a UID validity */
1811 if (stream->uid_validity && ((nmsgs > 1) || !pseudoseen)) {
1812 s += 6; /* advance to UID value */
1813 /* flush whitespace */
1814 while (*s == ' ') s++;
1815 j = 0;
1816 /* found a digit? */
1817 while (isdigit (*s)) {
1818 j *= 10; /* yes, add it in */
1819 j += *s++ - '0';
1821 /* flush remainder of line */
1822 while (*s != '\n') s++;
1823 /* make sure not duplicated */
1824 if (elt->private.uid)
1825 sprintf (tmp,"Message %lu UID %lu already has UID %lu",
1826 pseudoseen ? elt->msgno - 1 : elt->msgno,
1827 j,elt->private.uid);
1828 /* make sure UID doesn't go backwards */
1829 else if (j <= prevuid)
1830 sprintf (tmp,"Message %lu UID %lu less than %lu",
1831 pseudoseen ? elt->msgno - 1 : elt->msgno,
1832 j,prevuid + 1);
1833 #if 0 /* this is currently broken by UIDPLUS */
1834 /* or skip by mailbox's recorded last */
1835 else if (j > stream->uid_last)
1836 sprintf (tmp,"Message %lu UID %lu greater than last %lu",
1837 pseudoseen ? elt->msgno - 1 : elt->msgno,
1838 j,stream->uid_last);
1839 #endif
1840 else { /* normal UID case */
1841 prevuid = elt->private.uid = j;
1842 #if 1 /* temporary kludge for UIDPLUS */
1843 if (prevuid > stream->uid_last) {
1844 stream->uid_last = prevuid;
1845 LOCAL->ddirty = LOCAL->dirty = T;
1847 #endif
1848 break; /* exit this cruft */
1850 MM_LOG (tmp,WARN);
1851 /* invalidate UID validity */
1852 stream->uid_validity = 0;
1853 elt->private.uid = 0;
1855 break;
1858 /* otherwise fall into S case */
1860 case 'S': /* possible Status: line */
1861 if (s[0] == 'S' && s[1] == 't' && s[2] == 'a' && s[3] == 't' &&
1862 s[4] == 'u' && s[5] == 's' && s[6] == ':') {
1863 retain = NIL; /* don't retain continuation */
1864 s += 6; /* advance to status flags */
1865 do switch (*s++) {/* parse flags */
1866 case 'R': /* message read */
1867 elt->seen = T;
1868 break;
1869 case 'O': /* message old */
1870 if (elt->recent) {
1871 elt->recent = NIL;
1872 recent--; /* it really wasn't recent */
1874 break;
1875 case 'D': /* message deleted */
1876 elt->deleted = T;
1877 break;
1878 case 'F': /* message flagged */
1879 elt->flagged = T;
1880 break;
1881 case 'A': /* message answered */
1882 elt->answered = T;
1883 break;
1884 case 'T': /* message is a draft */
1885 elt->draft = T;
1886 break;
1887 default: /* some other crap */
1888 break;
1889 } while (*s && (*s != '\n') && ((*s != '\r') || (s[1] != '\n')));
1890 break; /* all done */
1892 /* otherwise fall into default case */
1894 default: /* ordinary header line */
1895 if ((*s == 'S') || (*s == 's') ||
1896 (((*s == 'X') || (*s == 'x')) && (s[1] == '-'))) {
1897 unsigned char *e,*v;
1898 /* must match what mail_filter() does */
1899 for (u = s,v = tmp,e = u + min (i,MAILTMPLEN - 1);
1900 (u < e) && ((c = (*u ? *u : (*u = ' '))) != ':') &&
1901 ((c > ' ') || ((c != ' ') && (c != '\t') &&
1902 (c != '\r') && (c != '\n')));
1903 *v++ = *u++);
1904 *v = '\0'; /* tie off */
1905 /* matches internal header? */
1906 if (!compare_cstring (tmp,"STATUS") ||
1907 !compare_cstring (tmp,"X-STATUS") ||
1908 !compare_cstring (tmp,"X-KEYWORDS") ||
1909 !compare_cstring (tmp,"X-UID") ||
1910 !compare_cstring (tmp,"X-IMAP") ||
1911 !compare_cstring (tmp,"X-IMAPBASE")) {
1912 char err[MAILTMPLEN];
1913 sprintf (err,"Discarding bogus %s header in message %lu",
1914 (char *) tmp,elt->msgno);
1915 MM_LOG (err,WARN);
1916 retain = NIL; /* don't retain continuation */
1917 break; /* different case or something */
1920 /* retain or non-continuation? */
1921 if (retain || ((*s != ' ') && (*s != '\t'))) {
1922 retain = T; /* retaining continuation now */
1923 /* line length in LF format newline */
1924 for (j = k = 0; j < i; ++j) if (s[j] != '\r') ++k;
1925 /* "internal" header size */
1926 elt->private.spare.data += k;
1927 /* message size */
1928 elt->rfc822_size += k + 1;
1930 else {
1931 char err[MAILTMPLEN];
1932 sprintf (err,"Discarding bogus continuation in msg %lu: %.80s",
1933 elt->msgno,(char *) s);
1934 if (u = strpbrk (err,"\r\n")) *u = '\0';
1935 MM_LOG (err,WARN);
1936 break; /* different case or something */
1938 break;
1940 } while (i && (*t != '\n') && ((*t != '\r') || (t[1] != '\n')));
1941 /* "internal" header sans trailing newline */
1942 if (i) elt->private.spare.data--;
1943 /* assign a UID if none found */
1944 if (((nmsgs > 1) || !pseudoseen) && !elt->private.uid) {
1945 prevuid = elt->private.uid = ++stream->uid_last;
1946 elt->private.dirty = T;
1948 else elt->private.dirty = elt->recent;
1950 /* note size of header, location of text */
1951 elt->private.msg.header.text.size =
1952 (elt->private.msg.text.offset =
1953 (LOCAL->filesize + GETPOS (&bs)) - elt->private.special.offset) -
1954 elt->private.special.text.size;
1955 /* note current position */
1956 j = LOCAL->filesize + GETPOS (&bs);
1957 if (i) do { /* look for next message */
1958 s = mmdf_mbxline (stream,&bs,&i);
1959 if (i) { /* got new data? */
1960 if (ISMMDF (s)) break;
1961 else { /* not a header line, add it to message */
1962 elt->rfc822_size += i;
1963 for (j = 0; j < i; ++j) switch (s[j]) {
1964 case '\r': /* squeeze out CRs */
1965 elt->rfc822_size -= 1;
1966 break;
1967 case '\n': /* LF becomes CRLF */
1968 elt->rfc822_size += 1;
1969 break;
1970 default:
1971 break;
1973 /* update current position */
1974 j = LOCAL->filesize + GETPOS (&bs);
1977 } while (i); /* until found a header */
1978 elt->private.msg.text.text.size = j -
1979 (elt->private.special.offset + elt->private.msg.text.offset);
1980 if (i) { /* get next header line */
1981 /* remember first internal header position */
1982 j = LOCAL->filesize + GETPOS (&bs);
1983 s = mmdf_mbxline (stream,&bs,&i);
1985 /* until end of buffer */
1986 } while (!stream->sniff && i);
1987 if (pseudoseen) { /* flush pseudo-message if present */
1988 /* decrement recent count */
1989 if (mail_elt (stream,1)->recent) recent--;
1990 /* and the exists count */
1991 mail_exists (stream,nmsgs--);
1992 mail_expunged(stream,1);/* fake an expunge of that message */
1994 /* need to start a new UID validity? */
1995 if (!stream->uid_validity) {
1996 stream->uid_validity = time (0);
1997 /* in case a whiner with no life */
1998 if (mail_parameters (NIL,GET_USERHASNOLIFE,NIL))
1999 stream->uid_nosticky = T;
2000 else if (nmsgs) { /* don't bother if empty file */
2001 /* make dirty to restart UID epoch */
2002 LOCAL->ddirty = LOCAL->dirty = T;
2003 /* need to rewrite msg 1 if not pseudo */
2004 if (!LOCAL->pseudo) mail_elt (stream,1)->private.dirty = T;
2005 MM_LOG ("Assigning new unique identifiers to all messages",NIL);
2008 stream->nmsgs = oldnmsgs; /* whack it back down */
2009 stream->silent = silent; /* restore old silent setting */
2010 /* notify upper level of new mailbox sizes */
2011 mail_exists (stream,nmsgs);
2012 mail_recent (stream,recent);
2013 /* mark dirty so O flags are set */
2014 if (recent) LOCAL->dirty = T;
2017 /* no change, don't babble if never got time */
2018 else if (LOCAL->filetime && LOCAL->filetime != sbuf.st_mtime)
2019 MM_LOG ("New mailbox modification time but apparently no changes",WARN);
2020 /* update parsed file size and time */
2021 LOCAL->filesize = sbuf.st_size;
2022 LOCAL->filetime = sbuf.st_mtime;
2023 return T; /* return the winnage */
2026 /* MMDF read line from mailbox
2027 * Accepts: mail stream
2028 * stringstruct
2029 * pointer to line size
2030 * Returns: pointer to input line
2031 */
2033 char *mmdf_mbxline (MAILSTREAM *stream,STRING *bs,unsigned long *size)
2035 unsigned long i,j,k,m;
2036 char *s,*t,*te;
2037 char *ret = "";
2038 /* flush old buffer */
2039 if (LOCAL->line) fs_give ((void **) &LOCAL->line);
2040 /* if buffer needs refreshing */
2041 if (!bs->cursize) SETPOS (bs,GETPOS (bs));
2042 if (SIZE (bs)) { /* find newline */
2043 /* end of fast scan */
2044 te = (t = (s = bs->curpos) + bs->cursize) - 12;
2045 while (s < te) if ((*s++ == '\n') || (*s++ == '\n') || (*s++ == '\n') ||
2046 (*s++ == '\n') || (*s++ == '\n') || (*s++ == '\n') ||
2047 (*s++ == '\n') || (*s++ == '\n') || (*s++ == '\n') ||
2048 (*s++ == '\n') || (*s++ == '\n') || (*s++ == '\n')) {
2049 --s; /* back up */
2050 break; /* exit loop */
2052 /* final character-at-a-time scan */
2053 while ((s < t) && (*s != '\n')) ++s;
2054 /* difficult case if line spans buffer */
2055 if ((i = s - bs->curpos) == bs->cursize) {
2056 /* have space in line buffer? */
2057 if (i > LOCAL->linebuflen) {
2058 fs_give ((void **) &LOCAL->linebuf);
2059 LOCAL->linebuf = (char *) fs_get (LOCAL->linebuflen = i);
2061 /* remember what we have so far */
2062 memcpy (LOCAL->linebuf,bs->curpos,i);
2063 /* load next buffer */
2064 SETPOS (bs,k = GETPOS (bs) + i);
2065 /* end of fast scan */
2066 te = (t = (s = bs->curpos) + bs->cursize) - 12;
2067 /* fast scan in overlap buffer */
2068 while (s < te) if ((*s++ == '\n') || (*s++ == '\n') || (*s++ == '\n') ||
2069 (*s++ == '\n') || (*s++ == '\n') || (*s++ == '\n') ||
2070 (*s++ == '\n') || (*s++ == '\n') || (*s++ == '\n') ||
2071 (*s++ == '\n') || (*s++ == '\n') || (*s++ == '\n')) {
2072 --s; /* back up */
2073 break; /* exit loop */
2076 /* final character-at-a-time scan */
2077 while ((s < t) && (*s != '\n')) ++s;
2078 /* huge line? */
2079 if ((j = s - bs->curpos) == bs->cursize) {
2080 SETPOS (bs,GETPOS (bs) + j);
2081 /* look for end of line (s-l-o-w!!) */
2082 for (m = SIZE (bs); m && (SNX (bs) != '\n'); --m,++j);
2083 SETPOS (bs,k); /* go back to where it started */
2085 /* got size of data, make buffer for return */
2086 ret = LOCAL->line = (char *) fs_get (i + j + 2);
2087 /* copy first chunk */
2088 memcpy (ret,LOCAL->linebuf,i);
2089 while (j) { /* copy remainder */
2090 if (!bs->cursize) SETPOS (bs,GETPOS (bs));
2091 memcpy (ret + i,bs->curpos,k = min (j,bs->cursize));
2092 i += k; /* account for this much read in */
2093 j -= k;
2094 bs->curpos += k; /* increment new position */
2095 bs->cursize -= k; /* eat that many bytes */
2097 /* read newline at end */
2098 if (SIZE (bs)) ret[i++] = SNX (bs);
2099 ret[i] = '\0'; /* makes debugging easier */
2101 else { /* this is easy */
2102 ret = bs->curpos; /* string it at this position */
2103 bs->curpos += ++i; /* increment new position */
2104 bs->cursize -= i; /* eat that many bytes */
2106 *size = i; /* return that to user */
2108 else *size = 0; /* end of data, return empty */
2109 /* embedded MMDF header at end of line? */
2110 if ((*size > sizeof (MMDFHDRTXT)) &&
2111 (s = ret + *size - (i = sizeof (MMDFHDRTXT) - 1)) && ISMMDF (s)) {
2112 SETPOS (bs,GETPOS (bs) - i);/* back up to start of MMDF header */
2113 *size -= i; /* reduce length of line */
2114 ret[*size - 1] = '\n'; /* force newline at end */
2116 return ret;
2119 /* MMDF make pseudo-header
2120 * Accepts: MAIL stream
2121 * buffer to write pseudo-header
2122 * Returns: length of pseudo-header
2123 */
2125 unsigned long mmdf_pseudo (MAILSTREAM *stream,char *hdr)
2127 int i;
2128 char *s,tmp[MAILTMPLEN];
2129 time_t now = time (0);
2130 rfc822_fixed_date (tmp);
2131 sprintf (hdr,"%sFrom %s %.24s\nDate: %s\nFrom: %s <%s@%.80s>\nSubject: %s\nMessage-ID: <%lu@%.80s>\nX-IMAP: %010lu %010lu",
2132 mmdfhdr,pseudo_from,ctime (&now),
2133 tmp,pseudo_name,pseudo_from,mylocalhost (),pseudo_subject,
2134 (unsigned long) now,mylocalhost (),stream->uid_validity,
2135 stream->uid_last);
2136 for (s = hdr + strlen (hdr),i = 0; i < NUSERFLAGS; ++i)
2137 if (stream->user_flags[i])
2138 sprintf (s += strlen (s)," %s",stream->user_flags[i]);
2139 sprintf (s += strlen (s),"\nStatus: RO\n\n%s\n%s",pseudo_msg,mmdfhdr);
2140 return strlen (hdr);
2143 /* MMDF make status string
2144 * Accepts: MAIL stream
2145 * destination string to write
2146 * message cache entry
2147 * UID to write if non-zero (else use elt->private.uid)
2148 * non-zero flag to write UID (.LT. 0 to write UID base info too)
2149 * Returns: length of string
2150 */
2152 unsigned long mmdf_xstatus (MAILSTREAM *stream,char *status,MESSAGECACHE *elt,
2153 unsigned long uid,long flag)
2155 char *t,stack[64];
2156 char *s = status;
2157 unsigned long n;
2158 int pad = 50;
2159 int sticky = uid ? T : !stream->uid_nosticky;
2160 /* This used to use sprintf(), but thanks to certain cretinous C libraries
2161 with horribly slow implementations of sprintf() I had to change it to this
2162 mess. At least it should be fast. */
2163 if ((flag < 0) && sticky) { /* need to write X-IMAPbase: header? */
2164 *s++ = 'X'; *s++ = '-'; *s++ = 'I'; *s++ = 'M'; *s++ = 'A'; *s++ = 'P';
2165 *s++ = 'b'; *s++ = 'a'; *s++ = 's'; *s++ = 'e'; *s++ = ':'; *s++ = ' ';
2166 t = stack;
2167 n = stream->uid_validity; /* push UID validity digits on the stack */
2168 do *t++ = (char) (n % 10) + '0';
2169 while (n /= 10);
2170 /* pop UID validity digits from stack */
2171 while (t > stack) *s++ = *--t;
2172 *s++ = ' ';
2173 n = stream->uid_last; /* push UID last digits on the stack */
2174 do *t++ = (char) (n % 10) + '0';
2175 while (n /= 10);
2176 /* pop UID last digits from stack */
2177 while (t > stack) *s++ = *--t;
2178 for (n = 0; n < NUSERFLAGS; ++n) if (t = stream->user_flags[n])
2179 for (*s++ = ' '; *t; *s++ = *t++);
2180 *s++ = '\n';
2181 pad += 30; /* increased padding if have IMAPbase */
2183 *s++ = 'S'; *s++ = 't'; *s++ = 'a'; *s++ = 't'; *s++ = 'u'; *s++ = 's';
2184 *s++ = ':'; *s++ = ' ';
2185 if (elt->seen) *s++ = 'R';
2186 /* only write O if have a UID */
2187 if (flag && (!elt->recent || !LOCAL->appending)) *s++ = 'O';
2188 *s++ = '\n';
2189 *s++ = 'X'; *s++ = '-'; *s++ = 'S'; *s++ = 't'; *s++ = 'a'; *s++ = 't';
2190 *s++ = 'u'; *s++ = 's'; *s++ = ':'; *s++ = ' ';
2191 if (elt->deleted) *s++ = 'D';
2192 if (elt->flagged) *s++ = 'F';
2193 if (elt->answered) *s++ = 'A';
2194 if (elt->draft) *s++ = 'T';
2195 *s++ = '\n';
2197 if (sticky) { /* only do this if UIDs sticky */
2198 *s++ = 'X'; *s++ = '-'; *s++ = 'K'; *s++ = 'e'; *s++ = 'y'; *s++ = 'w';
2199 *s++ = 'o'; *s++ = 'r'; *s++ = 'd'; *s++ = 's'; *s++ = ':';
2200 if (n = elt->user_flags) do {
2201 *s++ = ' ';
2202 for (t = stream->user_flags[find_rightmost_bit (&n)]; *t; *s++ = *t++);
2203 } while (n);
2204 n = s - status; /* get size of stuff so far */
2205 /* pad X-Keywords to make size constant */
2206 if (n < pad) for (n = pad - n; n > 0; --n) *s++ = ' ';
2207 *s++ = '\n';
2208 if (flag) { /* want to include UID? */
2209 t = stack;
2210 /* push UID digits on the stack */
2211 n = uid ? uid : elt->private.uid;
2212 do *t++ = (char) (n % 10) + '0';
2213 while (n /= 10);
2214 *s++ = 'X'; *s++ = '-'; *s++ = 'U'; *s++ = 'I'; *s++ = 'D'; *s++ = ':';
2215 *s++ = ' ';
2216 /* pop UID from stack */
2217 while (t > stack) *s++ = *--t;
2218 *s++ = '\n';
2221 *s++ = '\n'; *s = '\0'; /* end of extended message status */
2222 return s - status; /* return size of resulting string */
2225 /* Rewrite mailbox file
2226 * Accepts: MAIL stream, must be critical and locked
2227 * return pointer to number of expunged messages if want expunge
2228 * lock file name
2229 * expunge sequence, not deleted flag
2230 * Returns: T if success and mailbox unlocked, NIL if failure
2231 */
2233 #define OVERFLOWBUFLEN 8192 /* initial overflow buffer length */
2235 long mmdf_rewrite (MAILSTREAM *stream,unsigned long *nexp,DOTLOCK *lock,
2236 long flags)
2238 MESSAGECACHE *elt;
2239 MMDFFILE f;
2240 char *s;
2241 time_t tp[2];
2242 long ret,flag;
2243 unsigned long i,j;
2244 unsigned long recent = stream->recent;
2245 unsigned long size = LOCAL->pseudo ? mmdf_pseudo (stream,LOCAL->buf) : 0;
2246 if (nexp) *nexp = 0; /* initially nothing expunged */
2247 /* calculate size of mailbox after rewrite */
2248 for (i = 1,flag = LOCAL->pseudo ? 1 : -1; i <= stream->nmsgs; i++) {
2249 elt = mail_elt (stream,i); /* get cache */
2250 if (!(nexp && elt->deleted && (flags ? elt->sequence : T))) {
2251 /* add RFC822 size of this message */
2252 size += elt->private.special.text.size + elt->private.spare.data +
2253 mmdf_xstatus (stream,LOCAL->buf,elt,NIL,flag) +
2254 elt->private.msg.text.text.size + MMDFHDRLEN;
2255 flag = 1; /* only count X-IMAPbase once */
2258 /* no messages, has a life, and no pseudo */
2259 if (!size && !mail_parameters (NIL,GET_USERHASNOLIFE,NIL)) {
2260 LOCAL->pseudo = T; /* so make a pseudo-message now */
2261 size = mmdf_pseudo (stream,LOCAL->buf);
2263 /* extend the file as necessary */
2264 if (ret = mmdf_extend (stream,size)) {
2265 /* Set up buffered I/O file structure
2266 * curpos current position being written through buffering
2267 * filepos current position being written physically to the disk
2268 * bufpos current position being written in the buffer
2269 * protect current maximum position that can be written to the disk
2270 * before buffering is forced
2271 * The code tries to buffer so that that disk is written in multiples of
2272 * OVERBLOWBUFLEN bytes.
2273 */
2274 f.stream = stream; /* note mail stream */
2275 f.curpos = f.filepos = 0; /* start of file */
2276 f.protect = stream->nmsgs ? /* initial protection pointer */
2277 mail_elt (stream,1)->private.special.offset : 8192;
2278 f.bufpos = f.buf = (char *) fs_get (f.buflen = OVERFLOWBUFLEN);
2280 if (LOCAL->pseudo) /* update pseudo-header */
2281 mmdf_write (&f,LOCAL->buf,mmdf_pseudo (stream,LOCAL->buf));
2282 /* loop through all messages */
2283 for (i = 1,flag = LOCAL->pseudo ? 1 : -1; i <= stream->nmsgs;) {
2284 elt = mail_elt (stream,i);/* get cache */
2285 /* expunge this message? */
2286 if (nexp && elt->deleted && (flags ? elt->sequence : T)) {
2287 /* one less recent message */
2288 if (elt->recent) --recent;
2289 mail_expunged(stream,i);/* notify upper levels */
2290 ++*nexp; /* count up one more expunged message */
2292 else { /* preserve this message */
2293 i++; /* advance to next message */
2294 if ((flag < 0) || /* need to rewrite message? */
2295 elt->private.dirty || (f.curpos != elt->private.special.offset) ||
2296 (elt->private.msg.header.text.size !=
2297 (elt->private.spare.data +
2298 mmdf_xstatus (stream,LOCAL->buf,elt,NIL,flag)))) {
2299 unsigned long newoffset = f.curpos;
2300 /* yes, seek to internal header */
2301 lseek (LOCAL->fd,elt->private.special.offset,L_SET);
2302 read (LOCAL->fd,LOCAL->buf,elt->private.special.text.size);
2303 /* see if need to squeeze out a CR */
2304 if (LOCAL->buf[elt->private.special.text.size - 2] == '\r') {
2305 LOCAL->buf[--elt->private.special.text.size - 1] = '\n';
2306 --size; /* squeezed out a CR from PC */
2308 /* protection pointer moves to RFC822 header */
2309 f.protect = elt->private.special.offset +
2310 elt->private.msg.header.offset;
2311 /* write internal header */
2312 mmdf_write (&f,LOCAL->buf,elt->private.special.text.size);
2313 /* get RFC822 header */
2314 s = mmdf_header (stream,elt->msgno,&j,FT_INTERNAL);
2315 /* in case this got decremented */
2316 elt->private.msg.header.offset = elt->private.special.text.size;
2317 /* header size, sans trailing newline */
2318 if ((j < 2) || (s[j - 2] == '\n')) j--;
2319 /* this can happen if CRs were squeezed */
2320 if (j < elt->private.spare.data) {
2321 /* so fix up counts */
2322 size -= elt->private.spare.data - j;
2323 elt->private.spare.data = j;
2325 else if (j != elt->private.spare.data)
2326 fatal ("header size inconsistent");
2327 /* protection pointer moves to RFC822 text */
2328 f.protect = elt->private.special.offset +
2329 elt->private.msg.text.offset;
2330 mmdf_write (&f,s,j); /* write RFC822 header */
2331 /* write status and UID */
2332 mmdf_write (&f,LOCAL->buf,
2333 j = mmdf_xstatus (stream,LOCAL->buf,elt,NIL,flag));
2334 flag = 1; /* only write X-IMAPbase once */
2335 /* new file header size */
2336 elt->private.msg.header.text.size = elt->private.spare.data + j;
2338 /* did text move? */
2339 if (f.curpos != f.protect) {
2340 /* get message text */
2341 s = mmdf_text_work (stream,elt,&j,FT_INTERNAL);
2342 /* this can happen if CRs were squeezed */
2343 if (j < elt->private.msg.text.text.size) {
2344 /* so fix up counts */
2345 size -= elt->private.msg.text.text.size - j;
2346 elt->private.msg.text.text.size = j;
2348 /* can't happen it says here */
2349 else if (j > elt->private.msg.text.text.size)
2350 fatal ("text size inconsistent");
2351 /* new text offset, status/UID may change it */
2352 elt->private.msg.text.offset = f.curpos - newoffset;
2353 /* protection pointer moves to next message */
2354 f.protect = (i <= stream->nmsgs) ?
2355 mail_elt (stream,i)->private.special.offset :
2356 (f.curpos + j + MMDFHDRLEN);
2357 mmdf_write (&f,s,j);/* write text */
2358 /* write trailing newline */
2359 mmdf_write (&f,mmdfhdr,MMDFHDRLEN);
2361 else { /* tie off header and status */
2362 mmdf_write (&f,NIL,NIL);
2363 f.curpos = f.protect =/* restart everything at end of message */
2364 f.filepos += elt->private.msg.text.text.size + MMDFHDRLEN;
2366 /* new internal header offset */
2367 elt->private.special.offset = newoffset;
2368 elt->private.dirty =NIL;/* message is now clean */
2370 else { /* no need to rewrite this message */
2371 /* tie off previous message if needed */
2372 mmdf_write (&f,NIL,NIL);
2373 f.curpos = f.protect =/* restart everything at end of message */
2374 f.filepos += elt->private.special.text.size +
2375 elt->private.msg.header.text.size +
2376 elt->private.msg.text.text.size + MMDFHDRLEN;
2381 mmdf_write (&f,NIL,NIL); /* tie off final message */
2382 if (size != f.filepos) fatal ("file size inconsistent");
2383 fs_give ((void **) &f.buf); /* free buffer */
2384 /* make sure tied off */
2385 ftruncate (LOCAL->fd,LOCAL->filesize = size);
2386 fsync (LOCAL->fd); /* make sure the updates take */
2387 if (size && (flag < 0)) fatal ("lost UID base information");
2388 /* no longer dirty */
2389 LOCAL->ddirty = LOCAL->dirty = NIL;
2390 /* notify upper level of new mailbox sizes */
2391 mail_exists (stream,stream->nmsgs);
2392 mail_recent (stream,recent);
2393 /* set atime to now, mtime a second earlier */
2394 tp[1] = (tp[0] = time (0)) - 1;
2395 /* set the times, note change */
2396 if (!utime (stream->mailbox,tp)) LOCAL->filetime = tp[1];
2397 close (LOCAL->fd); /* close and reopen file */
2398 if ((LOCAL->fd = open (stream->mailbox,O_RDWR,
2399 (long) mail_parameters (NIL,GET_MBXPROTECTION,NIL)))
2400 < 0) {
2401 sprintf (LOCAL->buf,"Mailbox open failed, aborted: %s",strerror (errno));
2402 MM_LOG (LOCAL->buf,ERROR);
2403 mmdf_abort (stream);
2405 dotlock_unlock (lock); /* flush the lock file */
2407 return ret; /* return state from algorithm */
2410 /* Extend MMDF mailbox file
2411 * Accepts: MAIL stream
2412 * new desired size
2413 * Return: T if success, else NIL
2414 */
2416 long mmdf_extend (MAILSTREAM *stream,unsigned long size)
2418 unsigned long i = (size > LOCAL->filesize) ? size - LOCAL->filesize : 0;
2419 if (i) { /* does the mailbox need to grow? */
2420 if (i > LOCAL->buflen) { /* make sure have enough space */
2421 /* this user won the lottery all right */
2422 fs_give ((void **) &LOCAL->buf);
2423 LOCAL->buf = (char *) fs_get ((LOCAL->buflen = i) + 1);
2425 memset (LOCAL->buf,'\0',i); /* get a block of nulls */
2426 while (T) { /* until write successful or punt */
2427 lseek (LOCAL->fd,LOCAL->filesize,L_SET);
2428 if ((write (LOCAL->fd,LOCAL->buf,i) >= 0) && !fsync (LOCAL->fd)) break;
2429 else {
2430 long e = errno; /* note error before doing ftruncate */
2431 ftruncate (LOCAL->fd,LOCAL->filesize);
2432 if (MM_DISKERROR (stream,e,NIL)) {
2433 fsync (LOCAL->fd); /* user chose to punt */
2434 sprintf (LOCAL->buf,"Unable to extend mailbox: %s",strerror (e));
2435 if (!stream->silent) MM_LOG (LOCAL->buf,ERROR);
2436 return NIL;
2441 return LONGT;
2444 /* Write data to buffered file
2445 * Accepts: buffered file pointer
2446 * file data or NIL to indicate "flush buffer"
2447 * date size (ignored for "flush buffer")
2448 * Does not return until success
2449 */
2451 void mmdf_write (MMDFFILE *f,char *buf,unsigned long size)
2453 unsigned long i,j,k;
2454 if (buf) { /* doing buffered write? */
2455 i = f->bufpos - f->buf; /* yes, get size of current buffer data */
2456 /* yes, have space in current buffer chunk? */
2457 if (j = i ? ((f->buflen - i) % OVERFLOWBUFLEN) : f->buflen) {
2458 /* yes, fill up buffer as much as we can */
2459 memcpy (f->bufpos,buf,k = min (j,size));
2460 f->bufpos += k; /* new buffer position */
2461 f->curpos += k; /* new current position */
2462 if (j -= k) return; /* all done if still have buffer free space */
2463 buf += k; /* full, get new unwritten data pointer */
2464 size -= k; /* new data size */
2465 i += k; /* new buffer data size */
2467 /* This chunk of the buffer is full. See if can make some space by
2468 * writing to the disk, if there's enough unprotected space to do so.
2469 * Try to fill out any unaligned chunk, along with any subsequent full
2470 * chunks that will fit in unprotected space.
2471 */
2472 /* any unprotected space we can write to? */
2473 if (j = min (i,f->protect - f->filepos)) {
2474 /* yes, filepos not at chunk boundary? */
2475 if ((k = f->filepos % OVERFLOWBUFLEN) && ((k = OVERFLOWBUFLEN - k) < j))
2476 j -= k; /* yes, and can write out partial chunk */
2477 else k = 0; /* no partial chunk to write */
2478 /* if at least a chunk free, write that too */
2479 if (j > OVERFLOWBUFLEN) k += j - (j % OVERFLOWBUFLEN);
2480 if (k) { /* write data if there is anything we can */
2481 mmdf_phys_write (f,f->buf,k);
2482 /* slide buffer */
2483 if (i -= k) memmove (f->buf,f->buf + k,i);
2484 f->bufpos = f->buf + i; /* new end of buffer */
2488 /* Have flushed the buffer as best as possible. All done if no more
2489 * data to write. Otherwise, if the buffer is empty AND if the unwritten
2490 * data is larger than a chunk AND the unprotected space is also larger
2491 * than a chunk, then write as many chunks as we can directly from the
2492 * data. Buffer the rest, expanding the buffer as needed.
2493 */
2494 if (size) { /* have more data that we need to buffer? */
2495 /* can write any of it to disk instead? */
2496 if ((f->bufpos == f->buf) &&
2497 ((j = min (f->protect - f->filepos,size)) > OVERFLOWBUFLEN)) {
2498 /* write as much as we can right now */
2499 mmdf_phys_write (f,buf,j -= (j % OVERFLOWBUFLEN));
2500 buf += j; /* new data pointer */
2501 size -= j; /* new data size */
2502 f->curpos += j; /* advance current pointer */
2504 if (size) { /* still have data that we need to buffer? */
2505 /* yes, need to expand the buffer? */
2506 if ((i = ((f->bufpos + size) - f->buf)) > f->buflen) {
2507 /* note current position in buffer */
2508 j = f->bufpos - f->buf;
2509 i += OVERFLOWBUFLEN; /* yes, grow another chunk */
2510 fs_resize ((void **) &f->buf,f->buflen = i - (i % OVERFLOWBUFLEN));
2511 /* in case buffer relocated */
2512 f->bufpos = f->buf + j;
2514 /* buffer remaining data */
2515 memcpy (f->bufpos,buf,size);
2516 f->bufpos += size; /* new end of buffer */
2517 f->curpos += size; /* advance current pointer */
2521 else { /* flush buffer to disk */
2522 mmdf_phys_write (f,f->buf,i = f->bufpos - f->buf);
2523 f->bufpos = f->buf; /* reset buffer */
2524 /* update positions */
2525 f->curpos = f->protect = f->filepos;
2529 /* Physical disk write
2530 * Accepts: buffered file pointer
2531 * buffer address
2532 * buffer size
2533 * Does not return until success
2534 */
2536 void mmdf_phys_write (MMDFFILE *f,char *buf,size_t size)
2538 MAILSTREAM *stream = f->stream;
2539 /* write data at desired position */
2540 while (size && ((lseek (LOCAL->fd,f->filepos,L_SET) < 0) ||
2541 (write (LOCAL->fd,buf,size) < 0))) {
2542 int e;
2543 char tmp[MAILTMPLEN];
2544 sprintf (tmp,"Unable to write to mailbox: %s",strerror (e = errno));
2545 MM_LOG (tmp,ERROR);
2546 MM_DISKERROR (NIL,e,T); /* serious problem, must retry */
2548 f->filepos += size; /* update file position */

UW-IMAP'd extensions by yuuji