* Rewrite support for specific SSL encryption protocols, including
[alpine.git] / imap / src / c-client / mail.c
blob8f0373ed404553b97d61e6affde5d51c76bd5431
1 /* ========================================================================
2 * Copyright 2008-2010 Mark Crispin
3 * ========================================================================
4 */
6 /*
7 * Program: Mailbox Access routines
9 * Author: Mark Crispin
11 * Date: 22 November 1989
12 * Last Edited: 15 November 2010
14 * Previous versions of this file were
16 * Copyright 1988-2008 University of Washington
18 * Licensed under the Apache License, Version 2.0 (the "License");
19 * you may not use this file except in compliance with the License.
20 * You may obtain a copy of the License at
22 * http://www.apache.org/licenses/LICENSE-2.0
27 #include <ctype.h>
28 #include <stdio.h>
29 #include <time.h>
30 #include "c-client.h"
32 char *Panda_copyright = "Copyright 2008-2010 Mark Crispin\n";
34 char *UW_copyright = "Copyright 1988-2008 University of Washington\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n";
36 /* c-client global data */
37 /* version of this library */
38 static char *mailcclientversion = CCLIENTVERSION;
39 /* Minimum in range of encryption supported */
40 static int encryption_range_min = 0;
41 /* Maximum in range of encryption supported */
42 static int encryption_range_max = 0;
43 /* app identity */
44 static IDLIST *idapp = NIL;
45 /* list of mail drivers */
46 static DRIVER *maildrivers = NIL;
47 /* list of authenticators */
48 static AUTHENTICATOR *mailauthenticators = NIL;
49 /* SSL driver pointer */
50 static NETDRIVER *mailssldriver = NIL;
51 /* pointer to alternate gets function */
52 static mailgets_t mailgets = NIL;
53 /* pointer to read progress function */
54 static readprogress_t mailreadprogress = NIL;
55 /* mail cache manipulation function */
56 static mailcache_t mailcache = mm_cache;
57 /* RFC-822 output generator */
58 static rfc822out_t mail822out = NIL;
59 /* RFC-822 output generator (new style) */
60 static rfc822outfull_t mail822outfull = NIL;
61 /* SMTP verbose callback */
62 static smtpverbose_t mailsmtpverbose = mm_dlog;
63 /* proxy copy routine */
64 static mailproxycopy_t mailproxycopy = NIL;
65 /* RFC-822 external line parse */
66 static parseline_t mailparseline = NIL;
67 /* RFC-822 external phrase parser */
68 static parsephrase_t mailparsephrase = NIL;
69 static kinit_t mailkinit = NIL; /* application kinit callback */
70 /* note network sent command */
71 static sendcommand_t mailsendcommand = NIL;
72 /* newsrc file name decision function */
73 static newsrcquery_t mailnewsrcquery = NIL;
74 /* ACL results callback */
75 static getacl_t mailaclresults = NIL;
76 /* list rights results callback */
77 static listrights_t maillistrightsresults = NIL;
78 /* my rights results callback */
79 static myrights_t mailmyrightsresults = NIL;
80 /* quota results callback */
81 static quota_t mailquotaresults = NIL;
82 /* quota root results callback */
83 static quotaroot_t mailquotarootresults = NIL;
84 /* sorted results callback */
85 static sortresults_t mailsortresults = NIL;
86 /* threaded results callback */
87 static threadresults_t mailthreadresults = NIL;
88 /* COPY UID results */
89 static copyuid_t mailcopyuid = NIL;
90 /* APPEND UID results */
91 static appenduid_t mailappenduid = NIL;
92 /* free elt extra stuff callback */
93 static freeeltsparep_t mailfreeeltsparep = NIL;
94 /* free envelope extra stuff callback */
95 static freeenvelopesparep_t mailfreeenvelopesparep = NIL;
96 /* free body extra stuff callback */
97 static freebodysparep_t mailfreebodysparep = NIL;
98 /* free stream extra stuff callback */
99 static freestreamsparep_t mailfreestreamsparep = NIL;
100 /* SSL start routine */
101 static sslstart_t mailsslstart = NIL;
102 /* SSL certificate query */
103 static sslcertificatequery_t mailsslcertificatequery = NIL;
104 /* SSL client certificate */
105 static sslclientcert_t mailsslclientcert = NIL;
106 /* SSL client private key */
107 static sslclientkey_t mailsslclientkey = NIL;
108 /* SSL failure notify */
109 static sslfailure_t mailsslfailure = NIL;
110 /* snarf interval */
111 static long mailsnarfinterval = 60;
112 /* snarf preservation */
113 static long mailsnarfpreserve = NIL;
114 /* newsrc name uses canonical host */
115 static long mailnewsrccanon = LONGT;
117 /* supported threaders */
118 static THREADER mailthreadordsub = {
119 "ORDEREDSUBJECT",mail_thread_orderedsubject,NIL
121 static THREADER mailthreadlist = {
122 "REFERENCES",mail_thread_references,&mailthreadordsub
125 /* server name */
126 static char *servicename = "unknown";
127 /* server externally-set authentication ID */
128 static char *externalauthid = NIL;
129 static int expungeatping = T; /* mail_ping() may call mm_expunged() */
130 static int trysslfirst = NIL; /* always try SSL first */
131 static int notimezones = NIL; /* write timezones in "From " header */
132 static int trustdns = T; /* do DNS canonicalization */
133 static int saslusesptrname = T; /* SASL uses name from DNS PTR lookup */
134 /* trustdns also must be set */
135 static int debugsensitive = NIL;/* debug telemetry includes sensitive data */
137 /* Default mail cache handler
138 * Accepts: pointer to cache handle
139 * message number
140 * caching function
141 * Returns: cache data
144 void *mm_cache (MAILSTREAM *stream,unsigned long msgno,long op)
146 size_t n;
147 void *ret = NIL;
148 unsigned long i;
149 switch ((int) op) { /* what function? */
150 case CH_INIT: /* initialize cache */
151 if (stream->cache) { /* flush old cache contents */
152 while (stream->cachesize) {
153 mm_cache (stream,stream->cachesize,CH_FREE);
154 mm_cache (stream,stream->cachesize--,CH_FREESORTCACHE);
156 fs_give ((void **) &stream->cache);
157 fs_give ((void **) &stream->sc);
158 stream->nmsgs = 0; /* can't have any messages now */
160 break;
161 case CH_SIZE: /* (re-)size the cache */
162 if (!stream->cache) { /* have a cache already? */
163 /* no, create new cache */
164 n = (stream->cachesize = msgno + CACHEINCREMENT) * sizeof (void *);
165 stream->cache = (MESSAGECACHE **) memset (fs_get (n),0,n);
166 stream->sc = (SORTCACHE **) memset (fs_get (n),0,n);
168 /* is existing cache size large neough */
169 else if (msgno > stream->cachesize) {
170 i = stream->cachesize; /* remember old size */
171 n = (stream->cachesize = msgno + CACHEINCREMENT) * sizeof (void *);
172 fs_resize ((void **) &stream->cache,n);
173 fs_resize ((void **) &stream->sc,n);
174 while (i < stream->cachesize) {
175 stream->cache[i] = NIL;
176 stream->sc[i++] = NIL;
179 break;
181 case CH_MAKEELT: /* return elt, make if necessary */
182 if (!stream->cache[msgno - 1])
183 stream->cache[msgno - 1] = mail_new_cache_elt (msgno);
184 /* falls through */
185 case CH_ELT: /* return elt */
186 ret = (void *) stream->cache[msgno - 1];
187 break;
188 case CH_SORTCACHE: /* return sortcache entry, make if needed */
189 if (!stream->sc[msgno - 1]) stream->sc[msgno - 1] =
190 (SORTCACHE *) memset (fs_get (sizeof (SORTCACHE)),0,sizeof (SORTCACHE));
191 ret = (void *) stream->sc[msgno - 1];
192 break;
193 case CH_FREE: /* free elt */
194 mail_free_elt (&stream->cache[msgno - 1]);
195 break;
196 case CH_FREESORTCACHE:
197 if (stream->sc[msgno - 1]) {
198 if (stream->sc[msgno - 1]->from)
199 fs_give ((void **) &stream->sc[msgno - 1]->from);
200 if (stream->sc[msgno - 1]->to)
201 fs_give ((void **) &stream->sc[msgno - 1]->to);
202 if (stream->sc[msgno - 1]->cc)
203 fs_give ((void **) &stream->sc[msgno - 1]->cc);
204 if (stream->sc[msgno - 1]->subject)
205 fs_give ((void **) &stream->sc[msgno - 1]->subject);
206 if (stream->sc[msgno - 1]->unique &&
207 (stream->sc[msgno - 1]->unique != stream->sc[msgno - 1]->message_id))
208 fs_give ((void **) &stream->sc[msgno - 1]->unique);
209 if (stream->sc[msgno - 1]->message_id)
210 fs_give ((void **) &stream->sc[msgno - 1]->message_id);
211 if (stream->sc[msgno - 1]->references)
212 mail_free_stringlist (&stream->sc[msgno - 1]->references);
213 fs_give ((void **) &stream->sc[msgno - 1]);
215 break;
216 case CH_EXPUNGE: /* expunge cache slot */
217 for (i = msgno - 1; msgno < stream->nmsgs; i++,msgno++) {
218 if ((stream->cache[i] = stream->cache[msgno]) != NULL)
219 stream->cache[i]->msgno = msgno;
220 stream->sc[i] = stream->sc[msgno];
222 stream->cache[i] = NIL; /* top of cache goes away */
223 stream->sc[i] = NIL;
224 break;
225 default:
226 fatal ("Bad mm_cache op");
227 break;
229 return ret;
232 /* Dummy string driver for complete in-memory strings */
234 static void mail_string_init (STRING *s,void *data,unsigned long size);
235 static char mail_string_next (STRING *s);
236 static void mail_string_setpos (STRING *s,unsigned long i);
238 STRINGDRIVER mail_string = {
239 mail_string_init, /* initialize string structure */
240 mail_string_next, /* get next byte in string structure */
241 mail_string_setpos /* set position in string structure */
245 /* Initialize mail string structure for in-memory string
246 * Accepts: string structure
247 * pointer to string
248 * size of string
251 static void mail_string_init (STRING *s,void *data,unsigned long size)
253 /* set initial string pointers */
254 s->chunk = s->curpos = (char *) (s->data = data);
255 /* and sizes */
256 s->size = s->chunksize = s->cursize = size;
257 s->data1 = s->offset = 0; /* never any offset */
261 /* Get next character from string
262 * Accepts: string structure
263 * Returns: character, string structure chunk refreshed
266 static char mail_string_next (STRING *s)
268 return *s->curpos++; /* return the last byte */
272 /* Set string pointer position
273 * Accepts: string structure
274 * new position
277 static void mail_string_setpos (STRING *s,unsigned long i)
279 s->curpos = s->chunk + i; /* set new position */
280 s->cursize = s->chunksize - i;/* and new size */
283 /* Mail routines
285 * mail_xxx routines are the interface between this module and the outside
286 * world. Only these routines should be referenced by external callers.
288 * Note that there is an important difference between a "sequence" and a
289 * "message #" (msgno). A sequence is a string representing a sequence in
290 * {"n", "n:m", or combination separated by commas} format, whereas a msgno
291 * is a single integer.
295 /* Mail version check
296 * Accepts: version
299 void mail_versioncheck (char *version)
301 /* attempt to protect again wrong .h */
302 if (strcmp (version,mailcclientversion)) {
303 char tmp[MAILTMPLEN];
304 sprintf (tmp,"c-client library version skew, app=%.100s library=%.100s",
305 version,mailcclientversion);
306 fatal (tmp);
311 /* Mail link driver
312 * Accepts: driver to add to list
315 void mail_link (DRIVER *driver)
317 DRIVER **d = &maildrivers;
318 while (*d) d = &(*d)->next; /* find end of list of drivers */
319 *d = driver; /* put driver at the end */
320 driver->next = NIL; /* this driver is the end of the list */
323 /* Mail manipulate driver parameters
324 * Accepts: mail stream
325 * function code
326 * function-dependent value
327 * Returns: function-dependent return value
330 void *mail_parameters (MAILSTREAM *stream,long function,void *value)
332 void *r,*ret = NIL;
333 DRIVER *d;
334 AUTHENTICATOR *a;
335 switch ((int) function) {
336 case SET_INBOXPATH:
337 fatal ("SET_INBOXPATH not permitted");
338 case GET_INBOXPATH:
339 if ((stream || (stream = mail_open (NIL,"INBOX",OP_PROTOTYPE))) &&
340 stream->dtb) ret = (*stream->dtb->parameters) (function,value);
341 break;
342 case SET_THREADERS:
343 fatal ("SET_THREADERS not permitted");
344 case GET_THREADERS: /* use stream dtb instead of global */
345 ret = (stream && stream->dtb) ?
346 /* KLUDGE ALERT: note stream passed as value */
347 (*stream->dtb->parameters) (function,stream) : (void *) &mailthreadlist;
348 break;
349 case SET_NAMESPACE:
350 fatal ("SET_NAMESPACE not permitted");
351 break;
352 case SET_NEWSRC: /* too late on open stream */
353 if (stream && stream->dtb && (stream != ((*stream->dtb->open) (NIL))))
354 fatal ("SET_NEWSRC not permitted");
355 else ret = env_parameters (function,value);
356 break;
357 case GET_NAMESPACE:
358 ret = (stream && stream->dtb && !(stream->dtb->flags & DR_LOCAL)) ?
359 /* KLUDGE ALERT: note stream passed as value */
360 (*stream->dtb->parameters) (function,stream) :
361 env_parameters (function,value);
362 break;
363 case GET_NEWSRC: /* use stream dtb instead of environment */
364 ret = (stream && stream->dtb) ?
365 /* KLUDGE ALERT: note stream passed as value */
366 (*stream->dtb->parameters) (function,stream) :
367 env_parameters (function,value);
368 break;
369 case ENABLE_DEBUG:
370 fatal ("ENABLE_DEBUG not permitted");
371 case DISABLE_DEBUG:
372 fatal ("DISABLE_DEBUG not permitted");
373 case SET_DIRFMTTEST:
374 fatal ("SET_DIRFMTTEST not permitted");
375 case GET_DIRFMTTEST:
376 if (!(stream && stream->dtb &&
377 (ret = (*stream->dtb->parameters) (function,NIL))))
378 fatal ("GET_DIRFMTTEST not permitted");
379 break;
381 case SET_DRIVERS:
382 fatal ("SET_DRIVERS not permitted");
383 case GET_DRIVERS: /* always return global */
384 ret = (void *) maildrivers;
385 break;
386 case SET_DRIVER:
387 fatal ("SET_DRIVER not permitted");
388 case GET_DRIVER:
389 for (d = maildrivers; d && compare_cstring (d->name,(char *) value);
390 d = d->next);
391 ret = (void *) d;
392 break;
393 case ENABLE_DRIVER:
394 for (d = maildrivers; d && compare_cstring (d->name,(char *) value);
395 d = d->next);
396 if ((ret = (void *) d) != NULL) d->flags &= ~DR_DISABLE;
397 break;
398 case DISABLE_DRIVER:
399 for (d = maildrivers; d && compare_cstring (d->name,(char *) value);
400 d = d->next);
401 if ((ret = (void *) d) != NULL) d->flags |= DR_DISABLE;
402 break;
403 case ENABLE_AUTHENTICATOR:
404 for (a = mailauthenticators;/* scan authenticators */
405 a && compare_cstring (a->name,(char *) value); a = a->next);
406 if ((ret = (void *) a) != NULL) a->flags &= ~AU_DISABLE;
407 break;
408 case DISABLE_AUTHENTICATOR:
409 for (a = mailauthenticators;/* scan authenticators */
410 a && compare_cstring (a->name,(char *) value); a = a->next);
411 if ((ret = (void *) a) != NULL) a->flags |= AU_DISABLE;
412 break;
413 case UNHIDE_AUTHENTICATOR:
414 for (a = mailauthenticators;/* scan authenticators */
415 a && compare_cstring (a->name,(char *) value); a = a->next);
416 if ((ret = (void *) a) != NULL) a->flags &= ~AU_HIDE;
417 break;
418 case HIDE_AUTHENTICATOR:
419 for (a = mailauthenticators;/* scan authenticators */
420 a && compare_cstring (a->name,(char *) value); a = a->next);
421 if ((ret = (void *) a) != NULL) a->flags |= AU_HIDE;
422 break;
423 case SET_EXTERNALAUTHID:
424 if (value) { /* setting external authentication ID */
425 externalauthid = cpystr ((char *) value);
426 mail_parameters (NIL,UNHIDE_AUTHENTICATOR,"EXTERNAL");
428 else { /* clearing external authentication ID */
429 if (externalauthid) fs_give ((void **) &externalauthid);
430 mail_parameters (NIL,HIDE_AUTHENTICATOR,"EXTERNAL");
432 case GET_EXTERNALAUTHID:
433 ret = (void *) externalauthid;
434 break;
436 case SET_GETS:
437 mailgets = (mailgets_t) value;
438 case GET_GETS:
439 ret = (void *) mailgets;
440 break;
441 case SET_READPROGRESS:
442 mailreadprogress = (readprogress_t) value;
443 case GET_READPROGRESS:
444 ret = (void *) mailreadprogress;
445 break;
446 case SET_CACHE:
447 mailcache = (mailcache_t) value;
448 case GET_CACHE:
449 ret = (void *) mailcache;
450 break;
451 case SET_RFC822OUTPUT:
452 mail822out = (rfc822out_t) value;
453 case GET_RFC822OUTPUT:
454 ret = (void *) mail822out;
455 break;
456 case SET_RFC822OUTPUTFULL:
457 mail822outfull = (rfc822outfull_t) value;
458 case GET_RFC822OUTPUTFULL:
459 ret = (void *) mail822outfull;
460 break;
461 case SET_SMTPVERBOSE:
462 mailsmtpverbose = (smtpverbose_t) value;
463 case GET_SMTPVERBOSE:
464 ret = (void *) mailsmtpverbose;
465 break;
466 case SET_MAILPROXYCOPY:
467 mailproxycopy = (mailproxycopy_t) value;
468 case GET_MAILPROXYCOPY:
469 ret = (void *) mailproxycopy;
470 break;
471 case SET_PARSELINE:
472 mailparseline = (parseline_t) value;
473 case GET_PARSELINE:
474 ret = (void *) mailparseline;
475 break;
476 case SET_PARSEPHRASE:
477 mailparsephrase = (parsephrase_t) value;
478 case GET_PARSEPHRASE:
479 ret = (void *) mailparsephrase;
480 break;
481 case SET_NEWSRCQUERY:
482 mailnewsrcquery = (newsrcquery_t) value;
483 case GET_NEWSRCQUERY:
484 ret = (void *) mailnewsrcquery;
485 break;
486 case SET_NEWSRCCANONHOST:
487 mailnewsrccanon = (long) value;
488 case GET_NEWSRCCANONHOST:
489 ret = (void *) mailnewsrccanon;
490 break;
492 case SET_COPYUID:
493 mailcopyuid = (copyuid_t) value;
494 case GET_COPYUID:
495 ret = (void *) mailcopyuid;
496 break;
497 case SET_APPENDUID:
498 mailappenduid = (appenduid_t) value;
499 case GET_APPENDUID:
500 ret = (void *) mailappenduid;
501 break;
502 case SET_FREEENVELOPESPAREP:
503 mailfreeenvelopesparep = (freeenvelopesparep_t) value;
504 case GET_FREEENVELOPESPAREP:
505 ret = (void *) mailfreeenvelopesparep;
506 break;
507 case SET_FREEELTSPAREP:
508 mailfreeeltsparep = (freeeltsparep_t) value;
509 case GET_FREEELTSPAREP:
510 ret = (void *) mailfreeeltsparep;
511 break;
512 case SET_FREESTREAMSPAREP:
513 mailfreestreamsparep = (freestreamsparep_t) value;
514 case GET_FREESTREAMSPAREP:
515 ret = (void *) mailfreestreamsparep;
516 break;
517 case SET_FREEBODYSPAREP:
518 mailfreebodysparep = (freebodysparep_t) value;
519 case GET_FREEBODYSPAREP:
520 ret = (void *) mailfreebodysparep;
521 break;
523 case SET_SSLSTART:
524 mailsslstart = (sslstart_t) value;
525 case GET_SSLSTART:
526 ret = (void *) mailsslstart;
527 break;
528 case SET_SSLCERTIFICATEQUERY:
529 mailsslcertificatequery = (sslcertificatequery_t) value;
530 case GET_SSLCERTIFICATEQUERY:
531 ret = (void *) mailsslcertificatequery;
532 break;
533 case SET_SSLCLIENTCERT:
534 mailsslclientcert = (sslclientcert_t) value;
535 case GET_SSLCLIENTCERT:
536 ret = (void *) mailsslclientcert;
537 break;
538 case SET_SSLCLIENTKEY:
539 mailsslclientkey = (sslclientkey_t) value;
540 case GET_SSLCLIENTKEY:
541 ret = (void *) mailsslclientkey;
542 break;
543 case SET_SSLFAILURE:
544 mailsslfailure = (sslfailure_t) value;
545 case GET_SSLFAILURE:
546 ret = (void *) mailsslfailure;
547 break;
548 case SET_ENCRYPTION_RANGE_MIN:
549 encryption_range_min = *(int *) value;
550 case GET_ENCRYPTION_RANGE_MIN:
551 ret = (void *) &encryption_range_min;
552 break;
553 case SET_ENCRYPTION_RANGE_MAX:
554 encryption_range_max = *(int *) value;
555 case GET_ENCRYPTION_RANGE_MAX:
556 ret = (void *) &encryption_range_max;
557 break;
558 case SET_KINIT:
559 mailkinit = (kinit_t) value;
560 case GET_KINIT:
561 ret = (void *) mailkinit;
562 break;
563 case SET_SENDCOMMAND:
564 mailsendcommand = (sendcommand_t) value;
565 case GET_SENDCOMMAND:
566 ret = (void *) mailsendcommand;
567 break;
569 case SET_SERVICENAME:
570 servicename = (char *) value;
571 case GET_SERVICENAME:
572 ret = (void *) servicename;
573 break;
574 case SET_EXPUNGEATPING:
575 expungeatping = (value ? T : NIL);
576 case GET_EXPUNGEATPING:
577 ret = (void *) (expungeatping ? VOIDT : NIL);
578 break;
579 case SET_SORTRESULTS:
580 mailsortresults = (sortresults_t) value;
581 case GET_SORTRESULTS:
582 ret = (void *) mailsortresults;
583 break;
584 case SET_THREADRESULTS:
585 mailthreadresults = (threadresults_t) value;
586 case GET_THREADRESULTS:
587 ret = (void *) mailthreadresults;
588 break;
589 case SET_SSLDRIVER:
590 mailssldriver = (NETDRIVER *) value;
591 case GET_SSLDRIVER:
592 ret = (void *) mailssldriver;
593 break;
594 case SET_TRYSSLFIRST:
595 trysslfirst = (value ? T : NIL);
596 case GET_TRYSSLFIRST:
597 ret = (void *) (trysslfirst ? VOIDT : NIL);
598 break;
599 case SET_NOTIMEZONES:
600 notimezones = (value ? T : NIL);
601 case GET_NOTIMEZONES:
602 ret = (void *) (notimezones ? VOIDT : NIL);
603 break;
604 case SET_TRUSTDNS:
605 trustdns = (value ? T : NIL);
606 case GET_TRUSTDNS:
607 ret = (void *) (trustdns ? VOIDT : NIL);
608 break;
609 case SET_SASLUSESPTRNAME:
610 saslusesptrname = (value ? T : NIL);
611 case GET_SASLUSESPTRNAME:
612 ret = (void *) (saslusesptrname ? VOIDT : NIL);
613 break;
614 case SET_DEBUGSENSITIVE:
615 debugsensitive = (value ? T : NIL);
616 case GET_DEBUGSENSITIVE:
617 ret = (void *) (debugsensitive ? VOIDT : NIL);
618 break;
620 case SET_ACL:
621 mailaclresults = (getacl_t) value;
622 case GET_ACL:
623 ret = (void *) mailaclresults;
624 break;
625 case SET_LISTRIGHTS:
626 maillistrightsresults = (listrights_t) value;
627 case GET_LISTRIGHTS:
628 ret = (void *) maillistrightsresults;
629 break;
630 case SET_MYRIGHTS:
631 mailmyrightsresults = (myrights_t) value;
632 case GET_MYRIGHTS:
633 ret = (void *) mailmyrightsresults;
634 break;
635 case SET_QUOTA:
636 mailquotaresults = (quota_t) value;
637 case GET_QUOTA:
638 ret = (void *) mailquotaresults;
639 break;
640 case SET_QUOTAROOT:
641 mailquotarootresults = (quotaroot_t) value;
642 case GET_QUOTAROOT:
643 ret = (void *) mailquotarootresults;
644 break;
645 case SET_SNARFINTERVAL:
646 mailsnarfinterval = (long) value;
647 case GET_SNARFINTERVAL:
648 ret = (void *) mailsnarfinterval;
649 break;
650 case SET_SNARFPRESERVE:
651 mailsnarfpreserve = (long) value;
652 case GET_SNARFPRESERVE:
653 ret = (void *) mailsnarfpreserve;
654 break;
655 case SET_SNARFMAILBOXNAME:
656 if (stream) { /* have a stream? */
657 if (stream->snarf.name) fs_give ((void **) &stream->snarf.name);
658 stream->snarf.name = cpystr ((char *) value);
660 else fatal ("SET_SNARFMAILBOXNAME with no stream");
661 case GET_SNARFMAILBOXNAME:
662 if (stream) ret = (void *) stream->snarf.name;
663 break;
664 case SET_IDPARAMS: /* program id */
665 idapp = (IDLIST *) value;
666 case GET_IDPARAMS:
667 ret = (void *) idapp;
668 default:
669 if ((r = smtp_parameters (function,value)) != NULL) ret = r;
670 if ((r = env_parameters (function,value)) != NULL) ret = r;
671 if ((r = tcp_parameters (function,value)) != NULL) ret = r;
672 if ((r = utf8_parameters (function,value)) != NULL) ret = r;
673 if (stream && stream->dtb) {/* if have stream, do for its driver only */
674 if ((r = (*stream->dtb->parameters) (function,value)) != NULL) ret = r;
676 /* else do all drivers */
677 else for (d = maildrivers; d; d = d->next)
678 if ((r = (d->parameters) (function,value)) != NULL) ret = r;
679 break;
681 return ret;
684 /* Mail validate mailbox name
685 * Accepts: MAIL stream
686 * mailbox name
687 * purpose string for error message
688 * Return: driver factory on success, NIL on failure
691 DRIVER *mail_valid (MAILSTREAM *stream,char *mailbox,char *purpose)
693 char tmp[MAILTMPLEN];
694 DRIVER *factory = NIL;
695 /* never allow names with newlines */
696 if (strpbrk (mailbox,"\015\012")) {
697 if (purpose) { /* if want an error message */
698 sprintf (tmp,"Can't %s with such a name",purpose);
699 MM_LOG (tmp,ERROR);
701 return NIL;
703 /* validate name, find driver factory */
704 if (strlen (mailbox) < (NETMAXHOST+(NETMAXUSER*2)+NETMAXMBX+NETMAXSRV+50))
705 for (factory = maildrivers; factory &&
706 ((factory->flags & DR_DISABLE) ||
707 ((factory->flags & DR_LOCAL) && (*mailbox == '{')) ||
708 !(*factory->valid) (mailbox));
709 factory = factory->next);
710 /* validate factory against non-dummy stream */
711 if (factory && stream && stream->dtb && (stream->dtb != factory) &&
712 strcmp (stream->dtb->name,"dummy"))
713 /* factory invalid; if dummy, use stream */
714 factory = strcmp (factory->name,"dummy") ? NIL : stream->dtb;
715 if (!factory && purpose) { /* if want an error message */
716 sprintf (tmp,"Can't %s %.80s: %s",purpose,mailbox,(*mailbox == '{') ?
717 "invalid remote specification" : "no such mailbox");
718 MM_LOG (tmp,ERROR);
720 return factory; /* return driver factory */
723 /* Mail validate network mailbox name
724 * Accepts: mailbox name
725 * mailbox driver to validate against
726 * pointer to where to return host name if non-NIL
727 * pointer to where to return mailbox name if non-NIL
728 * Returns: driver on success, NIL on failure
731 DRIVER *mail_valid_net (char *name,DRIVER *drv,char *host,char *mailbox)
733 NETMBX mb;
734 if (!mail_valid_net_parse (name,&mb) || strcmp (mb.service,drv->name))
735 return NIL;
736 if (host) strcpy (host,mb.host);
737 if (mailbox) strcpy (mailbox,mb.mailbox);
738 return drv;
742 /* Mail validate network mailbox name
743 * Accepts: mailbox name
744 * NETMBX structure to return values
745 * Returns: T on success, NIL on failure
748 long mail_valid_net_parse (char *name,NETMBX *mb)
750 return mail_valid_net_parse_work (name,mb,"imap");
753 /* Mail validate network mailbox name worker routine
754 * Accepts: mailbox name
755 * NETMBX structure to return values
756 * default service
757 * Returns: T on success, NIL on failure
760 long mail_valid_net_parse_work (char *name,NETMBX *mb,char *service)
762 int i,j;
763 char c,*s,*t,*v,tmp[MAILTMPLEN],arg[MAILTMPLEN];
764 /* initialize structure */
765 memset (mb,'\0',sizeof (NETMBX));
766 /* must have host specification */
767 if (*name++ != '{') return NIL;
768 if (*name == '[') { /* if domain literal, find its ending */
769 if (!((v = strpbrk (name,"]}")) && (*v++ == ']'))) return NIL;
771 /* find end of host name */
772 else if (!(v = strpbrk (name,"/:}"))) return NIL;
773 /* validate length, find mailbox part */
774 if (!((i = v - name) && (i < NETMAXHOST) && (t = strchr (v,'}')) &&
775 ((j = t - v) < MAILTMPLEN) && (strlen (t+1) < (size_t) NETMAXMBX)))
776 return NIL; /* invalid mailbox */
777 strncpy (mb->host,name,i); /* set host name */
778 strncpy (mb->orighost,name,i);
779 mb->host[i] = mb->orighost[i] = '\0';
780 strcpy (mb->mailbox,t+1); /* set mailbox name */
781 if (t - v) { /* any switches or port specification? */
782 strncpy (t = tmp,v,j); /* copy it */
783 tmp[j] = '\0'; /* tie it off */
784 c = *t++; /* get first delimiter */
785 do switch (c) { /* act based upon the character */
786 case ':': /* port specification */
787 if (mb->port || !(mb->port = strtoul (t,&t,10))) return NIL;
788 c = t ? *t++ : '\0'; /* get delimiter, advance pointer */
789 break;
790 case '/': /* switch */
791 /* find delimiter */
792 if ((t = strpbrk (s = t,"/:=")) != NULL) {
793 c = *t; /* remember delimiter for later */
794 *t++ = '\0'; /* tie off switch name */
796 else c = '\0'; /* no delimiter */
797 if (c == '=') { /* parse switches which take arguments */
798 if (*t == '"') { /* quoted string? */
799 for (v = arg,i = 0,++t; (c = *t++) != '"';) {
800 if (!c) return NIL; /* unterminated string */
801 /* quote next character */
802 if (c == '\\') c = *t++;
803 if (!c) return NIL; /* can't quote NUL either */
804 arg[i++] = c;
806 c = *t++; /* remember delimiter for later */
807 arg[i] = '\0'; /* tie off argument */
809 else { /* non-quoted argument */
810 if ((t = strpbrk (v = t,"/:")) != NULL) {
811 c = *t; /* remember delimiter for later */
812 *t++ = '\0'; /* tie off switch name */
814 else c = '\0'; /* no delimiter */
815 i = strlen (v); /* length of argument */
817 if (!compare_cstring (s,"service") && (i < NETMAXSRV) && !*mb->service)
818 lcase (strcpy (mb->service,v));
819 else if (!compare_cstring (s,"user") && (i < NETMAXUSER) && !*mb->user)
820 strcpy (mb->user,v);
821 else if (!compare_cstring (s,"authuser") && (i < NETMAXUSER) &&
822 !*mb->authuser) strcpy (mb->authuser,v);
823 else if (!compare_cstring (s,"auth") && (i < NETMAXAUTH) &&
824 !*mb->auth) strcpy (mb->auth,v);
825 else return NIL;
828 else { /* non-argument switch */
829 if (!compare_cstring (s,"anonymous")) mb->anoflag = T;
830 else if (!compare_cstring (s,"debug")) mb->dbgflag = T;
831 else if (!compare_cstring (s,"readonly")) mb->readonlyflag = T;
832 else if (!compare_cstring (s,"secure")) mb->secflag = T;
833 else if (!compare_cstring (s,"norsh")) mb->norsh = T;
834 else if (!compare_cstring (s,"loser")) mb->loser = T;
835 else if (!compare_cstring (s,"tls") && !mb->notlsflag)
836 mb->tlsflag = T;
837 else if (!compare_cstring (s,"tls-sslv23") && !mb->notlsflag)
838 mb->tlssslv23 = mb->tlsflag = T;
839 else if (!compare_cstring (s,"notls") && !mb->tlsflag)
840 mb->notlsflag = T;
841 else if (!compare_cstring (s,"tryssl"))
842 mb->trysslflag = mailssldriver? T : NIL;
843 else if (mailssldriver && !compare_cstring (s,"ssl") && !mb->tlsflag)
844 mb->sslflag = mb->notlsflag = T;
845 else if (!compare_cstring(s, "tls1")
846 && !mb->tls1_1 && !mb->tls1_2 && !mb->tls1_3)
847 mb->sslflag = mb->notlsflag = mb->tls1 = T;
848 else if (!compare_cstring(s, "tls1_1")
849 && !mb->tls1 && !mb->tls1_2 && !mb->tls1_3)
850 mb->sslflag = mb->notlsflag = mb->tls1_1 = T;
851 else if (!compare_cstring(s, "tls1_2")
852 && !mb->tls1 && !mb->tls1_1 && !mb->tls1_3)
853 mb->sslflag = mb->notlsflag = mb->tls1_2 = T;
854 else if (!compare_cstring(s, "tls1_3")
855 && !mb->tls1 && !mb->tls1_1 && !mb->tls1_2)
856 mb->sslflag = mb->notlsflag = mb->tls1_3 = T;
857 else if (mailssldriver && !compare_cstring (s,"novalidate-cert"))
858 mb->novalidate = T;
859 /* hack for compatibility with the past */
860 else if (mailssldriver && !compare_cstring (s,"validate-cert"));
861 /* service switches below here */
862 else if (*mb->service) return NIL;
863 else if (!compare_cstring (s,"imap") ||
864 !compare_cstring (s,"nntp") ||
865 !compare_cstring (s,"pop3") ||
866 !compare_cstring (s,"smtp") ||
867 !compare_cstring (s,"submit"))
868 lcase (strcpy (mb->service,s));
869 else if (!compare_cstring (s,"imap2") ||
870 !compare_cstring (s,"imap2bis") ||
871 !compare_cstring (s,"imap4") ||
872 !compare_cstring (s,"imap4rev1"))
873 strcpy (mb->service,"imap");
874 else if (!compare_cstring (s,"pop"))
875 strcpy (mb->service,"pop3");
876 else return NIL; /* invalid non-argument switch */
878 break;
879 default: /* anything else is bogus */
880 return NIL;
881 } while (c); /* see if anything more to parse */
883 /* default mailbox name */
884 if (!*mb->mailbox) strcpy (mb->mailbox,"INBOX");
885 /* default service name */
886 if (!*mb->service) strcpy (mb->service,service);
887 /* /norsh only valid if imap */
888 if (mb->norsh && strcmp (mb->service,"imap")) return NIL;
889 return T;
892 /* Mail scan mailboxes for string
893 * Accepts: mail stream
894 * reference
895 * pattern to search
896 * contents to search
899 void mail_scan (MAILSTREAM *stream,char *ref,char *pat,char *contents)
901 int remote = ((*pat == '{') || (ref && *ref == '{'));
902 DRIVER *d;
903 if (ref && (strlen (ref) > NETMAXMBX)) {
904 char tmp[MAILTMPLEN];
905 sprintf (tmp,"Invalid LIST reference specification: %.80s",ref);
906 MM_LOG (tmp,ERROR);
907 return;
909 if (strlen (pat) > NETMAXMBX) {
910 char tmp[MAILTMPLEN];
911 sprintf (tmp,"Invalid LIST pattern specification: %.80s",pat);
912 MM_LOG (tmp,ERROR);
913 return;
915 if (*pat == '{') ref = NIL; /* ignore reference if pattern is remote */
916 if (stream) { /* if have a stream, do it for that stream */
917 if ((d = stream->dtb) && d->scan &&
918 !(((d->flags & DR_LOCAL) && remote)))
919 (*d->scan) (stream,ref,pat,contents);
921 /* otherwise do for all DTB's */
922 else for (d = maildrivers; d; d = d->next)
923 if (d->scan && !((d->flags & DR_DISABLE) ||
924 ((d->flags & DR_LOCAL) && remote)))
925 (d->scan) (NIL,ref,pat,contents);
928 /* Mail list mailboxes
929 * Accepts: mail stream
930 * reference
931 * pattern to search
934 void mail_list (MAILSTREAM *stream,char *ref,char *pat)
936 int remote = ((*pat == '{') || (ref && *ref == '{'));
937 DRIVER *d = maildrivers;
938 if (ref && (strlen (ref) > NETMAXMBX)) {
939 char tmp[MAILTMPLEN];
940 sprintf (tmp,"Invalid LIST reference specification: %.80s",ref);
941 MM_LOG (tmp,ERROR);
942 return;
944 if (strlen (pat) > NETMAXMBX) {
945 char tmp[MAILTMPLEN];
946 sprintf (tmp,"Invalid LIST pattern specification: %.80s",pat);
947 MM_LOG (tmp,ERROR);
948 return;
950 if (*pat == '{') ref = NIL; /* ignore reference if pattern is remote */
951 if (stream && stream->dtb) { /* if have a stream, do it for that stream */
952 if (!(((d = stream->dtb)->flags & DR_LOCAL) && remote))
953 (*d->list) (stream,ref,pat);
955 /* otherwise do for all DTB's */
956 else do if (!((d->flags & DR_DISABLE) ||
957 ((d->flags & DR_LOCAL) && remote)))
958 (d->list) (NIL,ref,pat);
959 while ((d = d->next) != NULL); /* until at the end */
962 /* Mail list subscribed mailboxes
963 * Accepts: mail stream
964 * pattern to search
967 void mail_lsub (MAILSTREAM *stream,char *ref,char *pat)
969 int remote = ((*pat == '{') || (ref && *ref == '{'));
970 DRIVER *d = maildrivers;
971 if (ref && (strlen (ref) > NETMAXMBX)) {
972 char tmp[MAILTMPLEN];
973 sprintf (tmp,"Invalid LSUB reference specification: %.80s",ref);
974 MM_LOG (tmp,ERROR);
975 return;
977 if (strlen (pat) > NETMAXMBX) {
978 char tmp[MAILTMPLEN];
979 sprintf (tmp,"Invalid LSUB pattern specification: %.80s",pat);
980 MM_LOG (tmp,ERROR);
981 return;
983 if (*pat == '{') ref = NIL; /* ignore reference if pattern is remote */
984 if (stream && stream->dtb) { /* if have a stream, do it for that stream */
985 if (!(((d = stream->dtb)->flags & DR_LOCAL) && remote))
986 (*d->lsub) (stream,ref,pat);
988 /* otherwise do for all DTB's */
989 else do if (!((d->flags & DR_DISABLE) ||
990 ((d->flags & DR_LOCAL) && remote)))
991 (d->lsub) (NIL,ref,pat);
992 while ((d = d->next) != NULL); /* until at the end */
995 /* Mail subscribe to mailbox
996 * Accepts: mail stream
997 * mailbox to add to subscription list
998 * Returns: T on success, NIL on failure
1001 long mail_subscribe (MAILSTREAM *stream,char *mailbox)
1003 DRIVER *factory = mail_valid (stream,mailbox,"subscribe to mailbox");
1004 return factory ?
1005 (factory->subscribe ?
1006 (*factory->subscribe) (stream,mailbox) : sm_subscribe (mailbox)) : NIL;
1010 /* Mail unsubscribe to mailbox
1011 * Accepts: mail stream
1012 * mailbox to delete from subscription list
1013 * Returns: T on success, NIL on failure
1016 long mail_unsubscribe (MAILSTREAM *stream,char *mailbox)
1018 DRIVER *factory = mail_valid (stream,mailbox,NIL);
1019 return (factory && factory->unsubscribe) ?
1020 (*factory->unsubscribe) (stream,mailbox) : sm_unsubscribe (mailbox);
1023 /* Mail create mailbox
1024 * Accepts: mail stream
1025 * mailbox name to create
1026 * Returns: T on success, NIL on failure
1029 long mail_create (MAILSTREAM *stream,char *mailbox)
1031 MAILSTREAM *ts;
1032 char *s,*t,tmp[MAILTMPLEN];
1033 size_t i;
1034 DRIVER *d;
1035 /* never allow names with newlines */
1036 if ((s = strpbrk (mailbox,"\015\012")) != NULL) {
1037 MM_LOG ("Can't create mailbox with such a name",ERROR);
1038 return NIL;
1040 if (strlen (mailbox) >= (NETMAXHOST+(NETMAXUSER*2)+NETMAXMBX+NETMAXSRV+50)) {
1041 sprintf (tmp,"Can't create %.80s: %s",mailbox,(*mailbox == '{') ?
1042 "invalid remote specification" : "no such mailbox");
1043 MM_LOG (tmp,ERROR);
1044 return NIL;
1046 /* create of INBOX invalid */
1047 if (!compare_cstring (mailbox,"INBOX")) {
1048 MM_LOG ("Can't create INBOX",ERROR);
1049 return NIL;
1051 /* validate name */
1052 if ((s = mail_utf7_valid (mailbox)) != NULL) {
1053 sprintf (tmp,"Can't create %s: %.80s",s,mailbox);
1054 MM_LOG (tmp,ERROR);
1055 return NIL;
1058 /* see if special driver hack */
1059 if ((mailbox[0] == '#') && ((mailbox[1] == 'd') || (mailbox[1] == 'D')) &&
1060 ((mailbox[2] == 'r') || (mailbox[2] == 'R')) &&
1061 ((mailbox[3] == 'i') || (mailbox[3] == 'I')) &&
1062 ((mailbox[4] == 'v') || (mailbox[4] == 'V')) &&
1063 ((mailbox[5] == 'e') || (mailbox[5] == 'E')) &&
1064 ((mailbox[6] == 'r') || (mailbox[6] == 'R')) && (mailbox[7] == '.')) {
1065 /* copy driver until likely delimiter */
1066 if ((s = strpbrk (t = mailbox+8,"/\\:")) && (i = s - t)) {
1067 strncpy (tmp,t,i);
1068 tmp[i] = '\0';
1070 else {
1071 sprintf (tmp,"Can't create mailbox %.80s: bad driver syntax",mailbox);
1072 MM_LOG (tmp,ERROR);
1073 return NIL;
1075 for (d = maildrivers; d && strcmp (d->name,tmp); d = d->next);
1076 if (d) mailbox = ++s; /* skip past driver specification */
1077 else {
1078 sprintf (tmp,"Can't create mailbox %.80s: unknown driver",mailbox);
1079 MM_LOG (tmp,ERROR);
1080 return NIL;
1083 /* use stream if one given or deterministic */
1084 else if ((stream && stream->dtb) ||
1085 (((*mailbox == '{') || (*mailbox == '#')) &&
1086 (stream = mail_open (NIL,mailbox,OP_PROTOTYPE | OP_SILENT))))
1087 d = stream->dtb;
1088 else if ((*mailbox != '{') && (ts = default_proto (NIL))) d = ts->dtb;
1089 else { /* failed utterly */
1090 sprintf (tmp,"Can't create mailbox %.80s: indeterminate format",mailbox);
1091 MM_LOG (tmp,ERROR);
1092 return NIL;
1094 return (*d->create) (stream,mailbox);
1097 /* Mail delete mailbox
1098 * Accepts: mail stream
1099 * mailbox name to delete
1100 * Returns: T on success, NIL on failure
1103 long mail_delete (MAILSTREAM *stream,char *mailbox)
1105 DRIVER *dtb = mail_valid (stream,mailbox,"delete mailbox");
1106 if (!dtb) return NIL;
1107 if (((mailbox[0] == 'I') || (mailbox[0] == 'i')) &&
1108 ((mailbox[1] == 'N') || (mailbox[1] == 'n')) &&
1109 ((mailbox[2] == 'B') || (mailbox[2] == 'b')) &&
1110 ((mailbox[3] == 'O') || (mailbox[3] == 'o')) &&
1111 ((mailbox[4] == 'X') || (mailbox[4] == 'x')) && !mailbox[5]) {
1112 MM_LOG ("Can't delete INBOX",ERROR);
1113 return NIL;
1115 return SAFE_DELETE (dtb,stream,mailbox);
1119 /* Mail rename mailbox
1120 * Accepts: mail stream
1121 * old mailbox name
1122 * new mailbox name
1123 * Returns: T on success, NIL on failure
1126 long mail_rename (MAILSTREAM *stream,char *old,char *newname)
1128 char *s,tmp[MAILTMPLEN];
1129 DRIVER *dtb = mail_valid (stream,old,"rename mailbox");
1130 if (!dtb) return NIL;
1131 /* validate name */
1132 if ((s = mail_utf7_valid (newname)) != NULL) {
1133 sprintf (tmp,"Can't rename to %s: %.80s",s,newname);
1134 MM_LOG (tmp,ERROR);
1135 return NIL;
1137 if ((*old != '{') && (*old != '#') && mail_valid (NIL,newname,NIL)) {
1138 sprintf (tmp,"Can't rename %.80s: mailbox %.80s already exists",
1139 old,newname);
1140 MM_LOG (tmp,ERROR);
1141 return NIL;
1143 return SAFE_RENAME (dtb,stream,old,newname);
1146 /* Validate mailbox as Modified UTF-7
1147 * Accepts: candidate mailbox name
1148 * Returns: error string if error, NIL if valid
1151 char *mail_utf7_valid (char *mailbox)
1153 char *s;
1154 for (s = mailbox; *s; s++) { /* make sure valid name */
1155 /* reserved for future use with UTF-8 */
1156 if (*s & 0x80) return "mailbox name with 8-bit octet";
1157 /* validate modified UTF-7 */
1158 else if (*s == '&') while (*++s != '-') switch (*s) {
1159 case '\0':
1160 return "unterminated modified UTF-7 name";
1161 case '+': /* valid modified BASE64 */
1162 case ',':
1163 break; /* all OK so far */
1164 default: /* must be alphanumeric */
1165 if (!isalnum (*s)) return "invalid modified UTF-7 name";
1166 break;
1169 return NIL; /* all OK */
1172 /* Mail status of mailbox
1173 * Accepts: mail stream if open on this mailbox
1174 * mailbox name
1175 * status flags
1176 * Returns: T on success, NIL on failure
1179 long mail_status (MAILSTREAM *stream,char *mbx,long flags)
1181 DRIVER *dtb = mail_valid (stream,mbx,"get status of mailbox");
1182 if (!dtb) return NIL; /* only if valid */
1183 if (stream && ((dtb != stream->dtb) ||
1184 ((dtb->flags & DR_LOCAL) && strcmp (mbx,stream->mailbox) &&
1185 strcmp (mbx,stream->original_mailbox))))
1186 stream = NIL; /* stream not suitable */
1187 return SAFE_STATUS (dtb,stream,mbx,flags);
1191 /* Mail status of mailbox default handler
1192 * Accepts: mail stream
1193 * mailbox name
1194 * status flags
1195 * Returns: T on success, NIL on failure
1198 long mail_status_default (MAILSTREAM *stream,char *mbx,long flags)
1200 MAILSTATUS status;
1201 unsigned long i;
1202 MAILSTREAM *tstream = NIL;
1203 /* make temporary stream (unless this mbx) */
1204 if (!stream && !(stream = tstream =
1205 mail_open (NIL,mbx,OP_READONLY|OP_SILENT))) return NIL;
1206 status.flags = flags; /* return status values */
1207 status.messages = stream->nmsgs;
1208 status.recent = stream->recent;
1209 if (flags & SA_UNSEEN) /* must search to get unseen messages */
1210 for (i = 1,status.unseen = 0; i <= stream->nmsgs; i++)
1211 if (!mail_elt (stream,i)->seen) status.unseen++;
1212 status.uidnext = stream->uid_last + 1;
1213 status.uidvalidity = stream->uid_validity;
1214 MM_STATUS(stream,mbx,&status);/* pass status to main program */
1215 if (tstream) mail_close (tstream);
1216 return T; /* success */
1219 /* Mail open
1220 * Accepts: candidate stream for recycling
1221 * mailbox name
1222 * open options
1223 * Returns: stream to use on success, NIL on failure
1226 MAILSTREAM *mail_open (MAILSTREAM *stream,char *name,long options)
1228 int i;
1229 char c,*s,tmp[MAILTMPLEN];
1230 NETMBX mb;
1231 DRIVER *d;
1232 switch (name[0]) { /* see if special handling */
1233 case '#': /* possible special hacks */
1234 if (((name[1] == 'M') || (name[1] == 'm')) &&
1235 ((name[2] == 'O') || (name[2] == 'o')) &&
1236 ((name[3] == 'V') || (name[3] == 'v')) &&
1237 ((name[4] == 'E') || (name[4] == 'e')) && (c = name[5]) &&
1238 (s = strchr (name+6,c)) && (i = s - (name + 6)) && (i < MAILTMPLEN)) {
1239 if ((stream = mail_open (stream,s+1,options)) != NULL) {
1240 strncpy (tmp,name+6,i); /* copy snarf mailbox name */
1241 tmp[i] = '\0'; /* tie off name */
1242 mail_parameters (stream,SET_SNARFMAILBOXNAME,(void *) tmp);
1243 stream->snarf.options = options;
1244 mail_ping (stream); /* do initial snarf */
1245 /* punt if can't do initial snarf */
1246 if (!stream->snarf.time) stream = mail_close (stream);
1248 return stream;
1250 /* special POP hack */
1251 else if (((name[1] == 'P') || (name[1] == 'p')) &&
1252 ((name[2] == 'O') || (name[2] == 'o')) &&
1253 ((name[3] == 'P') || (name[3] == 'p')) &&
1254 mail_valid_net_parse_work (name+4,&mb,"pop3") &&
1255 !strcmp (mb.service,"pop3") && !mb.anoflag && !mb.readonlyflag) {
1256 if ((stream = mail_open (stream,mb.mailbox,options)) != NULL) {
1257 sprintf (tmp,"{%.255s",mb.host);
1258 if (mb.port) sprintf (tmp + strlen (tmp),":%lu",mb.port);
1259 if (mb.user[0]) sprintf (tmp + strlen (tmp),"/user=%.64s",mb.user);
1260 if (mb.dbgflag) strcat (tmp,"/debug");
1261 if (mb.secflag) strcat (tmp,"/secure");
1262 if (mb.tlsflag) strcat (tmp,"/tls");
1263 if (mb.notlsflag) strcat (tmp,"/notls");
1264 if (mb.sslflag) strcat (tmp,"/ssl");
1265 if (mb.tls1) strcat (tmp,"/tls1");
1266 if (mb.tls1_1) strcat (tmp,"/tls1_1");
1267 if (mb.tls1_2) strcat (tmp,"/tls1_2");
1268 if (mb.tls1_3) strcat (tmp,"/tls1_3");
1269 if (mb.trysslflag) strcat (tmp,"/tryssl");
1270 if (mb.novalidate) strcat (tmp,"/novalidate-cert");
1271 strcat (tmp,"/pop3/loser}");
1272 mail_parameters (stream,SET_SNARFMAILBOXNAME,(void *) tmp);
1273 mail_ping (stream); /* do initial snarf */
1275 return stream; /* return local mailbox stream */
1278 else if ((options & OP_PROTOTYPE) &&
1279 ((name[1] == 'D') || (name[1] == 'd')) &&
1280 ((name[2] == 'R') || (name[2] == 'r')) &&
1281 ((name[3] == 'I') || (name[3] == 'i')) &&
1282 ((name[4] == 'V') || (name[4] == 'v')) &&
1283 ((name[5] == 'E') || (name[5] == 'e')) &&
1284 ((name[6] == 'R') || (name[6] == 'r')) && (name[7] == '.')) {
1285 sprintf (tmp,"%.80s",name+8);
1286 /* tie off name at likely delimiter */
1287 if ((s = strpbrk (tmp,"/\\:")) != NULL) *s++ = '\0';
1288 else {
1289 sprintf (tmp,"Can't resolve mailbox %.80s: bad driver syntax",name);
1290 MM_LOG (tmp,ERROR);
1291 return mail_close (stream);
1293 for (d = maildrivers; d && compare_cstring (d->name,tmp); d = d->next);
1294 if (d) return (*d->open) (NIL);
1295 sprintf (tmp,"Can't resolve mailbox %.80s: unknown driver",name);
1296 MM_LOG (tmp,ERROR);
1297 return mail_close (stream);
1299 /* fall through to default case */
1300 default: /* not special hack (but could be # name */
1301 d = mail_valid (NIL,name,(options & OP_SILENT) ?
1302 (char *) NIL : "open mailbox");
1304 return d ? mail_open_work (d,stream,name,options) : stream;
1307 /* Mail open worker routine
1308 * Accepts: factory
1309 * candidate stream for recycling
1310 * mailbox name
1311 * open options
1312 * Returns: stream to use on success, NIL on failure
1315 MAILSTREAM *mail_open_work (DRIVER *d,MAILSTREAM *stream,char *name,
1316 long options)
1318 int i;
1319 char tmp[MAILTMPLEN];
1320 NETMBX mb;
1321 if (options & OP_PROTOTYPE) return (*d->open) (NIL);
1322 /* name is copied here in case the caller does a re-open using
1323 * stream->mailbox or stream->original_mailbox as the argument.
1325 name = cpystr (name); /* make copy of name */
1326 if (stream) { /* recycling requested? */
1327 if ((stream->dtb == d) && (d->flags & DR_RECYCLE) &&
1328 ((d->flags & DR_HALFOPEN) || !(options & OP_HALFOPEN)) &&
1329 mail_usable_network_stream (stream,name)) {
1330 /* yes, checkpoint if needed */
1331 if (d->flags & DR_XPOINT) mail_check (stream);
1332 mail_free_cache (stream); /* clean up stream */
1333 if (stream->mailbox) fs_give ((void **) &stream->mailbox);
1334 if (stream->original_mailbox)
1335 fs_give ((void **) &stream->original_mailbox);
1336 /* flush user flags */
1337 for (i = 0; i < NUSERFLAGS; i++)
1338 if (stream->user_flags[i]) fs_give ((void **) &stream->user_flags[i]);
1340 else { /* stream not recycleable, babble if net */
1341 if (!stream->silent && stream->dtb && !(stream->dtb->flags&DR_LOCAL) &&
1342 mail_valid_net_parse (stream->mailbox,&mb)) {
1343 sprintf (tmp,"Closing connection to %.80s",mb.host);
1344 MM_LOG (tmp,(long) NIL);
1346 /* flush the old stream */
1347 stream = mail_close (stream);
1350 /* check if driver does not support halfopen */
1351 else if ((options & OP_HALFOPEN) && !(d->flags & DR_HALFOPEN)) {
1352 fs_give ((void **) &name);
1353 return NIL;
1356 /* instantiate new stream if not recycling */
1357 if (!stream) (*mailcache) (stream = (MAILSTREAM *)
1358 memset (fs_get (sizeof (MAILSTREAM)),0,
1359 sizeof (MAILSTREAM)),(long) 0,CH_INIT);
1360 stream->dtb = d; /* set dispatch */
1361 /* set mailbox name */
1362 stream->mailbox = cpystr (stream->original_mailbox = name);
1363 /* initialize stream flags */
1364 stream->inbox = stream->lock = NIL;
1365 stream->debug = (options & OP_DEBUG) ? T : NIL;
1366 stream->rdonly = (options & OP_READONLY) ? T : NIL;
1367 stream->anonymous = (options & OP_ANONYMOUS) ? T : NIL;
1368 stream->scache = (options & OP_SHORTCACHE) ? T : NIL;
1369 stream->silent = (options & OP_SILENT) ? T : NIL;
1370 stream->halfopen = (options & OP_HALFOPEN) ? T : NIL;
1371 stream->secure = (options & OP_SECURE) ? T : NIL;
1372 stream->tryssl = (options & OP_TRYSSL) ? T : NIL;
1373 stream->mulnewsrc = (options & OP_MULNEWSRC) ? T : NIL;
1374 stream->nokod = (options & OP_NOKOD) ? T : NIL;
1375 stream->sniff = (options & OP_SNIFF) ? T : NIL;
1376 stream->perm_seen = stream->perm_deleted = stream->perm_flagged =
1377 stream->perm_answered = stream->perm_draft = stream->kwd_create = NIL;
1378 stream->uid_nosticky = (d->flags & DR_NOSTICKY) ? T : NIL;
1379 stream->uid_last = 0; /* default UID validity */
1380 stream->uid_validity = (unsigned long) time (0);
1381 /* have driver open, flush if failed */
1382 return ((*d->open) (stream)) ? stream : mail_close (stream);
1385 /* Mail close
1386 * Accepts: mail stream
1387 * close options
1388 * Returns: NIL, always
1391 MAILSTREAM *mail_close_full (MAILSTREAM *stream,long options)
1393 int i;
1394 if (stream) { /* make sure argument given */
1395 /* do the driver's close action */
1396 if (stream->dtb) (*stream->dtb->close) (stream,options);
1397 stream->dtb = NIL; /* resign driver */
1398 if (stream->mailbox) fs_give ((void **) &stream->mailbox);
1399 if (stream->original_mailbox)
1400 fs_give ((void **) &stream->original_mailbox);
1401 if (stream->snarf.name) fs_give ((void **) &stream->snarf.name);
1402 stream->sequence++; /* invalidate sequence */
1403 /* flush user flags */
1404 for (i = 0; i < NUSERFLAGS; i++)
1405 if (stream->user_flags[i]) fs_give ((void **) &stream->user_flags[i]);
1406 mail_free_cache (stream); /* finally free the stream's storage */
1407 if (mailfreestreamsparep && stream->sparep)
1408 (*mailfreestreamsparep) (&stream->sparep);
1409 if (!stream->use) fs_give ((void **) &stream);
1411 return NIL;
1414 /* Mail make handle
1415 * Accepts: mail stream
1416 * Returns: handle
1418 * Handles provide a way to have multiple pointers to a stream yet allow the
1419 * stream's owner to nuke it or recycle it.
1422 MAILHANDLE *mail_makehandle (MAILSTREAM *stream)
1424 MAILHANDLE *handle = (MAILHANDLE *) fs_get (sizeof (MAILHANDLE));
1425 handle->stream = stream; /* copy stream */
1426 /* and its sequence */
1427 handle->sequence = stream->sequence;
1428 stream->use++; /* let stream know another handle exists */
1429 return handle;
1432 void mail_free_idlist (IDLIST **idlist)
1434 if (idlist && *idlist){
1435 if((*idlist)->name) fs_give((void **)&(*idlist)->name);
1436 if((*idlist)->value) fs_give((void **)&(*idlist)->value);
1437 if((*idlist)->next) mail_free_idlist(&(*idlist)->next);
1438 fs_give((void **) idlist);
1443 /* Mail release handle
1444 * Accepts: Mail handle
1447 void mail_free_handle (MAILHANDLE **handle)
1449 MAILSTREAM *s;
1450 if (*handle) { /* only free if exists */
1451 /* resign stream, flush unreferenced zombies */
1452 if ((!--(s = (*handle)->stream)->use) && !s->dtb) fs_give ((void **) &s);
1453 fs_give ((void **) handle); /* now flush the handle */
1458 /* Mail get stream handle
1459 * Accepts: Mail handle
1460 * Returns: mail stream or NIL if stream gone
1463 MAILSTREAM *mail_stream (MAILHANDLE *handle)
1465 MAILSTREAM *s = handle->stream;
1466 return (s->dtb && (handle->sequence == s->sequence)) ? s : NIL;
1469 /* Mail fetch cache element
1470 * Accepts: mail stream
1471 * message # to fetch
1472 * Returns: cache element of this message
1473 * Can also be used to create cache elements for new messages.
1476 MESSAGECACHE *mail_elt (MAILSTREAM *stream,unsigned long msgno)
1478 if (msgno < 1 || msgno > stream->nmsgs) {
1479 char tmp[MAILTMPLEN];
1480 sprintf (tmp,"Bad msgno %lu in mail_elt, nmsgs = %lu, mbx=%.80s",
1481 msgno,stream->nmsgs,stream->mailbox ? stream->mailbox : "???");
1482 fatal (tmp);
1484 return (MESSAGECACHE *) (*mailcache) (stream,msgno,CH_MAKEELT);
1488 /* Mail fetch fast information
1489 * Accepts: mail stream
1490 * sequence
1491 * option flags
1493 * Generally, mail_fetch_structure is preferred
1496 void mail_fetch_fast (MAILSTREAM *stream,char *sequence,long flags)
1498 /* do the driver's action */
1499 if (stream->dtb && stream->dtb->fast)
1500 (*stream->dtb->fast) (stream,sequence,flags);
1504 /* Mail fetch flags
1505 * Accepts: mail stream
1506 * sequence
1507 * option flags
1510 void mail_fetch_flags (MAILSTREAM *stream,char *sequence,long flags)
1512 /* do the driver's action */
1513 if (stream->dtb && stream->dtb->msgflags)
1514 (*stream->dtb->msgflags) (stream,sequence,flags);
1517 /* Mail fetch message overview
1518 * Accepts: mail stream
1519 * UID sequence to fetch
1520 * pointer to overview return function
1523 void mail_fetch_overview (MAILSTREAM *stream,char *sequence,overview_t ofn)
1525 if (stream->dtb && mail_uid_sequence (stream,sequence) &&
1526 !(stream->dtb->overview && (*stream->dtb->overview) (stream,ofn)) &&
1527 mail_ping (stream))
1528 mail_fetch_overview_default (stream,ofn);
1532 /* Mail fetch message overview using sequence numbers instead of UIDs
1533 * Accepts: mail stream
1534 * sequence to fetch
1535 * pointer to overview return function
1538 void mail_fetch_overview_sequence (MAILSTREAM *stream,char *sequence,
1539 overview_t ofn)
1541 if (stream->dtb && mail_sequence (stream,sequence) &&
1542 !(stream->dtb->overview && (*stream->dtb->overview) (stream,ofn)) &&
1543 mail_ping (stream))
1544 mail_fetch_overview_default (stream,ofn);
1548 /* Mail fetch message overview default handler
1549 * Accepts: mail stream with sequence bits lit
1550 * pointer to overview return function
1553 void mail_fetch_overview_default (MAILSTREAM *stream,overview_t ofn)
1555 MESSAGECACHE *elt;
1556 ENVELOPE *env;
1557 OVERVIEW ov;
1558 unsigned long i;
1559 ov.optional.lines = 0;
1560 ov.optional.xref = NIL;
1561 for (i = 1; i <= stream->nmsgs; i++)
1562 if (((elt = mail_elt (stream,i))->sequence) &&
1563 (env = mail_fetch_structure (stream,i,NIL,NIL)) && ofn) {
1564 ov.subject = env->subject;
1565 ov.from = env->from;
1566 ov.date = env->date;
1567 ov.message_id = env->message_id;
1568 ov.references = env->references;
1569 ov.optional.octets = elt->rfc822_size;
1570 (*ofn) (stream,mail_uid (stream,i),&ov,i);
1574 /* Mail fetch message structure
1575 * Accepts: mail stream
1576 * message # to fetch
1577 * pointer to return body
1578 * option flags
1579 * Returns: envelope of this message, body returned in body value
1581 * Fetches the "fast" information as well
1584 ENVELOPE *mail_fetch_structure (MAILSTREAM *stream,unsigned long msgno,
1585 BODY **body,long flags)
1587 ENVELOPE **env;
1588 BODY **b;
1589 MESSAGECACHE *elt;
1590 char c,*s,*hdr;
1591 unsigned long hdrsize;
1592 STRING bs;
1593 /* do the driver's action if specified */
1594 if (stream->dtb && stream->dtb->structure)
1595 return (*stream->dtb->structure) (stream,msgno,body,flags);
1596 if (flags & FT_UID) { /* UID form of call */
1597 if ((msgno = mail_msgno (stream,msgno)) != 0L) flags &= ~FT_UID;
1598 else return NIL; /* must get UID/msgno map first */
1600 elt = mail_elt (stream,msgno);/* get elt for real message number */
1601 if (stream->scache) { /* short caching */
1602 if (msgno != stream->msgno){/* garbage collect if not same message */
1603 mail_gc (stream,GC_ENV | GC_TEXTS);
1604 stream->msgno = msgno; /* this is the current message now */
1606 env = &stream->env; /* get pointers to envelope and body */
1607 b = &stream->body;
1609 else { /* get pointers to elt envelope and body */
1610 env = &elt->private.msg.env;
1611 b = &elt->private.msg.body;
1614 if (stream->dtb && ((body && !*b) || !*env || (*env)->incomplete)) {
1615 mail_free_envelope (env); /* flush old envelope and body */
1616 mail_free_body (b);
1617 /* see if need to fetch the whole thing */
1618 if (body || !elt->rfc822_size) {
1619 s = (*stream->dtb->header) (stream,msgno,&hdrsize,flags & ~FT_INTERNAL);
1620 /* make copy in case body fetch smashes it */
1621 hdr = (char *) memcpy (fs_get ((size_t) hdrsize+1),s,(size_t) hdrsize);
1622 hdr[hdrsize] = '\0'; /* tie off header */
1623 (*stream->dtb->text) (stream,msgno,&bs,(flags & ~FT_INTERNAL) | FT_PEEK);
1624 if (!elt->rfc822_size) elt->rfc822_size = hdrsize + SIZE (&bs);
1625 if (body) /* only parse body if requested */
1626 rfc822_parse_msg (env,b,hdr,hdrsize,&bs,BADHOST,stream->dtb->flags);
1627 else
1628 rfc822_parse_msg (env,NIL,hdr,hdrsize,NIL,BADHOST,stream->dtb->flags);
1629 fs_give ((void **) &hdr); /* flush header */
1631 else { /* can save memory doing it this way */
1632 hdr = (*stream->dtb->header) (stream,msgno,&hdrsize,flags | FT_INTERNAL);
1633 if (hdrsize) { /* in case null header */
1634 c = hdr[hdrsize]; /* preserve what's there */
1635 hdr[hdrsize] = '\0'; /* tie off header */
1636 rfc822_parse_msg (env,NIL,hdr,hdrsize,NIL,BADHOST,stream->dtb->flags);
1637 hdr[hdrsize] = c; /* restore in case cached data */
1639 else *env = mail_newenvelope ();
1642 /* if need date, have date in envelope? */
1643 if (!elt->day && *env && (*env)->date) mail_parse_date (elt,(*env)->date);
1644 /* sigh, fill in bogus default */
1645 if (!elt->day) elt->day = elt->month = 1;
1646 if (body) *body = *b; /* return the body */
1647 return *env; /* return the envelope */
1650 /* Mail mark single message (internal use only)
1651 * Accepts: mail stream
1652 * elt to mark
1653 * fetch flags
1656 static void markseen (MAILSTREAM *stream,MESSAGECACHE *elt,long flags)
1658 unsigned long i;
1659 char sequence[20];
1660 MESSAGECACHE *e;
1661 /* non-peeking and needs to set \Seen? */
1662 if (!(flags & FT_PEEK) && !elt->seen) {
1663 if (stream->dtb->flagmsg){ /* driver wants per-message call? */
1664 elt->valid = NIL; /* do pre-alteration driver call */
1665 (*stream->dtb->flagmsg) (stream,elt);
1666 /* set seen, do post-alteration driver call */
1667 elt->seen = elt->valid = T;
1668 (*stream->dtb->flagmsg) (stream,elt);
1670 if (stream->dtb->flag) { /* driver wants one-time call? */
1671 /* better safe than sorry, save seq bits */
1672 for (i = 1; i <= stream->nmsgs; i++) {
1673 e = mail_elt (stream,i);
1674 e->private.sequence = e->sequence;
1676 /* call driver to set the message */
1677 sprintf (sequence,"%lu",elt->msgno);
1678 (*stream->dtb->flag) (stream,sequence,"\\Seen",ST_SET);
1679 /* restore sequence bits */
1680 for (i = 1; i <= stream->nmsgs; i++) {
1681 e = mail_elt (stream,i);
1682 e->sequence = e->private.sequence;
1685 /* notify mail program of flag change */
1686 MM_FLAGS (stream,elt->msgno);
1690 /* Mail fetch message
1691 * Accepts: mail stream
1692 * message # to fetch
1693 * pointer to returned length
1694 * flags
1695 * Returns: message text
1698 char *mail_fetch_message (MAILSTREAM *stream,unsigned long msgno,
1699 unsigned long *len,long flags)
1701 GETS_DATA md;
1702 SIZEDTEXT *t;
1703 STRING bs;
1704 MESSAGECACHE *elt;
1705 char *s,*u;
1706 unsigned long i,j;
1707 if (len) *len = 0; /* default return size */
1708 if (flags & FT_UID) { /* UID form of call */
1709 if ((msgno = mail_msgno (stream,msgno)) != 0L) flags &= ~FT_UID;
1710 else return ""; /* must get UID/msgno map first */
1712 /* initialize message data identifier */
1713 INIT_GETS (md,stream,msgno,"",0,0);
1714 /* is data already cached? */
1715 if ((t = &(elt = mail_elt (stream,msgno))->private.msg.full.text)->data) {
1716 markseen (stream,elt,flags);/* mark message seen */
1717 return mail_fetch_text_return (&md,t,len);
1719 if (!stream->dtb) return ""; /* not in cache, must have live driver */
1720 if (stream->dtb->msgdata) return
1721 ((*stream->dtb->msgdata) (stream,msgno,"",0,0,NIL,flags) && t->data) ?
1722 mail_fetch_text_return (&md,t,len) : "";
1723 /* ugh, have to do this the crufty way */
1724 u = mail_fetch_header (stream,msgno,NIL,NIL,&i,flags);
1725 /* copy in case text method stomps on it */
1726 s = (char *) memcpy (fs_get ((size_t) i),u,(size_t) i);
1727 if ((*stream->dtb->text) (stream,msgno,&bs,flags)) {
1728 t = &stream->text; /* build combined copy */
1729 if (t->data) fs_give ((void **) &t->data);
1730 t->data = (unsigned char *) fs_get ((t->size = i + SIZE (&bs)) + 1);
1731 if (!elt->rfc822_size) elt->rfc822_size = t->size;
1732 else if (elt->rfc822_size != t->size) {
1733 char tmp[MAILTMPLEN];
1734 sprintf (tmp,"Calculated RFC822.SIZE (%lu) != reported size (%lu)",
1735 t->size,elt->rfc822_size);
1736 mm_log (tmp,WARN); /* bug trap */
1738 memcpy (t->data,s,(size_t) i);
1739 for (u = (char *) t->data + i, j = SIZE (&bs); j;) {
1740 memcpy (u,bs.curpos,bs.cursize);
1741 u += bs.cursize; /* update text */
1742 j -= bs.cursize;
1743 bs.curpos += (bs.cursize -1);
1744 bs.cursize = 0;
1745 (*bs.dtb->next) (&bs); /* advance to next buffer's worth */
1747 *u = '\0'; /* tie off data */
1748 u = mail_fetch_text_return (&md,t,len);
1750 else u = "";
1751 fs_give ((void **) &s); /* finished with copy of header */
1752 return u;
1755 /* Mail fetch message header
1756 * Accepts: mail stream
1757 * message # to fetch
1758 * MIME section specifier (#.#.#...#)
1759 * list of lines to fetch
1760 * pointer to returned length
1761 * flags
1762 * Returns: message header in RFC822 format
1764 * Note: never calls a mailgets routine
1767 char *mail_fetch_header (MAILSTREAM *stream,unsigned long msgno,char *section,
1768 STRINGLIST *lines,unsigned long *len,long flags)
1770 STRING bs;
1771 BODY *b = NIL;
1772 SIZEDTEXT *t = NIL,rt;
1773 MESSAGE *m = NIL;
1774 MESSAGECACHE *elt;
1775 char tmp[MAILTMPLEN];
1776 if (len) *len = 0; /* default return size */
1777 if (section && (strlen (section) > (MAILTMPLEN - 20))) return "";
1778 if (flags & FT_UID) { /* UID form of call */
1779 if ((msgno = mail_msgno (stream,msgno)) != 0L) flags &= ~FT_UID;
1780 else return ""; /* must get UID/msgno map first */
1782 elt = mail_elt (stream,msgno);/* get cache data */
1783 if (section && *section) { /* nested body header wanted? */
1784 if (!((b = mail_body (stream,msgno,section)) &&
1785 (b->type == TYPEMESSAGE) && !strcmp (b->subtype,"RFC822")))
1786 return ""; /* lose if no body or not MESSAGE/RFC822 */
1787 m = b->nested.msg; /* point to nested message */
1789 /* else top-level message header wanted */
1790 else m = &elt->private.msg;
1791 if (m->header.text.data && mail_match_lines (lines,m->lines,flags)) {
1792 if (lines) textcpy (t = &stream->text,&m->header.text);
1793 else t = &m->header.text; /* in cache, and cache is valid */
1794 markseen (stream,elt,flags);/* mark message seen */
1797 else if (stream->dtb) { /* not in cache, has live driver? */
1798 if (stream->dtb->msgdata) { /* has driver section fetch? */
1799 /* build driver section specifier */
1800 if (section && *section) sprintf (tmp,"%s.HEADER",section);
1801 else strcpy (tmp,"HEADER");
1802 if ((*stream->dtb->msgdata) (stream,msgno,tmp,0,0,lines,flags)) {
1803 t = &m->header.text; /* fetch data */
1804 /* don't need to postprocess lines */
1805 if (m->lines) lines = NIL;
1806 else if (lines) textcpy (t = &stream->text,&m->header.text);
1809 else if (b) { /* nested body wanted? */
1810 if (stream->private.search.text) {
1811 rt.data = (unsigned char *) stream->private.search.text +
1812 b->nested.msg->header.offset;
1813 rt.size = b->nested.msg->header.text.size;
1814 t = &rt;
1816 else if ((*stream->dtb->text) (stream,msgno,&bs,flags & ~FT_INTERNAL)) {
1817 if ((bs.dtb->next == mail_string_next) && !lines) {
1818 rt.data = (unsigned char *) bs.curpos + b->nested.msg->header.offset;
1819 rt.size = b->nested.msg->header.text.size;
1820 if (stream->private.search.string)
1821 stream->private.search.text = bs.curpos;
1822 t = &rt; /* special hack to avoid extra copy */
1824 else textcpyoffstring (t = &stream->text,&bs,
1825 b->nested.msg->header.offset,
1826 b->nested.msg->header.text.size);
1829 else { /* top-level header fetch */
1830 /* mark message seen */
1831 markseen (stream,elt,flags);
1832 if ((rt.data = (unsigned char *)
1833 (*stream->dtb->header) (stream,msgno,&rt.size,flags)) != NULL) {
1834 /* make a safe copy if need to filter */
1835 if (lines) textcpy (t = &stream->text,&rt);
1836 else t = &rt; /* top level header */
1840 if (!t || !t->data) return "";/* error if no string */
1841 /* filter headers if requested */
1842 if (lines) t->size = mail_filter ((char *) t->data,t->size,lines,flags);
1843 if (len) *len = t->size; /* return size if requested */
1844 return (char *) t->data; /* and text */
1847 /* Mail fetch message text
1848 * Accepts: mail stream
1849 * message # to fetch
1850 * MIME section specifier (#.#.#...#)
1851 * pointer to returned length
1852 * flags
1853 * Returns: message text
1856 char *mail_fetch_text (MAILSTREAM *stream,unsigned long msgno,char *section,
1857 unsigned long *len,long flags)
1859 GETS_DATA md;
1860 PARTTEXT *p;
1861 STRING bs;
1862 MESSAGECACHE *elt;
1863 BODY *b = NIL;
1864 char tmp[MAILTMPLEN];
1865 unsigned long i;
1866 if (len) *len = 0; /* default return size */
1867 memset (&stream->private.string,NIL,sizeof (STRING));
1868 if (section && (strlen (section) > (MAILTMPLEN - 20))) return "";
1869 if (flags & FT_UID) { /* UID form of call */
1870 if ((msgno = mail_msgno (stream,msgno)) != 0L) flags &= ~FT_UID;
1871 else return ""; /* must get UID/msgno map first */
1873 elt = mail_elt (stream,msgno);/* get cache data */
1874 if (section && *section) { /* nested body text wanted? */
1875 if (!((b = mail_body (stream,msgno,section)) &&
1876 (b->type == TYPEMESSAGE) && !strcmp (b->subtype,"RFC822")))
1877 return ""; /* lose if no body or not MESSAGE/RFC822 */
1878 p = &b->nested.msg->text; /* point at nested message */
1879 /* build IMAP-format section specifier */
1880 sprintf (tmp,"%s.TEXT",section);
1881 flags &= ~FT_INTERNAL; /* can't win with this set */
1883 else { /* top-level message text wanted */
1884 p = &elt->private.msg.text;
1885 strcpy (tmp,"TEXT");
1887 /* initialize message data identifier */
1888 INIT_GETS (md,stream,msgno,section,0,0);
1889 if (p->text.data) { /* is data already cached? */
1890 markseen (stream,elt,flags);/* mark message seen */
1891 return mail_fetch_text_return (&md,&p->text,len);
1893 if (!stream->dtb) return ""; /* not in cache, must have live driver */
1894 if (stream->dtb->msgdata) return
1895 ((*stream->dtb->msgdata) (stream,msgno,tmp,0,0,NIL,flags) && p->text.data)?
1896 mail_fetch_text_return (&md,&p->text,len) : "";
1897 if (!(*stream->dtb->text) (stream,msgno,&bs,flags)) return "";
1898 if (section && *section) { /* nested is more complex */
1899 SETPOS (&bs,p->offset);
1900 i = p->text.size; /* just want this much */
1902 else i = SIZE (&bs); /* want entire text */
1903 return mail_fetch_string_return (&md,&bs,i,len,flags);
1906 /* Mail fetch message body part MIME headers
1907 * Accepts: mail stream
1908 * message # to fetch
1909 * MIME section specifier (#.#.#...#)
1910 * pointer to returned length
1911 * flags
1912 * Returns: message text
1915 char *mail_fetch_mime (MAILSTREAM *stream,unsigned long msgno,char *section,
1916 unsigned long *len,long flags)
1918 PARTTEXT *p;
1919 STRING bs;
1920 BODY *b;
1921 char tmp[MAILTMPLEN];
1922 if (len) *len = 0; /* default return size */
1923 if (section && (strlen (section) > (MAILTMPLEN - 20))) return "";
1924 if (flags & FT_UID) { /* UID form of call */
1925 if ((msgno = mail_msgno (stream,msgno)) != 0L) flags &= ~FT_UID;
1926 else return ""; /* must get UID/msgno map first */
1928 flags &= ~FT_INTERNAL; /* can't win with this set */
1929 if (!(section && *section && (b = mail_body (stream,msgno,section))))
1930 return ""; /* not valid section */
1931 /* in cache? */
1932 if ((p = &b->mime)->text.data) {
1933 /* mark message seen */
1934 markseen (stream,mail_elt (stream,msgno),flags);
1935 if (len) *len = p->text.size;
1936 return (char *) p->text.data;
1938 if (!stream->dtb) return ""; /* not in cache, must have live driver */
1939 if (stream->dtb->msgdata) { /* has driver fetch? */
1940 /* build driver section specifier */
1941 sprintf (tmp,"%s.MIME",section);
1942 if ((*stream->dtb->msgdata) (stream,msgno,tmp,0,0,NIL,flags) &&
1943 p->text.data) {
1944 if (len) *len = p->text.size;
1945 return (char *) p->text.data;
1947 else return "";
1949 if (len) *len = b->mime.text.size;
1950 if (!b->mime.text.size) { /* empty MIME header -- mark seen anyway */
1951 markseen (stream,mail_elt (stream,msgno),flags);
1952 return "";
1954 /* have to get it from offset */
1955 if (stream->private.search.text)
1956 return stream->private.search.text + b->mime.offset;
1957 if (!(*stream->dtb->text) (stream,msgno,&bs,flags)) {
1958 if (len) *len = 0;
1959 return "";
1961 if (bs.dtb->next == mail_string_next) {
1962 if (stream->private.search.string) stream->private.search.text = bs.curpos;
1963 return bs.curpos + b->mime.offset;
1965 return textcpyoffstring (&stream->text,&bs,b->mime.offset,b->mime.text.size);
1968 /* Mail fetch message body part
1969 * Accepts: mail stream
1970 * message # to fetch
1971 * MIME section specifier (#.#.#...#)
1972 * pointer to returned length
1973 * flags
1974 * Returns: message body
1977 char *mail_fetch_body (MAILSTREAM *stream,unsigned long msgno,char *section,
1978 unsigned long *len,long flags)
1980 GETS_DATA md;
1981 PARTTEXT *p;
1982 STRING bs;
1983 BODY *b;
1984 SIZEDTEXT *t;
1985 char *s,tmp[MAILTMPLEN];
1986 memset (&stream->private.string,NIL,sizeof (STRING));
1987 if (!(section && *section)) /* top-level text wanted? */
1988 return mail_fetch_message (stream,msgno,len,flags);
1989 else if (strlen (section) > (MAILTMPLEN - 20)) return "";
1990 flags &= ~FT_INTERNAL; /* can't win with this set */
1991 /* initialize message data identifier */
1992 INIT_GETS (md,stream,msgno,section,0,0);
1993 /* kludge for old section 0 header */
1994 if (!strcmp (s = strcpy (tmp,section),"0") ||
1995 ((s = strstr (tmp,".0")) && !s[2])) {
1996 SIZEDTEXT ht;
1997 *s = '\0'; /* tie off section */
1998 /* this silly way so it does mailgets */
1999 ht.data = (unsigned char *) mail_fetch_header (stream,msgno,
2000 tmp[0] ? tmp : NIL,NIL,
2001 &ht.size,flags);
2002 /* may have UIDs here */
2003 md.flags = (flags & FT_UID) ? MG_UID : NIL;
2004 return mail_fetch_text_return (&md,&ht,len);
2006 if (len) *len = 0; /* default return size */
2007 if (flags & FT_UID) { /* UID form of call */
2008 if ((msgno = mail_msgno (stream,msgno)) != 0L) flags &= ~FT_UID;
2009 else return ""; /* must get UID/msgno map first */
2011 /* must have body */
2012 if (!(b = mail_body (stream,msgno,section))) return "";
2013 /* have cached text? */
2014 if ((t = &(p = &b->contents)->text)->data) {
2015 /* mark message seen */
2016 markseen (stream,mail_elt (stream,msgno),flags);
2017 return mail_fetch_text_return (&md,t,len);
2019 if (!stream->dtb) return ""; /* not in cache, must have live driver */
2020 if (stream->dtb->msgdata) return
2021 ((*stream->dtb->msgdata)(stream,msgno,section,0,0,NIL,flags) && t->data) ?
2022 mail_fetch_text_return (&md,t,len) : "";
2023 if (len) *len = t->size;
2024 if (!t->size) { /* empty body part -- mark seen anyway */
2025 markseen (stream,mail_elt (stream,msgno),flags);
2026 return "";
2028 /* copy body from stringstruct offset */
2029 if (stream->private.search.text)
2030 return stream->private.search.text + p->offset;
2031 if (!(*stream->dtb->text) (stream,msgno,&bs,flags)) {
2032 if (len) *len = 0;
2033 return "";
2035 if (bs.dtb->next == mail_string_next) {
2036 if (stream->private.search.string) stream->private.search.text = bs.curpos;
2037 return bs.curpos + p->offset;
2039 SETPOS (&bs,p->offset);
2040 return mail_fetch_string_return (&md,&bs,t->size,len,flags);
2043 /* Mail fetch partial message text
2044 * Accepts: mail stream
2045 * message # to fetch
2046 * MIME section specifier (#.#.#...#)
2047 * offset of first designed byte or 0 to start at beginning
2048 * maximum number of bytes or 0 for all bytes
2049 * flags
2050 * Returns: T if successful, else NIL
2053 long mail_partial_text (MAILSTREAM *stream,unsigned long msgno,char *section,
2054 unsigned long first,unsigned long last,long flags)
2056 GETS_DATA md;
2057 PARTTEXT *p = NIL;
2058 MESSAGECACHE *elt;
2059 STRING bs;
2060 BODY *b;
2061 char tmp[MAILTMPLEN];
2062 unsigned long i;
2063 if (!mailgets) fatal ("mail_partial_text() called without a mailgets!");
2064 if (section && (strlen (section) > (MAILTMPLEN - 20))) return NIL;
2065 if (flags & FT_UID) { /* UID form of call */
2066 if ((msgno = mail_msgno (stream,msgno)) != 0L) flags &= ~FT_UID;
2067 else return NIL; /* must get UID/msgno map first */
2069 elt = mail_elt (stream,msgno);/* get cache data */
2070 flags &= ~FT_INTERNAL; /* bogus if this is set */
2071 if (section && *section) { /* nested body text wanted? */
2072 if (!((b = mail_body (stream,msgno,section)) &&
2073 (b->type == TYPEMESSAGE) && !strcmp (b->subtype,"RFC822")))
2074 return NIL; /* lose if no body or not MESSAGE/RFC822 */
2075 p = &b->nested.msg->text; /* point at nested message */
2076 /* build IMAP-format section specifier */
2077 sprintf (tmp,"%s.TEXT",section);
2079 else { /* else top-level message text wanted */
2080 p = &elt->private.msg.text;
2081 strcpy (tmp,"TEXT");
2084 /* initialize message data identifier */
2085 INIT_GETS (md,stream,msgno,tmp,first,last);
2086 if (p->text.data) { /* is data already cached? */
2087 INIT (&bs,mail_string,p->text.data,i = p->text.size);
2088 markseen (stream,elt,flags);/* mark message seen */
2090 else { /* else get data from driver */
2091 if (!stream->dtb) return NIL;
2092 if (stream->dtb->msgdata) /* driver will handle this */
2093 return (*stream->dtb->msgdata) (stream,msgno,tmp,first,last,NIL,flags);
2094 if (!(*stream->dtb->text) (stream,msgno,&bs,flags)) return NIL;
2095 if (section && *section) { /* nexted if more complex */
2096 SETPOS (&bs,p->offset); /* offset stringstruct to data */
2097 i = p->text.size; /* maximum size of data */
2099 else i = SIZE (&bs); /* just want this much */
2101 if (i <= first) i = first = 0;/* first byte is beyond end of text */
2102 /* truncate as needed */
2103 else { /* offset and truncate */
2104 SETPOS (&bs,first + GETPOS (&bs));
2105 i -= first; /* reduced size */
2106 if (last && (i > last)) i = last;
2108 /* do the mailgets thing */
2109 (*mailgets) (mail_read,&bs,i,&md);
2110 return T; /* success */
2113 /* Mail fetch partial message body part
2114 * Accepts: mail stream
2115 * message # to fetch
2116 * MIME section specifier (#.#.#...#)
2117 * offset of first designed byte or 0 to start at beginning
2118 * maximum number of bytes or 0 for all bytes
2119 * flags
2120 * Returns: T if successful, else NIL
2123 long mail_partial_body (MAILSTREAM *stream,unsigned long msgno,char *section,
2124 unsigned long first,unsigned long last,long flags)
2126 GETS_DATA md;
2127 PARTTEXT *p;
2128 STRING bs;
2129 BODY *b;
2130 SIZEDTEXT *t;
2131 unsigned long i;
2132 if (!(section && *section)) /* top-level text wanted? */
2133 return mail_partial_text (stream,msgno,NIL,first,last,flags);
2134 if (!mailgets) fatal ("mail_partial_body() called without a mailgets!");
2135 if (flags & FT_UID) { /* UID form of call */
2136 if ((msgno = mail_msgno (stream,msgno)) != 0L) flags &= ~FT_UID;
2137 else return NIL; /* must get UID/msgno map first */
2139 /* must have body */
2140 if (!(b = mail_body (stream,msgno,section))) return NIL;
2141 flags &= ~FT_INTERNAL; /* bogus if this is set */
2143 /* initialize message data identifier */
2144 INIT_GETS (md,stream,msgno,section,first,last);
2145 /* have cached text? */
2146 if ((t = &(p = &b->contents)->text)->data) {
2147 /* mark message seen */
2148 markseen (stream,mail_elt (stream,msgno),flags);
2149 INIT (&bs,mail_string,t->data,i = t->size);
2151 else { /* else get data from driver */
2152 if (!stream->dtb) return NIL;
2153 if (stream->dtb->msgdata) /* driver will handle this */
2154 return (*stream->dtb->msgdata) (stream,msgno,section,first,last,NIL,
2155 flags);
2156 if (!(*stream->dtb->text) (stream,msgno,&bs,flags)) return NIL;
2157 if (section && *section) { /* nexted if more complex */
2158 SETPOS (&bs,p->offset); /* offset stringstruct to data */
2159 i = t->size; /* maximum size of data */
2161 else i = SIZE (&bs); /* just want this much */
2163 if (i <= first) i = first = 0;/* first byte is beyond end of text */
2164 else { /* offset and truncate */
2165 SETPOS (&bs,first + GETPOS (&bs));
2166 i -= first; /* reduced size */
2167 if (last && (i > last)) i = last;
2169 /* do the mailgets thing */
2170 (*mailgets) (mail_read,&bs,i,&md);
2171 return T; /* success */
2174 /* Mail return message text
2175 * Accepts: identifier data
2176 * sized text
2177 * pointer to returned length
2178 * Returns: text
2181 char *mail_fetch_text_return (GETS_DATA *md,SIZEDTEXT *t,unsigned long *len)
2183 STRING bs;
2184 if (len) *len = t->size; /* return size */
2185 if (t->size && mailgets) { /* have to do the mailgets thing? */
2186 /* silly but do it anyway for consistency */
2187 INIT (&bs,mail_string,t->data,t->size);
2188 return (*mailgets) (mail_read,&bs,t->size,md);
2190 return t->size ? (char *) t->data : "";
2194 /* Mail return message string
2195 * Accepts: identifier data
2196 * stringstruct
2197 * text length
2198 * pointer to returned length
2199 * flags
2200 * Returns: text, or NIL if stringstruct returned
2203 char *mail_fetch_string_return (GETS_DATA *md,STRING *bs,unsigned long i,
2204 unsigned long *len,long flags)
2206 char *ret = NIL;
2207 if (len) *len = i; /* return size */
2208 /* return stringstruct hack */
2209 if (flags & FT_RETURNSTRINGSTRUCT) {
2210 memcpy (&md->stream->private.string,bs,sizeof (STRING));
2211 SETPOS (&md->stream->private.string,GETPOS (&md->stream->private.string));
2213 /* have to do the mailgets thing? */
2214 else if (mailgets) ret = (*mailgets) (mail_read,bs,i,md);
2215 /* special hack to avoid extra copy */
2216 else if (bs->dtb->next == mail_string_next) ret = bs->curpos;
2217 /* make string copy in memory */
2218 else ret = textcpyoffstring (&md->stream->text,bs,GETPOS (bs),i);
2219 return ret;
2222 /* Read data from stringstruct
2223 * Accepts: stringstruct
2224 * size of data to read
2225 * buffer to read into
2226 * Returns: T, always, stringstruct updated
2229 long mail_read (void *stream,unsigned long size,char *buffer)
2231 unsigned long i;
2232 STRING *s = (STRING *) stream;
2233 while (size) { /* until satisfied */
2234 memcpy (buffer,s->curpos,i = min (s->cursize,size));
2235 buffer += i; /* update buffer */
2236 size -= i; /* note that we read this much */
2237 s->curpos += --i; /* advance that many spaces minus 1 */
2238 s->cursize -= i;
2239 SNX (s); /* now use SNX to advance the last byte */
2241 return T;
2244 /* Mail fetch UID
2245 * Accepts: mail stream
2246 * message number
2247 * Returns: UID or zero if dead stream
2250 unsigned long mail_uid (MAILSTREAM *stream,unsigned long msgno)
2252 unsigned long uid = mail_elt (stream,msgno)->private.uid;
2253 return uid ? uid :
2254 (stream->dtb && stream->dtb->uid) ? (*stream->dtb->uid) (stream,msgno) : 0;
2258 /* Mail fetch msgno from UID
2259 * Accepts: mail stream
2260 * UID
2261 * Returns: msgno or zero if failed
2264 unsigned long mail_msgno (MAILSTREAM *stream,unsigned long uid)
2266 unsigned long msgno,delta,first,firstuid,last,lastuid,middle,miduid;
2267 if (stream->dtb) { /* active stream? */
2268 if (stream->dtb->msgno) /* direct way */
2269 return (*stream->dtb->msgno) (stream,uid);
2270 else if (stream->dtb->uid) {/* indirect way */
2271 /* Placeholder for now, since currently there are no drivers which
2272 * have a uid method but not a msgno method
2274 for (msgno = 1; msgno <= stream->nmsgs; msgno++)
2275 if ((*stream->dtb->uid) (stream,msgno) == uid) return msgno;
2277 /* binary search since have full map */
2278 else for (first = 1,last = stream->nmsgs, delta = (first <= last) ? 1 : 0;
2279 delta &&
2280 (uid >= (firstuid = mail_elt (stream,first)->private.uid)) &&
2281 (uid <= (lastuid = mail_elt (stream,last)->private.uid));) {
2282 /* done if match at an endpoint */
2283 if (uid == firstuid) return first;
2284 if (uid == lastuid) return last;
2285 /* have anything between endpoints? */
2286 if ((delta = ((last - first) / 2)) != 0L){
2287 if ((miduid = mail_elt (stream,middle = first + delta)->private.uid)
2288 == uid)
2289 return middle; /* found match in middle */
2290 else if (uid < miduid) last = middle - 1;
2291 else first = middle + 1;
2295 else { /* dead stream, do linear search for UID */
2296 for (msgno = 1; msgno <= stream->nmsgs; msgno++)
2297 if (mail_elt (stream,msgno)->private.uid == uid) return msgno;
2299 return 0; /* didn't find the UID anywhere */
2302 /* Mail fetch From string for menu
2303 * Accepts: destination string
2304 * mail stream
2305 * message # to fetch
2306 * desired string length
2307 * Returns: string of requested length
2310 void mail_fetchfrom (char *s,MAILSTREAM *stream,unsigned long msgno,
2311 long length)
2313 char *t;
2314 char tmp[MAILTMPLEN];
2315 ENVELOPE *env = mail_fetchenvelope (stream,msgno);
2316 ADDRESS *adr = env ? env->from : NIL;
2317 memset (s,' ',(size_t)length);/* fill it with spaces */
2318 s[length] = '\0'; /* tie off with null */
2319 /* get first from address from envelope */
2320 while (adr && !adr->host) adr = adr->next;
2321 if (adr) { /* if a personal name exists use it */
2322 if (!(t = adr->personal))
2323 sprintf (t = tmp,"%.256s@%.256s",adr->mailbox,adr->host);
2324 memcpy (s,t,(size_t) min (length,(long) strlen (t)));
2329 /* Mail fetch Subject string for menu
2330 * Accepts: destination string
2331 * mail stream
2332 * message # to fetch
2333 * desired string length
2334 * Returns: string of no more than requested length
2337 void mail_fetchsubject (char *s,MAILSTREAM *stream,unsigned long msgno,
2338 long length)
2340 ENVELOPE *env = mail_fetchenvelope (stream,msgno);
2341 memset (s,'\0',(size_t) length+1);
2342 /* copy subject from envelope */
2343 if (env && env->subject) strncpy (s,env->subject,(size_t) length);
2344 else *s = ' '; /* if no subject then just a space */
2347 /* Mail modify flags
2348 * Accepts: mail stream
2349 * sequence
2350 * flag(s)
2351 * option flags
2354 void mail_flag (MAILSTREAM *stream,char *sequence,char *flag,long flags)
2356 MESSAGECACHE *elt;
2357 unsigned long i,uf;
2358 long f;
2359 short nf;
2360 if (!stream->dtb) return; /* no-op if no stream */
2361 if ((stream->dtb->flagmsg || !stream->dtb->flag) &&
2362 ((flags & ST_UID) ? mail_uid_sequence (stream,sequence) :
2363 mail_sequence (stream,sequence)) &&
2364 ((f = mail_parse_flags (stream,flag,&uf)) || uf))
2365 for (i = 1,nf = (flags & ST_SET) ? T : NIL; i <= stream->nmsgs; i++)
2366 if ((elt = mail_elt (stream,i))->sequence) {
2367 struct { /* old flags */
2368 unsigned int valid : 1;
2369 unsigned int seen : 1;
2370 unsigned int deleted : 1;
2371 unsigned int flagged : 1;
2372 unsigned int answered : 1;
2373 unsigned int draft : 1;
2374 unsigned long user_flags;
2375 } old;
2376 old.valid = elt->valid; old.seen = elt->seen;
2377 old.deleted = elt->deleted; old.flagged = elt->flagged;
2378 old.answered = elt->answered; old.draft = elt->draft;
2379 old.user_flags = elt->user_flags;
2380 elt->valid = NIL; /* prepare for flag alteration */
2381 if (stream->dtb->flagmsg) (*stream->dtb->flagmsg) (stream,elt);
2382 if (f&fSEEN) elt->seen = nf;
2383 if (f&fDELETED) elt->deleted = nf;
2384 if (f&fFLAGGED) elt->flagged = nf;
2385 if (f&fANSWERED) elt->answered = nf;
2386 if (f&fDRAFT) elt->draft = nf;
2387 /* user flags */
2388 if (flags & ST_SET) elt->user_flags |= uf;
2389 else elt->user_flags &= ~uf;
2390 elt->valid = T; /* flags now altered */
2391 if ((old.valid != elt->valid) || (old.seen != elt->seen) ||
2392 (old.deleted != elt->deleted) || (old.flagged != elt->flagged) ||
2393 (old.answered != elt->answered) || (old.draft != elt->draft) ||
2394 (old.user_flags != elt->user_flags))
2395 MM_FLAGS (stream,elt->msgno);
2396 if (stream->dtb->flagmsg) (*stream->dtb->flagmsg) (stream,elt);
2398 /* call driver once */
2399 if (stream->dtb->flag) (*stream->dtb->flag) (stream,sequence,flag,flags);
2402 /* Mail search for messages
2403 * Accepts: mail stream
2404 * character set
2405 * search program
2406 * option flags
2407 * Returns: T if successful, NIL if dead stream, NIL searchpgm or bad charset
2410 long mail_search_full (MAILSTREAM *stream,char *charset,SEARCHPGM *pgm,
2411 long flags)
2413 unsigned long i;
2414 long ret = NIL;
2415 if (!(flags & SE_RETAIN)) /* clear search vector unless retaining */
2416 for (i = 1; i <= stream->nmsgs; ++i) mail_elt (stream,i)->searched = NIL;
2417 if (pgm && stream->dtb) /* must have a search program and driver */
2418 ret = (*(stream->dtb->search ? stream->dtb->search : mail_search_default))
2419 (stream,charset,pgm,flags);
2420 /* flush search program if requested */
2421 if (flags & SE_FREE) mail_free_searchpgm (&pgm);
2422 return ret;
2426 /* Mail search for messages default handler
2427 * Accepts: mail stream
2428 * character set
2429 * search program
2430 * option flags
2431 * Returns: T if successful, NIL if bad charset
2434 long mail_search_default (MAILSTREAM *stream,char *charset,SEARCHPGM *pgm,
2435 long flags)
2437 unsigned long i;
2438 char *msg;
2439 /* make sure that charset is good */
2440 if ((msg = utf8_badcharset (charset)) != NULL) {
2441 MM_LOG (msg,ERROR); /* output error */
2442 fs_give ((void **) &msg);
2443 return NIL;
2445 utf8_searchpgm (pgm,charset);
2446 for (i = 1; i <= stream->nmsgs; ++i)
2447 if (mail_search_msg (stream,i,NIL,pgm)) {
2448 if (flags & SE_UID) mm_searched (stream,mail_uid (stream,i));
2449 else { /* mark as searched, notify mail program */
2450 mail_elt (stream,i)->searched = T;
2451 if (!stream->silent) mm_searched (stream,i);
2454 return LONGT; /* search completed */
2457 /* Mail ping mailbox
2458 * Accepts: mail stream
2459 * Returns: stream if still open else NIL
2462 long mail_ping (MAILSTREAM *stream)
2464 unsigned long i,n,uf,len;
2465 char *s,*f,tmp[MAILTMPLEN],flags[MAILTMPLEN];
2466 MAILSTREAM *snarf;
2467 MESSAGECACHE *elt;
2468 STRING bs;
2469 long ret;
2470 /* do driver action */
2471 if ((ret = ((stream && stream->dtb) ? (stream->dtb->ping) (stream) : NIL)) &&
2472 stream->snarf.name && /* time to snarf? */
2473 /* prohibit faster than once/min */
2474 (time (0) > (time_t) (stream->snarf.time + min(60,mailsnarfinterval))) &&
2475 (snarf = mail_open (NIL,stream->snarf.name,
2476 stream->snarf.options | OP_SILENT))) {
2477 if ((n = snarf->nmsgs) && /* yes, have messages to snarf? */
2478 mail_search_full (snarf,NIL,mail_criteria ("UNDELETED"),SE_FREE)) {
2479 for (i = 1; ret && (i <= n); i++) /* for each message */
2480 if ((elt = mail_elt (snarf,i))->searched &&
2481 (s = mail_fetch_message (snarf,i,&len,FT_PEEK)) && len) {
2482 INIT (&bs,mail_string,s,len);
2483 if (mailsnarfpreserve) {
2484 /* yes, make sure have fast data */
2485 if (!elt->valid || !elt->day) {
2486 sprintf (tmp,"%lu",n);
2487 mail_fetch_fast (snarf,tmp,NIL);
2489 /* initialize flag string */
2490 memset (flags,0,MAILTMPLEN);
2491 /* output system flags except \Deleted */
2492 if (elt->seen) strcat (flags," \\Seen");
2493 if (elt->flagged) strcat (flags," \\Flagged");
2494 if (elt->answered) strcat (flags," \\Answered");
2495 if (elt->draft) strcat (flags," \\Draft");
2496 /* any user flags? */
2497 for (uf = elt->user_flags,s = flags + strlen (flags);
2498 uf && (f = stream->user_flags[find_rightmost_bit (&uf)]) &&
2499 ((MAILTMPLEN - (s - tmp)) > (long) (2 + strlen (f)));
2500 s += strlen (s)) sprintf (s," %s",f);
2501 ret = mail_append_full (stream,stream->mailbox,flags + 1,
2502 mail_date (tmp,elt),&bs);
2504 else ret = mail_append (stream,stream->mailbox,&bs);
2506 if (ret) { /* did snarf succeed? */
2507 /* driver has per-message (or no) flag call */
2508 if (snarf->dtb->flagmsg || !snarf->dtb->flag) {
2509 elt->valid = NIL; /* prepare for flag alteration */
2510 if (snarf->dtb->flagmsg) (*snarf->dtb->flagmsg) (snarf,elt);
2511 /* flags now altered */
2512 elt->deleted = elt->seen = elt->valid = T;
2513 if (snarf->dtb->flagmsg) (*snarf->dtb->flagmsg) (snarf,elt);
2515 /* driver has one-time flag call */
2516 if (snarf->dtb->flag) {
2517 sprintf (tmp,"%lu",i);
2518 (*snarf->dtb->flag) (snarf,tmp,"\\Deleted \\Seen",ST_SET);
2521 else { /* copy failed */
2522 sprintf (tmp,"Unable to move message %lu from %s mailbox",
2523 i,snarf->dtb->name);
2524 mm_log (tmp,WARN);
2528 /* expunge the messages */
2529 mail_close_full (snarf,n ? CL_EXPUNGE : NIL);
2530 stream->snarf.time = (unsigned long) time (0);
2531 /* Even if the snarf failed, we don't want to return NIL if the stream
2532 * is still alive. Or at least that's what we currently think.
2534 /* redo the driver's action */
2535 ret = stream->dtb ? (*stream->dtb->ping) (stream) : NIL;
2537 return ret;
2540 /* Mail check mailbox
2541 * Accepts: mail stream
2544 void mail_check (MAILSTREAM *stream)
2546 /* do the driver's action */
2547 if (stream->dtb) (*stream->dtb->check) (stream);
2551 /* Mail expunge mailbox
2552 * Accepts: mail stream
2553 * sequence to expunge if non-NIL
2554 * expunge options
2555 * Returns: T on success, NIL on failure
2558 long mail_expunge_full (MAILSTREAM *stream,char *sequence,long options)
2560 /* do the driver's action */
2561 return stream->dtb ? (*stream->dtb->expunge) (stream,sequence,options) : NIL;
2565 /* Mail copy message(s)
2566 * Accepts: mail stream
2567 * sequence
2568 * destination mailbox
2569 * flags
2572 long mail_copy_full (MAILSTREAM *stream,char *sequence,char *mailbox,
2573 long options)
2575 return stream->dtb ?
2576 SAFE_COPY (stream->dtb,stream,sequence,mailbox,options) : NIL;
2579 /* Append data package to use for old single-message mail_append() interface */
2581 typedef struct mail_append_package {
2582 char *flags; /* initial flags */
2583 char *date; /* message internal date */
2584 STRING *message; /* stringstruct of message */
2585 } APPENDPACKAGE;
2588 /* Single append message string
2589 * Accepts: mail stream
2590 * package pointer (cast as a void *)
2591 * pointer to return initial flags
2592 * pointer to return message internal date
2593 * pointer to return stringstruct of message to append
2594 * Returns: T, always
2597 static long mail_append_single (MAILSTREAM *stream,void *data,char **flags,
2598 char **date,STRING **message)
2600 APPENDPACKAGE *ap = (APPENDPACKAGE *) data;
2601 *flags = ap->flags; /* get desired data from the package */
2602 *date = ap->date;
2603 *message = ap->message;
2604 ap->message = NIL; /* so next callback puts a stop to it */
2605 return LONGT; /* always return success */
2609 /* Mail append message string
2610 * Accepts: mail stream
2611 * destination mailbox
2612 * initial flags
2613 * message internal date
2614 * stringstruct of message to append
2615 * Returns: T on success, NIL on failure
2618 long mail_append_full (MAILSTREAM *stream,char *mailbox,char *flags,char *date,
2619 STRING *message)
2621 APPENDPACKAGE ap;
2622 ap.flags = flags; /* load append package */
2623 ap.date = date;
2624 ap.message = message;
2625 return mail_append_multiple (stream,mailbox,mail_append_single,(void *) &ap);
2628 /* Mail append message(s)
2629 * Accepts: mail stream
2630 * destination mailbox
2631 * append data callback
2632 * arbitrary data for callback use
2633 * Returns: T on success, NIL on failure
2636 long mail_append_multiple (MAILSTREAM *stream,char *mailbox,append_t af,
2637 void *data)
2639 char *s,tmp[MAILTMPLEN];
2640 DRIVER *d = NIL;
2641 long ret = NIL;
2642 /* never allow names with newlines */
2643 if (strpbrk (mailbox,"\015\012"))
2644 MM_LOG ("Can't append to mailbox with such a name",ERROR);
2645 else if (strlen (mailbox) >=
2646 (NETMAXHOST+(NETMAXUSER*2)+NETMAXMBX+NETMAXSRV+50)) {
2647 sprintf (tmp,"Can't append %.80s: %s",mailbox,(*mailbox == '{') ?
2648 "invalid remote specification" : "no such mailbox");
2649 MM_LOG (tmp,ERROR);
2651 /* special driver hack? */
2652 else if (!strncmp (lcase (strcpy (tmp,mailbox)),"#driver.",8)) {
2653 /* yes, tie off name at likely delimiter */
2654 if (!(s = strpbrk (tmp+8,"/\\:"))) {
2655 sprintf (tmp,"Can't append to mailbox %.80s: bad driver syntax",mailbox);
2656 MM_LOG (tmp,ERROR);
2657 return NIL;
2659 *s++ = '\0'; /* tie off at delimiter */
2660 if (!(d = (DRIVER *) mail_parameters (NIL,GET_DRIVER,tmp+8))) {
2661 sprintf (tmp,"Can't append to mailbox %.80s: unknown driver",mailbox);
2662 MM_LOG (tmp,ERROR);
2664 else ret = SAFE_APPEND (d,stream,mailbox + (s - tmp),af,data);
2666 else if ((d = mail_valid (stream,mailbox,NIL)) != NULL)
2667 ret = SAFE_APPEND (d,stream,mailbox,af,data);
2668 /* No driver, try for TRYCREATE if no stream. Note that we use the
2669 * createProto here, not the appendProto, since the dummy driver already
2670 * took care of the appendProto case. Otherwise, if appendProto is set to
2671 * NIL, we won't get a TRYCREATE.
2673 else if (!stream && (stream = default_proto (NIL)) && stream->dtb &&
2674 SAFE_APPEND (stream->dtb,stream,mailbox,af,data))
2675 /* timing race? */
2676 MM_NOTIFY (stream,"Append validity confusion",WARN);
2677 /* generate error message */
2678 else mail_valid (stream,mailbox,"append to mailbox");
2679 return ret;
2682 /* Mail garbage collect stream
2683 * Accepts: mail stream
2684 * garbage collection flags
2687 void mail_gc (MAILSTREAM *stream,long gcflags)
2689 MESSAGECACHE *elt;
2690 unsigned long i;
2691 /* do the driver's action first */
2692 if (stream->dtb && stream->dtb->gc) (*stream->dtb->gc) (stream,gcflags);
2693 stream->msgno = 0; /* nothing cached now */
2694 if (gcflags & GC_ENV) { /* garbage collect envelopes? */
2695 if (stream->env) mail_free_envelope (&stream->env);
2696 if (stream->body) mail_free_body (&stream->body);
2698 if (gcflags & GC_TEXTS) { /* free texts */
2699 if (stream->text.data) fs_give ((void **) &stream->text.data);
2700 stream->text.size = 0;
2702 /* garbage collect per-message stuff */
2703 for (i = 1; i <= stream->nmsgs; i++)
2704 if ((elt = (MESSAGECACHE *) (*mailcache) (stream,i,CH_ELT)) != NULL)
2705 mail_gc_msg (&elt->private.msg,gcflags);
2709 /* Mail garbage collect message
2710 * Accepts: message structure
2711 * garbage collection flags
2714 void mail_gc_msg (MESSAGE *msg,long gcflags)
2716 if (gcflags & GC_ENV) { /* garbage collect envelopes? */
2717 mail_free_envelope (&msg->env);
2718 mail_free_body (&msg->body);
2720 if (gcflags & GC_TEXTS) { /* garbage collect texts */
2721 if (msg->full.text.data) fs_give ((void **) &msg->full.text.data);
2722 if (msg->header.text.data) {
2723 mail_free_stringlist (&msg->lines);
2724 fs_give ((void **) &msg->header.text.data);
2726 if (msg->text.text.data) fs_give ((void **) &msg->text.text.data);
2727 /* now GC all body components */
2728 if (msg->body) mail_gc_body (msg->body);
2732 /* Mail garbage collect texts in BODY structure
2733 * Accepts: BODY structure
2736 void mail_gc_body (BODY *body)
2738 PART *part;
2739 switch (body->type) { /* free contents */
2740 case TYPEMULTIPART: /* multiple part */
2741 for (part = body->nested.part; part; part = part->next)
2742 mail_gc_body (&part->body);
2743 break;
2744 case TYPEMESSAGE: /* encapsulated message */
2745 if (body->subtype && !strcmp (body->subtype,"RFC822")) {
2746 mail_free_stringlist (&body->nested.msg->lines);
2747 mail_gc_msg (body->nested.msg,GC_TEXTS);
2749 break;
2750 default:
2751 break;
2753 if (body->mime.text.data) fs_give ((void **) &body->mime.text.data);
2754 if (body->contents.text.data) fs_give ((void **) &body->contents.text.data);
2756 /* Mail get body section
2757 * Accepts: body of message
2758 * section specifier
2759 * Returns: pointer to body at given section
2762 BODY *mail_body_section (BODY *b, unsigned char *section)
2764 PART *pt;
2765 unsigned long i;
2766 /* make sure have a body */
2767 if (section && *section && b)
2768 while (*section) { /* find desired section */
2769 if (isdigit (*section)) { /* get section specifier */
2770 /* make sure what follows is valid */
2771 if (!(i = strtoul (section,(char **) &section,10)) ||
2772 (*section && ((*section++ != '.') || !*section))) return NIL;
2773 /* multipart content? */
2774 if (b->type == TYPEMULTIPART) {
2775 /* yes, find desired part */
2776 if ((pt = b->nested.part) != NULL) while (--i && (pt = pt->next));
2777 if (!pt) return NIL; /* bad specifier */
2778 b = &pt->body; /* note new body */
2780 /* otherwise must be section 1 */
2781 else if (i != 1) return NIL;
2782 /* need to go down further? */
2783 if (*section) switch (b->type) {
2784 case TYPEMULTIPART: /* multipart */
2785 break;
2786 case TYPEMESSAGE: /* embedded message */
2787 if (!strcmp (b->subtype,"RFC822")) {
2788 b = b->nested.msg->body;
2789 break;
2791 default: /* bogus subpart specification */
2792 return NIL;
2795 else return NIL; /* unknown section specifier */
2797 return b;
2800 /* Mail get body part
2801 * Accepts: mail stream
2802 * message number
2803 * section specifier
2804 * Returns: pointer to body
2807 BODY *mail_body (MAILSTREAM *stream,unsigned long msgno,unsigned char *section)
2809 BODY *b = NIL;
2810 /* make sure have a body */
2811 if (section && *section && mail_fetchstructure (stream,msgno,&b) && b)
2812 return mail_body_section(b, section);
2813 return b;
2816 /* Mail output date from elt fields
2817 * Accepts: character string to write into
2818 * elt to get data data from
2819 * Returns: the character string
2822 const char *days[] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
2824 const char *months[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
2825 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
2827 char *mail_date (char *string,MESSAGECACHE *elt)
2829 sprintf (string,"%2d-%s-%d %02d:%02d:%02d %c%02d%02d",
2830 elt->day ? elt->day : 1,
2831 months[elt->month ? (elt->month - 1) : 0],
2832 elt->year + BASEYEAR,elt->hours,elt->minutes,elt->seconds,
2833 elt->zoccident ? '-' : '+',elt->zhours,elt->zminutes);
2834 return string;
2838 /* Mail output extended-ctime format date from elt fields
2839 * Accepts: character string to write into
2840 * elt to get data data from
2841 * Returns: the character string
2844 char *mail_cdate (char *string,MESSAGECACHE *elt)
2846 char *fmt = "%s %s %2d %02d:%02d:%02d %4d %s%02d%02d\n";
2847 int d = elt->day ? elt->day : 1;
2848 int m = elt->month ? (elt->month - 1) : 0;
2849 int y = elt->year + BASEYEAR;
2850 const char *s = months[m];
2851 if (m < 2) { /* if before March, */
2852 m += 10; /* January = month 10 of previous year */
2853 y--;
2855 else m -= 2; /* March is month 0 */
2856 sprintf (string,fmt,days[(int) (d + 2 + ((7 + 31 * m) / 12)
2857 #ifndef USEJULIANCALENDAR
2858 #ifndef USEORTHODOXCALENDAR /* Gregorian calendar */
2859 + (y / 400)
2860 #ifdef Y4KBUGFIX
2861 - (y / 4000)
2862 #endif
2863 #else /* Orthodox calendar */
2864 + (2 * (y / 900)) + ((y % 900) >= 200)
2865 + ((y % 900) >= 600)
2866 #endif
2867 - (y / 100)
2868 #endif
2869 + y + (y / 4)) % 7],
2870 s,d,elt->hours,elt->minutes,elt->seconds,elt->year + BASEYEAR,
2871 elt->zoccident ? "-" : "+",elt->zhours,elt->zminutes);
2872 return string;
2875 /* Mail parse date into elt fields
2876 * Accepts: elt to write into
2877 * date string to parse
2878 * Returns: T if parse successful, else NIL
2879 * This routine parses dates as follows:
2880 * . leading three alphas followed by comma and space are ignored
2881 * . date accepted in format: mm/dd/yy, mm/dd/yyyy, dd-mmm-yy, dd-mmm-yyyy,
2882 * dd mmm yy, dd mmm yyyy, yyyy-mm-dd, yyyymmdd
2883 * . two and three digit years interpreted according to RFC 2822 rules
2884 * . mandatory end of string if yyyy-mm-dd or yyyymmdd; otherwise optional
2885 * space followed by time:
2886 * . time accepted in format hh:mm:ss or hh:mm
2887 * . end of string accepted
2888 * . timezone accepted: hyphen followed by symbolic timezone, or space
2889 * followed by signed numeric timezone or symbolic timezone
2890 * Examples of normal input:
2891 * . IMAP date-only (SEARCH):
2892 * dd-mmm-yyyy
2893 * . IMAP date-time (INTERNALDATE):
2894 * dd-mmm-yyyy hh:mm:ss +zzzz
2895 * . RFC-822:
2896 * www, dd mmm yy hh:mm:ss zzz
2897 * . RFC-2822:
2898 * www, dd mmm yyyy hh:mm:ss +zzzz
2901 long mail_parse_date (MESSAGECACHE *elt,unsigned char *s)
2903 unsigned long d,m,y;
2904 int mi,ms;
2905 struct tm *t;
2906 time_t tn;
2907 char tmp[MAILTMPLEN];
2908 static unsigned long maxyear = 0;
2909 if (!maxyear) { /* know the end of time yet? */
2910 MESSAGECACHE tmpelt;
2911 memset (&tmpelt,0xff,sizeof (MESSAGECACHE));
2912 maxyear = BASEYEAR + tmpelt.year;
2914 /* clear elt */
2915 elt->zoccident = elt->zhours = elt->zminutes =
2916 elt->hours = elt->minutes = elt->seconds =
2917 elt->day = elt->month = elt->year = 0;
2918 /* make a writeable uppercase copy */
2919 if (s && *s && (strlen (s) < (size_t)MAILTMPLEN)) s = ucase (strcpy (tmp,s));
2920 else return NIL;
2921 /* skip over possible day of week */
2922 if (isalpha (*s) && isalpha (s[1]) && isalpha (s[2]) && (s[3] == ',') &&
2923 (s[4] == ' ')) s += 5;
2924 while (*s == ' ') s++; /* parse first number (probable month) */
2925 if (!(m = strtoul (s,(char **) &s,10))) return NIL;
2927 switch (*s) { /* different parse based on delimiter */
2928 case '/': /* mm/dd/yy format */
2929 if (isdigit (*++s) && (d = strtoul (s,(char **) &s,10)) &&
2930 (*s == '/') && isdigit (*++s)) {
2931 y = strtoul (s,(char **) &s,10);
2932 if (*s == '\0') break; /* must end here */
2934 return NIL; /* bogon */
2935 case ' ': /* dd mmm yy format */
2936 while (s[1] == ' ') s++; /* slurp extra whitespace */
2937 case '-':
2938 if (isdigit (s[1])) { /* possible ISO 8601 date format? */
2939 y = m; /* yes, first number is year */
2940 /* get month and day */
2941 if ((m = strtoul (s+1,(char **) &s,10)) && (*s++ == '-') &&
2942 (d = strtoul (s,(char **) &s,10)) && !*s) break;
2943 return NIL; /* syntax error or time present */
2945 d = m; /* dd-mmm-yy[yy], so first number is a day */
2946 /* make sure string long enough! */
2947 if (strlen (s) < (size_t) 5) return NIL;
2948 /* Some compilers don't allow `<<' and/or longs in case statements. */
2949 /* slurp up the month string */
2950 ms = ((s[1] - 'A') * 1024) + ((s[2] - 'A') * 32) + (s[3] - 'A');
2951 switch (ms) { /* determine the month */
2952 case (('J'-'A') * 1024) + (('A'-'A') * 32) + ('N'-'A'): m = 1; break;
2953 case (('F'-'A') * 1024) + (('E'-'A') * 32) + ('B'-'A'): m = 2; break;
2954 case (('M'-'A') * 1024) + (('A'-'A') * 32) + ('R'-'A'): m = 3; break;
2955 case (('A'-'A') * 1024) + (('P'-'A') * 32) + ('R'-'A'): m = 4; break;
2956 case (('M'-'A') * 1024) + (('A'-'A') * 32) + ('Y'-'A'): m = 5; break;
2957 case (('J'-'A') * 1024) + (('U'-'A') * 32) + ('N'-'A'): m = 6; break;
2958 case (('J'-'A') * 1024) + (('U'-'A') * 32) + ('L'-'A'): m = 7; break;
2959 case (('A'-'A') * 1024) + (('U'-'A') * 32) + ('G'-'A'): m = 8; break;
2960 case (('S'-'A') * 1024) + (('E'-'A') * 32) + ('P'-'A'): m = 9; break;
2961 case (('O'-'A') * 1024) + (('C'-'A') * 32) + ('T'-'A'): m = 10; break;
2962 case (('N'-'A') * 1024) + (('O'-'A') * 32) + ('V'-'A'): m = 11; break;
2963 case (('D'-'A') * 1024) + (('E'-'A') * 32) + ('C'-'A'): m = 12; break;
2964 default: return NIL; /* unknown month */
2966 if (s[4] == *s) s += 5; /* advance to year */
2967 else { /* first three were OK, possibly full name */
2968 mi = *s; /* note delimiter, skip alphas */
2969 for (s += 4; isalpha (*s); s++);
2970 /* error if delimiter not here */
2971 if (mi != *s++) return NIL;
2973 while (*s == ' ') s++; /* parse year */
2974 if (isdigit (*s)) { /* must be a digit here */
2975 y = strtoul (s,(char **) &s,10);
2976 if (*s == '\0' || *s == ' ') break;
2978 case '\0': /* ISO 8601 compact date */
2979 if (m < (BASEYEAR * 10000)) return NIL;
2980 y = m / 10000; /* get year */
2981 d = (m %= 10000) % 100; /* get day */
2982 m /= 100; /* and month */
2983 break;
2984 default:
2985 return NIL; /* unknown date format */
2988 /* minimal validity check of date */
2989 if ((d > 31) || (m > 12)) return NIL;
2990 if (y < 49) y += 2000; /* RFC 2282 rules for two digit years 00-49 */
2991 else if (y < 999) y += 1900; /* 2-digit years 50-99 and 3-digit years */
2992 /* reject prehistoric and far future years */
2993 if ((y < BASEYEAR) || (y > maxyear)) return NIL;
2994 /* set values in elt */
2995 elt->day = d; elt->month = m; elt->year = y - BASEYEAR;
2996 ms = '\0'; /* initially no time zone string */
2997 if (*s) { /* time specification present? */
2998 /* parse time */
2999 d = strtoul (s+1,(char **) &s,10);
3000 if (*s != ':') return NIL;
3001 m = strtoul (++s,(char **) &s,10);
3002 y = (*s == ':') ? strtoul (++s,(char **) &s,10) : 0;
3003 /* validity check time */
3004 if ((d > 23) || (m > 59) || (y > 60)) return NIL;
3005 /* set values in elt */
3006 elt->hours = d; elt->minutes = m; elt->seconds = y;
3007 switch (*s) { /* time zone specifier? */
3008 case ' ': /* numeric time zone */
3009 while (s[1] == ' ') s++; /* slurp extra whitespace */
3010 if (!isalpha (s[1])) { /* treat as '-' case if alphabetic */
3011 /* test for sign character */
3012 if ((elt->zoccident = (*++s == '-')) || (*s == '+')) s++;
3013 /* validate proper timezone */
3014 if (isdigit(*s) && isdigit(s[1]) && isdigit(s[2]) && (s[2] < '6') &&
3015 isdigit(s[3])) {
3016 elt->zhours = (*s - '0') * 10 + (s[1] - '0');
3017 elt->zminutes = (s[2] - '0') * 10 + (s[3] - '0');
3019 return T; /* all done! */
3021 /* falls through */
3022 case '-': /* symbolic time zone */
3023 if (!(ms = *++s)) ms = 'Z';
3024 else if (*++s) { /* multi-character? */
3025 ms -= 'A'; ms *= 1024; /* yes, make compressed three-byte form */
3026 ms += ((*s++ - 'A') * 32);
3027 if (*s) ms += *s++ - 'A';
3028 if (*s) ms = '\0'; /* more than three characters */
3030 default: /* ignore anything else */
3031 break;
3035 /* This is not intended to be a comprehensive list of all possible
3036 * timezone strings. Such a list would be impractical. Rather, this
3037 * listing is intended to incorporate all military, North American, and
3038 * a few special cases such as Japan and the major European zone names,
3039 * such as what might be expected to be found in a Tenex format mailbox
3040 * and spewed from an IMAP server. The trend is to migrate to numeric
3041 * timezones which lack the flavor but also the ambiguity of the names.
3043 * RFC-822 only recognizes UT, GMT, 1-letter military timezones, and the
3044 * 4 CONUS timezones and their summer time variants. [Sorry, Canadian
3045 * Atlantic Provinces, Alaska, and Hawaii.]
3047 switch (ms) { /* determine the timezone */
3048 /* Universal */
3049 case (('U'-'A')*1024)+(('T'-'A')*32):
3050 #ifndef STRICT_RFC822_TIMEZONES
3051 case (('U'-'A')*1024)+(('T'-'A')*32)+'C'-'A':
3052 #endif
3053 /* Greenwich */
3054 case (('G'-'A')*1024)+(('M'-'A')*32)+'T'-'A':
3055 case 'Z': elt->zhours = 0; break;
3057 /* oriental (from Greenwich) timezones */
3058 #ifndef STRICT_RFC822_TIMEZONES
3059 /* Middle Europe */
3060 case (('M'-'A')*1024)+(('E'-'A')*32)+'T'-'A':
3061 #endif
3062 #ifdef BRITISH_SUMMER_TIME
3063 /* British Summer */
3064 case (('B'-'A')*1024)+(('S'-'A')*32)+'T'-'A':
3065 #endif
3066 case 'A': elt->zhours = 1; break;
3067 #ifndef STRICT_RFC822_TIMEZONES
3068 /* Eastern Europe */
3069 case (('E'-'A')*1024)+(('E'-'A')*32)+'T'-'A':
3070 #endif
3071 case 'B': elt->zhours = 2; break;
3072 case 'C': elt->zhours = 3; break;
3073 case 'D': elt->zhours = 4; break;
3074 case 'E': elt->zhours = 5; break;
3075 case 'F': elt->zhours = 6; break;
3076 case 'G': elt->zhours = 7; break;
3077 case 'H': elt->zhours = 8; break;
3078 #ifndef STRICT_RFC822_TIMEZONES
3079 /* Japan */
3080 case (('J'-'A')*1024)+(('S'-'A')*32)+'T'-'A':
3081 #endif
3082 case 'I': elt->zhours = 9; break;
3083 case 'K': elt->zhours = 10; break;
3084 case 'L': elt->zhours = 11; break;
3085 case 'M': elt->zhours = 12; break;
3087 /* occidental (from Greenwich) timezones */
3088 case 'N': elt->zoccident = 1; elt->zhours = 1; break;
3089 case 'O': elt->zoccident = 1; elt->zhours = 2; break;
3090 #ifndef STRICT_RFC822_TIMEZONES
3091 case (('A'-'A')*1024)+(('D'-'A')*32)+'T'-'A':
3092 #endif
3093 case 'P': elt->zoccident = 1; elt->zhours = 3; break;
3094 #ifdef NEWFOUNDLAND_STANDARD_TIME
3095 /* Newfoundland */
3096 case (('N'-'A')*1024)+(('S'-'A')*32)+'T'-'A':
3097 elt->zoccident = 1; elt->zhours = 3; elt->zminutes = 30; break;
3098 #endif
3099 #ifndef STRICT_RFC822_TIMEZONES
3100 /* Atlantic */
3101 case (('A'-'A')*1024)+(('S'-'A')*32)+'T'-'A':
3102 #endif
3103 /* CONUS */
3104 case (('E'-'A')*1024)+(('D'-'A')*32)+'T'-'A':
3105 case 'Q': elt->zoccident = 1; elt->zhours = 4; break;
3106 /* Eastern */
3107 case (('E'-'A')*1024)+(('S'-'A')*32)+'T'-'A':
3108 case (('C'-'A')*1024)+(('D'-'A')*32)+'T'-'A':
3109 case 'R': elt->zoccident = 1; elt->zhours = 5; break;
3110 /* Central */
3111 case (('C'-'A')*1024)+(('S'-'A')*32)+'T'-'A':
3112 case (('M'-'A')*1024)+(('D'-'A')*32)+'T'-'A':
3113 case 'S': elt->zoccident = 1; elt->zhours = 6; break;
3114 /* Mountain */
3115 case (('M'-'A')*1024)+(('S'-'A')*32)+'T'-'A':
3116 case (('P'-'A')*1024)+(('D'-'A')*32)+'T'-'A':
3117 case 'T': elt->zoccident = 1; elt->zhours = 7; break;
3118 /* Pacific */
3119 case (('P'-'A')*1024)+(('S'-'A')*32)+'T'-'A':
3120 #ifndef STRICT_RFC822_TIMEZONES
3121 case (('Y'-'A')*1024)+(('D'-'A')*32)+'T'-'A':
3122 #endif
3123 case 'U': elt->zoccident = 1; elt->zhours = 8; break;
3124 #ifndef STRICT_RFC822_TIMEZONES
3125 /* Yukon */
3126 case (('Y'-'A')*1024)+(('S'-'A')*32)+'T'-'A':
3127 #endif
3128 case 'V': elt->zoccident = 1; elt->zhours = 9; break;
3129 #ifndef STRICT_RFC822_TIMEZONES
3130 /* Hawaii */
3131 case (('H'-'A')*1024)+(('S'-'A')*32)+'T'-'A':
3132 #endif
3133 case 'W': elt->zoccident = 1; elt->zhours = 10; break;
3134 /* Nome/Bering/Samoa */
3135 #ifdef NOME_STANDARD_TIME
3136 case (('N'-'A')*1024)+(('S'-'A')*32)+'T'-'A':
3137 #endif
3138 #ifdef BERING_STANDARD_TIME
3139 case (('B'-'A')*1024)+(('S'-'A')*32)+'T'-'A':
3140 #endif
3141 #ifdef SAMOA_STANDARD_TIME
3142 case (('S'-'A')*1024)+(('S'-'A')*32)+'T'-'A':
3143 #endif
3144 case 'X': elt->zoccident = 1; elt->zhours = 11; break;
3145 case 'Y': elt->zoccident = 1; elt->zhours = 12; break;
3147 default: /* unknown time zones treated as local */
3148 tn = time (0); /* time now... */
3149 t = localtime (&tn); /* get local minutes since midnight */
3150 mi = t->tm_hour * 60 + t->tm_min;
3151 ms = t->tm_yday; /* note Julian day */
3152 if ((t = gmtime (&tn)) != NULL) { /* minus UTC minutes since midnight */
3153 mi -= t->tm_hour * 60 + t->tm_min;
3154 /* ms can be one of:
3155 * 36x local time is December 31, UTC is January 1, offset -24 hours
3156 * 1 local time is 1 day ahead of UTC, offset +24 hours
3157 * 0 local time is same day as UTC, no offset
3158 * -1 local time is 1 day behind UTC, offset -24 hours
3159 * -36x local time is January 1, UTC is December 31, offset +24 hours
3161 if (ms -= t->tm_yday) /* correct offset if different Julian day */
3162 mi += ((ms < 0) == (abs (ms) == 1)) ? -24*60 : 24*60;
3163 if (mi < 0) { /* occidental? */
3164 mi = abs (mi); /* yup, make positive number */
3165 elt->zoccident = 1; /* and note west of UTC */
3167 elt->zhours = mi / 60; /* now break into hours and minutes */
3168 elt->zminutes = mi % 60;
3170 break;
3172 return T;
3175 /* Mail n messages exist
3176 * Accepts: mail stream
3177 * number of messages
3180 void mail_exists (MAILSTREAM *stream,unsigned long nmsgs)
3182 char tmp[MAILTMPLEN];
3183 if (nmsgs > MAXMESSAGES) {
3184 sprintf (tmp,"Mailbox has more messages (%lu) exist than maximum (%lu)",
3185 nmsgs,MAXMESSAGES);
3186 mm_log (tmp,ERROR);
3187 nmsgs = MAXMESSAGES; /* cap to maximum */
3188 /* probably will crash in mail_elt() soon enough... */
3190 /* make sure cache is large enough */
3191 (*mailcache) (stream,nmsgs,CH_SIZE);
3192 stream->nmsgs = nmsgs; /* update stream status */
3193 /* notify main program of change */
3194 if (!stream->silent) MM_EXISTS (stream,nmsgs);
3198 /* Mail n messages are recent
3199 * Accepts: mail stream
3200 * number of recent messages
3203 void mail_recent (MAILSTREAM *stream,unsigned long recent)
3205 char tmp[MAILTMPLEN];
3206 if (recent <= stream->nmsgs) stream->recent = recent;
3207 else {
3208 sprintf (tmp,"Non-existent recent message(s) %lu, nmsgs=%lu",
3209 recent,stream->nmsgs);
3210 mm_log (tmp,ERROR);
3215 /* Mail message n is expunged
3216 * Accepts: mail stream
3217 * message #
3220 void mail_expunged (MAILSTREAM *stream,unsigned long msgno)
3222 char tmp[MAILTMPLEN];
3223 MESSAGECACHE *elt;
3224 if (msgno > stream->nmsgs) {
3225 sprintf (tmp,"Expunge of non-existent message %lu, nmsgs=%lu",
3226 msgno,stream->nmsgs);
3227 mm_log (tmp,ERROR);
3229 else {
3230 elt = (MESSAGECACHE *) (*mailcache) (stream,msgno,CH_ELT);
3231 /* notify main program of change */
3232 if (!stream->silent) MM_EXPUNGED (stream,msgno);
3233 if (elt) { /* if an element is there */
3234 elt->msgno = 0; /* invalidate its message number and free */
3235 (*mailcache) (stream,msgno,CH_FREE);
3236 (*mailcache) (stream,msgno,CH_FREESORTCACHE);
3238 /* expunge the slot */
3239 (*mailcache) (stream,msgno,CH_EXPUNGE);
3240 --stream->nmsgs; /* update stream status */
3241 if (stream->msgno) { /* have stream pointers? */
3242 /* make sure the short cache is nuked */
3243 if (stream->scache) mail_gc (stream,GC_ENV | GC_TEXTS);
3244 else stream->msgno = 0; /* make sure invalidated in any case */
3249 /* Mail stream status routines */
3252 /* Mail lock stream
3253 * Accepts: mail stream
3256 void mail_lock (MAILSTREAM *stream)
3258 if (stream->lock) {
3259 char tmp[MAILTMPLEN];
3260 sprintf (tmp,"Lock when already locked, mbx=%.80s",
3261 stream->mailbox ? stream->mailbox : "???");
3262 fatal (tmp);
3264 else stream->lock = T; /* lock stream */
3268 /* Mail unlock stream
3269 * Accepts: mail stream
3272 void mail_unlock (MAILSTREAM *stream)
3274 if (!stream->lock) fatal ("Unlock when not locked");
3275 else stream->lock = NIL; /* unlock stream */
3279 /* Mail turn on debugging telemetry
3280 * Accepts: mail stream
3283 void mail_debug (MAILSTREAM *stream)
3285 stream->debug = T; /* turn on debugging telemetry */
3286 if (stream->dtb) (*stream->dtb->parameters) (ENABLE_DEBUG,stream);
3290 /* Mail turn off debugging telemetry
3291 * Accepts: mail stream
3294 void mail_nodebug (MAILSTREAM *stream)
3296 stream->debug = NIL; /* turn off debugging telemetry */
3297 if (stream->dtb) (*stream->dtb->parameters) (DISABLE_DEBUG,stream);
3301 /* Mail log to debugging telemetry
3302 * Accepts: message
3303 * flag that data is "sensitive"
3306 void mail_dlog (char *string,long flag)
3308 mm_dlog ((debugsensitive || !flag) ? string : "<suppressed>");
3311 /* Mail parse UID sequence
3312 * Accepts: mail stream
3313 * sequence to parse
3314 * Returns: T if parse successful, else NIL
3317 long mail_uid_sequence (MAILSTREAM *stream,unsigned char *sequence)
3319 unsigned long i,j,k,x,y;
3320 for (i = 1; i <= stream->nmsgs; i++) mail_elt (stream,i)->sequence = NIL;
3321 while (sequence && *sequence){/* while there is something to parse */
3322 if (*sequence == '*') { /* maximum message */
3323 i = stream->nmsgs ? mail_uid (stream,stream->nmsgs) : stream->uid_last;
3324 sequence++; /* skip past * */
3326 /* parse and validate message number */
3327 /* parse and validate message number */
3328 else if (!isdigit (*sequence)) {
3329 MM_LOG ("Syntax error in sequence",ERROR);
3330 return NIL;
3332 else if (!(i = strtoul (sequence,(char **) &sequence,10))) {
3333 MM_LOG ("UID may not be zero",ERROR);
3334 return NIL;
3336 switch (*sequence) { /* see what the delimiter is */
3337 case ':': /* sequence range */
3338 if (*++sequence == '*') { /* maximum message */
3339 j = stream->nmsgs ? mail_uid (stream,stream->nmsgs) : stream->uid_last;
3340 sequence++; /* skip past * */
3342 /* parse end of range */
3343 else if (!(j = strtoul (sequence,(char **) &sequence,10))) {
3344 MM_LOG ("UID sequence range invalid",ERROR);
3345 return NIL;
3347 if (*sequence && *sequence++ != ',') {
3348 MM_LOG ("UID sequence range syntax error",ERROR);
3349 return NIL;
3351 if (i > j) { /* swap the range if backwards */
3352 x = i; i = j; j = x;
3354 x = mail_msgno (stream,i);/* get msgnos */
3355 y = mail_msgno (stream,j);/* for both UIDS (don't && it) */
3356 /* easy if both UIDs valid */
3357 if (x && y) while (x <= y) mail_elt (stream,x++)->sequence = T;
3358 /* start UID valid, end is not */
3359 else if (x) while ((x <= stream->nmsgs) && (mail_uid (stream,x) <= j))
3360 mail_elt (stream,x++)->sequence = T;
3361 /* end UID valid, start is not */
3362 else if (y) for (x = 1; x <= y; x++) {
3363 if (mail_uid (stream,x) >= i) mail_elt (stream,x)->sequence = T;
3365 /* neither is valid, ugh */
3366 else for (x = 1; x <= stream->nmsgs; x++)
3367 if (((k = mail_uid (stream,x)) >= i) && (k <= j))
3368 mail_elt (stream,x)->sequence = T;
3369 break;
3370 case ',': /* single message */
3371 ++sequence; /* skip the delimiter, fall into end case */
3372 case '\0': /* end of sequence, mark this message */
3373 if ((x = mail_msgno (stream,i)) != 0L) mail_elt (stream,x)->sequence = T;
3374 break;
3375 default: /* anything else is a syntax error! */
3376 MM_LOG ("UID sequence syntax error",ERROR);
3377 return NIL;
3380 return T; /* successfully parsed sequence */
3383 /* Mail see if line list matches that in cache
3384 * Accepts: candidate line list
3385 * cached line list
3386 * matching flags
3387 * Returns: T if match, NIL if no match
3390 long mail_match_lines (STRINGLIST *lines,STRINGLIST *msglines,long flags)
3392 unsigned long i;
3393 unsigned char *s,*t;
3394 STRINGLIST *m;
3395 if (!msglines) return T; /* full header is in cache */
3396 /* need full header but filtered in cache */
3397 if ((flags & FT_NOT) || !lines) return NIL;
3398 do { /* make sure all present & accounted for */
3399 for (m = msglines; m; m = m->next) if (lines->text.size == m->text.size) {
3400 for (s = lines->text.data,t = m->text.data,i = lines->text.size;
3401 i && !compare_uchar (*s,*t); s++,t++,i--);
3402 if (!i) break; /* this line matches */
3404 if (!m) return NIL; /* didn't find in the list */
3406 while ((lines = lines->next) != NULL);
3407 return T; /* all lines found */
3410 /* Mail filter text by header lines
3411 * Accepts: text to filter, with trailing null
3412 * length of text
3413 * list of lines
3414 * fetch flags
3415 * Returns: new text size, text overwritten
3418 unsigned long mail_filter (char *text,unsigned long len,STRINGLIST *lines,
3419 long flags)
3421 STRINGLIST *hdrs;
3422 int notfound;
3423 unsigned long i;
3424 char c,*s,*e,*t,tmp[MAILTMPLEN];
3425 char *src = text;
3426 char *dst = src;
3427 char *end = text + len;
3428 text[len] = '\012'; /* guard against running off buffer */
3429 while (src < end) { /* process header */
3430 /* slurp header line name */
3431 for (s = src,e = s + MAILTMPLEN - 1,e = (e < end ? e : end),t = tmp;
3432 (s < e) && ((c = (*s ? *s : (*s = ' '))) != ':') &&
3433 ((c > ' ') ||
3434 ((c != ' ') && (c != '\t') && (c != '\015') && (c != '\012')));
3435 *t++ = *s++);
3436 *t = '\0'; /* tie off */
3437 notfound = T; /* not found yet */
3438 if ((i = t - tmp) != 0L) /* see if found in header */
3439 for (hdrs = lines; hdrs && notfound; hdrs = hdrs->next)
3440 if ((hdrs->text.size == i) && !compare_csizedtext (tmp,&hdrs->text))
3441 notfound = NIL;
3442 /* skip header line if not wanted */
3443 if (i && ((flags & FT_NOT) ? !notfound : notfound))
3444 while (((*src++ != '\012') && (*src++ != '\012') && (*src++ != '\012') &&
3445 (*src++ != '\012') && (*src++ != '\012') && (*src++ != '\012') &&
3446 (*src++ != '\012') && (*src++ != '\012') && (*src++ != '\012') &&
3447 (*src++ != '\012')) ||
3448 ((src < end) && ((*src == ' ') || (*src == '\t'))));
3449 else if (src == dst) { /* copy to self */
3450 while (((*src++ != '\012') && (*src++ != '\012') && (*src++ != '\012') &&
3451 (*src++ != '\012') && (*src++ != '\012') && (*src++ != '\012') &&
3452 (*src++ != '\012') && (*src++ != '\012') && (*src++ != '\012') &&
3453 (*src++ != '\012')) ||
3454 ((src < end) && ((*src == ' ') || (*src == '\t'))));
3455 dst = src; /* update destination */
3457 else { /* copy line and any continuation line */
3458 while ((((*dst++ = *src++) != '\012') && ((*dst++ = *src++) != '\012') &&
3459 ((*dst++ = *src++) != '\012') && ((*dst++ = *src++) != '\012') &&
3460 ((*dst++ = *src++) != '\012') && ((*dst++ = *src++) != '\012') &&
3461 ((*dst++ = *src++) != '\012') && ((*dst++ = *src++) != '\012') &&
3462 ((*dst++ = *src++) != '\012') && ((*dst++ = *src++) != '\012'))||
3463 ((src < end) && ((*src == ' ') || (*src == '\t'))));
3464 /* in case hit the guard LF */
3465 if (src > end) dst -= (src - end);
3468 *dst = '\0'; /* tie off destination */
3469 return dst - text;
3472 /* Local mail search message
3473 * Accepts: MAIL stream
3474 * message number
3475 * optional section specification
3476 * search program
3477 * Returns: T if found, NIL otherwise
3480 long mail_search_msg (MAILSTREAM *stream,unsigned long msgno,char *section,
3481 SEARCHPGM *pgm)
3483 unsigned short d;
3484 char tmp[MAILTMPLEN];
3485 MESSAGECACHE *elt = mail_elt (stream,msgno);
3486 SEARCHHEADER *hdr;
3487 SEARCHOR *or;
3488 SEARCHPGMLIST *not;
3489 unsigned long now = (unsigned long) time (0);
3490 if (pgm->msgno || pgm->uid) { /* message set searches */
3491 SEARCHSET *set;
3492 /* message sequences */
3493 if (pgm->msgno) { /* inside this message sequence set */
3494 for (set = pgm->msgno; set; set = set->next)
3495 if (set->last ? ((set->first <= set->last) ?
3496 ((msgno >= set->first) && (msgno <= set->last)) :
3497 ((msgno >= set->last) && (msgno <= set->first))) :
3498 msgno == set->first) break;
3499 if (!set) return NIL; /* not found within sequence */
3501 if (pgm->uid) { /* inside this unique identifier set */
3502 unsigned long uid = mail_uid (stream,msgno);
3503 for (set = pgm->uid; set; set = set->next)
3504 if (set->last ? ((set->first <= set->last) ?
3505 ((uid >= set->first) && (uid <= set->last)) :
3506 ((uid >= set->last) && (uid <= set->first))) :
3507 uid == set->first) break;
3508 if (!set) return NIL; /* not found within sequence */
3512 /* Fast data searches */
3513 /* need to fetch fast data? */
3514 if ((!elt->rfc822_size && (pgm->larger || pgm->smaller)) ||
3515 (!elt->year && (pgm->before || pgm->on || pgm->since ||
3516 pgm->older || pgm->younger)) ||
3517 (!elt->valid && (pgm->answered || pgm->unanswered ||
3518 pgm->deleted || pgm->undeleted ||
3519 pgm->draft || pgm->undraft ||
3520 pgm->flagged || pgm->unflagged ||
3521 pgm->recent || pgm->old ||
3522 pgm->seen || pgm->unseen ||
3523 pgm->keyword || pgm->unkeyword))) {
3524 unsigned long i;
3525 MESSAGECACHE *ielt;
3526 for (i = elt->msgno; /* find last unloaded message in range */
3527 (i < stream->nmsgs) && (ielt = mail_elt (stream,i+1)) &&
3528 ((!ielt->rfc822_size && (pgm->larger || pgm->smaller)) ||
3529 (!ielt->year && (pgm->before || pgm->on || pgm->since ||
3530 pgm->older || pgm->younger)) ||
3531 (!ielt->valid && (pgm->answered || pgm->unanswered ||
3532 pgm->deleted || pgm->undeleted ||
3533 pgm->draft || pgm->undraft ||
3534 pgm->flagged || pgm->unflagged ||
3535 pgm->recent || pgm->old ||
3536 pgm->seen || pgm->unseen ||
3537 pgm->keyword || pgm->unkeyword))); ++i);
3538 if (i == elt->msgno) sprintf (tmp,"%lu",elt->msgno);
3539 else sprintf (tmp,"%lu:%lu",elt->msgno,i);
3540 mail_fetch_fast (stream,tmp,NIL);
3542 /* size ranges */
3543 if ((pgm->larger && (elt->rfc822_size <= pgm->larger)) ||
3544 (pgm->smaller && (elt->rfc822_size >= pgm->smaller))) return NIL;
3545 /* message flags */
3546 if ((pgm->answered && !elt->answered) ||
3547 (pgm->unanswered && elt->answered) ||
3548 (pgm->deleted && !elt->deleted) ||
3549 (pgm->undeleted && elt->deleted) ||
3550 (pgm->draft && !elt->draft) ||
3551 (pgm->undraft && elt->draft) ||
3552 (pgm->flagged && !elt->flagged) ||
3553 (pgm->unflagged && elt->flagged) ||
3554 (pgm->recent && !elt->recent) ||
3555 (pgm->old && elt->recent) ||
3556 (pgm->seen && !elt->seen) ||
3557 (pgm->unseen && elt->seen)) return NIL;
3558 /* keywords */
3559 if ((pgm->keyword && !mail_search_keyword (stream,elt,pgm->keyword,LONGT)) ||
3560 (pgm->unkeyword && !mail_search_keyword (stream,elt,pgm->unkeyword,NIL)))
3561 return NIL;
3562 /* internal date ranges */
3563 if (pgm->before || pgm->on || pgm->since) {
3564 d = mail_shortdate (elt->year,elt->month,elt->day);
3565 if (pgm->before && (d >= pgm->before)) return NIL;
3566 if (pgm->on && (d != pgm->on)) return NIL;
3567 if (pgm->since && (d < pgm->since)) return NIL;
3569 if (pgm->older || pgm->younger) {
3570 unsigned long msgd = mail_longdate (elt);
3571 if (pgm->older && msgd > (now - pgm->older)) return NIL;
3572 if (pgm->younger && msgd < (now - pgm->younger)) return NIL;
3575 /* envelope searches */
3576 if (pgm->sentbefore || pgm->senton || pgm->sentsince ||
3577 pgm->bcc || pgm->cc || pgm->from || pgm->to || pgm->subject ||
3578 pgm->return_path || pgm->sender || pgm->reply_to || pgm->in_reply_to ||
3579 pgm->message_id || pgm->newsgroups || pgm->followup_to ||
3580 pgm->references) {
3581 ENVELOPE *env;
3582 MESSAGECACHE delt;
3583 if (section) { /* use body part envelope */
3584 BODY *body = mail_body (stream,msgno,section);
3585 env = (body && (body->type == TYPEMESSAGE) && body->subtype &&
3586 !strcmp (body->subtype,"RFC822")) ? body->nested.msg->env : NIL;
3588 else { /* use top level envelope if no section */
3589 if (pgm->header && !stream->scache && !(stream->dtb->flags & DR_LOCAL))
3590 mail_fetch_header(stream,msgno,NIL,NIL,NIL,FT_PEEK|FT_SEARCHLOOKAHEAD);
3591 env = mail_fetchenvelope (stream,msgno);
3593 if (!env) return NIL; /* no envelope obtained */
3594 /* sent date ranges */
3595 if ((pgm->sentbefore || pgm->senton || pgm->sentsince) &&
3596 (!mail_parse_date (&delt,env->date) ||
3597 !(d = mail_shortdate (delt.year,delt.month,delt.day)) ||
3598 (pgm->sentbefore && (d >= pgm->sentbefore)) ||
3599 (pgm->senton && (d != pgm->senton)) ||
3600 (pgm->sentsince && (d < pgm->sentsince)))) return NIL;
3601 /* search headers */
3602 if ((pgm->bcc && !mail_search_addr (env->bcc,pgm->bcc)) ||
3603 (pgm->cc && !mail_search_addr (env->cc,pgm->cc)) ||
3604 (pgm->from && !mail_search_addr (env->from,pgm->from)) ||
3605 (pgm->to && !mail_search_addr (env->to,pgm->to)) ||
3606 (pgm->subject && !mail_search_header_text (env->subject,pgm->subject)))
3607 return NIL;
3608 /* These criteria are not supported by IMAP and have to be emulated */
3609 if ((pgm->return_path &&
3610 !mail_search_addr (env->return_path,pgm->return_path)) ||
3611 (pgm->sender && !mail_search_addr (env->sender,pgm->sender)) ||
3612 (pgm->reply_to && !mail_search_addr (env->reply_to,pgm->reply_to)) ||
3613 (pgm->in_reply_to &&
3614 !mail_search_header_text (env->in_reply_to,pgm->in_reply_to)) ||
3615 (pgm->message_id &&
3616 !mail_search_header_text (env->message_id,pgm->message_id)) ||
3617 (pgm->newsgroups &&
3618 !mail_search_header_text (env->newsgroups,pgm->newsgroups)) ||
3619 (pgm->followup_to &&
3620 !mail_search_header_text (env->followup_to,pgm->followup_to)) ||
3621 (pgm->references &&
3622 !mail_search_header_text (env->references,pgm->references)))
3623 return NIL;
3626 /* search header lines */
3627 for (hdr = pgm->header; hdr; hdr = hdr->next) {
3628 char *t,*e,*v;
3629 SIZEDTEXT s;
3630 STRINGLIST sth,stc;
3631 sth.next = stc.next = NIL; /* only one at a time */
3632 sth.text.data = hdr->line.data;
3633 sth.text.size = hdr->line.size;
3634 /* get the header text */
3635 if ((t = mail_fetch_header (stream,msgno,NIL,&sth,&s.size,
3636 FT_INTERNAL | FT_PEEK |
3637 (section ? NIL : FT_SEARCHLOOKAHEAD))) &&
3638 strchr (t,':')) {
3639 if (hdr->text.size) { /* anything matches empty search string */
3640 /* non-empty, copy field data */
3641 s.data = (unsigned char *) fs_get (s.size + 1);
3642 /* for each line */
3643 for (v = (char *) s.data, e = t + s.size; t < e;) switch (*t) {
3644 default: /* non-continuation, skip leading field name */
3645 while ((t < e) && (*t++ != ':'));
3646 if ((t < e) && (*t == ':')) t++;
3647 case '\t': case ' ': /* copy field data */
3648 while ((t < e) && (*t != '\015') && (*t != '\012')) *v++ = *t++;
3649 *v++ = '\n'; /* tie off line */
3650 while (((*t == '\015') || (*t == '\012')) && (t < e)) t++;
3652 /* calculate true size */
3653 s.size = v - (char *) s.data;
3654 *v = '\0'; /* tie off results */
3655 stc.text.data = hdr->text.data;
3656 stc.text.size = hdr->text.size;
3657 /* search header */
3658 if (mail_search_header (&s,&stc)) fs_give ((void **) &s.data);
3659 else { /* search failed */
3660 fs_give ((void **) &s.data);
3661 return NIL;
3665 else return NIL; /* no matching header text */
3667 /* search strings */
3668 if ((pgm->text && !mail_search_text (stream,msgno,section,pgm->text,LONGT))||
3669 (pgm->body && !mail_search_text (stream,msgno,section,pgm->body,NIL)))
3670 return NIL;
3671 /* logical conditions */
3672 for (or = pgm->or; or; or = or->next)
3673 if (!(mail_search_msg (stream,msgno,section,or->first) ||
3674 mail_search_msg (stream,msgno,section,or->second))) return NIL;
3675 for (not = pgm->not; not; not = not->next)
3676 if (mail_search_msg (stream,msgno,section,not->pgm)) return NIL;
3677 return T;
3680 /* Mail search message header null-terminated text
3681 * Accepts: header text
3682 * strings to search
3683 * Returns: T if search found a match
3686 long mail_search_header_text (char *s,STRINGLIST *st)
3688 SIZEDTEXT h;
3689 /* have any text? */
3690 if ((h.data = (unsigned char *) s) != NULL) {
3691 h.size = strlen (s); /* yes, get its size */
3692 return mail_search_header (&h,st);
3694 return NIL;
3698 /* Mail search message header
3699 * Accepts: header as sized text
3700 * strings to search
3701 * Returns: T if search found a match
3704 long mail_search_header (SIZEDTEXT *hdr,STRINGLIST *st)
3706 SIZEDTEXT h;
3707 long ret = LONGT;
3708 /* make UTF-8 version of header */
3709 utf8_mime2text (hdr,&h,U8T_CANONICAL);
3710 while (h.size && ((h.data[h.size-1]=='\015') || (h.data[h.size-1]=='\012')))
3711 --h.size; /* slice off trailing newlines */
3712 do if (h.size ? /* search non-empty string */
3713 !ssearch (h.data,h.size,st->text.data,st->text.size) : st->text.size)
3714 ret = NIL;
3715 while (ret && (st = st->next));
3716 if (h.data != hdr->data) fs_give ((void **) &h.data);
3717 return ret;
3720 /* Mail search message body
3721 * Accepts: MAIL stream
3722 * message number
3723 * optional section specification
3724 * string list
3725 * flags
3726 * Returns: T if search found a match
3729 long mail_search_text (MAILSTREAM *stream,unsigned long msgno,char *section,
3730 STRINGLIST *st,long flags)
3732 BODY *body;
3733 long ret = NIL;
3734 STRINGLIST *s = mail_newstringlist ();
3735 mailgets_t omg = mailgets;
3736 if (stream->dtb->flags & DR_LOWMEM) mailgets = mail_search_gets;
3737 /* strings to search */
3738 for (stream->private.search.string = s; st;) {
3739 s->text.data = st->text.data;
3740 s->text.size = st->text.size;
3741 if ((st = st->next) != NULL) s = s->next = mail_newstringlist ();
3743 stream->private.search.text = NIL;
3744 if (flags) { /* want header? */
3745 SIZEDTEXT s,t;
3746 s.data = (unsigned char *)
3747 mail_fetch_header (stream,msgno,section,NIL,&s.size,FT_INTERNAL|FT_PEEK);
3748 utf8_mime2text (&s,&t,U8T_CANONICAL);
3749 ret = mail_search_string_work (&t,&stream->private.search.string);
3750 if (t.data != s.data) fs_give ((void **) &t.data);
3752 if (!ret) { /* still looking for match? */
3753 /* no section, get top-level body */
3754 if (!section) mail_fetchstructure (stream,msgno,&body);
3755 /* get body of nested message */
3756 else if ((body = mail_body (stream,msgno,section)) &&
3757 (body->type == TYPEMULTIPART) && body->subtype &&
3758 !strcmp (body->subtype,"RFC822")) body = body->nested.msg->body;
3759 if (body) ret = mail_search_body (stream,msgno,body,NIL,1,flags);
3761 mailgets = omg; /* restore former gets routine */
3762 /* clear searching */
3763 for (s = stream->private.search.string; s; s = s->next) s->text.data = NIL;
3764 mail_free_stringlist (&stream->private.search.string);
3765 stream->private.search.text = NIL;
3766 return ret;
3769 /* Mail search message body text parts
3770 * Accepts: MAIL stream
3771 * message number
3772 * current body pointer
3773 * hierarchical level prefix
3774 * position at current hierarchical level
3775 * string list
3776 * flags
3777 * Returns: T if search found a match
3780 long mail_search_body (MAILSTREAM *stream,unsigned long msgno,BODY *body,
3781 char *prefix,unsigned long section,long flags)
3783 long ret = NIL;
3784 unsigned long i;
3785 char *s,*t,sect[MAILTMPLEN];
3786 SIZEDTEXT st,h;
3787 PART *part;
3788 PARAMETER *param;
3789 if (prefix && (strlen (prefix) > (MAILTMPLEN - 20))) return NIL;
3790 sprintf (sect,"%s%lu",prefix ? prefix : "",section++);
3791 if (flags && prefix) { /* want to search MIME header too? */
3792 st.data = (unsigned char *) mail_fetch_mime (stream,msgno,sect,&st.size,
3793 FT_INTERNAL | FT_PEEK);
3794 if (stream->dtb->flags & DR_LOWMEM) ret = stream->private.search.result;
3795 else {
3796 /* make UTF-8 version of header */
3797 utf8_mime2text (&st,&h,U8T_CANONICAL);
3798 ret = mail_search_string_work (&h,&stream->private.search.string);
3799 if (h.data != st.data) fs_give ((void **) &h.data);
3802 if (!ret) switch (body->type) {
3803 case TYPEMULTIPART:
3804 /* extend prefix if not first time */
3805 s = prefix ? strcat (sect,".") : "";
3806 for (i = 1,part = body->nested.part; part && !ret; i++,part = part->next)
3807 ret = mail_search_body (stream,msgno,&part->body,s,i,flags);
3808 break;
3809 case TYPEMESSAGE:
3810 if (!strcmp (body->subtype,"RFC822")) {
3811 if (flags) { /* want to search nested message header? */
3812 st.data = (unsigned char *)
3813 mail_fetch_header (stream,msgno,sect,NIL,&st.size,
3814 FT_INTERNAL | FT_PEEK);
3815 if (stream->dtb->flags & DR_LOWMEM) ret =stream->private.search.result;
3816 else {
3817 /* make UTF-8 version of header */
3818 utf8_mime2text (&st,&h,U8T_CANONICAL);
3819 ret = mail_search_string_work (&h,&stream->private.search.string);
3820 if (h.data != st.data) fs_give ((void **) &h.data);
3823 if ((body = body->nested.msg->body) != NULL)
3824 ret = (body->type == TYPEMULTIPART) ?
3825 mail_search_body (stream,msgno,body,(prefix ? prefix : ""),
3826 section - 1,flags) :
3827 mail_search_body (stream,msgno,body,strcat (sect,"."),1,flags);
3828 break;
3830 /* non-MESSAGE/RFC822 falls into text case */
3832 case TYPETEXT:
3833 s = mail_fetch_body (stream,msgno,sect,&i,FT_INTERNAL | FT_PEEK);
3834 if (stream->dtb->flags & DR_LOWMEM) ret = stream->private.search.result;
3835 else {
3836 for (t = NIL,param = body->parameter; param && !t; param = param->next)
3837 if (!strcmp (param->attribute,"CHARSET")) t = param->value;
3838 switch (body->encoding) { /* what encoding? */
3839 case ENCBASE64:
3840 if ((st.data = (unsigned char *)
3841 rfc822_base64 ((unsigned char *) s,i,&st.size)) != NULL) {
3842 ret = mail_search_string (&st,t,&stream->private.search.string);
3843 fs_give ((void **) &st.data);
3845 break;
3846 case ENCQUOTEDPRINTABLE:
3847 if ((st.data = rfc822_qprint ((unsigned char *) s,i,&st.size)) != NULL) {
3848 ret = mail_search_string (&st,t,&stream->private.search.string);
3849 fs_give ((void **) &st.data);
3851 break;
3852 default:
3853 st.data = (unsigned char *) s;
3854 st.size = i;
3855 ret = mail_search_string (&st,t,&stream->private.search.string);
3856 break;
3859 break;
3861 return ret;
3864 /* Mail search text
3865 * Accepts: sized text to search
3866 * character set of sized text
3867 * string list of search keys
3868 * Returns: T if search found a match
3871 long mail_search_string (SIZEDTEXT *s,char *charset,STRINGLIST **st)
3873 SIZEDTEXT u;
3874 long ret;
3875 STRINGLIST **sc = st;
3876 /* convert to UTF-8 as best we can */
3877 if (!utf8_text (s,charset,&u,U8T_CANONICAL))
3878 utf8_text (s,NIL,&u,U8T_CANONICAL);
3879 ret = mail_search_string_work (&u,st);
3880 if (u.data != s->data) fs_give ((void **) &u.data);
3881 return ret;
3885 /* Mail search text worker routine
3886 * Accepts: sized text to search
3887 * string list of search keys
3888 * Returns: T if search found a match
3891 long mail_search_string_work (SIZEDTEXT *s,STRINGLIST **st)
3893 void *t;
3894 STRINGLIST **sc = st;
3895 while (*sc) { /* run down criteria list */
3896 if (ssearch (s->data,s->size,(*sc)->text.data,(*sc)->text.size)) {
3897 t = (void *) (*sc); /* found one, need to flush this */
3898 *sc = (*sc)->next; /* remove it from the list */
3899 fs_give (&t); /* flush the buffer */
3901 else sc = &(*sc)->next; /* move to next in list */
3903 return *st ? NIL : LONGT;
3907 /* Mail search keyword
3908 * Accepts: MAIL stream
3909 * elt to get flags from
3910 * keyword list
3911 * T for keyword search, NIL for unkeyword search
3912 * Returns: T if search found a match
3915 long mail_search_keyword (MAILSTREAM *stream,MESSAGECACHE *elt,STRINGLIST *st,
3916 long flag)
3918 int i,j;
3919 unsigned long f = 0;
3920 unsigned long tf;
3921 do {
3922 for (i = 0; (j = (i < NUSERFLAGS) && stream->user_flags[i]); ++i)
3923 if (!compare_csizedtext (stream->user_flags[i],&st->text)) {
3924 f |= (1 << i);
3925 break;
3927 if (flag && !j) return NIL;
3928 } while ((st = st->next) != NULL);
3929 tf = elt->user_flags & f; /* get set flags which match */
3930 return flag ? (f == tf) : !tf;
3933 /* Mail search an address list
3934 * Accepts: address list
3935 * string list
3936 * Returns: T if search found a match
3939 #define SEARCHBUFLEN (size_t) 2000
3940 #define SEARCHBUFSLOP (size_t) 5
3942 long mail_search_addr (ADDRESS *adr,STRINGLIST *st)
3944 ADDRESS *a,tadr;
3945 SIZEDTEXT txt;
3946 char tmp[SENDBUFLEN + 1];
3947 size_t i = SEARCHBUFLEN;
3948 size_t k;
3949 long ret = NIL;
3950 if (adr) {
3951 txt.data = (unsigned char *) fs_get (i + SEARCHBUFSLOP);
3952 /* never an error or next */
3953 tadr.error = NIL,tadr.next = NIL;
3954 /* write address list */
3955 for (txt.size = 0,a = adr; a; a = a->next) {
3956 k = (tadr.mailbox = a->mailbox) ? 4 + 2*strlen (a->mailbox) : 3;
3957 if ((tadr.personal = a->personal) != NULL) k += 3 + 2*strlen (a->personal);
3958 if ((tadr.adl = a->adl) != NULL) k += 3 + 2*strlen (a->adl);
3959 if ((tadr.host = a->host) != NULL) k += 3 + 2*strlen (a->host);
3960 if (tadr.personal || tadr.adl) k += 2;
3961 if (k < (SENDBUFLEN-10)) {/* ignore ridiculous addresses */
3962 tmp[0] = '\0';
3963 rfc822_write_address (tmp,&tadr);
3964 /* resize buffer if necessary */
3965 if (((k = strlen (tmp)) + txt.size) > i)
3966 fs_resize ((void **) &txt.data,SEARCHBUFSLOP + (i += SEARCHBUFLEN));
3967 /* add new address */
3968 memcpy (txt.data + txt.size,tmp,k);
3969 txt.size += k;
3970 /* another address follows */
3971 if (a->next) txt.data[txt.size++] = ',';
3974 txt.data[txt.size] = '\0'; /* tie off string */
3975 ret = mail_search_header (&txt,st);
3976 fs_give ((void **) &txt.data);
3978 return ret;
3981 /* Get string for low-memory searching
3982 * Accepts: readin function pointer
3983 * stream to use
3984 * number of bytes
3985 * gets data packet
3987 * mail stream
3988 * message number
3989 * descriptor string
3990 * option flags
3991 * Returns: NIL, always
3994 #define SEARCHSLOP 128
3996 char *mail_search_gets (readfn_t f,void *stream,unsigned long size,
3997 GETS_DATA *md)
3999 unsigned long i;
4000 char tmp[MAILTMPLEN+SEARCHSLOP+1];
4001 SIZEDTEXT st;
4002 /* better not be called unless searching */
4003 if (!md->stream->private.search.string) {
4004 sprintf (tmp,"Search botch, mbx = %.80s, %s = %lu[%.80s]",
4005 md->stream->mailbox,
4006 (md->flags & FT_UID) ? "UID" : "msg",md->msgno,md->what);
4007 fatal (tmp);
4009 /* initially no match for search */
4010 md->stream->private.search.result = NIL;
4011 /* make sure buffer clear */
4012 memset (st.data = (unsigned char *) tmp,'\0',
4013 (size_t) MAILTMPLEN+SEARCHSLOP+1);
4014 /* read first buffer */
4015 (*f) (stream,st.size = i = min (size,(long) MAILTMPLEN),tmp);
4016 /* search for text */
4017 if (mail_search_string (&st,NIL,&md->stream->private.search.string))
4018 md->stream->private.search.result = T;
4019 else if (size -= i) { /* more to do, blat slop down */
4020 memmove (tmp,tmp+MAILTMPLEN-SEARCHSLOP,(size_t) SEARCHSLOP);
4021 do { /* read subsequent buffers one at a time */
4022 (*f) (stream,i = min (size,(long) MAILTMPLEN),tmp+SEARCHSLOP);
4023 st.size = i + SEARCHSLOP;
4024 if (mail_search_string (&st,NIL,&md->stream->private.search.string))
4025 md->stream->private.search.result = T;
4026 else memmove (tmp,tmp+MAILTMPLEN,(size_t) SEARCHSLOP);
4028 while ((size -= i) && !md->stream->private.search.result);
4030 if (size) { /* toss out everything after that */
4031 do (*f) (stream,i = min (size,(long) MAILTMPLEN),tmp);
4032 while (size -= i);
4034 return NIL;
4037 /* Mail parse search criteria
4038 * Accepts: criteria
4039 * Returns: search program if parse successful, else NIL
4042 SEARCHPGM *mail_criteria (char *criteria)
4044 SEARCHPGM *pgm = NIL;
4045 char *criterion,*r,tmp[MAILTMPLEN];
4046 int f;
4047 if (criteria) { /* only if criteria defined */
4048 /* make writeable copy of criteria */
4049 criteria = cpystr (criteria);
4050 /* for each criterion */
4051 for (pgm = mail_newsearchpgm (), criterion = strtok_r (criteria," ",&r);
4052 criterion; (criterion = strtok_r (NIL," ",&r))) {
4053 f = NIL; /* init then scan the criterion */
4054 switch (*ucase (criterion)) {
4055 case 'A': /* possible ALL, ANSWERED */
4056 if (!strcmp (criterion+1,"LL")) f = T;
4057 else if (!strcmp (criterion+1,"NSWERED")) f = pgm->answered = T;
4058 break;
4059 case 'B': /* possible BCC, BEFORE, BODY */
4060 if (!strcmp (criterion+1,"CC"))
4061 f = mail_criteria_string (&pgm->bcc,&r);
4062 else if (!strcmp (criterion+1,"EFORE"))
4063 f = mail_criteria_date (&pgm->before,&r);
4064 else if (!strcmp (criterion+1,"ODY"))
4065 f = mail_criteria_string (&pgm->body,&r);
4066 break;
4067 case 'C': /* possible CC */
4068 if (!strcmp (criterion+1,"C")) f = mail_criteria_string (&pgm->cc,&r);
4069 break;
4070 case 'D': /* possible DELETED */
4071 if (!strcmp (criterion+1,"ELETED")) f = pgm->deleted = T;
4072 break;
4073 case 'F': /* possible FLAGGED, FROM */
4074 if (!strcmp (criterion+1,"LAGGED")) f = pgm->flagged = T;
4075 else if (!strcmp (criterion+1,"ROM"))
4076 f = mail_criteria_string (&pgm->from,&r);
4077 break;
4078 case 'K': /* possible KEYWORD */
4079 if (!strcmp (criterion+1,"EYWORD"))
4080 f = mail_criteria_string (&pgm->keyword,&r);
4081 break;
4083 case 'N': /* possible NEW */
4084 if (!strcmp (criterion+1,"EW")) f = pgm->recent = pgm->unseen = T;
4085 break;
4086 case 'O': /* possible OLD, ON */
4087 if (!strcmp (criterion+1,"LD")) f = pgm->old = T;
4088 else if (!strcmp (criterion+1,"N"))
4089 f = mail_criteria_date (&pgm->on,&r);
4090 break;
4091 case 'R': /* possible RECENT */
4092 if (!strcmp (criterion+1,"ECENT")) f = pgm->recent = T;
4093 break;
4094 case 'S': /* possible SEEN, SINCE, SUBJECT */
4095 if (!strcmp (criterion+1,"EEN")) f = pgm->seen = T;
4096 else if (!strcmp (criterion+1,"INCE"))
4097 f = mail_criteria_date (&pgm->since,&r);
4098 else if (!strcmp (criterion+1,"UBJECT"))
4099 f = mail_criteria_string (&pgm->subject,&r);
4100 break;
4101 case 'T': /* possible TEXT, TO */
4102 if (!strcmp (criterion+1,"EXT"))
4103 f = mail_criteria_string (&pgm->text,&r);
4104 else if (!strcmp (criterion+1,"O"))
4105 f = mail_criteria_string (&pgm->to,&r);
4106 break;
4107 case 'U': /* possible UN* */
4108 if (criterion[1] == 'N') {
4109 if (!strcmp (criterion+2,"ANSWERED")) f = pgm->unanswered = T;
4110 else if (!strcmp (criterion+2,"DELETED")) f = pgm->undeleted = T;
4111 else if (!strcmp (criterion+2,"FLAGGED")) f = pgm->unflagged = T;
4112 else if (!strcmp (criterion+2,"KEYWORD"))
4113 f = mail_criteria_string (&pgm->unkeyword,&r);
4114 else if (!strcmp (criterion+2,"SEEN")) f = pgm->unseen = T;
4116 break;
4117 default: /* we will barf below */
4118 break;
4120 if (!f) { /* if can't identify criterion */
4121 sprintf (tmp,"Unknown search criterion: %.30s",criterion);
4122 MM_LOG (tmp,ERROR);
4123 mail_free_searchpgm (&pgm);
4124 break;
4127 /* no longer need copy of criteria */
4128 fs_give ((void **) &criteria);
4130 return pgm;
4133 /* Parse a date
4134 * Accepts: pointer to date integer to return
4135 * pointer to strtok state
4136 * Returns: T if successful, else NIL
4139 int mail_criteria_date (unsigned short *date,char **r)
4141 STRINGLIST *s = NIL;
4142 MESSAGECACHE elt;
4143 /* parse the date and return fn if OK */
4144 int ret = (mail_criteria_string (&s,r) &&
4145 mail_parse_date (&elt,(char *) s->text.data) &&
4146 (*date = mail_shortdate (elt.year,elt.month,elt.day))) ?
4147 T : NIL;
4148 if (s) mail_free_stringlist (&s);
4149 return ret;
4152 /* Calculate shortdate from elt values
4153 * Accepts: year (0 = BASEYEAR)
4154 * month (1 = January)
4155 * day
4156 * Returns: shortdate
4159 unsigned short mail_shortdate (unsigned int year,unsigned int month,
4160 unsigned int day)
4162 return (year << 9) + (month << 5) + day;
4165 /* Parse a string
4166 * Accepts: pointer to stringlist
4167 * pointer to strtok state
4168 * Returns: T if successful, else NIL
4171 int mail_criteria_string (STRINGLIST **s,char **r)
4173 unsigned long n;
4174 char e,*d,*end = " ",*c = strtok_r (NIL,"",r);
4175 if (!c) return NIL; /* missing argument */
4176 switch (*c) { /* see what the argument is */
4177 case '{': /* literal string */
4178 n = strtoul (c+1,&d,10); /* get its length */
4179 if ((*d++ == '}') && (*d++ == '\015') && (*d++ == '\012') &&
4180 (!(*(c = d + n)) || (*c == ' '))) {
4181 e = *--c; /* store old delimiter */
4182 *c = '\377'; /* make sure not a space */
4183 strtok_r (c," ",r); /* reset the strtok mechanism */
4184 *c = e; /* put character back */
4185 break;
4187 case '\0': /* catch bogons */
4188 case ' ':
4189 return NIL;
4190 case '"': /* quoted string */
4191 if (strchr (c+1,'"')) end = "\"";
4192 else return NIL; /* falls through */
4193 default: /* atomic string */
4194 if ((d = strtok_r (c,end,r)) != NULL) n = strlen (d);
4195 else return NIL;
4196 break;
4198 while (*s) s = &(*s)->next; /* find tail of list */
4199 *s = mail_newstringlist (); /* make new entry */
4200 /* return the data */
4201 (*s)->text.data = (unsigned char *) cpystr (d);
4202 (*s)->text.size = n;
4203 return T;
4206 /* Mail parse set from string
4207 * Accepts: string to parse
4208 * pointer to updated string pointer for return
4209 * Returns: set with pointer updated, or NIL if error
4212 SEARCHSET *mail_parse_set (char *s,char **ret)
4214 SEARCHSET *cur;
4215 SEARCHSET *set = NIL;
4216 while (isdigit (*s)) {
4217 if (!set) cur = set = mail_newsearchset ();
4218 else cur = cur->next = mail_newsearchset ();
4219 /* parse value */
4220 if (!(cur->first = strtoul (s,&s,10)) ||
4221 ((*s == ':') && !(isdigit (*++s) && (cur->last = strtoul (s,&s,10)))))
4222 break; /* bad value or range */
4223 if (*s == ',') ++s; /* point to next value if more */
4224 else { /* end of set */
4225 *ret = s; /* set return pointer */
4226 return set; /* return set */
4229 mail_free_searchset (&set); /* failure, punt partial set */
4230 return NIL;
4234 /* Mail append to set
4235 * Accepts: head of search set or NIL to do nothing
4236 * message to add
4237 * Returns: tail of search set or NIL if did nothing
4240 SEARCHSET *mail_append_set (SEARCHSET *set,unsigned long msgno)
4242 if (set) { /* find tail */
4243 while (set->next) set = set->next;
4244 /* start of set if no first member */
4245 if (!set->first) set->first = msgno;
4246 else if (msgno == (set->last ? set->last : set->first) + 1)
4247 set->last = msgno; /* extend range if 1 past current */
4248 else (set = set->next = mail_newsearchset ())->first = msgno;
4250 return set;
4253 /* Mail sort messages
4254 * Accepts: mail stream
4255 * character set
4256 * search program
4257 * sort program
4258 * option flags
4259 * Returns: vector of sorted message sequences or NIL if error
4262 unsigned long *mail_sort (MAILSTREAM *stream,char *charset,SEARCHPGM *spg,
4263 SORTPGM *pgm,long flags)
4265 unsigned long *ret = NIL;
4266 if (stream->dtb) /* do the driver's action */
4267 ret = (*(stream->dtb->sort ? stream->dtb->sort : mail_sort_msgs))
4268 (stream,charset,spg,pgm,flags);
4269 /* flush search/sort programs if requested */
4270 if (spg && (flags & SE_FREE)) mail_free_searchpgm (&spg);
4271 if (flags & SO_FREE) mail_free_sortpgm (&pgm);
4272 return ret;
4275 /* Mail sort messages work routine
4276 * Accepts: mail stream
4277 * character set
4278 * search program
4279 * sort program
4280 * option flags
4281 * Returns: vector of sorted message sequences or NIL if error
4284 unsigned long *mail_sort_msgs (MAILSTREAM *stream,char *charset,SEARCHPGM *spg,
4285 SORTPGM *pgm,long flags)
4287 unsigned long i;
4288 SORTCACHE **sc;
4289 unsigned long *ret = NIL;
4290 if (spg) { /* only if a search needs to be done */
4291 int silent = stream->silent;
4292 stream->silent = T; /* don't pass up mm_searched() events */
4293 /* search for messages */
4294 mail_search_full (stream,charset,spg,NIL);
4295 stream->silent = silent; /* restore silence state */
4297 /* initialize progress counters */
4298 pgm->nmsgs = pgm->progress.cached = 0;
4299 /* pass 1: count messages to sort */
4300 for (i = 1; i <= stream->nmsgs; ++i)
4301 if (mail_elt (stream,i)->searched) pgm->nmsgs++;
4302 if (pgm->nmsgs) { /* pass 2: sort cache */
4303 sc = mail_sort_loadcache (stream,pgm);
4304 /* pass 3: sort messages */
4305 if (!pgm->abort) ret = mail_sort_cache (stream,pgm,sc,flags);
4306 fs_give ((void **) &sc); /* don't need sort vector any more */
4308 /* empty sort results */
4309 else ret = (unsigned long *) memset (fs_get (sizeof (unsigned long)),0,
4310 sizeof (unsigned long));
4311 /* also return via callback if requested */
4312 if (mailsortresults) (*mailsortresults) (stream,ret,pgm->nmsgs);
4313 return ret; /* return sort results */
4316 /* Mail sort sortcache vector
4317 * Accepts: mail stream
4318 * sort program
4319 * sortcache vector
4320 * option flags
4321 * Returns: vector of sorted message sequences or NIL if error
4324 unsigned long *mail_sort_cache (MAILSTREAM *stream,SORTPGM *pgm,SORTCACHE **sc,
4325 long flags)
4327 unsigned long i,*ret;
4328 /* pass 3: sort messages */
4329 qsort ((void *) sc,pgm->nmsgs,sizeof (SORTCACHE *),mail_sort_compare);
4330 /* optional post sorting */
4331 if (pgm->postsort) (*pgm->postsort) ((void *) sc);
4332 /* pass 4: return results */
4333 ret = (unsigned long *) fs_get ((pgm->nmsgs+1) * sizeof (unsigned long));
4334 if (flags & SE_UID) /* UID or msgno? */
4335 for (i = 0; i < pgm->nmsgs; i++) ret[i] = mail_uid (stream,sc[i]->num);
4336 else for (i = 0; i < pgm->nmsgs; i++) ret[i] = sc[i]->num;
4337 ret[pgm->nmsgs] = 0; /* tie off message list */
4338 return ret;
4341 /* Mail load sortcache
4342 * Accepts: mail stream, already searched
4343 * sort program
4344 * Returns: vector of sortcache pointers matching search
4347 static STRINGLIST maildateline = {{(unsigned char *) "date",4},NIL};
4348 static STRINGLIST mailrnfromline = {{(unsigned char *) ">from",5},NIL};
4349 static STRINGLIST mailfromline = {{(unsigned char *) "from",4},
4350 &mailrnfromline};
4351 static STRINGLIST mailtonline = {{(unsigned char *) "to",2},NIL};
4352 static STRINGLIST mailccline = {{(unsigned char *) "cc",2},NIL};
4353 static STRINGLIST mailsubline = {{(unsigned char *) "subject",7},NIL};
4355 SORTCACHE **mail_sort_loadcache (MAILSTREAM *stream,SORTPGM *pgm)
4357 char *t,*v,*x,tmp[MAILTMPLEN];
4358 SORTPGM *pg;
4359 SORTCACHE *s,**sc;
4360 MESSAGECACHE *elt,telt;
4361 ENVELOPE *env;
4362 ADDRESS *adr = NIL;
4363 unsigned long i = (pgm->nmsgs) * sizeof (SORTCACHE *);
4364 sc = (SORTCACHE **) memset (fs_get ((size_t) i),0,(size_t) i);
4365 /* see what needs to be loaded */
4366 for (i = 1; !pgm->abort && (i <= stream->nmsgs); i++)
4367 if ((elt = mail_elt (stream,i))->searched) {
4368 sc[pgm->progress.cached++] =
4369 s = (SORTCACHE *) (*mailcache) (stream,i,CH_SORTCACHE);
4370 s->pgm = pgm; /* note sort program */
4371 s->num = i;
4372 /* get envelope if cached */
4373 if (stream->scache) env = (i == stream->msgno) ? stream->env : NIL;
4374 else env = elt->private.msg.env;
4375 for (pg = pgm; pg; pg = pg->next) switch (pg->function) {
4376 case SORTARRIVAL: /* sort by arrival date */
4377 if (!s->arrival) {
4378 /* internal date unknown but can get? */
4379 if (!elt->day && !(stream->dtb->flags & DR_NOINTDATE)) {
4380 sprintf (tmp,"%lu",i);
4381 mail_fetch_fast (stream,tmp,NIL);
4383 /* wrong thing before 3-Jan-1970 */
4384 s->arrival = elt->day ? mail_longdate (elt) : 1;
4385 s->dirty = T;
4387 break;
4388 case SORTSIZE: /* sort by message size */
4389 if (!s->size) {
4390 if (!elt->rfc822_size) {
4391 sprintf (tmp,"%lu",i);
4392 mail_fetch_fast (stream,tmp,NIL);
4394 s->size = elt->rfc822_size ? elt->rfc822_size : 1;
4395 s->dirty = T;
4397 break;
4399 case SORTDATE: /* sort by date */
4400 if (!s->date) {
4401 if (env) t = env->date;
4402 else if ((t = mail_fetch_header (stream,i,NIL,&maildateline,NIL,
4403 FT_INTERNAL | FT_PEEK)) &&
4404 (t = strchr (t,':')))
4405 for (x = ++t; (x = strpbrk (x,"\012\015")) != NULL; x++)
4406 switch (*(v = ((*x == '\015') && (x[1] == '\012')) ? x+2 : x+1)){
4407 case ' ': /* erase continuation newlines */
4408 case '\t':
4409 memmove (x,v,strlen (v));
4410 break;
4411 default: /* tie off extraneous text */
4412 *x = x[1] = '\0';
4414 /* skip leading whitespace */
4415 if (t) while ((*t == ' ') || (*t == '\t')) t++;
4416 /* parse date from Date: header */
4417 if (!(t && mail_parse_date (&telt,t) &&
4418 (s->date = mail_longdate (&telt)))) {
4419 /* failed, use internal date */
4420 if (!(s->date = s->arrival)) {
4421 /* internal date unknown but can get? */
4422 if (!elt->day && !(stream->dtb->flags & DR_NOINTDATE)) {
4423 sprintf (tmp,"%lu",i);
4424 mail_fetch_fast (stream,tmp,NIL);
4426 /* wrong thing before 3-Jan-1970 */
4427 s->date = (s->arrival = elt->day ? mail_longdate (elt) : 1);
4430 s->dirty = T;
4432 break;
4434 case SORTFROM: /* sort by first from */
4435 if (!s->from) {
4436 if (env) s->from = env->from && env->from->mailbox ?
4437 cpystr (env->from->mailbox) : NIL;
4438 else if ((t = mail_fetch_header (stream,i,NIL,&mailfromline,NIL,
4439 FT_INTERNAL | FT_PEEK)) &&
4440 (t = strchr (t,':'))) {
4441 for (x = ++t; (x = strpbrk (x,"\012\015")) != NULL; x++)
4442 switch (*(v = ((*x == '\015') && (x[1] == '\012')) ? x+2 : x+1)){
4443 case ' ': /* erase continuation newlines */
4444 case '\t':
4445 memmove (x,v,strlen (v));
4446 break;
4447 case 'f': /* continuation but with extra "From:" */
4448 case 'F':
4449 if ((v = strchr (v,':')) != NULL) {
4450 memmove (x,v+1,strlen (v+1));
4451 break;
4453 default: /* tie off extraneous text */
4454 *x = x[1] = '\0';
4456 rfc822_parse_adrlist (&adr,t,BADHOST);
4457 if (adr) {
4458 s->from = adr->mailbox;
4459 adr->mailbox = NIL;
4460 mail_free_address (&adr);
4463 if (!s->from) s->from = cpystr ("");
4464 s->dirty = T;
4466 break;
4468 case SORTTO: /* sort by first to */
4469 if (!s->to) {
4470 if (env) s->to = env->to && env->to->mailbox ?
4471 cpystr (env->to->mailbox) : NIL;
4472 else if ((t = mail_fetch_header (stream,i,NIL,&mailtonline,NIL,
4473 FT_INTERNAL | FT_PEEK)) &&
4474 (t = strchr (t,':'))) {
4475 for (x = ++t; (x = strpbrk (x,"\012\015")) != NULL; x++)
4476 switch (*(v = ((*x == '\015') && (x[1] == '\012')) ? x+2 : x+1)){
4477 case ' ': /* erase continuation newlines */
4478 case '\t':
4479 memmove (x,v,strlen (v));
4480 break;
4481 case 't': /* continuation but with extra "To:" */
4482 case 'T':
4483 if ((v = strchr (v,':')) != NULL) {
4484 memmove (x,v+1,strlen (v+1));
4485 break;
4487 default: /* tie off extraneous text */
4488 *x = x[1] = '\0';
4490 rfc822_parse_adrlist (&adr,t,BADHOST);
4491 if (adr) {
4492 s->to = adr->mailbox;
4493 adr->mailbox = NIL;
4494 mail_free_address (&adr);
4497 if (!s->to) s->to = cpystr ("");
4498 s->dirty = T;
4500 break;
4502 case SORTCC: /* sort by first cc */
4503 if (!s->cc) {
4504 if (env) s->cc = env->cc && env->cc->mailbox ?
4505 cpystr (env->cc->mailbox) : NIL;
4506 else if ((t = mail_fetch_header (stream,i,NIL,&mailccline,NIL,
4507 FT_INTERNAL | FT_PEEK)) &&
4508 (t = strchr (t,':'))) {
4509 for (x = ++t; (x = strpbrk (x,"\012\015")) != NULL; x++)
4510 switch (*(v = ((*x == '\015') && (x[1] == '\012')) ? x+2 : x+1)){
4511 case ' ': /* erase continuation newlines */
4512 case '\t':
4513 memmove (x,v,strlen (v));
4514 break;
4515 case 'c': /* continuation but with extra "cc:" */
4516 case 'C':
4517 if ((v = strchr (v,':')) != NULL) {
4518 memmove (x,v+1,strlen (v+1));
4519 break;
4521 default: /* tie off extraneous text */
4522 *x = x[1] = '\0';
4524 rfc822_parse_adrlist (&adr,t,BADHOST);
4525 if (adr) {
4526 s->cc = adr->mailbox;
4527 adr->mailbox = NIL;
4528 mail_free_address (&adr);
4531 if (!s->cc) s->cc = cpystr ("");
4532 s->dirty = T;
4534 break;
4536 case SORTSUBJECT: /* sort by subject */
4537 if (!s->subject) {
4538 /* get subject from envelope if have one */
4539 if (env) t = env->subject ? env->subject : "";
4540 /* otherwise snarf from header text */
4541 else if ((t = mail_fetch_header (stream,i,NIL,&mailsubline,
4542 NIL,FT_INTERNAL | FT_PEEK)) &&
4543 (t = strchr (t,':')))
4544 for (x = ++t; (x = strpbrk (x,"\012\015")) != NULL; x++)
4545 switch (*(v = ((*x == '\015') && (x[1] == '\012')) ? x+2 : x+1)){
4546 case ' ': /* erase continuation newlines */
4547 case '\t':
4548 memmove (x,v,strlen (v));
4549 break;
4550 default: /* tie off extraneous text */
4551 *x = x[1] = '\0';
4553 else t = ""; /* empty subject */
4554 /* strip and cache subject */
4555 s->refwd = mail_strip_subject (t,&s->subject);
4556 s->dirty = T;
4558 break;
4559 default:
4560 fatal ("Unknown sort function");
4563 return sc;
4566 /* Strip subjects of extra spaces and leading and trailing cruft for sorting
4567 * Accepts: unstripped subject
4568 * pointer to return stripped subject, in cpystr form
4569 * Returns: T if subject had a re/fwd, NIL otherwise
4572 unsigned int mail_strip_subject (char *t,char **ret)
4574 SIZEDTEXT src,dst;
4575 unsigned long i,slen;
4576 char c,*s,*x;
4577 unsigned int refwd = NIL;
4578 if ((src.size = strlen (t)) != 0) { /* have non-empty subject? */
4579 src.data = (unsigned char *) t;
4580 /* Step 1 */
4581 /* make copy, convert MIME2 if needed */
4582 *ret = s = (utf8_mime2text (&src,&dst,U8T_CANONICAL) &&
4583 (src.data != dst.data)) ? (char *) dst.data : cpystr (t);
4584 /* convert spaces to tab, strip extra spaces */
4585 for (x = t = s, c = 'x'; *t; t++) {
4586 if (c != ' ') c = *x++ = ((*t == '\t') ? ' ' : *t);
4587 else if ((*t != '\t') && (*t != ' ')) c = *x++ = *t;
4589 *x = '\0'; /* tie off string */
4590 /* Step 2 */
4591 for (slen = dst.size; s; slen = strlen (s)) {
4592 for (t = s + slen; t > s; ) switch (t[-1]) {
4593 case ' ': case '\t': /* WSP */
4594 *--t = '\0'; /* just remove it */
4595 break;
4596 case ')': /* possible "(fwd)" */
4597 if ((t >= (s + 5)) && (t[-5] == '(') &&
4598 ((t[-4] == 'F') || (t[-4] == 'f')) &&
4599 ((t[-3] == 'W') || (t[-3] == 'w')) &&
4600 ((t[-2] == 'D') || (t[-2] == 'd'))) {
4601 *(t -= 5) = '\0'; /* remove "(fwd)" */
4602 refwd = T; /* note a re/fwd */
4603 break;
4605 default: /* not a subj-trailer */
4606 t = s;
4607 break;
4609 /* Steps 3-5 */
4610 for (t = s; t; ) switch (*s) {
4611 case ' ': case '\t': /* WSP */
4612 s = t = mail_strip_subject_wsp (s + 1);
4613 break;
4614 case 'r': case 'R': /* possible "re" */
4615 if (((s[1] == 'E') || (s[1] == 'e')) &&
4616 (t = mail_strip_subject_wsp (s + 2)) &&
4617 (t = mail_strip_subject_blob (t)) && (*t == ':')) {
4618 s = ++t; /* found "re" */
4619 refwd = T; /* definitely a re/fwd at this point */
4621 else t = NIL; /* found subj-middle */
4622 break;
4623 case 'f': case 'F': /* possible "fw" or "fwd" */
4624 if (((s[1] == 'w') || (s[1] == 'W')) &&
4625 (((s[2] == 'd') || (s[2] == 'D')) ?
4626 (t = mail_strip_subject_wsp (s + 3)) :
4627 (t = mail_strip_subject_wsp (s + 2))) &&
4628 (t = mail_strip_subject_blob (t)) && (*t == ':')) {
4629 s = ++t; /* found "fwd" */
4630 refwd = T; /* definitely a re/fwd at this point */
4632 else t = NIL; /* found subj-middle */
4633 break;
4634 case '[': /* possible subj-blob */
4635 if ((t = mail_strip_subject_blob (s)) && *t) s = t;
4636 else t = NIL; /* found subj-middle */
4637 break;
4638 default:
4639 t = NIL; /* found subj-middle */
4640 break;
4642 /* Step 6 */
4643 /* Netscape-style "[Fwd: ...]"? */
4644 if ((*s == '[') && ((s[1] == 'F') || (s[1] == 'f')) &&
4645 ((s[2] == 'W') || (s[2] == 'w')) &&
4646 ((s[3] == 'D') || (s[3] == 'd')) && (s[4] == ':') &&
4647 (s[i = strlen (s) - 1] == ']')) {
4648 s[i] = '\0'; /* flush closing "]" */
4649 s += 5; /* and leading "[Fwd:" */
4650 refwd = T; /* definitely a re/fwd at this point */
4652 else break; /* don't need to loop back to step 2 */
4654 if (s != (t = *ret)) { /* removed leading text? */
4655 s = *ret = cpystr (s); /* yes, make a fresh return copy */
4656 fs_give ((void **) &t); /* flush old copy */
4659 else *ret = cpystr (""); /* empty subject */
4660 return refwd; /* return re/fwd state */
4663 /* Strip subject wsp helper routine
4664 * Accepts: text
4665 * Returns: pointer to text after blob
4668 char *mail_strip_subject_wsp (char *s)
4670 while ((*s == ' ') || (*s == '\t')) s++;
4671 return s;
4675 /* Strip subject blob helper routine
4676 * Accepts: text
4677 * Returns: pointer to text after any blob, NIL if blob-like but not blob
4680 char *mail_strip_subject_blob (char *s)
4682 if (*s != '[') return s; /* not a blob, ignore */
4683 /* search for end of blob */
4684 while (*++s != ']') if ((*s == '[') || !*s) return NIL;
4685 return mail_strip_subject_wsp (s + 1);
4688 /* Sort compare messages
4689 * Accept: first message sort cache element
4690 * second message sort cache element
4691 * Returns: -1 if a1 < a2, 0 if a1 == a2, 1 if a1 > a2
4694 int mail_sort_compare (const void *a1,const void *a2)
4696 int i = 0;
4697 SORTCACHE *s1 = *(SORTCACHE **) a1;
4698 SORTCACHE *s2 = *(SORTCACHE **) a2;
4699 SORTPGM *pgm = s1->pgm;
4700 if (!s1->sorted) { /* this one sorted yet? */
4701 s1->sorted = T;
4702 pgm->progress.sorted++; /* another sorted message */
4704 if (!s2->sorted) { /* this one sorted yet? */
4705 s2->sorted = T;
4706 pgm->progress.sorted++; /* another sorted message */
4708 do {
4709 switch (pgm->function) { /* execute search program */
4710 case SORTDATE: /* sort by date */
4711 i = compare_ulong (s1->date,s2->date);
4712 break;
4713 case SORTARRIVAL: /* sort by arrival date */
4714 i = compare_ulong (s1->arrival,s2->arrival);
4715 break;
4716 case SORTSIZE: /* sort by message size */
4717 i = compare_ulong (s1->size,s2->size);
4718 break;
4719 case SORTFROM: /* sort by first from */
4720 i = compare_string (s1->from,s2->from);
4721 break;
4722 case SORTTO: /* sort by first to */
4723 i = compare_string (s1->to,s2->to);
4724 break;
4725 case SORTCC: /* sort by first cc */
4726 i = compare_string (s1->cc,s2->cc);
4727 break;
4728 case SORTSUBJECT: /* sort by subject */
4729 i = compare_string (s1->subject,s2->subject);
4730 break;
4732 if (pgm->reverse) i = -i; /* flip results if necessary */
4734 while ((pgm = i ? NIL : pgm->next) != NULL);
4735 /* return result, avoid 0 if at all possible */
4736 return i ? i : compare_ulong (s1->num,s2->num);
4739 /* Return message date as an unsigned long seconds since time began
4740 * Accepts: message cache pointer
4741 * Returns: unsigned long of date
4743 * This routine, like most UNIX systems, is clueless about leap seconds.
4744 * Thus, it treats 23:59:60 as equivalent to 00:00:00 the next day.
4746 * This routine forces any early hours on 1-Jan-1970 in oriental timezones
4747 * to be 1-Jan-1970 00:00:00 UTC, so as to avoid negative longdates.
4750 unsigned long mail_longdate (MESSAGECACHE *elt)
4752 unsigned long m = elt->month ? elt->month : 1;
4753 unsigned long yr = elt->year + BASEYEAR;
4754 /* number of days since time began */
4755 unsigned long ret = (elt->day ? (elt->day - 1) : 0)
4756 + 30 * (m - 1) + ((m + (m > 8)) / 2)
4757 #ifndef USEJULIANCALENDAR
4758 #ifndef USEORTHODOXCALENDAR /* Gregorian calendar */
4759 + ((yr / 400) - (BASEYEAR / 400)) - ((yr / 100) - (BASEYEAR / 100))
4760 #ifdef Y4KBUGFIX
4761 - ((yr / 4000) - (BASEYEAR / 4000))
4762 #endif
4763 - ((m < 3) ?
4764 !(yr % 4) && ((yr % 100) || (!(yr % 400)
4765 #ifdef Y4KBUGFIX
4766 && (yr % 4000)
4767 #endif
4768 )) : 2)
4769 #else /* Orthodox calendar */
4770 + ((2*(yr / 900)) - (2*(BASEYEAR / 900)))
4771 + (((yr % 900) >= 200) - ((BASEYEAR % 900) >= 200))
4772 + (((yr % 900) >= 600) - ((BASEYEAR % 900) >= 600))
4773 - ((yr / 100) - (BASEYEAR / 100))
4774 - ((m < 3) ?
4775 !(yr % 4) && ((yr % 100) || ((yr % 900) == 200) || ((yr % 900) == 600))
4776 : 2)
4777 #endif
4778 #endif
4779 + elt->year * 365 + (((unsigned long) (elt->year + (BASEYEAR % 4))) / 4);
4780 ret *= 24; ret += elt->hours; /* date value in hours */
4781 ret *= 60; ret +=elt->minutes;/* date value in minutes */
4782 yr = (elt->zhours * 60) + elt->zminutes;
4783 if (elt->zoccident) ret += yr;/* occidental timezone, make UTC */
4784 else if (ret < yr) return 0; /* still 31-Dec-1969 in UTC */
4785 else ret -= yr; /* oriental timezone, make UTC */
4786 ret *= 60; ret += elt->seconds;
4787 return ret;
4790 /* Mail thread messages
4791 * Accepts: mail stream
4792 * thread type
4793 * character set
4794 * search program
4795 * option flags
4796 * Returns: thread node tree or NIL if error
4799 THREADNODE *mail_thread (MAILSTREAM *stream,char *type,char *charset,
4800 SEARCHPGM *spg,long flags)
4802 THREADNODE *ret = NIL;
4803 if (stream->dtb) /* must have a live driver */
4804 ret = stream->dtb->thread ? /* do driver's action if available */
4805 (*stream->dtb->thread) (stream,type,charset,spg,flags) :
4806 mail_thread_msgs (stream,type,charset,spg,flags,mail_sort_msgs);
4807 /* flush search/sort programs if requested */
4808 if (spg && (flags & SE_FREE)) mail_free_searchpgm (&spg);
4809 return ret;
4813 /* Mail thread messages
4814 * Accepts: mail stream
4815 * thread type
4816 * character set
4817 * search program
4818 * option flags
4819 * sorter routine
4820 * Returns: thread node tree or NIL if error
4823 THREADNODE *mail_thread_msgs (MAILSTREAM *stream,char *type,char *charset,
4824 SEARCHPGM *spg,long flags,sorter_t sorter)
4826 THREADER *t;
4827 for (t = &mailthreadlist; t; t = t->next)
4828 if (!compare_cstring (type,t->name)) {
4829 THREADNODE *ret = (*t->dispatch) (stream,charset,spg,flags,sorter);
4830 if (mailthreadresults) (*mailthreadresults) (stream,ret);
4831 return ret;
4833 MM_LOG ("No such thread type",ERROR);
4834 return NIL;
4837 /* Mail thread ordered subject
4838 * Accepts: mail stream
4839 * character set
4840 * search program
4841 * option flags
4842 * sorter routine
4843 * Returns: thread node tree
4846 THREADNODE *mail_thread_orderedsubject (MAILSTREAM *stream,char *charset,
4847 SEARCHPGM *spg,long flags,
4848 sorter_t sorter)
4850 THREADNODE *thr = NIL;
4851 THREADNODE *cur,*top,**tc;
4852 SORTPGM pgm,pgm2;
4853 SORTCACHE *s;
4854 unsigned long i,j,*lst,*ls;
4855 /* sort by subject+date */
4856 memset (&pgm,0,sizeof (SORTPGM));
4857 memset (&pgm2,0,sizeof (SORTPGM));
4858 pgm.function = SORTSUBJECT;
4859 pgm.next = &pgm2;
4860 pgm2.function = SORTDATE;
4861 if ((lst = (*sorter) (stream,charset,spg,&pgm,flags & ~(SE_FREE | SE_UID))) != NULL){
4862 if (*(ls = lst)) { /* create thread */
4863 /* note first subject */
4864 cur = top = thr = mail_newthreadnode
4865 ((SORTCACHE *) (*mailcache) (stream,*ls++,CH_SORTCACHE));
4866 /* note its number */
4867 cur->num = (flags & SE_UID) ? mail_uid (stream,*lst) : *lst;
4868 i = 1; /* number of threads */
4869 while (*ls) { /* build tree */
4870 /* subjects match? */
4871 s = (SORTCACHE *) (*mailcache) (stream,*ls++,CH_SORTCACHE);
4872 if (compare_cstring (top->sc->subject,s->subject)) {
4873 i++; /* have a new thread */
4874 top = top->branch = cur = mail_newthreadnode (s);
4876 /* start a child of the top */
4877 else if (cur == top) cur = cur->next = mail_newthreadnode (s);
4878 /* sibling of child */
4879 else cur = cur->branch = mail_newthreadnode (s);
4880 /* set to msgno or UID as needed */
4881 cur->num = (flags & SE_UID) ? mail_uid (stream,s->num) : s->num;
4883 /* make threadnode cache */
4884 tc = (THREADNODE **) fs_get (i * sizeof (THREADNODE *));
4885 /* load threadnode cache */
4886 for (j = 0, cur = thr; cur; cur = cur->branch) tc[j++] = cur;
4887 if (i != j) fatal ("Threadnode cache confusion");
4888 qsort ((void *) tc,i,sizeof (THREADNODE *),mail_thread_compare_date);
4889 for (j = 0, --i; j < i; j++) tc[j]->branch = tc[j+1];
4890 tc[j]->branch = NIL; /* end of root */
4891 thr = tc[0]; /* head of data */
4892 fs_give ((void **) &tc);
4894 fs_give ((void **) &lst);
4896 return thr;
4899 /* Mail thread references
4900 * Accepts: mail stream
4901 * character set
4902 * search program
4903 * option flags
4904 * sorter routine
4905 * Returns: thread node tree
4908 #define REFHASHSIZE 1009 /* arbitrary prime for hash table size */
4910 /* Reference threading container, as described in Jamie Zawinski's web page
4911 * (http://www.jwz.org/doc/threading.html) for this algorithm. These are
4912 * stored as extended data in the hash table (called "id_table" in JWZ's
4913 * document) and are maintained by the hash table routines. The hash table
4914 * routines implement extended data as additional void* words at the end of
4915 * each bucket, hence these strange macros instead of a struct which would
4916 * have been more straightforward.
4919 #define THREADLINKS 3 /* number of thread links */
4921 #define CACHE(data) ((SORTCACHE *) (data)[0])
4922 #define PARENT(data) ((container_t) (data)[1])
4923 #define SETPARENT(data,value) ((container_t) (data[1] = value))
4924 #define SIBLING(data) ((container_t) (data)[2])
4925 #define SETSIBLING(data,value) ((container_t) (data[2] = value))
4926 #define CHILD(data) ((container_t) (data)[3])
4927 #define SETCHILD(data,value) ((container_t) (data[3] = value))
4929 THREADNODE *mail_thread_references (MAILSTREAM *stream,char *charset,
4930 SEARCHPGM *spg,long flags,sorter_t sorter)
4932 MESSAGECACHE *elt,telt;
4933 ENVELOPE *env;
4934 SORTCACHE *s;
4935 STRINGLIST *st;
4936 HASHENT *he;
4937 THREADNODE **tc,*cur,*lst,*nxt,*sis,*msg;
4938 container_t con,nxc,prc,sib;
4939 void **sub;
4940 char *t,tmp[MAILTMPLEN];
4941 unsigned long j,nmsgs;
4942 unsigned long i = stream->nmsgs * sizeof (SORTCACHE *);
4943 SORTCACHE **sc = (SORTCACHE **) memset (fs_get ((size_t) i),0,(size_t) i);
4944 HASHTAB *ht = hash_create (REFHASHSIZE);
4945 THREADNODE *root = NIL;
4946 if (spg) { /* only if a search needs to be done */
4947 int silent = stream->silent;
4948 stream->silent = T; /* don't pass up mm_searched() events */
4949 /* search for messages */
4950 mail_search_full (stream,charset,spg,NIL);
4951 stream->silent = silent; /* restore silence state */
4954 /* create SORTCACHE vector of requested msgs */
4955 for (i = 1, nmsgs = 0; i <= stream->nmsgs; ++i)
4956 if (mail_elt (stream,i)->searched)
4957 (sc[nmsgs++] = (SORTCACHE *)(*mailcache)(stream,i,CH_SORTCACHE))->num =i;
4958 /* separate pass so can do overview fetch lookahead */
4959 for (i = 0; i < nmsgs; ++i) { /* for each requested message */
4960 /* is anything missing in its SORTCACHE? */
4961 if (!((s = sc[i])->date && s->subject && s->message_id && s->references)) {
4962 /* driver has an overview mechanism? */
4963 if (stream->dtb && stream->dtb->overview) {
4964 /* yes, find following unloaded entries */
4965 for (j = i + 1; (j < nmsgs) && !sc[j]->references; ++j);
4966 sprintf (tmp,"%lu",mail_uid (stream,s->num));
4967 if (i != --j) /* end of range different? */
4968 sprintf (tmp + strlen (tmp),":%lu",mail_uid (stream,sc[j]->num));
4969 /* load via overview mechanism */
4970 mail_fetch_overview (stream,tmp,mail_thread_loadcache);
4972 /* still missing data? */
4973 if (!s->date || !s->subject || !s->message_id || !s->references) {
4974 /* try to load data from envelope */
4975 if ((env = mail_fetch_structure (stream,s->num,NIL,NIL)) != NULL) {
4976 if (!s->date && env->date && mail_parse_date (&telt,env->date))
4977 s->date = mail_longdate (&telt);
4978 if (!s->subject && env->subject)
4979 s->refwd =
4980 mail_strip_subject (env->subject,&s->subject);
4981 if (!s->message_id && env->message_id && *env->message_id)
4982 s->message_id = mail_thread_parse_msgid (env->message_id,NIL);
4983 if (!s->references && /* use References: or In-Reply-To: */
4984 !(s->references =
4985 mail_thread_parse_references (env->references,T)))
4986 s->references = mail_thread_parse_references(env->in_reply_to,NIL);
4988 /* last resort */
4989 if (!s->date && !(s->date = s->arrival)) {
4990 /* internal date unknown but can get? */
4991 if (!(elt = mail_elt (stream,s->num))->day &&
4992 !(stream->dtb->flags & DR_NOINTDATE)) {
4993 sprintf (tmp,"%lu",s->num);
4994 mail_fetch_fast (stream,tmp,NIL);
4996 /* wrong thing before 3-Jan-1970 */
4997 s->date = (s->arrival = elt->day ? mail_longdate (elt) : 1);
4999 if (!s->subject) s->subject = cpystr ("");
5000 if (!s->references) s->references = mail_newstringlist ();
5001 s->dirty = T;
5005 /* Step 1 (preliminary) */
5006 /* generate unique string */
5007 sprintf (tmp,"%s.%lx.%lx@%s",stream->mailbox,stream->uid_validity,
5008 mail_uid (stream,s->num),mylocalhost ());
5009 /* flush old unique string if not message-id */
5010 if (s->unique && (s->unique != s->message_id))
5011 fs_give ((void **) &s->unique);
5012 s->unique = s->message_id ? /* don't permit Message ID duplicates */
5013 (hash_lookup (ht,s->message_id) ? cpystr (tmp) : s->message_id) :
5014 (s->message_id = cpystr (tmp));
5015 /* add unique string to hash table */
5016 hash_add (ht,s->unique,s,THREADLINKS);
5018 /* Step 1 */
5019 for (i = 0; i < nmsgs; ++i) { /* for each message in sortcache */
5020 /* Step 1A */
5021 if ((st = (s = sc[i])->references) && st->text.data)
5022 for (con = hash_lookup_and_add (ht,(char *) st->text.data,NIL,
5023 THREADLINKS); (st = st->next) != NULL; con = nxc) {
5024 nxc = hash_lookup_and_add (ht,(char *) st->text.data,NIL,THREADLINKS);
5025 /* only if no parent & won't introduce loop */
5026 if (!PARENT (nxc) && !mail_thread_check_child (con,nxc)) {
5027 SETPARENT (nxc,con); /* establish parent/child link */
5028 /* other children become sibling of this one */
5029 SETSIBLING (nxc,CHILD (con));
5030 SETCHILD (con,nxc); /* set as child of parent */
5033 else con = NIL; /* else message has no ancestors */
5034 /* Step 1B */
5035 if ((prc = PARENT ((nxc = hash_lookup (ht,s->unique)))) &&
5036 (prc != con)) { /* break links if have a different parent */
5037 SETPARENT (nxc,NIL); /* easy if direct child */
5038 if (nxc == CHILD (prc)) SETCHILD (prc,SIBLING (nxc));
5039 else { /* otherwise hunt through sisters */
5040 for (sib = CHILD (prc); nxc != SIBLING (sib); sib = SIBLING (sib));
5041 SETSIBLING (sib,SIBLING (nxc));
5043 SETSIBLING (nxc,NIL); /* no more little sisters either */
5044 prc = NIL; /* no more parent set */
5046 /* need to set parent, and parent is good? */
5047 if (!prc && !mail_thread_check_child (con,nxc)) {
5048 SETPARENT (nxc,con); /* establish parent/child link */
5049 if (con) { /* if non-root parent, set parent's child */
5050 if (CHILD (con)) { /* have a child already */
5051 /* find youngest daughter */
5052 for (con = CHILD (con); SIBLING (con); con = SIBLING (con));
5053 SETSIBLING (con,nxc); /* add new baby sister */
5055 else SETCHILD (con,nxc);/* set as only child */
5059 fs_give ((void **) &sc); /* finished with sortcache vector */
5061 /* Step 2 */
5062 /* search hash table for parentless messages */
5063 for (i = 0, prc = con = NIL; i < ht->size; i++)
5064 for (he = ht->table[i]; he; he = he->next)
5065 if (!PARENT ((nxc = he->data))) {
5066 /* sibling of previous parentless message */
5067 if (con) con = SETSIBLING (con,nxc);
5068 else prc = con = nxc; /* first parentless message */
5070 /* Once the dummy containers are pruned, we no longer need the parent
5071 * information, so we can convert the containers to THREADNODEs. Since
5072 * we don't need the id_table any more either, we can reset the hash table
5073 * and reuse it as a subject_table. Resetting the hash table will also
5074 * destroy the containers.
5076 /* Step 3 */
5077 /* prune dummies, convert to threadnode */
5078 root = mail_thread_c2node (stream,mail_thread_prune_dummy (prc,NIL),flags);
5079 /* Step 4 */
5080 /* make buffer for sorting */
5081 tc = (THREADNODE **) fs_get (nmsgs * sizeof (THREADNODE *));
5082 /* load threadcache and count nodes to sort */
5083 for (i = 0, cur = root; cur ; cur = cur->branch) tc[i++] = cur;
5084 if (i > 1) { /* only if need to sort */
5085 qsort ((void *) tc,i,sizeof (THREADNODE *),mail_thread_compare_date);
5086 /* relink siblings */
5087 for (j = 0, --i; j < i; j++) tc[j]->branch = tc[j+1];
5088 tc[j]->branch = NIL; /* end of root */
5089 root = tc[0]; /* establish new root */
5091 /* Step 5A */
5092 hash_reset (ht); /* discard containers, reset ht */
5093 /* Step 5B */
5094 for (cur = root; cur; cur = cur->branch)
5095 if ((t = (nxt = (cur->sc ? cur : cur->next))->sc->subject) && *t) {
5096 /* add new subject to hash table */
5097 if (!(sub = hash_lookup (ht,t))) hash_add (ht,t,cur,0);
5098 /* if one in table not dummy and */
5099 else if ((s = (lst = (THREADNODE *) sub[0])->sc) &&
5100 /* current dummy, or not re/fwd and table is */
5101 (!cur->sc || (!nxt->sc->refwd && s->refwd)))
5102 sub[0] = (void *) cur; /* replace with this message */
5105 /* Step 5C */
5106 for (cur = root, sis = NIL; cur; cur = msg) {
5107 /* do nothing if current message or no sub */
5108 if (!(t = (cur->sc ? cur : cur->next)->sc->subject) || !*t ||
5109 ((lst = (THREADNODE *) (sub = hash_lookup (ht,t))[0]) == cur))
5110 msg = (sis = cur)->branch;
5111 else if (!lst->sc) { /* is message in the table a dummy? */
5112 /* find youngest daughter of msg in table */
5113 for (msg = lst->next; msg->branch; msg = msg->branch);
5114 if (!cur->sc) { /* current message a dummy? */
5115 msg->branch = cur->next;/* current's daughter now dummy's youngest */
5116 msg = cur->branch; /* continue scan at younger sister */
5117 /* now delete this node */
5118 cur->branch = cur->next = NIL;
5119 mail_free_threadnode (&cur);
5121 else { /* current message not a dummy */
5122 msg->branch = cur; /* append as youngest daughter */
5123 msg = cur->branch; /* continue scan at younger sister */
5124 cur->branch = NIL; /* lose our younger sisters */
5127 else { /* no dummies, is current re/fwd, table not? */
5128 if (cur->sc->refwd && !lst->sc->refwd) {
5129 if (lst->next) { /* find youngest daughter of msg in table */
5130 for (msg = lst->next; msg->branch; msg = msg->branch);
5131 msg->branch = cur; /* append as youngest daughter */
5133 else lst->next = cur; /* no children, so make the eldest daughter */
5136 else { /* no re/fwd, create a new dummy */
5137 msg = mail_newthreadnode (NIL);
5138 if (lst == root) { /* msg in table is root? */
5139 root = lst->branch; /* younger sister becomes new root */
5140 /* no longer older sister either */
5141 if (lst == sis) sis = NIL;
5143 else { /* find older sister of msg in table */
5144 for (nxt = root; lst != nxt->branch; nxt = nxt->branch);
5145 /* remove from older sister */
5146 nxt->branch = lst->branch;
5148 msg->next = lst; /* msg in table becomes child */
5149 lst->branch = cur; /* current now little sister of msg in table */
5150 if (sis) { /* have an elder sister? */
5151 if (sis == lst) /* rescan if lost her */
5152 for (sis = root; cur != sis->branch; sis = sis->branch);
5153 sis->branch = msg; /* make dummy younger sister of big sister */
5155 else root = msg; /* otherwise this is the new root */
5156 sub[0] = sis = msg; /* set new msg in table and new big sister */
5158 msg = cur->branch; /* continue scan at younger sister */
5159 cur->branch = NIL; /* lose our younger sisters */
5161 if (sis) sis->branch = msg; /* older sister gets this as younger sister */
5162 else root = msg; /* otherwise this is the new root */
5164 hash_destroy (&ht); /* finished with hash table */
5165 /* Step 6 */
5166 /* sort threads */
5167 root = mail_thread_sort (root,tc);
5168 fs_give ((void **) &tc); /* finished with sort buffer */
5169 return root; /* return sorted list */
5172 /* Fetch overview callback to load sortcache for threading
5173 * Accepts: MAIL stream
5174 * UID of this message
5175 * overview of this message
5176 * msgno of this message
5179 void mail_thread_loadcache (MAILSTREAM *stream,unsigned long uid,OVERVIEW *ov,
5180 unsigned long msgno)
5182 if (msgno && ov) { /* just in case */
5183 MESSAGECACHE telt, *elt;
5184 ENVELOPE *env;
5185 SORTCACHE *s = (SORTCACHE *) (*mailcache) (stream,msgno,CH_SORTCACHE);
5186 if (!s->subject && ov->subject) {
5187 s->refwd = mail_strip_subject (ov->subject,&s->subject);
5188 s->dirty = T;
5190 if (!s->from && ov->from && ov->from->mailbox) {
5191 s->from = cpystr (ov->from->mailbox);
5192 s->dirty = T;
5194 if (!s->date && ov->date && mail_parse_date (&telt,ov->date)) {
5195 s->date = mail_longdate (&telt);
5196 s->dirty = T;
5198 if (!s->message_id && ov->message_id) {
5199 s->message_id = mail_thread_parse_msgid (ov->message_id,NIL);
5200 s->dirty = T;
5202 if (!s->references &&
5203 !(s->references = mail_thread_parse_references (ov->references,T))
5204 && stream->dtb && !strcmp(stream->dtb->name, "imap")
5205 && (elt = mail_elt (stream, msgno)) != NULL
5206 && (env = elt->private.msg.env) != NULL
5207 && env->in_reply_to
5208 && !(s->references = mail_thread_parse_references(env->in_reply_to, NIL))) {
5209 /* don't do In-Reply-To with NNTP mailboxes */
5210 s->references = mail_newstringlist ();
5211 s->dirty = T;
5213 if (!s->size && ov->optional.octets) {
5214 s->size = ov->optional.octets;
5215 s->dirty = T;
5220 /* Thread parse Message ID
5221 * Accepts: pointer to purported Message ID
5222 * pointer to return pointer
5223 * Returns: Message ID or NIL, return pointer updated
5226 char *mail_thread_parse_msgid (char *s,char **ss)
5228 char *ret = NIL;
5229 char *t = NIL;
5230 ADDRESS *adr;
5231 if (s) { /* only for non-NIL strings */
5232 rfc822_skipws (&s); /* skip whitespace */
5233 /* ignore phrases */
5234 if (((*s == '<') || (s = rfc822_parse_phrase (s))) &&
5235 (adr = rfc822_parse_routeaddr (s,&t,BADHOST))) {
5236 /* make return msgid */
5237 if (adr->mailbox && adr->host)
5238 sprintf (ret = (char *) fs_get (strlen (adr->mailbox) +
5239 strlen (adr->host) + 2),"%s@%s",
5240 adr->mailbox,adr->host);
5241 mail_free_address (&adr); /* don't need temporary address */
5244 if (ss) *ss = t; /* update return pointer */
5245 return ret;
5249 /* Thread parse references
5250 * Accepts: pointer to purported references
5251 * parse multiple references flag
5252 * Returns: references or NIL
5255 STRINGLIST *mail_thread_parse_references (char *s,long flag)
5257 char *t;
5258 STRINGLIST *ret = NIL;
5259 STRINGLIST *cur;
5260 /* found first reference? */
5261 if ((t = mail_thread_parse_msgid (s,&s)) != NULL) {
5262 (ret = mail_newstringlist ())->text.data = (unsigned char *) t;
5263 ret->text.size = strlen (t);
5264 if (flag) /* parse subsequent references */
5265 for (cur = ret; (t = mail_thread_parse_msgid (s,&s)) != NULL; cur = cur->next) {
5266 (cur->next = mail_newstringlist ())->text.data = (unsigned char *) t;
5267 cur->next->text.size = strlen (t);
5270 return ret;
5273 /* Prune dummy messages
5274 * Accepts: candidate container to prune
5275 * older sibling of container, if any
5276 * Returns: container in this position, possibly pruned
5277 * All children and younger siblings are also pruned
5280 container_t mail_thread_prune_dummy (container_t msg,container_t ane)
5282 /* prune container and children */
5283 container_t ret = msg ? mail_thread_prune_dummy_work (msg,ane) : NIL;
5284 /* prune all younger sisters */
5285 if (ret) for (ane = ret; ane && (msg = SIBLING (ane)); ane = msg)
5286 msg = mail_thread_prune_dummy_work (msg,ane);
5287 return ret;
5291 /* Prune dummy messages worker routine
5292 * Accepts: candidate container to prune
5293 * older sibling of container, if any
5294 * Returns: container in this position, possibly pruned
5295 * All children are also pruned
5298 container_t mail_thread_prune_dummy_work (container_t msg,container_t ane)
5300 container_t cur;
5301 /* get children, if any */
5302 container_t nxt = mail_thread_prune_dummy (CHILD (msg),NIL);
5303 /* just update children if container has msg */
5304 if (CACHE (msg)) SETCHILD (msg,nxt);
5305 else if (!nxt) { /* delete dummy with no children */
5306 nxt = SIBLING (msg); /* get younger sister */
5307 if (ane) SETSIBLING (ane,nxt);
5308 /* prune younger sister if exists */
5309 msg = nxt ? mail_thread_prune_dummy_work (nxt,ane) : NIL;
5311 /* not if parent root & multiple children */
5312 else if ((cur = PARENT (msg)) || !SIBLING (nxt)) {
5313 /* OK to promote, try younger sister of aunt */
5314 if (ane) SETSIBLING (ane,nxt);
5315 /* otherwise promote to child of grandmother */
5316 else if (cur) SETCHILD (cur,nxt);
5317 SETPARENT (nxt,cur); /* set parent as well */
5318 /* look for end of siblings in new container */
5319 for (cur = nxt; SIBLING (cur); cur = SIBLING (cur));
5320 /* reattach deleted container's siblings */
5321 SETSIBLING (cur,SIBLING (msg));
5322 /* prune and return new container */
5323 msg = mail_thread_prune_dummy_work (nxt,ane);
5325 else SETCHILD (msg,nxt); /* in case child pruned */
5326 return msg; /* return this message */
5329 /* Test that purported mother is not a child of purported daughter
5330 * Accepts: mother
5331 * purported daugher
5332 * Returns: T if circular parentage exists, else NIL
5335 long mail_thread_check_child (container_t mother,container_t daughter)
5337 if (mother) { /* only if mother non-NIL */
5338 if (mother == daughter) return T;
5339 for (daughter = CHILD (daughter); daughter; daughter = SIBLING (daughter))
5340 if (mail_thread_check_child (mother,daughter)) return T;
5342 return NIL;
5346 /* Generate threadnodes from containers
5347 * Accepts: Mail stream
5348 * container
5349 * flags
5350 * Return: threadnode list
5353 THREADNODE *mail_thread_c2node (MAILSTREAM *stream,container_t con,long flags)
5355 THREADNODE *ret,*cur;
5356 SORTCACHE *s;
5357 container_t nxt;
5358 /* for each container */
5359 for (ret = cur = NIL; con; con = SIBLING (con)) {
5360 s = CACHE (con); /* yes, get its sortcache */
5361 /* create node for it */
5362 if (ret) cur = cur->branch = mail_newthreadnode (s);
5363 else ret = cur = mail_newthreadnode (s);
5364 /* attach sequence or UID for non-dummy */
5365 if (s) cur->num = (flags & SE_UID) ? mail_uid (stream,s->num) : s->num;
5366 /* attach the children */
5367 if ((nxt = CHILD (con)) != NULL) cur->next = mail_thread_c2node (stream,nxt,flags);
5369 return ret;
5372 /* Sort thread tree by date
5373 * Accepts: thread tree to sort
5374 * qsort vector to sort
5375 * Returns: sorted thread tree
5378 THREADNODE *mail_thread_sort (THREADNODE *thr,THREADNODE **tc)
5380 unsigned long i,j;
5381 THREADNODE *cur;
5382 /* sort children of each thread */
5383 for (cur = thr; cur; cur = cur->branch)
5384 if (cur->next) cur->next = mail_thread_sort (cur->next,tc);
5385 /* Must do this in a separate pass since recursive call will clobber tc */
5386 /* load threadcache and count nodes to sort */
5387 for (i = 0, cur = thr; cur; cur = cur->branch) tc[i++] = cur;
5388 if (i > 1) { /* only if need to sort */
5389 qsort ((void *) tc,i,sizeof (THREADNODE *),mail_thread_compare_date);
5390 /* relink root siblings */
5391 for (j = 0, --i; j < i; j++) tc[j]->branch = tc[j+1];
5392 tc[j]->branch = NIL; /* end of root */
5394 return i ? tc[0] : NIL; /* return new head of list */
5398 /* Thread compare date
5399 * Accept: first message sort cache element
5400 * second message sort cache element
5401 * Returns: -1 if a1 < a2, 1 if a1 > a2
5403 * This assumes that a sort cache element is either a message (with a
5404 * sortcache entry) or a dummy with a message (with sortcache entry) child.
5405 * This is true of both the ORDEREDSUBJECT (no dummies) and REFERENCES
5406 * (dummies only at top-level, and with non-dummy children).
5408 * If a new algorithm allows a dummy parent to have a dummy child, this
5409 * routine must be changed if it is to be used by that algorithm.
5411 * Messages with bogus dates are always sorted at the top.
5414 int mail_thread_compare_date (const void *a1,const void *a2)
5416 THREADNODE *t1 = *(THREADNODE **) a1;
5417 THREADNODE *t2 = *(THREADNODE **) a2;
5418 SORTCACHE *s1 = t1->sc ? t1->sc : t1->next->sc;
5419 SORTCACHE *s2 = t2->sc ? t2->sc : t2->next->sc;
5420 int ret = compare_ulong (s1->date,s2->date);
5421 /* use number as final tie-breaker */
5422 return ret ? ret : compare_ulong (s1->num,s2->num);
5425 /* Mail parse sequence
5426 * Accepts: mail stream
5427 * sequence to parse
5428 * Returns: T if parse successful, else NIL
5431 long mail_sequence (MAILSTREAM *stream,unsigned char *sequence)
5433 unsigned long i,j,x;
5434 for (i = 1; i <= stream->nmsgs; i++) mail_elt (stream,i)->sequence = NIL;
5435 while (sequence && *sequence){/* while there is something to parse */
5436 if (*sequence == '*') { /* maximum message */
5437 if (stream->nmsgs) i = stream->nmsgs;
5438 else {
5439 MM_LOG ("No messages, so no maximum message number",ERROR);
5440 return NIL;
5442 sequence++; /* skip past * */
5444 /* parse and validate message number */
5445 else if (!isdigit (*sequence)) {
5446 MM_LOG ("Syntax error in sequence",ERROR);
5447 return NIL;
5449 else if (!(i = strtoul (sequence,(char **) &sequence,10)) ||
5450 (i > stream->nmsgs)) {
5451 MM_LOG ("Sequence out of range",ERROR);
5452 return NIL;
5454 switch (*sequence) { /* see what the delimiter is */
5455 case ':': /* sequence range */
5456 if (*++sequence == '*') { /* maximum message */
5457 if (stream->nmsgs) j = stream->nmsgs;
5458 else {
5459 MM_LOG ("No messages, so no maximum message number",ERROR);
5460 return NIL;
5462 sequence++; /* skip past * */
5464 /* parse end of range */
5465 else if (!(j = strtoul (sequence,(char **) &sequence,10)) ||
5466 (j > stream->nmsgs)) {
5467 MM_LOG ("Sequence range invalid",ERROR);
5468 return NIL;
5470 if (*sequence && *sequence++ != ',') {
5471 MM_LOG ("Sequence range syntax error",ERROR);
5472 return NIL;
5474 if (i > j) { /* swap the range if backwards */
5475 x = i; i = j; j = x;
5477 /* mark each item in the sequence */
5478 while (i <= j) mail_elt (stream,j--)->sequence = T;
5479 break;
5480 case ',': /* single message */
5481 ++sequence; /* skip the delimiter, fall into end case */
5482 case '\0': /* end of sequence, mark this message */
5483 mail_elt (stream,i)->sequence = T;
5484 break;
5485 default: /* anything else is a syntax error! */
5486 MM_LOG ("Sequence syntax error",ERROR);
5487 return NIL;
5490 return T; /* successfully parsed sequence */
5493 /* Parse flag list
5494 * Accepts: MAIL stream
5495 * flag list as a character string
5496 * pointer to user flags to return
5497 * Returns: system flags
5500 long mail_parse_flags (MAILSTREAM *stream,char *flag,unsigned long *uf)
5502 char *t,*n,*s,tmp[MAILTMPLEN],msg[MAILTMPLEN];
5503 short f = 0;
5504 long i,j;
5505 *uf = 0; /* initially no user flags */
5506 if (flag && *flag) { /* no-op if no flag string */
5507 /* check if a list and make sure valid */
5508 if (((i = (*flag == '(')) ^ (flag[strlen (flag)-1] == ')')) ||
5509 (strlen (flag) >= MAILTMPLEN)) {
5510 MM_LOG ("Bad flag list",ERROR);
5511 return NIL;
5513 /* copy the flag string w/o list construct */
5514 strncpy (n = tmp,flag+i,(j = strlen (flag) - (2*i)));
5515 tmp[j] = '\0';
5516 while ((t = n) && *t) { /* parse the flags */
5517 /* find end of flag */
5518 if ((n = strchr (t,' ')) != NULL) *n++ = '\0';
5519 if (*t == '\\') { /* system flag? */
5520 if (!compare_cstring (t+1,"SEEN")) f |= fSEEN;
5521 else if (!compare_cstring (t+1,"DELETED")) f |= fDELETED;
5522 else if (!compare_cstring (t+1,"FLAGGED")) f |= fFLAGGED;
5523 else if (!compare_cstring (t+1,"ANSWERED")) f |= fANSWERED;
5524 else if (!compare_cstring (t+1,"DRAFT")) f |= fDRAFT;
5525 else {
5526 sprintf (msg,"Unsupported system flag: %.80s",t);
5527 MM_LOG (msg,WARN);
5531 else { /* keyword flag */
5532 for (i = j = 0; /* user flag, search through table */
5533 !i && (j < NUSERFLAGS) && (s = stream->user_flags[j]); ++j)
5534 if (!compare_cstring (t,s)) *uf |= i = 1 << j;
5535 if (!i) { /* flag not found, can it be created? */
5536 if (stream->kwd_create && (j < NUSERFLAGS) && *t &&
5537 (strlen (t) <= MAXUSERFLAG)) {
5538 for (s = t; t && *s; s++) switch (*s) {
5539 default: /* all other characters */
5540 /* SPACE, CTL, or not CHAR */
5541 if ((*s > ' ') && (*s < 0x7f)) break;
5542 case '*': case '%': /* list_wildcards */
5543 case '"': case '\\':/* quoted-specials */
5544 /* atom_specials */
5545 case '(': case ')': case '{':
5546 case ']': /* resp-specials */
5547 sprintf (msg,"Invalid flag: %.80s",t);
5548 MM_LOG (msg,WARN);
5549 t = NIL;
5551 if (t) { /* only if valid */
5552 *uf |= 1 << j; /* set the bit */
5553 stream->user_flags[j] = cpystr (t);
5554 /* if out of user flags */
5555 if (j == NUSERFLAGS - 1) stream->kwd_create = NIL;
5558 else {
5559 if (*t) sprintf (msg,"Unknown flag: %.80s",t);
5560 else strcpy (msg,"Empty flag invalid");
5561 MM_LOG (msg,WARN);
5567 return f;
5570 /* Mail check network stream for usability with new name
5571 * Accepts: MAIL stream
5572 * candidate new name
5573 * Returns: T if stream can be used, NIL otherwise
5576 long mail_usable_network_stream (MAILSTREAM *stream,char *name)
5578 NETMBX smb,nmb,omb;
5579 char *s = NIL;
5580 long ret= (stream && stream->dtb && !(stream->dtb->flags & DR_LOCAL) &&
5581 mail_valid_net_parse (name,&nmb) &&
5582 mail_valid_net_parse (stream->mailbox,&smb) &&
5583 mail_valid_net_parse (stream->original_mailbox,&omb) &&
5584 ((!compare_cstring (smb.host,trustdns ?
5585 (s = tcp_canonical (nmb.host)) : nmb.host) &&
5586 !strcmp (smb.service,nmb.service) &&
5587 (!nmb.port || (smb.port == nmb.port)) &&
5588 (nmb.anoflag == stream->anonymous) &&
5589 (!nmb.user[0] || !strcmp (smb.user,nmb.user))) ||
5590 (!compare_cstring (omb.host,nmb.host) &&
5591 !strcmp (omb.service,nmb.service) &&
5592 (!nmb.port || (omb.port == nmb.port)) &&
5593 (nmb.anoflag == stream->anonymous) &&
5594 (!nmb.user[0] || !strcmp (omb.user,nmb.user))))) ? LONGT : NIL;
5595 if(s) fs_give((void **) &s);
5596 return ret;
5599 /* Mail data structure instantiation routines */
5602 /* Mail instantiate cache elt
5603 * Accepts: initial message number
5604 * Returns: new cache elt
5607 MESSAGECACHE *mail_new_cache_elt (unsigned long msgno)
5609 MESSAGECACHE *elt = (MESSAGECACHE *) memset (fs_get (sizeof (MESSAGECACHE)),
5610 0,sizeof (MESSAGECACHE));
5611 elt->lockcount = 1; /* initially only cache references it */
5612 elt->msgno = msgno; /* message number */
5613 return elt;
5617 /* Mail instantiate envelope
5618 * Returns: new envelope
5621 ENVELOPE *mail_newenvelope (void)
5623 return (ENVELOPE *) memset (fs_get (sizeof (ENVELOPE)),0,sizeof (ENVELOPE));
5627 /* Mail instantiate address
5628 * Returns: new address
5631 ADDRESS *mail_newaddr (void)
5633 return (ADDRESS *) memset (fs_get (sizeof (ADDRESS)),0,sizeof (ADDRESS));
5636 /* Mail instantiate body
5637 * Returns: new body
5640 BODY *mail_newbody (void)
5642 return mail_initbody ((BODY *) fs_get (sizeof (BODY)));
5646 /* Mail initialize body
5647 * Accepts: body
5648 * Returns: body
5651 BODY *mail_initbody (BODY *body)
5653 memset ((void *) body,0,sizeof (BODY));
5654 body->type = TYPETEXT; /* content type */
5655 body->encoding = ENC7BIT; /* content encoding */
5656 return body;
5660 /* Mail instantiate body parameter
5661 * Returns: new body part
5664 PARAMETER *mail_newbody_parameter (void)
5666 return (PARAMETER *) memset (fs_get (sizeof(PARAMETER)),0,sizeof(PARAMETER));
5670 /* Mail instantiate body part
5671 * Returns: new body part
5674 PART *mail_newbody_part (void)
5676 PART *part = (PART *) memset (fs_get (sizeof (PART)),0,sizeof (PART));
5677 mail_initbody (&part->body); /* initialize the body */
5678 return part;
5682 /* Mail instantiate body message part
5683 * Returns: new body message part
5686 MESSAGE *mail_newmsg (void)
5688 return (MESSAGE *) memset (fs_get (sizeof (MESSAGE)),0,sizeof (MESSAGE));
5691 /* Mail instantiate string list
5692 * Returns: new string list
5695 STRINGLIST *mail_newstringlist (void)
5697 return (STRINGLIST *) memset (fs_get (sizeof (STRINGLIST)),0,
5698 sizeof (STRINGLIST));
5702 /* Mail instantiate new search program
5703 * Returns: new search program
5706 SEARCHPGM *mail_newsearchpgm (void)
5708 return (SEARCHPGM *) memset (fs_get (sizeof(SEARCHPGM)),0,sizeof(SEARCHPGM));
5712 /* Mail instantiate new search program
5713 * Accepts: header line name
5714 * Returns: new search program
5717 SEARCHHEADER *mail_newsearchheader (char *line,char *text)
5719 SEARCHHEADER *hdr = (SEARCHHEADER *) memset (fs_get (sizeof (SEARCHHEADER)),
5720 0,sizeof (SEARCHHEADER));
5721 hdr->line.size = strlen ((char *) (hdr->line.data =
5722 (unsigned char *) cpystr (line)));
5723 hdr->text.size = strlen ((char *) (hdr->text.data =
5724 (unsigned char *) cpystr (text)));
5725 return hdr;
5729 /* Mail instantiate new search set
5730 * Returns: new search set
5733 SEARCHSET *mail_newsearchset (void)
5735 return (SEARCHSET *) memset (fs_get (sizeof(SEARCHSET)),0,sizeof(SEARCHSET));
5739 /* Mail instantiate new search or
5740 * Returns: new search or
5743 SEARCHOR *mail_newsearchor (void)
5745 SEARCHOR *or = (SEARCHOR *) memset (fs_get (sizeof (SEARCHOR)),0,
5746 sizeof (SEARCHOR));
5747 or->first = mail_newsearchpgm ();
5748 or->second = mail_newsearchpgm ();
5749 return or;
5752 /* Mail instantiate new searchpgmlist
5753 * Returns: new searchpgmlist
5756 SEARCHPGMLIST *mail_newsearchpgmlist (void)
5758 SEARCHPGMLIST *pgl = (SEARCHPGMLIST *)
5759 memset (fs_get (sizeof (SEARCHPGMLIST)),0,sizeof (SEARCHPGMLIST));
5760 pgl->pgm = mail_newsearchpgm ();
5761 return pgl;
5765 /* Mail instantiate new sortpgm
5766 * Returns: new sortpgm
5769 SORTPGM *mail_newsortpgm (void)
5771 return (SORTPGM *) memset (fs_get (sizeof (SORTPGM)),0,sizeof (SORTPGM));
5775 /* Mail instantiate new threadnode
5776 * Accepts: sort cache for thread node
5777 * Returns: new threadnode
5780 THREADNODE *mail_newthreadnode (SORTCACHE *sc)
5782 THREADNODE *thr = (THREADNODE *) memset (fs_get (sizeof (THREADNODE)),0,
5783 sizeof (THREADNODE));
5784 if (sc) thr->sc = sc; /* initialize sortcache */
5785 return thr;
5789 /* Mail instantiate new acllist
5790 * Returns: new acllist
5793 ACLLIST *mail_newacllist (void)
5795 return (ACLLIST *) memset (fs_get (sizeof (ACLLIST)),0,sizeof (ACLLIST));
5799 /* Mail instantiate new quotalist
5800 * Returns: new quotalist
5803 QUOTALIST *mail_newquotalist (void)
5805 return (QUOTALIST *) memset (fs_get (sizeof (QUOTALIST)),0,
5806 sizeof (QUOTALIST));
5809 /* Mail garbage collection routines */
5812 /* Mail garbage collect body
5813 * Accepts: pointer to body pointer
5816 void mail_free_body (BODY **body)
5818 if (*body) { /* only free if exists */
5819 mail_free_body_data (*body);/* free its data */
5820 fs_give ((void **) body); /* return body to free storage */
5825 /* Mail garbage collect body data
5826 * Accepts: body pointer
5829 void mail_free_body_data (BODY *body)
5831 switch (body->type) { /* free contents */
5832 case TYPEMULTIPART: /* multiple part */
5833 mail_free_body_part (&body->nested.part);
5834 break;
5835 case TYPEMESSAGE: /* encapsulated message */
5836 if (body->subtype && !strcmp (body->subtype,"RFC822")) {
5837 mail_free_stringlist (&body->nested.msg->lines);
5838 mail_gc_msg (body->nested.msg,GC_ENV | GC_TEXTS);
5840 if (body->nested.msg) fs_give ((void **) &body->nested.msg);
5841 break;
5842 default:
5843 break;
5845 if (body->subtype) fs_give ((void **) &body->subtype);
5846 mail_free_body_parameter (&body->parameter);
5847 if (body->id) fs_give ((void **) &body->id);
5848 if (body->description) fs_give ((void **) &body->description);
5849 if (body->disposition.type) fs_give ((void **) &body->disposition.type);
5850 if (body->disposition.parameter)
5851 mail_free_body_parameter (&body->disposition.parameter);
5852 if (body->language) mail_free_stringlist (&body->language);
5853 if (body->location) fs_give ((void **) &body->location);
5854 if (body->mime.text.data) fs_give ((void **) &body->mime.text.data);
5855 if (body->contents.text.data) fs_give ((void **) &body->contents.text.data);
5856 if (body->md5) fs_give ((void **) &body->md5);
5857 if (mailfreebodysparep && body->sparep)
5858 (*mailfreebodysparep) (&body->sparep);
5861 /* Mail garbage collect body parameter
5862 * Accepts: pointer to body parameter pointer
5865 void mail_free_body_parameter (PARAMETER **parameter)
5867 if (*parameter) { /* only free if exists */
5868 if ((*parameter)->attribute) fs_give ((void **) &(*parameter)->attribute);
5869 if ((*parameter)->value) fs_give ((void **) &(*parameter)->value);
5870 /* run down the list as necessary */
5871 mail_free_body_parameter (&(*parameter)->next);
5872 /* return body part to free storage */
5873 fs_give ((void **) parameter);
5878 /* Mail garbage collect body part
5879 * Accepts: pointer to body part pointer
5882 void mail_free_body_part (PART **part)
5884 if (*part) { /* only free if exists */
5885 mail_free_body_data (&(*part)->body);
5886 /* run down the list as necessary */
5887 mail_free_body_part (&(*part)->next);
5888 fs_give ((void **) part); /* return body part to free storage */
5892 /* Mail garbage collect message cache
5893 * Accepts: mail stream
5895 * The message cache is set to NIL when this function finishes.
5898 void mail_free_cache (MAILSTREAM *stream)
5900 /* do driver specific stuff first */
5901 mail_gc (stream,GC_ELT | GC_ENV | GC_TEXTS);
5902 /* flush the cache */
5903 (*mailcache) (stream,(long) 0,CH_INIT);
5907 /* Mail garbage collect cache element
5908 * Accepts: pointer to cache element pointer
5911 void mail_free_elt (MESSAGECACHE **elt)
5913 /* only free if exists and no sharers */
5914 if (*elt && !--(*elt)->lockcount) {
5915 mail_gc_msg (&(*elt)->private.msg,GC_ENV | GC_TEXTS);
5916 if (mailfreeeltsparep && (*elt)->sparep)
5917 (*mailfreeeltsparep) (&(*elt)->sparep);
5918 fs_give ((void **) elt);
5920 else *elt = NIL; /* else simply drop pointer */
5923 /* Mail garbage collect envelope
5924 * Accepts: pointer to envelope pointer
5927 void mail_free_envelope (ENVELOPE **env)
5929 if (*env) { /* only free if exists */
5930 if ((*env)->remail) fs_give ((void **) &(*env)->remail);
5931 mail_free_address (&(*env)->return_path);
5932 if ((*env)->date) fs_give ((void **) &(*env)->date);
5933 mail_free_address (&(*env)->from);
5934 mail_free_address (&(*env)->sender);
5935 mail_free_address (&(*env)->reply_to);
5936 if ((*env)->subject) fs_give ((void **) &(*env)->subject);
5937 mail_free_address (&(*env)->to);
5938 mail_free_address (&(*env)->cc);
5939 mail_free_address (&(*env)->bcc);
5940 if ((*env)->in_reply_to) fs_give ((void **) &(*env)->in_reply_to);
5941 if ((*env)->message_id) fs_give ((void **) &(*env)->message_id);
5942 if ((*env)->newsgroups) fs_give ((void **) &(*env)->newsgroups);
5943 if ((*env)->followup_to) fs_give ((void **) &(*env)->followup_to);
5944 if ((*env)->references) fs_give ((void **) &(*env)->references);
5945 if (mailfreeenvelopesparep && (*env)->sparep)
5946 (*mailfreeenvelopesparep) (&(*env)->sparep);
5947 fs_give ((void **) env); /* return envelope to free storage */
5952 /* Mail garbage collect address
5953 * Accepts: pointer to address pointer
5956 void mail_free_address (ADDRESS **address)
5958 if (*address) { /* only free if exists */
5959 if ((*address)->personal) fs_give ((void **) &(*address)->personal);
5960 if ((*address)->adl) fs_give ((void **) &(*address)->adl);
5961 if ((*address)->mailbox) fs_give ((void **) &(*address)->mailbox);
5962 if ((*address)->host) fs_give ((void **) &(*address)->host);
5963 if ((*address)->error) fs_give ((void **) &(*address)->error);
5964 if ((*address)->orcpt.type) fs_give ((void **) &(*address)->orcpt.type);
5965 if ((*address)->orcpt.addr) fs_give ((void **) &(*address)->orcpt.addr);
5966 mail_free_address (&(*address)->next);
5967 fs_give ((void **) address);/* return address to free storage */
5972 /* Mail garbage collect stringlist
5973 * Accepts: pointer to stringlist pointer
5976 void mail_free_stringlist (STRINGLIST **string)
5978 if (*string) { /* only free if exists */
5979 if ((*string)->text.data) fs_give ((void **) &(*string)->text.data);
5980 mail_free_stringlist (&(*string)->next);
5981 fs_give ((void **) string); /* return string to free storage */
5985 /* Mail garbage collect searchpgm
5986 * Accepts: pointer to searchpgm pointer
5989 void mail_free_searchpgm (SEARCHPGM **pgm)
5991 if (*pgm) { /* only free if exists */
5992 mail_free_searchset (&(*pgm)->msgno);
5993 mail_free_searchset (&(*pgm)->uid);
5994 mail_free_searchor (&(*pgm)->or);
5995 mail_free_searchpgmlist (&(*pgm)->not);
5996 mail_free_searchheader (&(*pgm)->header);
5997 mail_free_stringlist (&(*pgm)->bcc);
5998 mail_free_stringlist (&(*pgm)->body);
5999 mail_free_stringlist (&(*pgm)->cc);
6000 mail_free_stringlist (&(*pgm)->from);
6001 mail_free_stringlist (&(*pgm)->keyword);
6002 mail_free_stringlist (&(*pgm)->subject);
6003 mail_free_stringlist (&(*pgm)->text);
6004 mail_free_stringlist (&(*pgm)->to);
6005 mail_free_stringlist (&(*pgm)->x_gm_ext1);
6006 fs_give ((void **) pgm); /* return program to free storage */
6011 /* Mail garbage collect searchheader
6012 * Accepts: pointer to searchheader pointer
6015 void mail_free_searchheader (SEARCHHEADER **hdr)
6017 if (*hdr) { /* only free if exists */
6018 if ((*hdr)->line.data) fs_give ((void **) &(*hdr)->line.data);
6019 if ((*hdr)->text.data) fs_give ((void **) &(*hdr)->text.data);
6020 mail_free_searchheader (&(*hdr)->next);
6021 fs_give ((void **) hdr); /* return header to free storage */
6026 /* Mail garbage collect searchset
6027 * Accepts: pointer to searchset pointer
6030 void mail_free_searchset (SEARCHSET **set)
6032 if (*set) { /* only free if exists */
6033 mail_free_searchset (&(*set)->next);
6034 fs_give ((void **) set); /* return set to free storage */
6038 /* Mail garbage collect searchor
6039 * Accepts: pointer to searchor pointer
6042 void mail_free_searchor (SEARCHOR **orl)
6044 if (*orl) { /* only free if exists */
6045 mail_free_searchpgm (&(*orl)->first);
6046 mail_free_searchpgm (&(*orl)->second);
6047 mail_free_searchor (&(*orl)->next);
6048 fs_give ((void **) orl); /* return searchor to free storage */
6053 /* Mail garbage collect search program list
6054 * Accepts: pointer to searchpgmlist pointer
6057 void mail_free_searchpgmlist (SEARCHPGMLIST **pgl)
6059 if (*pgl) { /* only free if exists */
6060 mail_free_searchpgm (&(*pgl)->pgm);
6061 mail_free_searchpgmlist (&(*pgl)->next);
6062 fs_give ((void **) pgl); /* return searchpgmlist to free storage */
6067 /* Mail garbage collect namespace
6068 * Accepts: poiner to namespace
6071 void mail_free_namespace (NAMESPACE **n)
6073 if (*n) {
6074 fs_give ((void **) &(*n)->name);
6075 mail_free_namespace (&(*n)->next);
6076 mail_free_body_parameter (&(*n)->param);
6077 fs_give ((void **) n); /* return namespace to free storage */
6081 /* Mail garbage collect sort program
6082 * Accepts: pointer to sortpgm pointer
6085 void mail_free_sortpgm (SORTPGM **pgm)
6087 if (*pgm) { /* only free if exists */
6088 mail_free_sortpgm (&(*pgm)->next);
6089 fs_give ((void **) pgm); /* return sortpgm to free storage */
6094 /* Mail garbage collect thread node
6095 * Accepts: pointer to threadnode pointer
6098 void mail_free_threadnode (THREADNODE **thr)
6100 if (*thr) { /* only free if exists */
6101 mail_free_threadnode (&(*thr)->branch);
6102 mail_free_threadnode (&(*thr)->next);
6103 fs_give ((void **) thr); /* return threadnode to free storage */
6108 /* Mail garbage collect acllist
6109 * Accepts: pointer to acllist pointer
6112 void mail_free_acllist (ACLLIST **al)
6114 if (*al) { /* only free if exists */
6115 if ((*al)->identifier) fs_give ((void **) &(*al)->identifier);
6116 if ((*al)->rights) fs_give ((void **) &(*al)->rights);
6117 mail_free_acllist (&(*al)->next);
6118 fs_give ((void **) al); /* return acllist to free storage */
6123 /* Mail garbage collect quotalist
6124 * Accepts: pointer to quotalist pointer
6127 void mail_free_quotalist (QUOTALIST **ql)
6129 if (*ql) { /* only free if exists */
6130 if ((*ql)->name) fs_give ((void **) &(*ql)->name);
6131 mail_free_quotalist (&(*ql)->next);
6132 fs_give ((void **) ql); /* return quotalist to free storage */
6136 /* Link authenicator
6137 * Accepts: authenticator to add to list
6140 void auth_link (AUTHENTICATOR *auth)
6142 if (!auth->valid || (*auth->valid) ()) {
6143 AUTHENTICATOR **a = &mailauthenticators;
6144 while (*a) a = &(*a)->next; /* find end of list of authenticators */
6145 *a = auth; /* put authenticator at the end */
6146 auth->next = NIL; /* this authenticator is the end of the list */
6151 /* Authenticate access
6152 * Accepts: mechanism name
6153 * responder function
6154 * argument count
6155 * argument vector
6156 * Returns: authenticated user name or NIL
6159 char *mail_auth (char *mechanism,authresponse_t resp,int argc,char *argv[])
6161 AUTHENTICATOR *auth;
6162 for (auth = mailauthenticators; auth; auth = auth->next)
6163 if (auth->server && !compare_cstring (auth->name,mechanism))
6164 return (!(auth->flags & AU_DISABLE) &&
6165 ((auth->flags & AU_SECURE) ||
6166 !mail_parameters (NIL,GET_DISABLEPLAINTEXT,NIL))) ?
6167 (*auth->server) (resp,argc,argv) : NIL;
6168 return NIL; /* no authenticator found */
6171 /* Lookup authenticator index
6172 * Accepts: authenticator index
6173 * Returns: authenticator, or 0 if not found
6176 AUTHENTICATOR *mail_lookup_auth (unsigned long i)
6178 AUTHENTICATOR *auth = mailauthenticators;
6179 while (auth && --i) auth = auth->next;
6180 return auth;
6184 /* Lookup authenticator name
6185 * Accepts: authenticator name
6186 * required authenticator flags
6187 * Returns: index in authenticator chain, or 0 if not found
6190 unsigned int mail_lookup_auth_name (char *mechanism,long flags)
6192 int i;
6193 AUTHENTICATOR *auth;
6194 for (i = 1, auth = mailauthenticators; auth; i++, auth = auth->next)
6195 if (auth->client && !(flags & ~auth->flags) &&
6196 !(auth->flags & AU_DISABLE) && !compare_cstring (auth->name,mechanism))
6197 return i;
6198 return 0;
6201 /* Standard TCP/IP network driver */
6203 static NETDRIVER tcpdriver = {
6204 tcp_open, /* open connection */
6205 tcp_aopen, /* open preauthenticated connection */
6206 tcp_getline, /* get a line */
6207 tcp_getbuffer, /* get a buffer */
6208 tcp_soutr, /* output pushed data */
6209 tcp_sout, /* output string */
6210 tcp_close, /* close connection */
6211 tcp_host, /* return host name */
6212 tcp_remotehost, /* return remote host name */
6213 tcp_port, /* return port number */
6214 tcp_localhost /* return local host name */
6218 /* Network open
6219 * Accepts: NETMBX specifier to open
6220 * default network driver
6221 * default port
6222 * SSL driver
6223 * SSL service name
6224 * SSL driver port
6225 * Returns: Network stream if success, else NIL
6228 NETSTREAM *net_open (NETMBX *mb,NETDRIVER *dv,unsigned long port,
6229 NETDRIVER *ssld,char *ssls,unsigned long sslp)
6231 NETSTREAM *stream = NIL;
6232 char tmp[MAILTMPLEN];
6233 unsigned long flags = mb->novalidate ? NET_NOVALIDATECERT : 0;
6234 flags |= mb->tls1 || mb->tlsflag ? NET_TRYTLS1 : 0;
6235 flags |= mb->tls1_1 ? NET_TRYTLS1_1 : 0;
6236 flags |= mb->tls1_2 ? NET_TRYTLS1_2 : 0;
6237 flags |= mb->tls1_3 ? NET_TRYTLS1_3 : 0;
6238 if (strlen (mb->host) >= NETMAXHOST) {
6239 sprintf (tmp,"Invalid host name: %.80s",mb->host);
6240 MM_LOG (tmp,ERROR);
6242 /* use designated driver if given */
6243 else if (dv) stream = net_open_work (dv,mb->host,mb->service,port,mb->port,
6244 flags);
6245 else if (mb->sslflag && ssld) /* use ssl if sslflag lit */
6246 stream = net_open_work (ssld,mb->host,ssls,sslp,mb->port,flags);
6247 /* if trysslfirst and can open ssl... */
6248 else if ((mb->trysslflag || trysslfirst) && ssld &&
6249 (stream = net_open_work (ssld,mb->host,ssls,sslp,mb->port,
6250 flags | NET_SILENT | NET_TRYSSL))) {
6251 if (net_sout (stream,"",0)) mb->sslflag = T;
6252 else {
6253 net_close (stream); /* flush fake SSL stream */
6254 stream = NIL;
6257 /* default to TCP driver */
6258 else stream = net_open_work (&tcpdriver,mb->host,mb->service,port,mb->port,
6259 flags);
6260 return stream;
6263 /* Network open worker routine
6264 * Accepts: network driver
6265 * host name
6266 * service name to look up port
6267 * port number if service name not found
6268 * port number to override service name
6269 * flags (passed on top of port)
6270 * Returns: Network stream if success, else NIL
6273 NETSTREAM *net_open_work (NETDRIVER *dv,char *host,char *service,
6274 unsigned long port,unsigned long portoverride,
6275 unsigned long flags)
6277 NETSTREAM *stream = NIL;
6278 void *tstream;
6279 if (service && (*service == '*')) {
6280 flags |= NET_NOOPENTIMEOUT; /* mark that no timeout is desired */
6281 ++service; /* no longer need the no timeout indicator */
6283 if (portoverride) { /* explicit port number? */
6284 service = NIL; /* yes, override service name */
6285 port = portoverride; /* use that instead of default port */
6287 if ((tstream = (*dv->open) (host,service,port | flags)) != NULL){
6288 stream = (NETSTREAM *) fs_get (sizeof (NETSTREAM));
6289 stream->stream = tstream;
6290 stream->dtb = dv;
6292 return stream;
6296 /* Network authenticated open
6297 * Accepts: network driver
6298 * NETMBX specifier
6299 * service specifier
6300 * return user name buffer
6301 * Returns: Network stream if success else NIL
6304 NETSTREAM *net_aopen (NETDRIVER *dv,NETMBX *mb,char *service,char *user)
6306 NETSTREAM *stream = NIL;
6307 void *tstream;
6308 if (!dv) dv = &tcpdriver; /* default to TCP driver */
6309 if ((tstream = (*dv->aopen) (mb,service,user)) != NULL) {
6310 stream = (NETSTREAM *) fs_get (sizeof (NETSTREAM));
6311 stream->stream = tstream;
6312 stream->dtb = dv;
6314 return stream;
6317 /* Network receive line
6318 * Accepts: Network stream
6319 * Returns: text line string or NIL if failure
6322 char *net_getline (NETSTREAM *stream)
6324 return (*stream->dtb->getline) (stream->stream);
6328 /* Network receive buffer
6329 * Accepts: Network stream (must be void * for use as readfn_t)
6330 * size in bytes
6331 * buffer to read into
6332 * Returns: T if success, NIL otherwise
6335 long net_getbuffer (void *st,unsigned long size,char *buffer)
6337 NETSTREAM *stream = (NETSTREAM *) st;
6338 return (*stream->dtb->getbuffer) (stream->stream,size,buffer);
6342 /* Network send null-terminated string
6343 * Accepts: Network stream
6344 * string pointer
6345 * Returns: T if success else NIL
6348 long net_soutr (NETSTREAM *stream,char *string)
6350 return (*stream->dtb->soutr) (stream->stream,string);
6354 /* Network send string
6355 * Accepts: Network stream
6356 * string pointer
6357 * byte count
6358 * Returns: T if success else NIL
6361 long net_sout (NETSTREAM *stream,char *string,unsigned long size)
6363 return (*stream->dtb->sout) (stream->stream,string,size);
6366 /* Network close
6367 * Accepts: Network stream
6370 void net_close (NETSTREAM *stream)
6372 if (stream->stream) (*stream->dtb->close) (stream->stream);
6373 fs_give ((void **) &stream);
6377 /* Network get host name
6378 * Accepts: Network stream
6379 * Returns: host name for this stream
6382 char *net_host (NETSTREAM *stream)
6384 return (*stream->dtb->host) (stream->stream);
6388 /* Network get remote host name
6389 * Accepts: Network stream
6390 * Returns: host name for this stream
6393 char *net_remotehost (NETSTREAM *stream)
6395 return (*stream->dtb->remotehost) (stream->stream);
6398 /* Network return port for this stream
6399 * Accepts: Network stream
6400 * Returns: port number for this stream
6403 unsigned long net_port (NETSTREAM *stream)
6405 return (*stream->dtb->port) (stream->stream);
6409 /* Network get local host name
6410 * Accepts: Network stream
6411 * Returns: local host name
6414 char *net_localhost (NETSTREAM *stream)
6416 return (*stream->dtb->localhost) (stream->stream);
6419 void free_c_client_module_globals(void)
6421 env_end();
6422 tcp_end();