* Clean up some function definitions to comply with strict
[alpine.git] / imap / src / osdep / amiga / unix.c
blobe553662fa437d1d48e5aa1edc10ac07a14db6ad2
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@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 <signal.h>
47 #include "mail.h"
48 #include "osdep.h"
49 #include <time.h>
50 #include <sys/stat.h>
51 #include "unix.h"
52 #include "pseudo.h"
53 #include "fdstring.h"
54 #include "misc.h"
55 #include "dummy.h"
57 /* UNIX I/O stream local data */
59 typedef struct unix_local {
60 unsigned int dirty : 1; /* disk copy needs updating */
61 unsigned int ddirty : 1; /* double-dirty, ping becomes checkpoint */
62 unsigned int pseudo : 1; /* uses a pseudo message */
63 unsigned int appending : 1; /* don't mark new messages as old */
64 int fd; /* mailbox file descriptor */
65 int ld; /* lock file descriptor */
66 char *lname; /* lock file name */
67 off_t filesize; /* file size parsed */
68 time_t filetime; /* last file time */
69 time_t lastsnarf; /* last snarf time (for mbox driver) */
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 long unix_isvalid_fd (int fd);
102 void *unix_parameters (long function,void *value);
103 void unix_scan (MAILSTREAM *stream,char *ref,char *pat,char *contents);
104 void unix_list (MAILSTREAM *stream,char *ref,char *pat);
105 void unix_lsub (MAILSTREAM *stream,char *ref,char *pat);
106 long unix_create (MAILSTREAM *stream,char *mailbox);
107 long unix_delete (MAILSTREAM *stream,char *mailbox);
108 long unix_rename (MAILSTREAM *stream,char *old,char *newname);
109 MAILSTREAM *unix_open (MAILSTREAM *stream);
110 void unix_close (MAILSTREAM *stream,long options);
111 char *unix_header (MAILSTREAM *stream,unsigned long msgno,
112 unsigned long *length,long flags);
113 long unix_text (MAILSTREAM *stream,unsigned long msgno,STRING *bs,long flags);
114 char *unix_text_work (MAILSTREAM *stream,MESSAGECACHE *elt,
115 unsigned long *length,long flags);
116 void unix_flagmsg (MAILSTREAM *stream,MESSAGECACHE *elt);
117 long unix_ping (MAILSTREAM *stream);
118 void unix_check (MAILSTREAM *stream);
119 long unix_expunge (MAILSTREAM *stream,char *sequence,long options);
120 long unix_copy (MAILSTREAM *stream,char *sequence,char *mailbox,long options);
121 long unix_append (MAILSTREAM *stream,char *mailbox,append_t af,void *data);
122 int unix_collect_msg (MAILSTREAM *stream,FILE *sf,char *flags,char *date,
123 STRING *msg);
124 int unix_append_msgs (MAILSTREAM *stream,FILE *sf,FILE *df,SEARCHSET *set);
126 void unix_abort (MAILSTREAM *stream);
127 char *unix_file (char *dst,char *name);
128 int unix_lock (char *file,int flags,int mode,DOTLOCK *lock,int op);
129 void unix_unlock (int fd,MAILSTREAM *stream,DOTLOCK *lock);
130 int unix_parse (MAILSTREAM *stream,DOTLOCK *lock,int op);
131 char *unix_mbxline (MAILSTREAM *stream,STRING *bs,unsigned long *size);
132 unsigned long unix_pseudo (MAILSTREAM *stream,char *hdr);
133 unsigned long unix_xstatus (MAILSTREAM *stream,char *status,MESSAGECACHE *elt,
134 unsigned long uid,long flag);
135 long unix_rewrite (MAILSTREAM *stream,unsigned long *nexp,DOTLOCK *lock,
136 long flags);
137 long unix_extend (MAILSTREAM *stream,unsigned long size);
138 void unix_write (UNIXFILE *f,char *s,unsigned long i);
139 void unix_phys_write (UNIXFILE *f,char *buf,size_t size);
141 /* mbox mail routines */
143 /* Function prototypes */
145 DRIVER *mbox_valid (char *name);
146 long mbox_create (MAILSTREAM *stream,char *mailbox);
147 long mbox_delete (MAILSTREAM *stream,char *mailbox);
148 long mbox_rename (MAILSTREAM *stream,char *old,char *newname);
149 long mbox_status (MAILSTREAM *stream,char *mbx,long flags);
150 MAILSTREAM *mbox_open (MAILSTREAM *stream);
151 long mbox_ping (MAILSTREAM *stream);
152 void mbox_check (MAILSTREAM *stream);
153 long mbox_expunge (MAILSTREAM *stream,char *sequence,long options);
154 long mbox_append (MAILSTREAM *stream,char *mailbox,append_t af,void *data);
157 /* UNIX mail routines */
160 /* Driver dispatch used by MAIL */
162 DRIVER unixdriver = {
163 "unix", /* driver name */
164 /* driver flags */
165 DR_LOCAL|DR_MAIL|DR_LOCKING|DR_NONEWMAILRONLY|DR_XPOINT,
166 (DRIVER *) NIL, /* next driver */
167 unix_valid, /* mailbox is valid for us */
168 unix_parameters, /* manipulate parameters */
169 unix_scan, /* scan mailboxes */
170 unix_list, /* list mailboxes */
171 unix_lsub, /* list subscribed mailboxes */
172 NIL, /* subscribe to mailbox */
173 NIL, /* unsubscribe from mailbox */
174 unix_create, /* create mailbox */
175 unix_delete, /* delete mailbox */
176 unix_rename, /* rename mailbox */
177 mail_status_default, /* status of mailbox */
178 unix_open, /* open mailbox */
179 unix_close, /* close mailbox */
180 NIL, /* fetch message "fast" attributes */
181 NIL, /* fetch message flags */
182 NIL, /* fetch overview */
183 NIL, /* fetch message envelopes */
184 unix_header, /* fetch message header */
185 unix_text, /* fetch message text */
186 NIL, /* fetch partial message text */
187 NIL, /* unique identifier */
188 NIL, /* message number */
189 NIL, /* modify flags */
190 unix_flagmsg, /* per-message modify flags */
191 NIL, /* search for message based on criteria */
192 NIL, /* sort messages */
193 NIL, /* thread messages */
194 unix_ping, /* ping mailbox to see if still alive */
195 unix_check, /* check for new messages */
196 unix_expunge, /* expunge deleted messages */
197 unix_copy, /* copy messages to another mailbox */
198 unix_append, /* append string message to mailbox */
199 NIL /* garbage collect stream */
202 /* prototype stream */
203 MAILSTREAM unixproto = {&unixdriver};
205 /* driver parameters */
206 static long unix_fromwidget = T;
208 /* UNIX mail validate mailbox
209 * Accepts: mailbox name
210 * Returns: our driver if name is valid, NIL otherwise
213 DRIVER *unix_valid (char *name)
215 int fd;
216 DRIVER *ret = NIL;
217 char *t,file[MAILTMPLEN];
218 struct stat sbuf;
219 time_t tp[2];
220 errno = EINVAL; /* assume invalid argument */
221 /* must be non-empty file */
222 if ((t = dummy_file (file,name)) && !stat (t,&sbuf)) {
223 if (!sbuf.st_size)errno = 0;/* empty file */
224 else if ((fd = open (file,O_RDONLY,NIL)) >= 0) {
225 /* OK if mailbox format good */
226 if (unix_isvalid_fd (fd)) ret = &unixdriver;
227 else errno = -1; /* invalid format */
228 close (fd); /* close the file */
229 /* \Marked status? */
230 if ((sbuf.st_ctime > sbuf.st_atime) || (sbuf.st_mtime > sbuf.st_atime)) {
231 tp[0] = sbuf.st_atime; /* yes, preserve atime and mtime */
232 tp[1] = sbuf.st_mtime;
233 utime (file,tp); /* set the times */
237 return ret; /* return what we should */
240 /* UNIX mail test for valid mailbox
241 * Accepts: file descriptor
242 * scratch buffer
243 * Returns: T if valid, NIL otherwise
246 long unix_isvalid_fd (int fd)
248 int zn;
249 int ret = NIL;
250 char tmp[MAILTMPLEN],*s,*t,c = '\n';
251 memset (tmp,'\0',MAILTMPLEN);
252 if (read (fd,tmp,MAILTMPLEN-1) >= 0) {
253 for (s = tmp; (*s == '\r') || (*s == '\n') || (*s == ' ') || (*s == '\t');)
254 c = *s++;
255 if (c == '\n') VALID (s,t,ret,zn);
257 return ret; /* return what we should */
261 /* UNIX manipulate driver parameters
262 * Accepts: function code
263 * function-dependent value
264 * Returns: function-dependent return value
267 void *unix_parameters (long function,void *value)
269 void *ret = NIL;
270 switch ((int) function) {
271 case GET_INBOXPATH:
272 if (value) ret = dummy_file ((char *) value,"INBOX");
273 break;
274 case SET_FROMWIDGET:
275 unix_fromwidget = (long) value;
276 case GET_FROMWIDGET:
277 ret = (void *) unix_fromwidget;
278 break;
280 return ret;
283 /* UNIX mail scan mailboxes
284 * Accepts: mail stream
285 * reference
286 * pattern to search
287 * string to scan
290 void unix_scan (MAILSTREAM *stream,char *ref,char *pat,char *contents)
292 if (stream) dummy_scan (NIL,ref,pat,contents);
296 /* UNIX mail list mailboxes
297 * Accepts: mail stream
298 * reference
299 * pattern to search
302 void unix_list (MAILSTREAM *stream,char *ref,char *pat)
304 if (stream) dummy_list (NIL,ref,pat);
308 /* UNIX mail list subscribed mailboxes
309 * Accepts: mail stream
310 * reference
311 * pattern to search
314 void unix_lsub (MAILSTREAM *stream,char *ref,char *pat)
316 if (stream) dummy_lsub (NIL,ref,pat);
319 /* UNIX mail create mailbox
320 * Accepts: MAIL stream
321 * mailbox name to create
322 * Returns: T on success, NIL on failure
325 long unix_create (MAILSTREAM *stream,char *mailbox)
327 char *s,mbx[MAILTMPLEN],tmp[MAILTMPLEN];
328 long ret = NIL;
329 int i,fd;
330 time_t ti = time (0);
331 if (!(s = dummy_file (mbx,mailbox))) {
332 sprintf (tmp,"Can't create %.80s: invalid name",mailbox);
333 MM_LOG (tmp,ERROR);
335 /* create underlying file */
336 else if (dummy_create_path (stream,s,get_dir_protection (mailbox))) {
337 /* done if dir-only or whiner */
338 if (((s = strrchr (s,'/')) && !s[1]) ||
339 mail_parameters (NIL,GET_USERHASNOLIFE,NIL)) ret = T;
340 else if ((fd = open (mbx,O_WRONLY,
341 (long) mail_parameters (NIL,GET_MBXPROTECTION,NIL))) < 0) {
342 sprintf (tmp,"Can't reopen mailbox node %.80s: %s",mbx,strerror (errno));
343 MM_LOG (tmp,ERROR);
344 unlink (mbx); /* delete the file */
346 else { /* initialize header */
347 memset (tmp,'\0',MAILTMPLEN);
348 sprintf (tmp,"From %s %sDate: ",pseudo_from,ctime (&ti));
349 rfc822_fixed_date (s = tmp + strlen (tmp));
350 /* write the pseudo-header */
351 sprintf (s += strlen (s),
352 "\nFrom: %s <%s@%s>\nSubject: %s\nX-IMAP: %010lu 0000000000",
353 pseudo_name,pseudo_from,mylocalhost (),pseudo_subject,
354 (unsigned long) ti);
355 for (i = 0; i < NUSERFLAGS; ++i) if (default_user_flag (i))
356 sprintf (s += strlen (s)," %s",default_user_flag (i));
357 sprintf (s += strlen (s),"\nStatus: RO\n\n%s\n\n",pseudo_msg);
358 if (write (fd,tmp,strlen (tmp)) > 0) ret = T;
359 else {
360 sprintf (tmp,"Can't initialize mailbox node %.80s: %s",mbx,
361 strerror (errno));
362 MM_LOG (tmp,ERROR);
363 unlink (mbx); /* delete the file */
365 close (fd); /* close file */
368 /* set proper protections */
369 return ret ? set_mbx_protections (mailbox,mbx) : NIL;
372 /* UNIX mail delete mailbox
373 * Accepts: MAIL stream
374 * mailbox name to delete
375 * Returns: T on success, NIL on failure
378 long unix_delete (MAILSTREAM *stream,char *mailbox)
380 return unix_rename (stream,mailbox,NIL);
384 /* UNIX mail rename mailbox
385 * Accepts: MAIL stream
386 * old mailbox name
387 * new mailbox name (or NIL for delete)
388 * Returns: T on success, NIL on failure
391 long unix_rename (MAILSTREAM *stream,char *old,char *newname)
393 long ret = NIL;
394 char c,*s = NIL;
395 char tmp[MAILTMPLEN],file[MAILTMPLEN],lock[MAILTMPLEN];
396 DOTLOCK lockx;
397 int fd,ld;
398 long i;
399 struct stat sbuf;
400 MM_CRITICAL (stream); /* get the c-client lock */
401 if (!dummy_file (file,old) ||
402 (newname && (!((s = mailboxfile (tmp,newname)) && *s) ||
403 ((s = strrchr (tmp,'/')) && !s[1]))))
404 sprintf (tmp,newname ?
405 "Can't rename mailbox %.80s to %.80s: invalid name" :
406 "Can't delete mailbox %.80s: invalid name",
407 old,newname);
408 /* lock out other c-clients */
409 else if ((ld = lockname (lock,file,LOCK_EX|LOCK_NB,&i)) < 0)
410 sprintf (tmp,"Mailbox %.80s is in use by another process",old);
412 else {
413 if ((fd = unix_lock (file,O_RDWR,
414 (long) mail_parameters (NIL,GET_MBXPROTECTION,NIL),
415 &lockx,LOCK_EX)) < 0)
416 sprintf (tmp,"Can't lock mailbox %.80s: %s",old,strerror (errno));
417 else {
418 if (newname) { /* want rename? */
419 /* found superior to destination name? */
420 if (s = strrchr (s,'/')) {
421 c = *++s; /* remember first character of inferior */
422 *s = '\0'; /* tie off to get just superior */
423 /* name doesn't exist, create it */
424 if ((stat (tmp,&sbuf) || ((sbuf.st_mode & S_IFMT) != S_IFDIR)) &&
425 !dummy_create_path (stream,tmp,get_dir_protection (newname))) {
426 unix_unlock (fd,NIL,&lockx);
427 unix_unlock (ld,NIL,NIL);
428 unlink (lock);
429 MM_NOCRITICAL (stream);
430 return ret; /* return success or failure */
432 *s = c; /* restore full name */
434 if (rename (file,tmp))
435 sprintf (tmp,"Can't rename mailbox %.80s to %.80s: %s",old,newname,
436 strerror (errno));
437 else ret = T; /* set success */
439 else if (unlink (file))
440 sprintf (tmp,"Can't delete mailbox %.80s: %s",old,strerror (errno));
441 else ret = T; /* set success */
442 unix_unlock (fd,NIL,&lockx);
444 unix_unlock (ld,NIL,NIL); /* flush the lock */
445 unlink (lock);
447 MM_NOCRITICAL (stream); /* no longer critical */
448 if (!ret) MM_LOG (tmp,ERROR); /* log error */
449 return ret; /* return success or failure */
452 /* UNIX mail open
453 * Accepts: Stream to open
454 * Returns: Stream on success, NIL on failure
457 MAILSTREAM *unix_open (MAILSTREAM *stream)
459 long i;
460 int fd;
461 char tmp[MAILTMPLEN];
462 DOTLOCK lock;
463 long retry;
464 /* return prototype for OP_PROTOTYPE call */
465 if (!stream) return user_flags (&unixproto);
466 retry = stream->silent ? 1 : KODRETRY;
467 if (stream->local) fatal ("unix recycle stream");
468 stream->local = memset (fs_get (sizeof (UNIXLOCAL)),0,sizeof (UNIXLOCAL));
469 /* note if an INBOX or not */
470 stream->inbox = !compare_cstring (stream->mailbox,"INBOX");
471 /* canonicalize the stream mailbox name */
472 if (!dummy_file (tmp,stream->mailbox)) {
473 sprintf (tmp,"Can't open - invalid name: %.80s",stream->mailbox);
474 MM_LOG (tmp,ERROR);
475 return NIL;
477 /* flush old name */
478 fs_give ((void **) &stream->mailbox);
479 /* save canonical name */
480 stream->mailbox = cpystr (tmp);
481 LOCAL->fd = LOCAL->ld = -1; /* no file or state locking yet */
482 LOCAL->buf = (char *) fs_get (CHUNKSIZE);
483 LOCAL->buflen = CHUNKSIZE - 1;
484 LOCAL->text.data = (unsigned char *) fs_get (CHUNKSIZE);
485 LOCAL->text.size = CHUNKSIZE - 1;
486 LOCAL->linebuf = (char *) fs_get (CHUNKSIZE);
487 LOCAL->linebuflen = CHUNKSIZE - 1;
488 stream->sequence++; /* bump sequence number */
490 /* make lock for read/write access */
491 if (!stream->rdonly) while (retry) {
492 /* try to lock file */
493 if ((fd = lockname (tmp,stream->mailbox,LOCK_EX|LOCK_NB,&i)) < 0) {
494 /* suppressing kiss-of-death? */
495 if (stream->nokod) retry = 0;
496 /* no, first time through? */
497 else if (retry-- == KODRETRY) {
498 /* learned other guy's PID and can signal? */
499 if (i && !kill ((int) i,SIGUSR2)) {
500 sprintf (tmp,"Trying to get mailbox lock from process %ld",i);
501 MM_LOG (tmp,WARN);
503 else retry = 0; /* give up */
505 if (!stream->silent) { /* nothing if silent stream */
506 if (retry) sleep (1); /* wait a second before trying again */
507 else MM_LOG ("Mailbox is open by another process, access is readonly",
508 WARN);
511 else { /* got the lock, nobody else can alter state */
512 LOCAL->ld = fd; /* note lock's fd and name */
513 LOCAL->lname = cpystr (tmp);
514 /* make sure mode OK (don't use fchmod()) */
515 chmod (LOCAL->lname,(long) mail_parameters (NIL,GET_LOCKPROTECTION,NIL));
516 if (stream->silent) i = 0;/* silent streams won't accept KOD */
517 else { /* note our PID in the lock */
518 sprintf (tmp,"%d",getpid ());
519 write (fd,tmp,(i = strlen (tmp))+1);
521 ftruncate (fd,i); /* make sure tied off */
522 fsync (fd); /* make sure it's available */
523 retry = 0; /* no more need to try */
527 /* parse mailbox */
528 stream->nmsgs = stream->recent = 0;
529 /* will we be able to get write access? */
530 if ((LOCAL->ld >= 0) && access (stream->mailbox,W_OK) && (errno == EACCES)) {
531 MM_LOG ("Can't get write access to mailbox, access is readonly",WARN);
532 flock (LOCAL->ld,LOCK_UN); /* release the lock */
533 close (LOCAL->ld); /* close the lock file */
534 LOCAL->ld = -1; /* no more lock fd */
535 unlink (LOCAL->lname); /* delete it */
537 /* reset UID validity */
538 stream->uid_validity = stream->uid_last = 0;
539 if (stream->silent && !stream->rdonly && (LOCAL->ld < 0))
540 unix_abort (stream); /* abort if can't get RW silent stream */
541 /* parse mailbox */
542 else if (unix_parse (stream,&lock,LOCK_SH)) {
543 unix_unlock (LOCAL->fd,stream,&lock);
544 mail_unlock (stream);
545 MM_NOCRITICAL (stream); /* done with critical */
547 if (!LOCAL) return NIL; /* failure if stream died */
548 /* make sure upper level knows readonly */
549 stream->rdonly = (LOCAL->ld < 0);
550 /* notify about empty mailbox */
551 if (!(stream->nmsgs || stream->silent)) MM_LOG ("Mailbox is empty",NIL);
552 if (!stream->rdonly) { /* flags stick if readwrite */
553 stream->perm_seen = stream->perm_deleted =
554 stream->perm_flagged = stream->perm_answered = stream->perm_draft = T;
555 if (!stream->uid_nosticky) {/* users with lives get permanent keywords */
556 stream->perm_user_flags = 0xffffffff;
557 /* and maybe can create them too! */
558 stream->kwd_create = stream->user_flags[NUSERFLAGS-1] ? NIL : T;
561 return stream; /* return stream alive to caller */
565 /* UNIX mail close
566 * Accepts: MAIL stream
567 * close options
570 void unix_close (MAILSTREAM *stream,long options)
572 int silent = stream->silent;
573 stream->silent = T; /* go silent */
574 /* expunge if requested */
575 if (options & CL_EXPUNGE) unix_expunge (stream,NIL,NIL);
576 /* else dump final checkpoint */
577 else if (LOCAL->dirty) unix_check (stream);
578 stream->silent = silent; /* restore old silence state */
579 unix_abort (stream); /* now punt the file and local data */
582 /* UNIX mail fetch message header
583 * Accepts: MAIL stream
584 * message # to fetch
585 * pointer to returned header text length
586 * option flags
587 * Returns: message header in RFC822 format
590 /* lines to filter from header */
591 static STRINGLIST *unix_hlines = NIL;
593 char *unix_header (MAILSTREAM *stream,unsigned long msgno,
594 unsigned long *length,long flags)
596 MESSAGECACHE *elt;
597 unsigned char *s,*t,*tl;
598 *length = 0; /* default to empty */
599 if (flags & FT_UID) return "";/* UID call "impossible" */
600 elt = mail_elt (stream,msgno);/* get cache */
601 if (!unix_hlines) { /* once only code */
602 STRINGLIST *lines = unix_hlines = mail_newstringlist ();
603 lines->text.size = strlen ((char *) (lines->text.data =
604 (unsigned char *) "Status"));
605 lines = lines->next = mail_newstringlist ();
606 lines->text.size = strlen ((char *) (lines->text.data =
607 (unsigned char *) "X-Status"));
608 lines = lines->next = mail_newstringlist ();
609 lines->text.size = strlen ((char *) (lines->text.data =
610 (unsigned char *) "X-Keywords"));
611 lines = lines->next = mail_newstringlist ();
612 lines->text.size = strlen ((char *) (lines->text.data =
613 (unsigned char *) "X-UID"));
614 lines = lines->next = mail_newstringlist ();
615 lines->text.size = strlen ((char *) (lines->text.data =
616 (unsigned char *) "X-IMAP"));
617 lines = lines->next = mail_newstringlist ();
618 lines->text.size = strlen ((char *) (lines->text.data =
619 (unsigned char *) "X-IMAPbase"));
621 /* go to header position */
622 lseek (LOCAL->fd,elt->private.special.offset +
623 elt->private.msg.header.offset,L_SET);
625 if (flags & FT_INTERNAL) { /* initial data OK? */
626 if (elt->private.msg.header.text.size > LOCAL->buflen) {
627 fs_give ((void **) &LOCAL->buf);
628 LOCAL->buf = (char *) fs_get ((LOCAL->buflen =
629 elt->private.msg.header.text.size) + 1);
631 /* read message */
632 read (LOCAL->fd,LOCAL->buf,elt->private.msg.header.text.size);
633 /* got text, tie off string */
634 LOCAL->buf[*length = elt->private.msg.header.text.size] = '\0';
635 /* squeeze out CRs (in case from PC) */
636 for (s = t = LOCAL->buf,tl = LOCAL->buf + *length; t < tl; t++)
637 if (*t != '\r') *s++ = *t;
638 *s = '\0';
639 *length = s - LOCAL->buf; /* adjust length */
641 else { /* need to make a CRLF version */
642 read (LOCAL->fd,s = (char *) fs_get (elt->private.msg.header.text.size+1),
643 elt->private.msg.header.text.size);
644 /* tie off string, and convert to CRLF */
645 s[elt->private.msg.header.text.size] = '\0';
646 *length = strcrlfcpy (&LOCAL->buf,&LOCAL->buflen,s,
647 elt->private.msg.header.text.size);
648 fs_give ((void **) &s); /* free readin buffer */
649 /* squeeze out spurious CRs */
650 for (s = t = LOCAL->buf,tl = LOCAL->buf + *length; t < tl; t++)
651 if ((*t != '\r') || (t[1] == '\n')) *s++ = *t;
652 *s = '\0';
653 *length = s - LOCAL->buf; /* adjust length */
655 *length = mail_filter (LOCAL->buf,*length,unix_hlines,FT_NOT);
656 return (char *) LOCAL->buf; /* return processed copy */
659 /* UNIX mail fetch message text
660 * Accepts: MAIL stream
661 * message # to fetch
662 * pointer to returned stringstruct
663 * option flags
664 * Returns: T on success, NIL if failure
667 long unix_text (MAILSTREAM *stream,unsigned long msgno,STRING *bs,long flags)
669 char *s;
670 unsigned long i;
671 MESSAGECACHE *elt;
672 /* UID call "impossible" */
673 if (flags & FT_UID) return NIL;
674 elt = mail_elt (stream,msgno);/* get cache element */
675 /* if message not seen */
676 if (!(flags & FT_PEEK) && !elt->seen) {
677 /* mark message seen and dirty */
678 elt->seen = elt->private.dirty = LOCAL->dirty = T;
679 MM_FLAGS (stream,msgno);
681 s = unix_text_work (stream,elt,&i,flags);
682 INIT (bs,mail_string,s,i); /* set up stringstruct */
683 return T; /* success */
686 /* UNIX mail fetch message text worker routine
687 * Accepts: MAIL stream
688 * message cache element
689 * pointer to returned header text length
690 * option flags
693 char *unix_text_work (MAILSTREAM *stream,MESSAGECACHE *elt,
694 unsigned long *length,long flags)
696 FDDATA d;
697 STRING bs;
698 unsigned char c,*s,*t,*tl,tmp[CHUNKSIZE];
699 /* go to text position */
700 lseek (LOCAL->fd,elt->private.special.offset +
701 elt->private.msg.text.offset,L_SET);
702 if (flags & FT_INTERNAL) { /* initial data OK? */
703 if (elt->private.msg.text.text.size > LOCAL->buflen) {
704 fs_give ((void **) &LOCAL->buf);
705 LOCAL->buf = (char *) fs_get ((LOCAL->buflen =
706 elt->private.msg.text.text.size) + 1);
708 /* read message */
709 read (LOCAL->fd,LOCAL->buf,elt->private.msg.text.text.size);
710 /* got text, tie off string */
711 LOCAL->buf[*length = elt->private.msg.text.text.size] = '\0';
712 /* squeeze out CRs (in case from PC) */
713 for (s = t = LOCAL->buf,tl = LOCAL->buf + *length; t < tl; t++)
714 if (*t != '\r') *s++ = *t;
715 *s = '\0';
716 *length = s - LOCAL->buf; /* adjust length */
717 return (char *) LOCAL->buf;
720 /* have it cached already? */
721 if (elt->private.uid != LOCAL->uid) {
722 /* not cached, cache it now */
723 LOCAL->uid = elt->private.uid;
724 /* is buffer big enough? */
725 if (elt->rfc822_size > LOCAL->text.size) {
726 /* excessively conservative, but the right thing is too hard to do */
727 fs_give ((void **) &LOCAL->text.data);
728 LOCAL->text.data = (unsigned char *)
729 fs_get ((LOCAL->text.size = elt->rfc822_size) + 1);
731 d.fd = LOCAL->fd; /* yes, set up file descriptor */
732 d.pos = elt->private.special.offset + elt->private.msg.text.offset;
733 d.chunk = tmp; /* initial buffer chunk */
734 d.chunksize = CHUNKSIZE; /* file chunk size */
735 INIT (&bs,fd_string,&d,elt->private.msg.text.text.size);
736 for (s = (char *) LOCAL->text.data; SIZE (&bs);) switch (c = SNX (&bs)) {
737 case '\r': /* carriage return seen */
738 break;
739 case '\n':
740 *s++ = '\r'; /* insert a CR */
741 default:
742 *s++ = c; /* copy characters */
744 *s = '\0'; /* tie off buffer */
745 /* calculate length of cached data */
746 LOCAL->textlen = s - LOCAL->text.data;
748 *length = LOCAL->textlen; /* return from cache */
749 return (char *) LOCAL->text.data;
752 /* UNIX per-message modify flag
753 * Accepts: MAIL stream
754 * message cache element
757 void unix_flagmsg (MAILSTREAM *stream,MESSAGECACHE *elt)
759 /* only after finishing */
760 if (elt->valid) elt->private.dirty = LOCAL->dirty = T;
764 /* UNIX mail ping mailbox
765 * Accepts: MAIL stream
766 * Returns: T if stream alive, else NIL
769 long unix_ping (MAILSTREAM *stream)
771 DOTLOCK lock;
772 struct stat sbuf;
773 long reparse;
774 /* big no-op if not readwrite */
775 if (LOCAL && (LOCAL->ld >= 0) && !stream->lock) {
776 if (stream->rdonly) { /* does he want to give up readwrite? */
777 /* checkpoint if we changed something */
778 if (LOCAL->dirty) unix_check (stream);
779 flock (LOCAL->ld,LOCK_UN);/* release readwrite lock */
780 close (LOCAL->ld); /* close the readwrite lock file */
781 LOCAL->ld = -1; /* no more readwrite lock fd */
782 unlink (LOCAL->lname); /* delete the readwrite lock file */
784 else { /* see if need to reparse */
785 if (!(reparse = (long) mail_parameters (NIL,GET_NETFSSTATBUG,NIL))) {
786 /* get current mailbox size */
787 if (LOCAL->fd >= 0) fstat (LOCAL->fd,&sbuf);
788 else if (stat (stream->mailbox,&sbuf)) {
789 sprintf (LOCAL->buf,"Mailbox stat failed, aborted: %s",
790 strerror (errno));
791 MM_LOG (LOCAL->buf,ERROR);
792 unix_abort (stream);
793 return NIL;
795 reparse = (sbuf.st_size != LOCAL->filesize);
797 /* parse if mailbox changed */
798 if ((LOCAL->ddirty || reparse) && unix_parse (stream,&lock,LOCK_EX)) {
799 /* force checkpoint if double-dirty */
800 if (LOCAL->ddirty) unix_rewrite (stream,NIL,&lock,NIL);
801 /* unlock mailbox */
802 else unix_unlock (LOCAL->fd,stream,&lock);
803 mail_unlock (stream); /* and stream */
804 MM_NOCRITICAL (stream); /* done with critical */
808 return LOCAL ? LONGT : NIL; /* return if still alive */
811 /* UNIX mail check mailbox
812 * Accepts: MAIL stream
815 void unix_check (MAILSTREAM *stream)
817 DOTLOCK lock;
818 /* parse and lock mailbox */
819 if (LOCAL && (LOCAL->ld >= 0) && !stream->lock &&
820 unix_parse (stream,&lock,LOCK_EX)) {
821 /* any unsaved changes? */
822 if (LOCAL->dirty && unix_rewrite (stream,NIL,&lock,NIL)) {
823 if (!stream->silent) MM_LOG ("Checkpoint completed",NIL);
825 /* no checkpoint needed, just unlock */
826 else unix_unlock (LOCAL->fd,stream,&lock);
827 mail_unlock (stream); /* unlock the stream */
828 MM_NOCRITICAL (stream); /* done with critical */
833 /* UNIX mail expunge mailbox
834 * Accepts: MAIL stream
835 * sequence to expunge if non-NIL
836 * expunge options
837 * Returns: T, always
840 long unix_expunge (MAILSTREAM *stream,char *sequence,long options)
842 long ret;
843 unsigned long i;
844 DOTLOCK lock;
845 char *msg = NIL;
846 /* parse and lock mailbox */
847 if (ret = (sequence ? ((options & EX_UID) ?
848 mail_uid_sequence (stream,sequence) :
849 mail_sequence (stream,sequence)) : LONGT) &&
850 LOCAL && (LOCAL->ld >= 0) && !stream->lock &&
851 unix_parse (stream,&lock,LOCK_EX)) {
852 /* check expunged messages if not dirty */
853 for (i = 1; !LOCAL->dirty && (i <= stream->nmsgs); i++) {
854 MESSAGECACHE *elt = mail_elt (stream,i);
855 if (mail_elt (stream,i)->deleted) LOCAL->dirty = T;
857 if (!LOCAL->dirty) { /* not dirty and no expunged messages */
858 unix_unlock (LOCAL->fd,stream,&lock);
859 msg = "No messages deleted, so no update needed";
861 else if (unix_rewrite (stream,&i,&lock,sequence ? LONGT : NIL)) {
862 if (i) sprintf (msg = LOCAL->buf,"Expunged %lu messages",i);
863 else msg = "Mailbox checkpointed, but no messages expunged";
865 /* rewrite failed */
866 else unix_unlock (LOCAL->fd,stream,&lock);
867 mail_unlock (stream); /* unlock the stream */
868 MM_NOCRITICAL (stream); /* done with critical */
869 if (msg && !stream->silent) MM_LOG (msg,NIL);
871 else if (!stream->silent) MM_LOG("Expunge ignored on readonly mailbox",WARN);
872 return ret;
875 /* UNIX mail copy message(s)
876 * Accepts: MAIL stream
877 * sequence
878 * destination mailbox
879 * copy options
880 * Returns: T if copy successful, else NIL
883 long unix_copy (MAILSTREAM *stream,char *sequence,char *mailbox,long options)
885 struct stat sbuf;
886 int fd;
887 char *s,file[MAILTMPLEN];
888 DOTLOCK lock;
889 time_t tp[2];
890 unsigned long i,j;
891 MESSAGECACHE *elt;
892 long ret = T;
893 mailproxycopy_t pc =
894 (mailproxycopy_t) mail_parameters (stream,GET_MAILPROXYCOPY,NIL);
895 copyuid_t cu = (copyuid_t) (mail_parameters (NIL,GET_USERHASNOLIFE,NIL) ?
896 NIL : mail_parameters (NIL,GET_COPYUID,NIL));
897 SEARCHSET *source = cu ? mail_newsearchset () : NIL;
898 SEARCHSET *dest = cu ? mail_newsearchset () : NIL;
899 MAILSTREAM *tstream = NIL;
900 DRIVER *d;
901 for (d = (DRIVER *) mail_parameters (NIL,GET_DRIVERS,NIL);
902 (d && strcmp (d->name,"mbox") && !(d->flags & DR_DISABLE));
903 d = d->next); /* see if mbox driver active */
904 if (!((options & CP_UID) ? mail_uid_sequence (stream,sequence) :
905 mail_sequence (stream,sequence))) return NIL;
906 /* make sure destination is valid */
907 if (!((d && mbox_valid (mailbox) && (mailbox = "mbox")) ||
908 unix_valid (mailbox) || !errno))
909 switch (errno) {
910 case ENOENT: /* no such file? */
911 if (compare_cstring (mailbox,"INBOX")) {
912 MM_NOTIFY (stream,"[TRYCREATE] Must create mailbox before copy",NIL);
913 return NIL;
915 if (pc) return (*pc) (stream,sequence,mailbox,options);
916 unix_create (NIL,"INBOX");/* create empty INBOX */
917 case EACCES: /* file protected */
918 sprintf (LOCAL->buf,"Can't access destination: %.80s",mailbox);
919 MM_LOG (LOCAL->buf,ERROR);
920 return NIL;
921 case EINVAL:
922 if (pc) return (*pc) (stream,sequence,mailbox,options);
923 sprintf (LOCAL->buf,"Invalid UNIX-format mailbox name: %.80s",mailbox);
924 MM_LOG (LOCAL->buf,ERROR);
925 return NIL;
926 default:
927 if (pc) return (*pc) (stream,sequence,mailbox,options);
928 sprintf (LOCAL->buf,"Not a UNIX-format mailbox: %.80s",mailbox);
929 MM_LOG (LOCAL->buf,ERROR);
930 return NIL;
933 /* try to open rewrite for UIDPLUS */
934 if ((tstream = mail_open_work (&unixdriver,NIL,mailbox,
935 OP_SILENT|OP_NOKOD)) && tstream->rdonly)
936 tstream = mail_close (tstream);
937 if (cu && !tstream) { /* wanted a COPYUID? */
938 sprintf (LOCAL->buf,"Unable to write-open mailbox for COPYUID: %.80s",
939 mailbox);
940 MM_LOG (LOCAL->buf,WARN);
941 cu = NIL; /* don't try to do COPYUID */
943 LOCAL->buf[0] = '\0';
944 MM_CRITICAL (stream); /* go critical */
945 if ((fd = unix_lock (dummy_file (file,mailbox),O_WRONLY|O_APPEND,
946 (long) mail_parameters (NIL,GET_MBXPROTECTION,NIL),
947 &lock,LOCK_EX)) < 0) {
948 MM_NOCRITICAL (stream); /* done with critical */
949 sprintf (LOCAL->buf,"Can't open destination mailbox: %s",strerror (errno));
950 MM_LOG (LOCAL->buf,ERROR);/* log the error */
951 return NIL; /* failed */
953 fstat (fd,&sbuf); /* get current file size */
954 /* write all requested messages to mailbox */
955 for (i = 1; ret && (i <= stream->nmsgs); i++)
956 if ((elt = mail_elt (stream,i))->sequence) {
957 lseek (LOCAL->fd,elt->private.special.offset,L_SET);
958 read (LOCAL->fd,LOCAL->buf,elt->private.special.text.size);
959 if (write (fd,LOCAL->buf,elt->private.special.text.size) < 0) ret = NIL;
960 else { /* internal header succeeded */
961 s = unix_header (stream,i,&j,FT_INTERNAL);
962 /* header size, sans trailing newline */
963 if (j && (s[j - 2] == '\n')) j--;
964 if (write (fd,s,j) < 0) ret = NIL;
965 else { /* message header succeeded */
966 j = tstream ? /* write UIDPLUS data if have readwrite */
967 unix_xstatus (stream,LOCAL->buf,elt,++(tstream->uid_last),LONGT) :
968 unix_xstatus (stream,LOCAL->buf,elt,NIL,NIL);
969 if (write (fd,LOCAL->buf,j) < 0) ret = NIL;
970 else { /* message status succeeded */
971 s = unix_text_work (stream,elt,&j,FT_INTERNAL);
972 if ((write (fd,s,j) < 0) || (write (fd,"\n",1) < 0)) ret = NIL;
973 else if (cu) { /* need to pass back new UID? */
974 mail_append_set (source,mail_uid (stream,i));
975 mail_append_set (dest,tstream->uid_last);
982 if (!ret || fsync (fd)) { /* force out the update */
983 sprintf (LOCAL->buf,"Message copy failed: %s",strerror (errno));
984 ftruncate (fd,sbuf.st_size);
985 ret = NIL;
987 /* force UIDVALIDITY assignment now */
988 if (tstream && !tstream->uid_validity) tstream->uid_validity = time (0);
989 /* return sets if doing COPYUID */
990 if (cu && ret) (*cu) (stream,mailbox,tstream->uid_validity,source,dest);
991 else { /* flush any sets we may have built */
992 mail_free_searchset (&source);
993 mail_free_searchset (&dest);
995 tp[1] = time (0); /* set mtime to now */
996 if (ret) tp[0] = tp[1] - 1; /* set atime to now-1 if successful copy */
997 else tp[0] = /* else preserve \Marked status */
998 ((sbuf.st_ctime > sbuf.st_atime) || (sbuf.st_mtime > sbuf.st_atime)) ?
999 sbuf.st_atime : tp[1];
1000 utime (file,tp); /* set the times */
1001 unix_unlock (fd,NIL,&lock); /* unlock and close mailbox */
1002 if (tstream) { /* update last UID if we can */
1003 UNIXLOCAL *local = (UNIXLOCAL *) tstream->local;
1004 local->dirty = T; /* do a rewrite */
1005 local->appending = T; /* but not at the cost of marking as old */
1006 tstream = mail_close (tstream);
1008 /* log the error */
1009 if (!ret) MM_LOG (LOCAL->buf,ERROR);
1010 /* delete if requested message */
1011 else if (options & CP_MOVE) for (i = 1; i <= stream->nmsgs; i++)
1012 if ((elt = mail_elt (stream,i))->sequence)
1013 elt->deleted = elt->private.dirty = LOCAL->dirty = T;
1014 MM_NOCRITICAL (stream); /* release critical */
1015 return ret;
1018 /* UNIX mail append message from stringstruct
1019 * Accepts: MAIL stream
1020 * destination mailbox
1021 * append callback
1022 * data for callback
1023 * Returns: T if append successful, else NIL
1026 #define BUFLEN 8*MAILTMPLEN
1028 long unix_append (MAILSTREAM *stream,char *mailbox,append_t af,void *data)
1030 struct stat sbuf;
1031 int fd;
1032 unsigned long i;
1033 char *flags,*date,buf[BUFLEN],tmp[MAILTMPLEN],file[MAILTMPLEN];
1034 time_t tp[2];
1035 FILE *sf,*df;
1036 MESSAGECACHE elt;
1037 DOTLOCK lock;
1038 STRING *message;
1039 unsigned long uidlocation = 0;
1040 appenduid_t au = (appenduid_t)
1041 (mail_parameters (NIL,GET_USERHASNOLIFE,NIL) ? NIL :
1042 mail_parameters (NIL,GET_APPENDUID,NIL));
1043 SEARCHSET *dst = au ? mail_newsearchset () : NIL;
1044 long ret = LONGT;
1045 MAILSTREAM *tstream = NIL;
1046 if (!stream) { /* stream specified? */
1047 stream = &unixproto; /* no, default stream to prototype */
1048 for (i = 0; i < NUSERFLAGS && stream->user_flags[i]; ++i)
1049 fs_give ((void **) &stream->user_flags[i]);
1051 if (!unix_valid (mailbox)) switch (errno) {
1052 case ENOENT: /* no such file? */
1053 if (compare_cstring (mailbox,"INBOX")) {
1054 MM_NOTIFY (stream,"[TRYCREATE] Must create mailbox before append",NIL);
1055 return NIL;
1057 unix_create (NIL,"INBOX"); /* create empty INBOX */
1058 case 0: /* merely empty file? */
1059 tstream = stream;
1060 break;
1061 case EACCES: /* file protected */
1062 sprintf (tmp,"Can't access destination: %.80s",mailbox);
1063 MM_LOG (tmp,ERROR);
1064 return NIL;
1065 case EINVAL:
1066 sprintf (tmp,"Invalid UNIX-format mailbox name: %.80s",mailbox);
1067 MM_LOG (tmp,ERROR);
1068 return NIL;
1069 default:
1070 sprintf (tmp,"Not a UNIX-format mailbox: %.80s",mailbox);
1071 MM_LOG (tmp,ERROR);
1072 return NIL;
1074 /* get sniffing stream for keywords */
1075 else if (!(tstream = mail_open (NIL,mailbox,
1076 OP_READONLY|OP_SILENT|OP_NOKOD|OP_SNIFF))) {
1077 sprintf (tmp,"Unable to examine mailbox for APPEND: %.80s",mailbox);
1078 MM_LOG (tmp,ERROR);
1079 return NIL;
1082 /* get first message */
1083 if (!MM_APPEND (af) (tstream,data,&flags,&date,&message)) return NIL;
1084 if (!(sf = tmpfile ())) { /* must have scratch file */
1085 sprintf (tmp,".%lx.%lx",(unsigned long) time (0),(unsigned long)getpid ());
1086 if (!stat (tmp,&sbuf) || !(sf = fopen (tmp,"wb+"))) {
1087 sprintf (tmp,"Unable to create scratch file: %.80s",strerror (errno));
1088 MM_LOG (tmp,ERROR);
1089 return NIL;
1091 unlink (tmp);
1093 do { /* parse date */
1094 if (!date) rfc822_date (date = tmp);
1095 if (!mail_parse_date (&elt,date)) {
1096 sprintf (tmp,"Bad date in append: %.80s",date);
1097 MM_LOG (tmp,ERROR);
1099 else { /* user wants to suppress time zones? */
1100 if (mail_parameters (NIL,GET_NOTIMEZONES,NIL)) {
1101 time_t when = mail_longdate (&elt);
1102 date = ctime (&when); /* use traditional date */
1104 /* use POSIX-style date */
1105 else date = mail_cdate (tmp,&elt);
1106 if (!SIZE (message)) MM_LOG ("Append of zero-length message",ERROR);
1107 else if (!unix_collect_msg (tstream,sf,flags,date,message)) {
1108 sprintf (tmp,"Error writing scratch file: %.80s",strerror (errno));
1109 MM_LOG (tmp,ERROR);
1111 /* get next message */
1112 else if (MM_APPEND (af) (tstream,data,&flags,&date,&message)) continue;
1114 fclose (sf); /* punt scratch file */
1115 return NIL; /* give up */
1116 } while (message); /* until no more messages */
1117 if (fflush (sf)) {
1118 sprintf (tmp,"Error finishing scratch file: %.80s",strerror (errno));
1119 MM_LOG (tmp,ERROR);
1120 fclose (sf); /* punt scratch file */
1121 return NIL; /* give up */
1123 i = ftell (sf); /* size of scratch file */
1124 /* close sniffing stream */
1125 if (tstream != stream) tstream = mail_close (tstream);
1127 MM_CRITICAL (stream); /* go critical */
1128 /* try to open readwrite for UIDPLUS */
1129 if ((tstream = mail_open_work (&unixdriver,NIL,mailbox,
1130 OP_SILENT|OP_NOKOD)) && tstream->rdonly)
1131 tstream = mail_close (tstream);
1132 if (au && !tstream) { /* wanted an APPENDUID? */
1133 sprintf (tmp,"Unable to re-open mailbox for APPENDUID: %.80s",mailbox);
1134 MM_LOG (tmp,WARN);
1135 au = NIL;
1137 if (((fd = unix_lock (dummy_file (file,mailbox),O_WRONLY|O_APPEND,
1138 (long) mail_parameters (NIL,GET_MBXPROTECTION,NIL),
1139 &lock,LOCK_EX)) < 0) ||
1140 !(df = fdopen (fd,"ab"))) {
1141 MM_NOCRITICAL (stream); /* done with critical */
1142 sprintf (tmp,"Can't open append mailbox: %s",strerror (errno));
1143 MM_LOG (tmp,ERROR);
1144 return NIL;
1146 fstat (fd,&sbuf); /* get current file size */
1147 rewind (sf);
1148 tp[1] = time (0); /* set mtime to now */
1149 /* write all messages */
1150 if (!unix_append_msgs (tstream,sf,df,au ? dst : NIL) ||
1151 (fflush (df) == EOF) || fsync (fd)) {
1152 sprintf (buf,"Message append failed: %s",strerror (errno));
1153 MM_LOG (buf,ERROR);
1154 ftruncate (fd,sbuf.st_size);
1155 tp[0] = /* preserve \Marked status */
1156 ((sbuf.st_ctime > sbuf.st_atime) || (sbuf.st_mtime > sbuf.st_atime)) ?
1157 sbuf.st_atime : tp[1];
1158 ret = NIL; /* return error */
1160 else tp[0] = tp[1] - 1; /* set atime to now-1 if successful copy */
1161 utime (file,tp); /* set the times */
1162 fclose (sf); /* done with scratch file */
1163 /* force UIDVALIDITY assignment now */
1164 if (tstream && !tstream->uid_validity) tstream->uid_validity = time (0);
1165 /* return sets if doing APPENDUID */
1166 if (au && ret) (*au) (mailbox,tstream->uid_validity,dst);
1167 else mail_free_searchset (&dst);
1168 unix_unlock (fd,NIL,&lock); /* unlock and close mailbox */
1169 fclose (df); /* note that unix_unlock() released the fd */
1170 if (tstream) { /* update last UID if we can */
1171 UNIXLOCAL *local = (UNIXLOCAL *) tstream->local;
1172 local->dirty = T; /* do a rewrite */
1173 local->appending = T; /* but not at the cost of marking as old */
1174 tstream = mail_close (tstream);
1176 MM_NOCRITICAL (stream); /* release critical */
1177 return ret;
1180 /* Collect and write single message to append scratch file
1181 * Accepts: MAIL stream
1182 * scratch file
1183 * flags
1184 * date
1185 * message stringstruct
1186 * Returns: NIL if write error, else T
1189 int unix_collect_msg (MAILSTREAM *stream,FILE *sf,char *flags,char *date,
1190 STRING *msg)
1192 unsigned char *s,*t;
1193 unsigned long uf;
1194 long f = mail_parse_flags (stream,flags,&uf);
1195 /* write metadata, note date ends with NL */
1196 if (fprintf (sf,"%ld %lu %s",f,SIZE (msg) + 1,date) < 0) return NIL;
1197 while (uf) /* write user flags */
1198 if ((s = stream->user_flags[find_rightmost_bit (&uf)]) &&
1199 (fprintf (sf," %s",s) < 0)) return NIL;
1200 if (putc ('\n',sf) == EOF) return NIL;
1201 while (SIZE (msg)) { /* copy text to scratch file */
1202 for (s = (unsigned char *) msg->curpos, t = s + msg->cursize; s < t; ++s)
1203 if (!*s) *s = 0x80; /* disallow NUL */
1204 /* write buffered text */
1205 if (fwrite (msg->curpos,1,msg->cursize,sf) == msg->cursize)
1206 SETPOS (msg,GETPOS (msg) + msg->cursize);
1207 else return NIL; /* failed */
1209 /* write trailing newline and return */
1210 return (putc ('\n',sf) == EOF) ? NIL : T;
1213 /* Append messages from scratch file to mailbox
1214 * Accepts: MAIL stream
1215 * source file
1216 * destination file
1217 * uidset to update if non-NIL
1218 * Returns: T if success, NIL if failure
1221 int unix_append_msgs (MAILSTREAM *stream,FILE *sf,FILE *df,SEARCHSET *set)
1223 int ti,zn,c;
1224 long f;
1225 unsigned long i,j;
1226 char *x,tmp[MAILTMPLEN];
1227 int hdrp = T;
1228 /* get message metadata line */
1229 while (fgets (tmp,MAILTMPLEN,sf)) {
1230 if (!(isdigit (tmp[0]) && strchr (tmp,'\n'))) return NIL;
1231 f = strtol (tmp,&x,10); /* get flags */
1232 if (!((*x++ == ' ') && isdigit (*x))) return NIL;
1233 i = strtoul (x,&x,10); /* get message size */
1234 if ((*x++ != ' ') || /* build initial header */
1235 (fprintf (df,"From %s@%s %sStatus: ",myusername(),mylocalhost(),x)<0)||
1236 (f&fSEEN && (putc ('R',df) == EOF)) ||
1237 (fputs ("\nX-Status: ",df) == EOF) ||
1238 (f&fDELETED && (putc ('D',df) == EOF)) ||
1239 (f&fFLAGGED && (putc ('F',df) == EOF)) ||
1240 (f&fANSWERED && (putc ('A',df) == EOF)) ||
1241 (f&fDRAFT && (putc ('T',df) == EOF)) ||
1242 (fputs ("\nX-Keywords:",df) == EOF)) return NIL;
1243 /* copy keywords */
1244 while ((c = getc (sf)) != '\n') switch (c) {
1245 case EOF:
1246 return NIL;
1247 default:
1248 if (putc (c,df) == EOF) return NIL;
1250 if ((putc ('\n',df) == EOF) ||
1251 (set && (fprintf (df,"X-UID: %lu\n",++(stream->uid_last)) < 0)))
1252 return NIL;
1254 for (c = '\n'; i && fgets (tmp,MAILTMPLEN,sf); c = tmp[j-1]) {
1255 /* get read line length */
1256 if (i < (j = strlen (tmp))) fatal ("unix_append_msgs overrun");
1257 i -= j; /* number of bytes left */
1258 /* squish out CRs (note also copies NUL) */
1259 for (x = tmp; x = strchr (x,'\r'); --j) memmove (x,x+1,j-(x-tmp));
1260 if (!j) continue; /* do nothing if line emptied */
1261 /* start of line? */
1262 if ((c == '\n')) switch (tmp[0]) {
1263 case 'F': /* possible "From " (case counts here) */
1264 if ((j > 4) && (tmp[0] == 'F') && (tmp[1] == 'r') && (tmp[2] == 'o') &&
1265 (tmp[3] == 'm') && (tmp[4] == ' ')) {
1266 if (!unix_fromwidget) {
1267 VALID (tmp,x,ti,zn);/* conditional, only write widget if */
1268 if (!ti) break; /* it looks like a valid header */
1269 } /* write the widget */
1270 if (putc ('>',df) == EOF) return NIL;
1272 break;
1273 case 'S': case 's': /* possible "Status:" */
1274 if (hdrp && (j > 6) && ((tmp[1] == 't') || (tmp[1] == 'T')) &&
1275 ((tmp[2] == 'a') || (tmp[2] == 'A')) &&
1276 ((tmp[3] == 't') || (tmp[3] == 'T')) &&
1277 ((tmp[4] == 'u') || (tmp[4] == 'U')) &&
1278 ((tmp[5] == 's') || (tmp[5] == 'S')) && (tmp[6] == ':') &&
1279 (fputs ("X-Original-",df) == EOF)) return NIL;
1280 break;
1281 case 'X': case 'x': /* possible X-??? header */
1282 if (hdrp && (tmp[1] == '-') &&
1283 /* possible X-UID: */
1284 (((j > 5) && ((tmp[2] == 'U') || (tmp[2] == 'u')) &&
1285 ((tmp[3] == 'I') || (tmp[3] == 'i')) &&
1286 ((tmp[4] == 'D') || (tmp[4] == 'd')) && (tmp[5] == ':')) ||
1287 /* possible X-IMAP: */
1288 ((j > 6) && ((tmp[2] == 'I') || (tmp[2] == 'i')) &&
1289 ((tmp[3] == 'M') || (tmp[3] == 'm')) &&
1290 ((tmp[4] == 'A') || (tmp[4] == 'a')) &&
1291 ((tmp[5] == 'P') || (tmp[5] == 'p')) &&
1292 ((tmp[6] == ':') ||
1293 /* or X-IMAPbase: */
1294 ((j > 10) && ((tmp[6] == 'b') || (tmp[6] == 'B')) &&
1295 ((tmp[7] == 'a') || (tmp[7] == 'A')) &&
1296 ((tmp[8] == 's') || (tmp[8] == 'S')) &&
1297 ((tmp[9] == 'e') || (tmp[9] == 'E')) && (tmp[10] == ':')))) ||
1298 /* possible X-Status: */
1299 ((j > 8) && ((tmp[2] == 'S') || (tmp[2] == 's')) &&
1300 ((tmp[3] == 't') || (tmp[3] == 'T')) &&
1301 ((tmp[4] == 'a') || (tmp[4] == 'A')) &&
1302 ((tmp[5] == 't') || (tmp[5] == 'T')) &&
1303 ((tmp[6] == 'u') || (tmp[6] == 'U')) &&
1304 ((tmp[7] == 's') || (tmp[7] == 'S')) && (tmp[8] == ':')) ||
1305 /* possible X-Keywords: */
1306 ((j > 10) && ((tmp[2] == 'K') || (tmp[2] == 'k')) &&
1307 ((tmp[3] == 'e') || (tmp[3] == 'E')) &&
1308 ((tmp[4] == 'y') || (tmp[4] == 'Y')) &&
1309 ((tmp[5] == 'w') || (tmp[5] == 'W')) &&
1310 ((tmp[6] == 'o') || (tmp[6] == 'O')) &&
1311 ((tmp[7] == 'r') || (tmp[7] == 'R')) &&
1312 ((tmp[8] == 'd') || (tmp[8] == 'D')) &&
1313 ((tmp[9] == 's') || (tmp[9] == 'S')) && (tmp[10] == ':'))) &&
1314 (fputs ("X-Original-",df) == EOF)) return NIL;
1315 case '\n': /* blank line */
1316 hdrp = NIL;
1317 break;
1318 default: /* nothing to do */
1319 break;
1321 /* just write the line */
1322 if (fwrite (tmp,1,j,df) != j) return NIL;
1324 if (i) return NIL; /* didn't read entire message */
1325 /* update set */
1326 if (stream) mail_append_set (set,stream->uid_last);
1328 return T;
1331 /* Internal routines */
1334 /* UNIX mail abort stream
1335 * Accepts: MAIL stream
1338 void unix_abort (MAILSTREAM *stream)
1340 if (LOCAL) { /* only if a file is open */
1341 if (LOCAL->fd >= 0) close (LOCAL->fd);
1342 if (LOCAL->ld >= 0) { /* have a mailbox lock? */
1343 flock (LOCAL->ld,LOCK_UN);/* yes, release the lock */
1344 close (LOCAL->ld); /* close the lock file */
1345 unlink (LOCAL->lname); /* and delete it */
1347 if (LOCAL->lname) fs_give ((void **) &LOCAL->lname);
1348 /* free local text buffers */
1349 if (LOCAL->buf) fs_give ((void **) &LOCAL->buf);
1350 if (LOCAL->text.data) fs_give ((void **) &LOCAL->text.data);
1351 if (LOCAL->linebuf) fs_give ((void **) &LOCAL->linebuf);
1352 if (LOCAL->line) fs_give ((void **) &LOCAL->line);
1353 /* nuke the local data */
1354 fs_give ((void **) &stream->local);
1355 stream->dtb = NIL; /* log out the DTB */
1359 /* UNIX open and lock mailbox
1360 * Accepts: file name to open/lock
1361 * file open mode
1362 * destination buffer for lock file name
1363 * type of locking operation (LOCK_SH or LOCK_EX)
1366 int unix_lock (char *file,int flags,int mode,DOTLOCK *lock,int op)
1368 int fd;
1369 blocknotify_t bn = (blocknotify_t) mail_parameters (NIL,GET_BLOCKNOTIFY,NIL);
1370 (*bn) (BLOCK_FILELOCK,NIL);
1371 /* try locking the easy way */
1372 if (dotlock_lock (file,lock,-1)) {
1373 /* got dotlock file, easy open */
1374 if ((fd = open (file,flags,mode)) >= 0) flock (fd,op);
1375 else dotlock_unlock (lock); /* open failed, free the dotlock */
1377 /* no dot lock file, open file now */
1378 else if ((fd = open (file,flags,mode)) >= 0) {
1379 /* try paranoid way to make a dot lock file */
1380 if (dotlock_lock (file,lock,fd)) {
1381 close (fd); /* get fresh fd in case of timing race */
1382 if ((fd = open (file,flags,mode)) >= 0) flock (fd,op);
1383 /* open failed, free the dotlock */
1384 else dotlock_unlock (lock);
1386 else flock (fd,op); /* paranoid way failed, just flock() it */
1388 (*bn) (BLOCK_NONE,NIL);
1389 return fd;
1392 /* UNIX unlock and close mailbox
1393 * Accepts: file descriptor
1394 * (optional) mailbox stream to check atime/mtime
1395 * (optional) lock file name
1398 void unix_unlock (int fd,MAILSTREAM *stream,DOTLOCK *lock)
1400 if (stream) { /* need to muck with times? */
1401 struct stat sbuf;
1402 time_t tp[2];
1403 time_t now = time (0);
1404 fstat (fd,&sbuf); /* get file times */
1405 if (LOCAL->ld >= 0) { /* yes, readwrite session? */
1406 tp[0] = now; /* set atime to now */
1407 /* set mtime to (now - 1) if necessary */
1408 tp[1] = (now > sbuf.st_mtime) ? sbuf.st_mtime : now - 1;
1410 else if (stream->recent) { /* readonly with recent messages */
1411 if ((sbuf.st_atime >= sbuf.st_mtime) ||
1412 (sbuf.st_atime >= sbuf.st_ctime))
1413 /* keep past mtime, whack back atime */
1414 tp[0] = (tp[1] = (sbuf.st_mtime < now) ? sbuf.st_mtime : now) - 1;
1415 else now = 0; /* no time change needed */
1417 /* readonly with no recent messages */
1418 else if ((sbuf.st_atime < sbuf.st_mtime) ||
1419 (sbuf.st_atime < sbuf.st_ctime)) {
1420 tp[0] = now; /* set atime to now */
1421 /* set mtime to (now - 1) if necessary */
1422 tp[1] = (now > sbuf.st_mtime) ? sbuf.st_mtime : now - 1;
1424 else now = 0; /* no time change needed */
1425 /* set the times, note change */
1426 if (now && !utime (stream->mailbox,tp)) LOCAL->filetime = tp[1];
1428 flock (fd,LOCK_UN); /* release flock'ers */
1429 if (!stream) close (fd); /* close the file if no stream */
1430 dotlock_unlock (lock); /* flush the lock file if any */
1433 /* UNIX mail parse and lock mailbox
1434 * Accepts: MAIL stream
1435 * space to write lock file name
1436 * type of locking operation
1437 * Returns: T if parse OK, critical & mailbox is locked shared; NIL if failure
1440 int unix_parse (MAILSTREAM *stream,DOTLOCK *lock,int op)
1442 int zn;
1443 unsigned long i,j,k,m;
1444 unsigned char c,*s,*t,*u,tmp[MAILTMPLEN],date[30];
1445 int ti = 0,retain = T;
1446 unsigned long nmsgs = stream->nmsgs;
1447 unsigned long prevuid = nmsgs ? mail_elt (stream,nmsgs)->private.uid : 0;
1448 unsigned long recent = stream->recent;
1449 unsigned long oldnmsgs = stream->nmsgs;
1450 short silent = stream->silent;
1451 short pseudoseen = NIL;
1452 struct stat sbuf;
1453 STRING bs;
1454 FDDATA d;
1455 MESSAGECACHE *elt;
1456 mail_lock (stream); /* guard against recursion or pingers */
1457 /* toss out previous descriptor */
1458 if (LOCAL->fd >= 0) close (LOCAL->fd);
1459 MM_CRITICAL (stream); /* open and lock mailbox (shared OK) */
1460 if ((LOCAL->fd = unix_lock (stream->mailbox,(LOCAL->ld >= 0) ?
1461 O_RDWR : O_RDONLY,
1462 (long)mail_parameters(NIL,GET_MBXPROTECTION,NIL),
1463 lock,op)) < 0) {
1464 sprintf (tmp,"Mailbox open failed, aborted: %s",strerror (errno));
1465 MM_LOG (tmp,ERROR);
1466 unix_abort (stream);
1467 mail_unlock (stream);
1468 MM_NOCRITICAL (stream); /* done with critical */
1469 return NIL;
1471 fstat (LOCAL->fd,&sbuf); /* get status */
1472 /* validate change in size */
1473 if (sbuf.st_size < LOCAL->filesize) {
1474 sprintf (tmp,"Mailbox shrank from %lu to %lu bytes, aborted",
1475 (unsigned long) LOCAL->filesize,(unsigned long) sbuf.st_size);
1476 MM_LOG (tmp,ERROR); /* this is pretty bad */
1477 unix_unlock (LOCAL->fd,stream,lock);
1478 unix_abort (stream);
1479 mail_unlock (stream);
1480 MM_NOCRITICAL (stream); /* done with critical */
1481 return NIL;
1484 /* new data? */
1485 else if (i = sbuf.st_size - LOCAL->filesize) {
1486 d.fd = LOCAL->fd; /* yes, set up file descriptor */
1487 d.pos = LOCAL->filesize; /* get to that position in the file */
1488 d.chunk = LOCAL->buf; /* initial buffer chunk */
1489 d.chunksize = CHUNKSIZE; /* file chunk size */
1490 INIT (&bs,fd_string,&d,i); /* initialize stringstruct */
1491 /* skip leading whitespace for broken MTAs */
1492 while (((c = CHR (&bs)) == '\n') || (c == '\r') ||
1493 (c == ' ') || (c == '\t')) SNX (&bs);
1494 if (SIZE (&bs)) { /* read new data */
1495 /* remember internal header position */
1496 j = LOCAL->filesize + GETPOS (&bs);
1497 s = unix_mbxline (stream,&bs,&i);
1498 t = NIL,zn = 0;
1499 if (i) VALID (s,t,ti,zn); /* see if valid From line */
1500 if (!ti) { /* someone pulled the rug from under us */
1501 sprintf (tmp,"Unexpected changes to mailbox (try restarting): %.20s",
1502 (char *) s);
1503 MM_LOG (tmp,ERROR);
1504 unix_unlock (LOCAL->fd,stream,lock);
1505 unix_abort (stream);
1506 mail_unlock (stream);
1507 /* done with critical */
1508 MM_NOCRITICAL (stream);
1509 return NIL;
1511 stream->silent = T; /* quell main program new message events */
1512 do { /* found a message */
1513 /* instantiate first new message */
1514 mail_exists (stream,++nmsgs);
1515 (elt = mail_elt (stream,nmsgs))->valid = T;
1516 recent++; /* assume recent by default */
1517 elt->recent = T;
1518 /* note position/size of internal header */
1519 elt->private.special.offset = j;
1520 elt->private.msg.header.offset = elt->private.special.text.size = i;
1522 /* generate plausible IMAPish date string */
1523 date[2] = date[6] = date[20] = '-'; date[11] = ' ';
1524 date[14] = date[17] = ':';
1525 /* dd */
1526 date[0] = t[ti - 2]; date[1] = t[ti - 1];
1527 /* mmm */
1528 date[3] = t[ti - 6]; date[4] = t[ti - 5]; date[5] = t[ti - 4];
1529 /* hh */
1530 date[12] = t[ti + 1]; date[13] = t[ti + 2];
1531 /* mm */
1532 date[15] = t[ti + 4]; date[16] = t[ti + 5];
1533 if (t[ti += 6] == ':') {/* ss */
1534 date[18] = t[++ti]; date[19] = t[++ti];
1535 ti++; /* move to space */
1537 else date[18] = date[19] = '0';
1538 /* yy -- advance over timezone if necessary */
1539 if (zn == ti) ti += (((t[zn+1] == '+') || (t[zn+1] == '-')) ? 6 : 4);
1540 date[7] = t[ti + 1]; date[8] = t[ti + 2];
1541 date[9] = t[ti + 3]; date[10] = t[ti + 4];
1542 /* zzz */
1543 t = zn ? (t + zn + 1) : (unsigned char *) "LCL";
1544 date[21] = *t++; date[22] = *t++; date[23] = *t++;
1545 if ((date[21] != '+') && (date[21] != '-')) date[24] = '\0';
1546 else { /* numeric time zone */
1547 date[24] = *t++; date[25] = *t++;
1548 date[26] = '\0'; date[20] = ' ';
1550 /* set internal date */
1551 if (!mail_parse_date (elt,date)) {
1552 sprintf (tmp,"Unable to parse internal date: %s",(char *) date);
1553 MM_LOG (tmp,WARN);
1556 do { /* look for message body */
1557 s = t = unix_mbxline (stream,&bs,&i);
1558 if (i) switch (*s) { /* check header lines */
1559 case 'X': /* possible X-???: line */
1560 if (s[1] == '-') { /* must be immediately followed by hyphen */
1561 /* X-Status: becomes Status: in S case */
1562 if (s[2] == 'S' && s[3] == 't' && s[4] == 'a' && s[5] == 't' &&
1563 s[6] == 'u' && s[7] == 's' && s[8] == ':') s += 2;
1564 /* possible X-Keywords */
1565 else if (s[2] == 'K' && s[3] == 'e' && s[4] == 'y' &&
1566 s[5] == 'w' && s[6] == 'o' && s[7] == 'r' &&
1567 s[8] == 'd' && s[9] == 's' && s[10] == ':') {
1568 SIZEDTEXT uf;
1569 retain = NIL; /* don't retain continuation */
1570 s += 11; /* flush leading whitespace */
1571 while (*s && (*s != '\n') && ((*s != '\r') || (s[1] != '\n'))){
1572 while (*s == ' ') s++;
1573 /* find end of keyword */
1574 if (!(u = strpbrk (s," \n\r"))) u = s + strlen (s);
1575 /* got a keyword? */
1576 if ((k = (u - s)) && (k <= MAXUSERFLAG)) {
1577 uf.data = (unsigned char *) s;
1578 uf.size = k;
1579 for (j = 0; (j < NUSERFLAGS) && stream->user_flags[j]; ++j)
1580 if (!compare_csizedtext (stream->user_flags[j],&uf)) {
1581 elt->user_flags |= ((long) 1) << j;
1582 break;
1585 s = u; /* advance to next keyword */
1587 break;
1590 /* possible X-IMAP */
1591 else if ((s[2] == 'I') && (s[3] == 'M') && (s[4] == 'A') &&
1592 (s[5] == 'P') && ((m = (s[6] == ':')) ||
1593 ((s[6] == 'b') && (s[7] == 'a') &&
1594 (s[8] == 's') && (s[9] == 'e') &&
1595 (s[10] == ':')))) {
1596 retain = NIL; /* don't retain continuation */
1597 if ((nmsgs == 1) && !stream->uid_validity) {
1598 /* advance to data */
1599 s += m ? 7 : 11;
1600 /* flush whitespace */
1601 while (*s == ' ') s++;
1602 j = 0; /* slurp UID validity */
1603 /* found a digit? */
1604 while (isdigit (*s)) {
1605 j *= 10; /* yes, add it in */
1606 j += *s++ - '0';
1608 /* flush whitespace */
1609 while (*s == ' ') s++;
1610 /* must have valid UID validity and UID last */
1611 if (j && isdigit (*s)) {
1612 /* pseudo-header seen if X-IMAP */
1613 if (m) pseudoseen = LOCAL->pseudo = T;
1614 /* save UID validity */
1615 stream->uid_validity = j;
1616 j = 0; /* slurp UID last */
1617 while (isdigit (*s)) {
1618 j *= 10; /* yes, add it in */
1619 j += *s++ - '0';
1621 /* save UID last */
1622 stream->uid_last = j;
1623 /* process keywords */
1624 for (j = 0; (*s != '\n') && ((*s != '\r')||(s[1] != '\n'));
1625 s = u,j++) {
1626 /* flush leading whitespace */
1627 while (*s == ' ') s++;
1628 u = strpbrk (s," \n\r");
1629 /* got a keyword? */
1630 if ((j < NUSERFLAGS) && (k = (u - s)) &&
1631 (k <= MAXUSERFLAG)) {
1632 if (stream->user_flags[j])
1633 fs_give ((void **) &stream->user_flags[j]);
1634 stream->user_flags[j] = (char *) fs_get (k + 1);
1635 strncpy (stream->user_flags[j],s,k);
1636 stream->user_flags[j][k] = '\0';
1641 break;
1644 /* possible X-UID */
1645 else if (s[2] == 'U' && s[3] == 'I' && s[4] == 'D' &&
1646 s[5] == ':') {
1647 retain = NIL; /* don't retain continuation */
1648 /* only believe if have a UID validity */
1649 if (stream->uid_validity && ((nmsgs > 1) || !pseudoseen)) {
1650 s += 6; /* advance to UID value */
1651 /* flush whitespace */
1652 while (*s == ' ') s++;
1653 j = 0;
1654 /* found a digit? */
1655 while (isdigit (*s)) {
1656 j *= 10; /* yes, add it in */
1657 j += *s++ - '0';
1659 /* flush remainder of line */
1660 while (*s != '\n') s++;
1661 /* make sure not duplicated */
1662 if (elt->private.uid)
1663 sprintf (tmp,"Message %lu UID %lu already has UID %lu",
1664 pseudoseen ? elt->msgno - 1 : elt->msgno,
1665 j,elt->private.uid);
1666 /* make sure UID doesn't go backwards */
1667 else if (j <= prevuid)
1668 sprintf (tmp,"Message %lu UID %lu less than %lu",
1669 pseudoseen ? elt->msgno - 1 : elt->msgno,
1670 j,prevuid + 1);
1671 #if 0 /* this is currently broken by UIDPLUS */
1672 /* or skip by mailbox's recorded last */
1673 else if (j > stream->uid_last)
1674 sprintf (tmp,"Message %lu UID %lu greater than last %lu",
1675 pseudoseen ? elt->msgno - 1 : elt->msgno,
1676 j,stream->uid_last);
1677 #endif
1678 else { /* normal UID case */
1679 prevuid = elt->private.uid = j;
1680 #if 1 /* temporary kludge for UIDPLUS */
1681 if (prevuid > stream->uid_last) {
1682 stream->uid_last = prevuid;
1683 LOCAL->ddirty = LOCAL->dirty = T;
1685 #endif
1686 break; /* exit this cruft */
1688 MM_LOG (tmp,WARN);
1689 /* invalidate UID validity */
1690 stream->uid_validity = 0;
1691 elt->private.uid = 0;
1693 break;
1696 /* otherwise fall into S case */
1698 case 'S': /* possible Status: line */
1699 if (s[0] == 'S' && s[1] == 't' && s[2] == 'a' && s[3] == 't' &&
1700 s[4] == 'u' && s[5] == 's' && s[6] == ':') {
1701 retain = NIL; /* don't retain continuation */
1702 s += 6; /* advance to status flags */
1703 do switch (*s++) {/* parse flags */
1704 case 'R': /* message read */
1705 elt->seen = T;
1706 break;
1707 case 'O': /* message old */
1708 if (elt->recent) {
1709 elt->recent = NIL;
1710 recent--; /* it really wasn't recent */
1712 break;
1713 case 'D': /* message deleted */
1714 elt->deleted = T;
1715 break;
1716 case 'F': /* message flagged */
1717 elt->flagged = T;
1718 break;
1719 case 'A': /* message answered */
1720 elt->answered = T;
1721 break;
1722 case 'T': /* message is a draft */
1723 elt->draft = T;
1724 break;
1725 default: /* some other crap */
1726 break;
1727 } while (*s && (*s != '\n') && ((*s != '\r') || (s[1] != '\n')));
1728 break; /* all done */
1730 /* otherwise fall into default case */
1732 default: /* ordinary header line */
1733 if ((*s == 'S') || (*s == 's') ||
1734 (((*s == 'X') || (*s == 'x')) && (s[1] == '-'))) {
1735 unsigned char *e,*v;
1736 /* must match what mail_filter() does */
1737 for (u = s,v = tmp,e = u + min (i,MAILTMPLEN - 1);
1738 (u < e) && ((c = (*u ? *u : (*u = ' '))) != ':') &&
1739 ((c > ' ') || ((c != ' ') && (c != '\t') &&
1740 (c != '\r') && (c != '\n')));
1741 *v++ = *u++);
1742 *v = '\0'; /* tie off */
1743 /* matches internal header? */
1744 if (!compare_cstring (tmp,"STATUS") ||
1745 !compare_cstring (tmp,"X-STATUS") ||
1746 !compare_cstring (tmp,"X-KEYWORDS") ||
1747 !compare_cstring (tmp,"X-UID") ||
1748 !compare_cstring (tmp,"X-IMAP") ||
1749 !compare_cstring (tmp,"X-IMAPBASE")) {
1750 char err[MAILTMPLEN];
1751 sprintf (err,"Discarding bogus %s header in message %lu",
1752 (char *) tmp,elt->msgno);
1753 MM_LOG (err,WARN);
1754 retain = NIL; /* don't retain continuation */
1755 break; /* different case or something */
1758 /* retain or non-continuation? */
1759 if (retain || ((*s != ' ') && (*s != '\t'))) {
1760 retain = T; /* retaining continuation now */
1761 /* line length in LF format newline */
1762 for (j = k = 0; j < i; ++j) if (s[j] != '\r') ++k;
1763 /* "internal" header size */
1764 elt->private.spare.data += k;
1765 /* message size */
1766 elt->rfc822_size += k + 1;
1768 else {
1769 char err[MAILTMPLEN];
1770 sprintf (err,"Discarding bogus continuation in msg %lu: %.80s",
1771 elt->msgno,(char *) s);
1772 if (u = strpbrk (err,"\r\n")) *u = '\0';
1773 MM_LOG (err,WARN);
1774 break; /* different case or something */
1776 break;
1778 } while (i && (*t != '\n') && ((*t != '\r') || (t[1] != '\n')));
1779 /* "internal" header sans trailing newline */
1780 if (i) elt->private.spare.data--;
1781 /* assign a UID if none found */
1782 if (((nmsgs > 1) || !pseudoseen) && !elt->private.uid) {
1783 prevuid = elt->private.uid = ++stream->uid_last;
1784 elt->private.dirty = T;
1785 LOCAL->ddirty = T; /* force update */
1787 else elt->private.dirty = elt->recent;
1789 /* note size of header, location of text */
1790 elt->private.msg.header.text.size =
1791 (elt->private.msg.text.offset =
1792 (LOCAL->filesize + GETPOS (&bs)) - elt->private.special.offset) -
1793 elt->private.special.text.size;
1794 k = m = 0; /* no previous line size yet */
1795 /* note current position */
1796 j = LOCAL->filesize + GETPOS (&bs);
1797 if (i) do { /* look for next message */
1798 s = unix_mbxline (stream,&bs,&i);
1799 if (i) { /* got new data? */
1800 VALID (s,t,ti,zn); /* yes, parse line */
1801 if (!ti) { /* not a header line, add it to message */
1802 elt->rfc822_size += i;
1803 for (j = 0; j < i; ++j) switch (s[j]) {
1804 case '\r': /* squeeze out CRs */
1805 elt->rfc822_size -= 1;
1806 break;
1807 case '\n': /* LF becomes CRLF */
1808 elt->rfc822_size += 1;
1809 break;
1810 default:
1811 break;
1813 if ((i == 1) && (*s == '\n')) {
1814 k = 2;
1815 m = 1;
1817 else if ((i == 2) && (*s == '\r') && (s[1] == '\n'))
1818 k = m = 2;
1819 else k = m = 0; /* file does not end with newline! */
1820 /* update current position */
1821 j = LOCAL->filesize + GETPOS (&bs);
1824 } while (i && !ti); /* until found a header */
1825 elt->private.msg.text.text.size = j -
1826 (elt->private.special.offset + elt->private.msg.text.offset);
1827 /* flush ending blank line */
1828 elt->private.msg.text.text.size -= m;
1829 elt->rfc822_size -= k;
1830 /* until end of buffer */
1831 } while (!stream->sniff && i);
1832 if (pseudoseen) { /* flush pseudo-message if present */
1833 /* decrement recent count */
1834 if (mail_elt (stream,1)->recent) recent--;
1835 /* and the exists count */
1836 mail_exists (stream,nmsgs--);
1837 mail_expunged(stream,1);/* fake an expunge of that message */
1839 /* need to start a new UID validity? */
1840 if (!stream->uid_validity) {
1841 stream->uid_validity = time (0);
1842 /* in case a whiner with no life */
1843 if (mail_parameters (NIL,GET_USERHASNOLIFE,NIL))
1844 stream->uid_nosticky = T;
1845 else if (nmsgs) { /* don't bother if empty file */
1846 /* make dirty to restart UID epoch */
1847 LOCAL->ddirty = LOCAL->dirty = T;
1848 /* need to rewrite msg 1 if not pseudo */
1849 if (!LOCAL->pseudo) mail_elt (stream,1)->private.dirty = T;
1850 MM_LOG ("Assigning new unique identifiers to all messages",NIL);
1853 stream->nmsgs = oldnmsgs; /* whack it back down */
1854 stream->silent = silent; /* restore old silent setting */
1855 /* notify upper level of new mailbox sizes */
1856 mail_exists (stream,nmsgs);
1857 mail_recent (stream,recent);
1858 /* mark dirty so O flags are set */
1859 if (recent) LOCAL->dirty = T;
1862 /* no change, don't babble if never got time */
1863 else if (LOCAL->filetime && LOCAL->filetime != sbuf.st_mtime)
1864 MM_LOG ("New mailbox modification time but apparently no changes",WARN);
1865 /* update parsed file size and time */
1866 LOCAL->filesize = sbuf.st_size;
1867 LOCAL->filetime = sbuf.st_mtime;
1868 return T; /* return the winnage */
1871 /* UNIX read line from mailbox
1872 * Accepts: mail stream
1873 * stringstruct
1874 * pointer to line size
1875 * Returns: pointer to input line
1878 char *unix_mbxline (MAILSTREAM *stream,STRING *bs,unsigned long *size)
1880 unsigned long i,j,k,m;
1881 char *s,*t,*te;
1882 char *ret = "";
1883 /* flush old buffer */
1884 if (LOCAL->line) fs_give ((void **) &LOCAL->line);
1885 /* if buffer needs refreshing */
1886 if (!bs->cursize) SETPOS (bs,GETPOS (bs));
1887 if (SIZE (bs)) { /* find newline */
1888 /* end of fast scan */
1889 te = (t = (s = bs->curpos) + bs->cursize) - 12;
1890 while (s < te) if ((*s++ == '\n') || (*s++ == '\n') || (*s++ == '\n') ||
1891 (*s++ == '\n') || (*s++ == '\n') || (*s++ == '\n') ||
1892 (*s++ == '\n') || (*s++ == '\n') || (*s++ == '\n') ||
1893 (*s++ == '\n') || (*s++ == '\n') || (*s++ == '\n')) {
1894 --s; /* back up */
1895 break; /* exit loop */
1897 /* final character-at-a-time scan */
1898 while ((s < t) && (*s != '\n')) ++s;
1899 /* difficult case if line spans buffer */
1900 if ((i = s - bs->curpos) == bs->cursize) {
1901 /* have space in line buffer? */
1902 if (i > LOCAL->linebuflen) {
1903 fs_give ((void **) &LOCAL->linebuf);
1904 LOCAL->linebuf = (char *) fs_get (LOCAL->linebuflen = i);
1906 /* remember what we have so far */
1907 memcpy (LOCAL->linebuf,bs->curpos,i);
1908 /* load next buffer */
1909 SETPOS (bs,k = GETPOS (bs) + i);
1910 /* end of fast scan */
1911 te = (t = (s = bs->curpos) + bs->cursize) - 12;
1912 /* fast scan in overlap buffer */
1913 while (s < te) if ((*s++ == '\n') || (*s++ == '\n') || (*s++ == '\n') ||
1914 (*s++ == '\n') || (*s++ == '\n') || (*s++ == '\n') ||
1915 (*s++ == '\n') || (*s++ == '\n') || (*s++ == '\n') ||
1916 (*s++ == '\n') || (*s++ == '\n') || (*s++ == '\n')) {
1917 --s; /* back up */
1918 break; /* exit loop */
1921 /* final character-at-a-time scan */
1922 while ((s < t) && (*s != '\n')) ++s;
1923 /* huge line? */
1924 if ((j = s - bs->curpos) == bs->cursize) {
1925 SETPOS (bs,GETPOS (bs) + j);
1926 /* look for end of line (s-l-o-w!!) */
1927 for (m = SIZE (bs); m && (SNX (bs) != '\n'); --m,++j);
1928 SETPOS (bs,k); /* go back to where it started */
1930 /* got size of data, make buffer for return */
1931 ret = LOCAL->line = (char *) fs_get (i + j + 2);
1932 /* copy first chunk */
1933 memcpy (ret,LOCAL->linebuf,i);
1934 while (j) { /* copy remainder */
1935 if (!bs->cursize) SETPOS (bs,GETPOS (bs));
1936 memcpy (ret + i,bs->curpos,k = min (j,bs->cursize));
1937 i += k; /* account for this much read in */
1938 j -= k;
1939 bs->curpos += k; /* increment new position */
1940 bs->cursize -= k; /* eat that many bytes */
1942 if (!bs->cursize) SETPOS (bs,GETPOS (bs));
1943 /* read newline at end */
1944 if (SIZE (bs)) ret[i++] = SNX (bs);
1945 ret[i] = '\0'; /* makes debugging easier */
1947 else { /* this is easy */
1948 ret = bs->curpos; /* string it at this position */
1949 bs->curpos += ++i; /* increment new position */
1950 bs->cursize -= i; /* eat that many bytes */
1952 *size = i; /* return that to user */
1954 else *size = 0; /* end of data, return empty */
1955 return ret;
1958 /* UNIX make pseudo-header
1959 * Accepts: MAIL stream
1960 * buffer to write pseudo-header
1961 * Returns: length of pseudo-header
1964 unsigned long unix_pseudo (MAILSTREAM *stream,char *hdr)
1966 int i;
1967 char *s,tmp[MAILTMPLEN];
1968 time_t now = time (0);
1969 rfc822_fixed_date (tmp);
1970 sprintf (hdr,"From %s %.24s\nDate: %s\nFrom: %s <%s@%.80s>\nSubject: %s\nMessage-ID: <%lu@%.80s>\nX-IMAP: %010lu %010lu",
1971 pseudo_from,ctime (&now),
1972 tmp,pseudo_name,pseudo_from,mylocalhost (),pseudo_subject,
1973 (unsigned long) now,mylocalhost (),stream->uid_validity,
1974 stream->uid_last);
1975 for (s = hdr + strlen (hdr),i = 0; i < NUSERFLAGS; ++i)
1976 if (stream->user_flags[i])
1977 sprintf (s += strlen (s)," %s",stream->user_flags[i]);
1978 sprintf (s += strlen (s),"\nStatus: RO\n\n%s\n\n",pseudo_msg);
1979 return strlen (hdr); /* return header length */
1982 /* UNIX make status string
1983 * Accepts: MAIL stream
1984 * destination string to write
1985 * message cache entry
1986 * UID to write if non-zero (else use elt->private.uid)
1987 * non-zero flag to write UID (.LT. 0 to write UID base info too)
1988 * Returns: length of string
1991 unsigned long unix_xstatus (MAILSTREAM *stream,char *status,MESSAGECACHE *elt,
1992 unsigned long uid,long flag)
1994 char *t,stack[64];
1995 char *s = status;
1996 unsigned long n;
1997 int pad = 50;
1998 int sticky = uid ? T : !stream->uid_nosticky;
1999 /* This used to use sprintf(), but thanks to certain cretinous C libraries
2000 with horribly slow implementations of sprintf() I had to change it to this
2001 mess. At least it should be fast. */
2002 if ((flag < 0) && sticky) { /* need to write X-IMAPbase: header? */
2003 *s++ = 'X'; *s++ = '-'; *s++ = 'I'; *s++ = 'M'; *s++ = 'A'; *s++ = 'P';
2004 *s++ = 'b'; *s++ = 'a'; *s++ = 's'; *s++ = 'e'; *s++ = ':'; *s++ = ' ';
2005 t = stack;
2006 n = stream->uid_validity; /* push UID validity digits on the stack */
2007 do *t++ = (char) (n % 10) + '0';
2008 while (n /= 10);
2009 /* pop UID validity digits from stack */
2010 while (t > stack) *s++ = *--t;
2011 *s++ = ' ';
2012 n = stream->uid_last; /* push UID last digits on the stack */
2013 do *t++ = (char) (n % 10) + '0';
2014 while (n /= 10);
2015 /* pop UID last digits from stack */
2016 while (t > stack) *s++ = *--t;
2017 for (n = 0; n < NUSERFLAGS; ++n) if (t = stream->user_flags[n])
2018 for (*s++ = ' '; *t; *s++ = *t++);
2019 *s++ = '\n';
2020 pad += 30; /* increased padding if have IMAPbase */
2022 *s++ = 'S'; *s++ = 't'; *s++ = 'a'; *s++ = 't'; *s++ = 'u'; *s++ = 's';
2023 *s++ = ':'; *s++ = ' ';
2024 if (elt->seen) *s++ = 'R';
2025 /* only write O if have a UID */
2026 if (flag && (!elt->recent || !LOCAL->appending)) *s++ = 'O';
2027 *s++ = '\n';
2028 *s++ = 'X'; *s++ = '-'; *s++ = 'S'; *s++ = 't'; *s++ = 'a'; *s++ = 't';
2029 *s++ = 'u'; *s++ = 's'; *s++ = ':'; *s++ = ' ';
2030 if (elt->deleted) *s++ = 'D';
2031 if (elt->flagged) *s++ = 'F';
2032 if (elt->answered) *s++ = 'A';
2033 if (elt->draft) *s++ = 'T';
2034 *s++ = '\n';
2036 if (sticky) { /* only do this if UIDs sticky */
2037 *s++ = 'X'; *s++ = '-'; *s++ = 'K'; *s++ = 'e'; *s++ = 'y'; *s++ = 'w';
2038 *s++ = 'o'; *s++ = 'r'; *s++ = 'd'; *s++ = 's'; *s++ = ':';
2039 if (n = elt->user_flags) do {
2040 *s++ = ' ';
2041 for (t = stream->user_flags[find_rightmost_bit (&n)]; *t; *s++ = *t++);
2042 } while (n);
2043 n = s - status; /* get size of stuff so far */
2044 /* pad X-Keywords to make size constant */
2045 if (n < pad) for (n = pad - n; n > 0; --n) *s++ = ' ';
2046 *s++ = '\n';
2047 if (flag) { /* want to include UID? */
2048 t = stack;
2049 /* push UID digits on the stack */
2050 n = uid ? uid : elt->private.uid;
2051 do *t++ = (char) (n % 10) + '0';
2052 while (n /= 10);
2053 *s++ = 'X'; *s++ = '-'; *s++ = 'U'; *s++ = 'I'; *s++ = 'D'; *s++ = ':';
2054 *s++ = ' ';
2055 /* pop UID from stack */
2056 while (t > stack) *s++ = *--t;
2057 *s++ = '\n';
2060 *s++ = '\n'; *s = '\0'; /* end of extended message status */
2061 return s - status; /* return size of resulting string */
2064 /* Rewrite mailbox file
2065 * Accepts: MAIL stream, must be critical and locked
2066 * return pointer to number of expunged messages if want expunge
2067 * lock file name
2068 * expunge sequence, not deleted flag
2069 * Returns: T if success and mailbox unlocked, NIL if failure
2072 #define OVERFLOWBUFLEN 8192 /* initial overflow buffer length */
2074 long unix_rewrite (MAILSTREAM *stream,unsigned long *nexp,DOTLOCK *lock,
2075 long flags)
2077 MESSAGECACHE *elt;
2078 UNIXFILE f;
2079 char *s;
2080 time_t tp[2];
2081 long ret,flag;
2082 unsigned long i,j;
2083 unsigned long recent = stream->recent;
2084 unsigned long size = LOCAL->pseudo ? unix_pseudo (stream,LOCAL->buf) : 0;
2085 if (nexp) *nexp = 0; /* initially nothing expunged */
2086 /* calculate size of mailbox after rewrite */
2087 for (i = 1,flag = LOCAL->pseudo ? 1 : -1; i <= stream->nmsgs; i++) {
2088 elt = mail_elt (stream,i); /* get cache */
2089 if (!(nexp && elt->deleted && (flags ? elt->sequence : T))) {
2090 /* add RFC822 size of this message */
2091 size += elt->private.special.text.size + elt->private.spare.data +
2092 unix_xstatus (stream,LOCAL->buf,elt,NIL,flag) +
2093 elt->private.msg.text.text.size + 1;
2094 flag = 1; /* only count X-IMAPbase once */
2097 /* no messages, has a life, and no pseudo */
2098 if (!size && !mail_parameters (NIL,GET_USERHASNOLIFE,NIL)) {
2099 LOCAL->pseudo = T; /* so make a pseudo-message now */
2100 size = unix_pseudo (stream,LOCAL->buf);
2102 /* extend the file as necessary */
2103 if (ret = unix_extend (stream,size)) {
2104 /* Set up buffered I/O file structure
2105 * curpos current position being written through buffering
2106 * filepos current position being written physically to the disk
2107 * bufpos current position being written in the buffer
2108 * protect current maximum position that can be written to the disk
2109 * before buffering is forced
2110 * The code tries to buffer so that that disk is written in multiples of
2111 * OVERBLOWBUFLEN bytes.
2113 f.stream = stream; /* note mail stream */
2114 f.curpos = f.filepos = 0; /* start of file */
2115 f.protect = stream->nmsgs ? /* initial protection pointer */
2116 mail_elt (stream,1)->private.special.offset : 8192;
2117 f.bufpos = f.buf = (char *) fs_get (f.buflen = OVERFLOWBUFLEN);
2119 if (LOCAL->pseudo) /* update pseudo-header */
2120 unix_write (&f,LOCAL->buf,unix_pseudo (stream,LOCAL->buf));
2121 /* loop through all messages */
2122 for (i = 1,flag = LOCAL->pseudo ? 1 : -1; i <= stream->nmsgs;) {
2123 elt = mail_elt (stream,i);/* get cache */
2124 /* expunge this message? */
2125 if (nexp && elt->deleted && (flags ? elt->sequence : T)) {
2126 /* one less recent message */
2127 if (elt->recent) --recent;
2128 mail_expunged(stream,i);/* notify upper levels */
2129 ++*nexp; /* count up one more expunged message */
2131 else { /* preserve this message */
2132 i++; /* advance to next message */
2133 if ((flag < 0) || /* need to rewrite message? */
2134 elt->private.dirty || (f.curpos != elt->private.special.offset) ||
2135 (elt->private.msg.header.text.size !=
2136 (elt->private.spare.data +
2137 unix_xstatus (stream,LOCAL->buf,elt,NIL,flag)))) {
2138 unsigned long newoffset = f.curpos;
2139 /* yes, seek to internal header */
2140 lseek (LOCAL->fd,elt->private.special.offset,L_SET);
2141 read (LOCAL->fd,LOCAL->buf,elt->private.special.text.size);
2142 /* see if need to squeeze out a CR */
2143 if (LOCAL->buf[elt->private.special.text.size - 2] == '\r') {
2144 LOCAL->buf[--elt->private.special.text.size - 1] = '\n';
2145 --size; /* squeezed out a CR from PC */
2147 /* protection pointer moves to RFC822 header */
2148 f.protect = elt->private.special.offset +
2149 elt->private.msg.header.offset;
2150 /* write internal header */
2151 unix_write (&f,LOCAL->buf,elt->private.special.text.size);
2152 /* get RFC822 header */
2153 s = unix_header (stream,elt->msgno,&j,FT_INTERNAL);
2154 /* in case this got decremented */
2155 elt->private.msg.header.offset = elt->private.special.text.size;
2156 /* header size, sans trailing newline */
2157 if ((j < 2) || (s[j - 2] == '\n')) j--;
2158 /* this can happen if CRs were squeezed */
2159 if (j < elt->private.spare.data) {
2160 /* so fix up counts */
2161 size -= elt->private.spare.data - j;
2162 elt->private.spare.data = j;
2164 else if (j != elt->private.spare.data)
2165 fatal ("header size inconsistent");
2166 /* protection pointer moves to RFC822 text */
2167 f.protect = elt->private.special.offset +
2168 elt->private.msg.text.offset;
2169 unix_write (&f,s,j); /* write RFC822 header */
2170 /* write status and UID */
2171 unix_write (&f,LOCAL->buf,
2172 j = unix_xstatus (stream,LOCAL->buf,elt,NIL,flag));
2173 flag = 1; /* only write X-IMAPbase once */
2174 /* new file header size */
2175 elt->private.msg.header.text.size = elt->private.spare.data + j;
2177 /* did text move? */
2178 if (f.curpos != f.protect) {
2179 /* get message text */
2180 s = unix_text_work (stream,elt,&j,FT_INTERNAL);
2181 /* this can happen if CRs were squeezed */
2182 if (j < elt->private.msg.text.text.size) {
2183 /* so fix up counts */
2184 size -= elt->private.msg.text.text.size - j;
2185 elt->private.msg.text.text.size = j;
2187 /* can't happen it says here */
2188 else if (j > elt->private.msg.text.text.size)
2189 fatal ("text size inconsistent");
2190 /* new text offset, status/UID may change it */
2191 elt->private.msg.text.offset = f.curpos - newoffset;
2192 /* protection pointer moves to next message */
2193 f.protect = (i <= stream->nmsgs) ?
2194 mail_elt (stream,i)->private.special.offset : (f.curpos + j + 1);
2195 unix_write (&f,s,j);/* write text */
2196 /* write trailing newline */
2197 unix_write (&f,"\n",1);
2199 else { /* tie off header and status */
2200 unix_write (&f,NIL,NIL);
2201 /* protection pointer moves to next message */
2202 f.protect = (i <= stream->nmsgs) ?
2203 mail_elt (stream,i)->private.special.offset : size;
2204 /* locate end of message text */
2205 j = f.filepos + elt->private.msg.text.text.size;
2206 /* trailing newline already there? */
2207 if (f.protect == (j + 1)) f.curpos = f.filepos = f.protect;
2208 else { /* trailing newline missing, write it */
2209 f.curpos = f.filepos = j;
2210 unix_write (&f,"\n",1);
2213 /* new internal header offset */
2214 elt->private.special.offset = newoffset;
2215 elt->private.dirty =NIL;/* message is now clean */
2217 else { /* no need to rewrite this message */
2218 /* tie off previous message if needed */
2219 unix_write (&f,NIL,NIL);
2220 /* protection pointer moves to next message */
2221 f.protect = (i <= stream->nmsgs) ?
2222 mail_elt (stream,i)->private.special.offset : size;
2223 /* locate end of message text */
2224 j = f.filepos + elt->private.special.text.size +
2225 elt->private.msg.header.text.size +
2226 elt->private.msg.text.text.size;
2227 /* trailing newline already there? */
2228 if (f.protect == (j + 1)) f.curpos = f.filepos = f.protect;
2229 else { /* trailing newline missing, write it */
2230 f.curpos = f.filepos = j;
2231 unix_write (&f,"\n",1);
2237 unix_write (&f,NIL,NIL); /* tie off final message */
2238 if (size != f.filepos) fatal ("file size inconsistent");
2239 fs_give ((void **) &f.buf); /* free buffer */
2240 /* make sure tied off */
2241 ftruncate (LOCAL->fd,LOCAL->filesize = size);
2242 fsync (LOCAL->fd); /* make sure the updates take */
2243 if (size && (flag < 0)) fatal ("lost UID base information");
2244 /* no longer dirty */
2245 LOCAL->ddirty = LOCAL->dirty = NIL;
2246 /* notify upper level of new mailbox sizes */
2247 mail_exists (stream,stream->nmsgs);
2248 mail_recent (stream,recent);
2249 /* set atime to now, mtime a second earlier */
2250 tp[1] = (tp[0] = time (0)) - 1;
2251 /* set the times, note change */
2252 if (!utime (stream->mailbox,tp)) LOCAL->filetime = tp[1];
2253 close (LOCAL->fd); /* close and reopen file */
2254 if ((LOCAL->fd = open (stream->mailbox,O_RDWR,
2255 (long) mail_parameters (NIL,GET_MBXPROTECTION,NIL)))
2256 < 0) {
2257 sprintf (LOCAL->buf,"Mailbox open failed, aborted: %s",strerror (errno));
2258 MM_LOG (LOCAL->buf,ERROR);
2259 unix_abort (stream);
2261 dotlock_unlock (lock); /* flush the lock file */
2263 return ret; /* return state from algorithm */
2266 /* Extend UNIX mailbox file
2267 * Accepts: MAIL stream
2268 * new desired size
2269 * Return: T if success, else NIL
2272 long unix_extend (MAILSTREAM *stream,unsigned long size)
2274 unsigned long i = (size > LOCAL->filesize) ? size - LOCAL->filesize : 0;
2275 if (i) { /* does the mailbox need to grow? */
2276 if (i > LOCAL->buflen) { /* make sure have enough space */
2277 /* this user won the lottery all right */
2278 fs_give ((void **) &LOCAL->buf);
2279 LOCAL->buf = (char *) fs_get ((LOCAL->buflen = i) + 1);
2281 memset (LOCAL->buf,'\0',i); /* get a block of nulls */
2282 while (T) { /* until write successful or punt */
2283 lseek (LOCAL->fd,LOCAL->filesize,L_SET);
2284 if ((write (LOCAL->fd,LOCAL->buf,i) >= 0) && !fsync (LOCAL->fd)) break;
2285 else {
2286 long e = errno; /* note error before doing ftruncate */
2287 ftruncate (LOCAL->fd,LOCAL->filesize);
2288 if (MM_DISKERROR (stream,e,NIL)) {
2289 fsync (LOCAL->fd); /* user chose to punt */
2290 sprintf (LOCAL->buf,"Unable to extend mailbox: %s",strerror (e));
2291 if (!stream->silent) MM_LOG (LOCAL->buf,ERROR);
2292 return NIL;
2297 return LONGT;
2300 /* Write data to buffered file
2301 * Accepts: buffered file pointer
2302 * file data or NIL to indicate "flush buffer"
2303 * date size (ignored for "flush buffer")
2304 * Does not return until success
2307 void unix_write (UNIXFILE *f,char *buf,unsigned long size)
2309 unsigned long i,j,k;
2310 if (buf) { /* doing buffered write? */
2311 i = f->bufpos - f->buf; /* yes, get size of current buffer data */
2312 /* yes, have space in current buffer chunk? */
2313 if (j = i ? ((f->buflen - i) % OVERFLOWBUFLEN) : f->buflen) {
2314 /* yes, fill up buffer as much as we can */
2315 memcpy (f->bufpos,buf,k = min (j,size));
2316 f->bufpos += k; /* new buffer position */
2317 f->curpos += k; /* new current position */
2318 if (j -= k) return; /* all done if still have buffer free space */
2319 buf += k; /* full, get new unwritten data pointer */
2320 size -= k; /* new data size */
2321 i += k; /* new buffer data size */
2323 /* This chunk of the buffer is full. See if can make some space by
2324 * writing to the disk, if there's enough unprotected space to do so.
2325 * Try to fill out any unaligned chunk, along with any subsequent full
2326 * chunks that will fit in unprotected space.
2328 /* any unprotected space we can write to? */
2329 if (j = min (i,f->protect - f->filepos)) {
2330 /* yes, filepos not at chunk boundary? */
2331 if ((k = f->filepos % OVERFLOWBUFLEN) && ((k = OVERFLOWBUFLEN - k) < j))
2332 j -= k; /* yes, and can write out partial chunk */
2333 else k = 0; /* no partial chunk to write */
2334 /* if at least a chunk free, write that too */
2335 if (j > OVERFLOWBUFLEN) k += j - (j % OVERFLOWBUFLEN);
2336 if (k) { /* write data if there is anything we can */
2337 unix_phys_write (f,f->buf,k);
2338 /* slide buffer */
2339 if (i -= k) memmove (f->buf,f->buf + k,i);
2340 f->bufpos = f->buf + i; /* new end of buffer */
2344 /* Have flushed the buffer as best as possible. All done if no more
2345 * data to write. Otherwise, if the buffer is empty AND if the unwritten
2346 * data is larger than a chunk AND the unprotected space is also larger
2347 * than a chunk, then write as many chunks as we can directly from the
2348 * data. Buffer the rest, expanding the buffer as needed.
2350 if (size) { /* have more data that we need to buffer? */
2351 /* can write any of it to disk instead? */
2352 if ((f->bufpos == f->buf) &&
2353 ((j = min (f->protect - f->filepos,size)) > OVERFLOWBUFLEN)) {
2354 /* write as much as we can right now */
2355 unix_phys_write (f,buf,j -= (j % OVERFLOWBUFLEN));
2356 buf += j; /* new data pointer */
2357 size -= j; /* new data size */
2358 f->curpos += j; /* advance current pointer */
2360 if (size) { /* still have data that we need to buffer? */
2361 /* yes, need to expand the buffer? */
2362 if ((i = ((f->bufpos + size) - f->buf)) > f->buflen) {
2363 /* note current position in buffer */
2364 j = f->bufpos - f->buf;
2365 i += OVERFLOWBUFLEN; /* yes, grow another chunk */
2366 fs_resize ((void **) &f->buf,f->buflen = i - (i % OVERFLOWBUFLEN));
2367 /* in case buffer relocated */
2368 f->bufpos = f->buf + j;
2370 /* buffer remaining data */
2371 memcpy (f->bufpos,buf,size);
2372 f->bufpos += size; /* new end of buffer */
2373 f->curpos += size; /* advance current pointer */
2377 else { /* flush buffer to disk */
2378 unix_phys_write (f,f->buf,i = f->bufpos - f->buf);
2379 f->bufpos = f->buf; /* reset buffer */
2380 /* update positions */
2381 f->curpos = f->protect = f->filepos;
2385 /* Physical disk write
2386 * Accepts: buffered file pointer
2387 * buffer address
2388 * buffer size
2389 * Does not return until success
2392 void unix_phys_write (UNIXFILE *f,char *buf,size_t size)
2394 MAILSTREAM *stream = f->stream;
2395 /* write data at desired position */
2396 while (size && ((lseek (LOCAL->fd,f->filepos,L_SET) < 0) ||
2397 (write (LOCAL->fd,buf,size) < 0))) {
2398 int e;
2399 char tmp[MAILTMPLEN];
2400 sprintf (tmp,"Unable to write to mailbox: %s",strerror (e = errno));
2401 MM_LOG (tmp,ERROR);
2402 MM_DISKERROR (NIL,e,T); /* serious problem, must retry */
2404 f->filepos += size; /* update file position */
2407 /* MBOX mail routines */
2410 /* Driver dispatch used by MAIL */
2412 DRIVER mboxdriver = {
2413 "mbox", /* driver name */
2414 /* driver flags */
2415 DR_LOCAL|DR_MAIL|DR_LOCKING|DR_NONEWMAILRONLY,
2416 (DRIVER *) NIL, /* next driver */
2417 mbox_valid, /* mailbox is valid for us */
2418 unix_parameters, /* manipulate parameters */
2419 unix_scan, /* scan mailboxes */
2420 unix_list, /* find mailboxes */
2421 unix_lsub, /* find subscribed mailboxes */
2422 NIL, /* subscribe to mailbox */
2423 NIL, /* unsubscribe from mailbox */
2424 mbox_create, /* create mailbox */
2425 mbox_delete, /* delete mailbox */
2426 mbox_rename, /* rename mailbox */
2427 mbox_status, /* status of mailbox */
2428 mbox_open, /* open mailbox */
2429 unix_close, /* close mailbox */
2430 NIL, /* fetch message "fast" attributes */
2431 NIL, /* fetch message flags */
2432 NIL, /* fetch overview */
2433 NIL, /* fetch message structure */
2434 unix_header, /* fetch message header */
2435 unix_text, /* fetch message body */
2436 NIL, /* fetch partial message text */
2437 NIL, /* unique identifier */
2438 NIL, /* message number */
2439 NIL, /* modify flags */
2440 unix_flagmsg, /* per-message modify flags */
2441 NIL, /* search for message based on criteria */
2442 NIL, /* sort messages */
2443 NIL, /* thread messages */
2444 mbox_ping, /* ping mailbox to see if still alive */
2445 mbox_check, /* check for new messages */
2446 mbox_expunge, /* expunge deleted messages */
2447 unix_copy, /* copy messages to another mailbox */
2448 mbox_append, /* append string message to mailbox */
2449 NIL /* garbage collect stream */
2452 /* prototype stream */
2453 MAILSTREAM mboxproto = {&mboxdriver};
2455 /* MBOX mail validate mailbox
2456 * Accepts: mailbox name
2457 * Returns: our driver if name is valid, NIL otherwise
2460 DRIVER *mbox_valid (char *name)
2462 /* only INBOX, mbox must exist */
2463 if (!compare_cstring (name,"INBOX") && (unix_valid ("mbox") || !errno) &&
2464 (unix_valid (sysinbox()) || !errno || (errno == ENOENT)))
2465 return &mboxdriver;
2466 return NIL; /* can't win (yet, anyway) */
2469 /* MBOX mail create mailbox
2470 * Accepts: MAIL stream
2471 * mailbox name to create
2472 * Returns: T on success, NIL on failure
2475 long mbox_create (MAILSTREAM *stream,char *mailbox)
2477 char tmp[MAILTMPLEN];
2478 if (!compare_cstring (mailbox,"INBOX")) return unix_create (NIL,"mbox");
2479 sprintf (tmp,"Can't create non-INBOX name as mbox: %.80s",mailbox);
2480 MM_LOG (tmp,ERROR);
2481 return NIL;
2485 /* MBOX mail delete mailbox
2486 * Accepts: MAIL stream
2487 * mailbox name to delete
2488 * Returns: T on success, NIL on failure
2491 long mbox_delete (MAILSTREAM *stream,char *mailbox)
2493 return mbox_rename (stream,mailbox,NIL);
2497 /* MBOX mail rename mailbox
2498 * Accepts: MAIL stream
2499 * old mailbox name
2500 * new mailbox name (or NIL for delete)
2501 * Returns: T on success, NIL on failure
2504 long mbox_rename (MAILSTREAM *stream,char *old,char *newname)
2506 char tmp[MAILTMPLEN];
2507 long ret = unix_rename (stream,"~/mbox",newname);
2508 /* recreate file if renamed INBOX */
2509 if (ret) unix_create (NIL,"mbox");
2510 else MM_LOG (tmp,ERROR); /* log error */
2511 return ret; /* return success */
2514 /* MBOX Mail status
2515 * Accepts: mail stream
2516 * mailbox name
2517 * status flags
2518 * Returns: T on success, NIL on failure
2521 long mbox_status (MAILSTREAM *stream,char *mbx,long flags)
2523 MAILSTATUS status;
2524 unsigned long i;
2525 MAILSTREAM *tstream = NIL;
2526 MAILSTREAM *systream = NIL;
2527 /* make temporary stream (unless this mbx) */
2528 if (!stream && !(stream = tstream =
2529 mail_open (NIL,mbx,OP_READONLY|OP_SILENT))) return NIL;
2530 status.flags = flags; /* return status values */
2531 status.messages = stream->nmsgs;
2532 status.recent = stream->recent;
2533 if (flags & SA_UNSEEN) /* must search to get unseen messages */
2534 for (i = 1,status.unseen = 0; i <= stream->nmsgs; i++)
2535 if (!mail_elt (stream,i)->seen) status.unseen++;
2536 status.uidnext = stream->uid_last + 1;
2537 status.uidvalidity = stream->uid_validity;
2538 if (!status.recent && /* calculate post-snarf results */
2539 (systream = mail_open (NIL,sysinbox (),OP_READONLY|OP_SILENT))) {
2540 status.messages += systream->nmsgs;
2541 status.recent += systream->recent;
2542 if (flags & SA_UNSEEN) /* must search to get unseen messages */
2543 for (i = 1; i <= systream->nmsgs; i++)
2544 if (!mail_elt (systream,i)->seen) status.unseen++;
2545 /* kludge but probably good enough */
2546 status.uidnext += systream->nmsgs;
2548 MM_STATUS(stream,mbx,&status);/* pass status to main program */
2549 if (tstream) mail_close (tstream);
2550 if (systream) mail_close (systream);
2551 return T; /* success */
2554 /* MBOX mail open
2555 * Accepts: stream to open
2556 * Returns: stream on success, NIL on failure
2559 MAILSTREAM *mbox_open (MAILSTREAM *stream)
2561 unsigned long i = 1;
2562 unsigned long recent = 0;
2563 /* return prototype for OP_PROTOTYPE call */
2564 if (!stream) return &mboxproto;
2565 /* change mailbox file name */
2566 fs_give ((void **) &stream->mailbox);
2567 stream->mailbox = cpystr ("mbox");
2568 /* open mailbox, snarf new mail */
2569 if (!(unix_open (stream) && mbox_ping (stream))) return NIL;
2570 stream->inbox = T; /* mark that this is an INBOX */
2571 /* notify upper level of mailbox sizes */
2572 mail_exists (stream,stream->nmsgs);
2573 while (i <= stream->nmsgs) if (mail_elt (stream,i++)->recent) ++recent;
2574 mail_recent (stream,recent); /* including recent messages */
2575 return stream;
2578 /* MBOX mail ping mailbox
2579 * Accepts: MAIL stream
2580 * Returns: T if stream alive, else NIL
2581 * No-op for readonly files, since read/writer can expunge it from under us!
2584 static int snarfed = 0; /* number of snarfs */
2586 long mbox_ping (MAILSTREAM *stream)
2588 int sfd;
2589 unsigned long size;
2590 struct stat sbuf;
2591 char *s;
2592 DOTLOCK lock,lockx;
2593 /* time to try snarf and sysinbox non-empty? */
2594 if (LOCAL && !stream->rdonly && !stream->lock &&
2595 (time (0) >= (LOCAL->lastsnarf +
2596 (long) mail_parameters (NIL,GET_SNARFINTERVAL,NIL))) &&
2597 !stat (sysinbox (),&sbuf) && sbuf.st_size) {
2598 MM_CRITICAL (stream); /* yes, go critical */
2599 /* open and lock sysinbox */
2600 if ((sfd = unix_lock (sysinbox (),O_RDWR,
2601 (long) mail_parameters (NIL,GET_MBXPROTECTION,NIL),
2602 &lockx,LOCK_EX)) >= 0) {
2603 /* locked sysinbox in good format? */
2604 if (fstat (sfd,&sbuf) || !(size = sbuf.st_size) ||
2605 !unix_isvalid_fd (sfd)) {
2606 sprintf (LOCAL->buf,"Mail drop %s is not in standard Unix format",
2607 sysinbox ());
2608 MM_LOG (LOCAL->buf,ERROR);
2610 /* sysinbox good, parse and excl-lock mbox */
2611 else if (unix_parse (stream,&lock,LOCK_EX)) {
2612 lseek (sfd,0,L_SET); /* read entire sysinbox into memory */
2613 read (sfd,s = (char *) fs_get (size + 1),size);
2614 s[size] = '\0'; /* tie it off */
2615 /* append to end of mbox */
2616 lseek (LOCAL->fd,LOCAL->filesize,L_SET);
2618 /* copy to mbox */
2619 if ((write (LOCAL->fd,s,size) < 0) || fsync (LOCAL->fd)) {
2620 sprintf (LOCAL->buf,"New mail move failed: %s",strerror (errno));
2621 MM_LOG (LOCAL->buf,WARN);
2622 /* revert mbox to previous size */
2623 ftruncate (LOCAL->fd,LOCAL->filesize);
2625 /* sysinbox better not have changed */
2626 else if (fstat (sfd,&sbuf) || (size != sbuf.st_size)) {
2627 sprintf (LOCAL->buf,"Mail drop %s lock failure, old=%lu now=%lu",
2628 sysinbox (),size,(unsigned long) sbuf.st_size);
2629 MM_LOG (LOCAL->buf,ERROR);
2630 /* revert mbox to previous size */
2631 ftruncate (LOCAL->fd,LOCAL->filesize);
2632 /* Believe it or not, a Singaporean government system actually had
2633 * symlinks from /var/mail/user to ~user/mbox. To compound this
2634 * error, they used an SVR4 system; BSD and OSF locks would have
2635 * prevented it but not SVR4 locks.
2637 if (!fstat (sfd,&sbuf) && (size == sbuf.st_size))
2638 syslog (LOG_ALERT,"File %s and %s are the same file!",
2639 sysinbox (),stream->mailbox);
2641 else { /* data copied OK */
2642 ftruncate (sfd,0); /* truncate sysinbox to zero bytes */
2643 if (!snarfed++) { /* have we snarfed before? */
2644 /* syslog if server, else user log */
2645 sprintf (LOCAL->buf,"Moved %lu bytes of new mail to %s from %s",
2646 size,stream->mailbox,sysinbox ());
2647 if (strcmp ((char *) mail_parameters (NIL,GET_SERVICENAME,NIL),
2648 "unknown"))
2649 syslog (LOG_INFO,"%s host= %s",LOCAL->buf,tcp_clienthost ());
2650 else MM_LOG (LOCAL->buf,WARN);
2653 /* done with sysinbox text */
2654 fs_give ((void **) &s);
2655 /* all done with mbox */
2656 unix_unlock (LOCAL->fd,stream,&lock);
2657 mail_unlock (stream); /* unlock the stream */
2658 MM_NOCRITICAL (stream); /* done with critical */
2660 /* all done with sysinbox */
2661 unix_unlock (sfd,NIL,&lockx);
2663 MM_NOCRITICAL (stream); /* done with critical */
2664 LOCAL->lastsnarf = time (0);/* note time of last snarf */
2666 return unix_ping (stream); /* do the unix routine now */
2669 /* MBOX mail check mailbox
2670 * Accepts: MAIL stream
2673 void mbox_check (MAILSTREAM *stream)
2675 /* do local ping, then do unix routine */
2676 if (mbox_ping (stream)) unix_check (stream);
2680 /* MBOX mail expunge mailbox
2681 * Accepts: MAIL stream
2682 * sequence to expunge if non-NIL
2683 * expunge options
2684 * Returns: T, always
2687 long mbox_expunge (MAILSTREAM *stream,char *sequence,long options)
2689 long ret = unix_expunge (stream,sequence,options);
2690 mbox_ping (stream); /* do local ping */
2691 return ret;
2695 /* MBOX mail append message from stringstruct
2696 * Accepts: MAIL stream
2697 * destination mailbox
2698 * append callback
2699 * data for callback
2700 * Returns: T if append successful, else NIL
2703 long mbox_append (MAILSTREAM *stream,char *mailbox,append_t af,void *data)
2705 char tmp[MAILTMPLEN];
2706 if (mbox_valid (mailbox)) return unix_append (stream,"mbox",af,data);
2707 sprintf (tmp,"Can't append to that name: %.80s",mailbox);
2708 MM_LOG (tmp,ERROR);
2709 return NIL;