* More changes to make Valgrind happy. Work in progress.
[alpine.git] / imap / src / c-client / mail.c
blob02519e5ab2ff712ccf00b5ebb8c180dc6c043fd1
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 /* app identity */
40 static IDLIST *idapp = NIL;
41 /* list of mail drivers */
42 static DRIVER *maildrivers = NIL;
43 /* list of authenticators */
44 static AUTHENTICATOR *mailauthenticators = NIL;
45 /* SSL driver pointer */
46 static NETDRIVER *mailssldriver = NIL;
47 /* pointer to alternate gets function */
48 static mailgets_t mailgets = NIL;
49 /* pointer to read progress function */
50 static readprogress_t mailreadprogress = NIL;
51 /* mail cache manipulation function */
52 static mailcache_t mailcache = mm_cache;
53 /* RFC-822 output generator */
54 static rfc822out_t mail822out = NIL;
55 /* RFC-822 output generator (new style) */
56 static rfc822outfull_t mail822outfull = NIL;
57 /* SMTP verbose callback */
58 static smtpverbose_t mailsmtpverbose = mm_dlog;
59 /* proxy copy routine */
60 static mailproxycopy_t mailproxycopy = NIL;
61 /* RFC-822 external line parse */
62 static parseline_t mailparseline = NIL;
63 /* RFC-822 external phrase parser */
64 static parsephrase_t mailparsephrase = NIL;
65 static kinit_t mailkinit = NIL; /* application kinit callback */
66 /* note network sent command */
67 static sendcommand_t mailsendcommand = NIL;
68 /* newsrc file name decision function */
69 static newsrcquery_t mailnewsrcquery = NIL;
70 /* ACL results callback */
71 static getacl_t mailaclresults = NIL;
72 /* list rights results callback */
73 static listrights_t maillistrightsresults = NIL;
74 /* my rights results callback */
75 static myrights_t mailmyrightsresults = NIL;
76 /* quota results callback */
77 static quota_t mailquotaresults = NIL;
78 /* quota root results callback */
79 static quotaroot_t mailquotarootresults = NIL;
80 /* sorted results callback */
81 static sortresults_t mailsortresults = NIL;
82 /* threaded results callback */
83 static threadresults_t mailthreadresults = NIL;
84 /* COPY UID results */
85 static copyuid_t mailcopyuid = NIL;
86 /* APPEND UID results */
87 static appenduid_t mailappenduid = NIL;
88 /* free elt extra stuff callback */
89 static freeeltsparep_t mailfreeeltsparep = NIL;
90 /* free envelope extra stuff callback */
91 static freeenvelopesparep_t mailfreeenvelopesparep = NIL;
92 /* free body extra stuff callback */
93 static freebodysparep_t mailfreebodysparep = NIL;
94 /* free stream extra stuff callback */
95 static freestreamsparep_t mailfreestreamsparep = NIL;
96 /* SSL start routine */
97 static sslstart_t mailsslstart = NIL;
98 /* SSL certificate query */
99 static sslcertificatequery_t mailsslcertificatequery = NIL;
100 /* SSL client certificate */
101 static sslclientcert_t mailsslclientcert = NIL;
102 /* SSL client private key */
103 static sslclientkey_t mailsslclientkey = NIL;
104 /* SSL failure notify */
105 static sslfailure_t mailsslfailure = NIL;
106 /* snarf interval */
107 static long mailsnarfinterval = 60;
108 /* snarf preservation */
109 static long mailsnarfpreserve = NIL;
110 /* newsrc name uses canonical host */
111 static long mailnewsrccanon = LONGT;
113 /* supported threaders */
114 static THREADER mailthreadordsub = {
115 "ORDEREDSUBJECT",mail_thread_orderedsubject,NIL
117 static THREADER mailthreadlist = {
118 "REFERENCES",mail_thread_references,&mailthreadordsub
121 /* server name */
122 static char *servicename = "unknown";
123 /* server externally-set authentication ID */
124 static char *externalauthid = NIL;
125 static int expungeatping = T; /* mail_ping() may call mm_expunged() */
126 static int trysslfirst = NIL; /* always try SSL first */
127 static int notimezones = NIL; /* write timezones in "From " header */
128 static int trustdns = T; /* do DNS canonicalization */
129 static int saslusesptrname = T; /* SASL uses name from DNS PTR lookup */
130 /* trustdns also must be set */
131 static int debugsensitive = NIL;/* debug telemetry includes sensitive data */
133 /* Default mail cache handler
134 * Accepts: pointer to cache handle
135 * message number
136 * caching function
137 * Returns: cache data
140 void *mm_cache (MAILSTREAM *stream,unsigned long msgno,long op)
142 size_t n;
143 void *ret = NIL;
144 unsigned long i;
145 switch ((int) op) { /* what function? */
146 case CH_INIT: /* initialize cache */
147 if (stream->cache) { /* flush old cache contents */
148 while (stream->cachesize) {
149 mm_cache (stream,stream->cachesize,CH_FREE);
150 mm_cache (stream,stream->cachesize--,CH_FREESORTCACHE);
152 fs_give ((void **) &stream->cache);
153 fs_give ((void **) &stream->sc);
154 stream->nmsgs = 0; /* can't have any messages now */
156 break;
157 case CH_SIZE: /* (re-)size the cache */
158 if (!stream->cache) { /* have a cache already? */
159 /* no, create new cache */
160 n = (stream->cachesize = msgno + CACHEINCREMENT) * sizeof (void *);
161 stream->cache = (MESSAGECACHE **) memset (fs_get (n),0,n);
162 stream->sc = (SORTCACHE **) memset (fs_get (n),0,n);
164 /* is existing cache size large neough */
165 else if (msgno > stream->cachesize) {
166 i = stream->cachesize; /* remember old size */
167 n = (stream->cachesize = msgno + CACHEINCREMENT) * sizeof (void *);
168 fs_resize ((void **) &stream->cache,n);
169 fs_resize ((void **) &stream->sc,n);
170 while (i < stream->cachesize) {
171 stream->cache[i] = NIL;
172 stream->sc[i++] = NIL;
175 break;
177 case CH_MAKEELT: /* return elt, make if necessary */
178 if (!stream->cache[msgno - 1])
179 stream->cache[msgno - 1] = mail_new_cache_elt (msgno);
180 /* falls through */
181 case CH_ELT: /* return elt */
182 ret = (void *) stream->cache[msgno - 1];
183 break;
184 case CH_SORTCACHE: /* return sortcache entry, make if needed */
185 if (!stream->sc[msgno - 1]) stream->sc[msgno - 1] =
186 (SORTCACHE *) memset (fs_get (sizeof (SORTCACHE)),0,sizeof (SORTCACHE));
187 ret = (void *) stream->sc[msgno - 1];
188 break;
189 case CH_FREE: /* free elt */
190 mail_free_elt (&stream->cache[msgno - 1]);
191 break;
192 case CH_FREESORTCACHE:
193 if (stream->sc[msgno - 1]) {
194 if (stream->sc[msgno - 1]->from)
195 fs_give ((void **) &stream->sc[msgno - 1]->from);
196 if (stream->sc[msgno - 1]->to)
197 fs_give ((void **) &stream->sc[msgno - 1]->to);
198 if (stream->sc[msgno - 1]->cc)
199 fs_give ((void **) &stream->sc[msgno - 1]->cc);
200 if (stream->sc[msgno - 1]->subject)
201 fs_give ((void **) &stream->sc[msgno - 1]->subject);
202 if (stream->sc[msgno - 1]->unique &&
203 (stream->sc[msgno - 1]->unique != stream->sc[msgno - 1]->message_id))
204 fs_give ((void **) &stream->sc[msgno - 1]->unique);
205 if (stream->sc[msgno - 1]->message_id)
206 fs_give ((void **) &stream->sc[msgno - 1]->message_id);
207 if (stream->sc[msgno - 1]->references)
208 mail_free_stringlist (&stream->sc[msgno - 1]->references);
209 fs_give ((void **) &stream->sc[msgno - 1]);
211 break;
212 case CH_EXPUNGE: /* expunge cache slot */
213 for (i = msgno - 1; msgno < stream->nmsgs; i++,msgno++) {
214 if ((stream->cache[i] = stream->cache[msgno]) != NULL)
215 stream->cache[i]->msgno = msgno;
216 stream->sc[i] = stream->sc[msgno];
218 stream->cache[i] = NIL; /* top of cache goes away */
219 stream->sc[i] = NIL;
220 break;
221 default:
222 fatal ("Bad mm_cache op");
223 break;
225 return ret;
228 /* Dummy string driver for complete in-memory strings */
230 static void mail_string_init (STRING *s,void *data,unsigned long size);
231 static char mail_string_next (STRING *s);
232 static void mail_string_setpos (STRING *s,unsigned long i);
234 STRINGDRIVER mail_string = {
235 mail_string_init, /* initialize string structure */
236 mail_string_next, /* get next byte in string structure */
237 mail_string_setpos /* set position in string structure */
241 /* Initialize mail string structure for in-memory string
242 * Accepts: string structure
243 * pointer to string
244 * size of string
247 static void mail_string_init (STRING *s,void *data,unsigned long size)
249 /* set initial string pointers */
250 s->chunk = s->curpos = (char *) (s->data = data);
251 /* and sizes */
252 s->size = s->chunksize = s->cursize = size;
253 s->data1 = s->offset = 0; /* never any offset */
257 /* Get next character from string
258 * Accepts: string structure
259 * Returns: character, string structure chunk refreshed
262 static char mail_string_next (STRING *s)
264 return *s->curpos++; /* return the last byte */
268 /* Set string pointer position
269 * Accepts: string structure
270 * new position
273 static void mail_string_setpos (STRING *s,unsigned long i)
275 s->curpos = s->chunk + i; /* set new position */
276 s->cursize = s->chunksize - i;/* and new size */
279 /* Mail routines
281 * mail_xxx routines are the interface between this module and the outside
282 * world. Only these routines should be referenced by external callers.
284 * Note that there is an important difference between a "sequence" and a
285 * "message #" (msgno). A sequence is a string representing a sequence in
286 * {"n", "n:m", or combination separated by commas} format, whereas a msgno
287 * is a single integer.
291 /* Mail version check
292 * Accepts: version
295 void mail_versioncheck (char *version)
297 /* attempt to protect again wrong .h */
298 if (strcmp (version,mailcclientversion)) {
299 char tmp[MAILTMPLEN];
300 sprintf (tmp,"c-client library version skew, app=%.100s library=%.100s",
301 version,mailcclientversion);
302 fatal (tmp);
307 /* Mail link driver
308 * Accepts: driver to add to list
311 void mail_link (DRIVER *driver)
313 DRIVER **d = &maildrivers;
314 while (*d) d = &(*d)->next; /* find end of list of drivers */
315 *d = driver; /* put driver at the end */
316 driver->next = NIL; /* this driver is the end of the list */
319 /* Mail manipulate driver parameters
320 * Accepts: mail stream
321 * function code
322 * function-dependent value
323 * Returns: function-dependent return value
326 void *mail_parameters (MAILSTREAM *stream,long function,void *value)
328 void *r,*ret = NIL;
329 DRIVER *d;
330 AUTHENTICATOR *a;
331 switch ((int) function) {
332 case SET_INBOXPATH:
333 fatal ("SET_INBOXPATH not permitted");
334 case GET_INBOXPATH:
335 if ((stream || (stream = mail_open (NIL,"INBOX",OP_PROTOTYPE))) &&
336 stream->dtb) ret = (*stream->dtb->parameters) (function,value);
337 break;
338 case SET_THREADERS:
339 fatal ("SET_THREADERS not permitted");
340 case GET_THREADERS: /* use stream dtb instead of global */
341 ret = (stream && stream->dtb) ?
342 /* KLUDGE ALERT: note stream passed as value */
343 (*stream->dtb->parameters) (function,stream) : (void *) &mailthreadlist;
344 break;
345 case SET_NAMESPACE:
346 fatal ("SET_NAMESPACE not permitted");
347 break;
348 case SET_NEWSRC: /* too late on open stream */
349 if (stream && stream->dtb && (stream != ((*stream->dtb->open) (NIL))))
350 fatal ("SET_NEWSRC not permitted");
351 else ret = env_parameters (function,value);
352 break;
353 case GET_NAMESPACE:
354 ret = (stream && stream->dtb && !(stream->dtb->flags & DR_LOCAL)) ?
355 /* KLUDGE ALERT: note stream passed as value */
356 (*stream->dtb->parameters) (function,stream) :
357 env_parameters (function,value);
358 break;
359 case GET_NEWSRC: /* use stream dtb instead of environment */
360 ret = (stream && stream->dtb) ?
361 /* KLUDGE ALERT: note stream passed as value */
362 (*stream->dtb->parameters) (function,stream) :
363 env_parameters (function,value);
364 break;
365 case ENABLE_DEBUG:
366 fatal ("ENABLE_DEBUG not permitted");
367 case DISABLE_DEBUG:
368 fatal ("DISABLE_DEBUG not permitted");
369 case SET_DIRFMTTEST:
370 fatal ("SET_DIRFMTTEST not permitted");
371 case GET_DIRFMTTEST:
372 if (!(stream && stream->dtb &&
373 (ret = (*stream->dtb->parameters) (function,NIL))))
374 fatal ("GET_DIRFMTTEST not permitted");
375 break;
377 case SET_DRIVERS:
378 fatal ("SET_DRIVERS not permitted");
379 case GET_DRIVERS: /* always return global */
380 ret = (void *) maildrivers;
381 break;
382 case SET_DRIVER:
383 fatal ("SET_DRIVER not permitted");
384 case GET_DRIVER:
385 for (d = maildrivers; d && compare_cstring (d->name,(char *) value);
386 d = d->next);
387 ret = (void *) d;
388 break;
389 case ENABLE_DRIVER:
390 for (d = maildrivers; d && compare_cstring (d->name,(char *) value);
391 d = d->next);
392 if ((ret = (void *) d) != NULL) d->flags &= ~DR_DISABLE;
393 break;
394 case DISABLE_DRIVER:
395 for (d = maildrivers; d && compare_cstring (d->name,(char *) value);
396 d = d->next);
397 if ((ret = (void *) d) != NULL) d->flags |= DR_DISABLE;
398 break;
399 case ENABLE_AUTHENTICATOR:
400 for (a = mailauthenticators;/* scan authenticators */
401 a && compare_cstring (a->name,(char *) value); a = a->next);
402 if ((ret = (void *) a) != NULL) a->flags &= ~AU_DISABLE;
403 break;
404 case DISABLE_AUTHENTICATOR:
405 for (a = mailauthenticators;/* scan authenticators */
406 a && compare_cstring (a->name,(char *) value); a = a->next);
407 if ((ret = (void *) a) != NULL) a->flags |= AU_DISABLE;
408 break;
409 case UNHIDE_AUTHENTICATOR:
410 for (a = mailauthenticators;/* scan authenticators */
411 a && compare_cstring (a->name,(char *) value); a = a->next);
412 if ((ret = (void *) a) != NULL) a->flags &= ~AU_HIDE;
413 break;
414 case HIDE_AUTHENTICATOR:
415 for (a = mailauthenticators;/* scan authenticators */
416 a && compare_cstring (a->name,(char *) value); a = a->next);
417 if ((ret = (void *) a) != NULL) a->flags |= AU_HIDE;
418 break;
419 case SET_EXTERNALAUTHID:
420 if (value) { /* setting external authentication ID */
421 externalauthid = cpystr ((char *) value);
422 mail_parameters (NIL,UNHIDE_AUTHENTICATOR,"EXTERNAL");
424 else { /* clearing external authentication ID */
425 if (externalauthid) fs_give ((void **) &externalauthid);
426 mail_parameters (NIL,HIDE_AUTHENTICATOR,"EXTERNAL");
428 case GET_EXTERNALAUTHID:
429 ret = (void *) externalauthid;
430 break;
432 case SET_GETS:
433 mailgets = (mailgets_t) value;
434 case GET_GETS:
435 ret = (void *) mailgets;
436 break;
437 case SET_READPROGRESS:
438 mailreadprogress = (readprogress_t) value;
439 case GET_READPROGRESS:
440 ret = (void *) mailreadprogress;
441 break;
442 case SET_CACHE:
443 mailcache = (mailcache_t) value;
444 case GET_CACHE:
445 ret = (void *) mailcache;
446 break;
447 case SET_RFC822OUTPUT:
448 mail822out = (rfc822out_t) value;
449 case GET_RFC822OUTPUT:
450 ret = (void *) mail822out;
451 break;
452 case SET_RFC822OUTPUTFULL:
453 mail822outfull = (rfc822outfull_t) value;
454 case GET_RFC822OUTPUTFULL:
455 ret = (void *) mail822outfull;
456 break;
457 case SET_SMTPVERBOSE:
458 mailsmtpverbose = (smtpverbose_t) value;
459 case GET_SMTPVERBOSE:
460 ret = (void *) mailsmtpverbose;
461 break;
462 case SET_MAILPROXYCOPY:
463 mailproxycopy = (mailproxycopy_t) value;
464 case GET_MAILPROXYCOPY:
465 ret = (void *) mailproxycopy;
466 break;
467 case SET_PARSELINE:
468 mailparseline = (parseline_t) value;
469 case GET_PARSELINE:
470 ret = (void *) mailparseline;
471 break;
472 case SET_PARSEPHRASE:
473 mailparsephrase = (parsephrase_t) value;
474 case GET_PARSEPHRASE:
475 ret = (void *) mailparsephrase;
476 break;
477 case SET_NEWSRCQUERY:
478 mailnewsrcquery = (newsrcquery_t) value;
479 case GET_NEWSRCQUERY:
480 ret = (void *) mailnewsrcquery;
481 break;
482 case SET_NEWSRCCANONHOST:
483 mailnewsrccanon = (long) value;
484 case GET_NEWSRCCANONHOST:
485 ret = (void *) mailnewsrccanon;
486 break;
488 case SET_COPYUID:
489 mailcopyuid = (copyuid_t) value;
490 case GET_COPYUID:
491 ret = (void *) mailcopyuid;
492 break;
493 case SET_APPENDUID:
494 mailappenduid = (appenduid_t) value;
495 case GET_APPENDUID:
496 ret = (void *) mailappenduid;
497 break;
498 case SET_FREEENVELOPESPAREP:
499 mailfreeenvelopesparep = (freeenvelopesparep_t) value;
500 case GET_FREEENVELOPESPAREP:
501 ret = (void *) mailfreeenvelopesparep;
502 break;
503 case SET_FREEELTSPAREP:
504 mailfreeeltsparep = (freeeltsparep_t) value;
505 case GET_FREEELTSPAREP:
506 ret = (void *) mailfreeeltsparep;
507 break;
508 case SET_FREESTREAMSPAREP:
509 mailfreestreamsparep = (freestreamsparep_t) value;
510 case GET_FREESTREAMSPAREP:
511 ret = (void *) mailfreestreamsparep;
512 break;
513 case SET_FREEBODYSPAREP:
514 mailfreebodysparep = (freebodysparep_t) value;
515 case GET_FREEBODYSPAREP:
516 ret = (void *) mailfreebodysparep;
517 break;
519 case SET_SSLSTART:
520 mailsslstart = (sslstart_t) value;
521 case GET_SSLSTART:
522 ret = (void *) mailsslstart;
523 break;
524 case SET_SSLCERTIFICATEQUERY:
525 mailsslcertificatequery = (sslcertificatequery_t) value;
526 case GET_SSLCERTIFICATEQUERY:
527 ret = (void *) mailsslcertificatequery;
528 break;
529 case SET_SSLCLIENTCERT:
530 mailsslclientcert = (sslclientcert_t) value;
531 case GET_SSLCLIENTCERT:
532 ret = (void *) mailsslclientcert;
533 break;
534 case SET_SSLCLIENTKEY:
535 mailsslclientkey = (sslclientkey_t) value;
536 case GET_SSLCLIENTKEY:
537 ret = (void *) mailsslclientkey;
538 break;
539 case SET_SSLFAILURE:
540 mailsslfailure = (sslfailure_t) value;
541 case GET_SSLFAILURE:
542 ret = (void *) mailsslfailure;
543 break;
544 case SET_KINIT:
545 mailkinit = (kinit_t) value;
546 case GET_KINIT:
547 ret = (void *) mailkinit;
548 break;
549 case SET_SENDCOMMAND:
550 mailsendcommand = (sendcommand_t) value;
551 case GET_SENDCOMMAND:
552 ret = (void *) mailsendcommand;
553 break;
555 case SET_SERVICENAME:
556 servicename = (char *) value;
557 case GET_SERVICENAME:
558 ret = (void *) servicename;
559 break;
560 case SET_EXPUNGEATPING:
561 expungeatping = (value ? T : NIL);
562 case GET_EXPUNGEATPING:
563 ret = (void *) (expungeatping ? VOIDT : NIL);
564 break;
565 case SET_SORTRESULTS:
566 mailsortresults = (sortresults_t) value;
567 case GET_SORTRESULTS:
568 ret = (void *) mailsortresults;
569 break;
570 case SET_THREADRESULTS:
571 mailthreadresults = (threadresults_t) value;
572 case GET_THREADRESULTS:
573 ret = (void *) mailthreadresults;
574 break;
575 case SET_SSLDRIVER:
576 mailssldriver = (NETDRIVER *) value;
577 case GET_SSLDRIVER:
578 ret = (void *) mailssldriver;
579 break;
580 case SET_TRYSSLFIRST:
581 trysslfirst = (value ? T : NIL);
582 case GET_TRYSSLFIRST:
583 ret = (void *) (trysslfirst ? VOIDT : NIL);
584 break;
585 case SET_NOTIMEZONES:
586 notimezones = (value ? T : NIL);
587 case GET_NOTIMEZONES:
588 ret = (void *) (notimezones ? VOIDT : NIL);
589 break;
590 case SET_TRUSTDNS:
591 trustdns = (value ? T : NIL);
592 case GET_TRUSTDNS:
593 ret = (void *) (trustdns ? VOIDT : NIL);
594 break;
595 case SET_SASLUSESPTRNAME:
596 saslusesptrname = (value ? T : NIL);
597 case GET_SASLUSESPTRNAME:
598 ret = (void *) (saslusesptrname ? VOIDT : NIL);
599 break;
600 case SET_DEBUGSENSITIVE:
601 debugsensitive = (value ? T : NIL);
602 case GET_DEBUGSENSITIVE:
603 ret = (void *) (debugsensitive ? VOIDT : NIL);
604 break;
606 case SET_ACL:
607 mailaclresults = (getacl_t) value;
608 case GET_ACL:
609 ret = (void *) mailaclresults;
610 break;
611 case SET_LISTRIGHTS:
612 maillistrightsresults = (listrights_t) value;
613 case GET_LISTRIGHTS:
614 ret = (void *) maillistrightsresults;
615 break;
616 case SET_MYRIGHTS:
617 mailmyrightsresults = (myrights_t) value;
618 case GET_MYRIGHTS:
619 ret = (void *) mailmyrightsresults;
620 break;
621 case SET_QUOTA:
622 mailquotaresults = (quota_t) value;
623 case GET_QUOTA:
624 ret = (void *) mailquotaresults;
625 break;
626 case SET_QUOTAROOT:
627 mailquotarootresults = (quotaroot_t) value;
628 case GET_QUOTAROOT:
629 ret = (void *) mailquotarootresults;
630 break;
631 case SET_SNARFINTERVAL:
632 mailsnarfinterval = (long) value;
633 case GET_SNARFINTERVAL:
634 ret = (void *) mailsnarfinterval;
635 break;
636 case SET_SNARFPRESERVE:
637 mailsnarfpreserve = (long) value;
638 case GET_SNARFPRESERVE:
639 ret = (void *) mailsnarfpreserve;
640 break;
641 case SET_SNARFMAILBOXNAME:
642 if (stream) { /* have a stream? */
643 if (stream->snarf.name) fs_give ((void **) &stream->snarf.name);
644 stream->snarf.name = cpystr ((char *) value);
646 else fatal ("SET_SNARFMAILBOXNAME with no stream");
647 case GET_SNARFMAILBOXNAME:
648 if (stream) ret = (void *) stream->snarf.name;
649 break;
650 case SET_IDPARAMS: /* program id */
651 idapp = (IDLIST *) value;
652 case GET_IDPARAMS:
653 ret = (void *) idapp;
654 default:
655 if ((r = smtp_parameters (function,value)) != NULL) ret = r;
656 if ((r = env_parameters (function,value)) != NULL) ret = r;
657 if ((r = tcp_parameters (function,value)) != NULL) ret = r;
658 if ((r = utf8_parameters (function,value)) != NULL) ret = r;
659 if (stream && stream->dtb) {/* if have stream, do for its driver only */
660 if ((r = (*stream->dtb->parameters) (function,value)) != NULL) ret = r;
662 /* else do all drivers */
663 else for (d = maildrivers; d; d = d->next)
664 if ((r = (d->parameters) (function,value)) != NULL) ret = r;
665 break;
667 return ret;
670 /* Mail validate mailbox name
671 * Accepts: MAIL stream
672 * mailbox name
673 * purpose string for error message
674 * Return: driver factory on success, NIL on failure
677 DRIVER *mail_valid (MAILSTREAM *stream,char *mailbox,char *purpose)
679 char tmp[MAILTMPLEN];
680 DRIVER *factory = NIL;
681 /* never allow names with newlines */
682 if (strpbrk (mailbox,"\015\012")) {
683 if (purpose) { /* if want an error message */
684 sprintf (tmp,"Can't %s with such a name",purpose);
685 MM_LOG (tmp,ERROR);
687 return NIL;
689 /* validate name, find driver factory */
690 if (strlen (mailbox) < (NETMAXHOST+(NETMAXUSER*2)+NETMAXMBX+NETMAXSRV+50))
691 for (factory = maildrivers; factory &&
692 ((factory->flags & DR_DISABLE) ||
693 ((factory->flags & DR_LOCAL) && (*mailbox == '{')) ||
694 !(*factory->valid) (mailbox));
695 factory = factory->next);
696 /* validate factory against non-dummy stream */
697 if (factory && stream && stream->dtb && (stream->dtb != factory) &&
698 strcmp (stream->dtb->name,"dummy"))
699 /* factory invalid; if dummy, use stream */
700 factory = strcmp (factory->name,"dummy") ? NIL : stream->dtb;
701 if (!factory && purpose) { /* if want an error message */
702 sprintf (tmp,"Can't %s %.80s: %s",purpose,mailbox,(*mailbox == '{') ?
703 "invalid remote specification" : "no such mailbox");
704 MM_LOG (tmp,ERROR);
706 return factory; /* return driver factory */
709 /* Mail validate network mailbox name
710 * Accepts: mailbox name
711 * mailbox driver to validate against
712 * pointer to where to return host name if non-NIL
713 * pointer to where to return mailbox name if non-NIL
714 * Returns: driver on success, NIL on failure
717 DRIVER *mail_valid_net (char *name,DRIVER *drv,char *host,char *mailbox)
719 NETMBX mb;
720 if (!mail_valid_net_parse (name,&mb) || strcmp (mb.service,drv->name))
721 return NIL;
722 if (host) strcpy (host,mb.host);
723 if (mailbox) strcpy (mailbox,mb.mailbox);
724 return drv;
728 /* Mail validate network mailbox name
729 * Accepts: mailbox name
730 * NETMBX structure to return values
731 * Returns: T on success, NIL on failure
734 long mail_valid_net_parse (char *name,NETMBX *mb)
736 return mail_valid_net_parse_work (name,mb,"imap");
739 /* Mail validate network mailbox name worker routine
740 * Accepts: mailbox name
741 * NETMBX structure to return values
742 * default service
743 * Returns: T on success, NIL on failure
746 long mail_valid_net_parse_work (char *name,NETMBX *mb,char *service)
748 int i,j;
749 char c,*s,*t,*v,tmp[MAILTMPLEN],arg[MAILTMPLEN];
750 /* initialize structure */
751 memset (mb,'\0',sizeof (NETMBX));
752 /* must have host specification */
753 if (*name++ != '{') return NIL;
754 if (*name == '[') { /* if domain literal, find its ending */
755 if (!((v = strpbrk (name,"]}")) && (*v++ == ']'))) return NIL;
757 /* find end of host name */
758 else if (!(v = strpbrk (name,"/:}"))) return NIL;
759 /* validate length, find mailbox part */
760 if (!((i = v - name) && (i < NETMAXHOST) && (t = strchr (v,'}')) &&
761 ((j = t - v) < MAILTMPLEN) && (strlen (t+1) < (size_t) NETMAXMBX)))
762 return NIL; /* invalid mailbox */
763 strncpy (mb->host,name,i); /* set host name */
764 strncpy (mb->orighost,name,i);
765 mb->host[i] = mb->orighost[i] = '\0';
766 strcpy (mb->mailbox,t+1); /* set mailbox name */
767 if (t - v) { /* any switches or port specification? */
768 strncpy (t = tmp,v,j); /* copy it */
769 tmp[j] = '\0'; /* tie it off */
770 c = *t++; /* get first delimiter */
771 do switch (c) { /* act based upon the character */
772 case ':': /* port specification */
773 if (mb->port || !(mb->port = strtoul (t,&t,10))) return NIL;
774 c = t ? *t++ : '\0'; /* get delimiter, advance pointer */
775 break;
776 case '/': /* switch */
777 /* find delimiter */
778 if ((t = strpbrk (s = t,"/:=")) != NULL) {
779 c = *t; /* remember delimiter for later */
780 *t++ = '\0'; /* tie off switch name */
782 else c = '\0'; /* no delimiter */
783 if (c == '=') { /* parse switches which take arguments */
784 if (*t == '"') { /* quoted string? */
785 for (v = arg,i = 0,++t; (c = *t++) != '"';) {
786 if (!c) return NIL; /* unterminated string */
787 /* quote next character */
788 if (c == '\\') c = *t++;
789 if (!c) return NIL; /* can't quote NUL either */
790 arg[i++] = c;
792 c = *t++; /* remember delimiter for later */
793 arg[i] = '\0'; /* tie off argument */
795 else { /* non-quoted argument */
796 if ((t = strpbrk (v = t,"/:")) != NULL) {
797 c = *t; /* remember delimiter for later */
798 *t++ = '\0'; /* tie off switch name */
800 else c = '\0'; /* no delimiter */
801 i = strlen (v); /* length of argument */
803 if (!compare_cstring (s,"service") && (i < NETMAXSRV) && !*mb->service)
804 lcase (strcpy (mb->service,v));
805 else if (!compare_cstring (s,"user") && (i < NETMAXUSER) && !*mb->user)
806 strcpy (mb->user,v);
807 else if (!compare_cstring (s,"authuser") && (i < NETMAXUSER) &&
808 !*mb->authuser) strcpy (mb->authuser,v);
809 else return NIL;
812 else { /* non-argument switch */
813 if (!compare_cstring (s,"anonymous")) mb->anoflag = T;
814 else if (!compare_cstring (s,"debug")) mb->dbgflag = T;
815 else if (!compare_cstring (s,"readonly")) mb->readonlyflag = T;
816 else if (!compare_cstring (s,"secure")) mb->secflag = T;
817 else if (!compare_cstring (s,"norsh")) mb->norsh = T;
818 else if (!compare_cstring (s,"loser")) mb->loser = T;
819 else if (!compare_cstring (s,"tls") && !mb->notlsflag)
820 mb->tlsflag = T;
821 else if (!compare_cstring (s,"tls-sslv23") && !mb->notlsflag)
822 mb->tlssslv23 = mb->tlsflag = T;
823 else if (!compare_cstring (s,"notls") && !mb->tlsflag)
824 mb->notlsflag = T;
825 else if (!compare_cstring (s,"tryssl"))
826 mb->trysslflag = mailssldriver? T : NIL;
827 else if (mailssldriver && !compare_cstring (s,"ssl") && !mb->tlsflag)
828 mb->sslflag = mb->notlsflag = T;
829 else if (!compare_cstring(s, "tls1")
830 && !mb->tls1_1 && !mb->tls1_2 && !mb->dtls1)
831 mb->sslflag = mb->notlsflag = mb->tls1 = T;
832 #ifdef TLSV1_2
833 else if (!compare_cstring(s, "tls1_1")
834 && !mb->tls1 && !mb->tls1_2 && !mb->dtls1)
835 mb->sslflag = mb->notlsflag = mb->tls1_1 = T;
836 else if (!compare_cstring(s, "tls1_2")
837 && !mb->tls1 && !mb->tls1_1 && !mb->dtls1)
838 mb->sslflag = mb->notlsflag = mb->tls1_2 = T;
839 #endif
840 else if (!compare_cstring(s, "dtls1")
841 && !mb->tls1 && !mb->tls1_1 && !mb->tls1_2)
842 mb->sslflag = mb->notlsflag = mb->dtls1 = T;
843 else if (mailssldriver && !compare_cstring (s,"novalidate-cert"))
844 mb->novalidate = T;
845 /* hack for compatibility with the past */
846 else if (mailssldriver && !compare_cstring (s,"validate-cert"));
847 /* service switches below here */
848 else if (*mb->service) return NIL;
849 else if (!compare_cstring (s,"imap") ||
850 !compare_cstring (s,"nntp") ||
851 !compare_cstring (s,"pop3") ||
852 !compare_cstring (s,"smtp") ||
853 !compare_cstring (s,"submit"))
854 lcase (strcpy (mb->service,s));
855 else if (!compare_cstring (s,"imap2") ||
856 !compare_cstring (s,"imap2bis") ||
857 !compare_cstring (s,"imap4") ||
858 !compare_cstring (s,"imap4rev1"))
859 strcpy (mb->service,"imap");
860 else if (!compare_cstring (s,"pop"))
861 strcpy (mb->service,"pop3");
862 else return NIL; /* invalid non-argument switch */
864 break;
865 default: /* anything else is bogus */
866 return NIL;
867 } while (c); /* see if anything more to parse */
869 /* default mailbox name */
870 if (!*mb->mailbox) strcpy (mb->mailbox,"INBOX");
871 /* default service name */
872 if (!*mb->service) strcpy (mb->service,service);
873 /* /norsh only valid if imap */
874 if (mb->norsh && strcmp (mb->service,"imap")) return NIL;
875 return T;
878 /* Mail scan mailboxes for string
879 * Accepts: mail stream
880 * reference
881 * pattern to search
882 * contents to search
885 void mail_scan (MAILSTREAM *stream,char *ref,char *pat,char *contents)
887 int remote = ((*pat == '{') || (ref && *ref == '{'));
888 DRIVER *d;
889 if (ref && (strlen (ref) > NETMAXMBX)) {
890 char tmp[MAILTMPLEN];
891 sprintf (tmp,"Invalid LIST reference specification: %.80s",ref);
892 MM_LOG (tmp,ERROR);
893 return;
895 if (strlen (pat) > NETMAXMBX) {
896 char tmp[MAILTMPLEN];
897 sprintf (tmp,"Invalid LIST pattern specification: %.80s",pat);
898 MM_LOG (tmp,ERROR);
899 return;
901 if (*pat == '{') ref = NIL; /* ignore reference if pattern is remote */
902 if (stream) { /* if have a stream, do it for that stream */
903 if ((d = stream->dtb) && d->scan &&
904 !(((d->flags & DR_LOCAL) && remote)))
905 (*d->scan) (stream,ref,pat,contents);
907 /* otherwise do for all DTB's */
908 else for (d = maildrivers; d; d = d->next)
909 if (d->scan && !((d->flags & DR_DISABLE) ||
910 ((d->flags & DR_LOCAL) && remote)))
911 (d->scan) (NIL,ref,pat,contents);
914 /* Mail list mailboxes
915 * Accepts: mail stream
916 * reference
917 * pattern to search
920 void mail_list (MAILSTREAM *stream,char *ref,char *pat)
922 int remote = ((*pat == '{') || (ref && *ref == '{'));
923 DRIVER *d = maildrivers;
924 if (ref && (strlen (ref) > NETMAXMBX)) {
925 char tmp[MAILTMPLEN];
926 sprintf (tmp,"Invalid LIST reference specification: %.80s",ref);
927 MM_LOG (tmp,ERROR);
928 return;
930 if (strlen (pat) > NETMAXMBX) {
931 char tmp[MAILTMPLEN];
932 sprintf (tmp,"Invalid LIST pattern specification: %.80s",pat);
933 MM_LOG (tmp,ERROR);
934 return;
936 if (*pat == '{') ref = NIL; /* ignore reference if pattern is remote */
937 if (stream && stream->dtb) { /* if have a stream, do it for that stream */
938 if (!(((d = stream->dtb)->flags & DR_LOCAL) && remote))
939 (*d->list) (stream,ref,pat);
941 /* otherwise do for all DTB's */
942 else do if (!((d->flags & DR_DISABLE) ||
943 ((d->flags & DR_LOCAL) && remote)))
944 (d->list) (NIL,ref,pat);
945 while ((d = d->next) != NULL); /* until at the end */
948 /* Mail list subscribed mailboxes
949 * Accepts: mail stream
950 * pattern to search
953 void mail_lsub (MAILSTREAM *stream,char *ref,char *pat)
955 int remote = ((*pat == '{') || (ref && *ref == '{'));
956 DRIVER *d = maildrivers;
957 if (ref && (strlen (ref) > NETMAXMBX)) {
958 char tmp[MAILTMPLEN];
959 sprintf (tmp,"Invalid LSUB reference specification: %.80s",ref);
960 MM_LOG (tmp,ERROR);
961 return;
963 if (strlen (pat) > NETMAXMBX) {
964 char tmp[MAILTMPLEN];
965 sprintf (tmp,"Invalid LSUB pattern specification: %.80s",pat);
966 MM_LOG (tmp,ERROR);
967 return;
969 if (*pat == '{') ref = NIL; /* ignore reference if pattern is remote */
970 if (stream && stream->dtb) { /* if have a stream, do it for that stream */
971 if (!(((d = stream->dtb)->flags & DR_LOCAL) && remote))
972 (*d->lsub) (stream,ref,pat);
974 /* otherwise do for all DTB's */
975 else do if (!((d->flags & DR_DISABLE) ||
976 ((d->flags & DR_LOCAL) && remote)))
977 (d->lsub) (NIL,ref,pat);
978 while ((d = d->next) != NULL); /* until at the end */
981 /* Mail subscribe to mailbox
982 * Accepts: mail stream
983 * mailbox to add to subscription list
984 * Returns: T on success, NIL on failure
987 long mail_subscribe (MAILSTREAM *stream,char *mailbox)
989 DRIVER *factory = mail_valid (stream,mailbox,"subscribe to mailbox");
990 return factory ?
991 (factory->subscribe ?
992 (*factory->subscribe) (stream,mailbox) : sm_subscribe (mailbox)) : NIL;
996 /* Mail unsubscribe to mailbox
997 * Accepts: mail stream
998 * mailbox to delete from subscription list
999 * Returns: T on success, NIL on failure
1002 long mail_unsubscribe (MAILSTREAM *stream,char *mailbox)
1004 DRIVER *factory = mail_valid (stream,mailbox,NIL);
1005 return (factory && factory->unsubscribe) ?
1006 (*factory->unsubscribe) (stream,mailbox) : sm_unsubscribe (mailbox);
1009 /* Mail create mailbox
1010 * Accepts: mail stream
1011 * mailbox name to create
1012 * Returns: T on success, NIL on failure
1015 long mail_create (MAILSTREAM *stream,char *mailbox)
1017 MAILSTREAM *ts;
1018 char *s,*t,tmp[MAILTMPLEN];
1019 size_t i;
1020 DRIVER *d;
1021 /* never allow names with newlines */
1022 if ((s = strpbrk (mailbox,"\015\012")) != NULL) {
1023 MM_LOG ("Can't create mailbox with such a name",ERROR);
1024 return NIL;
1026 if (strlen (mailbox) >= (NETMAXHOST+(NETMAXUSER*2)+NETMAXMBX+NETMAXSRV+50)) {
1027 sprintf (tmp,"Can't create %.80s: %s",mailbox,(*mailbox == '{') ?
1028 "invalid remote specification" : "no such mailbox");
1029 MM_LOG (tmp,ERROR);
1030 return NIL;
1032 /* create of INBOX invalid */
1033 if (!compare_cstring (mailbox,"INBOX")) {
1034 MM_LOG ("Can't create INBOX",ERROR);
1035 return NIL;
1037 /* validate name */
1038 if ((s = mail_utf7_valid (mailbox)) != NULL) {
1039 sprintf (tmp,"Can't create %s: %.80s",s,mailbox);
1040 MM_LOG (tmp,ERROR);
1041 return NIL;
1044 /* see if special driver hack */
1045 if ((mailbox[0] == '#') && ((mailbox[1] == 'd') || (mailbox[1] == 'D')) &&
1046 ((mailbox[2] == 'r') || (mailbox[2] == 'R')) &&
1047 ((mailbox[3] == 'i') || (mailbox[3] == 'I')) &&
1048 ((mailbox[4] == 'v') || (mailbox[4] == 'V')) &&
1049 ((mailbox[5] == 'e') || (mailbox[5] == 'E')) &&
1050 ((mailbox[6] == 'r') || (mailbox[6] == 'R')) && (mailbox[7] == '.')) {
1051 /* copy driver until likely delimiter */
1052 if ((s = strpbrk (t = mailbox+8,"/\\:")) && (i = s - t)) {
1053 strncpy (tmp,t,i);
1054 tmp[i] = '\0';
1056 else {
1057 sprintf (tmp,"Can't create mailbox %.80s: bad driver syntax",mailbox);
1058 MM_LOG (tmp,ERROR);
1059 return NIL;
1061 for (d = maildrivers; d && strcmp (d->name,tmp); d = d->next);
1062 if (d) mailbox = ++s; /* skip past driver specification */
1063 else {
1064 sprintf (tmp,"Can't create mailbox %.80s: unknown driver",mailbox);
1065 MM_LOG (tmp,ERROR);
1066 return NIL;
1069 /* use stream if one given or deterministic */
1070 else if ((stream && stream->dtb) ||
1071 (((*mailbox == '{') || (*mailbox == '#')) &&
1072 (stream = mail_open (NIL,mailbox,OP_PROTOTYPE | OP_SILENT))))
1073 d = stream->dtb;
1074 else if ((*mailbox != '{') && (ts = default_proto (NIL))) d = ts->dtb;
1075 else { /* failed utterly */
1076 sprintf (tmp,"Can't create mailbox %.80s: indeterminate format",mailbox);
1077 MM_LOG (tmp,ERROR);
1078 return NIL;
1080 return (*d->create) (stream,mailbox);
1083 /* Mail delete mailbox
1084 * Accepts: mail stream
1085 * mailbox name to delete
1086 * Returns: T on success, NIL on failure
1089 long mail_delete (MAILSTREAM *stream,char *mailbox)
1091 DRIVER *dtb = mail_valid (stream,mailbox,"delete mailbox");
1092 if (!dtb) return NIL;
1093 if (((mailbox[0] == 'I') || (mailbox[0] == 'i')) &&
1094 ((mailbox[1] == 'N') || (mailbox[1] == 'n')) &&
1095 ((mailbox[2] == 'B') || (mailbox[2] == 'b')) &&
1096 ((mailbox[3] == 'O') || (mailbox[3] == 'o')) &&
1097 ((mailbox[4] == 'X') || (mailbox[4] == 'x')) && !mailbox[5]) {
1098 MM_LOG ("Can't delete INBOX",ERROR);
1099 return NIL;
1101 return SAFE_DELETE (dtb,stream,mailbox);
1105 /* Mail rename mailbox
1106 * Accepts: mail stream
1107 * old mailbox name
1108 * new mailbox name
1109 * Returns: T on success, NIL on failure
1112 long mail_rename (MAILSTREAM *stream,char *old,char *newname)
1114 char *s,tmp[MAILTMPLEN];
1115 DRIVER *dtb = mail_valid (stream,old,"rename mailbox");
1116 if (!dtb) return NIL;
1117 /* validate name */
1118 if ((s = mail_utf7_valid (newname)) != NULL) {
1119 sprintf (tmp,"Can't rename to %s: %.80s",s,newname);
1120 MM_LOG (tmp,ERROR);
1121 return NIL;
1123 if ((*old != '{') && (*old != '#') && mail_valid (NIL,newname,NIL)) {
1124 sprintf (tmp,"Can't rename %.80s: mailbox %.80s already exists",
1125 old,newname);
1126 MM_LOG (tmp,ERROR);
1127 return NIL;
1129 return SAFE_RENAME (dtb,stream,old,newname);
1132 /* Validate mailbox as Modified UTF-7
1133 * Accepts: candidate mailbox name
1134 * Returns: error string if error, NIL if valid
1137 char *mail_utf7_valid (char *mailbox)
1139 char *s;
1140 for (s = mailbox; *s; s++) { /* make sure valid name */
1141 /* reserved for future use with UTF-8 */
1142 if (*s & 0x80) return "mailbox name with 8-bit octet";
1143 /* validate modified UTF-7 */
1144 else if (*s == '&') while (*++s != '-') switch (*s) {
1145 case '\0':
1146 return "unterminated modified UTF-7 name";
1147 case '+': /* valid modified BASE64 */
1148 case ',':
1149 break; /* all OK so far */
1150 default: /* must be alphanumeric */
1151 if (!isalnum (*s)) return "invalid modified UTF-7 name";
1152 break;
1155 return NIL; /* all OK */
1158 /* Mail status of mailbox
1159 * Accepts: mail stream if open on this mailbox
1160 * mailbox name
1161 * status flags
1162 * Returns: T on success, NIL on failure
1165 long mail_status (MAILSTREAM *stream,char *mbx,long flags)
1167 DRIVER *dtb = mail_valid (stream,mbx,"get status of mailbox");
1168 if (!dtb) return NIL; /* only if valid */
1169 if (stream && ((dtb != stream->dtb) ||
1170 ((dtb->flags & DR_LOCAL) && strcmp (mbx,stream->mailbox) &&
1171 strcmp (mbx,stream->original_mailbox))))
1172 stream = NIL; /* stream not suitable */
1173 return SAFE_STATUS (dtb,stream,mbx,flags);
1177 /* Mail status of mailbox default handler
1178 * Accepts: mail stream
1179 * mailbox name
1180 * status flags
1181 * Returns: T on success, NIL on failure
1184 long mail_status_default (MAILSTREAM *stream,char *mbx,long flags)
1186 MAILSTATUS status;
1187 unsigned long i;
1188 MAILSTREAM *tstream = NIL;
1189 /* make temporary stream (unless this mbx) */
1190 if (!stream && !(stream = tstream =
1191 mail_open (NIL,mbx,OP_READONLY|OP_SILENT))) return NIL;
1192 status.flags = flags; /* return status values */
1193 status.messages = stream->nmsgs;
1194 status.recent = stream->recent;
1195 if (flags & SA_UNSEEN) /* must search to get unseen messages */
1196 for (i = 1,status.unseen = 0; i <= stream->nmsgs; i++)
1197 if (!mail_elt (stream,i)->seen) status.unseen++;
1198 status.uidnext = stream->uid_last + 1;
1199 status.uidvalidity = stream->uid_validity;
1200 MM_STATUS(stream,mbx,&status);/* pass status to main program */
1201 if (tstream) mail_close (tstream);
1202 return T; /* success */
1205 /* Mail open
1206 * Accepts: candidate stream for recycling
1207 * mailbox name
1208 * open options
1209 * Returns: stream to use on success, NIL on failure
1212 MAILSTREAM *mail_open (MAILSTREAM *stream,char *name,long options)
1214 int i;
1215 char c,*s,tmp[MAILTMPLEN];
1216 NETMBX mb;
1217 DRIVER *d;
1218 switch (name[0]) { /* see if special handling */
1219 case '#': /* possible special hacks */
1220 if (((name[1] == 'M') || (name[1] == 'm')) &&
1221 ((name[2] == 'O') || (name[2] == 'o')) &&
1222 ((name[3] == 'V') || (name[3] == 'v')) &&
1223 ((name[4] == 'E') || (name[4] == 'e')) && (c = name[5]) &&
1224 (s = strchr (name+6,c)) && (i = s - (name + 6)) && (i < MAILTMPLEN)) {
1225 if ((stream = mail_open (stream,s+1,options)) != NULL) {
1226 strncpy (tmp,name+6,i); /* copy snarf mailbox name */
1227 tmp[i] = '\0'; /* tie off name */
1228 mail_parameters (stream,SET_SNARFMAILBOXNAME,(void *) tmp);
1229 stream->snarf.options = options;
1230 mail_ping (stream); /* do initial snarf */
1231 /* punt if can't do initial snarf */
1232 if (!stream->snarf.time) stream = mail_close (stream);
1234 return stream;
1236 /* special POP hack */
1237 else if (((name[1] == 'P') || (name[1] == 'p')) &&
1238 ((name[2] == 'O') || (name[2] == 'o')) &&
1239 ((name[3] == 'P') || (name[3] == 'p')) &&
1240 mail_valid_net_parse_work (name+4,&mb,"pop3") &&
1241 !strcmp (mb.service,"pop3") && !mb.anoflag && !mb.readonlyflag) {
1242 if ((stream = mail_open (stream,mb.mailbox,options)) != NULL) {
1243 sprintf (tmp,"{%.255s",mb.host);
1244 if (mb.port) sprintf (tmp + strlen (tmp),":%lu",mb.port);
1245 if (mb.user[0]) sprintf (tmp + strlen (tmp),"/user=%.64s",mb.user);
1246 if (mb.dbgflag) strcat (tmp,"/debug");
1247 if (mb.secflag) strcat (tmp,"/secure");
1248 if (mb.tlsflag) strcat (tmp,"/tls");
1249 if (mb.notlsflag) strcat (tmp,"/notls");
1250 if (mb.sslflag) strcat (tmp,"/ssl");
1251 if (mb.tls1) strcat (tmp,"/tls1");
1252 if (mb.tls1_1) strcat (tmp,"/tls1_1");
1253 if (mb.tls1_2) strcat (tmp,"/tls1_2");
1254 if (mb.dtls1) strcat (tmp,"/dtls1");
1255 if (mb.trysslflag) strcat (tmp,"/tryssl");
1256 if (mb.novalidate) strcat (tmp,"/novalidate-cert");
1257 strcat (tmp,"/pop3/loser}");
1258 mail_parameters (stream,SET_SNARFMAILBOXNAME,(void *) tmp);
1259 mail_ping (stream); /* do initial snarf */
1261 return stream; /* return local mailbox stream */
1264 else if ((options & OP_PROTOTYPE) &&
1265 ((name[1] == 'D') || (name[1] == 'd')) &&
1266 ((name[2] == 'R') || (name[2] == 'r')) &&
1267 ((name[3] == 'I') || (name[3] == 'i')) &&
1268 ((name[4] == 'V') || (name[4] == 'v')) &&
1269 ((name[5] == 'E') || (name[5] == 'e')) &&
1270 ((name[6] == 'R') || (name[6] == 'r')) && (name[7] == '.')) {
1271 sprintf (tmp,"%.80s",name+8);
1272 /* tie off name at likely delimiter */
1273 if ((s = strpbrk (tmp,"/\\:")) != NULL) *s++ = '\0';
1274 else {
1275 sprintf (tmp,"Can't resolve mailbox %.80s: bad driver syntax",name);
1276 MM_LOG (tmp,ERROR);
1277 return mail_close (stream);
1279 for (d = maildrivers; d && compare_cstring (d->name,tmp); d = d->next);
1280 if (d) return (*d->open) (NIL);
1281 sprintf (tmp,"Can't resolve mailbox %.80s: unknown driver",name);
1282 MM_LOG (tmp,ERROR);
1283 return mail_close (stream);
1285 /* fall through to default case */
1286 default: /* not special hack (but could be # name */
1287 d = mail_valid (NIL,name,(options & OP_SILENT) ?
1288 (char *) NIL : "open mailbox");
1290 return d ? mail_open_work (d,stream,name,options) : stream;
1293 /* Mail open worker routine
1294 * Accepts: factory
1295 * candidate stream for recycling
1296 * mailbox name
1297 * open options
1298 * Returns: stream to use on success, NIL on failure
1301 MAILSTREAM *mail_open_work (DRIVER *d,MAILSTREAM *stream,char *name,
1302 long options)
1304 int i;
1305 char tmp[MAILTMPLEN];
1306 NETMBX mb;
1307 if (options & OP_PROTOTYPE) return (*d->open) (NIL);
1308 /* name is copied here in case the caller does a re-open using
1309 * stream->mailbox or stream->original_mailbox as the argument.
1311 name = cpystr (name); /* make copy of name */
1312 if (stream) { /* recycling requested? */
1313 if ((stream->dtb == d) && (d->flags & DR_RECYCLE) &&
1314 ((d->flags & DR_HALFOPEN) || !(options & OP_HALFOPEN)) &&
1315 mail_usable_network_stream (stream,name)) {
1316 /* yes, checkpoint if needed */
1317 if (d->flags & DR_XPOINT) mail_check (stream);
1318 mail_free_cache (stream); /* clean up stream */
1319 if (stream->mailbox) fs_give ((void **) &stream->mailbox);
1320 if (stream->original_mailbox)
1321 fs_give ((void **) &stream->original_mailbox);
1322 /* flush user flags */
1323 for (i = 0; i < NUSERFLAGS; i++)
1324 if (stream->user_flags[i]) fs_give ((void **) &stream->user_flags[i]);
1326 else { /* stream not recycleable, babble if net */
1327 if (!stream->silent && stream->dtb && !(stream->dtb->flags&DR_LOCAL) &&
1328 mail_valid_net_parse (stream->mailbox,&mb)) {
1329 sprintf (tmp,"Closing connection to %.80s",mb.host);
1330 MM_LOG (tmp,(long) NIL);
1332 /* flush the old stream */
1333 stream = mail_close (stream);
1336 /* check if driver does not support halfopen */
1337 else if ((options & OP_HALFOPEN) && !(d->flags & DR_HALFOPEN)) {
1338 fs_give ((void **) &name);
1339 return NIL;
1342 /* instantiate new stream if not recycling */
1343 if (!stream) (*mailcache) (stream = (MAILSTREAM *)
1344 memset (fs_get (sizeof (MAILSTREAM)),0,
1345 sizeof (MAILSTREAM)),(long) 0,CH_INIT);
1346 stream->dtb = d; /* set dispatch */
1347 /* set mailbox name */
1348 stream->mailbox = cpystr (stream->original_mailbox = name);
1349 /* initialize stream flags */
1350 stream->inbox = stream->lock = NIL;
1351 stream->debug = (options & OP_DEBUG) ? T : NIL;
1352 stream->rdonly = (options & OP_READONLY) ? T : NIL;
1353 stream->anonymous = (options & OP_ANONYMOUS) ? T : NIL;
1354 stream->scache = (options & OP_SHORTCACHE) ? T : NIL;
1355 stream->silent = (options & OP_SILENT) ? T : NIL;
1356 stream->halfopen = (options & OP_HALFOPEN) ? T : NIL;
1357 stream->secure = (options & OP_SECURE) ? T : NIL;
1358 stream->tryssl = (options & OP_TRYSSL) ? T : NIL;
1359 stream->mulnewsrc = (options & OP_MULNEWSRC) ? T : NIL;
1360 stream->nokod = (options & OP_NOKOD) ? T : NIL;
1361 stream->sniff = (options & OP_SNIFF) ? T : NIL;
1362 stream->perm_seen = stream->perm_deleted = stream->perm_flagged =
1363 stream->perm_answered = stream->perm_draft = stream->kwd_create = NIL;
1364 stream->uid_nosticky = (d->flags & DR_NOSTICKY) ? T : NIL;
1365 stream->uid_last = 0; /* default UID validity */
1366 stream->uid_validity = (unsigned long) time (0);
1367 /* have driver open, flush if failed */
1368 return ((*d->open) (stream)) ? stream : mail_close (stream);
1371 /* Mail close
1372 * Accepts: mail stream
1373 * close options
1374 * Returns: NIL, always
1377 MAILSTREAM *mail_close_full (MAILSTREAM *stream,long options)
1379 int i;
1380 if (stream) { /* make sure argument given */
1381 /* do the driver's close action */
1382 if (stream->dtb) (*stream->dtb->close) (stream,options);
1383 stream->dtb = NIL; /* resign driver */
1384 if (stream->mailbox) fs_give ((void **) &stream->mailbox);
1385 if (stream->original_mailbox)
1386 fs_give ((void **) &stream->original_mailbox);
1387 if (stream->snarf.name) fs_give ((void **) &stream->snarf.name);
1388 stream->sequence++; /* invalidate sequence */
1389 /* flush user flags */
1390 for (i = 0; i < NUSERFLAGS; i++)
1391 if (stream->user_flags[i]) fs_give ((void **) &stream->user_flags[i]);
1392 mail_free_cache (stream); /* finally free the stream's storage */
1393 if (mailfreestreamsparep && stream->sparep)
1394 (*mailfreestreamsparep) (&stream->sparep);
1395 if (!stream->use) fs_give ((void **) &stream);
1397 return NIL;
1400 /* Mail make handle
1401 * Accepts: mail stream
1402 * Returns: handle
1404 * Handles provide a way to have multiple pointers to a stream yet allow the
1405 * stream's owner to nuke it or recycle it.
1408 MAILHANDLE *mail_makehandle (MAILSTREAM *stream)
1410 MAILHANDLE *handle = (MAILHANDLE *) fs_get (sizeof (MAILHANDLE));
1411 handle->stream = stream; /* copy stream */
1412 /* and its sequence */
1413 handle->sequence = stream->sequence;
1414 stream->use++; /* let stream know another handle exists */
1415 return handle;
1418 void mail_free_idlist (IDLIST **idlist)
1420 if (idlist && *idlist){
1421 if((*idlist)->name) fs_give((void **)&(*idlist)->name);
1422 if((*idlist)->value) fs_give((void **)&(*idlist)->value);
1423 if((*idlist)->next) mail_free_idlist(&(*idlist)->next);
1424 fs_give((void **) idlist);
1429 /* Mail release handle
1430 * Accepts: Mail handle
1433 void mail_free_handle (MAILHANDLE **handle)
1435 MAILSTREAM *s;
1436 if (*handle) { /* only free if exists */
1437 /* resign stream, flush unreferenced zombies */
1438 if ((!--(s = (*handle)->stream)->use) && !s->dtb) fs_give ((void **) &s);
1439 fs_give ((void **) handle); /* now flush the handle */
1444 /* Mail get stream handle
1445 * Accepts: Mail handle
1446 * Returns: mail stream or NIL if stream gone
1449 MAILSTREAM *mail_stream (MAILHANDLE *handle)
1451 MAILSTREAM *s = handle->stream;
1452 return (s->dtb && (handle->sequence == s->sequence)) ? s : NIL;
1455 /* Mail fetch cache element
1456 * Accepts: mail stream
1457 * message # to fetch
1458 * Returns: cache element of this message
1459 * Can also be used to create cache elements for new messages.
1462 MESSAGECACHE *mail_elt (MAILSTREAM *stream,unsigned long msgno)
1464 if (msgno < 1 || msgno > stream->nmsgs) {
1465 char tmp[MAILTMPLEN];
1466 sprintf (tmp,"Bad msgno %lu in mail_elt, nmsgs = %lu, mbx=%.80s",
1467 msgno,stream->nmsgs,stream->mailbox ? stream->mailbox : "???");
1468 fatal (tmp);
1470 return (MESSAGECACHE *) (*mailcache) (stream,msgno,CH_MAKEELT);
1474 /* Mail fetch fast information
1475 * Accepts: mail stream
1476 * sequence
1477 * option flags
1479 * Generally, mail_fetch_structure is preferred
1482 void mail_fetch_fast (MAILSTREAM *stream,char *sequence,long flags)
1484 /* do the driver's action */
1485 if (stream->dtb && stream->dtb->fast)
1486 (*stream->dtb->fast) (stream,sequence,flags);
1490 /* Mail fetch flags
1491 * Accepts: mail stream
1492 * sequence
1493 * option flags
1496 void mail_fetch_flags (MAILSTREAM *stream,char *sequence,long flags)
1498 /* do the driver's action */
1499 if (stream->dtb && stream->dtb->msgflags)
1500 (*stream->dtb->msgflags) (stream,sequence,flags);
1503 /* Mail fetch message overview
1504 * Accepts: mail stream
1505 * UID sequence to fetch
1506 * pointer to overview return function
1509 void mail_fetch_overview (MAILSTREAM *stream,char *sequence,overview_t ofn)
1511 if (stream->dtb && mail_uid_sequence (stream,sequence) &&
1512 !(stream->dtb->overview && (*stream->dtb->overview) (stream,ofn)) &&
1513 mail_ping (stream))
1514 mail_fetch_overview_default (stream,ofn);
1518 /* Mail fetch message overview using sequence numbers instead of UIDs
1519 * Accepts: mail stream
1520 * sequence to fetch
1521 * pointer to overview return function
1524 void mail_fetch_overview_sequence (MAILSTREAM *stream,char *sequence,
1525 overview_t ofn)
1527 if (stream->dtb && mail_sequence (stream,sequence) &&
1528 !(stream->dtb->overview && (*stream->dtb->overview) (stream,ofn)) &&
1529 mail_ping (stream))
1530 mail_fetch_overview_default (stream,ofn);
1534 /* Mail fetch message overview default handler
1535 * Accepts: mail stream with sequence bits lit
1536 * pointer to overview return function
1539 void mail_fetch_overview_default (MAILSTREAM *stream,overview_t ofn)
1541 MESSAGECACHE *elt;
1542 ENVELOPE *env;
1543 OVERVIEW ov;
1544 unsigned long i;
1545 ov.optional.lines = 0;
1546 ov.optional.xref = NIL;
1547 for (i = 1; i <= stream->nmsgs; i++)
1548 if (((elt = mail_elt (stream,i))->sequence) &&
1549 (env = mail_fetch_structure (stream,i,NIL,NIL)) && ofn) {
1550 ov.subject = env->subject;
1551 ov.from = env->from;
1552 ov.date = env->date;
1553 ov.message_id = env->message_id;
1554 ov.references = env->references;
1555 ov.optional.octets = elt->rfc822_size;
1556 (*ofn) (stream,mail_uid (stream,i),&ov,i);
1560 /* Mail fetch message structure
1561 * Accepts: mail stream
1562 * message # to fetch
1563 * pointer to return body
1564 * option flags
1565 * Returns: envelope of this message, body returned in body value
1567 * Fetches the "fast" information as well
1570 ENVELOPE *mail_fetch_structure (MAILSTREAM *stream,unsigned long msgno,
1571 BODY **body,long flags)
1573 ENVELOPE **env;
1574 BODY **b;
1575 MESSAGECACHE *elt;
1576 char c,*s,*hdr;
1577 unsigned long hdrsize;
1578 STRING bs;
1579 /* do the driver's action if specified */
1580 if (stream->dtb && stream->dtb->structure)
1581 return (*stream->dtb->structure) (stream,msgno,body,flags);
1582 if (flags & FT_UID) { /* UID form of call */
1583 if ((msgno = mail_msgno (stream,msgno)) != 0L) flags &= ~FT_UID;
1584 else return NIL; /* must get UID/msgno map first */
1586 elt = mail_elt (stream,msgno);/* get elt for real message number */
1587 if (stream->scache) { /* short caching */
1588 if (msgno != stream->msgno){/* garbage collect if not same message */
1589 mail_gc (stream,GC_ENV | GC_TEXTS);
1590 stream->msgno = msgno; /* this is the current message now */
1592 env = &stream->env; /* get pointers to envelope and body */
1593 b = &stream->body;
1595 else { /* get pointers to elt envelope and body */
1596 env = &elt->private.msg.env;
1597 b = &elt->private.msg.body;
1600 if (stream->dtb && ((body && !*b) || !*env || (*env)->incomplete)) {
1601 mail_free_envelope (env); /* flush old envelope and body */
1602 mail_free_body (b);
1603 /* see if need to fetch the whole thing */
1604 if (body || !elt->rfc822_size) {
1605 s = (*stream->dtb->header) (stream,msgno,&hdrsize,flags & ~FT_INTERNAL);
1606 /* make copy in case body fetch smashes it */
1607 hdr = (char *) memcpy (fs_get ((size_t) hdrsize+1),s,(size_t) hdrsize);
1608 hdr[hdrsize] = '\0'; /* tie off header */
1609 (*stream->dtb->text) (stream,msgno,&bs,(flags & ~FT_INTERNAL) | FT_PEEK);
1610 if (!elt->rfc822_size) elt->rfc822_size = hdrsize + SIZE (&bs);
1611 if (body) /* only parse body if requested */
1612 rfc822_parse_msg (env,b,hdr,hdrsize,&bs,BADHOST,stream->dtb->flags);
1613 else
1614 rfc822_parse_msg (env,NIL,hdr,hdrsize,NIL,BADHOST,stream->dtb->flags);
1615 fs_give ((void **) &hdr); /* flush header */
1617 else { /* can save memory doing it this way */
1618 hdr = (*stream->dtb->header) (stream,msgno,&hdrsize,flags | FT_INTERNAL);
1619 if (hdrsize) { /* in case null header */
1620 c = hdr[hdrsize]; /* preserve what's there */
1621 hdr[hdrsize] = '\0'; /* tie off header */
1622 rfc822_parse_msg (env,NIL,hdr,hdrsize,NIL,BADHOST,stream->dtb->flags);
1623 hdr[hdrsize] = c; /* restore in case cached data */
1625 else *env = mail_newenvelope ();
1628 /* if need date, have date in envelope? */
1629 if (!elt->day && *env && (*env)->date) mail_parse_date (elt,(*env)->date);
1630 /* sigh, fill in bogus default */
1631 if (!elt->day) elt->day = elt->month = 1;
1632 if (body) *body = *b; /* return the body */
1633 return *env; /* return the envelope */
1636 /* Mail mark single message (internal use only)
1637 * Accepts: mail stream
1638 * elt to mark
1639 * fetch flags
1642 static void markseen (MAILSTREAM *stream,MESSAGECACHE *elt,long flags)
1644 unsigned long i;
1645 char sequence[20];
1646 MESSAGECACHE *e;
1647 /* non-peeking and needs to set \Seen? */
1648 if (!(flags & FT_PEEK) && !elt->seen) {
1649 if (stream->dtb->flagmsg){ /* driver wants per-message call? */
1650 elt->valid = NIL; /* do pre-alteration driver call */
1651 (*stream->dtb->flagmsg) (stream,elt);
1652 /* set seen, do post-alteration driver call */
1653 elt->seen = elt->valid = T;
1654 (*stream->dtb->flagmsg) (stream,elt);
1656 if (stream->dtb->flag) { /* driver wants one-time call? */
1657 /* better safe than sorry, save seq bits */
1658 for (i = 1; i <= stream->nmsgs; i++) {
1659 e = mail_elt (stream,i);
1660 e->private.sequence = e->sequence;
1662 /* call driver to set the message */
1663 sprintf (sequence,"%lu",elt->msgno);
1664 (*stream->dtb->flag) (stream,sequence,"\\Seen",ST_SET);
1665 /* restore sequence bits */
1666 for (i = 1; i <= stream->nmsgs; i++) {
1667 e = mail_elt (stream,i);
1668 e->sequence = e->private.sequence;
1671 /* notify mail program of flag change */
1672 MM_FLAGS (stream,elt->msgno);
1676 /* Mail fetch message
1677 * Accepts: mail stream
1678 * message # to fetch
1679 * pointer to returned length
1680 * flags
1681 * Returns: message text
1684 char *mail_fetch_message (MAILSTREAM *stream,unsigned long msgno,
1685 unsigned long *len,long flags)
1687 GETS_DATA md;
1688 SIZEDTEXT *t;
1689 STRING bs;
1690 MESSAGECACHE *elt;
1691 char *s,*u;
1692 unsigned long i,j;
1693 if (len) *len = 0; /* default return size */
1694 if (flags & FT_UID) { /* UID form of call */
1695 if ((msgno = mail_msgno (stream,msgno)) != 0L) flags &= ~FT_UID;
1696 else return ""; /* must get UID/msgno map first */
1698 /* initialize message data identifier */
1699 INIT_GETS (md,stream,msgno,"",0,0);
1700 /* is data already cached? */
1701 if ((t = &(elt = mail_elt (stream,msgno))->private.msg.full.text)->data) {
1702 markseen (stream,elt,flags);/* mark message seen */
1703 return mail_fetch_text_return (&md,t,len);
1705 if (!stream->dtb) return ""; /* not in cache, must have live driver */
1706 if (stream->dtb->msgdata) return
1707 ((*stream->dtb->msgdata) (stream,msgno,"",0,0,NIL,flags) && t->data) ?
1708 mail_fetch_text_return (&md,t,len) : "";
1709 /* ugh, have to do this the crufty way */
1710 u = mail_fetch_header (stream,msgno,NIL,NIL,&i,flags);
1711 /* copy in case text method stomps on it */
1712 s = (char *) memcpy (fs_get ((size_t) i),u,(size_t) i);
1713 if ((*stream->dtb->text) (stream,msgno,&bs,flags)) {
1714 t = &stream->text; /* build combined copy */
1715 if (t->data) fs_give ((void **) &t->data);
1716 t->data = (unsigned char *) fs_get ((t->size = i + SIZE (&bs)) + 1);
1717 if (!elt->rfc822_size) elt->rfc822_size = t->size;
1718 else if (elt->rfc822_size != t->size) {
1719 char tmp[MAILTMPLEN];
1720 sprintf (tmp,"Calculated RFC822.SIZE (%lu) != reported size (%lu)",
1721 t->size,elt->rfc822_size);
1722 mm_log (tmp,WARN); /* bug trap */
1724 memcpy (t->data,s,(size_t) i);
1725 for (u = (char *) t->data + i, j = SIZE (&bs); j;) {
1726 memcpy (u,bs.curpos,bs.cursize);
1727 u += bs.cursize; /* update text */
1728 j -= bs.cursize;
1729 bs.curpos += (bs.cursize -1);
1730 bs.cursize = 0;
1731 (*bs.dtb->next) (&bs); /* advance to next buffer's worth */
1733 *u = '\0'; /* tie off data */
1734 u = mail_fetch_text_return (&md,t,len);
1736 else u = "";
1737 fs_give ((void **) &s); /* finished with copy of header */
1738 return u;
1741 /* Mail fetch message header
1742 * Accepts: mail stream
1743 * message # to fetch
1744 * MIME section specifier (#.#.#...#)
1745 * list of lines to fetch
1746 * pointer to returned length
1747 * flags
1748 * Returns: message header in RFC822 format
1750 * Note: never calls a mailgets routine
1753 char *mail_fetch_header (MAILSTREAM *stream,unsigned long msgno,char *section,
1754 STRINGLIST *lines,unsigned long *len,long flags)
1756 STRING bs;
1757 BODY *b = NIL;
1758 SIZEDTEXT *t = NIL,rt;
1759 MESSAGE *m = NIL;
1760 MESSAGECACHE *elt;
1761 char tmp[MAILTMPLEN];
1762 if (len) *len = 0; /* default return size */
1763 if (section && (strlen (section) > (MAILTMPLEN - 20))) return "";
1764 if (flags & FT_UID) { /* UID form of call */
1765 if ((msgno = mail_msgno (stream,msgno)) != 0L) flags &= ~FT_UID;
1766 else return ""; /* must get UID/msgno map first */
1768 elt = mail_elt (stream,msgno);/* get cache data */
1769 if (section && *section) { /* nested body header wanted? */
1770 if (!((b = mail_body (stream,msgno,section)) &&
1771 (b->type == TYPEMESSAGE) && !strcmp (b->subtype,"RFC822")))
1772 return ""; /* lose if no body or not MESSAGE/RFC822 */
1773 m = b->nested.msg; /* point to nested message */
1775 /* else top-level message header wanted */
1776 else m = &elt->private.msg;
1777 if (m->header.text.data && mail_match_lines (lines,m->lines,flags)) {
1778 if (lines) textcpy (t = &stream->text,&m->header.text);
1779 else t = &m->header.text; /* in cache, and cache is valid */
1780 markseen (stream,elt,flags);/* mark message seen */
1783 else if (stream->dtb) { /* not in cache, has live driver? */
1784 if (stream->dtb->msgdata) { /* has driver section fetch? */
1785 /* build driver section specifier */
1786 if (section && *section) sprintf (tmp,"%s.HEADER",section);
1787 else strcpy (tmp,"HEADER");
1788 if ((*stream->dtb->msgdata) (stream,msgno,tmp,0,0,lines,flags)) {
1789 t = &m->header.text; /* fetch data */
1790 /* don't need to postprocess lines */
1791 if (m->lines) lines = NIL;
1792 else if (lines) textcpy (t = &stream->text,&m->header.text);
1795 else if (b) { /* nested body wanted? */
1796 if (stream->private.search.text) {
1797 rt.data = (unsigned char *) stream->private.search.text +
1798 b->nested.msg->header.offset;
1799 rt.size = b->nested.msg->header.text.size;
1800 t = &rt;
1802 else if ((*stream->dtb->text) (stream,msgno,&bs,flags & ~FT_INTERNAL)) {
1803 if ((bs.dtb->next == mail_string_next) && !lines) {
1804 rt.data = (unsigned char *) bs.curpos + b->nested.msg->header.offset;
1805 rt.size = b->nested.msg->header.text.size;
1806 if (stream->private.search.string)
1807 stream->private.search.text = bs.curpos;
1808 t = &rt; /* special hack to avoid extra copy */
1810 else textcpyoffstring (t = &stream->text,&bs,
1811 b->nested.msg->header.offset,
1812 b->nested.msg->header.text.size);
1815 else { /* top-level header fetch */
1816 /* mark message seen */
1817 markseen (stream,elt,flags);
1818 if ((rt.data = (unsigned char *)
1819 (*stream->dtb->header) (stream,msgno,&rt.size,flags)) != NULL) {
1820 /* make a safe copy if need to filter */
1821 if (lines) textcpy (t = &stream->text,&rt);
1822 else t = &rt; /* top level header */
1826 if (!t || !t->data) return "";/* error if no string */
1827 /* filter headers if requested */
1828 if (lines) t->size = mail_filter ((char *) t->data,t->size,lines,flags);
1829 if (len) *len = t->size; /* return size if requested */
1830 return (char *) t->data; /* and text */
1833 /* Mail fetch message text
1834 * Accepts: mail stream
1835 * message # to fetch
1836 * MIME section specifier (#.#.#...#)
1837 * pointer to returned length
1838 * flags
1839 * Returns: message text
1842 char *mail_fetch_text (MAILSTREAM *stream,unsigned long msgno,char *section,
1843 unsigned long *len,long flags)
1845 GETS_DATA md;
1846 PARTTEXT *p;
1847 STRING bs;
1848 MESSAGECACHE *elt;
1849 BODY *b = NIL;
1850 char tmp[MAILTMPLEN];
1851 unsigned long i;
1852 if (len) *len = 0; /* default return size */
1853 memset (&stream->private.string,NIL,sizeof (STRING));
1854 if (section && (strlen (section) > (MAILTMPLEN - 20))) return "";
1855 if (flags & FT_UID) { /* UID form of call */
1856 if ((msgno = mail_msgno (stream,msgno)) != 0L) flags &= ~FT_UID;
1857 else return ""; /* must get UID/msgno map first */
1859 elt = mail_elt (stream,msgno);/* get cache data */
1860 if (section && *section) { /* nested body text wanted? */
1861 if (!((b = mail_body (stream,msgno,section)) &&
1862 (b->type == TYPEMESSAGE) && !strcmp (b->subtype,"RFC822")))
1863 return ""; /* lose if no body or not MESSAGE/RFC822 */
1864 p = &b->nested.msg->text; /* point at nested message */
1865 /* build IMAP-format section specifier */
1866 sprintf (tmp,"%s.TEXT",section);
1867 flags &= ~FT_INTERNAL; /* can't win with this set */
1869 else { /* top-level message text wanted */
1870 p = &elt->private.msg.text;
1871 strcpy (tmp,"TEXT");
1873 /* initialize message data identifier */
1874 INIT_GETS (md,stream,msgno,section,0,0);
1875 if (p->text.data) { /* is data already cached? */
1876 markseen (stream,elt,flags);/* mark message seen */
1877 return mail_fetch_text_return (&md,&p->text,len);
1879 if (!stream->dtb) return ""; /* not in cache, must have live driver */
1880 if (stream->dtb->msgdata) return
1881 ((*stream->dtb->msgdata) (stream,msgno,tmp,0,0,NIL,flags) && p->text.data)?
1882 mail_fetch_text_return (&md,&p->text,len) : "";
1883 if (!(*stream->dtb->text) (stream,msgno,&bs,flags)) return "";
1884 if (section && *section) { /* nested is more complex */
1885 SETPOS (&bs,p->offset);
1886 i = p->text.size; /* just want this much */
1888 else i = SIZE (&bs); /* want entire text */
1889 return mail_fetch_string_return (&md,&bs,i,len,flags);
1892 /* Mail fetch message body part MIME headers
1893 * Accepts: mail stream
1894 * message # to fetch
1895 * MIME section specifier (#.#.#...#)
1896 * pointer to returned length
1897 * flags
1898 * Returns: message text
1901 char *mail_fetch_mime (MAILSTREAM *stream,unsigned long msgno,char *section,
1902 unsigned long *len,long flags)
1904 PARTTEXT *p;
1905 STRING bs;
1906 BODY *b;
1907 char tmp[MAILTMPLEN];
1908 if (len) *len = 0; /* default return size */
1909 if (section && (strlen (section) > (MAILTMPLEN - 20))) return "";
1910 if (flags & FT_UID) { /* UID form of call */
1911 if ((msgno = mail_msgno (stream,msgno)) != 0L) flags &= ~FT_UID;
1912 else return ""; /* must get UID/msgno map first */
1914 flags &= ~FT_INTERNAL; /* can't win with this set */
1915 if (!(section && *section && (b = mail_body (stream,msgno,section))))
1916 return ""; /* not valid section */
1917 /* in cache? */
1918 if ((p = &b->mime)->text.data) {
1919 /* mark message seen */
1920 markseen (stream,mail_elt (stream,msgno),flags);
1921 if (len) *len = p->text.size;
1922 return (char *) p->text.data;
1924 if (!stream->dtb) return ""; /* not in cache, must have live driver */
1925 if (stream->dtb->msgdata) { /* has driver fetch? */
1926 /* build driver section specifier */
1927 sprintf (tmp,"%s.MIME",section);
1928 if ((*stream->dtb->msgdata) (stream,msgno,tmp,0,0,NIL,flags) &&
1929 p->text.data) {
1930 if (len) *len = p->text.size;
1931 return (char *) p->text.data;
1933 else return "";
1935 if (len) *len = b->mime.text.size;
1936 if (!b->mime.text.size) { /* empty MIME header -- mark seen anyway */
1937 markseen (stream,mail_elt (stream,msgno),flags);
1938 return "";
1940 /* have to get it from offset */
1941 if (stream->private.search.text)
1942 return stream->private.search.text + b->mime.offset;
1943 if (!(*stream->dtb->text) (stream,msgno,&bs,flags)) {
1944 if (len) *len = 0;
1945 return "";
1947 if (bs.dtb->next == mail_string_next) {
1948 if (stream->private.search.string) stream->private.search.text = bs.curpos;
1949 return bs.curpos + b->mime.offset;
1951 return textcpyoffstring (&stream->text,&bs,b->mime.offset,b->mime.text.size);
1954 /* Mail fetch message body part
1955 * Accepts: mail stream
1956 * message # to fetch
1957 * MIME section specifier (#.#.#...#)
1958 * pointer to returned length
1959 * flags
1960 * Returns: message body
1963 char *mail_fetch_body (MAILSTREAM *stream,unsigned long msgno,char *section,
1964 unsigned long *len,long flags)
1966 GETS_DATA md;
1967 PARTTEXT *p;
1968 STRING bs;
1969 BODY *b;
1970 SIZEDTEXT *t;
1971 char *s,tmp[MAILTMPLEN];
1972 memset (&stream->private.string,NIL,sizeof (STRING));
1973 if (!(section && *section)) /* top-level text wanted? */
1974 return mail_fetch_message (stream,msgno,len,flags);
1975 else if (strlen (section) > (MAILTMPLEN - 20)) return "";
1976 flags &= ~FT_INTERNAL; /* can't win with this set */
1977 /* initialize message data identifier */
1978 INIT_GETS (md,stream,msgno,section,0,0);
1979 /* kludge for old section 0 header */
1980 if (!strcmp (s = strcpy (tmp,section),"0") ||
1981 ((s = strstr (tmp,".0")) && !s[2])) {
1982 SIZEDTEXT ht;
1983 *s = '\0'; /* tie off section */
1984 /* this silly way so it does mailgets */
1985 ht.data = (unsigned char *) mail_fetch_header (stream,msgno,
1986 tmp[0] ? tmp : NIL,NIL,
1987 &ht.size,flags);
1988 /* may have UIDs here */
1989 md.flags = (flags & FT_UID) ? MG_UID : NIL;
1990 return mail_fetch_text_return (&md,&ht,len);
1992 if (len) *len = 0; /* default return size */
1993 if (flags & FT_UID) { /* UID form of call */
1994 if ((msgno = mail_msgno (stream,msgno)) != 0L) flags &= ~FT_UID;
1995 else return ""; /* must get UID/msgno map first */
1997 /* must have body */
1998 if (!(b = mail_body (stream,msgno,section))) return "";
1999 /* have cached text? */
2000 if ((t = &(p = &b->contents)->text)->data) {
2001 /* mark message seen */
2002 markseen (stream,mail_elt (stream,msgno),flags);
2003 return mail_fetch_text_return (&md,t,len);
2005 if (!stream->dtb) return ""; /* not in cache, must have live driver */
2006 if (stream->dtb->msgdata) return
2007 ((*stream->dtb->msgdata)(stream,msgno,section,0,0,NIL,flags) && t->data) ?
2008 mail_fetch_text_return (&md,t,len) : "";
2009 if (len) *len = t->size;
2010 if (!t->size) { /* empty body part -- mark seen anyway */
2011 markseen (stream,mail_elt (stream,msgno),flags);
2012 return "";
2014 /* copy body from stringstruct offset */
2015 if (stream->private.search.text)
2016 return stream->private.search.text + p->offset;
2017 if (!(*stream->dtb->text) (stream,msgno,&bs,flags)) {
2018 if (len) *len = 0;
2019 return "";
2021 if (bs.dtb->next == mail_string_next) {
2022 if (stream->private.search.string) stream->private.search.text = bs.curpos;
2023 return bs.curpos + p->offset;
2025 SETPOS (&bs,p->offset);
2026 return mail_fetch_string_return (&md,&bs,t->size,len,flags);
2029 /* Mail fetch partial message text
2030 * Accepts: mail stream
2031 * message # to fetch
2032 * MIME section specifier (#.#.#...#)
2033 * offset of first designed byte or 0 to start at beginning
2034 * maximum number of bytes or 0 for all bytes
2035 * flags
2036 * Returns: T if successful, else NIL
2039 long mail_partial_text (MAILSTREAM *stream,unsigned long msgno,char *section,
2040 unsigned long first,unsigned long last,long flags)
2042 GETS_DATA md;
2043 PARTTEXT *p = NIL;
2044 MESSAGECACHE *elt;
2045 STRING bs;
2046 BODY *b;
2047 char tmp[MAILTMPLEN];
2048 unsigned long i;
2049 if (!mailgets) fatal ("mail_partial_text() called without a mailgets!");
2050 if (section && (strlen (section) > (MAILTMPLEN - 20))) return NIL;
2051 if (flags & FT_UID) { /* UID form of call */
2052 if ((msgno = mail_msgno (stream,msgno)) != 0L) flags &= ~FT_UID;
2053 else return NIL; /* must get UID/msgno map first */
2055 elt = mail_elt (stream,msgno);/* get cache data */
2056 flags &= ~FT_INTERNAL; /* bogus if this is set */
2057 if (section && *section) { /* nested body text wanted? */
2058 if (!((b = mail_body (stream,msgno,section)) &&
2059 (b->type == TYPEMESSAGE) && !strcmp (b->subtype,"RFC822")))
2060 return NIL; /* lose if no body or not MESSAGE/RFC822 */
2061 p = &b->nested.msg->text; /* point at nested message */
2062 /* build IMAP-format section specifier */
2063 sprintf (tmp,"%s.TEXT",section);
2065 else { /* else top-level message text wanted */
2066 p = &elt->private.msg.text;
2067 strcpy (tmp,"TEXT");
2070 /* initialize message data identifier */
2071 INIT_GETS (md,stream,msgno,tmp,first,last);
2072 if (p->text.data) { /* is data already cached? */
2073 INIT (&bs,mail_string,p->text.data,i = p->text.size);
2074 markseen (stream,elt,flags);/* mark message seen */
2076 else { /* else get data from driver */
2077 if (!stream->dtb) return NIL;
2078 if (stream->dtb->msgdata) /* driver will handle this */
2079 return (*stream->dtb->msgdata) (stream,msgno,tmp,first,last,NIL,flags);
2080 if (!(*stream->dtb->text) (stream,msgno,&bs,flags)) return NIL;
2081 if (section && *section) { /* nexted if more complex */
2082 SETPOS (&bs,p->offset); /* offset stringstruct to data */
2083 i = p->text.size; /* maximum size of data */
2085 else i = SIZE (&bs); /* just want this much */
2087 if (i <= first) i = first = 0;/* first byte is beyond end of text */
2088 /* truncate as needed */
2089 else { /* offset and truncate */
2090 SETPOS (&bs,first + GETPOS (&bs));
2091 i -= first; /* reduced size */
2092 if (last && (i > last)) i = last;
2094 /* do the mailgets thing */
2095 (*mailgets) (mail_read,&bs,i,&md);
2096 return T; /* success */
2099 /* Mail fetch partial message body part
2100 * Accepts: mail stream
2101 * message # to fetch
2102 * MIME section specifier (#.#.#...#)
2103 * offset of first designed byte or 0 to start at beginning
2104 * maximum number of bytes or 0 for all bytes
2105 * flags
2106 * Returns: T if successful, else NIL
2109 long mail_partial_body (MAILSTREAM *stream,unsigned long msgno,char *section,
2110 unsigned long first,unsigned long last,long flags)
2112 GETS_DATA md;
2113 PARTTEXT *p;
2114 STRING bs;
2115 BODY *b;
2116 SIZEDTEXT *t;
2117 unsigned long i;
2118 if (!(section && *section)) /* top-level text wanted? */
2119 return mail_partial_text (stream,msgno,NIL,first,last,flags);
2120 if (!mailgets) fatal ("mail_partial_body() called without a mailgets!");
2121 if (flags & FT_UID) { /* UID form of call */
2122 if ((msgno = mail_msgno (stream,msgno)) != 0L) flags &= ~FT_UID;
2123 else return NIL; /* must get UID/msgno map first */
2125 /* must have body */
2126 if (!(b = mail_body (stream,msgno,section))) return NIL;
2127 flags &= ~FT_INTERNAL; /* bogus if this is set */
2129 /* initialize message data identifier */
2130 INIT_GETS (md,stream,msgno,section,first,last);
2131 /* have cached text? */
2132 if ((t = &(p = &b->contents)->text)->data) {
2133 /* mark message seen */
2134 markseen (stream,mail_elt (stream,msgno),flags);
2135 INIT (&bs,mail_string,t->data,i = t->size);
2137 else { /* else get data from driver */
2138 if (!stream->dtb) return NIL;
2139 if (stream->dtb->msgdata) /* driver will handle this */
2140 return (*stream->dtb->msgdata) (stream,msgno,section,first,last,NIL,
2141 flags);
2142 if (!(*stream->dtb->text) (stream,msgno,&bs,flags)) return NIL;
2143 if (section && *section) { /* nexted if more complex */
2144 SETPOS (&bs,p->offset); /* offset stringstruct to data */
2145 i = t->size; /* maximum size of data */
2147 else i = SIZE (&bs); /* just want this much */
2149 if (i <= first) i = first = 0;/* first byte is beyond end of text */
2150 else { /* offset and truncate */
2151 SETPOS (&bs,first + GETPOS (&bs));
2152 i -= first; /* reduced size */
2153 if (last && (i > last)) i = last;
2155 /* do the mailgets thing */
2156 (*mailgets) (mail_read,&bs,i,&md);
2157 return T; /* success */
2160 /* Mail return message text
2161 * Accepts: identifier data
2162 * sized text
2163 * pointer to returned length
2164 * Returns: text
2167 char *mail_fetch_text_return (GETS_DATA *md,SIZEDTEXT *t,unsigned long *len)
2169 STRING bs;
2170 if (len) *len = t->size; /* return size */
2171 if (t->size && mailgets) { /* have to do the mailgets thing? */
2172 /* silly but do it anyway for consistency */
2173 INIT (&bs,mail_string,t->data,t->size);
2174 return (*mailgets) (mail_read,&bs,t->size,md);
2176 return t->size ? (char *) t->data : "";
2180 /* Mail return message string
2181 * Accepts: identifier data
2182 * stringstruct
2183 * text length
2184 * pointer to returned length
2185 * flags
2186 * Returns: text, or NIL if stringstruct returned
2189 char *mail_fetch_string_return (GETS_DATA *md,STRING *bs,unsigned long i,
2190 unsigned long *len,long flags)
2192 char *ret = NIL;
2193 if (len) *len = i; /* return size */
2194 /* return stringstruct hack */
2195 if (flags & FT_RETURNSTRINGSTRUCT) {
2196 memcpy (&md->stream->private.string,bs,sizeof (STRING));
2197 SETPOS (&md->stream->private.string,GETPOS (&md->stream->private.string));
2199 /* have to do the mailgets thing? */
2200 else if (mailgets) ret = (*mailgets) (mail_read,bs,i,md);
2201 /* special hack to avoid extra copy */
2202 else if (bs->dtb->next == mail_string_next) ret = bs->curpos;
2203 /* make string copy in memory */
2204 else ret = textcpyoffstring (&md->stream->text,bs,GETPOS (bs),i);
2205 return ret;
2208 /* Read data from stringstruct
2209 * Accepts: stringstruct
2210 * size of data to read
2211 * buffer to read into
2212 * Returns: T, always, stringstruct updated
2215 long mail_read (void *stream,unsigned long size,char *buffer)
2217 unsigned long i;
2218 STRING *s = (STRING *) stream;
2219 while (size) { /* until satisfied */
2220 memcpy (buffer,s->curpos,i = min (s->cursize,size));
2221 buffer += i; /* update buffer */
2222 size -= i; /* note that we read this much */
2223 s->curpos += --i; /* advance that many spaces minus 1 */
2224 s->cursize -= i;
2225 SNX (s); /* now use SNX to advance the last byte */
2227 return T;
2230 /* Mail fetch UID
2231 * Accepts: mail stream
2232 * message number
2233 * Returns: UID or zero if dead stream
2236 unsigned long mail_uid (MAILSTREAM *stream,unsigned long msgno)
2238 unsigned long uid = mail_elt (stream,msgno)->private.uid;
2239 return uid ? uid :
2240 (stream->dtb && stream->dtb->uid) ? (*stream->dtb->uid) (stream,msgno) : 0;
2244 /* Mail fetch msgno from UID
2245 * Accepts: mail stream
2246 * UID
2247 * Returns: msgno or zero if failed
2250 unsigned long mail_msgno (MAILSTREAM *stream,unsigned long uid)
2252 unsigned long msgno,delta,first,firstuid,last,lastuid,middle,miduid;
2253 if (stream->dtb) { /* active stream? */
2254 if (stream->dtb->msgno) /* direct way */
2255 return (*stream->dtb->msgno) (stream,uid);
2256 else if (stream->dtb->uid) {/* indirect way */
2257 /* Placeholder for now, since currently there are no drivers which
2258 * have a uid method but not a msgno method
2260 for (msgno = 1; msgno <= stream->nmsgs; msgno++)
2261 if ((*stream->dtb->uid) (stream,msgno) == uid) return msgno;
2263 /* binary search since have full map */
2264 else for (first = 1,last = stream->nmsgs, delta = (first <= last) ? 1 : 0;
2265 delta &&
2266 (uid >= (firstuid = mail_elt (stream,first)->private.uid)) &&
2267 (uid <= (lastuid = mail_elt (stream,last)->private.uid));) {
2268 /* done if match at an endpoint */
2269 if (uid == firstuid) return first;
2270 if (uid == lastuid) return last;
2271 /* have anything between endpoints? */
2272 if ((delta = ((last - first) / 2)) != 0L){
2273 if ((miduid = mail_elt (stream,middle = first + delta)->private.uid)
2274 == uid)
2275 return middle; /* found match in middle */
2276 else if (uid < miduid) last = middle - 1;
2277 else first = middle + 1;
2281 else { /* dead stream, do linear search for UID */
2282 for (msgno = 1; msgno <= stream->nmsgs; msgno++)
2283 if (mail_elt (stream,msgno)->private.uid == uid) return msgno;
2285 return 0; /* didn't find the UID anywhere */
2288 /* Mail fetch From string for menu
2289 * Accepts: destination string
2290 * mail stream
2291 * message # to fetch
2292 * desired string length
2293 * Returns: string of requested length
2296 void mail_fetchfrom (char *s,MAILSTREAM *stream,unsigned long msgno,
2297 long length)
2299 char *t;
2300 char tmp[MAILTMPLEN];
2301 ENVELOPE *env = mail_fetchenvelope (stream,msgno);
2302 ADDRESS *adr = env ? env->from : NIL;
2303 memset (s,' ',(size_t)length);/* fill it with spaces */
2304 s[length] = '\0'; /* tie off with null */
2305 /* get first from address from envelope */
2306 while (adr && !adr->host) adr = adr->next;
2307 if (adr) { /* if a personal name exists use it */
2308 if (!(t = adr->personal))
2309 sprintf (t = tmp,"%.256s@%.256s",adr->mailbox,adr->host);
2310 memcpy (s,t,(size_t) min (length,(long) strlen (t)));
2315 /* Mail fetch Subject string for menu
2316 * Accepts: destination string
2317 * mail stream
2318 * message # to fetch
2319 * desired string length
2320 * Returns: string of no more than requested length
2323 void mail_fetchsubject (char *s,MAILSTREAM *stream,unsigned long msgno,
2324 long length)
2326 ENVELOPE *env = mail_fetchenvelope (stream,msgno);
2327 memset (s,'\0',(size_t) length+1);
2328 /* copy subject from envelope */
2329 if (env && env->subject) strncpy (s,env->subject,(size_t) length);
2330 else *s = ' '; /* if no subject then just a space */
2333 /* Mail modify flags
2334 * Accepts: mail stream
2335 * sequence
2336 * flag(s)
2337 * option flags
2340 void mail_flag (MAILSTREAM *stream,char *sequence,char *flag,long flags)
2342 MESSAGECACHE *elt;
2343 unsigned long i,uf;
2344 long f;
2345 short nf;
2346 if (!stream->dtb) return; /* no-op if no stream */
2347 if ((stream->dtb->flagmsg || !stream->dtb->flag) &&
2348 ((flags & ST_UID) ? mail_uid_sequence (stream,sequence) :
2349 mail_sequence (stream,sequence)) &&
2350 ((f = mail_parse_flags (stream,flag,&uf)) || uf))
2351 for (i = 1,nf = (flags & ST_SET) ? T : NIL; i <= stream->nmsgs; i++)
2352 if ((elt = mail_elt (stream,i))->sequence) {
2353 struct { /* old flags */
2354 unsigned int valid : 1;
2355 unsigned int seen : 1;
2356 unsigned int deleted : 1;
2357 unsigned int flagged : 1;
2358 unsigned int answered : 1;
2359 unsigned int draft : 1;
2360 unsigned long user_flags;
2361 } old;
2362 old.valid = elt->valid; old.seen = elt->seen;
2363 old.deleted = elt->deleted; old.flagged = elt->flagged;
2364 old.answered = elt->answered; old.draft = elt->draft;
2365 old.user_flags = elt->user_flags;
2366 elt->valid = NIL; /* prepare for flag alteration */
2367 if (stream->dtb->flagmsg) (*stream->dtb->flagmsg) (stream,elt);
2368 if (f&fSEEN) elt->seen = nf;
2369 if (f&fDELETED) elt->deleted = nf;
2370 if (f&fFLAGGED) elt->flagged = nf;
2371 if (f&fANSWERED) elt->answered = nf;
2372 if (f&fDRAFT) elt->draft = nf;
2373 /* user flags */
2374 if (flags & ST_SET) elt->user_flags |= uf;
2375 else elt->user_flags &= ~uf;
2376 elt->valid = T; /* flags now altered */
2377 if ((old.valid != elt->valid) || (old.seen != elt->seen) ||
2378 (old.deleted != elt->deleted) || (old.flagged != elt->flagged) ||
2379 (old.answered != elt->answered) || (old.draft != elt->draft) ||
2380 (old.user_flags != elt->user_flags))
2381 MM_FLAGS (stream,elt->msgno);
2382 if (stream->dtb->flagmsg) (*stream->dtb->flagmsg) (stream,elt);
2384 /* call driver once */
2385 if (stream->dtb->flag) (*stream->dtb->flag) (stream,sequence,flag,flags);
2388 /* Mail search for messages
2389 * Accepts: mail stream
2390 * character set
2391 * search program
2392 * option flags
2393 * Returns: T if successful, NIL if dead stream, NIL searchpgm or bad charset
2396 long mail_search_full (MAILSTREAM *stream,char *charset,SEARCHPGM *pgm,
2397 long flags)
2399 unsigned long i;
2400 long ret = NIL;
2401 if (!(flags & SE_RETAIN)) /* clear search vector unless retaining */
2402 for (i = 1; i <= stream->nmsgs; ++i) mail_elt (stream,i)->searched = NIL;
2403 if (pgm && stream->dtb) /* must have a search program and driver */
2404 ret = (*(stream->dtb->search ? stream->dtb->search : mail_search_default))
2405 (stream,charset,pgm,flags);
2406 /* flush search program if requested */
2407 if (flags & SE_FREE) mail_free_searchpgm (&pgm);
2408 return ret;
2412 /* Mail search for messages default handler
2413 * Accepts: mail stream
2414 * character set
2415 * search program
2416 * option flags
2417 * Returns: T if successful, NIL if bad charset
2420 long mail_search_default (MAILSTREAM *stream,char *charset,SEARCHPGM *pgm,
2421 long flags)
2423 unsigned long i;
2424 char *msg;
2425 /* make sure that charset is good */
2426 if ((msg = utf8_badcharset (charset)) != NULL) {
2427 MM_LOG (msg,ERROR); /* output error */
2428 fs_give ((void **) &msg);
2429 return NIL;
2431 utf8_searchpgm (pgm,charset);
2432 for (i = 1; i <= stream->nmsgs; ++i)
2433 if (mail_search_msg (stream,i,NIL,pgm)) {
2434 if (flags & SE_UID) mm_searched (stream,mail_uid (stream,i));
2435 else { /* mark as searched, notify mail program */
2436 mail_elt (stream,i)->searched = T;
2437 if (!stream->silent) mm_searched (stream,i);
2440 return LONGT; /* search completed */
2443 /* Mail ping mailbox
2444 * Accepts: mail stream
2445 * Returns: stream if still open else NIL
2448 long mail_ping (MAILSTREAM *stream)
2450 unsigned long i,n,uf,len;
2451 char *s,*f,tmp[MAILTMPLEN],flags[MAILTMPLEN];
2452 MAILSTREAM *snarf;
2453 MESSAGECACHE *elt;
2454 STRING bs;
2455 long ret;
2456 /* do driver action */
2457 if ((ret = ((stream && stream->dtb) ? (stream->dtb->ping) (stream) : NIL)) &&
2458 stream->snarf.name && /* time to snarf? */
2459 /* prohibit faster than once/min */
2460 (time (0) > (time_t) (stream->snarf.time + min(60,mailsnarfinterval))) &&
2461 (snarf = mail_open (NIL,stream->snarf.name,
2462 stream->snarf.options | OP_SILENT))) {
2463 if ((n = snarf->nmsgs) && /* yes, have messages to snarf? */
2464 mail_search_full (snarf,NIL,mail_criteria ("UNDELETED"),SE_FREE)) {
2465 for (i = 1; ret && (i <= n); i++) /* for each message */
2466 if ((elt = mail_elt (snarf,i))->searched &&
2467 (s = mail_fetch_message (snarf,i,&len,FT_PEEK)) && len) {
2468 INIT (&bs,mail_string,s,len);
2469 if (mailsnarfpreserve) {
2470 /* yes, make sure have fast data */
2471 if (!elt->valid || !elt->day) {
2472 sprintf (tmp,"%lu",n);
2473 mail_fetch_fast (snarf,tmp,NIL);
2475 /* initialize flag string */
2476 memset (flags,0,MAILTMPLEN);
2477 /* output system flags except \Deleted */
2478 if (elt->seen) strcat (flags," \\Seen");
2479 if (elt->flagged) strcat (flags," \\Flagged");
2480 if (elt->answered) strcat (flags," \\Answered");
2481 if (elt->draft) strcat (flags," \\Draft");
2482 /* any user flags? */
2483 for (uf = elt->user_flags,s = flags + strlen (flags);
2484 uf && (f = stream->user_flags[find_rightmost_bit (&uf)]) &&
2485 ((MAILTMPLEN - (s - tmp)) > (long) (2 + strlen (f)));
2486 s += strlen (s)) sprintf (s," %s",f);
2487 ret = mail_append_full (stream,stream->mailbox,flags + 1,
2488 mail_date (tmp,elt),&bs);
2490 else ret = mail_append (stream,stream->mailbox,&bs);
2492 if (ret) { /* did snarf succeed? */
2493 /* driver has per-message (or no) flag call */
2494 if (snarf->dtb->flagmsg || !snarf->dtb->flag) {
2495 elt->valid = NIL; /* prepare for flag alteration */
2496 if (snarf->dtb->flagmsg) (*snarf->dtb->flagmsg) (snarf,elt);
2497 /* flags now altered */
2498 elt->deleted = elt->seen = elt->valid = T;
2499 if (snarf->dtb->flagmsg) (*snarf->dtb->flagmsg) (snarf,elt);
2501 /* driver has one-time flag call */
2502 if (snarf->dtb->flag) {
2503 sprintf (tmp,"%lu",i);
2504 (*snarf->dtb->flag) (snarf,tmp,"\\Deleted \\Seen",ST_SET);
2507 else { /* copy failed */
2508 sprintf (tmp,"Unable to move message %lu from %s mailbox",
2509 i,snarf->dtb->name);
2510 mm_log (tmp,WARN);
2514 /* expunge the messages */
2515 mail_close_full (snarf,n ? CL_EXPUNGE : NIL);
2516 stream->snarf.time = (unsigned long) time (0);
2517 /* Even if the snarf failed, we don't want to return NIL if the stream
2518 * is still alive. Or at least that's what we currently think.
2520 /* redo the driver's action */
2521 ret = stream->dtb ? (*stream->dtb->ping) (stream) : NIL;
2523 return ret;
2526 /* Mail check mailbox
2527 * Accepts: mail stream
2530 void mail_check (MAILSTREAM *stream)
2532 /* do the driver's action */
2533 if (stream->dtb) (*stream->dtb->check) (stream);
2537 /* Mail expunge mailbox
2538 * Accepts: mail stream
2539 * sequence to expunge if non-NIL
2540 * expunge options
2541 * Returns: T on success, NIL on failure
2544 long mail_expunge_full (MAILSTREAM *stream,char *sequence,long options)
2546 /* do the driver's action */
2547 return stream->dtb ? (*stream->dtb->expunge) (stream,sequence,options) : NIL;
2551 /* Mail copy message(s)
2552 * Accepts: mail stream
2553 * sequence
2554 * destination mailbox
2555 * flags
2558 long mail_copy_full (MAILSTREAM *stream,char *sequence,char *mailbox,
2559 long options)
2561 return stream->dtb ?
2562 SAFE_COPY (stream->dtb,stream,sequence,mailbox,options) : NIL;
2565 /* Append data package to use for old single-message mail_append() interface */
2567 typedef struct mail_append_package {
2568 char *flags; /* initial flags */
2569 char *date; /* message internal date */
2570 STRING *message; /* stringstruct of message */
2571 } APPENDPACKAGE;
2574 /* Single append message string
2575 * Accepts: mail stream
2576 * package pointer (cast as a void *)
2577 * pointer to return initial flags
2578 * pointer to return message internal date
2579 * pointer to return stringstruct of message to append
2580 * Returns: T, always
2583 static long mail_append_single (MAILSTREAM *stream,void *data,char **flags,
2584 char **date,STRING **message)
2586 APPENDPACKAGE *ap = (APPENDPACKAGE *) data;
2587 *flags = ap->flags; /* get desired data from the package */
2588 *date = ap->date;
2589 *message = ap->message;
2590 ap->message = NIL; /* so next callback puts a stop to it */
2591 return LONGT; /* always return success */
2595 /* Mail append message string
2596 * Accepts: mail stream
2597 * destination mailbox
2598 * initial flags
2599 * message internal date
2600 * stringstruct of message to append
2601 * Returns: T on success, NIL on failure
2604 long mail_append_full (MAILSTREAM *stream,char *mailbox,char *flags,char *date,
2605 STRING *message)
2607 APPENDPACKAGE ap;
2608 ap.flags = flags; /* load append package */
2609 ap.date = date;
2610 ap.message = message;
2611 return mail_append_multiple (stream,mailbox,mail_append_single,(void *) &ap);
2614 /* Mail append message(s)
2615 * Accepts: mail stream
2616 * destination mailbox
2617 * append data callback
2618 * arbitrary data for callback use
2619 * Returns: T on success, NIL on failure
2622 long mail_append_multiple (MAILSTREAM *stream,char *mailbox,append_t af,
2623 void *data)
2625 char *s,tmp[MAILTMPLEN];
2626 DRIVER *d = NIL;
2627 long ret = NIL;
2628 /* never allow names with newlines */
2629 if (strpbrk (mailbox,"\015\012"))
2630 MM_LOG ("Can't append to mailbox with such a name",ERROR);
2631 else if (strlen (mailbox) >=
2632 (NETMAXHOST+(NETMAXUSER*2)+NETMAXMBX+NETMAXSRV+50)) {
2633 sprintf (tmp,"Can't append %.80s: %s",mailbox,(*mailbox == '{') ?
2634 "invalid remote specification" : "no such mailbox");
2635 MM_LOG (tmp,ERROR);
2637 /* special driver hack? */
2638 else if (!strncmp (lcase (strcpy (tmp,mailbox)),"#driver.",8)) {
2639 /* yes, tie off name at likely delimiter */
2640 if (!(s = strpbrk (tmp+8,"/\\:"))) {
2641 sprintf (tmp,"Can't append to mailbox %.80s: bad driver syntax",mailbox);
2642 MM_LOG (tmp,ERROR);
2643 return NIL;
2645 *s++ = '\0'; /* tie off at delimiter */
2646 if (!(d = (DRIVER *) mail_parameters (NIL,GET_DRIVER,tmp+8))) {
2647 sprintf (tmp,"Can't append to mailbox %.80s: unknown driver",mailbox);
2648 MM_LOG (tmp,ERROR);
2650 else ret = SAFE_APPEND (d,stream,mailbox + (s - tmp),af,data);
2652 else if ((d = mail_valid (stream,mailbox,NIL)) != NULL)
2653 ret = SAFE_APPEND (d,stream,mailbox,af,data);
2654 /* No driver, try for TRYCREATE if no stream. Note that we use the
2655 * createProto here, not the appendProto, since the dummy driver already
2656 * took care of the appendProto case. Otherwise, if appendProto is set to
2657 * NIL, we won't get a TRYCREATE.
2659 else if (!stream && (stream = default_proto (NIL)) && stream->dtb &&
2660 SAFE_APPEND (stream->dtb,stream,mailbox,af,data))
2661 /* timing race? */
2662 MM_NOTIFY (stream,"Append validity confusion",WARN);
2663 /* generate error message */
2664 else mail_valid (stream,mailbox,"append to mailbox");
2665 return ret;
2668 /* Mail garbage collect stream
2669 * Accepts: mail stream
2670 * garbage collection flags
2673 void mail_gc (MAILSTREAM *stream,long gcflags)
2675 MESSAGECACHE *elt;
2676 unsigned long i;
2677 /* do the driver's action first */
2678 if (stream->dtb && stream->dtb->gc) (*stream->dtb->gc) (stream,gcflags);
2679 stream->msgno = 0; /* nothing cached now */
2680 if (gcflags & GC_ENV) { /* garbage collect envelopes? */
2681 if (stream->env) mail_free_envelope (&stream->env);
2682 if (stream->body) mail_free_body (&stream->body);
2684 if (gcflags & GC_TEXTS) { /* free texts */
2685 if (stream->text.data) fs_give ((void **) &stream->text.data);
2686 stream->text.size = 0;
2688 /* garbage collect per-message stuff */
2689 for (i = 1; i <= stream->nmsgs; i++)
2690 if ((elt = (MESSAGECACHE *) (*mailcache) (stream,i,CH_ELT)) != NULL)
2691 mail_gc_msg (&elt->private.msg,gcflags);
2695 /* Mail garbage collect message
2696 * Accepts: message structure
2697 * garbage collection flags
2700 void mail_gc_msg (MESSAGE *msg,long gcflags)
2702 if (gcflags & GC_ENV) { /* garbage collect envelopes? */
2703 mail_free_envelope (&msg->env);
2704 mail_free_body (&msg->body);
2706 if (gcflags & GC_TEXTS) { /* garbage collect texts */
2707 if (msg->full.text.data) fs_give ((void **) &msg->full.text.data);
2708 if (msg->header.text.data) {
2709 mail_free_stringlist (&msg->lines);
2710 fs_give ((void **) &msg->header.text.data);
2712 if (msg->text.text.data) fs_give ((void **) &msg->text.text.data);
2713 /* now GC all body components */
2714 if (msg->body) mail_gc_body (msg->body);
2718 /* Mail garbage collect texts in BODY structure
2719 * Accepts: BODY structure
2722 void mail_gc_body (BODY *body)
2724 PART *part;
2725 switch (body->type) { /* free contents */
2726 case TYPEMULTIPART: /* multiple part */
2727 for (part = body->nested.part; part; part = part->next)
2728 mail_gc_body (&part->body);
2729 break;
2730 case TYPEMESSAGE: /* encapsulated message */
2731 if (body->subtype && !strcmp (body->subtype,"RFC822")) {
2732 mail_free_stringlist (&body->nested.msg->lines);
2733 mail_gc_msg (body->nested.msg,GC_TEXTS);
2735 break;
2736 default:
2737 break;
2739 if (body->mime.text.data) fs_give ((void **) &body->mime.text.data);
2740 if (body->contents.text.data) fs_give ((void **) &body->contents.text.data);
2742 /* Mail get body section
2743 * Accepts: body of message
2744 * section specifier
2745 * Returns: pointer to body at given section
2748 BODY *mail_body_section (BODY *b, unsigned char *section)
2750 PART *pt;
2751 unsigned long i;
2752 /* make sure have a body */
2753 if (section && *section && b)
2754 while (*section) { /* find desired section */
2755 if (isdigit (*section)) { /* get section specifier */
2756 /* make sure what follows is valid */
2757 if (!(i = strtoul (section,(char **) &section,10)) ||
2758 (*section && ((*section++ != '.') || !*section))) return NIL;
2759 /* multipart content? */
2760 if (b->type == TYPEMULTIPART) {
2761 /* yes, find desired part */
2762 if ((pt = b->nested.part) != NULL) while (--i && (pt = pt->next));
2763 if (!pt) return NIL; /* bad specifier */
2764 b = &pt->body; /* note new body */
2766 /* otherwise must be section 1 */
2767 else if (i != 1) return NIL;
2768 /* need to go down further? */
2769 if (*section) switch (b->type) {
2770 case TYPEMULTIPART: /* multipart */
2771 break;
2772 case TYPEMESSAGE: /* embedded message */
2773 if (!strcmp (b->subtype,"RFC822")) {
2774 b = b->nested.msg->body;
2775 break;
2777 default: /* bogus subpart specification */
2778 return NIL;
2781 else return NIL; /* unknown section specifier */
2783 return b;
2786 /* Mail get body part
2787 * Accepts: mail stream
2788 * message number
2789 * section specifier
2790 * Returns: pointer to body
2793 BODY *mail_body (MAILSTREAM *stream,unsigned long msgno,unsigned char *section)
2795 BODY *b = NIL;
2796 PART *pt;
2797 unsigned long i;
2798 /* make sure have a body */
2799 if (section && *section && mail_fetchstructure (stream,msgno,&b) && b)
2800 return mail_body_section(b, section);
2801 return b;
2804 /* Mail output date from elt fields
2805 * Accepts: character string to write into
2806 * elt to get data data from
2807 * Returns: the character string
2810 const char *days[] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
2812 const char *months[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
2813 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
2815 char *mail_date (char *string,MESSAGECACHE *elt)
2817 sprintf (string,"%2d-%s-%d %02d:%02d:%02d %c%02d%02d",
2818 elt->day ? elt->day : 1,
2819 months[elt->month ? (elt->month - 1) : 0],
2820 elt->year + BASEYEAR,elt->hours,elt->minutes,elt->seconds,
2821 elt->zoccident ? '-' : '+',elt->zhours,elt->zminutes);
2822 return string;
2826 /* Mail output extended-ctime format date from elt fields
2827 * Accepts: character string to write into
2828 * elt to get data data from
2829 * Returns: the character string
2832 char *mail_cdate (char *string,MESSAGECACHE *elt)
2834 char *fmt = "%s %s %2d %02d:%02d:%02d %4d %s%02d%02d\n";
2835 int d = elt->day ? elt->day : 1;
2836 int m = elt->month ? (elt->month - 1) : 0;
2837 int y = elt->year + BASEYEAR;
2838 const char *s = months[m];
2839 if (m < 2) { /* if before March, */
2840 m += 10; /* January = month 10 of previous year */
2841 y--;
2843 else m -= 2; /* March is month 0 */
2844 sprintf (string,fmt,days[(int) (d + 2 + ((7 + 31 * m) / 12)
2845 #ifndef USEJULIANCALENDAR
2846 #ifndef USEORTHODOXCALENDAR /* Gregorian calendar */
2847 + (y / 400)
2848 #ifdef Y4KBUGFIX
2849 - (y / 4000)
2850 #endif
2851 #else /* Orthodox calendar */
2852 + (2 * (y / 900)) + ((y % 900) >= 200)
2853 + ((y % 900) >= 600)
2854 #endif
2855 - (y / 100)
2856 #endif
2857 + y + (y / 4)) % 7],
2858 s,d,elt->hours,elt->minutes,elt->seconds,elt->year + BASEYEAR,
2859 elt->zoccident ? "-" : "+",elt->zhours,elt->zminutes);
2860 return string;
2863 /* Mail parse date into elt fields
2864 * Accepts: elt to write into
2865 * date string to parse
2866 * Returns: T if parse successful, else NIL
2867 * This routine parses dates as follows:
2868 * . leading three alphas followed by comma and space are ignored
2869 * . date accepted in format: mm/dd/yy, mm/dd/yyyy, dd-mmm-yy, dd-mmm-yyyy,
2870 * dd mmm yy, dd mmm yyyy, yyyy-mm-dd, yyyymmdd
2871 * . two and three digit years interpreted according to RFC 2822 rules
2872 * . mandatory end of string if yyyy-mm-dd or yyyymmdd; otherwise optional
2873 * space followed by time:
2874 * . time accepted in format hh:mm:ss or hh:mm
2875 * . end of string accepted
2876 * . timezone accepted: hyphen followed by symbolic timezone, or space
2877 * followed by signed numeric timezone or symbolic timezone
2878 * Examples of normal input:
2879 * . IMAP date-only (SEARCH):
2880 * dd-mmm-yyyy
2881 * . IMAP date-time (INTERNALDATE):
2882 * dd-mmm-yyyy hh:mm:ss +zzzz
2883 * . RFC-822:
2884 * www, dd mmm yy hh:mm:ss zzz
2885 * . RFC-2822:
2886 * www, dd mmm yyyy hh:mm:ss +zzzz
2889 long mail_parse_date (MESSAGECACHE *elt,unsigned char *s)
2891 unsigned long d,m,y;
2892 int mi,ms;
2893 struct tm *t;
2894 time_t tn;
2895 char tmp[MAILTMPLEN];
2896 static unsigned long maxyear = 0;
2897 if (!maxyear) { /* know the end of time yet? */
2898 MESSAGECACHE tmpelt;
2899 memset (&tmpelt,0xff,sizeof (MESSAGECACHE));
2900 maxyear = BASEYEAR + tmpelt.year;
2902 /* clear elt */
2903 elt->zoccident = elt->zhours = elt->zminutes =
2904 elt->hours = elt->minutes = elt->seconds =
2905 elt->day = elt->month = elt->year = 0;
2906 /* make a writeable uppercase copy */
2907 if (s && *s && (strlen (s) < (size_t)MAILTMPLEN)) s = ucase (strcpy (tmp,s));
2908 else return NIL;
2909 /* skip over possible day of week */
2910 if (isalpha (*s) && isalpha (s[1]) && isalpha (s[2]) && (s[3] == ',') &&
2911 (s[4] == ' ')) s += 5;
2912 while (*s == ' ') s++; /* parse first number (probable month) */
2913 if (!(m = strtoul (s,(char **) &s,10))) return NIL;
2915 switch (*s) { /* different parse based on delimiter */
2916 case '/': /* mm/dd/yy format */
2917 if (isdigit (*++s) && (d = strtoul (s,(char **) &s,10)) &&
2918 (*s == '/') && isdigit (*++s)) {
2919 y = strtoul (s,(char **) &s,10);
2920 if (*s == '\0') break; /* must end here */
2922 return NIL; /* bogon */
2923 case ' ': /* dd mmm yy format */
2924 while (s[1] == ' ') s++; /* slurp extra whitespace */
2925 case '-':
2926 if (isdigit (s[1])) { /* possible ISO 8601 date format? */
2927 y = m; /* yes, first number is year */
2928 /* get month and day */
2929 if ((m = strtoul (s+1,(char **) &s,10)) && (*s++ == '-') &&
2930 (d = strtoul (s,(char **) &s,10)) && !*s) break;
2931 return NIL; /* syntax error or time present */
2933 d = m; /* dd-mmm-yy[yy], so first number is a day */
2934 /* make sure string long enough! */
2935 if (strlen (s) < (size_t) 5) return NIL;
2936 /* Some compilers don't allow `<<' and/or longs in case statements. */
2937 /* slurp up the month string */
2938 ms = ((s[1] - 'A') * 1024) + ((s[2] - 'A') * 32) + (s[3] - 'A');
2939 switch (ms) { /* determine the month */
2940 case (('J'-'A') * 1024) + (('A'-'A') * 32) + ('N'-'A'): m = 1; break;
2941 case (('F'-'A') * 1024) + (('E'-'A') * 32) + ('B'-'A'): m = 2; break;
2942 case (('M'-'A') * 1024) + (('A'-'A') * 32) + ('R'-'A'): m = 3; break;
2943 case (('A'-'A') * 1024) + (('P'-'A') * 32) + ('R'-'A'): m = 4; break;
2944 case (('M'-'A') * 1024) + (('A'-'A') * 32) + ('Y'-'A'): m = 5; break;
2945 case (('J'-'A') * 1024) + (('U'-'A') * 32) + ('N'-'A'): m = 6; break;
2946 case (('J'-'A') * 1024) + (('U'-'A') * 32) + ('L'-'A'): m = 7; break;
2947 case (('A'-'A') * 1024) + (('U'-'A') * 32) + ('G'-'A'): m = 8; break;
2948 case (('S'-'A') * 1024) + (('E'-'A') * 32) + ('P'-'A'): m = 9; break;
2949 case (('O'-'A') * 1024) + (('C'-'A') * 32) + ('T'-'A'): m = 10; break;
2950 case (('N'-'A') * 1024) + (('O'-'A') * 32) + ('V'-'A'): m = 11; break;
2951 case (('D'-'A') * 1024) + (('E'-'A') * 32) + ('C'-'A'): m = 12; break;
2952 default: return NIL; /* unknown month */
2954 if (s[4] == *s) s += 5; /* advance to year */
2955 else { /* first three were OK, possibly full name */
2956 mi = *s; /* note delimiter, skip alphas */
2957 for (s += 4; isalpha (*s); s++);
2958 /* error if delimiter not here */
2959 if (mi != *s++) return NIL;
2961 while (*s == ' ') s++; /* parse year */
2962 if (isdigit (*s)) { /* must be a digit here */
2963 y = strtoul (s,(char **) &s,10);
2964 if (*s == '\0' || *s == ' ') break;
2966 case '\0': /* ISO 8601 compact date */
2967 if (m < (BASEYEAR * 10000)) return NIL;
2968 y = m / 10000; /* get year */
2969 d = (m %= 10000) % 100; /* get day */
2970 m /= 100; /* and month */
2971 break;
2972 default:
2973 return NIL; /* unknown date format */
2976 /* minimal validity check of date */
2977 if ((d > 31) || (m > 12)) return NIL;
2978 if (y < 49) y += 2000; /* RFC 2282 rules for two digit years 00-49 */
2979 else if (y < 999) y += 1900; /* 2-digit years 50-99 and 3-digit years */
2980 /* reject prehistoric and far future years */
2981 if ((y < BASEYEAR) || (y > maxyear)) return NIL;
2982 /* set values in elt */
2983 elt->day = d; elt->month = m; elt->year = y - BASEYEAR;
2984 ms = '\0'; /* initially no time zone string */
2985 if (*s) { /* time specification present? */
2986 /* parse time */
2987 d = strtoul (s+1,(char **) &s,10);
2988 if (*s != ':') return NIL;
2989 m = strtoul (++s,(char **) &s,10);
2990 y = (*s == ':') ? strtoul (++s,(char **) &s,10) : 0;
2991 /* validity check time */
2992 if ((d > 23) || (m > 59) || (y > 60)) return NIL;
2993 /* set values in elt */
2994 elt->hours = d; elt->minutes = m; elt->seconds = y;
2995 switch (*s) { /* time zone specifier? */
2996 case ' ': /* numeric time zone */
2997 while (s[1] == ' ') s++; /* slurp extra whitespace */
2998 if (!isalpha (s[1])) { /* treat as '-' case if alphabetic */
2999 /* test for sign character */
3000 if ((elt->zoccident = (*++s == '-')) || (*s == '+')) s++;
3001 /* validate proper timezone */
3002 if (isdigit(*s) && isdigit(s[1]) && isdigit(s[2]) && (s[2] < '6') &&
3003 isdigit(s[3])) {
3004 elt->zhours = (*s - '0') * 10 + (s[1] - '0');
3005 elt->zminutes = (s[2] - '0') * 10 + (s[3] - '0');
3007 return T; /* all done! */
3009 /* falls through */
3010 case '-': /* symbolic time zone */
3011 if (!(ms = *++s)) ms = 'Z';
3012 else if (*++s) { /* multi-character? */
3013 ms -= 'A'; ms *= 1024; /* yes, make compressed three-byte form */
3014 ms += ((*s++ - 'A') * 32);
3015 if (*s) ms += *s++ - 'A';
3016 if (*s) ms = '\0'; /* more than three characters */
3018 default: /* ignore anything else */
3019 break;
3023 /* This is not intended to be a comprehensive list of all possible
3024 * timezone strings. Such a list would be impractical. Rather, this
3025 * listing is intended to incorporate all military, North American, and
3026 * a few special cases such as Japan and the major European zone names,
3027 * such as what might be expected to be found in a Tenex format mailbox
3028 * and spewed from an IMAP server. The trend is to migrate to numeric
3029 * timezones which lack the flavor but also the ambiguity of the names.
3031 * RFC-822 only recognizes UT, GMT, 1-letter military timezones, and the
3032 * 4 CONUS timezones and their summer time variants. [Sorry, Canadian
3033 * Atlantic Provinces, Alaska, and Hawaii.]
3035 switch (ms) { /* determine the timezone */
3036 /* Universal */
3037 case (('U'-'A')*1024)+(('T'-'A')*32):
3038 #ifndef STRICT_RFC822_TIMEZONES
3039 case (('U'-'A')*1024)+(('T'-'A')*32)+'C'-'A':
3040 #endif
3041 /* Greenwich */
3042 case (('G'-'A')*1024)+(('M'-'A')*32)+'T'-'A':
3043 case 'Z': elt->zhours = 0; break;
3045 /* oriental (from Greenwich) timezones */
3046 #ifndef STRICT_RFC822_TIMEZONES
3047 /* Middle Europe */
3048 case (('M'-'A')*1024)+(('E'-'A')*32)+'T'-'A':
3049 #endif
3050 #ifdef BRITISH_SUMMER_TIME
3051 /* British Summer */
3052 case (('B'-'A')*1024)+(('S'-'A')*32)+'T'-'A':
3053 #endif
3054 case 'A': elt->zhours = 1; break;
3055 #ifndef STRICT_RFC822_TIMEZONES
3056 /* Eastern Europe */
3057 case (('E'-'A')*1024)+(('E'-'A')*32)+'T'-'A':
3058 #endif
3059 case 'B': elt->zhours = 2; break;
3060 case 'C': elt->zhours = 3; break;
3061 case 'D': elt->zhours = 4; break;
3062 case 'E': elt->zhours = 5; break;
3063 case 'F': elt->zhours = 6; break;
3064 case 'G': elt->zhours = 7; break;
3065 case 'H': elt->zhours = 8; break;
3066 #ifndef STRICT_RFC822_TIMEZONES
3067 /* Japan */
3068 case (('J'-'A')*1024)+(('S'-'A')*32)+'T'-'A':
3069 #endif
3070 case 'I': elt->zhours = 9; break;
3071 case 'K': elt->zhours = 10; break;
3072 case 'L': elt->zhours = 11; break;
3073 case 'M': elt->zhours = 12; break;
3075 /* occidental (from Greenwich) timezones */
3076 case 'N': elt->zoccident = 1; elt->zhours = 1; break;
3077 case 'O': elt->zoccident = 1; elt->zhours = 2; break;
3078 #ifndef STRICT_RFC822_TIMEZONES
3079 case (('A'-'A')*1024)+(('D'-'A')*32)+'T'-'A':
3080 #endif
3081 case 'P': elt->zoccident = 1; elt->zhours = 3; break;
3082 #ifdef NEWFOUNDLAND_STANDARD_TIME
3083 /* Newfoundland */
3084 case (('N'-'A')*1024)+(('S'-'A')*32)+'T'-'A':
3085 elt->zoccident = 1; elt->zhours = 3; elt->zminutes = 30; break;
3086 #endif
3087 #ifndef STRICT_RFC822_TIMEZONES
3088 /* Atlantic */
3089 case (('A'-'A')*1024)+(('S'-'A')*32)+'T'-'A':
3090 #endif
3091 /* CONUS */
3092 case (('E'-'A')*1024)+(('D'-'A')*32)+'T'-'A':
3093 case 'Q': elt->zoccident = 1; elt->zhours = 4; break;
3094 /* Eastern */
3095 case (('E'-'A')*1024)+(('S'-'A')*32)+'T'-'A':
3096 case (('C'-'A')*1024)+(('D'-'A')*32)+'T'-'A':
3097 case 'R': elt->zoccident = 1; elt->zhours = 5; break;
3098 /* Central */
3099 case (('C'-'A')*1024)+(('S'-'A')*32)+'T'-'A':
3100 case (('M'-'A')*1024)+(('D'-'A')*32)+'T'-'A':
3101 case 'S': elt->zoccident = 1; elt->zhours = 6; break;
3102 /* Mountain */
3103 case (('M'-'A')*1024)+(('S'-'A')*32)+'T'-'A':
3104 case (('P'-'A')*1024)+(('D'-'A')*32)+'T'-'A':
3105 case 'T': elt->zoccident = 1; elt->zhours = 7; break;
3106 /* Pacific */
3107 case (('P'-'A')*1024)+(('S'-'A')*32)+'T'-'A':
3108 #ifndef STRICT_RFC822_TIMEZONES
3109 case (('Y'-'A')*1024)+(('D'-'A')*32)+'T'-'A':
3110 #endif
3111 case 'U': elt->zoccident = 1; elt->zhours = 8; break;
3112 #ifndef STRICT_RFC822_TIMEZONES
3113 /* Yukon */
3114 case (('Y'-'A')*1024)+(('S'-'A')*32)+'T'-'A':
3115 #endif
3116 case 'V': elt->zoccident = 1; elt->zhours = 9; break;
3117 #ifndef STRICT_RFC822_TIMEZONES
3118 /* Hawaii */
3119 case (('H'-'A')*1024)+(('S'-'A')*32)+'T'-'A':
3120 #endif
3121 case 'W': elt->zoccident = 1; elt->zhours = 10; break;
3122 /* Nome/Bering/Samoa */
3123 #ifdef NOME_STANDARD_TIME
3124 case (('N'-'A')*1024)+(('S'-'A')*32)+'T'-'A':
3125 #endif
3126 #ifdef BERING_STANDARD_TIME
3127 case (('B'-'A')*1024)+(('S'-'A')*32)+'T'-'A':
3128 #endif
3129 #ifdef SAMOA_STANDARD_TIME
3130 case (('S'-'A')*1024)+(('S'-'A')*32)+'T'-'A':
3131 #endif
3132 case 'X': elt->zoccident = 1; elt->zhours = 11; break;
3133 case 'Y': elt->zoccident = 1; elt->zhours = 12; break;
3135 default: /* unknown time zones treated as local */
3136 tn = time (0); /* time now... */
3137 t = localtime (&tn); /* get local minutes since midnight */
3138 mi = t->tm_hour * 60 + t->tm_min;
3139 ms = t->tm_yday; /* note Julian day */
3140 if ((t = gmtime (&tn)) != NULL) { /* minus UTC minutes since midnight */
3141 mi -= t->tm_hour * 60 + t->tm_min;
3142 /* ms can be one of:
3143 * 36x local time is December 31, UTC is January 1, offset -24 hours
3144 * 1 local time is 1 day ahead of UTC, offset +24 hours
3145 * 0 local time is same day as UTC, no offset
3146 * -1 local time is 1 day behind UTC, offset -24 hours
3147 * -36x local time is January 1, UTC is December 31, offset +24 hours
3149 if (ms -= t->tm_yday) /* correct offset if different Julian day */
3150 mi += ((ms < 0) == (abs (ms) == 1)) ? -24*60 : 24*60;
3151 if (mi < 0) { /* occidental? */
3152 mi = abs (mi); /* yup, make positive number */
3153 elt->zoccident = 1; /* and note west of UTC */
3155 elt->zhours = mi / 60; /* now break into hours and minutes */
3156 elt->zminutes = mi % 60;
3158 break;
3160 return T;
3163 /* Mail n messages exist
3164 * Accepts: mail stream
3165 * number of messages
3168 void mail_exists (MAILSTREAM *stream,unsigned long nmsgs)
3170 char tmp[MAILTMPLEN];
3171 if (nmsgs > MAXMESSAGES) {
3172 sprintf (tmp,"Mailbox has more messages (%lu) exist than maximum (%lu)",
3173 nmsgs,MAXMESSAGES);
3174 mm_log (tmp,ERROR);
3175 nmsgs = MAXMESSAGES; /* cap to maximum */
3176 /* probably will crash in mail_elt() soon enough... */
3178 /* make sure cache is large enough */
3179 (*mailcache) (stream,nmsgs,CH_SIZE);
3180 stream->nmsgs = nmsgs; /* update stream status */
3181 /* notify main program of change */
3182 if (!stream->silent) MM_EXISTS (stream,nmsgs);
3186 /* Mail n messages are recent
3187 * Accepts: mail stream
3188 * number of recent messages
3191 void mail_recent (MAILSTREAM *stream,unsigned long recent)
3193 char tmp[MAILTMPLEN];
3194 if (recent <= stream->nmsgs) stream->recent = recent;
3195 else {
3196 sprintf (tmp,"Non-existent recent message(s) %lu, nmsgs=%lu",
3197 recent,stream->nmsgs);
3198 mm_log (tmp,ERROR);
3203 /* Mail message n is expunged
3204 * Accepts: mail stream
3205 * message #
3208 void mail_expunged (MAILSTREAM *stream,unsigned long msgno)
3210 char tmp[MAILTMPLEN];
3211 MESSAGECACHE *elt;
3212 if (msgno > stream->nmsgs) {
3213 sprintf (tmp,"Expunge of non-existent message %lu, nmsgs=%lu",
3214 msgno,stream->nmsgs);
3215 mm_log (tmp,ERROR);
3217 else {
3218 elt = (MESSAGECACHE *) (*mailcache) (stream,msgno,CH_ELT);
3219 /* notify main program of change */
3220 if (!stream->silent) MM_EXPUNGED (stream,msgno);
3221 if (elt) { /* if an element is there */
3222 elt->msgno = 0; /* invalidate its message number and free */
3223 (*mailcache) (stream,msgno,CH_FREE);
3224 (*mailcache) (stream,msgno,CH_FREESORTCACHE);
3226 /* expunge the slot */
3227 (*mailcache) (stream,msgno,CH_EXPUNGE);
3228 --stream->nmsgs; /* update stream status */
3229 if (stream->msgno) { /* have stream pointers? */
3230 /* make sure the short cache is nuked */
3231 if (stream->scache) mail_gc (stream,GC_ENV | GC_TEXTS);
3232 else stream->msgno = 0; /* make sure invalidated in any case */
3237 /* Mail stream status routines */
3240 /* Mail lock stream
3241 * Accepts: mail stream
3244 void mail_lock (MAILSTREAM *stream)
3246 if (stream->lock) {
3247 char tmp[MAILTMPLEN];
3248 sprintf (tmp,"Lock when already locked, mbx=%.80s",
3249 stream->mailbox ? stream->mailbox : "???");
3250 fatal (tmp);
3252 else stream->lock = T; /* lock stream */
3256 /* Mail unlock stream
3257 * Accepts: mail stream
3260 void mail_unlock (MAILSTREAM *stream)
3262 if (!stream->lock) fatal ("Unlock when not locked");
3263 else stream->lock = NIL; /* unlock stream */
3267 /* Mail turn on debugging telemetry
3268 * Accepts: mail stream
3271 void mail_debug (MAILSTREAM *stream)
3273 stream->debug = T; /* turn on debugging telemetry */
3274 if (stream->dtb) (*stream->dtb->parameters) (ENABLE_DEBUG,stream);
3278 /* Mail turn off debugging telemetry
3279 * Accepts: mail stream
3282 void mail_nodebug (MAILSTREAM *stream)
3284 stream->debug = NIL; /* turn off debugging telemetry */
3285 if (stream->dtb) (*stream->dtb->parameters) (DISABLE_DEBUG,stream);
3289 /* Mail log to debugging telemetry
3290 * Accepts: message
3291 * flag that data is "sensitive"
3294 void mail_dlog (char *string,long flag)
3296 mm_dlog ((debugsensitive || !flag) ? string : "<suppressed>");
3299 /* Mail parse UID sequence
3300 * Accepts: mail stream
3301 * sequence to parse
3302 * Returns: T if parse successful, else NIL
3305 long mail_uid_sequence (MAILSTREAM *stream,unsigned char *sequence)
3307 unsigned long i,j,k,x,y;
3308 for (i = 1; i <= stream->nmsgs; i++) mail_elt (stream,i)->sequence = NIL;
3309 while (sequence && *sequence){/* while there is something to parse */
3310 if (*sequence == '*') { /* maximum message */
3311 i = stream->nmsgs ? mail_uid (stream,stream->nmsgs) : stream->uid_last;
3312 sequence++; /* skip past * */
3314 /* parse and validate message number */
3315 /* parse and validate message number */
3316 else if (!isdigit (*sequence)) {
3317 MM_LOG ("Syntax error in sequence",ERROR);
3318 return NIL;
3320 else if (!(i = strtoul (sequence,(char **) &sequence,10))) {
3321 MM_LOG ("UID may not be zero",ERROR);
3322 return NIL;
3324 switch (*sequence) { /* see what the delimiter is */
3325 case ':': /* sequence range */
3326 if (*++sequence == '*') { /* maximum message */
3327 j = stream->nmsgs ? mail_uid (stream,stream->nmsgs) : stream->uid_last;
3328 sequence++; /* skip past * */
3330 /* parse end of range */
3331 else if (!(j = strtoul (sequence,(char **) &sequence,10))) {
3332 MM_LOG ("UID sequence range invalid",ERROR);
3333 return NIL;
3335 if (*sequence && *sequence++ != ',') {
3336 MM_LOG ("UID sequence range syntax error",ERROR);
3337 return NIL;
3339 if (i > j) { /* swap the range if backwards */
3340 x = i; i = j; j = x;
3342 x = mail_msgno (stream,i);/* get msgnos */
3343 y = mail_msgno (stream,j);/* for both UIDS (don't && it) */
3344 /* easy if both UIDs valid */
3345 if (x && y) while (x <= y) mail_elt (stream,x++)->sequence = T;
3346 /* start UID valid, end is not */
3347 else if (x) while ((x <= stream->nmsgs) && (mail_uid (stream,x) <= j))
3348 mail_elt (stream,x++)->sequence = T;
3349 /* end UID valid, start is not */
3350 else if (y) for (x = 1; x <= y; x++) {
3351 if (mail_uid (stream,x) >= i) mail_elt (stream,x)->sequence = T;
3353 /* neither is valid, ugh */
3354 else for (x = 1; x <= stream->nmsgs; x++)
3355 if (((k = mail_uid (stream,x)) >= i) && (k <= j))
3356 mail_elt (stream,x)->sequence = T;
3357 break;
3358 case ',': /* single message */
3359 ++sequence; /* skip the delimiter, fall into end case */
3360 case '\0': /* end of sequence, mark this message */
3361 if ((x = mail_msgno (stream,i)) != 0L) mail_elt (stream,x)->sequence = T;
3362 break;
3363 default: /* anything else is a syntax error! */
3364 MM_LOG ("UID sequence syntax error",ERROR);
3365 return NIL;
3368 return T; /* successfully parsed sequence */
3371 /* Mail see if line list matches that in cache
3372 * Accepts: candidate line list
3373 * cached line list
3374 * matching flags
3375 * Returns: T if match, NIL if no match
3378 long mail_match_lines (STRINGLIST *lines,STRINGLIST *msglines,long flags)
3380 unsigned long i;
3381 unsigned char *s,*t;
3382 STRINGLIST *m;
3383 if (!msglines) return T; /* full header is in cache */
3384 /* need full header but filtered in cache */
3385 if ((flags & FT_NOT) || !lines) return NIL;
3386 do { /* make sure all present & accounted for */
3387 for (m = msglines; m; m = m->next) if (lines->text.size == m->text.size) {
3388 for (s = lines->text.data,t = m->text.data,i = lines->text.size;
3389 i && !compare_uchar (*s,*t); s++,t++,i--);
3390 if (!i) break; /* this line matches */
3392 if (!m) return NIL; /* didn't find in the list */
3394 while ((lines = lines->next) != NULL);
3395 return T; /* all lines found */
3398 /* Mail filter text by header lines
3399 * Accepts: text to filter, with trailing null
3400 * length of text
3401 * list of lines
3402 * fetch flags
3403 * Returns: new text size, text overwritten
3406 unsigned long mail_filter (char *text,unsigned long len,STRINGLIST *lines,
3407 long flags)
3409 STRINGLIST *hdrs;
3410 int notfound;
3411 unsigned long i;
3412 char c,*s,*e,*t,tmp[MAILTMPLEN];
3413 char *src = text;
3414 char *dst = src;
3415 char *end = text + len;
3416 text[len] = '\012'; /* guard against running off buffer */
3417 while (src < end) { /* process header */
3418 /* slurp header line name */
3419 for (s = src,e = s + MAILTMPLEN - 1,e = (e < end ? e : end),t = tmp;
3420 (s < e) && ((c = (*s ? *s : (*s = ' '))) != ':') &&
3421 ((c > ' ') ||
3422 ((c != ' ') && (c != '\t') && (c != '\015') && (c != '\012')));
3423 *t++ = *s++);
3424 *t = '\0'; /* tie off */
3425 notfound = T; /* not found yet */
3426 if ((i = t - tmp) != 0L) /* see if found in header */
3427 for (hdrs = lines; hdrs && notfound; hdrs = hdrs->next)
3428 if ((hdrs->text.size == i) && !compare_csizedtext (tmp,&hdrs->text))
3429 notfound = NIL;
3430 /* skip header line if not wanted */
3431 if (i && ((flags & FT_NOT) ? !notfound : notfound))
3432 while (((*src++ != '\012') && (*src++ != '\012') && (*src++ != '\012') &&
3433 (*src++ != '\012') && (*src++ != '\012') && (*src++ != '\012') &&
3434 (*src++ != '\012') && (*src++ != '\012') && (*src++ != '\012') &&
3435 (*src++ != '\012')) ||
3436 ((src < end) && ((*src == ' ') || (*src == '\t'))));
3437 else if (src == dst) { /* copy to self */
3438 while (((*src++ != '\012') && (*src++ != '\012') && (*src++ != '\012') &&
3439 (*src++ != '\012') && (*src++ != '\012') && (*src++ != '\012') &&
3440 (*src++ != '\012') && (*src++ != '\012') && (*src++ != '\012') &&
3441 (*src++ != '\012')) ||
3442 ((src < end) && ((*src == ' ') || (*src == '\t'))));
3443 dst = src; /* update destination */
3445 else { /* copy line and any continuation line */
3446 while ((((*dst++ = *src++) != '\012') && ((*dst++ = *src++) != '\012') &&
3447 ((*dst++ = *src++) != '\012') && ((*dst++ = *src++) != '\012') &&
3448 ((*dst++ = *src++) != '\012') && ((*dst++ = *src++) != '\012') &&
3449 ((*dst++ = *src++) != '\012') && ((*dst++ = *src++) != '\012') &&
3450 ((*dst++ = *src++) != '\012') && ((*dst++ = *src++) != '\012'))||
3451 ((src < end) && ((*src == ' ') || (*src == '\t'))));
3452 /* in case hit the guard LF */
3453 if (src > end) dst -= (src - end);
3456 *dst = '\0'; /* tie off destination */
3457 return dst - text;
3460 /* Local mail search message
3461 * Accepts: MAIL stream
3462 * message number
3463 * optional section specification
3464 * search program
3465 * Returns: T if found, NIL otherwise
3468 long mail_search_msg (MAILSTREAM *stream,unsigned long msgno,char *section,
3469 SEARCHPGM *pgm)
3471 unsigned short d;
3472 char tmp[MAILTMPLEN];
3473 MESSAGECACHE *elt = mail_elt (stream,msgno);
3474 SEARCHHEADER *hdr;
3475 SEARCHOR *or;
3476 SEARCHPGMLIST *not;
3477 unsigned long now = (unsigned long) time (0);
3478 if (pgm->msgno || pgm->uid) { /* message set searches */
3479 SEARCHSET *set;
3480 /* message sequences */
3481 if (pgm->msgno) { /* inside this message sequence set */
3482 for (set = pgm->msgno; set; set = set->next)
3483 if (set->last ? ((set->first <= set->last) ?
3484 ((msgno >= set->first) && (msgno <= set->last)) :
3485 ((msgno >= set->last) && (msgno <= set->first))) :
3486 msgno == set->first) break;
3487 if (!set) return NIL; /* not found within sequence */
3489 if (pgm->uid) { /* inside this unique identifier set */
3490 unsigned long uid = mail_uid (stream,msgno);
3491 for (set = pgm->uid; set; set = set->next)
3492 if (set->last ? ((set->first <= set->last) ?
3493 ((uid >= set->first) && (uid <= set->last)) :
3494 ((uid >= set->last) && (uid <= set->first))) :
3495 uid == set->first) break;
3496 if (!set) return NIL; /* not found within sequence */
3500 /* Fast data searches */
3501 /* need to fetch fast data? */
3502 if ((!elt->rfc822_size && (pgm->larger || pgm->smaller)) ||
3503 (!elt->year && (pgm->before || pgm->on || pgm->since ||
3504 pgm->older || pgm->younger)) ||
3505 (!elt->valid && (pgm->answered || pgm->unanswered ||
3506 pgm->deleted || pgm->undeleted ||
3507 pgm->draft || pgm->undraft ||
3508 pgm->flagged || pgm->unflagged ||
3509 pgm->recent || pgm->old ||
3510 pgm->seen || pgm->unseen ||
3511 pgm->keyword || pgm->unkeyword))) {
3512 unsigned long i;
3513 MESSAGECACHE *ielt;
3514 for (i = elt->msgno; /* find last unloaded message in range */
3515 (i < stream->nmsgs) && (ielt = mail_elt (stream,i+1)) &&
3516 ((!ielt->rfc822_size && (pgm->larger || pgm->smaller)) ||
3517 (!ielt->year && (pgm->before || pgm->on || pgm->since ||
3518 pgm->older || pgm->younger)) ||
3519 (!ielt->valid && (pgm->answered || pgm->unanswered ||
3520 pgm->deleted || pgm->undeleted ||
3521 pgm->draft || pgm->undraft ||
3522 pgm->flagged || pgm->unflagged ||
3523 pgm->recent || pgm->old ||
3524 pgm->seen || pgm->unseen ||
3525 pgm->keyword || pgm->unkeyword))); ++i);
3526 if (i == elt->msgno) sprintf (tmp,"%lu",elt->msgno);
3527 else sprintf (tmp,"%lu:%lu",elt->msgno,i);
3528 mail_fetch_fast (stream,tmp,NIL);
3530 /* size ranges */
3531 if ((pgm->larger && (elt->rfc822_size <= pgm->larger)) ||
3532 (pgm->smaller && (elt->rfc822_size >= pgm->smaller))) return NIL;
3533 /* message flags */
3534 if ((pgm->answered && !elt->answered) ||
3535 (pgm->unanswered && elt->answered) ||
3536 (pgm->deleted && !elt->deleted) ||
3537 (pgm->undeleted && elt->deleted) ||
3538 (pgm->draft && !elt->draft) ||
3539 (pgm->undraft && elt->draft) ||
3540 (pgm->flagged && !elt->flagged) ||
3541 (pgm->unflagged && elt->flagged) ||
3542 (pgm->recent && !elt->recent) ||
3543 (pgm->old && elt->recent) ||
3544 (pgm->seen && !elt->seen) ||
3545 (pgm->unseen && elt->seen)) return NIL;
3546 /* keywords */
3547 if ((pgm->keyword && !mail_search_keyword (stream,elt,pgm->keyword,LONGT)) ||
3548 (pgm->unkeyword && !mail_search_keyword (stream,elt,pgm->unkeyword,NIL)))
3549 return NIL;
3550 /* internal date ranges */
3551 if (pgm->before || pgm->on || pgm->since) {
3552 d = mail_shortdate (elt->year,elt->month,elt->day);
3553 if (pgm->before && (d >= pgm->before)) return NIL;
3554 if (pgm->on && (d != pgm->on)) return NIL;
3555 if (pgm->since && (d < pgm->since)) return NIL;
3557 if (pgm->older || pgm->younger) {
3558 unsigned long msgd = mail_longdate (elt);
3559 if (pgm->older && msgd > (now - pgm->older)) return NIL;
3560 if (pgm->younger && msgd < (now - pgm->younger)) return NIL;
3563 /* envelope searches */
3564 if (pgm->sentbefore || pgm->senton || pgm->sentsince ||
3565 pgm->bcc || pgm->cc || pgm->from || pgm->to || pgm->subject ||
3566 pgm->return_path || pgm->sender || pgm->reply_to || pgm->in_reply_to ||
3567 pgm->message_id || pgm->newsgroups || pgm->followup_to ||
3568 pgm->references) {
3569 ENVELOPE *env;
3570 MESSAGECACHE delt;
3571 if (section) { /* use body part envelope */
3572 BODY *body = mail_body (stream,msgno,section);
3573 env = (body && (body->type == TYPEMESSAGE) && body->subtype &&
3574 !strcmp (body->subtype,"RFC822")) ? body->nested.msg->env : NIL;
3576 else { /* use top level envelope if no section */
3577 if (pgm->header && !stream->scache && !(stream->dtb->flags & DR_LOCAL))
3578 mail_fetch_header(stream,msgno,NIL,NIL,NIL,FT_PEEK|FT_SEARCHLOOKAHEAD);
3579 env = mail_fetchenvelope (stream,msgno);
3581 if (!env) return NIL; /* no envelope obtained */
3582 /* sent date ranges */
3583 if ((pgm->sentbefore || pgm->senton || pgm->sentsince) &&
3584 (!mail_parse_date (&delt,env->date) ||
3585 !(d = mail_shortdate (delt.year,delt.month,delt.day)) ||
3586 (pgm->sentbefore && (d >= pgm->sentbefore)) ||
3587 (pgm->senton && (d != pgm->senton)) ||
3588 (pgm->sentsince && (d < pgm->sentsince)))) return NIL;
3589 /* search headers */
3590 if ((pgm->bcc && !mail_search_addr (env->bcc,pgm->bcc)) ||
3591 (pgm->cc && !mail_search_addr (env->cc,pgm->cc)) ||
3592 (pgm->from && !mail_search_addr (env->from,pgm->from)) ||
3593 (pgm->to && !mail_search_addr (env->to,pgm->to)) ||
3594 (pgm->subject && !mail_search_header_text (env->subject,pgm->subject)))
3595 return NIL;
3596 /* These criteria are not supported by IMAP and have to be emulated */
3597 if ((pgm->return_path &&
3598 !mail_search_addr (env->return_path,pgm->return_path)) ||
3599 (pgm->sender && !mail_search_addr (env->sender,pgm->sender)) ||
3600 (pgm->reply_to && !mail_search_addr (env->reply_to,pgm->reply_to)) ||
3601 (pgm->in_reply_to &&
3602 !mail_search_header_text (env->in_reply_to,pgm->in_reply_to)) ||
3603 (pgm->message_id &&
3604 !mail_search_header_text (env->message_id,pgm->message_id)) ||
3605 (pgm->newsgroups &&
3606 !mail_search_header_text (env->newsgroups,pgm->newsgroups)) ||
3607 (pgm->followup_to &&
3608 !mail_search_header_text (env->followup_to,pgm->followup_to)) ||
3609 (pgm->references &&
3610 !mail_search_header_text (env->references,pgm->references)))
3611 return NIL;
3614 /* search header lines */
3615 for (hdr = pgm->header; hdr; hdr = hdr->next) {
3616 char *t,*e,*v;
3617 SIZEDTEXT s;
3618 STRINGLIST sth,stc;
3619 sth.next = stc.next = NIL; /* only one at a time */
3620 sth.text.data = hdr->line.data;
3621 sth.text.size = hdr->line.size;
3622 /* get the header text */
3623 if ((t = mail_fetch_header (stream,msgno,NIL,&sth,&s.size,
3624 FT_INTERNAL | FT_PEEK |
3625 (section ? NIL : FT_SEARCHLOOKAHEAD))) &&
3626 strchr (t,':')) {
3627 if (hdr->text.size) { /* anything matches empty search string */
3628 /* non-empty, copy field data */
3629 s.data = (unsigned char *) fs_get (s.size + 1);
3630 /* for each line */
3631 for (v = (char *) s.data, e = t + s.size; t < e;) switch (*t) {
3632 default: /* non-continuation, skip leading field name */
3633 while ((t < e) && (*t++ != ':'));
3634 if ((t < e) && (*t == ':')) t++;
3635 case '\t': case ' ': /* copy field data */
3636 while ((t < e) && (*t != '\015') && (*t != '\012')) *v++ = *t++;
3637 *v++ = '\n'; /* tie off line */
3638 while (((*t == '\015') || (*t == '\012')) && (t < e)) t++;
3640 /* calculate true size */
3641 s.size = v - (char *) s.data;
3642 *v = '\0'; /* tie off results */
3643 stc.text.data = hdr->text.data;
3644 stc.text.size = hdr->text.size;
3645 /* search header */
3646 if (mail_search_header (&s,&stc)) fs_give ((void **) &s.data);
3647 else { /* search failed */
3648 fs_give ((void **) &s.data);
3649 return NIL;
3653 else return NIL; /* no matching header text */
3655 /* search strings */
3656 if ((pgm->text && !mail_search_text (stream,msgno,section,pgm->text,LONGT))||
3657 (pgm->body && !mail_search_text (stream,msgno,section,pgm->body,NIL)))
3658 return NIL;
3659 /* logical conditions */
3660 for (or = pgm->or; or; or = or->next)
3661 if (!(mail_search_msg (stream,msgno,section,or->first) ||
3662 mail_search_msg (stream,msgno,section,or->second))) return NIL;
3663 for (not = pgm->not; not; not = not->next)
3664 if (mail_search_msg (stream,msgno,section,not->pgm)) return NIL;
3665 return T;
3668 /* Mail search message header null-terminated text
3669 * Accepts: header text
3670 * strings to search
3671 * Returns: T if search found a match
3674 long mail_search_header_text (char *s,STRINGLIST *st)
3676 SIZEDTEXT h;
3677 /* have any text? */
3678 if ((h.data = (unsigned char *) s) != NULL) {
3679 h.size = strlen (s); /* yes, get its size */
3680 return mail_search_header (&h,st);
3682 return NIL;
3686 /* Mail search message header
3687 * Accepts: header as sized text
3688 * strings to search
3689 * Returns: T if search found a match
3692 long mail_search_header (SIZEDTEXT *hdr,STRINGLIST *st)
3694 SIZEDTEXT h;
3695 long ret = LONGT;
3696 /* make UTF-8 version of header */
3697 utf8_mime2text (hdr,&h,U8T_CANONICAL);
3698 while (h.size && ((h.data[h.size-1]=='\015') || (h.data[h.size-1]=='\012')))
3699 --h.size; /* slice off trailing newlines */
3700 do if (h.size ? /* search non-empty string */
3701 !ssearch (h.data,h.size,st->text.data,st->text.size) : st->text.size)
3702 ret = NIL;
3703 while (ret && (st = st->next));
3704 if (h.data != hdr->data) fs_give ((void **) &h.data);
3705 return ret;
3708 /* Mail search message body
3709 * Accepts: MAIL stream
3710 * message number
3711 * optional section specification
3712 * string list
3713 * flags
3714 * Returns: T if search found a match
3717 long mail_search_text (MAILSTREAM *stream,unsigned long msgno,char *section,
3718 STRINGLIST *st,long flags)
3720 BODY *body;
3721 long ret = NIL;
3722 STRINGLIST *s = mail_newstringlist ();
3723 mailgets_t omg = mailgets;
3724 if (stream->dtb->flags & DR_LOWMEM) mailgets = mail_search_gets;
3725 /* strings to search */
3726 for (stream->private.search.string = s; st;) {
3727 s->text.data = st->text.data;
3728 s->text.size = st->text.size;
3729 if ((st = st->next) != NULL) s = s->next = mail_newstringlist ();
3731 stream->private.search.text = NIL;
3732 if (flags) { /* want header? */
3733 SIZEDTEXT s,t;
3734 s.data = (unsigned char *)
3735 mail_fetch_header (stream,msgno,section,NIL,&s.size,FT_INTERNAL|FT_PEEK);
3736 utf8_mime2text (&s,&t,U8T_CANONICAL);
3737 ret = mail_search_string_work (&t,&stream->private.search.string);
3738 if (t.data != s.data) fs_give ((void **) &t.data);
3740 if (!ret) { /* still looking for match? */
3741 /* no section, get top-level body */
3742 if (!section) mail_fetchstructure (stream,msgno,&body);
3743 /* get body of nested message */
3744 else if ((body = mail_body (stream,msgno,section)) &&
3745 (body->type == TYPEMULTIPART) && body->subtype &&
3746 !strcmp (body->subtype,"RFC822")) body = body->nested.msg->body;
3747 if (body) ret = mail_search_body (stream,msgno,body,NIL,1,flags);
3749 mailgets = omg; /* restore former gets routine */
3750 /* clear searching */
3751 for (s = stream->private.search.string; s; s = s->next) s->text.data = NIL;
3752 mail_free_stringlist (&stream->private.search.string);
3753 stream->private.search.text = NIL;
3754 return ret;
3757 /* Mail search message body text parts
3758 * Accepts: MAIL stream
3759 * message number
3760 * current body pointer
3761 * hierarchical level prefix
3762 * position at current hierarchical level
3763 * string list
3764 * flags
3765 * Returns: T if search found a match
3768 long mail_search_body (MAILSTREAM *stream,unsigned long msgno,BODY *body,
3769 char *prefix,unsigned long section,long flags)
3771 long ret = NIL;
3772 unsigned long i;
3773 char *s,*t,sect[MAILTMPLEN];
3774 SIZEDTEXT st,h;
3775 PART *part;
3776 PARAMETER *param;
3777 if (prefix && (strlen (prefix) > (MAILTMPLEN - 20))) return NIL;
3778 sprintf (sect,"%s%lu",prefix ? prefix : "",section++);
3779 if (flags && prefix) { /* want to search MIME header too? */
3780 st.data = (unsigned char *) mail_fetch_mime (stream,msgno,sect,&st.size,
3781 FT_INTERNAL | FT_PEEK);
3782 if (stream->dtb->flags & DR_LOWMEM) ret = stream->private.search.result;
3783 else {
3784 /* make UTF-8 version of header */
3785 utf8_mime2text (&st,&h,U8T_CANONICAL);
3786 ret = mail_search_string_work (&h,&stream->private.search.string);
3787 if (h.data != st.data) fs_give ((void **) &h.data);
3790 if (!ret) switch (body->type) {
3791 case TYPEMULTIPART:
3792 /* extend prefix if not first time */
3793 s = prefix ? strcat (sect,".") : "";
3794 for (i = 1,part = body->nested.part; part && !ret; i++,part = part->next)
3795 ret = mail_search_body (stream,msgno,&part->body,s,i,flags);
3796 break;
3797 case TYPEMESSAGE:
3798 if (!strcmp (body->subtype,"RFC822")) {
3799 if (flags) { /* want to search nested message header? */
3800 st.data = (unsigned char *)
3801 mail_fetch_header (stream,msgno,sect,NIL,&st.size,
3802 FT_INTERNAL | FT_PEEK);
3803 if (stream->dtb->flags & DR_LOWMEM) ret =stream->private.search.result;
3804 else {
3805 /* make UTF-8 version of header */
3806 utf8_mime2text (&st,&h,U8T_CANONICAL);
3807 ret = mail_search_string_work (&h,&stream->private.search.string);
3808 if (h.data != st.data) fs_give ((void **) &h.data);
3811 if ((body = body->nested.msg->body) != NULL)
3812 ret = (body->type == TYPEMULTIPART) ?
3813 mail_search_body (stream,msgno,body,(prefix ? prefix : ""),
3814 section - 1,flags) :
3815 mail_search_body (stream,msgno,body,strcat (sect,"."),1,flags);
3816 break;
3818 /* non-MESSAGE/RFC822 falls into text case */
3820 case TYPETEXT:
3821 s = mail_fetch_body (stream,msgno,sect,&i,FT_INTERNAL | FT_PEEK);
3822 if (stream->dtb->flags & DR_LOWMEM) ret = stream->private.search.result;
3823 else {
3824 for (t = NIL,param = body->parameter; param && !t; param = param->next)
3825 if (!strcmp (param->attribute,"CHARSET")) t = param->value;
3826 switch (body->encoding) { /* what encoding? */
3827 case ENCBASE64:
3828 if ((st.data = (unsigned char *)
3829 rfc822_base64 ((unsigned char *) s,i,&st.size)) != NULL) {
3830 ret = mail_search_string (&st,t,&stream->private.search.string);
3831 fs_give ((void **) &st.data);
3833 break;
3834 case ENCQUOTEDPRINTABLE:
3835 if ((st.data = rfc822_qprint ((unsigned char *) s,i,&st.size)) != NULL) {
3836 ret = mail_search_string (&st,t,&stream->private.search.string);
3837 fs_give ((void **) &st.data);
3839 break;
3840 default:
3841 st.data = (unsigned char *) s;
3842 st.size = i;
3843 ret = mail_search_string (&st,t,&stream->private.search.string);
3844 break;
3847 break;
3849 return ret;
3852 /* Mail search text
3853 * Accepts: sized text to search
3854 * character set of sized text
3855 * string list of search keys
3856 * Returns: T if search found a match
3859 long mail_search_string (SIZEDTEXT *s,char *charset,STRINGLIST **st)
3861 SIZEDTEXT u;
3862 long ret;
3863 STRINGLIST **sc = st;
3864 /* convert to UTF-8 as best we can */
3865 if (!utf8_text (s,charset,&u,U8T_CANONICAL))
3866 utf8_text (s,NIL,&u,U8T_CANONICAL);
3867 ret = mail_search_string_work (&u,st);
3868 if (u.data != s->data) fs_give ((void **) &u.data);
3869 return ret;
3873 /* Mail search text worker routine
3874 * Accepts: sized text to search
3875 * string list of search keys
3876 * Returns: T if search found a match
3879 long mail_search_string_work (SIZEDTEXT *s,STRINGLIST **st)
3881 void *t;
3882 STRINGLIST **sc = st;
3883 while (*sc) { /* run down criteria list */
3884 if (ssearch (s->data,s->size,(*sc)->text.data,(*sc)->text.size)) {
3885 t = (void *) (*sc); /* found one, need to flush this */
3886 *sc = (*sc)->next; /* remove it from the list */
3887 fs_give (&t); /* flush the buffer */
3889 else sc = &(*sc)->next; /* move to next in list */
3891 return *st ? NIL : LONGT;
3895 /* Mail search keyword
3896 * Accepts: MAIL stream
3897 * elt to get flags from
3898 * keyword list
3899 * T for keyword search, NIL for unkeyword search
3900 * Returns: T if search found a match
3903 long mail_search_keyword (MAILSTREAM *stream,MESSAGECACHE *elt,STRINGLIST *st,
3904 long flag)
3906 int i,j;
3907 unsigned long f = 0;
3908 unsigned long tf;
3909 do {
3910 for (i = 0; (j = (i < NUSERFLAGS) && stream->user_flags[i]); ++i)
3911 if (!compare_csizedtext (stream->user_flags[i],&st->text)) {
3912 f |= (1 << i);
3913 break;
3915 if (flag && !j) return NIL;
3916 } while ((st = st->next) != NULL);
3917 tf = elt->user_flags & f; /* get set flags which match */
3918 return flag ? (f == tf) : !tf;
3921 /* Mail search an address list
3922 * Accepts: address list
3923 * string list
3924 * Returns: T if search found a match
3927 #define SEARCHBUFLEN (size_t) 2000
3928 #define SEARCHBUFSLOP (size_t) 5
3930 long mail_search_addr (ADDRESS *adr,STRINGLIST *st)
3932 ADDRESS *a,tadr;
3933 SIZEDTEXT txt;
3934 char tmp[SENDBUFLEN + 1];
3935 size_t i = SEARCHBUFLEN;
3936 size_t k;
3937 long ret = NIL;
3938 if (adr) {
3939 txt.data = (unsigned char *) fs_get (i + SEARCHBUFSLOP);
3940 /* never an error or next */
3941 tadr.error = NIL,tadr.next = NIL;
3942 /* write address list */
3943 for (txt.size = 0,a = adr; a; a = a->next) {
3944 k = (tadr.mailbox = a->mailbox) ? 4 + 2*strlen (a->mailbox) : 3;
3945 if ((tadr.personal = a->personal) != NULL) k += 3 + 2*strlen (a->personal);
3946 if ((tadr.adl = a->adl) != NULL) k += 3 + 2*strlen (a->adl);
3947 if ((tadr.host = a->host) != NULL) k += 3 + 2*strlen (a->host);
3948 if (tadr.personal || tadr.adl) k += 2;
3949 if (k < (SENDBUFLEN-10)) {/* ignore ridiculous addresses */
3950 tmp[0] = '\0';
3951 rfc822_write_address (tmp,&tadr);
3952 /* resize buffer if necessary */
3953 if (((k = strlen (tmp)) + txt.size) > i)
3954 fs_resize ((void **) &txt.data,SEARCHBUFSLOP + (i += SEARCHBUFLEN));
3955 /* add new address */
3956 memcpy (txt.data + txt.size,tmp,k);
3957 txt.size += k;
3958 /* another address follows */
3959 if (a->next) txt.data[txt.size++] = ',';
3962 txt.data[txt.size] = '\0'; /* tie off string */
3963 ret = mail_search_header (&txt,st);
3964 fs_give ((void **) &txt.data);
3966 return ret;
3969 /* Get string for low-memory searching
3970 * Accepts: readin function pointer
3971 * stream to use
3972 * number of bytes
3973 * gets data packet
3975 * mail stream
3976 * message number
3977 * descriptor string
3978 * option flags
3979 * Returns: NIL, always
3982 #define SEARCHSLOP 128
3984 char *mail_search_gets (readfn_t f,void *stream,unsigned long size,
3985 GETS_DATA *md)
3987 unsigned long i;
3988 char tmp[MAILTMPLEN+SEARCHSLOP+1];
3989 SIZEDTEXT st;
3990 /* better not be called unless searching */
3991 if (!md->stream->private.search.string) {
3992 sprintf (tmp,"Search botch, mbx = %.80s, %s = %lu[%.80s]",
3993 md->stream->mailbox,
3994 (md->flags & FT_UID) ? "UID" : "msg",md->msgno,md->what);
3995 fatal (tmp);
3997 /* initially no match for search */
3998 md->stream->private.search.result = NIL;
3999 /* make sure buffer clear */
4000 memset (st.data = (unsigned char *) tmp,'\0',
4001 (size_t) MAILTMPLEN+SEARCHSLOP+1);
4002 /* read first buffer */
4003 (*f) (stream,st.size = i = min (size,(long) MAILTMPLEN),tmp);
4004 /* search for text */
4005 if (mail_search_string (&st,NIL,&md->stream->private.search.string))
4006 md->stream->private.search.result = T;
4007 else if (size -= i) { /* more to do, blat slop down */
4008 memmove (tmp,tmp+MAILTMPLEN-SEARCHSLOP,(size_t) SEARCHSLOP);
4009 do { /* read subsequent buffers one at a time */
4010 (*f) (stream,i = min (size,(long) MAILTMPLEN),tmp+SEARCHSLOP);
4011 st.size = i + SEARCHSLOP;
4012 if (mail_search_string (&st,NIL,&md->stream->private.search.string))
4013 md->stream->private.search.result = T;
4014 else memmove (tmp,tmp+MAILTMPLEN,(size_t) SEARCHSLOP);
4016 while ((size -= i) && !md->stream->private.search.result);
4018 if (size) { /* toss out everything after that */
4019 do (*f) (stream,i = min (size,(long) MAILTMPLEN),tmp);
4020 while (size -= i);
4022 return NIL;
4025 /* Mail parse search criteria
4026 * Accepts: criteria
4027 * Returns: search program if parse successful, else NIL
4030 SEARCHPGM *mail_criteria (char *criteria)
4032 SEARCHPGM *pgm = NIL;
4033 char *criterion,*r,tmp[MAILTMPLEN];
4034 int f;
4035 if (criteria) { /* only if criteria defined */
4036 /* make writeable copy of criteria */
4037 criteria = cpystr (criteria);
4038 /* for each criterion */
4039 for (pgm = mail_newsearchpgm (), criterion = strtok_r (criteria," ",&r);
4040 criterion; (criterion = strtok_r (NIL," ",&r))) {
4041 f = NIL; /* init then scan the criterion */
4042 switch (*ucase (criterion)) {
4043 case 'A': /* possible ALL, ANSWERED */
4044 if (!strcmp (criterion+1,"LL")) f = T;
4045 else if (!strcmp (criterion+1,"NSWERED")) f = pgm->answered = T;
4046 break;
4047 case 'B': /* possible BCC, BEFORE, BODY */
4048 if (!strcmp (criterion+1,"CC"))
4049 f = mail_criteria_string (&pgm->bcc,&r);
4050 else if (!strcmp (criterion+1,"EFORE"))
4051 f = mail_criteria_date (&pgm->before,&r);
4052 else if (!strcmp (criterion+1,"ODY"))
4053 f = mail_criteria_string (&pgm->body,&r);
4054 break;
4055 case 'C': /* possible CC */
4056 if (!strcmp (criterion+1,"C")) f = mail_criteria_string (&pgm->cc,&r);
4057 break;
4058 case 'D': /* possible DELETED */
4059 if (!strcmp (criterion+1,"ELETED")) f = pgm->deleted = T;
4060 break;
4061 case 'F': /* possible FLAGGED, FROM */
4062 if (!strcmp (criterion+1,"LAGGED")) f = pgm->flagged = T;
4063 else if (!strcmp (criterion+1,"ROM"))
4064 f = mail_criteria_string (&pgm->from,&r);
4065 break;
4066 case 'K': /* possible KEYWORD */
4067 if (!strcmp (criterion+1,"EYWORD"))
4068 f = mail_criteria_string (&pgm->keyword,&r);
4069 break;
4071 case 'N': /* possible NEW */
4072 if (!strcmp (criterion+1,"EW")) f = pgm->recent = pgm->unseen = T;
4073 break;
4074 case 'O': /* possible OLD, ON */
4075 if (!strcmp (criterion+1,"LD")) f = pgm->old = T;
4076 else if (!strcmp (criterion+1,"N"))
4077 f = mail_criteria_date (&pgm->on,&r);
4078 break;
4079 case 'R': /* possible RECENT */
4080 if (!strcmp (criterion+1,"ECENT")) f = pgm->recent = T;
4081 break;
4082 case 'S': /* possible SEEN, SINCE, SUBJECT */
4083 if (!strcmp (criterion+1,"EEN")) f = pgm->seen = T;
4084 else if (!strcmp (criterion+1,"INCE"))
4085 f = mail_criteria_date (&pgm->since,&r);
4086 else if (!strcmp (criterion+1,"UBJECT"))
4087 f = mail_criteria_string (&pgm->subject,&r);
4088 break;
4089 case 'T': /* possible TEXT, TO */
4090 if (!strcmp (criterion+1,"EXT"))
4091 f = mail_criteria_string (&pgm->text,&r);
4092 else if (!strcmp (criterion+1,"O"))
4093 f = mail_criteria_string (&pgm->to,&r);
4094 break;
4095 case 'U': /* possible UN* */
4096 if (criterion[1] == 'N') {
4097 if (!strcmp (criterion+2,"ANSWERED")) f = pgm->unanswered = T;
4098 else if (!strcmp (criterion+2,"DELETED")) f = pgm->undeleted = T;
4099 else if (!strcmp (criterion+2,"FLAGGED")) f = pgm->unflagged = T;
4100 else if (!strcmp (criterion+2,"KEYWORD"))
4101 f = mail_criteria_string (&pgm->unkeyword,&r);
4102 else if (!strcmp (criterion+2,"SEEN")) f = pgm->unseen = T;
4104 break;
4105 default: /* we will barf below */
4106 break;
4108 if (!f) { /* if can't identify criterion */
4109 sprintf (tmp,"Unknown search criterion: %.30s",criterion);
4110 MM_LOG (tmp,ERROR);
4111 mail_free_searchpgm (&pgm);
4112 break;
4115 /* no longer need copy of criteria */
4116 fs_give ((void **) &criteria);
4118 return pgm;
4121 /* Parse a date
4122 * Accepts: pointer to date integer to return
4123 * pointer to strtok state
4124 * Returns: T if successful, else NIL
4127 int mail_criteria_date (unsigned short *date,char **r)
4129 STRINGLIST *s = NIL;
4130 MESSAGECACHE elt;
4131 /* parse the date and return fn if OK */
4132 int ret = (mail_criteria_string (&s,r) &&
4133 mail_parse_date (&elt,(char *) s->text.data) &&
4134 (*date = mail_shortdate (elt.year,elt.month,elt.day))) ?
4135 T : NIL;
4136 if (s) mail_free_stringlist (&s);
4137 return ret;
4140 /* Calculate shortdate from elt values
4141 * Accepts: year (0 = BASEYEAR)
4142 * month (1 = January)
4143 * day
4144 * Returns: shortdate
4147 unsigned short mail_shortdate (unsigned int year,unsigned int month,
4148 unsigned int day)
4150 return (year << 9) + (month << 5) + day;
4153 /* Parse a string
4154 * Accepts: pointer to stringlist
4155 * pointer to strtok state
4156 * Returns: T if successful, else NIL
4159 int mail_criteria_string (STRINGLIST **s,char **r)
4161 unsigned long n;
4162 char e,*d,*end = " ",*c = strtok_r (NIL,"",r);
4163 if (!c) return NIL; /* missing argument */
4164 switch (*c) { /* see what the argument is */
4165 case '{': /* literal string */
4166 n = strtoul (c+1,&d,10); /* get its length */
4167 if ((*d++ == '}') && (*d++ == '\015') && (*d++ == '\012') &&
4168 (!(*(c = d + n)) || (*c == ' '))) {
4169 e = *--c; /* store old delimiter */
4170 *c = '\377'; /* make sure not a space */
4171 strtok_r (c," ",r); /* reset the strtok mechanism */
4172 *c = e; /* put character back */
4173 break;
4175 case '\0': /* catch bogons */
4176 case ' ':
4177 return NIL;
4178 case '"': /* quoted string */
4179 if (strchr (c+1,'"')) end = "\"";
4180 else return NIL; /* falls through */
4181 default: /* atomic string */
4182 if ((d = strtok_r (c,end,r)) != NULL) n = strlen (d);
4183 else return NIL;
4184 break;
4186 while (*s) s = &(*s)->next; /* find tail of list */
4187 *s = mail_newstringlist (); /* make new entry */
4188 /* return the data */
4189 (*s)->text.data = (unsigned char *) cpystr (d);
4190 (*s)->text.size = n;
4191 return T;
4194 /* Mail parse set from string
4195 * Accepts: string to parse
4196 * pointer to updated string pointer for return
4197 * Returns: set with pointer updated, or NIL if error
4200 SEARCHSET *mail_parse_set (char *s,char **ret)
4202 SEARCHSET *cur;
4203 SEARCHSET *set = NIL;
4204 while (isdigit (*s)) {
4205 if (!set) cur = set = mail_newsearchset ();
4206 else cur = cur->next = mail_newsearchset ();
4207 /* parse value */
4208 if (!(cur->first = strtoul (s,&s,10)) ||
4209 ((*s == ':') && !(isdigit (*++s) && (cur->last = strtoul (s,&s,10)))))
4210 break; /* bad value or range */
4211 if (*s == ',') ++s; /* point to next value if more */
4212 else { /* end of set */
4213 *ret = s; /* set return pointer */
4214 return set; /* return set */
4217 mail_free_searchset (&set); /* failure, punt partial set */
4218 return NIL;
4222 /* Mail append to set
4223 * Accepts: head of search set or NIL to do nothing
4224 * message to add
4225 * Returns: tail of search set or NIL if did nothing
4228 SEARCHSET *mail_append_set (SEARCHSET *set,unsigned long msgno)
4230 if (set) { /* find tail */
4231 while (set->next) set = set->next;
4232 /* start of set if no first member */
4233 if (!set->first) set->first = msgno;
4234 else if (msgno == (set->last ? set->last : set->first) + 1)
4235 set->last = msgno; /* extend range if 1 past current */
4236 else (set = set->next = mail_newsearchset ())->first = msgno;
4238 return set;
4241 /* Mail sort messages
4242 * Accepts: mail stream
4243 * character set
4244 * search program
4245 * sort program
4246 * option flags
4247 * Returns: vector of sorted message sequences or NIL if error
4250 unsigned long *mail_sort (MAILSTREAM *stream,char *charset,SEARCHPGM *spg,
4251 SORTPGM *pgm,long flags)
4253 unsigned long *ret = NIL;
4254 if (stream->dtb) /* do the driver's action */
4255 ret = (*(stream->dtb->sort ? stream->dtb->sort : mail_sort_msgs))
4256 (stream,charset,spg,pgm,flags);
4257 /* flush search/sort programs if requested */
4258 if (spg && (flags & SE_FREE)) mail_free_searchpgm (&spg);
4259 if (flags & SO_FREE) mail_free_sortpgm (&pgm);
4260 return ret;
4263 /* Mail sort messages work routine
4264 * Accepts: mail stream
4265 * character set
4266 * search program
4267 * sort program
4268 * option flags
4269 * Returns: vector of sorted message sequences or NIL if error
4272 unsigned long *mail_sort_msgs (MAILSTREAM *stream,char *charset,SEARCHPGM *spg,
4273 SORTPGM *pgm,long flags)
4275 unsigned long i;
4276 SORTCACHE **sc;
4277 unsigned long *ret = NIL;
4278 if (spg) { /* only if a search needs to be done */
4279 int silent = stream->silent;
4280 stream->silent = T; /* don't pass up mm_searched() events */
4281 /* search for messages */
4282 mail_search_full (stream,charset,spg,NIL);
4283 stream->silent = silent; /* restore silence state */
4285 /* initialize progress counters */
4286 pgm->nmsgs = pgm->progress.cached = 0;
4287 /* pass 1: count messages to sort */
4288 for (i = 1; i <= stream->nmsgs; ++i)
4289 if (mail_elt (stream,i)->searched) pgm->nmsgs++;
4290 if (pgm->nmsgs) { /* pass 2: sort cache */
4291 sc = mail_sort_loadcache (stream,pgm);
4292 /* pass 3: sort messages */
4293 if (!pgm->abort) ret = mail_sort_cache (stream,pgm,sc,flags);
4294 fs_give ((void **) &sc); /* don't need sort vector any more */
4296 /* empty sort results */
4297 else ret = (unsigned long *) memset (fs_get (sizeof (unsigned long)),0,
4298 sizeof (unsigned long));
4299 /* also return via callback if requested */
4300 if (mailsortresults) (*mailsortresults) (stream,ret,pgm->nmsgs);
4301 return ret; /* return sort results */
4304 /* Mail sort sortcache vector
4305 * Accepts: mail stream
4306 * sort program
4307 * sortcache vector
4308 * option flags
4309 * Returns: vector of sorted message sequences or NIL if error
4312 unsigned long *mail_sort_cache (MAILSTREAM *stream,SORTPGM *pgm,SORTCACHE **sc,
4313 long flags)
4315 unsigned long i,*ret;
4316 /* pass 3: sort messages */
4317 qsort ((void *) sc,pgm->nmsgs,sizeof (SORTCACHE *),mail_sort_compare);
4318 /* optional post sorting */
4319 if (pgm->postsort) (*pgm->postsort) ((void *) sc);
4320 /* pass 4: return results */
4321 ret = (unsigned long *) fs_get ((pgm->nmsgs+1) * sizeof (unsigned long));
4322 if (flags & SE_UID) /* UID or msgno? */
4323 for (i = 0; i < pgm->nmsgs; i++) ret[i] = mail_uid (stream,sc[i]->num);
4324 else for (i = 0; i < pgm->nmsgs; i++) ret[i] = sc[i]->num;
4325 ret[pgm->nmsgs] = 0; /* tie off message list */
4326 return ret;
4329 /* Mail load sortcache
4330 * Accepts: mail stream, already searched
4331 * sort program
4332 * Returns: vector of sortcache pointers matching search
4335 static STRINGLIST maildateline = {{(unsigned char *) "date",4},NIL};
4336 static STRINGLIST mailrnfromline = {{(unsigned char *) ">from",5},NIL};
4337 static STRINGLIST mailfromline = {{(unsigned char *) "from",4},
4338 &mailrnfromline};
4339 static STRINGLIST mailtonline = {{(unsigned char *) "to",2},NIL};
4340 static STRINGLIST mailccline = {{(unsigned char *) "cc",2},NIL};
4341 static STRINGLIST mailsubline = {{(unsigned char *) "subject",7},NIL};
4343 SORTCACHE **mail_sort_loadcache (MAILSTREAM *stream,SORTPGM *pgm)
4345 char *t,*v,*x,tmp[MAILTMPLEN];
4346 SORTPGM *pg;
4347 SORTCACHE *s,**sc;
4348 MESSAGECACHE *elt,telt;
4349 ENVELOPE *env;
4350 ADDRESS *adr = NIL;
4351 unsigned long i = (pgm->nmsgs) * sizeof (SORTCACHE *);
4352 sc = (SORTCACHE **) memset (fs_get ((size_t) i),0,(size_t) i);
4353 /* see what needs to be loaded */
4354 for (i = 1; !pgm->abort && (i <= stream->nmsgs); i++)
4355 if ((elt = mail_elt (stream,i))->searched) {
4356 sc[pgm->progress.cached++] =
4357 s = (SORTCACHE *) (*mailcache) (stream,i,CH_SORTCACHE);
4358 s->pgm = pgm; /* note sort program */
4359 s->num = i;
4360 /* get envelope if cached */
4361 if (stream->scache) env = (i == stream->msgno) ? stream->env : NIL;
4362 else env = elt->private.msg.env;
4363 for (pg = pgm; pg; pg = pg->next) switch (pg->function) {
4364 case SORTARRIVAL: /* sort by arrival date */
4365 if (!s->arrival) {
4366 /* internal date unknown but can get? */
4367 if (!elt->day && !(stream->dtb->flags & DR_NOINTDATE)) {
4368 sprintf (tmp,"%lu",i);
4369 mail_fetch_fast (stream,tmp,NIL);
4371 /* wrong thing before 3-Jan-1970 */
4372 s->arrival = elt->day ? mail_longdate (elt) : 1;
4373 s->dirty = T;
4375 break;
4376 case SORTSIZE: /* sort by message size */
4377 if (!s->size) {
4378 if (!elt->rfc822_size) {
4379 sprintf (tmp,"%lu",i);
4380 mail_fetch_fast (stream,tmp,NIL);
4382 s->size = elt->rfc822_size ? elt->rfc822_size : 1;
4383 s->dirty = T;
4385 break;
4387 case SORTDATE: /* sort by date */
4388 if (!s->date) {
4389 if (env) t = env->date;
4390 else if ((t = mail_fetch_header (stream,i,NIL,&maildateline,NIL,
4391 FT_INTERNAL | FT_PEEK)) &&
4392 (t = strchr (t,':')))
4393 for (x = ++t; (x = strpbrk (x,"\012\015")) != NULL; x++)
4394 switch (*(v = ((*x == '\015') && (x[1] == '\012')) ? x+2 : x+1)){
4395 case ' ': /* erase continuation newlines */
4396 case '\t':
4397 memmove (x,v,strlen (v));
4398 break;
4399 default: /* tie off extraneous text */
4400 *x = x[1] = '\0';
4402 /* skip leading whitespace */
4403 if (t) while ((*t == ' ') || (*t == '\t')) t++;
4404 /* parse date from Date: header */
4405 if (!(t && mail_parse_date (&telt,t) &&
4406 (s->date = mail_longdate (&telt)))) {
4407 /* failed, use internal date */
4408 if (!(s->date = s->arrival)) {
4409 /* internal date unknown but can get? */
4410 if (!elt->day && !(stream->dtb->flags & DR_NOINTDATE)) {
4411 sprintf (tmp,"%lu",i);
4412 mail_fetch_fast (stream,tmp,NIL);
4414 /* wrong thing before 3-Jan-1970 */
4415 s->date = (s->arrival = elt->day ? mail_longdate (elt) : 1);
4418 s->dirty = T;
4420 break;
4422 case SORTFROM: /* sort by first from */
4423 if (!s->from) {
4424 if (env) s->from = env->from && env->from->mailbox ?
4425 cpystr (env->from->mailbox) : NIL;
4426 else if ((t = mail_fetch_header (stream,i,NIL,&mailfromline,NIL,
4427 FT_INTERNAL | FT_PEEK)) &&
4428 (t = strchr (t,':'))) {
4429 for (x = ++t; (x = strpbrk (x,"\012\015")) != NULL; x++)
4430 switch (*(v = ((*x == '\015') && (x[1] == '\012')) ? x+2 : x+1)){
4431 case ' ': /* erase continuation newlines */
4432 case '\t':
4433 memmove (x,v,strlen (v));
4434 break;
4435 case 'f': /* continuation but with extra "From:" */
4436 case 'F':
4437 if ((v = strchr (v,':')) != NULL) {
4438 memmove (x,v+1,strlen (v+1));
4439 break;
4441 default: /* tie off extraneous text */
4442 *x = x[1] = '\0';
4444 rfc822_parse_adrlist (&adr,t,BADHOST);
4445 if (adr) {
4446 s->from = adr->mailbox;
4447 adr->mailbox = NIL;
4448 mail_free_address (&adr);
4451 if (!s->from) s->from = cpystr ("");
4452 s->dirty = T;
4454 break;
4456 case SORTTO: /* sort by first to */
4457 if (!s->to) {
4458 if (env) s->to = env->to && env->to->mailbox ?
4459 cpystr (env->to->mailbox) : NIL;
4460 else if ((t = mail_fetch_header (stream,i,NIL,&mailtonline,NIL,
4461 FT_INTERNAL | FT_PEEK)) &&
4462 (t = strchr (t,':'))) {
4463 for (x = ++t; (x = strpbrk (x,"\012\015")) != NULL; x++)
4464 switch (*(v = ((*x == '\015') && (x[1] == '\012')) ? x+2 : x+1)){
4465 case ' ': /* erase continuation newlines */
4466 case '\t':
4467 memmove (x,v,strlen (v));
4468 break;
4469 case 't': /* continuation but with extra "To:" */
4470 case 'T':
4471 if ((v = strchr (v,':')) != NULL) {
4472 memmove (x,v+1,strlen (v+1));
4473 break;
4475 default: /* tie off extraneous text */
4476 *x = x[1] = '\0';
4478 rfc822_parse_adrlist (&adr,t,BADHOST);
4479 if (adr) {
4480 s->to = adr->mailbox;
4481 adr->mailbox = NIL;
4482 mail_free_address (&adr);
4485 if (!s->to) s->to = cpystr ("");
4486 s->dirty = T;
4488 break;
4490 case SORTCC: /* sort by first cc */
4491 if (!s->cc) {
4492 if (env) s->cc = env->cc && env->cc->mailbox ?
4493 cpystr (env->cc->mailbox) : NIL;
4494 else if ((t = mail_fetch_header (stream,i,NIL,&mailccline,NIL,
4495 FT_INTERNAL | FT_PEEK)) &&
4496 (t = strchr (t,':'))) {
4497 for (x = ++t; (x = strpbrk (x,"\012\015")) != NULL; x++)
4498 switch (*(v = ((*x == '\015') && (x[1] == '\012')) ? x+2 : x+1)){
4499 case ' ': /* erase continuation newlines */
4500 case '\t':
4501 memmove (x,v,strlen (v));
4502 break;
4503 case 'c': /* continuation but with extra "cc:" */
4504 case 'C':
4505 if ((v = strchr (v,':')) != NULL) {
4506 memmove (x,v+1,strlen (v+1));
4507 break;
4509 default: /* tie off extraneous text */
4510 *x = x[1] = '\0';
4512 rfc822_parse_adrlist (&adr,t,BADHOST);
4513 if (adr) {
4514 s->cc = adr->mailbox;
4515 adr->mailbox = NIL;
4516 mail_free_address (&adr);
4519 if (!s->cc) s->cc = cpystr ("");
4520 s->dirty = T;
4522 break;
4524 case SORTSUBJECT: /* sort by subject */
4525 if (!s->subject) {
4526 /* get subject from envelope if have one */
4527 if (env) t = env->subject ? env->subject : "";
4528 /* otherwise snarf from header text */
4529 else if ((t = mail_fetch_header (stream,i,NIL,&mailsubline,
4530 NIL,FT_INTERNAL | FT_PEEK)) &&
4531 (t = strchr (t,':')))
4532 for (x = ++t; (x = strpbrk (x,"\012\015")) != NULL; x++)
4533 switch (*(v = ((*x == '\015') && (x[1] == '\012')) ? x+2 : x+1)){
4534 case ' ': /* erase continuation newlines */
4535 case '\t':
4536 memmove (x,v,strlen (v));
4537 break;
4538 default: /* tie off extraneous text */
4539 *x = x[1] = '\0';
4541 else t = ""; /* empty subject */
4542 /* strip and cache subject */
4543 s->refwd = mail_strip_subject (t,&s->subject);
4544 s->dirty = T;
4546 break;
4547 default:
4548 fatal ("Unknown sort function");
4551 return sc;
4554 /* Strip subjects of extra spaces and leading and trailing cruft for sorting
4555 * Accepts: unstripped subject
4556 * pointer to return stripped subject, in cpystr form
4557 * Returns: T if subject had a re/fwd, NIL otherwise
4560 unsigned int mail_strip_subject (char *t,char **ret)
4562 SIZEDTEXT src,dst;
4563 unsigned long i,slen;
4564 char c,*s,*x;
4565 unsigned int refwd = NIL;
4566 if ((src.size = strlen (t)) != 0) { /* have non-empty subject? */
4567 src.data = (unsigned char *) t;
4568 /* Step 1 */
4569 /* make copy, convert MIME2 if needed */
4570 *ret = s = (utf8_mime2text (&src,&dst,U8T_CANONICAL) &&
4571 (src.data != dst.data)) ? (char *) dst.data : cpystr (t);
4572 /* convert spaces to tab, strip extra spaces */
4573 for (x = t = s, c = 'x'; *t; t++) {
4574 if (c != ' ') c = *x++ = ((*t == '\t') ? ' ' : *t);
4575 else if ((*t != '\t') && (*t != ' ')) c = *x++ = *t;
4577 *x = '\0'; /* tie off string */
4578 /* Step 2 */
4579 for (slen = dst.size; s; slen = strlen (s)) {
4580 for (t = s + slen; t > s; ) switch (t[-1]) {
4581 case ' ': case '\t': /* WSP */
4582 *--t = '\0'; /* just remove it */
4583 break;
4584 case ')': /* possible "(fwd)" */
4585 if ((t >= (s + 5)) && (t[-5] == '(') &&
4586 ((t[-4] == 'F') || (t[-4] == 'f')) &&
4587 ((t[-3] == 'W') || (t[-3] == 'w')) &&
4588 ((t[-2] == 'D') || (t[-2] == 'd'))) {
4589 *(t -= 5) = '\0'; /* remove "(fwd)" */
4590 refwd = T; /* note a re/fwd */
4591 break;
4593 default: /* not a subj-trailer */
4594 t = s;
4595 break;
4597 /* Steps 3-5 */
4598 for (t = s; t; ) switch (*s) {
4599 case ' ': case '\t': /* WSP */
4600 s = t = mail_strip_subject_wsp (s + 1);
4601 break;
4602 case 'r': case 'R': /* possible "re" */
4603 if (((s[1] == 'E') || (s[1] == 'e')) &&
4604 (t = mail_strip_subject_wsp (s + 2)) &&
4605 (t = mail_strip_subject_blob (t)) && (*t == ':')) {
4606 s = ++t; /* found "re" */
4607 refwd = T; /* definitely a re/fwd at this point */
4609 else t = NIL; /* found subj-middle */
4610 break;
4611 case 'f': case 'F': /* possible "fw" or "fwd" */
4612 if (((s[1] == 'w') || (s[1] == 'W')) &&
4613 (((s[2] == 'd') || (s[2] == 'D')) ?
4614 (t = mail_strip_subject_wsp (s + 3)) :
4615 (t = mail_strip_subject_wsp (s + 2))) &&
4616 (t = mail_strip_subject_blob (t)) && (*t == ':')) {
4617 s = ++t; /* found "fwd" */
4618 refwd = T; /* definitely a re/fwd at this point */
4620 else t = NIL; /* found subj-middle */
4621 break;
4622 case '[': /* possible subj-blob */
4623 if ((t = mail_strip_subject_blob (s)) && *t) s = t;
4624 else t = NIL; /* found subj-middle */
4625 break;
4626 default:
4627 t = NIL; /* found subj-middle */
4628 break;
4630 /* Step 6 */
4631 /* Netscape-style "[Fwd: ...]"? */
4632 if ((*s == '[') && ((s[1] == 'F') || (s[1] == 'f')) &&
4633 ((s[2] == 'W') || (s[2] == 'w')) &&
4634 ((s[3] == 'D') || (s[3] == 'd')) && (s[4] == ':') &&
4635 (s[i = strlen (s) - 1] == ']')) {
4636 s[i] = '\0'; /* flush closing "]" */
4637 s += 5; /* and leading "[Fwd:" */
4638 refwd = T; /* definitely a re/fwd at this point */
4640 else break; /* don't need to loop back to step 2 */
4642 if (s != (t = *ret)) { /* removed leading text? */
4643 s = *ret = cpystr (s); /* yes, make a fresh return copy */
4644 fs_give ((void **) &t); /* flush old copy */
4647 else *ret = cpystr (""); /* empty subject */
4648 return refwd; /* return re/fwd state */
4651 /* Strip subject wsp helper routine
4652 * Accepts: text
4653 * Returns: pointer to text after blob
4656 char *mail_strip_subject_wsp (char *s)
4658 while ((*s == ' ') || (*s == '\t')) s++;
4659 return s;
4663 /* Strip subject blob helper routine
4664 * Accepts: text
4665 * Returns: pointer to text after any blob, NIL if blob-like but not blob
4668 char *mail_strip_subject_blob (char *s)
4670 if (*s != '[') return s; /* not a blob, ignore */
4671 /* search for end of blob */
4672 while (*++s != ']') if ((*s == '[') || !*s) return NIL;
4673 return mail_strip_subject_wsp (s + 1);
4676 /* Sort compare messages
4677 * Accept: first message sort cache element
4678 * second message sort cache element
4679 * Returns: -1 if a1 < a2, 0 if a1 == a2, 1 if a1 > a2
4682 int mail_sort_compare (const void *a1,const void *a2)
4684 int i = 0;
4685 SORTCACHE *s1 = *(SORTCACHE **) a1;
4686 SORTCACHE *s2 = *(SORTCACHE **) a2;
4687 SORTPGM *pgm = s1->pgm;
4688 if (!s1->sorted) { /* this one sorted yet? */
4689 s1->sorted = T;
4690 pgm->progress.sorted++; /* another sorted message */
4692 if (!s2->sorted) { /* this one sorted yet? */
4693 s2->sorted = T;
4694 pgm->progress.sorted++; /* another sorted message */
4696 do {
4697 switch (pgm->function) { /* execute search program */
4698 case SORTDATE: /* sort by date */
4699 i = compare_ulong (s1->date,s2->date);
4700 break;
4701 case SORTARRIVAL: /* sort by arrival date */
4702 i = compare_ulong (s1->arrival,s2->arrival);
4703 break;
4704 case SORTSIZE: /* sort by message size */
4705 i = compare_ulong (s1->size,s2->size);
4706 break;
4707 case SORTFROM: /* sort by first from */
4708 i = compare_string (s1->from,s2->from);
4709 break;
4710 case SORTTO: /* sort by first to */
4711 i = compare_string (s1->to,s2->to);
4712 break;
4713 case SORTCC: /* sort by first cc */
4714 i = compare_string (s1->cc,s2->cc);
4715 break;
4716 case SORTSUBJECT: /* sort by subject */
4717 i = compare_string (s1->subject,s2->subject);
4718 break;
4720 if (pgm->reverse) i = -i; /* flip results if necessary */
4722 while ((pgm = i ? NIL : pgm->next) != NULL);
4723 /* return result, avoid 0 if at all possible */
4724 return i ? i : compare_ulong (s1->num,s2->num);
4727 /* Return message date as an unsigned long seconds since time began
4728 * Accepts: message cache pointer
4729 * Returns: unsigned long of date
4731 * This routine, like most UNIX systems, is clueless about leap seconds.
4732 * Thus, it treats 23:59:60 as equivalent to 00:00:00 the next day.
4734 * This routine forces any early hours on 1-Jan-1970 in oriental timezones
4735 * to be 1-Jan-1970 00:00:00 UTC, so as to avoid negative longdates.
4738 unsigned long mail_longdate (MESSAGECACHE *elt)
4740 unsigned long m = elt->month ? elt->month : 1;
4741 unsigned long yr = elt->year + BASEYEAR;
4742 /* number of days since time began */
4743 unsigned long ret = (elt->day ? (elt->day - 1) : 0)
4744 + 30 * (m - 1) + ((m + (m > 8)) / 2)
4745 #ifndef USEJULIANCALENDAR
4746 #ifndef USEORTHODOXCALENDAR /* Gregorian calendar */
4747 + ((yr / 400) - (BASEYEAR / 400)) - ((yr / 100) - (BASEYEAR / 100))
4748 #ifdef Y4KBUGFIX
4749 - ((yr / 4000) - (BASEYEAR / 4000))
4750 #endif
4751 - ((m < 3) ?
4752 !(yr % 4) && ((yr % 100) || (!(yr % 400)
4753 #ifdef Y4KBUGFIX
4754 && (yr % 4000)
4755 #endif
4756 )) : 2)
4757 #else /* Orthodox calendar */
4758 + ((2*(yr / 900)) - (2*(BASEYEAR / 900)))
4759 + (((yr % 900) >= 200) - ((BASEYEAR % 900) >= 200))
4760 + (((yr % 900) >= 600) - ((BASEYEAR % 900) >= 600))
4761 - ((yr / 100) - (BASEYEAR / 100))
4762 - ((m < 3) ?
4763 !(yr % 4) && ((yr % 100) || ((yr % 900) == 200) || ((yr % 900) == 600))
4764 : 2)
4765 #endif
4766 #endif
4767 + elt->year * 365 + (((unsigned long) (elt->year + (BASEYEAR % 4))) / 4);
4768 ret *= 24; ret += elt->hours; /* date value in hours */
4769 ret *= 60; ret +=elt->minutes;/* date value in minutes */
4770 yr = (elt->zhours * 60) + elt->zminutes;
4771 if (elt->zoccident) ret += yr;/* occidental timezone, make UTC */
4772 else if (ret < yr) return 0; /* still 31-Dec-1969 in UTC */
4773 else ret -= yr; /* oriental timezone, make UTC */
4774 ret *= 60; ret += elt->seconds;
4775 return ret;
4778 /* Mail thread messages
4779 * Accepts: mail stream
4780 * thread type
4781 * character set
4782 * search program
4783 * option flags
4784 * Returns: thread node tree or NIL if error
4787 THREADNODE *mail_thread (MAILSTREAM *stream,char *type,char *charset,
4788 SEARCHPGM *spg,long flags)
4790 THREADNODE *ret = NIL;
4791 if (stream->dtb) /* must have a live driver */
4792 ret = stream->dtb->thread ? /* do driver's action if available */
4793 (*stream->dtb->thread) (stream,type,charset,spg,flags) :
4794 mail_thread_msgs (stream,type,charset,spg,flags,mail_sort_msgs);
4795 /* flush search/sort programs if requested */
4796 if (spg && (flags & SE_FREE)) mail_free_searchpgm (&spg);
4797 return ret;
4801 /* Mail thread messages
4802 * Accepts: mail stream
4803 * thread type
4804 * character set
4805 * search program
4806 * option flags
4807 * sorter routine
4808 * Returns: thread node tree or NIL if error
4811 THREADNODE *mail_thread_msgs (MAILSTREAM *stream,char *type,char *charset,
4812 SEARCHPGM *spg,long flags,sorter_t sorter)
4814 THREADER *t;
4815 for (t = &mailthreadlist; t; t = t->next)
4816 if (!compare_cstring (type,t->name)) {
4817 THREADNODE *ret = (*t->dispatch) (stream,charset,spg,flags,sorter);
4818 if (mailthreadresults) (*mailthreadresults) (stream,ret);
4819 return ret;
4821 MM_LOG ("No such thread type",ERROR);
4822 return NIL;
4825 /* Mail thread ordered subject
4826 * Accepts: mail stream
4827 * character set
4828 * search program
4829 * option flags
4830 * sorter routine
4831 * Returns: thread node tree
4834 THREADNODE *mail_thread_orderedsubject (MAILSTREAM *stream,char *charset,
4835 SEARCHPGM *spg,long flags,
4836 sorter_t sorter)
4838 THREADNODE *thr = NIL;
4839 THREADNODE *cur,*top,**tc;
4840 SORTPGM pgm,pgm2;
4841 SORTCACHE *s;
4842 unsigned long i,j,*lst,*ls;
4843 /* sort by subject+date */
4844 memset (&pgm,0,sizeof (SORTPGM));
4845 memset (&pgm2,0,sizeof (SORTPGM));
4846 pgm.function = SORTSUBJECT;
4847 pgm.next = &pgm2;
4848 pgm2.function = SORTDATE;
4849 if ((lst = (*sorter) (stream,charset,spg,&pgm,flags & ~(SE_FREE | SE_UID))) != NULL){
4850 if (*(ls = lst)) { /* create thread */
4851 /* note first subject */
4852 cur = top = thr = mail_newthreadnode
4853 ((SORTCACHE *) (*mailcache) (stream,*ls++,CH_SORTCACHE));
4854 /* note its number */
4855 cur->num = (flags & SE_UID) ? mail_uid (stream,*lst) : *lst;
4856 i = 1; /* number of threads */
4857 while (*ls) { /* build tree */
4858 /* subjects match? */
4859 s = (SORTCACHE *) (*mailcache) (stream,*ls++,CH_SORTCACHE);
4860 if (compare_cstring (top->sc->subject,s->subject)) {
4861 i++; /* have a new thread */
4862 top = top->branch = cur = mail_newthreadnode (s);
4864 /* start a child of the top */
4865 else if (cur == top) cur = cur->next = mail_newthreadnode (s);
4866 /* sibling of child */
4867 else cur = cur->branch = mail_newthreadnode (s);
4868 /* set to msgno or UID as needed */
4869 cur->num = (flags & SE_UID) ? mail_uid (stream,s->num) : s->num;
4871 /* make threadnode cache */
4872 tc = (THREADNODE **) fs_get (i * sizeof (THREADNODE *));
4873 /* load threadnode cache */
4874 for (j = 0, cur = thr; cur; cur = cur->branch) tc[j++] = cur;
4875 if (i != j) fatal ("Threadnode cache confusion");
4876 qsort ((void *) tc,i,sizeof (THREADNODE *),mail_thread_compare_date);
4877 for (j = 0, --i; j < i; j++) tc[j]->branch = tc[j+1];
4878 tc[j]->branch = NIL; /* end of root */
4879 thr = tc[0]; /* head of data */
4880 fs_give ((void **) &tc);
4882 fs_give ((void **) &lst);
4884 return thr;
4887 /* Mail thread references
4888 * Accepts: mail stream
4889 * character set
4890 * search program
4891 * option flags
4892 * sorter routine
4893 * Returns: thread node tree
4896 #define REFHASHSIZE 1009 /* arbitrary prime for hash table size */
4898 /* Reference threading container, as described in Jamie Zawinski's web page
4899 * (http://www.jwz.org/doc/threading.html) for this algorithm. These are
4900 * stored as extended data in the hash table (called "id_table" in JWZ's
4901 * document) and are maintained by the hash table routines. The hash table
4902 * routines implement extended data as additional void* words at the end of
4903 * each bucket, hence these strange macros instead of a struct which would
4904 * have been more straightforward.
4907 #define THREADLINKS 3 /* number of thread links */
4909 #define CACHE(data) ((SORTCACHE *) (data)[0])
4910 #define PARENT(data) ((container_t) (data)[1])
4911 #define SETPARENT(data,value) ((container_t) (data[1] = value))
4912 #define SIBLING(data) ((container_t) (data)[2])
4913 #define SETSIBLING(data,value) ((container_t) (data[2] = value))
4914 #define CHILD(data) ((container_t) (data)[3])
4915 #define SETCHILD(data,value) ((container_t) (data[3] = value))
4917 THREADNODE *mail_thread_references (MAILSTREAM *stream,char *charset,
4918 SEARCHPGM *spg,long flags,sorter_t sorter)
4920 MESSAGECACHE *elt,telt;
4921 ENVELOPE *env;
4922 SORTCACHE *s;
4923 STRINGLIST *st;
4924 HASHENT *he;
4925 THREADNODE **tc,*cur,*lst,*nxt,*sis,*msg;
4926 container_t con,nxc,prc,sib;
4927 void **sub;
4928 char *t,tmp[MAILTMPLEN];
4929 unsigned long j,nmsgs;
4930 unsigned long i = stream->nmsgs * sizeof (SORTCACHE *);
4931 SORTCACHE **sc = (SORTCACHE **) memset (fs_get ((size_t) i),0,(size_t) i);
4932 HASHTAB *ht = hash_create (REFHASHSIZE);
4933 THREADNODE *root = NIL;
4934 if (spg) { /* only if a search needs to be done */
4935 int silent = stream->silent;
4936 stream->silent = T; /* don't pass up mm_searched() events */
4937 /* search for messages */
4938 mail_search_full (stream,charset,spg,NIL);
4939 stream->silent = silent; /* restore silence state */
4942 /* create SORTCACHE vector of requested msgs */
4943 for (i = 1, nmsgs = 0; i <= stream->nmsgs; ++i)
4944 if (mail_elt (stream,i)->searched)
4945 (sc[nmsgs++] = (SORTCACHE *)(*mailcache)(stream,i,CH_SORTCACHE))->num =i;
4946 /* separate pass so can do overview fetch lookahead */
4947 for (i = 0; i < nmsgs; ++i) { /* for each requested message */
4948 /* is anything missing in its SORTCACHE? */
4949 if (!((s = sc[i])->date && s->subject && s->message_id && s->references)) {
4950 /* driver has an overview mechanism? */
4951 if (stream->dtb && stream->dtb->overview) {
4952 /* yes, find following unloaded entries */
4953 for (j = i + 1; (j < nmsgs) && !sc[j]->references; ++j);
4954 sprintf (tmp,"%lu",mail_uid (stream,s->num));
4955 if (i != --j) /* end of range different? */
4956 sprintf (tmp + strlen (tmp),":%lu",mail_uid (stream,sc[j]->num));
4957 /* load via overview mechanism */
4958 mail_fetch_overview (stream,tmp,mail_thread_loadcache);
4960 /* still missing data? */
4961 if (!s->date || !s->subject || !s->message_id || !s->references) {
4962 /* try to load data from envelope */
4963 if ((env = mail_fetch_structure (stream,s->num,NIL,NIL)) != NULL) {
4964 if (!s->date && env->date && mail_parse_date (&telt,env->date))
4965 s->date = mail_longdate (&telt);
4966 if (!s->subject && env->subject)
4967 s->refwd =
4968 mail_strip_subject (env->subject,&s->subject);
4969 if (!s->message_id && env->message_id && *env->message_id)
4970 s->message_id = mail_thread_parse_msgid (env->message_id,NIL);
4971 if (!s->references && /* use References: or In-Reply-To: */
4972 !(s->references =
4973 mail_thread_parse_references (env->references,T)))
4974 s->references = mail_thread_parse_references(env->in_reply_to,NIL);
4976 /* last resort */
4977 if (!s->date && !(s->date = s->arrival)) {
4978 /* internal date unknown but can get? */
4979 if (!(elt = mail_elt (stream,s->num))->day &&
4980 !(stream->dtb->flags & DR_NOINTDATE)) {
4981 sprintf (tmp,"%lu",s->num);
4982 mail_fetch_fast (stream,tmp,NIL);
4984 /* wrong thing before 3-Jan-1970 */
4985 s->date = (s->arrival = elt->day ? mail_longdate (elt) : 1);
4987 if (!s->subject) s->subject = cpystr ("");
4988 if (!s->references) s->references = mail_newstringlist ();
4989 s->dirty = T;
4993 /* Step 1 (preliminary) */
4994 /* generate unique string */
4995 sprintf (tmp,"%s.%lx.%lx@%s",stream->mailbox,stream->uid_validity,
4996 mail_uid (stream,s->num),mylocalhost ());
4997 /* flush old unique string if not message-id */
4998 if (s->unique && (s->unique != s->message_id))
4999 fs_give ((void **) &s->unique);
5000 s->unique = s->message_id ? /* don't permit Message ID duplicates */
5001 (hash_lookup (ht,s->message_id) ? cpystr (tmp) : s->message_id) :
5002 (s->message_id = cpystr (tmp));
5003 /* add unique string to hash table */
5004 hash_add (ht,s->unique,s,THREADLINKS);
5006 /* Step 1 */
5007 for (i = 0; i < nmsgs; ++i) { /* for each message in sortcache */
5008 /* Step 1A */
5009 if ((st = (s = sc[i])->references) && st->text.data)
5010 for (con = hash_lookup_and_add (ht,(char *) st->text.data,NIL,
5011 THREADLINKS); (st = st->next) != NULL; con = nxc) {
5012 nxc = hash_lookup_and_add (ht,(char *) st->text.data,NIL,THREADLINKS);
5013 /* only if no parent & won't introduce loop */
5014 if (!PARENT (nxc) && !mail_thread_check_child (con,nxc)) {
5015 SETPARENT (nxc,con); /* establish parent/child link */
5016 /* other children become sibling of this one */
5017 SETSIBLING (nxc,CHILD (con));
5018 SETCHILD (con,nxc); /* set as child of parent */
5021 else con = NIL; /* else message has no ancestors */
5022 /* Step 1B */
5023 if ((prc = PARENT ((nxc = hash_lookup (ht,s->unique)))) &&
5024 (prc != con)) { /* break links if have a different parent */
5025 SETPARENT (nxc,NIL); /* easy if direct child */
5026 if (nxc == CHILD (prc)) SETCHILD (prc,SIBLING (nxc));
5027 else { /* otherwise hunt through sisters */
5028 for (sib = CHILD (prc); nxc != SIBLING (sib); sib = SIBLING (sib));
5029 SETSIBLING (sib,SIBLING (nxc));
5031 SETSIBLING (nxc,NIL); /* no more little sisters either */
5032 prc = NIL; /* no more parent set */
5034 /* need to set parent, and parent is good? */
5035 if (!prc && !mail_thread_check_child (con,nxc)) {
5036 SETPARENT (nxc,con); /* establish parent/child link */
5037 if (con) { /* if non-root parent, set parent's child */
5038 if (CHILD (con)) { /* have a child already */
5039 /* find youngest daughter */
5040 for (con = CHILD (con); SIBLING (con); con = SIBLING (con));
5041 SETSIBLING (con,nxc); /* add new baby sister */
5043 else SETCHILD (con,nxc);/* set as only child */
5047 fs_give ((void **) &sc); /* finished with sortcache vector */
5049 /* Step 2 */
5050 /* search hash table for parentless messages */
5051 for (i = 0, prc = con = NIL; i < ht->size; i++)
5052 for (he = ht->table[i]; he; he = he->next)
5053 if (!PARENT ((nxc = he->data))) {
5054 /* sibling of previous parentless message */
5055 if (con) con = SETSIBLING (con,nxc);
5056 else prc = con = nxc; /* first parentless message */
5058 /* Once the dummy containers are pruned, we no longer need the parent
5059 * information, so we can convert the containers to THREADNODEs. Since
5060 * we don't need the id_table any more either, we can reset the hash table
5061 * and reuse it as a subject_table. Resetting the hash table will also
5062 * destroy the containers.
5064 /* Step 3 */
5065 /* prune dummies, convert to threadnode */
5066 root = mail_thread_c2node (stream,mail_thread_prune_dummy (prc,NIL),flags);
5067 /* Step 4 */
5068 /* make buffer for sorting */
5069 tc = (THREADNODE **) fs_get (nmsgs * sizeof (THREADNODE *));
5070 /* load threadcache and count nodes to sort */
5071 for (i = 0, cur = root; cur ; cur = cur->branch) tc[i++] = cur;
5072 if (i > 1) { /* only if need to sort */
5073 qsort ((void *) tc,i,sizeof (THREADNODE *),mail_thread_compare_date);
5074 /* relink siblings */
5075 for (j = 0, --i; j < i; j++) tc[j]->branch = tc[j+1];
5076 tc[j]->branch = NIL; /* end of root */
5077 root = tc[0]; /* establish new root */
5079 /* Step 5A */
5080 hash_reset (ht); /* discard containers, reset ht */
5081 /* Step 5B */
5082 for (cur = root; cur; cur = cur->branch)
5083 if ((t = (nxt = (cur->sc ? cur : cur->next))->sc->subject) && *t) {
5084 /* add new subject to hash table */
5085 if (!(sub = hash_lookup (ht,t))) hash_add (ht,t,cur,0);
5086 /* if one in table not dummy and */
5087 else if ((s = (lst = (THREADNODE *) sub[0])->sc) &&
5088 /* current dummy, or not re/fwd and table is */
5089 (!cur->sc || (!nxt->sc->refwd && s->refwd)))
5090 sub[0] = (void *) cur; /* replace with this message */
5093 /* Step 5C */
5094 for (cur = root, sis = NIL; cur; cur = msg) {
5095 /* do nothing if current message or no sub */
5096 if (!(t = (cur->sc ? cur : cur->next)->sc->subject) || !*t ||
5097 ((lst = (THREADNODE *) (sub = hash_lookup (ht,t))[0]) == cur))
5098 msg = (sis = cur)->branch;
5099 else if (!lst->sc) { /* is message in the table a dummy? */
5100 /* find youngest daughter of msg in table */
5101 for (msg = lst->next; msg->branch; msg = msg->branch);
5102 if (!cur->sc) { /* current message a dummy? */
5103 msg->branch = cur->next;/* current's daughter now dummy's youngest */
5104 msg = cur->branch; /* continue scan at younger sister */
5105 /* now delete this node */
5106 cur->branch = cur->next = NIL;
5107 mail_free_threadnode (&cur);
5109 else { /* current message not a dummy */
5110 msg->branch = cur; /* append as youngest daughter */
5111 msg = cur->branch; /* continue scan at younger sister */
5112 cur->branch = NIL; /* lose our younger sisters */
5115 else { /* no dummies, is current re/fwd, table not? */
5116 if (cur->sc->refwd && !lst->sc->refwd) {
5117 if (lst->next) { /* find youngest daughter of msg in table */
5118 for (msg = lst->next; msg->branch; msg = msg->branch);
5119 msg->branch = cur; /* append as youngest daughter */
5121 else lst->next = cur; /* no children, so make the eldest daughter */
5124 else { /* no re/fwd, create a new dummy */
5125 msg = mail_newthreadnode (NIL);
5126 if (lst == root) { /* msg in table is root? */
5127 root = lst->branch; /* younger sister becomes new root */
5128 /* no longer older sister either */
5129 if (lst == sis) sis = NIL;
5131 else { /* find older sister of msg in table */
5132 for (nxt = root; lst != nxt->branch; nxt = nxt->branch);
5133 /* remove from older sister */
5134 nxt->branch = lst->branch;
5136 msg->next = lst; /* msg in table becomes child */
5137 lst->branch = cur; /* current now little sister of msg in table */
5138 if (sis) { /* have an elder sister? */
5139 if (sis == lst) /* rescan if lost her */
5140 for (sis = root; cur != sis->branch; sis = sis->branch);
5141 sis->branch = msg; /* make dummy younger sister of big sister */
5143 else root = msg; /* otherwise this is the new root */
5144 sub[0] = sis = msg; /* set new msg in table and new big sister */
5146 msg = cur->branch; /* continue scan at younger sister */
5147 cur->branch = NIL; /* lose our younger sisters */
5149 if (sis) sis->branch = msg; /* older sister gets this as younger sister */
5150 else root = msg; /* otherwise this is the new root */
5152 hash_destroy (&ht); /* finished with hash table */
5153 /* Step 6 */
5154 /* sort threads */
5155 root = mail_thread_sort (root,tc);
5156 fs_give ((void **) &tc); /* finished with sort buffer */
5157 return root; /* return sorted list */
5160 /* Fetch overview callback to load sortcache for threading
5161 * Accepts: MAIL stream
5162 * UID of this message
5163 * overview of this message
5164 * msgno of this message
5167 void mail_thread_loadcache (MAILSTREAM *stream,unsigned long uid,OVERVIEW *ov,
5168 unsigned long msgno)
5170 if (msgno && ov) { /* just in case */
5171 MESSAGECACHE telt, *elt;
5172 ENVELOPE *env;
5173 SORTCACHE *s = (SORTCACHE *) (*mailcache) (stream,msgno,CH_SORTCACHE);
5174 if (!s->subject && ov->subject) {
5175 s->refwd = mail_strip_subject (ov->subject,&s->subject);
5176 s->dirty = T;
5178 if (!s->from && ov->from && ov->from->mailbox) {
5179 s->from = cpystr (ov->from->mailbox);
5180 s->dirty = T;
5182 if (!s->date && ov->date && mail_parse_date (&telt,ov->date)) {
5183 s->date = mail_longdate (&telt);
5184 s->dirty = T;
5186 if (!s->message_id && ov->message_id) {
5187 s->message_id = mail_thread_parse_msgid (ov->message_id,NIL);
5188 s->dirty = T;
5190 if (!s->references &&
5191 !(s->references = mail_thread_parse_references (ov->references,T))
5192 && stream->dtb && !strcmp(stream->dtb->name, "imap")
5193 && (elt = mail_elt (stream, msgno)) != NULL
5194 && (env = elt->private.msg.env) != NULL
5195 && env->in_reply_to
5196 && !(s->references = mail_thread_parse_references(env->in_reply_to, NIL))) {
5197 /* don't do In-Reply-To with NNTP mailboxes */
5198 s->references = mail_newstringlist ();
5199 s->dirty = T;
5201 if (!s->size && ov->optional.octets) {
5202 s->size = ov->optional.octets;
5203 s->dirty = T;
5208 /* Thread parse Message ID
5209 * Accepts: pointer to purported Message ID
5210 * pointer to return pointer
5211 * Returns: Message ID or NIL, return pointer updated
5214 char *mail_thread_parse_msgid (char *s,char **ss)
5216 char *ret = NIL;
5217 char *t = NIL;
5218 ADDRESS *adr;
5219 if (s) { /* only for non-NIL strings */
5220 rfc822_skipws (&s); /* skip whitespace */
5221 /* ignore phrases */
5222 if (((*s == '<') || (s = rfc822_parse_phrase (s))) &&
5223 (adr = rfc822_parse_routeaddr (s,&t,BADHOST))) {
5224 /* make return msgid */
5225 if (adr->mailbox && adr->host)
5226 sprintf (ret = (char *) fs_get (strlen (adr->mailbox) +
5227 strlen (adr->host) + 2),"%s@%s",
5228 adr->mailbox,adr->host);
5229 mail_free_address (&adr); /* don't need temporary address */
5232 if (ss) *ss = t; /* update return pointer */
5233 return ret;
5237 /* Thread parse references
5238 * Accepts: pointer to purported references
5239 * parse multiple references flag
5240 * Returns: references or NIL
5243 STRINGLIST *mail_thread_parse_references (char *s,long flag)
5245 char *t;
5246 STRINGLIST *ret = NIL;
5247 STRINGLIST *cur;
5248 /* found first reference? */
5249 if ((t = mail_thread_parse_msgid (s,&s)) != NULL) {
5250 (ret = mail_newstringlist ())->text.data = (unsigned char *) t;
5251 ret->text.size = strlen (t);
5252 if (flag) /* parse subsequent references */
5253 for (cur = ret; (t = mail_thread_parse_msgid (s,&s)) != NULL; cur = cur->next) {
5254 (cur->next = mail_newstringlist ())->text.data = (unsigned char *) t;
5255 cur->next->text.size = strlen (t);
5258 return ret;
5261 /* Prune dummy messages
5262 * Accepts: candidate container to prune
5263 * older sibling of container, if any
5264 * Returns: container in this position, possibly pruned
5265 * All children and younger siblings are also pruned
5268 container_t mail_thread_prune_dummy (container_t msg,container_t ane)
5270 /* prune container and children */
5271 container_t ret = msg ? mail_thread_prune_dummy_work (msg,ane) : NIL;
5272 /* prune all younger sisters */
5273 if (ret) for (ane = ret; ane && (msg = SIBLING (ane)); ane = msg)
5274 msg = mail_thread_prune_dummy_work (msg,ane);
5275 return ret;
5279 /* Prune dummy messages worker routine
5280 * Accepts: candidate container to prune
5281 * older sibling of container, if any
5282 * Returns: container in this position, possibly pruned
5283 * All children are also pruned
5286 container_t mail_thread_prune_dummy_work (container_t msg,container_t ane)
5288 container_t cur;
5289 /* get children, if any */
5290 container_t nxt = mail_thread_prune_dummy (CHILD (msg),NIL);
5291 /* just update children if container has msg */
5292 if (CACHE (msg)) SETCHILD (msg,nxt);
5293 else if (!nxt) { /* delete dummy with no children */
5294 nxt = SIBLING (msg); /* get younger sister */
5295 if (ane) SETSIBLING (ane,nxt);
5296 /* prune younger sister if exists */
5297 msg = nxt ? mail_thread_prune_dummy_work (nxt,ane) : NIL;
5299 /* not if parent root & multiple children */
5300 else if ((cur = PARENT (msg)) || !SIBLING (nxt)) {
5301 /* OK to promote, try younger sister of aunt */
5302 if (ane) SETSIBLING (ane,nxt);
5303 /* otherwise promote to child of grandmother */
5304 else if (cur) SETCHILD (cur,nxt);
5305 SETPARENT (nxt,cur); /* set parent as well */
5306 /* look for end of siblings in new container */
5307 for (cur = nxt; SIBLING (cur); cur = SIBLING (cur));
5308 /* reattach deleted container's siblings */
5309 SETSIBLING (cur,SIBLING (msg));
5310 /* prune and return new container */
5311 msg = mail_thread_prune_dummy_work (nxt,ane);
5313 else SETCHILD (msg,nxt); /* in case child pruned */
5314 return msg; /* return this message */
5317 /* Test that purported mother is not a child of purported daughter
5318 * Accepts: mother
5319 * purported daugher
5320 * Returns: T if circular parentage exists, else NIL
5323 long mail_thread_check_child (container_t mother,container_t daughter)
5325 if (mother) { /* only if mother non-NIL */
5326 if (mother == daughter) return T;
5327 for (daughter = CHILD (daughter); daughter; daughter = SIBLING (daughter))
5328 if (mail_thread_check_child (mother,daughter)) return T;
5330 return NIL;
5334 /* Generate threadnodes from containers
5335 * Accepts: Mail stream
5336 * container
5337 * flags
5338 * Return: threadnode list
5341 THREADNODE *mail_thread_c2node (MAILSTREAM *stream,container_t con,long flags)
5343 THREADNODE *ret,*cur;
5344 SORTCACHE *s;
5345 container_t nxt;
5346 /* for each container */
5347 for (ret = cur = NIL; con; con = SIBLING (con)) {
5348 s = CACHE (con); /* yes, get its sortcache */
5349 /* create node for it */
5350 if (ret) cur = cur->branch = mail_newthreadnode (s);
5351 else ret = cur = mail_newthreadnode (s);
5352 /* attach sequence or UID for non-dummy */
5353 if (s) cur->num = (flags & SE_UID) ? mail_uid (stream,s->num) : s->num;
5354 /* attach the children */
5355 if ((nxt = CHILD (con)) != NULL) cur->next = mail_thread_c2node (stream,nxt,flags);
5357 return ret;
5360 /* Sort thread tree by date
5361 * Accepts: thread tree to sort
5362 * qsort vector to sort
5363 * Returns: sorted thread tree
5366 THREADNODE *mail_thread_sort (THREADNODE *thr,THREADNODE **tc)
5368 unsigned long i,j;
5369 THREADNODE *cur;
5370 /* sort children of each thread */
5371 for (cur = thr; cur; cur = cur->branch)
5372 if (cur->next) cur->next = mail_thread_sort (cur->next,tc);
5373 /* Must do this in a separate pass since recursive call will clobber tc */
5374 /* load threadcache and count nodes to sort */
5375 for (i = 0, cur = thr; cur; cur = cur->branch) tc[i++] = cur;
5376 if (i > 1) { /* only if need to sort */
5377 qsort ((void *) tc,i,sizeof (THREADNODE *),mail_thread_compare_date);
5378 /* relink root siblings */
5379 for (j = 0, --i; j < i; j++) tc[j]->branch = tc[j+1];
5380 tc[j]->branch = NIL; /* end of root */
5382 return i ? tc[0] : NIL; /* return new head of list */
5386 /* Thread compare date
5387 * Accept: first message sort cache element
5388 * second message sort cache element
5389 * Returns: -1 if a1 < a2, 1 if a1 > a2
5391 * This assumes that a sort cache element is either a message (with a
5392 * sortcache entry) or a dummy with a message (with sortcache entry) child.
5393 * This is true of both the ORDEREDSUBJECT (no dummies) and REFERENCES
5394 * (dummies only at top-level, and with non-dummy children).
5396 * If a new algorithm allows a dummy parent to have a dummy child, this
5397 * routine must be changed if it is to be used by that algorithm.
5399 * Messages with bogus dates are always sorted at the top.
5402 int mail_thread_compare_date (const void *a1,const void *a2)
5404 THREADNODE *t1 = *(THREADNODE **) a1;
5405 THREADNODE *t2 = *(THREADNODE **) a2;
5406 SORTCACHE *s1 = t1->sc ? t1->sc : t1->next->sc;
5407 SORTCACHE *s2 = t2->sc ? t2->sc : t2->next->sc;
5408 int ret = compare_ulong (s1->date,s2->date);
5409 /* use number as final tie-breaker */
5410 return ret ? ret : compare_ulong (s1->num,s2->num);
5413 /* Mail parse sequence
5414 * Accepts: mail stream
5415 * sequence to parse
5416 * Returns: T if parse successful, else NIL
5419 long mail_sequence (MAILSTREAM *stream,unsigned char *sequence)
5421 unsigned long i,j,x;
5422 for (i = 1; i <= stream->nmsgs; i++) mail_elt (stream,i)->sequence = NIL;
5423 while (sequence && *sequence){/* while there is something to parse */
5424 if (*sequence == '*') { /* maximum message */
5425 if (stream->nmsgs) i = stream->nmsgs;
5426 else {
5427 MM_LOG ("No messages, so no maximum message number",ERROR);
5428 return NIL;
5430 sequence++; /* skip past * */
5432 /* parse and validate message number */
5433 else if (!isdigit (*sequence)) {
5434 MM_LOG ("Syntax error in sequence",ERROR);
5435 return NIL;
5437 else if (!(i = strtoul (sequence,(char **) &sequence,10)) ||
5438 (i > stream->nmsgs)) {
5439 MM_LOG ("Sequence out of range",ERROR);
5440 return NIL;
5442 switch (*sequence) { /* see what the delimiter is */
5443 case ':': /* sequence range */
5444 if (*++sequence == '*') { /* maximum message */
5445 if (stream->nmsgs) j = stream->nmsgs;
5446 else {
5447 MM_LOG ("No messages, so no maximum message number",ERROR);
5448 return NIL;
5450 sequence++; /* skip past * */
5452 /* parse end of range */
5453 else if (!(j = strtoul (sequence,(char **) &sequence,10)) ||
5454 (j > stream->nmsgs)) {
5455 MM_LOG ("Sequence range invalid",ERROR);
5456 return NIL;
5458 if (*sequence && *sequence++ != ',') {
5459 MM_LOG ("Sequence range syntax error",ERROR);
5460 return NIL;
5462 if (i > j) { /* swap the range if backwards */
5463 x = i; i = j; j = x;
5465 /* mark each item in the sequence */
5466 while (i <= j) mail_elt (stream,j--)->sequence = T;
5467 break;
5468 case ',': /* single message */
5469 ++sequence; /* skip the delimiter, fall into end case */
5470 case '\0': /* end of sequence, mark this message */
5471 mail_elt (stream,i)->sequence = T;
5472 break;
5473 default: /* anything else is a syntax error! */
5474 MM_LOG ("Sequence syntax error",ERROR);
5475 return NIL;
5478 return T; /* successfully parsed sequence */
5481 /* Parse flag list
5482 * Accepts: MAIL stream
5483 * flag list as a character string
5484 * pointer to user flags to return
5485 * Returns: system flags
5488 long mail_parse_flags (MAILSTREAM *stream,char *flag,unsigned long *uf)
5490 char *t,*n,*s,tmp[MAILTMPLEN],msg[MAILTMPLEN];
5491 short f = 0;
5492 long i,j;
5493 *uf = 0; /* initially no user flags */
5494 if (flag && *flag) { /* no-op if no flag string */
5495 /* check if a list and make sure valid */
5496 if (((i = (*flag == '(')) ^ (flag[strlen (flag)-1] == ')')) ||
5497 (strlen (flag) >= MAILTMPLEN)) {
5498 MM_LOG ("Bad flag list",ERROR);
5499 return NIL;
5501 /* copy the flag string w/o list construct */
5502 strncpy (n = tmp,flag+i,(j = strlen (flag) - (2*i)));
5503 tmp[j] = '\0';
5504 while ((t = n) && *t) { /* parse the flags */
5505 /* find end of flag */
5506 if ((n = strchr (t,' ')) != NULL) *n++ = '\0';
5507 if (*t == '\\') { /* system flag? */
5508 if (!compare_cstring (t+1,"SEEN")) f |= fSEEN;
5509 else if (!compare_cstring (t+1,"DELETED")) f |= fDELETED;
5510 else if (!compare_cstring (t+1,"FLAGGED")) f |= fFLAGGED;
5511 else if (!compare_cstring (t+1,"ANSWERED")) f |= fANSWERED;
5512 else if (!compare_cstring (t+1,"DRAFT")) f |= fDRAFT;
5513 else {
5514 sprintf (msg,"Unsupported system flag: %.80s",t);
5515 MM_LOG (msg,WARN);
5519 else { /* keyword flag */
5520 for (i = j = 0; /* user flag, search through table */
5521 !i && (j < NUSERFLAGS) && (s = stream->user_flags[j]); ++j)
5522 if (!compare_cstring (t,s)) *uf |= i = 1 << j;
5523 if (!i) { /* flag not found, can it be created? */
5524 if (stream->kwd_create && (j < NUSERFLAGS) && *t &&
5525 (strlen (t) <= MAXUSERFLAG)) {
5526 for (s = t; t && *s; s++) switch (*s) {
5527 default: /* all other characters */
5528 /* SPACE, CTL, or not CHAR */
5529 if ((*s > ' ') && (*s < 0x7f)) break;
5530 case '*': case '%': /* list_wildcards */
5531 case '"': case '\\':/* quoted-specials */
5532 /* atom_specials */
5533 case '(': case ')': case '{':
5534 case ']': /* resp-specials */
5535 sprintf (msg,"Invalid flag: %.80s",t);
5536 MM_LOG (msg,WARN);
5537 t = NIL;
5539 if (t) { /* only if valid */
5540 *uf |= 1 << j; /* set the bit */
5541 stream->user_flags[j] = cpystr (t);
5542 /* if out of user flags */
5543 if (j == NUSERFLAGS - 1) stream->kwd_create = NIL;
5546 else {
5547 if (*t) sprintf (msg,"Unknown flag: %.80s",t);
5548 else strcpy (msg,"Empty flag invalid");
5549 MM_LOG (msg,WARN);
5555 return f;
5558 /* Mail check network stream for usability with new name
5559 * Accepts: MAIL stream
5560 * candidate new name
5561 * Returns: T if stream can be used, NIL otherwise
5564 long mail_usable_network_stream (MAILSTREAM *stream,char *name)
5566 NETMBX smb,nmb,omb;
5567 char *s = NIL;
5568 long ret= (stream && stream->dtb && !(stream->dtb->flags & DR_LOCAL) &&
5569 mail_valid_net_parse (name,&nmb) &&
5570 mail_valid_net_parse (stream->mailbox,&smb) &&
5571 mail_valid_net_parse (stream->original_mailbox,&omb) &&
5572 ((!compare_cstring (smb.host,trustdns ?
5573 (s = tcp_canonical (nmb.host)) : nmb.host) &&
5574 !strcmp (smb.service,nmb.service) &&
5575 (!nmb.port || (smb.port == nmb.port)) &&
5576 (nmb.anoflag == stream->anonymous) &&
5577 (!nmb.user[0] || !strcmp (smb.user,nmb.user))) ||
5578 (!compare_cstring (omb.host,nmb.host) &&
5579 !strcmp (omb.service,nmb.service) &&
5580 (!nmb.port || (omb.port == nmb.port)) &&
5581 (nmb.anoflag == stream->anonymous) &&
5582 (!nmb.user[0] || !strcmp (omb.user,nmb.user))))) ? LONGT : NIL;
5583 if(s) fs_give((void **) &s);
5584 return ret;
5587 /* Mail data structure instantiation routines */
5590 /* Mail instantiate cache elt
5591 * Accepts: initial message number
5592 * Returns: new cache elt
5595 MESSAGECACHE *mail_new_cache_elt (unsigned long msgno)
5597 MESSAGECACHE *elt = (MESSAGECACHE *) memset (fs_get (sizeof (MESSAGECACHE)),
5598 0,sizeof (MESSAGECACHE));
5599 elt->lockcount = 1; /* initially only cache references it */
5600 elt->msgno = msgno; /* message number */
5601 return elt;
5605 /* Mail instantiate envelope
5606 * Returns: new envelope
5609 ENVELOPE *mail_newenvelope (void)
5611 return (ENVELOPE *) memset (fs_get (sizeof (ENVELOPE)),0,sizeof (ENVELOPE));
5615 /* Mail instantiate address
5616 * Returns: new address
5619 ADDRESS *mail_newaddr (void)
5621 return (ADDRESS *) memset (fs_get (sizeof (ADDRESS)),0,sizeof (ADDRESS));
5624 /* Mail instantiate body
5625 * Returns: new body
5628 BODY *mail_newbody (void)
5630 return mail_initbody ((BODY *) fs_get (sizeof (BODY)));
5634 /* Mail initialize body
5635 * Accepts: body
5636 * Returns: body
5639 BODY *mail_initbody (BODY *body)
5641 memset ((void *) body,0,sizeof (BODY));
5642 body->type = TYPETEXT; /* content type */
5643 body->encoding = ENC7BIT; /* content encoding */
5644 return body;
5648 /* Mail instantiate body parameter
5649 * Returns: new body part
5652 PARAMETER *mail_newbody_parameter (void)
5654 return (PARAMETER *) memset (fs_get (sizeof(PARAMETER)),0,sizeof(PARAMETER));
5658 /* Mail instantiate body part
5659 * Returns: new body part
5662 PART *mail_newbody_part (void)
5664 PART *part = (PART *) memset (fs_get (sizeof (PART)),0,sizeof (PART));
5665 mail_initbody (&part->body); /* initialize the body */
5666 return part;
5670 /* Mail instantiate body message part
5671 * Returns: new body message part
5674 MESSAGE *mail_newmsg (void)
5676 return (MESSAGE *) memset (fs_get (sizeof (MESSAGE)),0,sizeof (MESSAGE));
5679 /* Mail instantiate string list
5680 * Returns: new string list
5683 STRINGLIST *mail_newstringlist (void)
5685 return (STRINGLIST *) memset (fs_get (sizeof (STRINGLIST)),0,
5686 sizeof (STRINGLIST));
5690 /* Mail instantiate new search program
5691 * Returns: new search program
5694 SEARCHPGM *mail_newsearchpgm (void)
5696 return (SEARCHPGM *) memset (fs_get (sizeof(SEARCHPGM)),0,sizeof(SEARCHPGM));
5700 /* Mail instantiate new search program
5701 * Accepts: header line name
5702 * Returns: new search program
5705 SEARCHHEADER *mail_newsearchheader (char *line,char *text)
5707 SEARCHHEADER *hdr = (SEARCHHEADER *) memset (fs_get (sizeof (SEARCHHEADER)),
5708 0,sizeof (SEARCHHEADER));
5709 hdr->line.size = strlen ((char *) (hdr->line.data =
5710 (unsigned char *) cpystr (line)));
5711 hdr->text.size = strlen ((char *) (hdr->text.data =
5712 (unsigned char *) cpystr (text)));
5713 return hdr;
5717 /* Mail instantiate new search set
5718 * Returns: new search set
5721 SEARCHSET *mail_newsearchset (void)
5723 return (SEARCHSET *) memset (fs_get (sizeof(SEARCHSET)),0,sizeof(SEARCHSET));
5727 /* Mail instantiate new search or
5728 * Returns: new search or
5731 SEARCHOR *mail_newsearchor (void)
5733 SEARCHOR *or = (SEARCHOR *) memset (fs_get (sizeof (SEARCHOR)),0,
5734 sizeof (SEARCHOR));
5735 or->first = mail_newsearchpgm ();
5736 or->second = mail_newsearchpgm ();
5737 return or;
5740 /* Mail instantiate new searchpgmlist
5741 * Returns: new searchpgmlist
5744 SEARCHPGMLIST *mail_newsearchpgmlist (void)
5746 SEARCHPGMLIST *pgl = (SEARCHPGMLIST *)
5747 memset (fs_get (sizeof (SEARCHPGMLIST)),0,sizeof (SEARCHPGMLIST));
5748 pgl->pgm = mail_newsearchpgm ();
5749 return pgl;
5753 /* Mail instantiate new sortpgm
5754 * Returns: new sortpgm
5757 SORTPGM *mail_newsortpgm (void)
5759 return (SORTPGM *) memset (fs_get (sizeof (SORTPGM)),0,sizeof (SORTPGM));
5763 /* Mail instantiate new threadnode
5764 * Accepts: sort cache for thread node
5765 * Returns: new threadnode
5768 THREADNODE *mail_newthreadnode (SORTCACHE *sc)
5770 THREADNODE *thr = (THREADNODE *) memset (fs_get (sizeof (THREADNODE)),0,
5771 sizeof (THREADNODE));
5772 if (sc) thr->sc = sc; /* initialize sortcache */
5773 return thr;
5777 /* Mail instantiate new acllist
5778 * Returns: new acllist
5781 ACLLIST *mail_newacllist (void)
5783 return (ACLLIST *) memset (fs_get (sizeof (ACLLIST)),0,sizeof (ACLLIST));
5787 /* Mail instantiate new quotalist
5788 * Returns: new quotalist
5791 QUOTALIST *mail_newquotalist (void)
5793 return (QUOTALIST *) memset (fs_get (sizeof (QUOTALIST)),0,
5794 sizeof (QUOTALIST));
5797 /* Mail garbage collection routines */
5800 /* Mail garbage collect body
5801 * Accepts: pointer to body pointer
5804 void mail_free_body (BODY **body)
5806 if (*body) { /* only free if exists */
5807 mail_free_body_data (*body);/* free its data */
5808 fs_give ((void **) body); /* return body to free storage */
5813 /* Mail garbage collect body data
5814 * Accepts: body pointer
5817 void mail_free_body_data (BODY *body)
5819 switch (body->type) { /* free contents */
5820 case TYPEMULTIPART: /* multiple part */
5821 mail_free_body_part (&body->nested.part);
5822 break;
5823 case TYPEMESSAGE: /* encapsulated message */
5824 if (body->subtype && !strcmp (body->subtype,"RFC822")) {
5825 mail_free_stringlist (&body->nested.msg->lines);
5826 mail_gc_msg (body->nested.msg,GC_ENV | GC_TEXTS);
5828 if (body->nested.msg) fs_give ((void **) &body->nested.msg);
5829 break;
5830 default:
5831 break;
5833 if (body->subtype) fs_give ((void **) &body->subtype);
5834 mail_free_body_parameter (&body->parameter);
5835 if (body->id) fs_give ((void **) &body->id);
5836 if (body->description) fs_give ((void **) &body->description);
5837 if (body->disposition.type) fs_give ((void **) &body->disposition.type);
5838 if (body->disposition.parameter)
5839 mail_free_body_parameter (&body->disposition.parameter);
5840 if (body->language) mail_free_stringlist (&body->language);
5841 if (body->location) fs_give ((void **) &body->location);
5842 if (body->mime.text.data) fs_give ((void **) &body->mime.text.data);
5843 if (body->contents.text.data) fs_give ((void **) &body->contents.text.data);
5844 if (body->md5) fs_give ((void **) &body->md5);
5845 if (mailfreebodysparep && body->sparep)
5846 (*mailfreebodysparep) (&body->sparep);
5849 /* Mail garbage collect body parameter
5850 * Accepts: pointer to body parameter pointer
5853 void mail_free_body_parameter (PARAMETER **parameter)
5855 if (*parameter) { /* only free if exists */
5856 if ((*parameter)->attribute) fs_give ((void **) &(*parameter)->attribute);
5857 if ((*parameter)->value) fs_give ((void **) &(*parameter)->value);
5858 /* run down the list as necessary */
5859 mail_free_body_parameter (&(*parameter)->next);
5860 /* return body part to free storage */
5861 fs_give ((void **) parameter);
5866 /* Mail garbage collect body part
5867 * Accepts: pointer to body part pointer
5870 void mail_free_body_part (PART **part)
5872 if (*part) { /* only free if exists */
5873 mail_free_body_data (&(*part)->body);
5874 /* run down the list as necessary */
5875 mail_free_body_part (&(*part)->next);
5876 fs_give ((void **) part); /* return body part to free storage */
5880 /* Mail garbage collect message cache
5881 * Accepts: mail stream
5883 * The message cache is set to NIL when this function finishes.
5886 void mail_free_cache (MAILSTREAM *stream)
5888 /* do driver specific stuff first */
5889 mail_gc (stream,GC_ELT | GC_ENV | GC_TEXTS);
5890 /* flush the cache */
5891 (*mailcache) (stream,(long) 0,CH_INIT);
5895 /* Mail garbage collect cache element
5896 * Accepts: pointer to cache element pointer
5899 void mail_free_elt (MESSAGECACHE **elt)
5901 /* only free if exists and no sharers */
5902 if (*elt && !--(*elt)->lockcount) {
5903 mail_gc_msg (&(*elt)->private.msg,GC_ENV | GC_TEXTS);
5904 if (mailfreeeltsparep && (*elt)->sparep)
5905 (*mailfreeeltsparep) (&(*elt)->sparep);
5906 fs_give ((void **) elt);
5908 else *elt = NIL; /* else simply drop pointer */
5911 /* Mail garbage collect envelope
5912 * Accepts: pointer to envelope pointer
5915 void mail_free_envelope (ENVELOPE **env)
5917 if (*env) { /* only free if exists */
5918 if ((*env)->remail) fs_give ((void **) &(*env)->remail);
5919 mail_free_address (&(*env)->return_path);
5920 if ((*env)->date) fs_give ((void **) &(*env)->date);
5921 mail_free_address (&(*env)->from);
5922 mail_free_address (&(*env)->sender);
5923 mail_free_address (&(*env)->reply_to);
5924 if ((*env)->subject) fs_give ((void **) &(*env)->subject);
5925 mail_free_address (&(*env)->to);
5926 mail_free_address (&(*env)->cc);
5927 mail_free_address (&(*env)->bcc);
5928 if ((*env)->in_reply_to) fs_give ((void **) &(*env)->in_reply_to);
5929 if ((*env)->message_id) fs_give ((void **) &(*env)->message_id);
5930 if ((*env)->newsgroups) fs_give ((void **) &(*env)->newsgroups);
5931 if ((*env)->followup_to) fs_give ((void **) &(*env)->followup_to);
5932 if ((*env)->references) fs_give ((void **) &(*env)->references);
5933 if (mailfreeenvelopesparep && (*env)->sparep)
5934 (*mailfreeenvelopesparep) (&(*env)->sparep);
5935 fs_give ((void **) env); /* return envelope to free storage */
5940 /* Mail garbage collect address
5941 * Accepts: pointer to address pointer
5944 void mail_free_address (ADDRESS **address)
5946 if (*address) { /* only free if exists */
5947 if ((*address)->personal) fs_give ((void **) &(*address)->personal);
5948 if ((*address)->adl) fs_give ((void **) &(*address)->adl);
5949 if ((*address)->mailbox) fs_give ((void **) &(*address)->mailbox);
5950 if ((*address)->host) fs_give ((void **) &(*address)->host);
5951 if ((*address)->error) fs_give ((void **) &(*address)->error);
5952 if ((*address)->orcpt.type) fs_give ((void **) &(*address)->orcpt.type);
5953 if ((*address)->orcpt.addr) fs_give ((void **) &(*address)->orcpt.addr);
5954 mail_free_address (&(*address)->next);
5955 fs_give ((void **) address);/* return address to free storage */
5960 /* Mail garbage collect stringlist
5961 * Accepts: pointer to stringlist pointer
5964 void mail_free_stringlist (STRINGLIST **string)
5966 if (*string) { /* only free if exists */
5967 if ((*string)->text.data) fs_give ((void **) &(*string)->text.data);
5968 mail_free_stringlist (&(*string)->next);
5969 fs_give ((void **) string); /* return string to free storage */
5973 /* Mail garbage collect searchpgm
5974 * Accepts: pointer to searchpgm pointer
5977 void mail_free_searchpgm (SEARCHPGM **pgm)
5979 if (*pgm) { /* only free if exists */
5980 mail_free_searchset (&(*pgm)->msgno);
5981 mail_free_searchset (&(*pgm)->uid);
5982 mail_free_searchor (&(*pgm)->or);
5983 mail_free_searchpgmlist (&(*pgm)->not);
5984 mail_free_searchheader (&(*pgm)->header);
5985 mail_free_stringlist (&(*pgm)->bcc);
5986 mail_free_stringlist (&(*pgm)->body);
5987 mail_free_stringlist (&(*pgm)->cc);
5988 mail_free_stringlist (&(*pgm)->from);
5989 mail_free_stringlist (&(*pgm)->keyword);
5990 mail_free_stringlist (&(*pgm)->subject);
5991 mail_free_stringlist (&(*pgm)->text);
5992 mail_free_stringlist (&(*pgm)->to);
5993 fs_give ((void **) pgm); /* return program to free storage */
5998 /* Mail garbage collect searchheader
5999 * Accepts: pointer to searchheader pointer
6002 void mail_free_searchheader (SEARCHHEADER **hdr)
6004 if (*hdr) { /* only free if exists */
6005 if ((*hdr)->line.data) fs_give ((void **) &(*hdr)->line.data);
6006 if ((*hdr)->text.data) fs_give ((void **) &(*hdr)->text.data);
6007 mail_free_searchheader (&(*hdr)->next);
6008 fs_give ((void **) hdr); /* return header to free storage */
6013 /* Mail garbage collect searchset
6014 * Accepts: pointer to searchset pointer
6017 void mail_free_searchset (SEARCHSET **set)
6019 if (*set) { /* only free if exists */
6020 mail_free_searchset (&(*set)->next);
6021 fs_give ((void **) set); /* return set to free storage */
6025 /* Mail garbage collect searchor
6026 * Accepts: pointer to searchor pointer
6029 void mail_free_searchor (SEARCHOR **orl)
6031 if (*orl) { /* only free if exists */
6032 mail_free_searchpgm (&(*orl)->first);
6033 mail_free_searchpgm (&(*orl)->second);
6034 mail_free_searchor (&(*orl)->next);
6035 fs_give ((void **) orl); /* return searchor to free storage */
6040 /* Mail garbage collect search program list
6041 * Accepts: pointer to searchpgmlist pointer
6044 void mail_free_searchpgmlist (SEARCHPGMLIST **pgl)
6046 if (*pgl) { /* only free if exists */
6047 mail_free_searchpgm (&(*pgl)->pgm);
6048 mail_free_searchpgmlist (&(*pgl)->next);
6049 fs_give ((void **) pgl); /* return searchpgmlist to free storage */
6054 /* Mail garbage collect namespace
6055 * Accepts: poiner to namespace
6058 void mail_free_namespace (NAMESPACE **n)
6060 if (*n) {
6061 fs_give ((void **) &(*n)->name);
6062 mail_free_namespace (&(*n)->next);
6063 mail_free_body_parameter (&(*n)->param);
6064 fs_give ((void **) n); /* return namespace to free storage */
6068 /* Mail garbage collect sort program
6069 * Accepts: pointer to sortpgm pointer
6072 void mail_free_sortpgm (SORTPGM **pgm)
6074 if (*pgm) { /* only free if exists */
6075 mail_free_sortpgm (&(*pgm)->next);
6076 fs_give ((void **) pgm); /* return sortpgm to free storage */
6081 /* Mail garbage collect thread node
6082 * Accepts: pointer to threadnode pointer
6085 void mail_free_threadnode (THREADNODE **thr)
6087 if (*thr) { /* only free if exists */
6088 mail_free_threadnode (&(*thr)->branch);
6089 mail_free_threadnode (&(*thr)->next);
6090 fs_give ((void **) thr); /* return threadnode to free storage */
6095 /* Mail garbage collect acllist
6096 * Accepts: pointer to acllist pointer
6099 void mail_free_acllist (ACLLIST **al)
6101 if (*al) { /* only free if exists */
6102 if ((*al)->identifier) fs_give ((void **) &(*al)->identifier);
6103 if ((*al)->rights) fs_give ((void **) &(*al)->rights);
6104 mail_free_acllist (&(*al)->next);
6105 fs_give ((void **) al); /* return acllist to free storage */
6110 /* Mail garbage collect quotalist
6111 * Accepts: pointer to quotalist pointer
6114 void mail_free_quotalist (QUOTALIST **ql)
6116 if (*ql) { /* only free if exists */
6117 if ((*ql)->name) fs_give ((void **) &(*ql)->name);
6118 mail_free_quotalist (&(*ql)->next);
6119 fs_give ((void **) ql); /* return quotalist to free storage */
6123 /* Link authenicator
6124 * Accepts: authenticator to add to list
6127 void auth_link (AUTHENTICATOR *auth)
6129 if (!auth->valid || (*auth->valid) ()) {
6130 AUTHENTICATOR **a = &mailauthenticators;
6131 while (*a) a = &(*a)->next; /* find end of list of authenticators */
6132 *a = auth; /* put authenticator at the end */
6133 auth->next = NIL; /* this authenticator is the end of the list */
6138 /* Authenticate access
6139 * Accepts: mechanism name
6140 * responder function
6141 * argument count
6142 * argument vector
6143 * Returns: authenticated user name or NIL
6146 char *mail_auth (char *mechanism,authresponse_t resp,int argc,char *argv[])
6148 AUTHENTICATOR *auth;
6149 for (auth = mailauthenticators; auth; auth = auth->next)
6150 if (auth->server && !compare_cstring (auth->name,mechanism))
6151 return (!(auth->flags & AU_DISABLE) &&
6152 ((auth->flags & AU_SECURE) ||
6153 !mail_parameters (NIL,GET_DISABLEPLAINTEXT,NIL))) ?
6154 (*auth->server) (resp,argc,argv) : NIL;
6155 return NIL; /* no authenticator found */
6158 /* Lookup authenticator index
6159 * Accepts: authenticator index
6160 * Returns: authenticator, or 0 if not found
6163 AUTHENTICATOR *mail_lookup_auth (unsigned long i)
6165 AUTHENTICATOR *auth = mailauthenticators;
6166 while (auth && --i) auth = auth->next;
6167 return auth;
6171 /* Lookup authenticator name
6172 * Accepts: authenticator name
6173 * required authenticator flags
6174 * Returns: index in authenticator chain, or 0 if not found
6177 unsigned int mail_lookup_auth_name (char *mechanism,long flags)
6179 int i;
6180 AUTHENTICATOR *auth;
6181 for (i = 1, auth = mailauthenticators; auth; i++, auth = auth->next)
6182 if (auth->client && !(flags & ~auth->flags) &&
6183 !(auth->flags & AU_DISABLE) && !compare_cstring (auth->name,mechanism))
6184 return i;
6185 return 0;
6188 /* Standard TCP/IP network driver */
6190 static NETDRIVER tcpdriver = {
6191 tcp_open, /* open connection */
6192 tcp_aopen, /* open preauthenticated connection */
6193 tcp_getline, /* get a line */
6194 tcp_getbuffer, /* get a buffer */
6195 tcp_soutr, /* output pushed data */
6196 tcp_sout, /* output string */
6197 tcp_close, /* close connection */
6198 tcp_host, /* return host name */
6199 tcp_remotehost, /* return remote host name */
6200 tcp_port, /* return port number */
6201 tcp_localhost /* return local host name */
6205 /* Network open
6206 * Accepts: NETMBX specifier to open
6207 * default network driver
6208 * default port
6209 * SSL driver
6210 * SSL service name
6211 * SSL driver port
6212 * Returns: Network stream if success, else NIL
6215 NETSTREAM *net_open (NETMBX *mb,NETDRIVER *dv,unsigned long port,
6216 NETDRIVER *ssld,char *ssls,unsigned long sslp)
6218 NETSTREAM *stream = NIL;
6219 char tmp[MAILTMPLEN];
6220 unsigned long flags = mb->novalidate ? NET_NOVALIDATECERT : 0;
6221 flags |= mb->tls1 || mb->tlsflag ? NET_TRYTLS1 : 0;
6222 flags |= mb->tls1_1 ? NET_TRYTLS1_1 : 0;
6223 flags |= mb->tls1_2 ? NET_TRYTLS1_2 : 0;
6224 flags |= mb->dtls1 ? NET_TRYDTLS1 : 0;
6225 if (strlen (mb->host) >= NETMAXHOST) {
6226 sprintf (tmp,"Invalid host name: %.80s",mb->host);
6227 MM_LOG (tmp,ERROR);
6229 /* use designated driver if given */
6230 else if (dv) stream = net_open_work (dv,mb->host,mb->service,port,mb->port,
6231 flags);
6232 else if (mb->sslflag && ssld) /* use ssl if sslflag lit */
6233 stream = net_open_work (ssld,mb->host,ssls,sslp,mb->port,flags);
6234 /* if trysslfirst and can open ssl... */
6235 else if ((mb->trysslflag || trysslfirst) && ssld &&
6236 (stream = net_open_work (ssld,mb->host,ssls,sslp,mb->port,
6237 flags | NET_SILENT | NET_TRYSSL))) {
6238 if (net_sout (stream,"",0)) mb->sslflag = T;
6239 else {
6240 net_close (stream); /* flush fake SSL stream */
6241 stream = NIL;
6244 /* default to TCP driver */
6245 else stream = net_open_work (&tcpdriver,mb->host,mb->service,port,mb->port,
6246 flags);
6247 return stream;
6250 /* Network open worker routine
6251 * Accepts: network driver
6252 * host name
6253 * service name to look up port
6254 * port number if service name not found
6255 * port number to override service name
6256 * flags (passed on top of port)
6257 * Returns: Network stream if success, else NIL
6260 NETSTREAM *net_open_work (NETDRIVER *dv,char *host,char *service,
6261 unsigned long port,unsigned long portoverride,
6262 unsigned long flags)
6264 NETSTREAM *stream = NIL;
6265 void *tstream;
6266 if (service && (*service == '*')) {
6267 flags |= NET_NOOPENTIMEOUT; /* mark that no timeout is desired */
6268 ++service; /* no longer need the no timeout indicator */
6270 if (portoverride) { /* explicit port number? */
6271 service = NIL; /* yes, override service name */
6272 port = portoverride; /* use that instead of default port */
6274 if ((tstream = (*dv->open) (host,service,port | flags)) != NULL){
6275 stream = (NETSTREAM *) fs_get (sizeof (NETSTREAM));
6276 stream->stream = tstream;
6277 stream->dtb = dv;
6279 return stream;
6283 /* Network authenticated open
6284 * Accepts: network driver
6285 * NETMBX specifier
6286 * service specifier
6287 * return user name buffer
6288 * Returns: Network stream if success else NIL
6291 NETSTREAM *net_aopen (NETDRIVER *dv,NETMBX *mb,char *service,char *user)
6293 NETSTREAM *stream = NIL;
6294 void *tstream;
6295 if (!dv) dv = &tcpdriver; /* default to TCP driver */
6296 if ((tstream = (*dv->aopen) (mb,service,user)) != NULL) {
6297 stream = (NETSTREAM *) fs_get (sizeof (NETSTREAM));
6298 stream->stream = tstream;
6299 stream->dtb = dv;
6301 return stream;
6304 /* Network receive line
6305 * Accepts: Network stream
6306 * Returns: text line string or NIL if failure
6309 char *net_getline (NETSTREAM *stream)
6311 return (*stream->dtb->getline) (stream->stream);
6315 /* Network receive buffer
6316 * Accepts: Network stream (must be void * for use as readfn_t)
6317 * size in bytes
6318 * buffer to read into
6319 * Returns: T if success, NIL otherwise
6322 long net_getbuffer (void *st,unsigned long size,char *buffer)
6324 NETSTREAM *stream = (NETSTREAM *) st;
6325 return (*stream->dtb->getbuffer) (stream->stream,size,buffer);
6329 /* Network send null-terminated string
6330 * Accepts: Network stream
6331 * string pointer
6332 * Returns: T if success else NIL
6335 long net_soutr (NETSTREAM *stream,char *string)
6337 return (*stream->dtb->soutr) (stream->stream,string);
6341 /* Network send string
6342 * Accepts: Network stream
6343 * string pointer
6344 * byte count
6345 * Returns: T if success else NIL
6348 long net_sout (NETSTREAM *stream,char *string,unsigned long size)
6350 return (*stream->dtb->sout) (stream->stream,string,size);
6353 /* Network close
6354 * Accepts: Network stream
6357 void net_close (NETSTREAM *stream)
6359 if (stream->stream) (*stream->dtb->close) (stream->stream);
6360 fs_give ((void **) &stream);
6364 /* Network get host name
6365 * Accepts: Network stream
6366 * Returns: host name for this stream
6369 char *net_host (NETSTREAM *stream)
6371 return (*stream->dtb->host) (stream->stream);
6375 /* Network get remote host name
6376 * Accepts: Network stream
6377 * Returns: host name for this stream
6380 char *net_remotehost (NETSTREAM *stream)
6382 return (*stream->dtb->remotehost) (stream->stream);
6385 /* Network return port for this stream
6386 * Accepts: Network stream
6387 * Returns: port number for this stream
6390 unsigned long net_port (NETSTREAM *stream)
6392 return (*stream->dtb->port) (stream->stream);
6396 /* Network get local host name
6397 * Accepts: Network stream
6398 * Returns: local host name
6401 char *net_localhost (NETSTREAM *stream)
6403 return (*stream->dtb->localhost) (stream->stream);
6406 void free_c_client_module_globals(void)
6408 env_end();