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