* Clean up some function definitions to comply with strict
[alpine.git] / imap / src / osdep / nt / unixnt.c
blob1b9ee3a2af20a3fb36852cbf259c3a208f36e78f
1 /* ========================================================================
2 * Copyright 1988-2008 University of Washington
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
11 * ========================================================================
15 * Program: UNIX mail routines
17 * Author: Mark Crispin
18 * UW Technology
19 * University of Washington
20 * Seattle, WA 98195
21 * Internet: MRC@CAC.Washington.EDU
23 * Date: 20 December 1989
24 * Last Edited: 27 March 2008
28 /* DEDICATION
30 * This file is dedicated to my dog, Unix, also known as Yun-chan and
31 * Unix J. Terwilliker Jehosophat Aloysius Monstrosity Animal Beast. Unix
32 * passed away at the age of 11 1/2 on September 14, 1996, 12:18 PM PDT, after
33 * a two-month bout with cirrhosis of the liver.
35 * He was a dear friend, and I miss him terribly.
37 * Lift a leg, Yunie. Luv ya forever!!!!
40 #include <stdio.h>
41 #include <ctype.h>
42 #include <errno.h>
43 #ifndef errno
44 extern int errno; /* just in case */
45 #endif
46 #include "mail.h"
47 #include "osdep.h"
48 #include <time.h>
49 #include <fcntl.h>
50 #include <sys/stat.h>
51 #include <sys/utime.h>
52 #include "unixnt.h"
53 #include "pseudo.h"
54 #include "fdstring.h"
55 #include "misc.h"
56 #include "dummy.h"
58 /* UNIX I/O stream local data */
60 typedef struct unix_local {
61 unsigned int dirty : 1; /* disk copy needs updating */
62 unsigned int ddirty : 1; /* double-dirty, ping becomes checkpoint */
63 unsigned int pseudo : 1; /* uses a pseudo message */
64 unsigned int appending : 1; /* don't mark new messages as old */
65 int fd; /* mailbox file descriptor */
66 int ld; /* lock file descriptor */
67 char *lname; /* lock file name */
68 off_t filesize; /* file size parsed */
69 time_t filetime; /* last file time */
70 unsigned char *buf; /* temporary buffer */
71 unsigned long buflen; /* current size of temporary buffer */
72 unsigned long uid; /* current text uid */
73 SIZEDTEXT text; /* current text */
74 unsigned long textlen; /* current text length */
75 char *line; /* returned line */
76 char *linebuf; /* line readin buffer */
77 unsigned long linebuflen; /* current line readin buffer length */
78 } UNIXLOCAL;
81 /* Convenient access to local data */
83 #define LOCAL ((UNIXLOCAL *) stream->local)
86 /* UNIX protected file structure */
88 typedef struct unix_file {
89 MAILSTREAM *stream; /* current stream */
90 off_t curpos; /* current file position */
91 off_t protect; /* protected position */
92 off_t filepos; /* current last written file position */
93 char *buf; /* overflow buffer */
94 size_t buflen; /* current overflow buffer length */
95 char *bufpos; /* current buffer position */
96 } UNIXFILE;
98 /* Function prototypes */
100 DRIVER *unix_valid (char *name);
101 void *unix_parameters (long function,void *value);
102 void unix_scan (MAILSTREAM *stream,char *ref,char *pat,char *contents);
103 void unix_list (MAILSTREAM *stream,char *ref,char *pat);
104 void unix_lsub (MAILSTREAM *stream,char *ref,char *pat);
105 long unix_create (MAILSTREAM *stream,char *mailbox);
106 long unix_delete (MAILSTREAM *stream,char *mailbox);
107 long unix_rename (MAILSTREAM *stream,char *old,char *newname);
108 MAILSTREAM *unix_open (MAILSTREAM *stream);
109 void unix_close (MAILSTREAM *stream,long options);
110 char *unix_header (MAILSTREAM *stream,unsigned long msgno,
111 unsigned long *length,long flags);
112 long unix_text (MAILSTREAM *stream,unsigned long msgno,STRING *bs,long flags);
113 char *unix_text_work (MAILSTREAM *stream,MESSAGECACHE *elt,
114 unsigned long *length,long flags);
115 void unix_flagmsg (MAILSTREAM *stream,MESSAGECACHE *elt);
116 long unix_ping (MAILSTREAM *stream);
117 void unix_check (MAILSTREAM *stream);
118 long unix_expunge (MAILSTREAM *stream,char *sequence,long options);
119 long unix_copy (MAILSTREAM *stream,char *sequence,char *mailbox,long options);
120 long unix_append (MAILSTREAM *stream,char *mailbox,append_t af,void *data);
121 int unix_collect_msg (MAILSTREAM *stream,FILE *sf,char *flags,char *date,
122 STRING *msg);
123 int unix_append_msgs (MAILSTREAM *stream,FILE *sf,FILE *df,SEARCHSET *set);
125 void unix_abort (MAILSTREAM *stream);
126 char *unix_file (char *dst,char *name);
127 int unix_lock (char *file,int flags,int mode,char *lock,int op);
128 void unix_unlock (int fd,MAILSTREAM *stream,char *lock);
129 int unix_parse (MAILSTREAM *stream,char *lock,int op);
130 char *unix_mbxline (MAILSTREAM *stream,STRING *bs,unsigned long *size);
131 unsigned long unix_pseudo (MAILSTREAM *stream,char *hdr);
132 unsigned long unix_xstatus (MAILSTREAM *stream,char *status,MESSAGECACHE *elt,
133 unsigned long uid,long flag);
134 long unix_rewrite (MAILSTREAM *stream,unsigned long *nexp,char *lock,
135 long flags);
136 long unix_extend (MAILSTREAM *stream,unsigned long size);
137 void unix_write (UNIXFILE *f,char *s,unsigned long i);
138 void unix_phys_write (UNIXFILE *f,char *buf,size_t size);
140 /* UNIX mail routines */
143 /* Driver dispatch used by MAIL */
145 DRIVER unixdriver = {
146 "unix", /* driver name */
147 /* driver flags */
148 DR_LOCAL|DR_MAIL|DR_NONEWMAILRONLY|DR_XPOINT,
149 (DRIVER *) NIL, /* next driver */
150 unix_valid, /* mailbox is valid for us */
151 unix_parameters, /* manipulate parameters */
152 unix_scan, /* scan mailboxes */
153 unix_list, /* list mailboxes */
154 unix_lsub, /* list subscribed mailboxes */
155 NIL, /* subscribe to mailbox */
156 NIL, /* unsubscribe from mailbox */
157 unix_create, /* create mailbox */
158 unix_delete, /* delete mailbox */
159 unix_rename, /* rename mailbox */
160 mail_status_default, /* status of mailbox */
161 unix_open, /* open mailbox */
162 unix_close, /* close mailbox */
163 NIL, /* fetch message "fast" attributes */
164 NIL, /* fetch message flags */
165 NIL, /* fetch overview */
166 NIL, /* fetch message envelopes */
167 unix_header, /* fetch message header */
168 unix_text, /* fetch message text */
169 NIL, /* fetch partial message text */
170 NIL, /* unique identifier */
171 NIL, /* message number */
172 NIL, /* modify flags */
173 unix_flagmsg, /* per-message modify flags */
174 NIL, /* search for message based on criteria */
175 NIL, /* sort messages */
176 NIL, /* thread messages */
177 unix_ping, /* ping mailbox to see if still alive */
178 unix_check, /* check for new messages */
179 unix_expunge, /* expunge deleted messages */
180 unix_copy, /* copy messages to another mailbox */
181 unix_append, /* append string message to mailbox */
182 NIL, /* garbage collect stream */
183 NIL /* renew stream */
186 /* prototype stream */
187 MAILSTREAM unixproto = {&unixdriver};
189 /* driver parameters */
190 static long unix_fromwidget = T;
192 /* UNIX mail validate mailbox
193 * Accepts: mailbox name
194 * Returns: our driver if name is valid, NIL otherwise
197 DRIVER *unix_valid (char *name)
199 int fd;
200 DRIVER *ret = NIL;
201 int c,r;
202 char tmp[MAILTMPLEN],file[MAILTMPLEN],*s,*t;
203 struct stat sbuf;
204 struct utimbuf times;
205 errno = EINVAL; /* assume invalid argument */
206 /* must be non-empty file */
207 if ((t = dummy_file (file,name)) && !stat (t,&sbuf) &&
208 ((sbuf.st_mode & S_IFMT) == S_IFREG)) {
209 if (!sbuf.st_size)errno = 0;/* empty file */
210 else if ((fd = open (file,O_BINARY|O_RDONLY,NIL)) >= 0) {
211 memset (tmp,'\0',MAILTMPLEN);
212 if (read (fd,tmp,MAILTMPLEN-1) <= 0) errno = -1;
213 else { /* ignore leading whitespace */
214 for (s = tmp,c = '\n';
215 (*s == '\r') || (*s == '\n') || (*s == ' ') || (*s == '\t');
216 c = *s++);
217 if (c == '\n') { /* at start of a line? */
218 VALID (s,t,r,c); /* yes, validate format */
219 if (r) ret = &unixdriver;
220 else errno = -1; /* invalid format */
223 close (fd); /* close the file */
224 /* \Marked status? */
225 if ((sbuf.st_ctime > sbuf.st_atime) || (sbuf.st_mtime > sbuf.st_atime)) {
226 /* yes, preserve atime and mtime */
227 times.actime = sbuf.st_atime;
228 times.modtime = sbuf.st_mtime;
229 utime (file,&times); /* set the times */
233 return ret; /* return what we should */
235 /* UNIX manipulate driver parameters
236 * Accepts: function code
237 * function-dependent value
238 * Returns: function-dependent return value
241 void *unix_parameters (long function,void *value)
243 void *ret = NIL;
244 switch ((int) function) {
245 case SET_FROMWIDGET:
246 unix_fromwidget = (long) value;
247 case GET_FROMWIDGET:
248 ret = (void *) unix_fromwidget;
249 break;
251 return ret;
254 /* UNIX mail scan mailboxes
255 * Accepts: mail stream
256 * reference
257 * pattern to search
258 * string to scan
261 void unix_scan (MAILSTREAM *stream,char *ref,char *pat,char *contents)
263 if (stream) dummy_scan (NIL,ref,pat,contents);
267 /* UNIX mail list mailboxes
268 * Accepts: mail stream
269 * reference
270 * pattern to search
273 void unix_list (MAILSTREAM *stream,char *ref,char *pat)
275 if (stream) dummy_list (NIL,ref,pat);
279 /* UNIX mail list subscribed mailboxes
280 * Accepts: mail stream
281 * reference
282 * pattern to search
285 void unix_lsub (MAILSTREAM *stream,char *ref,char *pat)
287 if (stream) dummy_lsub (NIL,ref,pat);
290 /* UNIX mail create mailbox
291 * Accepts: MAIL stream
292 * mailbox name to create
293 * Returns: T on success, NIL on failure
296 long unix_create (MAILSTREAM *stream,char *mailbox)
298 char *s,mbx[MAILTMPLEN],tmp[MAILTMPLEN];
299 long ret = NIL;
300 int fd;
301 time_t ti = time (0);
302 if (!(s = dummy_file (mbx,mailbox))) {
303 sprintf (tmp,"Can't create %.80s: invalid name",mailbox);
304 mm_log (tmp,ERROR);
306 /* create underlying file */
307 else if (dummy_create_path (stream,s,NIL)) {
308 if ((s = strrchr (s,'\\')) && !s[1]) ret = T;
309 if ((fd = open (mbx,O_WRONLY|O_BINARY,NIL)) < 0) {
310 sprintf (tmp,"Can't reopen mailbox node %.80s: %s",mbx,strerror (errno));
311 mm_log (tmp,ERROR);
312 unlink (mbx); /* delete the file */
314 else { /* initialize header */
315 memset (tmp,'\0',MAILTMPLEN);
316 sprintf (tmp,"From %s %s",pseudo_from,ctime (&ti));
317 if (s = strpbrk (tmp,"\r\n")) *s = '\0';
318 strcat (tmp,"\r\nDate: ");
319 rfc822_fixed_date (s = tmp + strlen (tmp));
320 sprintf (s += strlen (s), /* write the pseudo-header */
321 "\r\nFrom: %s <%s@%s>\r\nSubject: %s\r\nX-IMAP: %010lu 0000000000\r\nStatus: RO\r\n\r\n%s\r\n\r\n",
322 pseudo_name,pseudo_from,mylocalhost (),pseudo_subject,
323 (unsigned long) ti,pseudo_msg);
324 if (write (fd,tmp,strlen (tmp)) > 0) {
325 close (fd); /* close file */
326 ret = T;
328 else {
329 sprintf (tmp,"Can't initialize mailbox node %.80s: %s",mbx,
330 strerror (errno));
331 mm_log (tmp,ERROR);
332 close (fd); /* close file before unlinking */
333 unlink (mbx); /* delete the file */
337 return ret;
340 /* UNIX mail delete mailbox
341 * Accepts: MAIL stream
342 * mailbox name to delete
343 * Returns: T on success, NIL on failure
346 long unix_delete (MAILSTREAM *stream,char *mailbox)
348 return unix_rename (stream,mailbox,NIL);
352 /* UNIX mail rename mailbox
353 * Accepts: MAIL stream
354 * old mailbox name
355 * new mailbox name (or NIL for delete)
356 * Returns: T on success, NIL on failure
359 long unix_rename (MAILSTREAM *stream,char *old,char *newname)
361 long ret = NIL;
362 char c,*s = NIL;
363 char tmp[MAILTMPLEN],file[MAILTMPLEN],lock[MAILTMPLEN],lockx[MAILTMPLEN];
364 int fd,ld;
365 struct stat sbuf;
366 mm_critical (stream); /* get the c-client lock */
367 if (!dummy_file (file,old) ||
368 (newname && (!(s = dummy_file (tmp,newname)) ||
369 ((s = strrchr (s,'\\')) && !s[1]))))
370 sprintf (tmp,newname ?
371 "Can't rename mailbox %.80s to %.80s: invalid name" :
372 "Can't delete mailbox %.80s: invalid name",
373 old,newname);
374 else if ((ld = lockname (lock,file,NIL)) < 0)
375 sprintf (tmp,"Can't get lock for mailbox %.80s",old);
377 else { /* lock out other c-clients */
378 if (flock (ld,LOCK_EX|LOCK_NB)) {
379 close (ld); /* couldn't lock, give up on it then */
380 sprintf (tmp,"Mailbox %.80s is in use by another process",old);
382 /* lock out non c-client applications */
383 else if ((fd = unix_lock (file,O_BINARY|O_RDWR,S_IREAD|S_IWRITE,lockx,
384 LOCK_EX)) < 0)
385 sprintf (tmp,"Can't lock mailbox %.80s: %s",old,strerror (errno));
386 else {
387 unix_unlock(fd,NIL,lockx);/* pacify evil NTFS */
388 if (newname) { /* want rename? */
389 /* found superior to destination name? */
390 if ((s = strrchr (tmp,'\\')) && (s != tmp) &&
391 ((tmp[1] != ':') || (s != tmp + 2))) {
392 c = s[1]; /* remember character after delimiter */
393 *s = s[1] = '\0'; /* tie off name at delimiter */
394 /* name doesn't exist, create it */
395 if (stat (tmp,&sbuf) || ((sbuf.st_mode & S_IFMT) != S_IFDIR)) {
396 *s = '\\'; /* restore delimiter */
397 if (!dummy_create (stream,newname)) {
398 flock (ld,LOCK_UN);
399 close (ld); /* close c-client lock */
400 unlink (lock); /* and delete it */
401 mm_nocritical (stream);
402 return NIL; /* couldn't create superior */
405 else *s = '\\'; /* restore delimiter */
406 s[1] = c; /* restore character after delimiter */
408 if (rename (file,tmp))
409 sprintf (tmp,"Can't rename mailbox %.80s to %.80s: %s",old,newname,
410 strerror (errno));
411 else ret = T; /* set success */
413 else if (unlink (file)) /* want delete */
414 sprintf (tmp,"Can't delete mailbox %.80s: %s",old,strerror (errno));
415 else ret = T; /* set success */
416 flock (ld,LOCK_UN); /* release c-client lock */
417 close (ld); /* close c-client lock */
418 unlink (lock); /* and delete it */
421 mm_nocritical (stream); /* no longer critical */
422 if (!ret) mm_log (tmp,ERROR); /* log error */
423 return ret; /* return success or failure */
426 /* UNIX mail open
427 * Accepts: Stream to open
428 * Returns: Stream on success, NIL on failure
431 MAILSTREAM *unix_open (MAILSTREAM *stream)
433 int fd;
434 char tmp[MAILTMPLEN];
435 /* return prototype for OP_PROTOTYPE call */
436 if (!stream) return &unixproto;
437 if (stream->local) fatal ("unix recycle stream");
438 stream->local = memset (fs_get (sizeof (UNIXLOCAL)),0,sizeof (UNIXLOCAL));
439 /* note if an INBOX or not */
440 stream->inbox = !compare_cstring (stream->mailbox,"INBOX");
441 /* canonicalize the stream mailbox name */
442 if (!dummy_file (tmp,stream->mailbox)) {
443 sprintf (tmp,"Can't open - invalid name: %.80s",stream->mailbox);
444 mm_log (tmp,ERROR);
445 return NIL;
447 /* flush old name */
448 fs_give ((void **) &stream->mailbox);
449 /* save canonical name */
450 stream->mailbox = cpystr (tmp);
451 LOCAL->fd = LOCAL->ld = -1; /* no file or state locking yet */
452 LOCAL->buf = (char *) fs_get ((LOCAL->buflen = CHUNKSIZE) + 1);
453 LOCAL->text.data = (unsigned char *) fs_get (CHUNKSIZE);
454 LOCAL->text.size = CHUNKSIZE - 1;
455 LOCAL->linebuf = (char *) fs_get (CHUNKSIZE);
456 LOCAL->linebuflen = CHUNKSIZE - 1;
457 stream->sequence++; /* bump sequence number */
458 if (!stream->rdonly) { /* make lock for read/write access */
459 if ((fd = lockname (tmp,stream->mailbox,NIL)) < 0)
460 mm_log ("Can't open mailbox lock, access is readonly",WARN);
461 /* can get the lock? */
462 else if (flock (fd,LOCK_EX|LOCK_NB)) {
463 if (!stream->silent)
464 mm_log ("Mailbox is open by another process, access is readonly",WARN);
465 close (fd);
467 else { /* got the lock, nobody else can alter state */
468 LOCAL->ld = fd; /* note lock's fd and name */
469 LOCAL->lname = cpystr (tmp);
473 /* parse mailbox */
474 stream->nmsgs = stream->recent = 0;
475 /* will we be able to get write access? */
476 if ((LOCAL->ld >= 0) && access (stream->mailbox,02) && (errno == EACCES)) {
477 mm_log ("Can't get write access to mailbox, access is readonly",WARN);
478 flock (LOCAL->ld,LOCK_UN); /* release the lock */
479 close (LOCAL->ld); /* close the lock file */
480 LOCAL->ld = -1; /* no more lock fd */
481 unlink (LOCAL->lname); /* delete it */
483 /* reset UID validity */
484 stream->uid_validity = stream->uid_last = 0;
485 if (stream->silent && !stream->rdonly && (LOCAL->ld < 0))
486 unix_abort (stream); /* abort if can't get RW silent stream */
487 /* parse mailbox */
488 else if (unix_parse (stream,tmp,LOCK_SH)) {
489 unix_unlock (LOCAL->fd,stream,tmp);
490 mail_unlock (stream);
491 mm_nocritical (stream); /* done with critical */
493 if (!LOCAL) return NIL; /* failure if stream died */
494 /* make sure upper level knows readonly */
495 stream->rdonly = (LOCAL->ld < 0);
496 /* notify about empty mailbox */
497 if (!(stream->nmsgs || stream->silent)) mm_log ("Mailbox is empty",NIL);
498 if (!stream->rdonly) { /* flags stick if readwrite */
499 stream->perm_seen = stream->perm_deleted =
500 stream->perm_flagged = stream->perm_answered = stream->perm_draft = T;
501 /* have permanent keywords */
502 stream->perm_user_flags = 0xffffffff;
503 /* and maybe can create them too */
504 stream->kwd_create = stream->user_flags[NUSERFLAGS-1] ? NIL : T;
506 return stream; /* return stream alive to caller */
510 /* UNIX mail close
511 * Accepts: MAIL stream
512 * close options
515 void unix_close (MAILSTREAM *stream,long options)
517 int silent = stream->silent;
518 stream->silent = T; /* go silent */
519 /* expunge if requested */
520 if (options & CL_EXPUNGE) unix_expunge (stream,NIL,NIL);
521 /* else dump final checkpoint */
522 else if (LOCAL->dirty) unix_check (stream);
523 stream->silent = silent; /* restore old silence state */
524 unix_abort (stream); /* now punt the file and local data */
527 /* UNIX mail fetch message header
528 * Accepts: MAIL stream
529 * message # to fetch
530 * pointer to returned header text length
531 * option flags
532 * Returns: message header in RFC822 format
535 /* lines to filter from header */
536 static STRINGLIST *unix_hlines = NIL;
538 char *unix_header (MAILSTREAM *stream,unsigned long msgno,
539 unsigned long *length,long flags)
541 MESSAGECACHE *elt;
542 unsigned char *s;
543 *length = 0; /* default to empty */
544 if (flags & FT_UID) return "";/* UID call "impossible" */
545 elt = mail_elt (stream,msgno);/* get cache */
546 if (!unix_hlines) { /* once only code */
547 STRINGLIST *lines = unix_hlines = mail_newstringlist ();
548 lines->text.size = strlen ((char *) (lines->text.data =
549 (unsigned char *) "Status"));
550 lines = lines->next = mail_newstringlist ();
551 lines->text.size = strlen ((char *) (lines->text.data =
552 (unsigned char *) "X-Status"));
553 lines = lines->next = mail_newstringlist ();
554 lines->text.size = strlen ((char *) (lines->text.data =
555 (unsigned char *) "X-Keywords"));
556 lines = lines->next = mail_newstringlist ();
557 lines->text.size = strlen ((char *) (lines->text.data =
558 (unsigned char *) "X-UID"));
559 lines = lines->next = mail_newstringlist ();
560 lines->text.size = strlen ((char *) (lines->text.data =
561 (unsigned char *) "X-IMAP"));
562 lines = lines->next = mail_newstringlist ();
563 lines->text.size = strlen ((char *) (lines->text.data =
564 (unsigned char *) "X-IMAPbase"));
566 /* go to header position */
567 lseek (LOCAL->fd,elt->private.special.offset +
568 elt->private.msg.header.offset,L_SET);
570 if (flags & FT_INTERNAL) { /* initial data OK? */
571 if (elt->private.msg.header.text.size > LOCAL->buflen) {
572 fs_give ((void **) &LOCAL->buf);
573 LOCAL->buf = (char *) fs_get ((LOCAL->buflen =
574 elt->private.msg.header.text.size) + 1);
576 /* read message */
577 read (LOCAL->fd,LOCAL->buf,elt->private.msg.header.text.size);
578 /* got text, tie off string */
579 LOCAL->buf[*length = elt->private.msg.header.text.size] = '\0';
581 else { /* need to make a CRLF version */
582 read (LOCAL->fd,s = (char *) fs_get (elt->private.msg.header.text.size+1),
583 elt->private.msg.header.text.size);
584 /* tie off string, and convert to CRLF */
585 s[elt->private.msg.header.text.size] = '\0';
586 *length = unix_crlfcpy (&LOCAL->buf,&LOCAL->buflen,s,
587 elt->private.msg.header.text.size);
588 fs_give ((void **) &s); /* free readin buffer */
590 *length = mail_filter (LOCAL->buf,*length,unix_hlines,FT_NOT);
591 return LOCAL->buf; /* return processed copy */
594 /* UNIX mail fetch message text
595 * Accepts: MAIL stream
596 * message # to fetch
597 * pointer to returned stringstruct
598 * option flags
599 * Returns: T on success, NIL if failure
602 long unix_text (MAILSTREAM *stream,unsigned long msgno,STRING *bs,long flags)
604 char *s;
605 unsigned long i;
606 MESSAGECACHE *elt;
607 /* UID call "impossible" */
608 if (flags & FT_UID) return NIL;
609 elt = mail_elt (stream,msgno);/* get cache element */
610 /* if message not seen */
611 if (!(flags & FT_PEEK) && !elt->seen) {
612 /* mark message seen and dirty */
613 elt->seen = elt->private.dirty = LOCAL->dirty = T;
614 mm_flags (stream,msgno);
616 s = unix_text_work (stream,elt,&i,flags);
617 INIT (bs,mail_string,s,i); /* set up stringstruct */
618 return T; /* success */
621 /* UNIX mail fetch message text worker routine
622 * Accepts: MAIL stream
623 * message cache element
624 * pointer to returned header text length
625 * option flags
628 char *unix_text_work (MAILSTREAM *stream,MESSAGECACHE *elt,
629 unsigned long *length,long flags)
631 FDDATA d;
632 STRING bs;
633 unsigned char c,*s,tmp[CHUNKSIZE];
634 /* go to text position */
635 lseek (LOCAL->fd,elt->private.special.offset +
636 elt->private.msg.text.offset,L_SET);
637 if (flags & FT_INTERNAL) { /* initial data OK? */
638 if (elt->private.msg.text.text.size > LOCAL->buflen) {
639 fs_give ((void **) &LOCAL->buf);
640 LOCAL->buf = (char *) fs_get ((LOCAL->buflen =
641 elt->private.msg.text.text.size) + 1);
643 /* read message */
644 read (LOCAL->fd,LOCAL->buf,elt->private.msg.text.text.size);
645 /* got text, tie off string */
646 LOCAL->buf[*length = elt->private.msg.text.text.size] = '\0';
647 return LOCAL->buf;
649 /* have it cached already? */
650 if (elt->private.uid != LOCAL->uid) {
651 /* not cached, cache it now */
652 LOCAL->uid = elt->private.uid;
653 /* is buffer big enough? */
654 if (elt->rfc822_size > LOCAL->text.size) {
655 /* excessively conservative, but the right thing is too hard to do */
656 fs_give ((void **) &LOCAL->text.data);
657 LOCAL->text.data = (unsigned char *)
658 fs_get ((LOCAL->text.size = elt->rfc822_size) + 1);
660 d.fd = LOCAL->fd; /* yes, set up file descriptor */
661 d.pos = elt->private.special.offset + elt->private.msg.text.offset;
662 d.chunk = tmp; /* initial buffer chunk */
663 d.chunksize = CHUNKSIZE; /* file chunk size */
664 INIT (&bs,fd_string,&d,elt->private.msg.text.text.size);
665 for (s = (char *) LOCAL->text.data; SIZE (&bs);) switch (c = SNX (&bs)) {
666 case '\r': /* carriage return seen */
667 *s++ = c; /* copy it and any succeeding LF */
668 if (SIZE (&bs) && (CHR (&bs) == '\n')) *s++ = SNX (&bs);
669 break;
670 case '\n':
671 *s++ = '\r'; /* insert a CR */
672 default:
673 *s++ = c; /* copy characters */
675 *s = '\0'; /* tie off buffer */
676 /* calculate length of cached data */
677 LOCAL->textlen = s - LOCAL->text.data;
679 *length = LOCAL->textlen; /* return from cache */
680 return (char *) LOCAL->text.data;
683 /* UNIX per-message modify flag
684 * Accepts: MAIL stream
685 * message cache element
688 void unix_flagmsg (MAILSTREAM *stream,MESSAGECACHE *elt)
690 /* only after finishing */
691 if (elt->valid) elt->private.dirty = LOCAL->dirty = T;
695 /* UNIX mail ping mailbox
696 * Accepts: MAIL stream
697 * Returns: T if stream alive, else NIL
700 long unix_ping (MAILSTREAM *stream)
702 char lock[MAILTMPLEN];
703 struct stat sbuf;
704 /* big no-op if not readwrite */
705 if (LOCAL && (LOCAL->ld >= 0) && !stream->lock) {
706 if (stream->rdonly) { /* does he want to give up readwrite? */
707 /* checkpoint if we changed something */
708 if (LOCAL->dirty) unix_check (stream);
709 flock (LOCAL->ld,LOCK_UN);/* release readwrite lock */
710 close (LOCAL->ld); /* close the readwrite lock file */
711 LOCAL->ld = -1; /* no more readwrite lock fd */
712 unlink (LOCAL->lname); /* delete the readwrite lock file */
714 else { /* get current mailbox size */
715 if (LOCAL->fd >= 0) fstat (LOCAL->fd,&sbuf);
716 else if (stat (stream->mailbox,&sbuf)) {
717 sprintf (LOCAL->buf,"Mailbox stat failed, aborted: %s",
718 strerror (errno));
719 MM_LOG (LOCAL->buf,ERROR);
720 unix_abort (stream);
721 return NIL;
723 /* parse if mailbox changed */
724 if ((LOCAL->ddirty || (sbuf.st_size != LOCAL->filesize)) &&
725 unix_parse (stream,lock,LOCK_EX)) {
726 /* force checkpoint if double-dirty */
727 if (LOCAL->ddirty) unix_rewrite (stream,NIL,lock,NIL);
728 /* unlock mailbox */
729 else unix_unlock (LOCAL->fd,stream,lock);
730 mail_unlock (stream); /* and stream */
731 mm_nocritical (stream); /* done with critical */
735 return LOCAL ? LONGT : NIL; /* return if still alive */
738 /* UNIX mail check mailbox
739 * Accepts: MAIL stream
742 void unix_check (MAILSTREAM *stream)
744 char lock[MAILTMPLEN];
745 /* parse and lock mailbox */
746 if (LOCAL && (LOCAL->ld >= 0) && !stream->lock &&
747 unix_parse (stream,lock,LOCK_EX)) {
748 /* any unsaved changes? */
749 if (LOCAL->dirty && unix_rewrite (stream,NIL,lock,NIL)) {
750 if (!stream->silent) mm_log ("Checkpoint completed",NIL);
752 /* no checkpoint needed, just unlock */
753 else unix_unlock (LOCAL->fd,stream,lock);
754 mail_unlock (stream); /* unlock the stream */
755 mm_nocritical (stream); /* done with critical */
760 /* UNIX mail expunge mailbox
761 * Accepts: MAIL stream
762 * sequence to expunge if non-NIL
763 * expunge options
764 * Returns: T, always
767 long unix_expunge (MAILSTREAM *stream,char *sequence,long options)
769 long ret;
770 unsigned long i;
771 char lock[MAILTMPLEN];
772 char *msg = NIL;
773 /* parse and lock mailbox */
774 if (ret = (sequence ? ((options & EX_UID) ?
775 mail_uid_sequence (stream,sequence) :
776 mail_sequence (stream,sequence)) : LONGT) &&
777 LOCAL && (LOCAL->ld >= 0) && !stream->lock &&
778 unix_parse (stream,lock,LOCK_EX)) {
779 /* check expunged messages if not dirty */
780 for (i = 1; !LOCAL->dirty && (i <= stream->nmsgs); i++) {
781 MESSAGECACHE *elt = mail_elt (stream,i);
782 if (mail_elt (stream,i)->deleted) LOCAL->dirty = T;
784 if (!LOCAL->dirty) { /* not dirty and no expunged messages */
785 unix_unlock (LOCAL->fd,stream,lock);
786 msg = "No messages deleted, so no update needed";
788 else if (unix_rewrite (stream,&i,lock,sequence ? LONGT : NIL)) {
789 if (i) sprintf (msg = LOCAL->buf,"Expunged %lu messages",i);
790 else msg = "Mailbox checkpointed, but no messages expunged";
792 /* rewrite failed */
793 else unix_unlock (LOCAL->fd,stream,lock);
794 mail_unlock (stream); /* unlock the stream */
795 mm_nocritical (stream); /* done with critical */
796 if (msg && !stream->silent) mm_log (msg,NIL);
798 else if (!stream->silent) mm_log("Expunge ignored on readonly mailbox",WARN);
799 return ret;
802 /* UNIX mail copy message(s)
803 * Accepts: MAIL stream
804 * sequence
805 * destination mailbox
806 * copy options
807 * Returns: T if copy successful, else NIL
810 long unix_copy (MAILSTREAM *stream,char *sequence,char *mailbox,long options)
812 struct stat sbuf;
813 int fd;
814 char *s,file[MAILTMPLEN],lock[MAILTMPLEN];
815 struct utimbuf times;
816 unsigned long i,j;
817 MESSAGECACHE *elt;
818 long ret = T;
819 mailproxycopy_t pc =
820 (mailproxycopy_t) mail_parameters (stream,GET_MAILPROXYCOPY,NIL);
821 copyuid_t cu = (copyuid_t) (mail_parameters (NIL,GET_USERHASNOLIFE,NIL) ?
822 NIL : mail_parameters (NIL,GET_COPYUID,NIL));
823 SEARCHSET *source = cu ? mail_newsearchset () : NIL;
824 SEARCHSET *dest = cu ? mail_newsearchset () : NIL;
825 MAILSTREAM *tstream = NIL;
826 if (!((options & CP_UID) ? mail_uid_sequence (stream,sequence) :
827 mail_sequence (stream,sequence))) return NIL;
828 /* make sure destination is valid */
829 if (!(unix_valid (mailbox) || !errno))
830 switch (errno) {
831 case ENOENT: /* no such file? */
832 if (compare_cstring (mailbox,"INBOX")) {
833 mm_notify (stream,"[TRYCREATE] Must create mailbox before copy",NIL);
834 return NIL;
836 if (pc) return (*pc) (stream,sequence,mailbox,options);
837 unix_create (NIL,"INBOX");/* create empty INBOX */
838 case EACCES: /* file protected */
839 sprintf (LOCAL->buf,"Can't access destination: %.80s",mailbox);
840 MM_LOG (LOCAL->buf,ERROR);
841 return NIL;
842 case EINVAL:
843 if (pc) return (*pc) (stream,sequence,mailbox,options);
844 sprintf (LOCAL->buf,"Invalid UNIX-format mailbox name: %.80s",mailbox);
845 mm_log (LOCAL->buf,ERROR);
846 return NIL;
847 default:
848 if (pc) return (*pc) (stream,sequence,mailbox,options);
849 sprintf (LOCAL->buf,"Not a UNIX-format mailbox: %.80s",mailbox);
850 mm_log (LOCAL->buf,ERROR);
851 return NIL;
854 /* try to open rewrite for UIDPLUS */
855 if ((tstream = mail_open_work (&unixdriver,NIL,mailbox,
856 OP_SILENT|OP_NOKOD)) && tstream->rdonly)
857 tstream = mail_close (tstream);
858 if (cu && !tstream) { /* wanted a COPYUID? */
859 sprintf (LOCAL->buf,"Unable to write-open mailbox for COPYUID: %.80s",
860 mailbox);
861 MM_LOG (LOCAL->buf,WARN);
862 cu = NIL; /* don't try to do COPYUID */
864 LOCAL->buf[0] = '\0';
865 mm_critical (stream); /* go critical */
866 if ((fd = unix_lock (dummy_file (file,mailbox),
867 O_BINARY|O_WRONLY|O_APPEND|O_CREAT,S_IREAD|S_IWRITE,
868 lock,LOCK_EX)) < 0) {
869 mm_nocritical (stream); /* done with critical */
870 sprintf (LOCAL->buf,"Can't open destination mailbox: %s",strerror (errno));
871 mm_log (LOCAL->buf,ERROR); /* log the error */
872 return NIL; /* failed */
874 fstat (fd,&sbuf); /* get current file size */
875 /* write all requested messages to mailbox */
876 for (i = 1; ret && (i <= stream->nmsgs); i++)
877 if ((elt = mail_elt (stream,i))->sequence) {
878 lseek (LOCAL->fd,elt->private.special.offset,L_SET);
879 read (LOCAL->fd,LOCAL->buf,elt->private.special.text.size);
880 if (LOCAL->buf[(j = elt->private.special.text.size) - 2] != '\r') {
881 LOCAL->buf[j - 1] = '\r';
882 LOCAL->buf[j++] = '\n';
884 if (write (fd,LOCAL->buf,j) < 0) ret = NIL;
885 else { /* internal header succeeded */
886 s = unix_header (stream,i,&j,NIL);
887 /* header size, sans trailing newline */
888 if (j && (s[j - 4] == '\r')) j -= 2;
889 if (write (fd,s,j) < 0) ret = NIL;
890 else { /* message header succeeded */
891 j = tstream ? /* write UIDPLUS data if have readwrite */
892 unix_xstatus (stream,LOCAL->buf,elt,++(tstream->uid_last),LONGT) :
893 unix_xstatus (stream,LOCAL->buf,elt,NIL,NIL);
894 if (write (fd,LOCAL->buf,j) < 0) ret = NIL;
895 else { /* message status succeeded */
896 s = unix_text_work (stream,elt,&j,NIL);
897 if ((write (fd,s,j) < 0) || (write (fd,"\r\n",2) < 0))
898 ret = NIL;
899 else if (cu) { /* need to pass back new UID? */
900 mail_append_set (source,mail_uid (stream,i));
901 mail_append_set (dest,tstream->uid_last);
908 if (!ret || fsync (fd)) { /* force out the update */
909 sprintf (LOCAL->buf,"Message copy failed: %s",strerror (errno));
910 ftruncate (fd,sbuf.st_size);
911 ret = NIL;
913 /* force UIDVALIDITY assignment now */
914 if (tstream && !tstream->uid_validity)
915 tstream->uid_validity = (unsigned long) time (0);
916 /* return sets if doing COPYUID */
917 if (cu && ret) (*cu) (stream,mailbox,tstream->uid_validity,source,dest);
918 else { /* flush any sets we may have built */
919 mail_free_searchset (&source);
920 mail_free_searchset (&dest);
922 times.modtime = time (0); /* set mtime to now */
923 /* set atime to now-1 if successful copy */
924 if (ret) times.actime = times.modtime - 1;
926 else times.actime = /* else preserve \Marked status */
927 ((sbuf.st_ctime > sbuf.st_atime) || (sbuf.st_mtime > sbuf.st_atime)) ?
928 sbuf.st_atime : times.modtime;
929 utime (file,&times); /* set the times */
930 unix_unlock (fd,NIL,lock); /* unlock and close mailbox */
931 if (tstream) { /* update last UID if we can */
932 UNIXLOCAL * local = (UNIXLOCAL *) tstream->local;
933 local->dirty = T; /* do a rewrite */
934 local->appending = T; /* but not at the cost of marking as old */
935 tstream = mail_close (tstream);
937 /* log the error */
938 if (!ret) mm_log (LOCAL->buf,ERROR);
939 /* delete if requested message */
940 else if (options & CP_MOVE) for (i = 1; i <= stream->nmsgs; i++)
941 if ((elt = mail_elt (stream,i))->sequence)
942 elt->deleted = elt->private.dirty = LOCAL->dirty = T;
943 mm_nocritical (stream); /* release critical */
944 return ret;
947 /* UNIX mail append message from stringstruct
948 * Accepts: MAIL stream
949 * destination mailbox
950 * append callback
951 * data for callback
952 * Returns: T if append successful, else NIL
955 #define BUFLEN 8*MAILTMPLEN
957 long unix_append (MAILSTREAM *stream,char *mailbox,append_t af,void *data)
959 struct stat sbuf;
960 int fd;
961 unsigned long i;
962 char *flags,*date,buf[BUFLEN],tmp[MAILTMPLEN],file[MAILTMPLEN],
963 lock[MAILTMPLEN];
964 struct utimbuf times;
965 FILE *sf,*df;
966 MESSAGECACHE elt;
967 STRING *message;
968 unsigned long uidlocation = 0;
969 appenduid_t au = (appenduid_t)
970 (mail_parameters (NIL,GET_USERHASNOLIFE,NIL) ? NIL :
971 mail_parameters (NIL,GET_APPENDUID,NIL));
972 SEARCHSET *dst = au ? mail_newsearchset () : NIL;
973 long ret = LONGT;
974 MAILSTREAM *tstream = NIL;
975 if (!stream) { /* stream specified? */
976 stream = &unixproto; /* no, default stream to prototype */
977 for (i = 0; i < NUSERFLAGS && stream->user_flags[i]; ++i)
978 fs_give ((void **) &stream->user_flags[i]);
980 if (!unix_valid (mailbox)) switch (errno) {
981 case ENOENT: /* no such file? */
982 if (!compare_cstring (mailbox,"INBOX")) {
983 mm_notify (stream,"[TRYCREATE] Must create mailbox before append",NIL);
984 return NIL;
986 unix_create (NIL,"INBOX"); /* create empty INBOX */
987 case 0: /* merely empty file? */
988 tstream = stream;
989 break;
990 case EACCES: /* file protected */
991 sprintf (tmp,"Can't access destination: %.80s",mailbox);
992 MM_LOG (tmp,ERROR);
993 return NIL;
994 case EINVAL:
995 sprintf (tmp,"Invalid UNIX-format mailbox name: %.80s",mailbox);
996 mm_log (tmp,ERROR);
997 return NIL;
998 default:
999 sprintf (tmp,"Not a UNIX-format mailbox: %.80s",mailbox);
1000 mm_log (tmp,ERROR);
1001 return NIL;
1003 /* get sniffing stream for keywords */
1004 else if (!(tstream = mail_open (NIL,mailbox,
1005 OP_READONLY|OP_SILENT|OP_NOKOD|OP_SNIFF))) {
1006 sprintf (tmp,"Unable to examine mailbox for APPEND: %.80s",mailbox);
1007 MM_LOG (tmp,ERROR);
1008 return NIL;
1011 /* get first message */
1012 if (!(*af) (tstream,data,&flags,&date,&message)) return NIL;
1013 if (!(sf = tmpfile ())) { /* must have scratch file */
1014 sprintf (tmp,".%lx.%lx",(unsigned long) time (0),(unsigned long)getpid ());
1015 if (!stat (tmp,&sbuf) || !(sf = fopen (tmp,"wb+"))) {
1016 sprintf (tmp,"Unable to create scratch file: %.80s",strerror (errno));
1017 mm_log (tmp,ERROR);
1018 return NIL;
1020 unlink (tmp);
1022 do { /* parse date */
1023 if (!date) rfc822_date (date = tmp);
1024 if (!mail_parse_date (&elt,date)) {
1025 sprintf (tmp,"Bad date in append: %.80s",date);
1026 mm_log (tmp,ERROR);
1028 else { /* user wants to suppress time zones? */
1029 if (mail_parameters (NIL,GET_NOTIMEZONES,NIL)) {
1030 time_t when = mail_longdate (&elt);
1031 date = ctime (&when); /* use traditional date */
1033 /* use POSIX-style date */
1034 else date = mail_cdate (tmp,&elt);
1035 if (!SIZE (message)) mm_log ("Append of zero-length message",ERROR);
1036 else if (!unix_collect_msg (tstream,sf,flags,date,message)) {
1037 sprintf (tmp,"Error writing scratch file: %.80s",strerror (errno));
1038 mm_log (tmp,ERROR);
1040 /* get next message */
1041 else if ((*af) (tstream,data,&flags,&date,&message)) continue;
1043 fclose (sf); /* punt scratch file */
1044 return NIL; /* give up */
1045 } while (message); /* until no more messages */
1046 if (fflush (sf)) {
1047 sprintf (tmp,"Error finishing scratch file: %.80s",strerror (errno));
1048 mm_log (tmp,ERROR);
1049 fclose (sf); /* punt scratch file */
1050 return NIL; /* give up */
1052 i = ftell (sf); /* size of scratch file */
1054 /* close sniffing stream */
1055 if (tstream != stream) tstream = mail_close (tstream);
1056 mm_critical (stream); /* go critical */
1057 /* try to open readwrite for UIDPLUS */
1058 if ((tstream = mail_open_work (&unixdriver,NIL,mailbox,
1059 OP_SILENT|OP_NOKOD)) && tstream->rdonly)
1060 tstream = mail_close (tstream);
1061 if (au && !tstream) { /* wanted an APPENDUID? */
1062 sprintf (tmp,"Unable to re-open mailbox for APPENDUID: %.80s",mailbox);
1063 MM_LOG (tmp,WARN);
1064 au = NIL;
1066 if (((fd = unix_lock (dummy_file (file,mailbox),
1067 O_BINARY|O_WRONLY|O_APPEND|O_CREAT,S_IREAD|S_IWRITE,
1068 lock,LOCK_EX)) < 0) || !(df = fdopen (fd,"ab"))) {
1069 mm_nocritical (stream); /* done with critical */
1070 sprintf (tmp,"Can't open append mailbox: %s",strerror (errno));
1071 mm_log (tmp,ERROR);
1072 return NIL;
1074 fstat (fd,&sbuf); /* get current file size */
1075 rewind (sf);
1076 times.modtime = time (0); /* set mtime to now */
1077 /* write all messages */
1078 if (!unix_append_msgs (tstream,sf,df,au ? dst : NIL) ||
1079 (fflush (df) == EOF) || fsync (fd)) {
1080 sprintf (buf,"Message append failed: %s",strerror (errno));
1081 mm_log (buf,ERROR);
1082 ftruncate (fd,sbuf.st_size);/* revert file */
1083 times.actime = /* preserve \Marked status */
1084 ((sbuf.st_ctime > sbuf.st_atime) || (sbuf.st_mtime > sbuf.st_atime)) ?
1085 sbuf.st_atime : times.modtime;
1086 ret = NIL; /* return error */
1088 /* set atime to now-1 if successful copy */
1089 else times.actime = times.modtime - 1;
1090 utime (file,&times); /* set the times */
1091 fclose (sf); /* done with scratch file */
1092 /* force UIDVALIDITY assignment now */
1093 if (tstream && !tstream->uid_validity)
1094 tstream->uid_validity = (unsigned long) time (0);
1095 /* return sets if doing APPENDUID */
1096 if (au && ret) (*au) (mailbox,tstream->uid_validity,dst);
1097 else mail_free_searchset (&dst);
1098 flock (fd,LOCK_UN); /* unlock mailbox (can't use unix_unlock() */
1099 if (lock && *lock) unlink (lock);
1100 fclose (df); /* close mailbox */
1101 if (tstream) { /* update last UID if we can */
1102 UNIXLOCAL * local = (UNIXLOCAL *) tstream->local;
1103 local->dirty = T; /* do a rewrite */
1104 local->appending = T; /* but not at the cost of marking as old */
1105 tstream = mail_close (tstream);
1107 mm_nocritical (stream); /* release critical */
1108 return ret;
1111 /* Collect and write single message to append scratch file
1112 * Accepts: MAIL stream
1113 * scratch file
1114 * flags
1115 * date
1116 * message stringstruct
1117 * Returns: NIL if write error, else T
1120 int unix_collect_msg (MAILSTREAM *stream,FILE *sf,char *flags,char *date,
1121 STRING *msg)
1123 unsigned char *s,*t;
1124 unsigned long uf;
1125 long f = mail_parse_flags (stream,flags,&uf);
1126 /* write metadata */
1127 if (fprintf (sf,"%ld %lu ",f,SIZE (msg) + 2) < 0) return NIL;
1128 for (s = date; *s; *s++) switch (*s) {
1129 default:
1130 if (putc (*s,sf) == EOF) return NIL;
1131 case '\r': case '\n':
1132 break;
1134 if (fputs ("\r\n",sf) == EOF) return NIL;
1135 while (uf) /* write user flags */
1136 if ((s = stream->user_flags[find_rightmost_bit (&uf)]) &&
1137 (fprintf (sf," %s",s) < 0)) return NIL;
1138 if (fputs ("\r\n",sf) == EOF) return NIL;
1139 while (SIZE (msg)) { /* copy text to scratch file */
1140 for (s = (unsigned char *) msg->curpos, t = s + msg->cursize; s < t; ++s)
1141 if (!*s) *s = 0x80; /* disallow NUL */
1142 /* write buffered text */
1143 if (fwrite (msg->curpos,1,msg->cursize,sf) == msg->cursize)
1144 SETPOS (msg,GETPOS (msg) + msg->cursize);
1145 else return NIL; /* failed */
1147 /* write trailing CRLF and return */
1148 return (fputs ("\r\n",sf) == EOF) ? NIL : T;
1151 /* Append messages from scratch file to mailbox
1152 * Accepts: MAIL stream
1153 * source file
1154 * destination file
1155 * uidset to update if non-NIL
1156 * Returns: T if success, NIL if failure
1159 int unix_append_msgs (MAILSTREAM *stream,FILE *sf,FILE *df,SEARCHSET *set)
1161 int ti,zn,c;
1162 long f;
1163 unsigned long i,j;
1164 char *x,tmp[MAILTMPLEN];
1165 int hdrp = T;
1166 /* get message metadata line */
1167 while (fgets (tmp,MAILTMPLEN,sf)) {
1168 if (!(isdigit (tmp[0]) && strchr (tmp,'\n'))) return NIL;
1169 f = strtol (tmp,&x,10); /* get flags */
1170 if (!((*x++ == ' ') && isdigit (*x))) return NIL;
1171 i = strtoul (x,&x,10); /* get message size */
1172 if ((*x++ != ' ') || /* build initial header */
1173 (fprintf (df,"From %s@%s %sStatus: ",myusername(),mylocalhost(),x)<0)||
1174 (f&fSEEN && (putc ('R',df) == EOF)) ||
1175 (fputs ("\r\nX-Status: ",df) == EOF) ||
1176 (f&fDELETED && (putc ('D',df) == EOF)) ||
1177 (f&fFLAGGED && (putc ('F',df) == EOF)) ||
1178 (f&fANSWERED && (putc ('A',df) == EOF)) ||
1179 (f&fDRAFT && (putc ('T',df) == EOF)) ||
1180 (fputs ("\r\nX-Keywords:",df) == EOF)) return NIL;
1181 /* copy keywords */
1182 while ((c = getc (sf)) != '\n') switch (c) {
1183 case EOF:
1184 return NIL;
1185 default:
1186 if (putc (c,df) == EOF) return NIL;
1188 if ((putc ('\n',df) == EOF) ||
1189 (set && (fprintf (df,"X-UID: %lu\r\n",++(stream->uid_last)) < 0)))
1190 return NIL;
1192 for (c = '\n'; i && fgets (tmp,MAILTMPLEN,sf); c = tmp[j-1]) {
1193 /* get read line length */
1194 if (i < (j = strlen (tmp))) fatal ("unix_append_msgs overrun");
1195 i -= j; /* number of bytes left */
1196 if (!j) continue; /* do nothing if line emptied */
1197 /* complete line? */
1198 if ((c == '\n')) switch (tmp[0]) {
1199 case 'F': /* possible "From " (case counts here) */
1200 if ((j > 4) && (tmp[0] == 'F') && (tmp[1] == 'r') && (tmp[2] == 'o') &&
1201 (tmp[3] == 'm') && (tmp[4] == ' ')) {
1202 if (!unix_fromwidget) {
1203 VALID (tmp,x,ti,zn);/* conditional, only write widget if */
1204 if (!ti) break; /* it looks like a valid header */
1205 } /* write the widget */
1206 if (putc ('>',df) == EOF) return NIL;
1208 break;
1209 case 'S': case 's': /* possible "Status:" */
1210 if (hdrp && (j > 6) && ((tmp[1] == 't') || (tmp[1] == 'T')) &&
1211 ((tmp[2] == 'a') || (tmp[2] == 'A')) &&
1212 ((tmp[3] == 't') || (tmp[3] == 'T')) &&
1213 ((tmp[4] == 'u') || (tmp[4] == 'U')) &&
1214 ((tmp[5] == 's') || (tmp[5] == 'S')) && (tmp[6] == ':') &&
1215 (fputs ("X-Original-",df) == EOF)) return NIL;
1216 break;
1217 case 'X': case 'x': /* possible X-??? header */
1218 if (hdrp && (tmp[1] == '-') &&
1219 /* possible X-UID: */
1220 (((j > 5) && ((tmp[2] == 'U') || (tmp[2] == 'u')) &&
1221 ((tmp[3] == 'I') || (tmp[3] == 'i')) &&
1222 ((tmp[4] == 'D') || (tmp[4] == 'd')) && (tmp[5] == ':')) ||
1223 /* possible X-IMAP: */
1224 ((j > 6) && ((tmp[2] == 'I') || (tmp[2] == 'i')) &&
1225 ((tmp[3] == 'M') || (tmp[3] == 'm')) &&
1226 ((tmp[4] == 'A') || (tmp[4] == 'a')) &&
1227 ((tmp[5] == 'P') || (tmp[5] == 'p')) &&
1228 ((tmp[6] == ':') ||
1229 /* or X-IMAPbase: */
1230 ((j > 10) && ((tmp[6] == 'b') || (tmp[6] == 'B')) &&
1231 ((tmp[7] == 'a') || (tmp[7] == 'A')) &&
1232 ((tmp[8] == 's') || (tmp[8] == 'S')) &&
1233 ((tmp[9] == 'e') || (tmp[9] == 'E')) && (tmp[10] == ':')))) ||
1234 /* possible X-Status: */
1235 ((j > 8) && ((tmp[2] == 'S') || (tmp[2] == 's')) &&
1236 ((tmp[3] == 't') || (tmp[3] == 'T')) &&
1237 ((tmp[4] == 'a') || (tmp[4] == 'A')) &&
1238 ((tmp[5] == 't') || (tmp[5] == 'T')) &&
1239 ((tmp[6] == 'u') || (tmp[6] == 'U')) &&
1240 ((tmp[7] == 's') || (tmp[7] == 'S')) && (tmp[8] == ':')) ||
1241 /* possible X-Keywords: */
1242 ((j > 10) && ((tmp[2] == 'K') || (tmp[2] == 'k')) &&
1243 ((tmp[3] == 'e') || (tmp[3] == 'E')) &&
1244 ((tmp[4] == 'y') || (tmp[4] == 'Y')) &&
1245 ((tmp[5] == 'w') || (tmp[5] == 'W')) &&
1246 ((tmp[6] == 'o') || (tmp[6] == 'O')) &&
1247 ((tmp[7] == 'r') || (tmp[7] == 'R')) &&
1248 ((tmp[8] == 'd') || (tmp[8] == 'D')) &&
1249 ((tmp[9] == 's') || (tmp[9] == 'S')) && (tmp[10] == ':'))) &&
1250 (fputs ("X-Original-",df) == EOF)) return NIL;
1251 break;
1252 case '\n': /* blank line */
1253 hdrp = NIL;
1254 break;
1255 default: /* nothing to do */
1256 break;
1258 /* just write the line */
1259 if (fwrite (tmp,1,j,df) != j) return NIL;
1261 if (i) return NIL; /* didn't read entire message */
1262 /* update set */
1263 if (stream) mail_append_set (set,stream->uid_last);
1265 return T;
1268 /* Internal routines */
1271 /* UNIX mail abort stream
1272 * Accepts: MAIL stream
1275 void unix_abort (MAILSTREAM *stream)
1277 if (LOCAL) { /* only if a file is open */
1278 if (LOCAL->fd >= 0) close (LOCAL->fd);
1279 if (LOCAL->ld >= 0) { /* have a mailbox lock? */
1280 flock (LOCAL->ld,LOCK_UN);/* yes, release the lock */
1281 close (LOCAL->ld); /* close the lock file */
1282 unlink (LOCAL->lname); /* and delete it */
1284 if (LOCAL->lname) fs_give ((void **) &LOCAL->lname);
1285 /* free local text buffers */
1286 if (LOCAL->buf) fs_give ((void **) &LOCAL->buf);
1287 if (LOCAL->text.data) fs_give ((void **) &LOCAL->text.data);
1288 if (LOCAL->linebuf) fs_give ((void **) &LOCAL->linebuf);
1289 if (LOCAL->line) fs_give ((void **) &LOCAL->line);
1290 /* nuke the local data */
1291 fs_give ((void **) &stream->local);
1292 stream->dtb = NIL; /* log out the DTB */
1296 /* UNIX open and lock mailbox
1297 * Accepts: file name to open/lock
1298 * file open mode
1299 * destination buffer for lock file name
1300 * type of locking operation (LOCK_SH or LOCK_EX)
1303 int unix_lock (char *file,int flags,int mode,char *lock,int op)
1305 int fd,ld,j;
1306 int i = LOCKTIMEOUT * 60 - 1;
1307 char tmp[MAILTMPLEN];
1308 time_t t;
1309 struct stat sb;
1310 sprintf (lock,"%s.lock",file);/* build lock filename */
1311 do { /* until OK or out of tries */
1312 t = time (0); /* get the time now */
1313 /* try to get the lock */
1314 if ((ld = open(lock,O_BINARY|O_WRONLY|O_CREAT|O_EXCL,S_IREAD|S_IWRITE))>=0)
1315 close (ld); /* got it, close the lock file! */
1316 else if (errno != EEXIST) { /* miscellaneous error */
1317 sprintf (tmp,"Error creating %.80s: %s",lock,strerror (errno));
1318 if (!(i%15)) mm_log (tmp,WARN);
1320 /* lock exists, still active? */
1321 else if (!stat (lock,&sb) && (t > sb.st_ctime + LOCKTIMEOUT * 60) &&
1322 ((ld = open(lock,O_BINARY|O_WRONLY|O_CREAT,S_IREAD|S_IWRITE))>=0))
1323 close (ld); /* got timed-out lock file */
1324 else { /* active lock, try again */
1325 if (!(i%15)) {
1326 sprintf (tmp,"Mailbox %.80s is locked, will override in %d seconds...",
1327 file,i);
1328 mm_log (tmp,WARN);
1330 sleep (1); /* wait a second before next retry */
1332 } while (*lock && ld < 0 && i--);
1333 /* open file */
1334 if ((fd = open (file,flags,mode)) >= 0) flock (fd,op);
1335 else { /* open failed */
1336 j = errno; /* preserve error code */
1337 if (*lock) unlink (lock); /* flush the lock file if any */
1338 errno = j; /* restore error code */
1340 return fd;
1343 /* UNIX unlock and close mailbox
1344 * Accepts: file descriptor
1345 * (optional) mailbox stream to check atime/mtime
1346 * (optional) lock file name
1349 void unix_unlock (int fd,MAILSTREAM *stream,char *lock)
1351 if (stream) { /* need to muck with times? */
1352 struct stat sbuf;
1353 struct utimbuf times;
1354 time_t now = time (0);
1355 fstat (fd,&sbuf); /* get file times */
1356 if (LOCAL->ld >= 0) { /* yes, readwrite session? */
1357 times.actime = now; /* set atime to now */
1358 /* set mtime to (now - 1) if necessary */
1359 times.modtime = (now > sbuf.st_mtime) ? sbuf.st_mtime : now - 1;
1361 else if (stream->recent) { /* readonly with recent messages */
1362 if ((sbuf.st_atime >= sbuf.st_mtime) ||
1363 (sbuf.st_atime >= sbuf.st_ctime))
1364 /* keep past mtime, whack back atime */
1365 times.actime = (times.modtime = (sbuf.st_mtime < now) ?
1366 sbuf.st_mtime : now) - 1;
1367 else now = 0; /* no time change needed */
1369 /* readonly with no recent messages */
1370 else if ((sbuf.st_atime < sbuf.st_mtime) ||
1371 (sbuf.st_atime < sbuf.st_ctime)) {
1372 times.actime = now; /* set atime to now */
1373 /* set mtime to (now - 1) if necessary */
1374 times.modtime = (now > sbuf.st_mtime) ? sbuf.st_mtime : now - 1;
1376 else now = 0; /* no time change needed */
1377 /* set the times, note change */
1378 if (now && !utime (stream->mailbox,&times))
1379 LOCAL->filetime = times.modtime;
1381 flock (fd,LOCK_UN); /* release flock'ers */
1382 if (!stream) close (fd); /* close the file if no stream */
1383 /* flush the lock file if any */
1384 if (lock && *lock) unlink (lock);
1387 /* UNIX mail parse and lock mailbox
1388 * Accepts: MAIL stream
1389 * space to write lock file name
1390 * type of locking operation
1391 * Returns: T if parse OK, critical & mailbox is locked shared; NIL if failure
1394 int unix_parse (MAILSTREAM *stream,char *lock,int op)
1396 int zn;
1397 unsigned long i,j,k,m;
1398 unsigned char c,*s,*t,*u,tmp[MAILTMPLEN],date[30];
1399 int ti = 0,retain = T;
1400 unsigned long nmsgs = stream->nmsgs;
1401 unsigned long prevuid = nmsgs ? mail_elt (stream,nmsgs)->private.uid : 0;
1402 unsigned long recent = stream->recent;
1403 unsigned long oldnmsgs = stream->nmsgs;
1404 short silent = stream->silent;
1405 short pseudoseen = NIL;
1406 struct stat sbuf;
1407 STRING bs;
1408 FDDATA d;
1409 MESSAGECACHE *elt;
1410 mail_lock (stream); /* guard against recursion or pingers */
1411 /* toss out previous descriptor */
1412 if (LOCAL->fd >= 0) close (LOCAL->fd);
1413 mm_critical (stream); /* open and lock mailbox (shared OK) */
1414 if ((LOCAL->fd = unix_lock (stream->mailbox,
1415 O_BINARY + ((LOCAL->ld >= 0) ? O_RDWR:O_RDONLY),
1416 NIL,lock,op)) < 0) {
1417 sprintf (tmp,"Mailbox open failed, aborted: %s",strerror (errno));
1418 mm_log (tmp,ERROR);
1419 unix_abort (stream);
1420 mail_unlock (stream);
1421 mm_nocritical (stream); /* done with critical */
1422 return NIL;
1424 fstat (LOCAL->fd,&sbuf); /* get status */
1425 /* validate change in size */
1426 if (sbuf.st_size < LOCAL->filesize) {
1427 sprintf (tmp,"Mailbox shrank from %lu to %lu bytes, aborted",
1428 (unsigned long) LOCAL->filesize,(unsigned long) sbuf.st_size);
1429 mm_log (tmp,ERROR); /* this is pretty bad */
1430 unix_unlock (LOCAL->fd,stream,lock);
1431 unix_abort (stream);
1432 mail_unlock (stream);
1433 mm_nocritical (stream); /* done with critical */
1434 return NIL;
1437 /* new data? */
1438 else if (i = sbuf.st_size - LOCAL->filesize) {
1439 d.fd = LOCAL->fd; /* yes, set up file descriptor */
1440 d.pos = LOCAL->filesize; /* get to that position in the file */
1441 d.chunk = LOCAL->buf; /* initial buffer chunk */
1442 d.chunksize = CHUNKSIZE; /* file chunk size */
1443 INIT (&bs,fd_string,&d,i); /* initialize stringstruct */
1444 /* skip leading whitespace for broken MTAs */
1445 while (((c = CHR (&bs)) == '\n') || (c == '\r') ||
1446 (c == ' ') || (c == '\t')) SNX (&bs);
1447 if (SIZE (&bs)) { /* read new data */
1448 /* remember internal header position */
1449 j = LOCAL->filesize + GETPOS (&bs);
1450 s = unix_mbxline (stream,&bs,&i);
1451 t = NIL,zn = 0;
1452 if (i) VALID (s,t,ti,zn); /* see if valid From line */
1453 if (!ti) { /* someone pulled the rug from under us */
1454 sprintf (tmp,"Unexpected changes to mailbox (try restarting): %.20s",
1455 (char *) s);
1456 mm_log (tmp,ERROR);
1457 unix_unlock (LOCAL->fd,stream,lock);
1458 unix_abort (stream);
1459 mail_unlock (stream);
1460 mm_nocritical (stream); /* done with critical */
1461 return NIL;
1463 stream->silent = T; /* quell main program new message events */
1464 do { /* found a message */
1465 /* instantiate first new message */
1466 mail_exists (stream,++nmsgs);
1467 (elt = mail_elt (stream,nmsgs))->valid = T;
1468 recent++; /* assume recent by default */
1469 elt->recent = T;
1470 /* note position/size of internal header */
1471 elt->private.special.offset = j;
1472 elt->private.msg.header.offset = elt->private.special.text.size = i;
1474 /* generate plausible IMAPish date string */
1475 date[2] = date[6] = date[20] = '-'; date[11] = ' ';
1476 date[14] = date[17] = ':';
1477 /* dd */
1478 date[0] = t[ti - 2]; date[1] = t[ti - 1];
1479 /* mmm */
1480 date[3] = t[ti - 6]; date[4] = t[ti - 5]; date[5] = t[ti - 4];
1481 /* hh */
1482 date[12] = t[ti + 1]; date[13] = t[ti + 2];
1483 /* mm */
1484 date[15] = t[ti + 4]; date[16] = t[ti + 5];
1485 if (t[ti += 6] == ':') {/* ss */
1486 date[18] = t[++ti]; date[19] = t[++ti];
1487 ti++; /* move to space */
1489 else date[18] = date[19] = '0';
1490 /* yy -- advance over timezone if necessary */
1491 if (zn == ti) ti += (((t[zn+1] == '+') || (t[zn+1] == '-')) ? 6 : 4);
1492 date[7] = t[ti + 1]; date[8] = t[ti + 2];
1493 date[9] = t[ti + 3]; date[10] = t[ti + 4];
1494 /* zzz */
1495 t = zn ? (t + zn + 1) : (unsigned char *) "LCL";
1496 date[21] = *t++; date[22] = *t++; date[23] = *t++;
1497 if ((date[21] != '+') && (date[21] != '-')) date[24] = '\0';
1498 else { /* numeric time zone */
1499 date[24] = *t++; date[25] = *t++;
1500 date[26] = '\0'; date[20] = ' ';
1502 /* set internal date */
1503 if (!mail_parse_date (elt,date)) {
1504 sprintf (tmp,"Unable to parse internal date: %s",(char *) date);
1505 mm_log (tmp,WARN);
1508 do { /* look for message body */
1509 s = t = unix_mbxline (stream,&bs,&i);
1510 if (i) switch (*s) { /* check header lines */
1511 case 'X': /* possible X-???: line */
1512 if (s[1] == '-') { /* must be immediately followed by hyphen */
1513 /* X-Status: becomes Status: in S case */
1514 if (s[2] == 'S' && s[3] == 't' && s[4] == 'a' && s[5] == 't' &&
1515 s[6] == 'u' && s[7] == 's' && s[8] == ':') s += 2;
1516 /* possible X-Keywords */
1517 else if (s[2] == 'K' && s[3] == 'e' && s[4] == 'y' &&
1518 s[5] == 'w' && s[6] == 'o' && s[7] == 'r' &&
1519 s[8] == 'd' && s[9] == 's' && s[10] == ':') {
1520 SIZEDTEXT uf;
1521 retain = NIL; /* don't retain continuation */
1522 s += 11; /* flush leading whitespace */
1523 while (*s && (*s != '\n') && ((*s != '\r') || (s[1] != '\n'))){
1524 while (*s == ' ') s++;
1525 /* find end of keyword */
1526 if (!(u = strpbrk (s," \n\r"))) u = s + strlen (s);
1527 /* got a keyword? */
1528 if ((k = (u - s)) && (k <= MAXUSERFLAG)) {
1529 uf.data = (unsigned char *) s;
1530 uf.size = k;
1531 for (j = 0; (j < NUSERFLAGS) && stream->user_flags[j]; ++j)
1532 if (!compare_csizedtext (stream->user_flags[j],&uf)) {
1533 elt->user_flags |= ((long) 1) << j;
1534 break;
1537 s = u; /* advance to next keyword */
1539 break;
1542 /* possible X-IMAP */
1543 else if ((s[2] == 'I') && (s[3] == 'M') && (s[4] == 'A') &&
1544 (s[5] == 'P') && ((m = (s[6] == ':')) ||
1545 ((s[6] == 'b') && (s[7] == 'a') &&
1546 (s[8] == 's') && (s[9] == 'e') &&
1547 (s[10] == ':')))) {
1548 retain = NIL; /* don't retain continuation */
1549 if ((nmsgs == 1) && !stream->uid_validity) {
1550 /* advance to data */
1551 s += m ? 7 : 11;
1552 /* flush whitespace */
1553 while (*s == ' ') s++;
1554 j = 0; /* slurp UID validity */
1555 /* found a digit? */
1556 while (isdigit (*s)) {
1557 j *= 10; /* yes, add it in */
1558 j += *s++ - '0';
1560 /* flush whitespace */
1561 while (*s == ' ') s++;
1562 /* must have valid UID validity and UID last */
1563 if (j && isdigit (*s)) {
1564 /* pseudo-header seen if X-IMAP */
1565 if (m) pseudoseen = LOCAL->pseudo = T;
1566 /* save UID validity */
1567 stream->uid_validity = j;
1568 j = 0; /* slurp UID last */
1569 while (isdigit (*s)) {
1570 j *= 10; /* yes, add it in */
1571 j += *s++ - '0';
1573 /* save UID last */
1574 stream->uid_last = j;
1575 /* process keywords */
1576 for (j = 0; (*s != '\n') && ((*s != '\r')||(s[1] != '\n'));
1577 s = u,j++) {
1578 /* flush leading whitespace */
1579 while (*s == ' ') s++;
1580 u = strpbrk (s," \n\r");
1581 /* got a keyword? */
1582 if ((j < NUSERFLAGS) && (k = (u - s)) &&
1583 (k <= MAXUSERFLAG)) {
1584 if (stream->user_flags[j])
1585 fs_give ((void **) &stream->user_flags[j]);
1586 stream->user_flags[j] = (char *) fs_get (k + 1);
1587 strncpy (stream->user_flags[j],s,k);
1588 stream->user_flags[j][k] = '\0';
1593 break;
1596 /* possible X-UID */
1597 else if (s[2] == 'U' && s[3] == 'I' && s[4] == 'D' &&
1598 s[5] == ':') {
1599 retain = NIL; /* don't retain continuation */
1600 /* only believe if have a UID validity */
1601 if (stream->uid_validity && ((nmsgs > 1) || !pseudoseen)) {
1602 s += 6; /* advance to UID value */
1603 /* flush whitespace */
1604 while (*s == ' ') s++;
1605 j = 0;
1606 /* found a digit? */
1607 while (isdigit (*s)) {
1608 j *= 10; /* yes, add it in */
1609 j += *s++ - '0';
1611 /* flush remainder of line */
1612 while (*s != '\n') s++;
1613 /* make sure not duplicated */
1614 if (elt->private.uid)
1615 sprintf (tmp,"Message %lu UID %lu already has UID %lu",
1616 pseudoseen ? elt->msgno - 1 : elt->msgno,
1617 j,elt->private.uid);
1618 /* make sure UID doesn't go backwards */
1619 else if (j <= prevuid)
1620 sprintf (tmp,"Message %lu UID %lu less than %lu",
1621 pseudoseen ? elt->msgno - 1 : elt->msgno,
1622 j,prevuid + 1);
1623 #if 0 /* this is currently broken by UIDPLUS */
1624 /* or skip by mailbox's recorded last */
1625 else if (j > stream->uid_last)
1626 sprintf (tmp,"Message %lu UID %lu greater than last %lu",
1627 pseudoseen ? elt->msgno - 1 : elt->msgno,
1628 j,stream->uid_last);
1629 #endif
1630 else { /* normal UID case */
1631 prevuid = elt->private.uid = j;
1632 #if 1 /* temporary kludge for UIDPLUS */
1633 if (prevuid > stream->uid_last) {
1634 stream->uid_last = prevuid;
1635 LOCAL->ddirty = LOCAL->dirty = T;
1637 #endif
1638 break; /* exit this cruft */
1640 mm_log (tmp,WARN);
1641 /* invalidate UID validity */
1642 stream->uid_validity = 0;
1643 elt->private.uid = 0;
1645 break;
1648 /* otherwise fall into S case */
1650 case 'S': /* possible Status: line */
1651 if (s[0] == 'S' && s[1] == 't' && s[2] == 'a' && s[3] == 't' &&
1652 s[4] == 'u' && s[5] == 's' && s[6] == ':') {
1653 retain = NIL; /* don't retain continuation */
1654 s += 6; /* advance to status flags */
1655 do switch (*s++) {/* parse flags */
1656 case 'R': /* message read */
1657 elt->seen = T;
1658 break;
1659 case 'O': /* message old */
1660 if (elt->recent) {
1661 elt->recent = NIL;
1662 recent--; /* it really wasn't recent */
1664 break;
1665 case 'D': /* message deleted */
1666 elt->deleted = T;
1667 break;
1668 case 'F': /* message flagged */
1669 elt->flagged = T;
1670 break;
1671 case 'A': /* message answered */
1672 elt->answered = T;
1673 break;
1674 case 'T': /* message is a draft */
1675 elt->draft = T;
1676 break;
1677 default: /* some other crap */
1678 break;
1679 } while (*s && (*s != '\n') && ((*s != '\r') || (s[1] != '\n')));
1680 break; /* all done */
1682 /* otherwise fall into default case */
1684 default: /* ordinary header line */
1685 if ((*s == 'S') || (*s == 's') ||
1686 (((*s == 'X') || (*s == 'x')) && (s[1] == '-'))) {
1687 unsigned char *e,*v;
1688 /* must match what mail_filter() does */
1689 for (u = s,v = tmp,e = u + min (i,MAILTMPLEN - 1);
1690 (u < e) && ((c = (*u ? *u : (*u = ' '))) != ':') &&
1691 ((c > ' ') || ((c != ' ') && (c != '\t') &&
1692 (c != '\r') && (c != '\n')));
1693 *v++ = *u++);
1694 *v = '\0'; /* tie off */
1695 /* matches internal header? */
1696 if (!compare_cstring (tmp,"STATUS") ||
1697 !compare_cstring (tmp,"X-STATUS") ||
1698 !compare_cstring (tmp,"X-KEYWORDS") ||
1699 !compare_cstring (tmp,"X-UID") ||
1700 !compare_cstring (tmp,"X-IMAP") ||
1701 !compare_cstring (tmp,"X-IMAPBASE")) {
1702 char err[MAILTMPLEN];
1703 sprintf (err,"Discarding bogus %s header in message %lu",
1704 (char *) tmp,elt->msgno);
1705 mm_log (err,WARN);
1706 retain = NIL; /* don't retain continuation */
1707 break; /* different case or something */
1710 /* retain or non-continuation? */
1711 if (retain || ((*s != ' ') && (*s != '\t'))) {
1712 retain = T; /* retaining continuation now */
1713 /* line length in CRLF format newline */
1714 k = i + (((i < 2) || (s[i - 2] != '\r')) ? 1 : 0);
1715 /* header size */
1716 elt->rfc822_size = elt->private.spare.data += k;
1718 else {
1719 char err[MAILTMPLEN];
1720 sprintf (err,"Discarding bogus continuation in msg %lu: %.80s",
1721 elt->msgno,(char *) s);
1722 if (u = strpbrk (err,"\r\n")) *u = '\0';
1723 mm_log (err,WARN);
1724 break; /* different case or something */
1726 break;
1728 } while (i && (*t != '\n') && ((*t != '\r') || (t[1] != '\n')));
1729 /* "internal" header sans trailing newline */
1730 if (i) elt->private.spare.data -= 2;
1731 /* assign a UID if none found */
1732 if (((nmsgs > 1) || !pseudoseen) && !elt->private.uid) {
1733 prevuid = elt->private.uid = ++stream->uid_last;
1734 elt->private.dirty = T;
1735 LOCAL->ddirty = T; /* force update */
1737 else elt->private.dirty = elt->recent;
1739 /* note size of header, location of text */
1740 elt->private.msg.header.text.size =
1741 (elt->private.msg.text.offset =
1742 (LOCAL->filesize + GETPOS (&bs)) - elt->private.special.offset) -
1743 elt->private.special.text.size;
1744 k = m = 0; /* no previous line size yet */
1745 /* note current position */
1746 j = LOCAL->filesize + GETPOS (&bs);
1747 if (i) do { /* look for next message */
1748 s = unix_mbxline (stream,&bs,&i);
1749 if (i) { /* got new data? */
1750 VALID (s,t,ti,zn); /* yes, parse line */
1751 if (!ti) { /* not a header line, add it to message */
1752 if (s[i - 1] == '\n')
1753 elt->rfc822_size +=
1754 k = i + (m = (((i < 2) || s[i - 2] != '\r') ? 1 : 0));
1755 else { /* file does not end with newline! */
1756 elt->rfc822_size += i;
1757 k = m = 0;
1759 /* update current position */
1760 j = LOCAL->filesize + GETPOS (&bs);
1763 } while (i && !ti); /* until found a header */
1764 elt->private.msg.text.text.size = j -
1765 (elt->private.special.offset + elt->private.msg.text.offset);
1766 if (k == 2) { /* last line was blank? */
1767 elt->private.msg.text.text.size -= (m ? 1 : 2);
1768 elt->rfc822_size -= 2;
1770 /* until end of buffer */
1771 } while (!stream->sniff && i);
1772 if (pseudoseen) { /* flush pseudo-message if present */
1773 /* decrement recent count */
1774 if (mail_elt (stream,1)->recent) recent--;
1775 /* and the exists count */
1776 mail_exists (stream,nmsgs--);
1777 mail_expunged(stream,1);/* fake an expunge of that message */
1779 /* need to start a new UID validity? */
1780 if (!stream->uid_validity) {
1781 stream->uid_validity = (unsigned long) time (0);
1782 if (nmsgs) { /* don't bother if empty file */
1783 /* make dirty to restart UID epoch */
1784 LOCAL->ddirty = LOCAL->dirty = T;
1785 /* need to rewrite msg 1 if not pseudo */
1786 if (!LOCAL->pseudo) mail_elt (stream,1)->private.dirty = T;
1787 mm_log ("Assigning new unique identifiers to all messages",NIL);
1790 stream->nmsgs = oldnmsgs; /* whack it back down */
1791 stream->silent = silent; /* restore old silent setting */
1792 /* notify upper level of new mailbox sizes */
1793 mail_exists (stream,nmsgs);
1794 mail_recent (stream,recent);
1795 /* mark dirty so O flags are set */
1796 if (recent) LOCAL->dirty = T;
1799 /* no change, don't babble if never got time */
1800 else if (LOCAL->filetime && LOCAL->filetime != sbuf.st_mtime)
1801 mm_log ("New mailbox modification time but apparently no changes",WARN);
1802 /* update parsed file size and time */
1803 LOCAL->filesize = sbuf.st_size;
1804 LOCAL->filetime = sbuf.st_mtime;
1805 return T; /* return the winnage */
1808 /* UNIX read line from mailbox
1809 * Accepts: mail stream
1810 * stringstruct
1811 * pointer to line size
1812 * Returns: pointer to input line
1815 char *unix_mbxline (MAILSTREAM *stream,STRING *bs,unsigned long *size)
1817 unsigned long i,j,k,m;
1818 char *s,*t,*te;
1819 char *ret = "";
1820 /* flush old buffer */
1821 if (LOCAL->line) fs_give ((void **) &LOCAL->line);
1822 /* if buffer needs refreshing */
1823 if (!bs->cursize) SETPOS (bs,GETPOS (bs));
1824 if (SIZE (bs)) { /* find newline */
1825 /* end of fast scan */
1826 te = (t = (s = bs->curpos) + bs->cursize) - 12;
1827 while (s < te) if ((*s++ == '\n') || (*s++ == '\n') || (*s++ == '\n') ||
1828 (*s++ == '\n') || (*s++ == '\n') || (*s++ == '\n') ||
1829 (*s++ == '\n') || (*s++ == '\n') || (*s++ == '\n') ||
1830 (*s++ == '\n') || (*s++ == '\n') || (*s++ == '\n')) {
1831 --s; /* back up */
1832 break; /* exit loop */
1834 /* final character-at-a-time scan */
1835 while ((s < t) && (*s != '\n')) ++s;
1836 /* difficult case if line spans buffer */
1837 if ((i = s - bs->curpos) == bs->cursize) {
1838 /* have space in line buffer? */
1839 if (i > LOCAL->linebuflen) {
1840 fs_give ((void **) &LOCAL->linebuf);
1841 LOCAL->linebuf = (char *) fs_get (LOCAL->linebuflen = i);
1843 /* remember what we have so far */
1844 memcpy (LOCAL->linebuf,bs->curpos,i);
1845 /* load next buffer */
1846 SETPOS (bs,k = GETPOS (bs) + i);
1847 /* end of fast scan */
1848 te = (t = (s = bs->curpos) + bs->cursize) - 12;
1849 /* fast scan in overlap buffer */
1850 while (s < te) if ((*s++ == '\n') || (*s++ == '\n') || (*s++ == '\n') ||
1851 (*s++ == '\n') || (*s++ == '\n') || (*s++ == '\n') ||
1852 (*s++ == '\n') || (*s++ == '\n') || (*s++ == '\n') ||
1853 (*s++ == '\n') || (*s++ == '\n') || (*s++ == '\n')) {
1854 --s; /* back up */
1855 break; /* exit loop */
1858 /* final character-at-a-time scan */
1859 while ((s < t) && (*s != '\n')) ++s;
1860 /* huge line? */
1861 if ((j = s - bs->curpos) == bs->cursize) {
1862 SETPOS (bs,GETPOS (bs) + j);
1863 /* look for end of line (s-l-o-w!!) */
1864 for (m = SIZE (bs); m && (SNX (bs) != '\n'); --m,++j);
1865 SETPOS (bs,k); /* go back to where it started */
1867 /* got size of data, make buffer for return */
1868 ret = LOCAL->line = (char *) fs_get (i + j + 2);
1869 /* copy first chunk */
1870 memcpy (ret,LOCAL->linebuf,i);
1871 while (j) { /* copy remainder */
1872 if (!bs->cursize) SETPOS (bs,GETPOS (bs));
1873 memcpy (ret + i,bs->curpos,k = min (j,bs->cursize));
1874 i += k; /* account for this much read in */
1875 j -= k;
1876 bs->curpos += k; /* increment new position */
1877 bs->cursize -= k; /* eat that many bytes */
1879 if (!bs->cursize) SETPOS (bs,GETPOS (bs));
1880 /* read newline at end */
1881 if (SIZE (bs)) ret[i++] = SNX (bs);
1882 ret[i] = '\0'; /* makes debugging easier */
1884 else { /* this is easy */
1885 ret = bs->curpos; /* string it at this position */
1886 bs->curpos += ++i; /* increment new position */
1887 bs->cursize -= i; /* eat that many bytes */
1889 *size = i; /* return that to user */
1891 else *size = 0; /* end of data, return empty */
1892 return ret;
1895 /* UNIX make pseudo-header
1896 * Accepts: MAIL stream
1897 * buffer to write pseudo-header
1898 * Returns: length of pseudo-header
1901 unsigned long unix_pseudo (MAILSTREAM *stream,char *hdr)
1903 int i;
1904 char *s,*t,tmp[MAILTMPLEN];
1905 time_t now = time(0);
1906 rfc822_fixed_date (tmp);
1907 sprintf (hdr,"From %s %.24s\r\nDate: %s\r\nFrom: %s <%s@%.80s>\r\nSubject: %s\r\nMessage-ID: <%lu@%.80s>\r\nX-IMAP: %010ld %010ld",
1908 pseudo_from,ctime (&now),
1909 tmp,pseudo_name,pseudo_from,mylocalhost (),pseudo_subject,
1910 (unsigned long) now,mylocalhost (),stream->uid_validity,
1911 stream->uid_last);
1912 for (t = hdr + strlen (hdr),i = 0; i < NUSERFLAGS; ++i)
1913 if (stream->user_flags[i])
1914 sprintf (t += strlen (t)," %s",stream->user_flags[i]);
1915 strcpy (t += strlen (t),"\r\nStatus: RO\r\n\r\n");
1916 for (s = pseudo_msg,t += strlen (t); *s; *t++ = *s++)
1917 if (*s == '\n') *t++ = '\r';
1918 *t++ = '\r'; *t++ = '\n'; *t++ = '\r'; *t++ = '\n';
1919 *t = '\0'; /* tie off pseudo header */
1920 return t - hdr; /* return length of pseudo header */
1923 /* UNIX make status string
1924 * Accepts: MAIL stream
1925 * destination string to write
1926 * message cache entry
1927 * UID to write if non-zero (else use elt->private.uid)
1928 * non-zero flag to write UID (.LT. 0 to write UID base info too)
1929 * Returns: length of string
1932 unsigned long unix_xstatus (MAILSTREAM *stream,char *status,MESSAGECACHE *elt,
1933 unsigned long uid,long flag)
1935 char *t,stack[64];
1936 char *s = status;
1937 unsigned long n;
1938 unsigned long pad = 50;
1939 /* This used to use sprintf(), but thanks to certain cretinous C libraries
1940 with horribly slow implementations of sprintf() I had to change it to this
1941 mess. At least it should be fast. */
1942 *s++ = 'S'; *s++ = 't'; *s++ = 'a'; *s++ = 't'; *s++ = 'u'; *s++ = 's';
1943 *s++ = ':'; *s++ = ' ';
1944 if (elt->seen) *s++ = 'R';
1945 /* only write O if have a UID */
1946 if (flag && (!elt->recent || LOCAL->appending)) *s++ = 'O';
1947 *s++ = '\r'; *s++ = '\n';
1948 *s++ = 'X'; *s++ = '-'; *s++ = 'S'; *s++ = 't'; *s++ = 'a'; *s++ = 't';
1949 *s++ = 'u'; *s++ = 's'; *s++ = ':'; *s++ = ' ';
1950 if (elt->deleted) *s++ = 'D';
1951 if (elt->flagged) *s++ = 'F';
1952 if (elt->answered) *s++ = 'A';
1953 if (elt->draft) *s++ = 'T';
1954 *s++ = '\r'; *s++ = '\n';
1956 *s++ = 'X'; *s++ = '-'; *s++ = 'K'; *s++ = 'e'; *s++ = 'y'; *s++ = 'w';
1957 *s++ = 'o'; *s++ = 'r'; *s++ = 'd'; *s++ = 's'; *s++ = ':';
1958 if (n = elt->user_flags) do {
1959 *s++ = ' ';
1960 for (t = stream->user_flags[find_rightmost_bit (&n)]; *t; *s++ = *t++);
1961 } while (n);
1962 n = s - status; /* get size of stuff so far */
1963 /* pad X-Keywords to make size constant */
1964 if (n < pad) for (n = pad - n; n > 0; --n) *s++ = ' ';
1965 *s++ = '\r'; *s++ = '\n';
1966 if (flag) { /* want to include UID? */
1967 t = stack;
1968 /* push UID digits on the stack */
1969 n = uid ? uid : elt->private.uid;
1970 do *t++ = (char) (n % 10) + '0';
1971 while (n /= 10);
1972 *s++ = 'X'; *s++ = '-'; *s++ = 'U'; *s++ = 'I'; *s++ = 'D'; *s++ = ':';
1973 *s++ = ' ';
1974 /* pop UID from stack */
1975 while (t > stack) *s++ = *--t;
1976 *s++ = '\r'; *s++ = '\n';
1978 /* end of extended message status */
1979 *s++ = '\r'; *s++ = '\n'; *s = '\0';
1980 return s - status; /* return size of resulting string */
1983 /* Rewrite mailbox file
1984 * Accepts: MAIL stream, must be critical and locked
1985 * return pointer to number of expunged messages if want expunge
1986 * lock file name
1987 * expunge sequence, not deleted flag
1988 * Returns: T if success and mailbox unlocked, NIL if failure
1991 #define OVERFLOWBUFLEN 8192 /* initial overflow buffer length */
1993 long unix_rewrite (MAILSTREAM *stream,unsigned long *nexp,char *lock,
1994 long flags)
1996 MESSAGECACHE *elt;
1997 UNIXFILE f;
1998 char *s;
1999 struct utimbuf times;
2000 long ret,flag;
2001 unsigned long i,j;
2002 unsigned long recent = stream->recent;
2003 unsigned long size = LOCAL->pseudo ? unix_pseudo (stream,LOCAL->buf) : 0;
2004 if (nexp) *nexp = 0; /* initially nothing expunged */
2005 /* calculate size of mailbox after rewrite */
2006 for (i = 1,flag = LOCAL->pseudo ? 1 : -1; i <= stream->nmsgs; i++) {
2007 elt = mail_elt (stream,i); /* get cache */
2008 if (!(nexp && elt->deleted && (flags ? elt->sequence : T))) {
2009 /* add RFC822 size of this message */
2010 size += elt->private.special.text.size + elt->private.spare.data +
2011 unix_xstatus (stream,LOCAL->buf,elt,NIL,flag) +
2012 elt->private.msg.text.text.size + 2;
2013 flag = 1; /* only count X-IMAPbase once */
2016 if (!size) { /* no messages and no pseudo, make one now */
2017 size = unix_pseudo (stream,LOCAL->buf);
2018 LOCAL->pseudo = T;
2020 /* extend the file as necessary */
2021 if (ret = unix_extend (stream,size)) {
2022 /* Set up buffered I/O file structure
2023 * curpos current position being written through buffering
2024 * filepos current position being written physically to the disk
2025 * bufpos current position being written in the buffer
2026 * protect current maximum position that can be written to the disk
2027 * before buffering is forced
2028 * The code tries to buffer so that that disk is written in multiples of
2029 * OVERBLOWBUFLEN bytes.
2031 f.stream = stream; /* note mail stream */
2032 f.curpos = f.filepos = 0; /* start of file */
2033 f.protect = stream->nmsgs ? /* initial protection pointer */
2034 mail_elt (stream,1)->private.special.offset : 8192;
2035 f.bufpos = f.buf = (char *) fs_get (f.buflen = OVERFLOWBUFLEN);
2037 if (LOCAL->pseudo) /* update pseudo-header */
2038 unix_write (&f,LOCAL->buf,unix_pseudo (stream,LOCAL->buf));
2039 /* loop through all messages */
2040 for (i = 1,flag = LOCAL->pseudo ? 1 : -1; i <= stream->nmsgs;) {
2041 elt = mail_elt (stream,i);/* get cache */
2042 /* expunge this message? */
2043 if (nexp && elt->deleted && (flags ? elt->sequence : T)) {
2044 /* one less recent message */
2045 if (elt->recent) --recent;
2046 mail_expunged(stream,i);/* notify upper levels */
2047 ++*nexp; /* count up one more expunged message */
2049 else { /* preserve this message */
2050 i++; /* advance to next message */
2051 if ((flag < 0) || /* need to rewrite message? */
2052 elt->private.dirty ||
2053 (((unsigned long) f.curpos) != elt->private.special.offset) ||
2054 (elt->private.msg.header.text.size !=
2055 (elt->private.spare.data +
2056 unix_xstatus (stream,LOCAL->buf,elt,NIL,flag)))) {
2057 unsigned long newoffset = f.curpos;
2058 /* yes, seek to internal header */
2059 lseek (LOCAL->fd,elt->private.special.offset,L_SET);
2060 read (LOCAL->fd,LOCAL->buf,elt->private.special.text.size);
2061 /* protection pointer moves to RFC822 header */
2062 f.protect = elt->private.special.offset +
2063 elt->private.msg.header.offset;
2064 /* write internal header */
2065 unix_write (&f,LOCAL->buf,elt->private.special.text.size);
2066 /* get RFC822 header */
2067 s = unix_header (stream,elt->msgno,&j,NIL);
2068 /* in case this got decremented */
2069 elt->private.msg.header.offset = elt->private.special.text.size;
2070 /* header size, sans trailing newline */
2071 if ((j < 4) || (s[j - 4] == '\r')) j -= 2;
2072 if (j != elt->private.spare.data) fatal ("header size inconsistent");
2073 /* protection pointer moves to RFC822 text */
2074 f.protect = elt->private.special.offset +
2075 elt->private.msg.text.offset;
2076 unix_write (&f,s,j); /* write RFC822 header */
2077 /* write status and UID */
2078 unix_write (&f,LOCAL->buf,
2079 j = unix_xstatus (stream,LOCAL->buf,elt,NIL,flag));
2080 flag = 1; /* only write X-IMAPbase once */
2081 /* new file header size */
2082 elt->private.msg.header.text.size = elt->private.spare.data + j;
2084 /* did text move? */
2085 if (f.curpos != f.protect) {
2086 /* get message text */
2087 s = unix_text_work (stream,elt,&j,FT_INTERNAL);
2088 /* can't happen it says here */
2089 if (j > elt->private.msg.text.text.size)
2090 fatal ("text size inconsistent");
2091 /* new text offset, status/UID may change it */
2092 elt->private.msg.text.offset = f.curpos - newoffset;
2093 /* protection pointer moves to next message */
2094 f.protect = (i <= stream->nmsgs) ?
2095 mail_elt (stream,i)->private.special.offset : (f.curpos + j + 2);
2096 unix_write (&f,s,j);/* write text */
2097 /* write trailing newline */
2098 unix_write (&f,"\r\n",2);
2100 else { /* tie off header and status */
2101 unix_write (&f,NIL,NIL);
2102 /* protection pointer moves to next message */
2103 f.protect = (i <= stream->nmsgs) ?
2104 mail_elt (stream,i)->private.special.offset : size;
2105 /* locate end of message text */
2106 j = f.filepos + elt->private.msg.text.text.size;
2107 /* trailing newline already there? */
2108 if (f.protect == (off_t) (j + 2)) f.curpos = f.filepos = f.protect;
2109 else { /* trailing newline missing, write it */
2110 f.curpos = f.filepos = j;
2111 unix_write (&f,"\r\n",2);
2114 /* new internal header offset */
2115 elt->private.special.offset = newoffset;
2116 elt->private.dirty =NIL;/* message is now clean */
2118 else { /* no need to rewrite this message */
2119 /* tie off previous message if needed */
2120 unix_write (&f,NIL,NIL);
2121 /* protection pointer moves to next message */
2122 f.protect = (i <= stream->nmsgs) ?
2123 mail_elt (stream,i)->private.special.offset : size;
2124 /* locate end of message text */
2125 j = f.filepos + elt->private.special.text.size +
2126 elt->private.msg.header.text.size +
2127 elt->private.msg.text.text.size;
2128 /* trailing newline already there? */
2129 if (f.protect == (off_t) (j + 2)) f.curpos = f.filepos = f.protect;
2130 else { /* trailing newline missing, write it */
2131 f.curpos = f.filepos = j;
2132 unix_write (&f,"\r\n",2);
2138 unix_write (&f,NIL,NIL); /* tie off final message */
2139 if (size != ((unsigned long) f.filepos)) fatal ("file size inconsistent");
2140 fs_give ((void **) &f.buf); /* free buffer */
2141 /* make sure tied off */
2142 ftruncate (LOCAL->fd,LOCAL->filesize = size);
2143 fsync (LOCAL->fd); /* make sure the updates take */
2144 if (size && (flag < 0)) fatal ("lost UID base information");
2145 /* no longer dirty */
2146 LOCAL->ddirty = LOCAL->dirty = NIL;
2147 /* notify upper level of new mailbox sizes */
2148 mail_exists (stream,stream->nmsgs);
2149 mail_recent (stream,recent);
2150 /* set atime to now, mtime a second earlier */
2151 times.modtime = (times.actime = time (0)) -1;
2152 /* set the times, note change */
2153 if (!utime (stream->mailbox,&times)) LOCAL->filetime = times.modtime;
2154 /* flush the lock file */
2155 unix_unlock (LOCAL->fd,stream,lock);
2157 return ret; /* return state from algorithm */
2160 /* Extend UNIX mailbox file
2161 * Accepts: MAIL stream
2162 * new desired size
2163 * Return: T if success, else NIL
2166 long unix_extend (MAILSTREAM *stream,unsigned long size)
2168 unsigned long i = (size > ((unsigned long) LOCAL->filesize)) ?
2169 size - ((unsigned long) LOCAL->filesize) : 0;
2170 if (i) { /* does the mailbox need to grow? */
2171 if (i > LOCAL->buflen) { /* make sure have enough space */
2172 /* this user won the lottery all right */
2173 fs_give ((void **) &LOCAL->buf);
2174 LOCAL->buf = (char *) fs_get ((LOCAL->buflen = i) + 1);
2176 memset (LOCAL->buf,'\0',i); /* get a block of nulls */
2177 while (T) { /* until write successful or punt */
2178 lseek (LOCAL->fd,LOCAL->filesize,L_SET);
2179 if ((write (LOCAL->fd,LOCAL->buf,i) >= 0) && !fsync (LOCAL->fd)) break;
2180 else {
2181 long e = errno; /* note error before doing ftruncate */
2182 ftruncate (LOCAL->fd,LOCAL->filesize);
2183 if (mm_diskerror (stream,e,NIL)) {
2184 fsync (LOCAL->fd); /* user chose to punt */
2185 sprintf (LOCAL->buf,"Unable to extend mailbox: %s",strerror (e));
2186 if (!stream->silent) mm_log (LOCAL->buf,ERROR);
2187 return NIL;
2192 return LONGT;
2195 /* Write data to buffered file
2196 * Accepts: buffered file pointer
2197 * file data or NIL to indicate "flush buffer"
2198 * date size (ignored for "flush buffer")
2199 * Does not return until success
2202 void unix_write (UNIXFILE *f,char *buf,unsigned long size)
2204 unsigned long i,j,k;
2205 if (buf) { /* doing buffered write? */
2206 i = f->bufpos - f->buf; /* yes, get size of current buffer data */
2207 /* yes, have space in current buffer chunk? */
2208 if (j = i ? ((f->buflen - i) % OVERFLOWBUFLEN) : f->buflen) {
2209 /* yes, fill up buffer as much as we can */
2210 memcpy (f->bufpos,buf,k = min (j,size));
2211 f->bufpos += k; /* new buffer position */
2212 f->curpos += k; /* new current position */
2213 if (j -= k) return; /* all done if still have buffer free space */
2214 buf += k; /* full, get new unwritten data pointer */
2215 size -= k; /* new data size */
2216 i += k; /* new buffer data size */
2218 /* This chunk of the buffer is full. See if can make some space by
2219 * writing to the disk, if there's enough unprotected space to do so.
2220 * Try to fill out any unaligned chunk, along with any subsequent full
2221 * chunks that will fit in unprotected space.
2223 /* any unprotected space we can write to? */
2224 if (j = min (i,f->protect - f->filepos)) {
2225 /* yes, filepos not at chunk boundary? */
2226 if ((k = f->filepos % OVERFLOWBUFLEN) && ((k = OVERFLOWBUFLEN - k) < j))
2227 j -= k; /* yes, and can write out partial chunk */
2228 else k = 0; /* no partial chunk to write */
2229 /* if at least a chunk free, write that too */
2230 if (j > OVERFLOWBUFLEN) k += j - (j % OVERFLOWBUFLEN);
2231 if (k) { /* write data if there is anything we can */
2232 unix_phys_write (f,f->buf,k);
2233 /* slide buffer */
2234 if (i -= k) memmove (f->buf,f->buf + k,i);
2235 f->bufpos = f->buf + i; /* new end of buffer */
2239 /* Have flushed the buffer as best as possible. All done if no more
2240 * data to write. Otherwise, if the buffer is empty AND if the unwritten
2241 * data is larger than a chunk AND the unprotected space is also larger
2242 * than a chunk, then write as many chunks as we can directly from the
2243 * data. Buffer the rest, expanding the buffer as needed.
2245 if (size) { /* have more data that we need to buffer? */
2246 /* can write any of it to disk instead? */
2247 if ((f->bufpos == f->buf) &&
2248 ((j = min (f->protect - f->filepos,size)) > OVERFLOWBUFLEN)) {
2249 /* write as much as we can right now */
2250 unix_phys_write (f,buf,j -= (j % OVERFLOWBUFLEN));
2251 buf += j; /* new data pointer */
2252 size -= j; /* new data size */
2253 f->curpos += j; /* advance current pointer */
2255 if (size) { /* still have data that we need to buffer? */
2256 /* yes, need to expand the buffer? */
2257 if ((i = ((f->bufpos + size) - f->buf)) > f->buflen) {
2258 /* note current position in buffer */
2259 j = f->bufpos - f->buf;
2260 i += OVERFLOWBUFLEN; /* yes, grow another chunk */
2261 fs_resize ((void **) &f->buf,f->buflen = i - (i % OVERFLOWBUFLEN));
2262 /* in case buffer relocated */
2263 f->bufpos = f->buf + j;
2265 /* buffer remaining data */
2266 memcpy (f->bufpos,buf,size);
2267 f->bufpos += size; /* new end of buffer */
2268 f->curpos += size; /* advance current pointer */
2272 else { /* flush buffer to disk */
2273 unix_phys_write (f,f->buf,i = f->bufpos - f->buf);
2274 f->bufpos = f->buf; /* reset buffer */
2275 /* update positions */
2276 f->curpos = f->protect = f->filepos;
2280 /* Physical disk write
2281 * Accepts: buffered file pointer
2282 * buffer address
2283 * buffer size
2284 * Does not return until success
2287 void unix_phys_write (UNIXFILE *f,char *buf,size_t size)
2289 MAILSTREAM *stream = f->stream;
2290 /* write data at desired position */
2291 while (size && ((lseek (LOCAL->fd,f->filepos,L_SET) < 0) ||
2292 (write (LOCAL->fd,buf,size) < 0))) {
2293 int e;
2294 char tmp[MAILTMPLEN];
2295 sprintf (tmp,"Unable to write to mailbox: %s",strerror (e = errno));
2296 mm_log (tmp,ERROR);
2297 mm_diskerror (NIL,e,T); /* serious problem, must retry */
2299 f->filepos += size; /* update file position */