* Improve code that determines the type of encryption that is used according
[alpine.git] / imap / src / c-client / mail.c
blob7291a642111381d816916ae304b3c8c7ea8c2412
1 /* ========================================================================
2 * Copyright 2008-2010 Mark Crispin
3 * ========================================================================
4 */
6 /*
7 * Program: Mailbox Access routines
9 * Author: Mark Crispin
11 * Date: 22 November 1989
12 * Last Edited: 15 November 2010
14 * Previous versions of this file were
16 * Copyright 1988-2008 University of Washington
18 * Licensed under the Apache License, Version 2.0 (the "License");
19 * you may not use this file except in compliance with the License.
20 * You may obtain a copy of the License at
22 * http://www.apache.org/licenses/LICENSE-2.0
27 #include <ctype.h>
28 #include <stdio.h>
29 #include <time.h>
30 #include "c-client.h"
32 char *Panda_copyright = "Copyright 2008-2010 Mark Crispin\n";
34 char *UW_copyright = "Copyright 1988-2008 University of Washington\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n";
36 /* c-client global data */
37 /* version of this library */
38 static char *mailcclientversion = CCLIENTVERSION;
39 /* Minimum in range of encryption supported */
40 static int encryption_range_min = 0;
41 /* Maximum in range of encryption supported */
42 static int encryption_range_max = 0;
43 /* app identity */
44 static IDLIST *idapp = NIL;
45 /* list of mail drivers */
46 static DRIVER *maildrivers = NIL;
47 /* list of authenticators */
48 static AUTHENTICATOR *mailauthenticators = NIL;
49 /* SSL driver pointer */
50 static NETDRIVER *mailssldriver = NIL;
51 /* pointer to alternate gets function */
52 static mailgets_t mailgets = NIL;
53 /* pointer to read progress function */
54 static readprogress_t mailreadprogress = NIL;
55 /* mail cache manipulation function */
56 static mailcache_t mailcache = mm_cache;
57 /* RFC-822 output generator */
58 static rfc822out_t mail822out = NIL;
59 /* RFC-822 output generator (new style) */
60 static rfc822outfull_t mail822outfull = NIL;
61 /* SMTP verbose callback */
62 static smtpverbose_t mailsmtpverbose = mm_dlog;
63 /* proxy copy routine */
64 static mailproxycopy_t mailproxycopy = NIL;
65 /* RFC-822 external line parse */
66 static parseline_t mailparseline = NIL;
67 /* RFC-822 external phrase parser */
68 static parsephrase_t mailparsephrase = NIL;
69 static kinit_t mailkinit = NIL; /* application kinit callback */
70 /* note network sent command */
71 static sendcommand_t mailsendcommand = NIL;
72 /* newsrc file name decision function */
73 static newsrcquery_t mailnewsrcquery = NIL;
74 /* ACL results callback */
75 static getacl_t mailaclresults = NIL;
76 /* list rights results callback */
77 static listrights_t maillistrightsresults = NIL;
78 /* my rights results callback */
79 static myrights_t mailmyrightsresults = NIL;
80 /* quota results callback */
81 static quota_t mailquotaresults = NIL;
82 /* quota root results callback */
83 static quotaroot_t mailquotarootresults = NIL;
84 /* sorted results callback */
85 static sortresults_t mailsortresults = NIL;
86 /* threaded results callback */
87 static threadresults_t mailthreadresults = NIL;
88 /* COPY UID results */
89 static copyuid_t mailcopyuid = NIL;
90 /* APPEND UID results */
91 static appenduid_t mailappenduid = NIL;
93 static oauth2getaccesscode_t oauth2getaccesscode = NIL;
94 /* free elt extra stuff callback */
95 static freeeltsparep_t mailfreeeltsparep = NIL;
96 /* free envelope extra stuff callback */
97 static freeenvelopesparep_t mailfreeenvelopesparep = NIL;
98 /* free body extra stuff callback */
99 static freebodysparep_t mailfreebodysparep = NIL;
100 /* free stream extra stuff callback */
101 static freestreamsparep_t mailfreestreamsparep = NIL;
102 /* SSL start routine */
103 static sslstart_t mailsslstart = NIL;
104 /* SSL certificate query */
105 static sslcertificatequery_t mailsslcertificatequery = NIL;
106 /* SSL client certificate */
107 static sslclientcert_t mailsslclientcert = NIL;
108 /* SSL client private key */
109 static sslclientkey_t mailsslclientkey = NIL;
110 /* SSL failure notify */
111 static sslfailure_t mailsslfailure = NIL;
112 /* snarf interval */
113 static long mailsnarfinterval = 60;
114 /* snarf preservation */
115 static long mailsnarfpreserve = NIL;
116 /* newsrc name uses canonical host */
117 static long mailnewsrccanon = LONGT;
119 /* supported threaders */
120 static THREADER mailthreadordsub = {
121 "ORDEREDSUBJECT",mail_thread_orderedsubject,NIL
123 static THREADER mailthreadlist = {
124 "REFERENCES",mail_thread_references,&mailthreadordsub
127 /* server name */
128 static char *servicename = "unknown";
129 /* server externally-set authentication ID */
130 static char *externalauthid = NIL;
131 static int expungeatping = T; /* mail_ping() may call mm_expunged() */
132 static int trysslfirst = NIL; /* always try SSL first */
133 static int notimezones = NIL; /* write timezones in "From " header */
134 static int trustdns = T; /* do DNS canonicalization */
135 static int saslusesptrname = T; /* SASL uses name from DNS PTR lookup */
136 /* trustdns also must be set */
137 static int debugsensitive = NIL;/* debug telemetry includes sensitive data */
139 /* Default mail cache handler
140 * Accepts: pointer to cache handle
141 * message number
142 * caching function
143 * Returns: cache data
146 void *mm_cache (MAILSTREAM *stream,unsigned long msgno,long op)
148 size_t n;
149 void *ret = NIL;
150 unsigned long i;
151 switch ((int) op) { /* what function? */
152 case CH_INIT: /* initialize cache */
153 if (stream->cache) { /* flush old cache contents */
154 while (stream->cachesize) {
155 mm_cache (stream,stream->cachesize,CH_FREE);
156 mm_cache (stream,stream->cachesize--,CH_FREESORTCACHE);
158 fs_give ((void **) &stream->cache);
159 fs_give ((void **) &stream->sc);
160 stream->nmsgs = 0; /* can't have any messages now */
162 break;
163 case CH_SIZE: /* (re-)size the cache */
164 if (!stream->cache) { /* have a cache already? */
165 /* no, create new cache */
166 n = (stream->cachesize = msgno + CACHEINCREMENT) * sizeof (void *);
167 stream->cache = (MESSAGECACHE **) memset (fs_get (n),0,n);
168 stream->sc = (SORTCACHE **) memset (fs_get (n),0,n);
170 /* is existing cache size large neough */
171 else if (msgno > stream->cachesize) {
172 i = stream->cachesize; /* remember old size */
173 n = (stream->cachesize = msgno + CACHEINCREMENT) * sizeof (void *);
174 fs_resize ((void **) &stream->cache,n);
175 fs_resize ((void **) &stream->sc,n);
176 while (i < stream->cachesize) {
177 stream->cache[i] = NIL;
178 stream->sc[i++] = NIL;
181 break;
183 case CH_MAKEELT: /* return elt, make if necessary */
184 if (!stream->cache[msgno - 1])
185 stream->cache[msgno - 1] = mail_new_cache_elt (msgno);
186 /* falls through */
187 case CH_ELT: /* return elt */
188 ret = (void *) stream->cache[msgno - 1];
189 break;
190 case CH_SORTCACHE: /* return sortcache entry, make if needed */
191 if (!stream->sc[msgno - 1]) stream->sc[msgno - 1] =
192 (SORTCACHE *) memset (fs_get (sizeof (SORTCACHE)),0,sizeof (SORTCACHE));
193 ret = (void *) stream->sc[msgno - 1];
194 break;
195 case CH_FREE: /* free elt */
196 mail_free_elt (&stream->cache[msgno - 1]);
197 break;
198 case CH_FREESORTCACHE:
199 if (stream->sc[msgno - 1]) {
200 if (stream->sc[msgno - 1]->from)
201 fs_give ((void **) &stream->sc[msgno - 1]->from);
202 if (stream->sc[msgno - 1]->to)
203 fs_give ((void **) &stream->sc[msgno - 1]->to);
204 if (stream->sc[msgno - 1]->cc)
205 fs_give ((void **) &stream->sc[msgno - 1]->cc);
206 if (stream->sc[msgno - 1]->subject)
207 fs_give ((void **) &stream->sc[msgno - 1]->subject);
208 if (stream->sc[msgno - 1]->unique &&
209 (stream->sc[msgno - 1]->unique != stream->sc[msgno - 1]->message_id))
210 fs_give ((void **) &stream->sc[msgno - 1]->unique);
211 if (stream->sc[msgno - 1]->message_id)
212 fs_give ((void **) &stream->sc[msgno - 1]->message_id);
213 if (stream->sc[msgno - 1]->references)
214 mail_free_stringlist (&stream->sc[msgno - 1]->references);
215 fs_give ((void **) &stream->sc[msgno - 1]);
217 break;
218 case CH_EXPUNGE: /* expunge cache slot */
219 for (i = msgno - 1; msgno < stream->nmsgs; i++,msgno++) {
220 if ((stream->cache[i] = stream->cache[msgno]) != NULL)
221 stream->cache[i]->msgno = msgno;
222 stream->sc[i] = stream->sc[msgno];
224 stream->cache[i] = NIL; /* top of cache goes away */
225 stream->sc[i] = NIL;
226 break;
227 default:
228 fatal ("Bad mm_cache op");
229 break;
231 return ret;
234 /* Dummy string driver for complete in-memory strings */
236 static void mail_string_init (STRING *s,void *data,unsigned long size);
237 static char mail_string_next (STRING *s);
238 static void mail_string_setpos (STRING *s,unsigned long i);
240 STRINGDRIVER mail_string = {
241 mail_string_init, /* initialize string structure */
242 mail_string_next, /* get next byte in string structure */
243 mail_string_setpos /* set position in string structure */
247 /* Initialize mail string structure for in-memory string
248 * Accepts: string structure
249 * pointer to string
250 * size of string
253 static void mail_string_init (STRING *s,void *data,unsigned long size)
255 /* set initial string pointers */
256 s->chunk = s->curpos = (char *) (s->data = data);
257 /* and sizes */
258 s->size = s->chunksize = s->cursize = size;
259 s->data1 = s->offset = 0; /* never any offset */
263 /* Get next character from string
264 * Accepts: string structure
265 * Returns: character, string structure chunk refreshed
268 static char mail_string_next (STRING *s)
270 return *s->curpos++; /* return the last byte */
274 /* Set string pointer position
275 * Accepts: string structure
276 * new position
279 static void mail_string_setpos (STRING *s,unsigned long i)
281 s->curpos = s->chunk + i; /* set new position */
282 s->cursize = s->chunksize - i;/* and new size */
285 /* Mail routines
287 * mail_xxx routines are the interface between this module and the outside
288 * world. Only these routines should be referenced by external callers.
290 * Note that there is an important difference between a "sequence" and a
291 * "message #" (msgno). A sequence is a string representing a sequence in
292 * {"n", "n:m", or combination separated by commas} format, whereas a msgno
293 * is a single integer.
297 /* Mail version check
298 * Accepts: version
301 void mail_versioncheck (char *version)
303 /* attempt to protect again wrong .h */
304 if (strcmp (version,mailcclientversion)) {
305 char tmp[MAILTMPLEN];
306 sprintf (tmp,"c-client library version skew, app=%.100s library=%.100s",
307 version,mailcclientversion);
308 fatal (tmp);
313 /* Mail link driver
314 * Accepts: driver to add to list
317 void mail_link (DRIVER *driver)
319 DRIVER **d = &maildrivers;
320 while (*d) d = &(*d)->next; /* find end of list of drivers */
321 *d = driver; /* put driver at the end */
322 driver->next = NIL; /* this driver is the end of the list */
325 /* Mail manipulate driver parameters
326 * Accepts: mail stream
327 * function code
328 * function-dependent value
329 * Returns: function-dependent return value
332 void *mail_parameters (MAILSTREAM *stream,long function,void *value)
334 void *r,*ret = NIL;
335 DRIVER *d;
336 AUTHENTICATOR *a;
337 switch ((int) function) {
338 case SET_INBOXPATH:
339 fatal ("SET_INBOXPATH not permitted");
340 case GET_INBOXPATH:
341 if ((stream || (stream = mail_open (NIL,"INBOX",OP_PROTOTYPE))) &&
342 stream->dtb) ret = (*stream->dtb->parameters) (function,value);
343 break;
344 case SET_THREADERS:
345 fatal ("SET_THREADERS not permitted");
346 case GET_THREADERS: /* use stream dtb instead of global */
347 ret = (stream && stream->dtb) ?
348 /* KLUDGE ALERT: note stream passed as value */
349 (*stream->dtb->parameters) (function,stream) : (void *) &mailthreadlist;
350 break;
351 case SET_NAMESPACE:
352 fatal ("SET_NAMESPACE not permitted");
353 break;
354 case SET_NEWSRC: /* too late on open stream */
355 if (stream && stream->dtb && (stream != ((*stream->dtb->open) (NIL))))
356 fatal ("SET_NEWSRC not permitted");
357 else ret = env_parameters (function,value);
358 break;
359 case GET_NAMESPACE:
360 ret = (stream && stream->dtb && !(stream->dtb->flags & DR_LOCAL)) ?
361 /* KLUDGE ALERT: note stream passed as value */
362 (*stream->dtb->parameters) (function,stream) :
363 env_parameters (function,value);
364 break;
365 case GET_NEWSRC: /* use stream dtb instead of environment */
366 ret = (stream && stream->dtb) ?
367 /* KLUDGE ALERT: note stream passed as value */
368 (*stream->dtb->parameters) (function,stream) :
369 env_parameters (function,value);
370 break;
371 case ENABLE_DEBUG:
372 fatal ("ENABLE_DEBUG not permitted");
373 case DISABLE_DEBUG:
374 fatal ("DISABLE_DEBUG not permitted");
375 case SET_DIRFMTTEST:
376 fatal ("SET_DIRFMTTEST not permitted");
377 case GET_DIRFMTTEST:
378 if (!(stream && stream->dtb &&
379 (ret = (*stream->dtb->parameters) (function,NIL))))
380 fatal ("GET_DIRFMTTEST not permitted");
381 break;
383 case SET_DRIVERS:
384 fatal ("SET_DRIVERS not permitted");
385 case GET_DRIVERS: /* always return global */
386 ret = (void *) maildrivers;
387 break;
388 case SET_DRIVER:
389 fatal ("SET_DRIVER not permitted");
390 case GET_DRIVER:
391 for (d = maildrivers; d && compare_cstring (d->name,(char *) value);
392 d = d->next);
393 ret = (void *) d;
394 break;
395 case ENABLE_DRIVER:
396 for (d = maildrivers; d && compare_cstring (d->name,(char *) value);
397 d = d->next);
398 if ((ret = (void *) d) != NULL) d->flags &= ~DR_DISABLE;
399 break;
400 case DISABLE_DRIVER:
401 for (d = maildrivers; d && compare_cstring (d->name,(char *) value);
402 d = d->next);
403 if ((ret = (void *) d) != NULL) d->flags |= DR_DISABLE;
404 break;
405 case ENABLE_AUTHENTICATOR:
406 for (a = mailauthenticators;/* scan authenticators */
407 a && compare_cstring (a->name,(char *) value); a = a->next);
408 if ((ret = (void *) a) != NULL) a->flags &= ~AU_DISABLE;
409 break;
410 case DISABLE_AUTHENTICATOR:
411 for (a = mailauthenticators;/* scan authenticators */
412 a && compare_cstring (a->name,(char *) value); a = a->next);
413 if ((ret = (void *) a) != NULL) a->flags |= AU_DISABLE;
414 break;
415 case UNHIDE_AUTHENTICATOR:
416 for (a = mailauthenticators;/* scan authenticators */
417 a && compare_cstring (a->name,(char *) value); a = a->next);
418 if ((ret = (void *) a) != NULL) a->flags &= ~AU_HIDE;
419 break;
420 case HIDE_AUTHENTICATOR:
421 for (a = mailauthenticators;/* scan authenticators */
422 a && compare_cstring (a->name,(char *) value); a = a->next);
423 if ((ret = (void *) a) != NULL) a->flags |= AU_HIDE;
424 break;
425 case SET_EXTERNALAUTHID:
426 if (value) { /* setting external authentication ID */
427 externalauthid = cpystr ((char *) value);
428 mail_parameters (NIL,UNHIDE_AUTHENTICATOR,"EXTERNAL");
430 else { /* clearing external authentication ID */
431 if (externalauthid) fs_give ((void **) &externalauthid);
432 mail_parameters (NIL,HIDE_AUTHENTICATOR,"EXTERNAL");
434 case GET_EXTERNALAUTHID:
435 ret = (void *) externalauthid;
436 break;
438 case SET_GETS:
439 mailgets = (mailgets_t) value;
440 case GET_GETS:
441 ret = (void *) mailgets;
442 break;
443 case SET_READPROGRESS:
444 mailreadprogress = (readprogress_t) value;
445 case GET_READPROGRESS:
446 ret = (void *) mailreadprogress;
447 break;
448 case SET_CACHE:
449 mailcache = (mailcache_t) value;
450 case GET_CACHE:
451 ret = (void *) mailcache;
452 break;
453 case SET_RFC822OUTPUT:
454 mail822out = (rfc822out_t) value;
455 case GET_RFC822OUTPUT:
456 ret = (void *) mail822out;
457 break;
458 case SET_RFC822OUTPUTFULL:
459 mail822outfull = (rfc822outfull_t) value;
460 case GET_RFC822OUTPUTFULL:
461 ret = (void *) mail822outfull;
462 break;
463 case SET_SMTPVERBOSE:
464 mailsmtpverbose = (smtpverbose_t) value;
465 case GET_SMTPVERBOSE:
466 ret = (void *) mailsmtpverbose;
467 break;
468 case SET_MAILPROXYCOPY:
469 mailproxycopy = (mailproxycopy_t) value;
470 case GET_MAILPROXYCOPY:
471 ret = (void *) mailproxycopy;
472 break;
473 case SET_PARSELINE:
474 mailparseline = (parseline_t) value;
475 case GET_PARSELINE:
476 ret = (void *) mailparseline;
477 break;
478 case SET_PARSEPHRASE:
479 mailparsephrase = (parsephrase_t) value;
480 case GET_PARSEPHRASE:
481 ret = (void *) mailparsephrase;
482 break;
483 case SET_NEWSRCQUERY:
484 mailnewsrcquery = (newsrcquery_t) value;
485 case GET_NEWSRCQUERY:
486 ret = (void *) mailnewsrcquery;
487 break;
488 case SET_NEWSRCCANONHOST:
489 mailnewsrccanon = (long) value;
490 case GET_NEWSRCCANONHOST:
491 ret = (void *) mailnewsrccanon;
492 break;
494 case SET_COPYUID:
495 mailcopyuid = (copyuid_t) value;
496 case GET_COPYUID:
497 ret = (void *) mailcopyuid;
498 break;
499 case SET_APPENDUID:
500 mailappenduid = (appenduid_t) value;
501 case GET_APPENDUID:
502 ret = (void *) mailappenduid;
503 break;
504 case SET_FREEENVELOPESPAREP:
505 mailfreeenvelopesparep = (freeenvelopesparep_t) value;
506 case GET_FREEENVELOPESPAREP:
507 ret = (void *) mailfreeenvelopesparep;
508 break;
509 case SET_FREEELTSPAREP:
510 mailfreeeltsparep = (freeeltsparep_t) value;
511 case GET_FREEELTSPAREP:
512 ret = (void *) mailfreeeltsparep;
513 break;
514 case SET_FREESTREAMSPAREP:
515 mailfreestreamsparep = (freestreamsparep_t) value;
516 case GET_FREESTREAMSPAREP:
517 ret = (void *) mailfreestreamsparep;
518 break;
519 case SET_FREEBODYSPAREP:
520 mailfreebodysparep = (freebodysparep_t) value;
521 case GET_FREEBODYSPAREP:
522 ret = (void *) mailfreebodysparep;
523 break;
525 case SET_SSLSTART:
526 mailsslstart = (sslstart_t) value;
527 case GET_SSLSTART:
528 ret = (void *) mailsslstart;
529 break;
530 case SET_SSLCERTIFICATEQUERY:
531 mailsslcertificatequery = (sslcertificatequery_t) value;
532 case GET_SSLCERTIFICATEQUERY:
533 ret = (void *) mailsslcertificatequery;
534 break;
535 case SET_SSLCLIENTCERT:
536 mailsslclientcert = (sslclientcert_t) value;
537 case GET_SSLCLIENTCERT:
538 ret = (void *) mailsslclientcert;
539 break;
540 case SET_SSLCLIENTKEY:
541 mailsslclientkey = (sslclientkey_t) value;
542 case GET_SSLCLIENTKEY:
543 ret = (void *) mailsslclientkey;
544 break;
545 case SET_SSLFAILURE:
546 mailsslfailure = (sslfailure_t) value;
547 case GET_SSLFAILURE:
548 ret = (void *) mailsslfailure;
549 break;
550 case SET_ENCRYPTION_RANGE_MIN:
551 encryption_range_min = *(int *) value;
552 case GET_ENCRYPTION_RANGE_MIN:
553 ret = (void *) &encryption_range_min;
554 break;
555 case SET_ENCRYPTION_RANGE_MAX:
556 encryption_range_max = *(int *) value;
557 case GET_ENCRYPTION_RANGE_MAX:
558 ret = (void *) &encryption_range_max;
559 break;
560 case SET_KINIT:
561 mailkinit = (kinit_t) value;
562 case GET_KINIT:
563 ret = (void *) mailkinit;
564 break;
565 case SET_SENDCOMMAND:
566 mailsendcommand = (sendcommand_t) value;
567 case GET_SENDCOMMAND:
568 ret = (void *) mailsendcommand;
569 break;
571 case SET_SERVICENAME:
572 servicename = (char *) value;
573 case GET_SERVICENAME:
574 ret = (void *) servicename;
575 break;
576 case SET_EXPUNGEATPING:
577 expungeatping = (value ? T : NIL);
578 case GET_EXPUNGEATPING:
579 ret = (void *) (expungeatping ? VOIDT : NIL);
580 break;
581 case SET_SORTRESULTS:
582 mailsortresults = (sortresults_t) value;
583 case GET_SORTRESULTS:
584 ret = (void *) mailsortresults;
585 break;
586 case SET_THREADRESULTS:
587 mailthreadresults = (threadresults_t) value;
588 case GET_THREADRESULTS:
589 ret = (void *) mailthreadresults;
590 break;
591 case SET_SSLDRIVER:
592 mailssldriver = (NETDRIVER *) value;
593 case GET_SSLDRIVER:
594 ret = (void *) mailssldriver;
595 break;
596 case SET_TRYSSLFIRST:
597 trysslfirst = (value ? T : NIL);
598 case GET_TRYSSLFIRST:
599 ret = (void *) (trysslfirst ? VOIDT : NIL);
600 break;
601 case SET_NOTIMEZONES:
602 notimezones = (value ? T : NIL);
603 case GET_NOTIMEZONES:
604 ret = (void *) (notimezones ? VOIDT : NIL);
605 break;
606 case SET_TRUSTDNS:
607 trustdns = (value ? T : NIL);
608 case GET_TRUSTDNS:
609 ret = (void *) (trustdns ? VOIDT : NIL);
610 break;
611 case SET_SASLUSESPTRNAME:
612 saslusesptrname = (value ? T : NIL);
613 case GET_SASLUSESPTRNAME:
614 ret = (void *) (saslusesptrname ? VOIDT : NIL);
615 break;
616 case SET_DEBUGSENSITIVE:
617 debugsensitive = (value ? T : NIL);
618 case GET_DEBUGSENSITIVE:
619 ret = (void *) (debugsensitive ? VOIDT : NIL);
620 break;
622 case SET_ACL:
623 mailaclresults = (getacl_t) value;
624 case GET_ACL:
625 ret = (void *) mailaclresults;
626 break;
627 case SET_LISTRIGHTS:
628 maillistrightsresults = (listrights_t) value;
629 case GET_LISTRIGHTS:
630 ret = (void *) maillistrightsresults;
631 break;
632 case SET_MYRIGHTS:
633 mailmyrightsresults = (myrights_t) value;
634 case GET_MYRIGHTS:
635 ret = (void *) mailmyrightsresults;
636 break;
637 case SET_QUOTA:
638 mailquotaresults = (quota_t) value;
639 case GET_QUOTA:
640 ret = (void *) mailquotaresults;
641 break;
642 case SET_QUOTAROOT:
643 mailquotarootresults = (quotaroot_t) value;
644 case GET_QUOTAROOT:
645 ret = (void *) mailquotarootresults;
646 break;
647 case SET_SNARFINTERVAL:
648 mailsnarfinterval = (long) value;
649 case GET_SNARFINTERVAL:
650 ret = (void *) mailsnarfinterval;
651 break;
652 case SET_SNARFPRESERVE:
653 mailsnarfpreserve = (long) value;
654 case GET_SNARFPRESERVE:
655 ret = (void *) mailsnarfpreserve;
656 break;
657 case SET_SNARFMAILBOXNAME:
658 if (stream) { /* have a stream? */
659 if (stream->snarf.name) fs_give ((void **) &stream->snarf.name);
660 stream->snarf.name = cpystr ((char *) value);
662 else fatal ("SET_SNARFMAILBOXNAME with no stream");
663 case GET_SNARFMAILBOXNAME:
664 if (stream) ret = (void *) stream->snarf.name;
665 break;
666 case SET_IDPARAMS: /* program id */
667 idapp = (IDLIST *) value;
668 case GET_IDPARAMS:
669 ret = (void *) idapp;
670 break;
671 case SET_OA2CLIENTGETACCESSCODE:
672 oauth2getaccesscode = (oauth2getaccesscode_t) value;
673 case GET_OA2CLIENTGETACCESSCODE:
674 ret = (void *) oauth2getaccesscode;
675 break;
676 default:
677 if ((r = smtp_parameters (function,value)) != NULL) ret = r;
678 if ((r = env_parameters (function,value)) != NULL) ret = r;
679 if ((r = tcp_parameters (function,value)) != NULL) ret = r;
680 if ((r = utf8_parameters (function,value)) != NULL) ret = r;
681 if (stream && stream->dtb) {/* if have stream, do for its driver only */
682 if ((r = (*stream->dtb->parameters) (function,value)) != NULL) ret = r;
684 /* else do all drivers */
685 else for (d = maildrivers; d; d = d->next)
686 if ((r = (d->parameters) (function,value)) != NULL) ret = r;
687 break;
689 return ret;
692 /* Mail validate mailbox name
693 * Accepts: MAIL stream
694 * mailbox name
695 * purpose string for error message
696 * Return: driver factory on success, NIL on failure
699 DRIVER *mail_valid (MAILSTREAM *stream,char *mailbox,char *purpose)
701 char tmp[MAILTMPLEN];
702 DRIVER *factory = NIL;
703 /* never allow names with newlines */
704 if (strpbrk (mailbox,"\015\012")) {
705 if (purpose) { /* if want an error message */
706 sprintf (tmp,"Can't %s with such a name",purpose);
707 MM_LOG (tmp,ERROR);
709 return NIL;
711 /* validate name, find driver factory */
712 if (strlen (mailbox) < (NETMAXHOST+(NETMAXUSER*2)+NETMAXMBX+NETMAXSRV+50))
713 for (factory = maildrivers; factory &&
714 ((factory->flags & DR_DISABLE) ||
715 ((factory->flags & DR_LOCAL) && (*mailbox == '{')) ||
716 !(*factory->valid) (mailbox));
717 factory = factory->next);
718 /* validate factory against non-dummy stream */
719 if (factory && stream && stream->dtb && (stream->dtb != factory) &&
720 strcmp (stream->dtb->name,"dummy"))
721 /* factory invalid; if dummy, use stream */
722 factory = strcmp (factory->name,"dummy") ? NIL : stream->dtb;
723 if (!factory && purpose) { /* if want an error message */
724 sprintf (tmp,"Can't %s %.80s: %s",purpose,mailbox,(*mailbox == '{') ?
725 "invalid remote specification" : "no such mailbox");
726 MM_LOG (tmp,ERROR);
728 return factory; /* return driver factory */
731 /* Mail validate network mailbox name
732 * Accepts: mailbox name
733 * mailbox driver to validate against
734 * pointer to where to return host name if non-NIL
735 * pointer to where to return mailbox name if non-NIL
736 * Returns: driver on success, NIL on failure
739 DRIVER *mail_valid_net (char *name,DRIVER *drv,char *host,char *mailbox)
741 NETMBX mb;
742 if (!mail_valid_net_parse (name,&mb) || strcmp (mb.service,drv->name))
743 return NIL;
744 if (host) strcpy (host,mb.host);
745 if (mailbox) strcpy (mailbox,mb.mailbox);
746 return drv;
750 /* Mail validate network mailbox name
751 * Accepts: mailbox name
752 * NETMBX structure to return values
753 * Returns: T on success, NIL on failure
756 long mail_valid_net_parse (char *name,NETMBX *mb)
758 return mail_valid_net_parse_work (name,mb,"imap");
761 /* Mail validate network mailbox name worker routine
762 * Accepts: mailbox name
763 * NETMBX structure to return values
764 * default service
765 * Returns: T on success, NIL on failure
768 long mail_valid_net_parse_work (char *name,NETMBX *mb,char *service)
770 int i,j;
771 char c,*s,*t,*v,tmp[MAILTMPLEN],arg[MAILTMPLEN];
772 /* initialize structure */
773 memset (mb,'\0',sizeof (NETMBX));
774 /* must have host specification */
775 if (*name++ != '{') return NIL;
776 if (*name == '[') { /* if domain literal, find its ending */
777 if (!((v = strpbrk (name,"]}")) && (*v++ == ']'))) return NIL;
779 /* find end of host name */
780 else if (!(v = strpbrk (name,"/:}"))) return NIL;
781 /* validate length, find mailbox part */
782 if (!((i = v - name) && (i < NETMAXHOST) && (t = strchr (v,'}')) &&
783 ((j = t - v) < MAILTMPLEN) && (strlen (t+1) < (size_t) NETMAXMBX)))
784 return NIL; /* invalid mailbox */
785 strncpy (mb->host,name,i); /* set host name */
786 strncpy (mb->orighost,name,i);
787 mb->host[i] = mb->orighost[i] = '\0';
788 strcpy (mb->mailbox,t+1); /* set mailbox name */
789 if (t - v) { /* any switches or port specification? */
790 strncpy (t = tmp,v,j); /* copy it */
791 tmp[j] = '\0'; /* tie it off */
792 c = *t++; /* get first delimiter */
793 do switch (c) { /* act based upon the character */
794 case ':': /* port specification */
795 if (mb->port || !(mb->port = strtoul (t,&t,10))) return NIL;
796 c = t ? *t++ : '\0'; /* get delimiter, advance pointer */
797 break;
798 case '/': /* switch */
799 /* find delimiter */
800 if ((t = strpbrk (s = t,"/:=")) != NULL) {
801 c = *t; /* remember delimiter for later */
802 *t++ = '\0'; /* tie off switch name */
804 else c = '\0'; /* no delimiter */
805 if (c == '=') { /* parse switches which take arguments */
806 if (*t == '"') { /* quoted string? */
807 for (v = arg,i = 0,++t; (c = *t++) != '"';) {
808 if (!c) return NIL; /* unterminated string */
809 /* quote next character */
810 if (c == '\\') c = *t++;
811 if (!c) return NIL; /* can't quote NUL either */
812 arg[i++] = c;
814 c = *t++; /* remember delimiter for later */
815 arg[i] = '\0'; /* tie off argument */
817 else { /* non-quoted argument */
818 if ((t = strpbrk (v = t,"/:")) != NULL) {
819 c = *t; /* remember delimiter for later */
820 *t++ = '\0'; /* tie off switch name */
822 else c = '\0'; /* no delimiter */
823 i = strlen (v); /* length of argument */
825 if (!compare_cstring (s,"service") && (i < NETMAXSRV) && !*mb->service)
826 lcase (strcpy (mb->service,v));
827 else if (!compare_cstring (s,"user") && (i < NETMAXUSER) && !*mb->user)
828 strcpy (mb->user,v);
829 else if (!compare_cstring (s,"authuser") && (i < NETMAXUSER) &&
830 !*mb->authuser) strcpy (mb->authuser,v);
831 else if (!compare_cstring (s,"auth") && (i < NETMAXAUTH) &&
832 !*mb->auth) strcpy (mb->auth,v);
833 else return NIL;
836 else { /* non-argument switch */
837 if (!compare_cstring (s,"anonymous")) mb->anoflag = T;
838 else if (!compare_cstring (s,"debug")) mb->dbgflag = T;
839 else if (!compare_cstring (s,"readonly")) mb->readonlyflag = T;
840 else if (!compare_cstring (s,"secure")) mb->secflag = T;
841 else if (!compare_cstring (s,"norsh")) mb->norsh = T;
842 else if (!compare_cstring (s,"loser")) mb->loser = T;
843 else if (!compare_cstring (s,"tls") && !mb->notlsflag)
844 mb->tlsflag = T;
845 else if (!compare_cstring (s,"tls-sslv23") && !mb->notlsflag)
846 mb->tlssslv23 = mb->tlsflag = T;
847 else if (!compare_cstring (s,"notls") && !mb->tlsflag)
848 mb->notlsflag = T;
849 else if (!compare_cstring (s,"tryssl"))
850 mb->trysslflag = mailssldriver? T : NIL;
851 else if (mailssldriver && !compare_cstring (s,"ssl") && !mb->tlsflag)
852 mb->sslflag = mb->notlsflag = T;
853 else if (!compare_cstring(s, "tls1")
854 && !mb->tls1_1 && !mb->tls1_2 && !mb->tls1_3)
855 mb->sslflag = mb->notlsflag = mb->tls1 = T;
856 else if (!compare_cstring(s, "tls1_1")
857 && !mb->tls1 && !mb->tls1_2 && !mb->tls1_3)
858 mb->sslflag = mb->notlsflag = mb->tls1_1 = T;
859 else if (!compare_cstring(s, "tls1_2")
860 && !mb->tls1 && !mb->tls1_1 && !mb->tls1_3)
861 mb->sslflag = mb->notlsflag = mb->tls1_2 = T;
862 else if (!compare_cstring(s, "tls1_3")
863 && !mb->tls1 && !mb->tls1_1 && !mb->tls1_2)
864 mb->sslflag = mb->notlsflag = mb->tls1_3 = T;
865 else if (mailssldriver && !compare_cstring (s,"novalidate-cert"))
866 mb->novalidate = T;
867 /* hack for compatibility with the past */
868 else if (mailssldriver && !compare_cstring (s,"validate-cert"));
869 /* service switches below here */
870 else if (*mb->service) return NIL;
871 else if (!compare_cstring (s,"imap") ||
872 !compare_cstring (s,"nntp") ||
873 !compare_cstring (s,"pop3") ||
874 !compare_cstring (s,"smtp") ||
875 !compare_cstring (s,"submit"))
876 lcase (strcpy (mb->service,s));
877 else if (!compare_cstring (s,"imap2") ||
878 !compare_cstring (s,"imap2bis") ||
879 !compare_cstring (s,"imap4") ||
880 !compare_cstring (s,"imap4rev1"))
881 strcpy (mb->service,"imap");
882 else if (!compare_cstring (s,"pop"))
883 strcpy (mb->service,"pop3");
884 else return NIL; /* invalid non-argument switch */
886 break;
887 default: /* anything else is bogus */
888 return NIL;
889 } while (c); /* see if anything more to parse */
891 /* default mailbox name */
892 if (!*mb->mailbox) strcpy (mb->mailbox,"INBOX");
893 /* default service name */
894 if (!*mb->service) strcpy (mb->service,service);
895 /* /norsh only valid if imap */
896 if (mb->norsh && strcmp (mb->service,"imap")) return NIL;
897 return T;
900 /* Mail scan mailboxes for string
901 * Accepts: mail stream
902 * reference
903 * pattern to search
904 * contents to search
907 void mail_scan (MAILSTREAM *stream,char *ref,char *pat,char *contents)
909 int remote = ((*pat == '{') || (ref && *ref == '{'));
910 DRIVER *d;
911 if (ref && (strlen (ref) > NETMAXMBX)) {
912 char tmp[MAILTMPLEN];
913 sprintf (tmp,"Invalid LIST reference specification: %.80s",ref);
914 MM_LOG (tmp,ERROR);
915 return;
917 if (strlen (pat) > NETMAXMBX) {
918 char tmp[MAILTMPLEN];
919 sprintf (tmp,"Invalid LIST pattern specification: %.80s",pat);
920 MM_LOG (tmp,ERROR);
921 return;
923 if (*pat == '{') ref = NIL; /* ignore reference if pattern is remote */
924 if (stream) { /* if have a stream, do it for that stream */
925 if ((d = stream->dtb) && d->scan &&
926 !(((d->flags & DR_LOCAL) && remote)))
927 (*d->scan) (stream,ref,pat,contents);
929 /* otherwise do for all DTB's */
930 else for (d = maildrivers; d; d = d->next)
931 if (d->scan && !((d->flags & DR_DISABLE) ||
932 ((d->flags & DR_LOCAL) && remote)))
933 (d->scan) (NIL,ref,pat,contents);
936 /* Mail list mailboxes
937 * Accepts: mail stream
938 * reference
939 * pattern to search
942 void mail_list (MAILSTREAM *stream,char *ref,char *pat)
944 int remote = ((*pat == '{') || (ref && *ref == '{'));
945 DRIVER *d = maildrivers;
946 if (ref && (strlen (ref) > NETMAXMBX)) {
947 char tmp[MAILTMPLEN];
948 sprintf (tmp,"Invalid LIST reference specification: %.80s",ref);
949 MM_LOG (tmp,ERROR);
950 return;
952 if (strlen (pat) > NETMAXMBX) {
953 char tmp[MAILTMPLEN];
954 sprintf (tmp,"Invalid LIST pattern specification: %.80s",pat);
955 MM_LOG (tmp,ERROR);
956 return;
958 if (*pat == '{') ref = NIL; /* ignore reference if pattern is remote */
959 if (stream && stream->dtb) { /* if have a stream, do it for that stream */
960 if (!(((d = stream->dtb)->flags & DR_LOCAL) && remote))
961 (*d->list) (stream,ref,pat);
963 /* otherwise do for all DTB's */
964 else do if (!((d->flags & DR_DISABLE) ||
965 ((d->flags & DR_LOCAL) && remote)))
966 (d->list) (NIL,ref,pat);
967 while ((d = d->next) != NULL); /* until at the end */
970 /* Mail list subscribed mailboxes
971 * Accepts: mail stream
972 * pattern to search
975 void mail_lsub (MAILSTREAM *stream,char *ref,char *pat)
977 int remote = ((*pat == '{') || (ref && *ref == '{'));
978 DRIVER *d = maildrivers;
979 if (ref && (strlen (ref) > NETMAXMBX)) {
980 char tmp[MAILTMPLEN];
981 sprintf (tmp,"Invalid LSUB reference specification: %.80s",ref);
982 MM_LOG (tmp,ERROR);
983 return;
985 if (strlen (pat) > NETMAXMBX) {
986 char tmp[MAILTMPLEN];
987 sprintf (tmp,"Invalid LSUB pattern specification: %.80s",pat);
988 MM_LOG (tmp,ERROR);
989 return;
991 if (*pat == '{') ref = NIL; /* ignore reference if pattern is remote */
992 if (stream && stream->dtb) { /* if have a stream, do it for that stream */
993 if (!(((d = stream->dtb)->flags & DR_LOCAL) && remote))
994 (*d->lsub) (stream,ref,pat);
996 /* otherwise do for all DTB's */
997 else do if (!((d->flags & DR_DISABLE) ||
998 ((d->flags & DR_LOCAL) && remote)))
999 (d->lsub) (NIL,ref,pat);
1000 while ((d = d->next) != NULL); /* until at the end */
1003 /* Mail subscribe to mailbox
1004 * Accepts: mail stream
1005 * mailbox to add to subscription list
1006 * Returns: T on success, NIL on failure
1009 long mail_subscribe (MAILSTREAM *stream,char *mailbox)
1011 DRIVER *factory = mail_valid (stream,mailbox,"subscribe to mailbox");
1012 return factory ?
1013 (factory->subscribe ?
1014 (*factory->subscribe) (stream,mailbox) : sm_subscribe (mailbox)) : NIL;
1018 /* Mail unsubscribe to mailbox
1019 * Accepts: mail stream
1020 * mailbox to delete from subscription list
1021 * Returns: T on success, NIL on failure
1024 long mail_unsubscribe (MAILSTREAM *stream,char *mailbox)
1026 DRIVER *factory = mail_valid (stream,mailbox,NIL);
1027 return (factory && factory->unsubscribe) ?
1028 (*factory->unsubscribe) (stream,mailbox) : sm_unsubscribe (mailbox);
1031 /* Mail create mailbox
1032 * Accepts: mail stream
1033 * mailbox name to create
1034 * Returns: T on success, NIL on failure
1037 long mail_create (MAILSTREAM *stream,char *mailbox)
1039 MAILSTREAM *ts;
1040 char *s,*t,tmp[MAILTMPLEN];
1041 size_t i;
1042 DRIVER *d;
1043 /* never allow names with newlines */
1044 if ((s = strpbrk (mailbox,"\015\012")) != NULL) {
1045 MM_LOG ("Can't create mailbox with such a name",ERROR);
1046 return NIL;
1048 if (strlen (mailbox) >= (NETMAXHOST+(NETMAXUSER*2)+NETMAXMBX+NETMAXSRV+50)) {
1049 sprintf (tmp,"Can't create %.80s: %s",mailbox,(*mailbox == '{') ?
1050 "invalid remote specification" : "no such mailbox");
1051 MM_LOG (tmp,ERROR);
1052 return NIL;
1054 /* create of INBOX invalid */
1055 if (!compare_cstring (mailbox,"INBOX")) {
1056 MM_LOG ("Can't create INBOX",ERROR);
1057 return NIL;
1059 /* validate name */
1060 if ((s = mail_utf7_valid (mailbox)) != NULL) {
1061 sprintf (tmp,"Can't create %s: %.80s",s,mailbox);
1062 MM_LOG (tmp,ERROR);
1063 return NIL;
1066 /* see if special driver hack */
1067 if ((mailbox[0] == '#') && ((mailbox[1] == 'd') || (mailbox[1] == 'D')) &&
1068 ((mailbox[2] == 'r') || (mailbox[2] == 'R')) &&
1069 ((mailbox[3] == 'i') || (mailbox[3] == 'I')) &&
1070 ((mailbox[4] == 'v') || (mailbox[4] == 'V')) &&
1071 ((mailbox[5] == 'e') || (mailbox[5] == 'E')) &&
1072 ((mailbox[6] == 'r') || (mailbox[6] == 'R')) && (mailbox[7] == '.')) {
1073 /* copy driver until likely delimiter */
1074 if ((s = strpbrk (t = mailbox+8,"/\\:")) && (i = s - t)) {
1075 strncpy (tmp,t,i);
1076 tmp[i] = '\0';
1078 else {
1079 sprintf (tmp,"Can't create mailbox %.80s: bad driver syntax",mailbox);
1080 MM_LOG (tmp,ERROR);
1081 return NIL;
1083 for (d = maildrivers; d && strcmp (d->name,tmp); d = d->next);
1084 if (d) mailbox = ++s; /* skip past driver specification */
1085 else {
1086 sprintf (tmp,"Can't create mailbox %.80s: unknown driver",mailbox);
1087 MM_LOG (tmp,ERROR);
1088 return NIL;
1091 /* use stream if one given or deterministic */
1092 else if ((stream && stream->dtb) ||
1093 (((*mailbox == '{') || (*mailbox == '#')) &&
1094 (stream = mail_open (NIL,mailbox,OP_PROTOTYPE | OP_SILENT))))
1095 d = stream->dtb;
1096 else if ((*mailbox != '{') && (ts = default_proto (NIL))) d = ts->dtb;
1097 else { /* failed utterly */
1098 sprintf (tmp,"Can't create mailbox %.80s: indeterminate format",mailbox);
1099 MM_LOG (tmp,ERROR);
1100 return NIL;
1102 return (*d->create) (stream,mailbox);
1105 /* Mail delete mailbox
1106 * Accepts: mail stream
1107 * mailbox name to delete
1108 * Returns: T on success, NIL on failure
1111 long mail_delete (MAILSTREAM *stream,char *mailbox)
1113 DRIVER *dtb = mail_valid (stream,mailbox,"delete mailbox");
1114 if (!dtb) return NIL;
1115 if (((mailbox[0] == 'I') || (mailbox[0] == 'i')) &&
1116 ((mailbox[1] == 'N') || (mailbox[1] == 'n')) &&
1117 ((mailbox[2] == 'B') || (mailbox[2] == 'b')) &&
1118 ((mailbox[3] == 'O') || (mailbox[3] == 'o')) &&
1119 ((mailbox[4] == 'X') || (mailbox[4] == 'x')) && !mailbox[5]) {
1120 MM_LOG ("Can't delete INBOX",ERROR);
1121 return NIL;
1123 return SAFE_DELETE (dtb,stream,mailbox);
1127 /* Mail rename mailbox
1128 * Accepts: mail stream
1129 * old mailbox name
1130 * new mailbox name
1131 * Returns: T on success, NIL on failure
1134 long mail_rename (MAILSTREAM *stream,char *old,char *newname)
1136 char *s,tmp[MAILTMPLEN];
1137 DRIVER *dtb = mail_valid (stream,old,"rename mailbox");
1138 if (!dtb) return NIL;
1139 /* validate name */
1140 if ((s = mail_utf7_valid (newname)) != NULL) {
1141 sprintf (tmp,"Can't rename to %s: %.80s",s,newname);
1142 MM_LOG (tmp,ERROR);
1143 return NIL;
1145 if ((*old != '{') && (*old != '#') && mail_valid (NIL,newname,NIL)) {
1146 sprintf (tmp,"Can't rename %.80s: mailbox %.80s already exists",
1147 old,newname);
1148 MM_LOG (tmp,ERROR);
1149 return NIL;
1151 return SAFE_RENAME (dtb,stream,old,newname);
1154 /* Validate mailbox as Modified UTF-7
1155 * Accepts: candidate mailbox name
1156 * Returns: error string if error, NIL if valid
1159 char *mail_utf7_valid (char *mailbox)
1161 char *s;
1162 for (s = mailbox; *s; s++) { /* make sure valid name */
1163 /* reserved for future use with UTF-8 */
1164 if (*s & 0x80) return "mailbox name with 8-bit octet";
1165 /* validate modified UTF-7 */
1166 else if (*s == '&') while (*++s != '-') switch (*s) {
1167 case '\0':
1168 return "unterminated modified UTF-7 name";
1169 case '+': /* valid modified BASE64 */
1170 case ',':
1171 break; /* all OK so far */
1172 default: /* must be alphanumeric */
1173 if (!isalnum (*s)) return "invalid modified UTF-7 name";
1174 break;
1177 return NIL; /* all OK */
1180 /* Mail status of mailbox
1181 * Accepts: mail stream if open on this mailbox
1182 * mailbox name
1183 * status flags
1184 * Returns: T on success, NIL on failure
1187 long mail_status (MAILSTREAM *stream,char *mbx,long flags)
1189 DRIVER *dtb = mail_valid (stream,mbx,"get status of mailbox");
1190 if (!dtb) return NIL; /* only if valid */
1191 if (stream && ((dtb != stream->dtb) ||
1192 ((dtb->flags & DR_LOCAL) && strcmp (mbx,stream->mailbox) &&
1193 strcmp (mbx,stream->original_mailbox))))
1194 stream = NIL; /* stream not suitable */
1195 return SAFE_STATUS (dtb,stream,mbx,flags);
1199 /* Mail status of mailbox default handler
1200 * Accepts: mail stream
1201 * mailbox name
1202 * status flags
1203 * Returns: T on success, NIL on failure
1206 long mail_status_default (MAILSTREAM *stream,char *mbx,long flags)
1208 MAILSTATUS status;
1209 unsigned long i;
1210 MAILSTREAM *tstream = NIL;
1211 /* make temporary stream (unless this mbx) */
1212 if (!stream && !(stream = tstream =
1213 mail_open (NIL,mbx,OP_READONLY|OP_SILENT))) return NIL;
1214 status.flags = flags; /* return status values */
1215 status.messages = stream->nmsgs;
1216 status.recent = stream->recent;
1217 if (flags & SA_UNSEEN) /* must search to get unseen messages */
1218 for (i = 1,status.unseen = 0; i <= stream->nmsgs; i++)
1219 if (!mail_elt (stream,i)->seen) status.unseen++;
1220 status.uidnext = stream->uid_last + 1;
1221 status.uidvalidity = stream->uid_validity;
1222 MM_STATUS(stream,mbx,&status);/* pass status to main program */
1223 if (tstream) mail_close (tstream);
1224 return T; /* success */
1227 /* Mail open
1228 * Accepts: candidate stream for recycling
1229 * mailbox name
1230 * open options
1231 * Returns: stream to use on success, NIL on failure
1234 MAILSTREAM *mail_open (MAILSTREAM *stream,char *name,long options)
1236 int i;
1237 char c,*s,tmp[MAILTMPLEN];
1238 NETMBX mb;
1239 DRIVER *d;
1240 switch (name[0]) { /* see if special handling */
1241 case '#': /* possible special hacks */
1242 if (((name[1] == 'M') || (name[1] == 'm')) &&
1243 ((name[2] == 'O') || (name[2] == 'o')) &&
1244 ((name[3] == 'V') || (name[3] == 'v')) &&
1245 ((name[4] == 'E') || (name[4] == 'e')) && (c = name[5]) &&
1246 (s = strchr (name+6,c)) && (i = s - (name + 6)) && (i < MAILTMPLEN)) {
1247 if ((stream = mail_open (stream,s+1,options)) != NULL) {
1248 strncpy (tmp,name+6,i); /* copy snarf mailbox name */
1249 tmp[i] = '\0'; /* tie off name */
1250 mail_parameters (stream,SET_SNARFMAILBOXNAME,(void *) tmp);
1251 stream->snarf.options = options;
1252 mail_ping (stream); /* do initial snarf */
1253 /* punt if can't do initial snarf */
1254 if (!stream->snarf.time) stream = mail_close (stream);
1256 return stream;
1258 /* special POP hack */
1259 else if (((name[1] == 'P') || (name[1] == 'p')) &&
1260 ((name[2] == 'O') || (name[2] == 'o')) &&
1261 ((name[3] == 'P') || (name[3] == 'p')) &&
1262 mail_valid_net_parse_work (name+4,&mb,"pop3") &&
1263 !strcmp (mb.service,"pop3") && !mb.anoflag && !mb.readonlyflag) {
1264 if ((stream = mail_open (stream,mb.mailbox,options)) != NULL) {
1265 sprintf (tmp,"{%.255s",mb.host);
1266 if (mb.port) sprintf (tmp + strlen (tmp),":%lu",mb.port);
1267 if (mb.user[0]) sprintf (tmp + strlen (tmp),"/user=%.64s",mb.user);
1268 if (mb.dbgflag) strcat (tmp,"/debug");
1269 if (mb.secflag) strcat (tmp,"/secure");
1270 if (mb.tlsflag) strcat (tmp,"/tls");
1271 if (mb.notlsflag) strcat (tmp,"/notls");
1272 if (mb.sslflag) strcat (tmp,"/ssl");
1273 if (mb.tls1) strcat (tmp,"/tls1");
1274 if (mb.tls1_1) strcat (tmp,"/tls1_1");
1275 if (mb.tls1_2) strcat (tmp,"/tls1_2");
1276 if (mb.tls1_3) strcat (tmp,"/tls1_3");
1277 if (mb.trysslflag) strcat (tmp,"/tryssl");
1278 if (mb.novalidate) strcat (tmp,"/novalidate-cert");
1279 strcat (tmp,"/pop3/loser}");
1280 mail_parameters (stream,SET_SNARFMAILBOXNAME,(void *) tmp);
1281 mail_ping (stream); /* do initial snarf */
1283 return stream; /* return local mailbox stream */
1286 else if ((options & OP_PROTOTYPE) &&
1287 ((name[1] == 'D') || (name[1] == 'd')) &&
1288 ((name[2] == 'R') || (name[2] == 'r')) &&
1289 ((name[3] == 'I') || (name[3] == 'i')) &&
1290 ((name[4] == 'V') || (name[4] == 'v')) &&
1291 ((name[5] == 'E') || (name[5] == 'e')) &&
1292 ((name[6] == 'R') || (name[6] == 'r')) && (name[7] == '.')) {
1293 sprintf (tmp,"%.80s",name+8);
1294 /* tie off name at likely delimiter */
1295 if ((s = strpbrk (tmp,"/\\:")) != NULL) *s++ = '\0';
1296 else {
1297 sprintf (tmp,"Can't resolve mailbox %.80s: bad driver syntax",name);
1298 MM_LOG (tmp,ERROR);
1299 return mail_close (stream);
1301 for (d = maildrivers; d && compare_cstring (d->name,tmp); d = d->next);
1302 if (d) return (*d->open) (NIL);
1303 sprintf (tmp,"Can't resolve mailbox %.80s: unknown driver",name);
1304 MM_LOG (tmp,ERROR);
1305 return mail_close (stream);
1307 /* fall through to default case */
1308 default: /* not special hack (but could be # name */
1309 d = mail_valid (NIL,name,(options & OP_SILENT) ?
1310 (char *) NIL : "open mailbox");
1312 return d ? mail_open_work (d,stream,name,options) : stream;
1315 /* Mail open worker routine
1316 * Accepts: factory
1317 * candidate stream for recycling
1318 * mailbox name
1319 * open options
1320 * Returns: stream to use on success, NIL on failure
1323 MAILSTREAM *mail_open_work (DRIVER *d,MAILSTREAM *stream,char *name,
1324 long options)
1326 int i;
1327 char tmp[MAILTMPLEN];
1328 NETMBX mb;
1329 if (options & OP_PROTOTYPE) return (*d->open) (NIL);
1330 /* name is copied here in case the caller does a re-open using
1331 * stream->mailbox or stream->original_mailbox as the argument.
1333 name = cpystr (name); /* make copy of name */
1334 if (stream) { /* recycling requested? */
1335 if ((stream->dtb == d) && (d->flags & DR_RECYCLE) &&
1336 ((d->flags & DR_HALFOPEN) || !(options & OP_HALFOPEN)) &&
1337 mail_usable_network_stream (stream,name)) {
1338 /* yes, checkpoint if needed */
1339 if (d->flags & DR_XPOINT) mail_check (stream);
1340 mail_free_cache (stream); /* clean up stream */
1341 if (stream->mailbox) fs_give ((void **) &stream->mailbox);
1342 if (stream->original_mailbox)
1343 fs_give ((void **) &stream->original_mailbox);
1344 /* flush user flags */
1345 for (i = 0; i < NUSERFLAGS; i++)
1346 if (stream->user_flags[i]) fs_give ((void **) &stream->user_flags[i]);
1348 else { /* stream not recycleable, babble if net */
1349 if (!stream->silent && stream->dtb && !(stream->dtb->flags&DR_LOCAL) &&
1350 mail_valid_net_parse (stream->mailbox,&mb)) {
1351 sprintf (tmp,"Closing connection to %.80s",mb.host);
1352 MM_LOG (tmp,(long) NIL);
1354 /* flush the old stream */
1355 stream = mail_close (stream);
1358 /* check if driver does not support halfopen */
1359 else if ((options & OP_HALFOPEN) && !(d->flags & DR_HALFOPEN)) {
1360 fs_give ((void **) &name);
1361 return NIL;
1364 /* instantiate new stream if not recycling */
1365 if (!stream) (*mailcache) (stream = (MAILSTREAM *)
1366 memset (fs_get (sizeof (MAILSTREAM)),0,
1367 sizeof (MAILSTREAM)),(long) 0,CH_INIT);
1368 stream->dtb = d; /* set dispatch */
1369 /* set mailbox name */
1370 stream->mailbox = cpystr (stream->original_mailbox = name);
1371 /* initialize stream flags */
1372 stream->inbox = stream->lock = NIL;
1373 stream->debug = (options & OP_DEBUG) ? T : NIL;
1374 stream->rdonly = (options & OP_READONLY) ? T : NIL;
1375 stream->anonymous = (options & OP_ANONYMOUS) ? T : NIL;
1376 stream->scache = (options & OP_SHORTCACHE) ? T : NIL;
1377 stream->silent = (options & OP_SILENT) ? T : NIL;
1378 stream->halfopen = (options & OP_HALFOPEN) ? T : NIL;
1379 stream->secure = (options & OP_SECURE) ? T : NIL;
1380 stream->tryssl = (options & OP_TRYSSL) ? T : NIL;
1381 stream->mulnewsrc = (options & OP_MULNEWSRC) ? T : NIL;
1382 stream->nokod = (options & OP_NOKOD) ? T : NIL;
1383 stream->sniff = (options & OP_SNIFF) ? T : NIL;
1384 stream->perm_seen = stream->perm_deleted = stream->perm_flagged =
1385 stream->perm_answered = stream->perm_draft = stream->kwd_create = NIL;
1386 stream->uid_nosticky = (d->flags & DR_NOSTICKY) ? T : NIL;
1387 stream->uid_last = 0; /* default UID validity */
1388 stream->uid_validity = (unsigned long) time (0);
1389 /* have driver open, flush if failed */
1390 return ((*d->open) (stream)) ? stream : mail_close (stream);
1393 /* Mail close
1394 * Accepts: mail stream
1395 * close options
1396 * Returns: NIL, always
1399 MAILSTREAM *mail_close_full (MAILSTREAM *stream,long options)
1401 int i;
1402 if (stream) { /* make sure argument given */
1403 /* do the driver's close action */
1404 if (stream->dtb) (*stream->dtb->close) (stream,options);
1405 stream->dtb = NIL; /* resign driver */
1406 if (stream->mailbox) fs_give ((void **) &stream->mailbox);
1407 if (stream->original_mailbox)
1408 fs_give ((void **) &stream->original_mailbox);
1409 if (stream->snarf.name) fs_give ((void **) &stream->snarf.name);
1410 stream->sequence++; /* invalidate sequence */
1411 /* flush user flags */
1412 for (i = 0; i < NUSERFLAGS; i++)
1413 if (stream->user_flags[i]) fs_give ((void **) &stream->user_flags[i]);
1414 mail_free_cache (stream); /* finally free the stream's storage */
1415 if (mailfreestreamsparep && stream->sparep)
1416 (*mailfreestreamsparep) (&stream->sparep);
1417 if (!stream->use) fs_give ((void **) &stream);
1419 return NIL;
1422 /* Mail make handle
1423 * Accepts: mail stream
1424 * Returns: handle
1426 * Handles provide a way to have multiple pointers to a stream yet allow the
1427 * stream's owner to nuke it or recycle it.
1430 MAILHANDLE *mail_makehandle (MAILSTREAM *stream)
1432 MAILHANDLE *handle = (MAILHANDLE *) fs_get (sizeof (MAILHANDLE));
1433 handle->stream = stream; /* copy stream */
1434 /* and its sequence */
1435 handle->sequence = stream->sequence;
1436 stream->use++; /* let stream know another handle exists */
1437 return handle;
1440 void mail_free_idlist (IDLIST **idlist)
1442 if (idlist && *idlist){
1443 if((*idlist)->name) fs_give((void **)&(*idlist)->name);
1444 if((*idlist)->value) fs_give((void **)&(*idlist)->value);
1445 if((*idlist)->next) mail_free_idlist(&(*idlist)->next);
1446 fs_give((void **) idlist);
1451 /* Mail release handle
1452 * Accepts: Mail handle
1455 void mail_free_handle (MAILHANDLE **handle)
1457 MAILSTREAM *s;
1458 if (*handle) { /* only free if exists */
1459 /* resign stream, flush unreferenced zombies */
1460 if ((!--(s = (*handle)->stream)->use) && !s->dtb) fs_give ((void **) &s);
1461 fs_give ((void **) handle); /* now flush the handle */
1466 /* Mail get stream handle
1467 * Accepts: Mail handle
1468 * Returns: mail stream or NIL if stream gone
1471 MAILSTREAM *mail_stream (MAILHANDLE *handle)
1473 MAILSTREAM *s = handle->stream;
1474 return (s->dtb && (handle->sequence == s->sequence)) ? s : NIL;
1477 /* Mail fetch cache element
1478 * Accepts: mail stream
1479 * message # to fetch
1480 * Returns: cache element of this message
1481 * Can also be used to create cache elements for new messages.
1484 MESSAGECACHE *mail_elt (MAILSTREAM *stream,unsigned long msgno)
1486 if (msgno < 1 || msgno > stream->nmsgs) {
1487 char tmp[MAILTMPLEN];
1488 sprintf (tmp,"Bad msgno %lu in mail_elt, nmsgs = %lu, mbx=%.80s",
1489 msgno,stream->nmsgs,stream->mailbox ? stream->mailbox : "???");
1490 fatal (tmp);
1492 return (MESSAGECACHE *) (*mailcache) (stream,msgno,CH_MAKEELT);
1496 /* Mail fetch fast information
1497 * Accepts: mail stream
1498 * sequence
1499 * option flags
1501 * Generally, mail_fetch_structure is preferred
1504 void mail_fetch_fast (MAILSTREAM *stream,char *sequence,long flags)
1506 /* do the driver's action */
1507 if (stream->dtb && stream->dtb->fast)
1508 (*stream->dtb->fast) (stream,sequence,flags);
1512 /* Mail fetch flags
1513 * Accepts: mail stream
1514 * sequence
1515 * option flags
1518 void mail_fetch_flags (MAILSTREAM *stream,char *sequence,long flags)
1520 /* do the driver's action */
1521 if (stream->dtb && stream->dtb->msgflags)
1522 (*stream->dtb->msgflags) (stream,sequence,flags);
1525 /* Mail fetch message overview
1526 * Accepts: mail stream
1527 * UID sequence to fetch
1528 * pointer to overview return function
1531 void mail_fetch_overview (MAILSTREAM *stream,char *sequence,overview_t ofn)
1533 if (stream->dtb && mail_uid_sequence (stream,sequence) &&
1534 !(stream->dtb->overview && (*stream->dtb->overview) (stream,ofn)) &&
1535 mail_ping (stream))
1536 mail_fetch_overview_default (stream,ofn);
1540 /* Mail fetch message overview using sequence numbers instead of UIDs
1541 * Accepts: mail stream
1542 * sequence to fetch
1543 * pointer to overview return function
1546 void mail_fetch_overview_sequence (MAILSTREAM *stream,char *sequence,
1547 overview_t ofn)
1549 if (stream->dtb && mail_sequence (stream,sequence) &&
1550 !(stream->dtb->overview && (*stream->dtb->overview) (stream,ofn)) &&
1551 mail_ping (stream))
1552 mail_fetch_overview_default (stream,ofn);
1556 /* Mail fetch message overview default handler
1557 * Accepts: mail stream with sequence bits lit
1558 * pointer to overview return function
1561 void mail_fetch_overview_default (MAILSTREAM *stream,overview_t ofn)
1563 MESSAGECACHE *elt;
1564 ENVELOPE *env;
1565 OVERVIEW ov;
1566 unsigned long i;
1567 ov.optional.lines = 0;
1568 ov.optional.xref = NIL;
1569 for (i = 1; i <= stream->nmsgs; i++)
1570 if (((elt = mail_elt (stream,i))->sequence) &&
1571 (env = mail_fetch_structure (stream,i,NIL,NIL)) && ofn) {
1572 ov.subject = env->subject;
1573 ov.from = env->from;
1574 ov.date = env->date;
1575 ov.message_id = env->message_id;
1576 ov.references = env->references;
1577 ov.optional.octets = elt->rfc822_size;
1578 (*ofn) (stream,mail_uid (stream,i),&ov,i);
1582 /* Mail fetch message structure
1583 * Accepts: mail stream
1584 * message # to fetch
1585 * pointer to return body
1586 * option flags
1587 * Returns: envelope of this message, body returned in body value
1589 * Fetches the "fast" information as well
1592 ENVELOPE *mail_fetch_structure (MAILSTREAM *stream,unsigned long msgno,
1593 BODY **body,long flags)
1595 ENVELOPE **env;
1596 BODY **b;
1597 MESSAGECACHE *elt;
1598 char c,*s,*hdr;
1599 unsigned long hdrsize;
1600 STRING bs;
1601 /* do the driver's action if specified */
1602 if (stream->dtb && stream->dtb->structure)
1603 return (*stream->dtb->structure) (stream,msgno,body,flags);
1604 if (flags & FT_UID) { /* UID form of call */
1605 if ((msgno = mail_msgno (stream,msgno)) != 0L) flags &= ~FT_UID;
1606 else return NIL; /* must get UID/msgno map first */
1608 elt = mail_elt (stream,msgno);/* get elt for real message number */
1609 if (stream->scache) { /* short caching */
1610 if (msgno != stream->msgno){/* garbage collect if not same message */
1611 mail_gc (stream,GC_ENV | GC_TEXTS);
1612 stream->msgno = msgno; /* this is the current message now */
1614 env = &stream->env; /* get pointers to envelope and body */
1615 b = &stream->body;
1617 else { /* get pointers to elt envelope and body */
1618 env = &elt->private.msg.env;
1619 b = &elt->private.msg.body;
1622 if (stream->dtb && ((body && !*b) || !*env || (*env)->incomplete)) {
1623 mail_free_envelope (env); /* flush old envelope and body */
1624 mail_free_body (b);
1625 /* see if need to fetch the whole thing */
1626 if (body || !elt->rfc822_size) {
1627 s = (*stream->dtb->header) (stream,msgno,&hdrsize,flags & ~FT_INTERNAL);
1628 /* make copy in case body fetch smashes it */
1629 hdr = (char *) memcpy (fs_get ((size_t) hdrsize+1),s,(size_t) hdrsize);
1630 hdr[hdrsize] = '\0'; /* tie off header */
1631 (*stream->dtb->text) (stream,msgno,&bs,(flags & ~FT_INTERNAL) | FT_PEEK);
1632 if (!elt->rfc822_size) elt->rfc822_size = hdrsize + SIZE (&bs);
1633 if (body) /* only parse body if requested */
1634 rfc822_parse_msg (env,b,hdr,hdrsize,&bs,BADHOST,stream->dtb->flags);
1635 else
1636 rfc822_parse_msg (env,NIL,hdr,hdrsize,NIL,BADHOST,stream->dtb->flags);
1637 fs_give ((void **) &hdr); /* flush header */
1639 else { /* can save memory doing it this way */
1640 hdr = (*stream->dtb->header) (stream,msgno,&hdrsize,flags | FT_INTERNAL);
1641 if (hdrsize) { /* in case null header */
1642 c = hdr[hdrsize]; /* preserve what's there */
1643 hdr[hdrsize] = '\0'; /* tie off header */
1644 rfc822_parse_msg (env,NIL,hdr,hdrsize,NIL,BADHOST,stream->dtb->flags);
1645 hdr[hdrsize] = c; /* restore in case cached data */
1647 else *env = mail_newenvelope ();
1650 /* if need date, have date in envelope? */
1651 if (!elt->day && *env && (*env)->date) mail_parse_date (elt,(*env)->date);
1652 /* sigh, fill in bogus default */
1653 if (!elt->day) elt->day = elt->month = 1;
1654 if (body) *body = *b; /* return the body */
1655 return *env; /* return the envelope */
1658 /* Mail mark single message (internal use only)
1659 * Accepts: mail stream
1660 * elt to mark
1661 * fetch flags
1664 static void markseen (MAILSTREAM *stream,MESSAGECACHE *elt,long flags)
1666 unsigned long i;
1667 char sequence[20];
1668 MESSAGECACHE *e;
1669 /* non-peeking and needs to set \Seen? */
1670 if (!(flags & FT_PEEK) && !elt->seen) {
1671 if (stream->dtb->flagmsg){ /* driver wants per-message call? */
1672 elt->valid = NIL; /* do pre-alteration driver call */
1673 (*stream->dtb->flagmsg) (stream,elt);
1674 /* set seen, do post-alteration driver call */
1675 elt->seen = elt->valid = T;
1676 (*stream->dtb->flagmsg) (stream,elt);
1678 if (stream->dtb->flag) { /* driver wants one-time call? */
1679 /* better safe than sorry, save seq bits */
1680 for (i = 1; i <= stream->nmsgs; i++) {
1681 e = mail_elt (stream,i);
1682 e->private.sequence = e->sequence;
1684 /* call driver to set the message */
1685 sprintf (sequence,"%lu",elt->msgno);
1686 (*stream->dtb->flag) (stream,sequence,"\\Seen",ST_SET);
1687 /* restore sequence bits */
1688 for (i = 1; i <= stream->nmsgs; i++) {
1689 e = mail_elt (stream,i);
1690 e->sequence = e->private.sequence;
1693 /* notify mail program of flag change */
1694 MM_FLAGS (stream,elt->msgno);
1698 /* Mail fetch message
1699 * Accepts: mail stream
1700 * message # to fetch
1701 * pointer to returned length
1702 * flags
1703 * Returns: message text
1706 char *mail_fetch_message (MAILSTREAM *stream,unsigned long msgno,
1707 unsigned long *len,long flags)
1709 GETS_DATA md;
1710 SIZEDTEXT *t;
1711 STRING bs;
1712 MESSAGECACHE *elt;
1713 char *s,*u;
1714 unsigned long i,j;
1715 if (len) *len = 0; /* default return size */
1716 if (flags & FT_UID) { /* UID form of call */
1717 if ((msgno = mail_msgno (stream,msgno)) != 0L) flags &= ~FT_UID;
1718 else return ""; /* must get UID/msgno map first */
1720 /* initialize message data identifier */
1721 INIT_GETS (md,stream,msgno,"",0,0);
1722 /* is data already cached? */
1723 if ((t = &(elt = mail_elt (stream,msgno))->private.msg.full.text)->data) {
1724 markseen (stream,elt,flags);/* mark message seen */
1725 return mail_fetch_text_return (&md,t,len);
1727 if (!stream->dtb) return ""; /* not in cache, must have live driver */
1728 if (stream->dtb->msgdata) return
1729 ((*stream->dtb->msgdata) (stream,msgno,"",0,0,NIL,flags) && t->data) ?
1730 mail_fetch_text_return (&md,t,len) : "";
1731 /* ugh, have to do this the crufty way */
1732 u = mail_fetch_header (stream,msgno,NIL,NIL,&i,flags);
1733 /* copy in case text method stomps on it */
1734 s = (char *) memcpy (fs_get ((size_t) i),u,(size_t) i);
1735 if ((*stream->dtb->text) (stream,msgno,&bs,flags)) {
1736 t = &stream->text; /* build combined copy */
1737 if (t->data) fs_give ((void **) &t->data);
1738 t->data = (unsigned char *) fs_get ((t->size = i + SIZE (&bs)) + 1);
1739 if (!elt->rfc822_size) elt->rfc822_size = t->size;
1740 else if (elt->rfc822_size != t->size) {
1741 char tmp[MAILTMPLEN];
1742 sprintf (tmp,"Calculated RFC822.SIZE (%lu) != reported size (%lu)",
1743 t->size,elt->rfc822_size);
1744 mm_log (tmp,WARN); /* bug trap */
1746 memcpy (t->data,s,(size_t) i);
1747 for (u = (char *) t->data + i, j = SIZE (&bs); j;) {
1748 memcpy (u,bs.curpos,bs.cursize);
1749 u += bs.cursize; /* update text */
1750 j -= bs.cursize;
1751 bs.curpos += (bs.cursize -1);
1752 bs.cursize = 0;
1753 (*bs.dtb->next) (&bs); /* advance to next buffer's worth */
1755 *u = '\0'; /* tie off data */
1756 u = mail_fetch_text_return (&md,t,len);
1758 else u = "";
1759 fs_give ((void **) &s); /* finished with copy of header */
1760 return u;
1763 /* Mail fetch message header
1764 * Accepts: mail stream
1765 * message # to fetch
1766 * MIME section specifier (#.#.#...#)
1767 * list of lines to fetch
1768 * pointer to returned length
1769 * flags
1770 * Returns: message header in RFC822 format
1772 * Note: never calls a mailgets routine
1775 char *mail_fetch_header (MAILSTREAM *stream,unsigned long msgno,char *section,
1776 STRINGLIST *lines,unsigned long *len,long flags)
1778 STRING bs;
1779 BODY *b = NIL;
1780 SIZEDTEXT *t = NIL,rt;
1781 MESSAGE *m = NIL;
1782 MESSAGECACHE *elt;
1783 char tmp[MAILTMPLEN];
1784 if (len) *len = 0; /* default return size */
1785 if (section && (strlen (section) > (MAILTMPLEN - 20))) return "";
1786 if (flags & FT_UID) { /* UID form of call */
1787 if ((msgno = mail_msgno (stream,msgno)) != 0L) flags &= ~FT_UID;
1788 else return ""; /* must get UID/msgno map first */
1790 elt = mail_elt (stream,msgno);/* get cache data */
1791 if (section && *section) { /* nested body header wanted? */
1792 if (!((b = mail_body (stream,msgno,section)) &&
1793 (b->type == TYPEMESSAGE) && !strcmp (b->subtype,"RFC822")))
1794 return ""; /* lose if no body or not MESSAGE/RFC822 */
1795 m = b->nested.msg; /* point to nested message */
1797 /* else top-level message header wanted */
1798 else m = &elt->private.msg;
1799 if (m->header.text.data && mail_match_lines (lines,m->lines,flags)) {
1800 if (lines) textcpy (t = &stream->text,&m->header.text);
1801 else t = &m->header.text; /* in cache, and cache is valid */
1802 markseen (stream,elt,flags);/* mark message seen */
1805 else if (stream->dtb) { /* not in cache, has live driver? */
1806 if (stream->dtb->msgdata) { /* has driver section fetch? */
1807 /* build driver section specifier */
1808 if (section && *section) sprintf (tmp,"%s.HEADER",section);
1809 else strcpy (tmp,"HEADER");
1810 if ((*stream->dtb->msgdata) (stream,msgno,tmp,0,0,lines,flags)) {
1811 t = &m->header.text; /* fetch data */
1812 /* don't need to postprocess lines */
1813 if (m->lines) lines = NIL;
1814 else if (lines) textcpy (t = &stream->text,&m->header.text);
1817 else if (b) { /* nested body wanted? */
1818 if (stream->private.search.text) {
1819 rt.data = (unsigned char *) stream->private.search.text +
1820 b->nested.msg->header.offset;
1821 rt.size = b->nested.msg->header.text.size;
1822 t = &rt;
1824 else if ((*stream->dtb->text) (stream,msgno,&bs,flags & ~FT_INTERNAL)) {
1825 if ((bs.dtb->next == mail_string_next) && !lines) {
1826 rt.data = (unsigned char *) bs.curpos + b->nested.msg->header.offset;
1827 rt.size = b->nested.msg->header.text.size;
1828 if (stream->private.search.string)
1829 stream->private.search.text = bs.curpos;
1830 t = &rt; /* special hack to avoid extra copy */
1832 else textcpyoffstring (t = &stream->text,&bs,
1833 b->nested.msg->header.offset,
1834 b->nested.msg->header.text.size);
1837 else { /* top-level header fetch */
1838 /* mark message seen */
1839 markseen (stream,elt,flags);
1840 if ((rt.data = (unsigned char *)
1841 (*stream->dtb->header) (stream,msgno,&rt.size,flags)) != NULL) {
1842 /* make a safe copy if need to filter */
1843 if (lines) textcpy (t = &stream->text,&rt);
1844 else t = &rt; /* top level header */
1848 if (!t || !t->data) return "";/* error if no string */
1849 /* filter headers if requested */
1850 if (lines) t->size = mail_filter ((char *) t->data,t->size,lines,flags);
1851 if (len) *len = t->size; /* return size if requested */
1852 return (char *) t->data; /* and text */
1855 /* Mail fetch message text
1856 * Accepts: mail stream
1857 * message # to fetch
1858 * MIME section specifier (#.#.#...#)
1859 * pointer to returned length
1860 * flags
1861 * Returns: message text
1864 char *mail_fetch_text (MAILSTREAM *stream,unsigned long msgno,char *section,
1865 unsigned long *len,long flags)
1867 GETS_DATA md;
1868 PARTTEXT *p;
1869 STRING bs;
1870 MESSAGECACHE *elt;
1871 BODY *b = NIL;
1872 char tmp[MAILTMPLEN];
1873 unsigned long i;
1874 if (len) *len = 0; /* default return size */
1875 memset (&stream->private.string,NIL,sizeof (STRING));
1876 if (section && (strlen (section) > (MAILTMPLEN - 20))) return "";
1877 if (flags & FT_UID) { /* UID form of call */
1878 if ((msgno = mail_msgno (stream,msgno)) != 0L) flags &= ~FT_UID;
1879 else return ""; /* must get UID/msgno map first */
1881 elt = mail_elt (stream,msgno);/* get cache data */
1882 if (section && *section) { /* nested body text wanted? */
1883 if (!((b = mail_body (stream,msgno,section)) &&
1884 (b->type == TYPEMESSAGE) && !strcmp (b->subtype,"RFC822")))
1885 return ""; /* lose if no body or not MESSAGE/RFC822 */
1886 p = &b->nested.msg->text; /* point at nested message */
1887 /* build IMAP-format section specifier */
1888 sprintf (tmp,"%s.TEXT",section);
1889 flags &= ~FT_INTERNAL; /* can't win with this set */
1891 else { /* top-level message text wanted */
1892 p = &elt->private.msg.text;
1893 strcpy (tmp,"TEXT");
1895 /* initialize message data identifier */
1896 INIT_GETS (md,stream,msgno,section,0,0);
1897 if (p->text.data) { /* is data already cached? */
1898 markseen (stream,elt,flags);/* mark message seen */
1899 return mail_fetch_text_return (&md,&p->text,len);
1901 if (!stream->dtb) return ""; /* not in cache, must have live driver */
1902 if (stream->dtb->msgdata) return
1903 ((*stream->dtb->msgdata) (stream,msgno,tmp,0,0,NIL,flags) && p->text.data)?
1904 mail_fetch_text_return (&md,&p->text,len) : "";
1905 if (!(*stream->dtb->text) (stream,msgno,&bs,flags)) return "";
1906 if (section && *section) { /* nested is more complex */
1907 SETPOS (&bs,p->offset);
1908 i = p->text.size; /* just want this much */
1910 else i = SIZE (&bs); /* want entire text */
1911 return mail_fetch_string_return (&md,&bs,i,len,flags);
1914 /* Mail fetch message body part MIME headers
1915 * Accepts: mail stream
1916 * message # to fetch
1917 * MIME section specifier (#.#.#...#)
1918 * pointer to returned length
1919 * flags
1920 * Returns: message text
1923 char *mail_fetch_mime (MAILSTREAM *stream,unsigned long msgno,char *section,
1924 unsigned long *len,long flags)
1926 PARTTEXT *p;
1927 STRING bs;
1928 BODY *b;
1929 char tmp[MAILTMPLEN];
1930 if (len) *len = 0; /* default return size */
1931 if (section && (strlen (section) > (MAILTMPLEN - 20))) return "";
1932 if (flags & FT_UID) { /* UID form of call */
1933 if ((msgno = mail_msgno (stream,msgno)) != 0L) flags &= ~FT_UID;
1934 else return ""; /* must get UID/msgno map first */
1936 flags &= ~FT_INTERNAL; /* can't win with this set */
1937 if (!(section && *section && (b = mail_body (stream,msgno,section))))
1938 return ""; /* not valid section */
1939 /* in cache? */
1940 if ((p = &b->mime)->text.data) {
1941 /* mark message seen */
1942 markseen (stream,mail_elt (stream,msgno),flags);
1943 if (len) *len = p->text.size;
1944 return (char *) p->text.data;
1946 if (!stream->dtb) return ""; /* not in cache, must have live driver */
1947 if (stream->dtb->msgdata) { /* has driver fetch? */
1948 /* build driver section specifier */
1949 sprintf (tmp,"%s.MIME",section);
1950 if ((*stream->dtb->msgdata) (stream,msgno,tmp,0,0,NIL,flags) &&
1951 p->text.data) {
1952 if (len) *len = p->text.size;
1953 return (char *) p->text.data;
1955 else return "";
1957 if (len) *len = b->mime.text.size;
1958 if (!b->mime.text.size) { /* empty MIME header -- mark seen anyway */
1959 markseen (stream,mail_elt (stream,msgno),flags);
1960 return "";
1962 /* have to get it from offset */
1963 if (stream->private.search.text)
1964 return stream->private.search.text + b->mime.offset;
1965 if (!(*stream->dtb->text) (stream,msgno,&bs,flags)) {
1966 if (len) *len = 0;
1967 return "";
1969 if (bs.dtb->next == mail_string_next) {
1970 if (stream->private.search.string) stream->private.search.text = bs.curpos;
1971 return bs.curpos + b->mime.offset;
1973 return textcpyoffstring (&stream->text,&bs,b->mime.offset,b->mime.text.size);
1976 /* Mail fetch message body part
1977 * Accepts: mail stream
1978 * message # to fetch
1979 * MIME section specifier (#.#.#...#)
1980 * pointer to returned length
1981 * flags
1982 * Returns: message body
1985 char *mail_fetch_body (MAILSTREAM *stream,unsigned long msgno,char *section,
1986 unsigned long *len,long flags)
1988 GETS_DATA md;
1989 PARTTEXT *p;
1990 STRING bs;
1991 BODY *b;
1992 SIZEDTEXT *t;
1993 char *s,tmp[MAILTMPLEN];
1994 memset (&stream->private.string,NIL,sizeof (STRING));
1995 if (!(section && *section)) /* top-level text wanted? */
1996 return mail_fetch_message (stream,msgno,len,flags);
1997 else if (strlen (section) > (MAILTMPLEN - 20)) return "";
1998 flags &= ~FT_INTERNAL; /* can't win with this set */
1999 /* initialize message data identifier */
2000 INIT_GETS (md,stream,msgno,section,0,0);
2001 /* kludge for old section 0 header */
2002 if (!strcmp (s = strcpy (tmp,section),"0") ||
2003 ((s = strstr (tmp,".0")) && !s[2])) {
2004 SIZEDTEXT ht;
2005 *s = '\0'; /* tie off section */
2006 /* this silly way so it does mailgets */
2007 ht.data = (unsigned char *) mail_fetch_header (stream,msgno,
2008 tmp[0] ? tmp : NIL,NIL,
2009 &ht.size,flags);
2010 /* may have UIDs here */
2011 md.flags = (flags & FT_UID) ? MG_UID : NIL;
2012 return mail_fetch_text_return (&md,&ht,len);
2014 if (len) *len = 0; /* default return size */
2015 if (flags & FT_UID) { /* UID form of call */
2016 if ((msgno = mail_msgno (stream,msgno)) != 0L) flags &= ~FT_UID;
2017 else return ""; /* must get UID/msgno map first */
2019 /* must have body */
2020 if (!(b = mail_body (stream,msgno,section))) return "";
2021 /* have cached text? */
2022 if ((t = &(p = &b->contents)->text)->data) {
2023 /* mark message seen */
2024 markseen (stream,mail_elt (stream,msgno),flags);
2025 return mail_fetch_text_return (&md,t,len);
2027 if (!stream->dtb) return ""; /* not in cache, must have live driver */
2028 if (stream->dtb->msgdata) return
2029 ((*stream->dtb->msgdata)(stream,msgno,section,0,0,NIL,flags) && t->data) ?
2030 mail_fetch_text_return (&md,t,len) : "";
2031 if (len) *len = t->size;
2032 if (!t->size) { /* empty body part -- mark seen anyway */
2033 markseen (stream,mail_elt (stream,msgno),flags);
2034 return "";
2036 /* copy body from stringstruct offset */
2037 if (stream->private.search.text)
2038 return stream->private.search.text + p->offset;
2039 if (!(*stream->dtb->text) (stream,msgno,&bs,flags)) {
2040 if (len) *len = 0;
2041 return "";
2043 if (bs.dtb->next == mail_string_next) {
2044 if (stream->private.search.string) stream->private.search.text = bs.curpos;
2045 return bs.curpos + p->offset;
2047 SETPOS (&bs,p->offset);
2048 return mail_fetch_string_return (&md,&bs,t->size,len,flags);
2051 /* Mail fetch partial message text
2052 * Accepts: mail stream
2053 * message # to fetch
2054 * MIME section specifier (#.#.#...#)
2055 * offset of first designed byte or 0 to start at beginning
2056 * maximum number of bytes or 0 for all bytes
2057 * flags
2058 * Returns: T if successful, else NIL
2061 long mail_partial_text (MAILSTREAM *stream,unsigned long msgno,char *section,
2062 unsigned long first,unsigned long last,long flags)
2064 GETS_DATA md;
2065 PARTTEXT *p = NIL;
2066 MESSAGECACHE *elt;
2067 STRING bs;
2068 BODY *b;
2069 char tmp[MAILTMPLEN];
2070 unsigned long i;
2071 if (!mailgets) fatal ("mail_partial_text() called without a mailgets!");
2072 if (section && (strlen (section) > (MAILTMPLEN - 20))) return NIL;
2073 if (flags & FT_UID) { /* UID form of call */
2074 if ((msgno = mail_msgno (stream,msgno)) != 0L) flags &= ~FT_UID;
2075 else return NIL; /* must get UID/msgno map first */
2077 elt = mail_elt (stream,msgno);/* get cache data */
2078 flags &= ~FT_INTERNAL; /* bogus if this is set */
2079 if (section && *section) { /* nested body text wanted? */
2080 if (!((b = mail_body (stream,msgno,section)) &&
2081 (b->type == TYPEMESSAGE) && !strcmp (b->subtype,"RFC822")))
2082 return NIL; /* lose if no body or not MESSAGE/RFC822 */
2083 p = &b->nested.msg->text; /* point at nested message */
2084 /* build IMAP-format section specifier */
2085 sprintf (tmp,"%s.TEXT",section);
2087 else { /* else top-level message text wanted */
2088 p = &elt->private.msg.text;
2089 strcpy (tmp,"TEXT");
2092 /* initialize message data identifier */
2093 INIT_GETS (md,stream,msgno,tmp,first,last);
2094 if (p->text.data) { /* is data already cached? */
2095 INIT (&bs,mail_string,p->text.data,i = p->text.size);
2096 markseen (stream,elt,flags);/* mark message seen */
2098 else { /* else get data from driver */
2099 if (!stream->dtb) return NIL;
2100 if (stream->dtb->msgdata) /* driver will handle this */
2101 return (*stream->dtb->msgdata) (stream,msgno,tmp,first,last,NIL,flags);
2102 if (!(*stream->dtb->text) (stream,msgno,&bs,flags)) return NIL;
2103 if (section && *section) { /* nexted if more complex */
2104 SETPOS (&bs,p->offset); /* offset stringstruct to data */
2105 i = p->text.size; /* maximum size of data */
2107 else i = SIZE (&bs); /* just want this much */
2109 if (i <= first) i = first = 0;/* first byte is beyond end of text */
2110 /* truncate as needed */
2111 else { /* offset and truncate */
2112 SETPOS (&bs,first + GETPOS (&bs));
2113 i -= first; /* reduced size */
2114 if (last && (i > last)) i = last;
2116 /* do the mailgets thing */
2117 (*mailgets) (mail_read,&bs,i,&md);
2118 return T; /* success */
2121 /* Mail fetch partial message body part
2122 * Accepts: mail stream
2123 * message # to fetch
2124 * MIME section specifier (#.#.#...#)
2125 * offset of first designed byte or 0 to start at beginning
2126 * maximum number of bytes or 0 for all bytes
2127 * flags
2128 * Returns: T if successful, else NIL
2131 long mail_partial_body (MAILSTREAM *stream,unsigned long msgno,char *section,
2132 unsigned long first,unsigned long last,long flags)
2134 GETS_DATA md;
2135 PARTTEXT *p;
2136 STRING bs;
2137 BODY *b;
2138 SIZEDTEXT *t;
2139 unsigned long i;
2140 if (!(section && *section)) /* top-level text wanted? */
2141 return mail_partial_text (stream,msgno,NIL,first,last,flags);
2142 if (!mailgets) fatal ("mail_partial_body() called without a mailgets!");
2143 if (flags & FT_UID) { /* UID form of call */
2144 if ((msgno = mail_msgno (stream,msgno)) != 0L) flags &= ~FT_UID;
2145 else return NIL; /* must get UID/msgno map first */
2147 /* must have body */
2148 if (!(b = mail_body (stream,msgno,section))) return NIL;
2149 flags &= ~FT_INTERNAL; /* bogus if this is set */
2151 /* initialize message data identifier */
2152 INIT_GETS (md,stream,msgno,section,first,last);
2153 /* have cached text? */
2154 if ((t = &(p = &b->contents)->text)->data) {
2155 /* mark message seen */
2156 markseen (stream,mail_elt (stream,msgno),flags);
2157 INIT (&bs,mail_string,t->data,i = t->size);
2159 else { /* else get data from driver */
2160 if (!stream->dtb) return NIL;
2161 if (stream->dtb->msgdata) /* driver will handle this */
2162 return (*stream->dtb->msgdata) (stream,msgno,section,first,last,NIL,
2163 flags);
2164 if (!(*stream->dtb->text) (stream,msgno,&bs,flags)) return NIL;
2165 if (section && *section) { /* nexted if more complex */
2166 SETPOS (&bs,p->offset); /* offset stringstruct to data */
2167 i = t->size; /* maximum size of data */
2169 else i = SIZE (&bs); /* just want this much */
2171 if (i <= first) i = first = 0;/* first byte is beyond end of text */
2172 else { /* offset and truncate */
2173 SETPOS (&bs,first + GETPOS (&bs));
2174 i -= first; /* reduced size */
2175 if (last && (i > last)) i = last;
2177 /* do the mailgets thing */
2178 (*mailgets) (mail_read,&bs,i,&md);
2179 return T; /* success */
2182 /* Mail return message text
2183 * Accepts: identifier data
2184 * sized text
2185 * pointer to returned length
2186 * Returns: text
2189 char *mail_fetch_text_return (GETS_DATA *md,SIZEDTEXT *t,unsigned long *len)
2191 STRING bs;
2192 if (len) *len = t->size; /* return size */
2193 if (t->size && mailgets) { /* have to do the mailgets thing? */
2194 /* silly but do it anyway for consistency */
2195 INIT (&bs,mail_string,t->data,t->size);
2196 return (*mailgets) (mail_read,&bs,t->size,md);
2198 return t->size ? (char *) t->data : "";
2202 /* Mail return message string
2203 * Accepts: identifier data
2204 * stringstruct
2205 * text length
2206 * pointer to returned length
2207 * flags
2208 * Returns: text, or NIL if stringstruct returned
2211 char *mail_fetch_string_return (GETS_DATA *md,STRING *bs,unsigned long i,
2212 unsigned long *len,long flags)
2214 char *ret = NIL;
2215 if (len) *len = i; /* return size */
2216 /* return stringstruct hack */
2217 if (flags & FT_RETURNSTRINGSTRUCT) {
2218 memcpy (&md->stream->private.string,bs,sizeof (STRING));
2219 SETPOS (&md->stream->private.string,GETPOS (&md->stream->private.string));
2221 /* have to do the mailgets thing? */
2222 else if (mailgets) ret = (*mailgets) (mail_read,bs,i,md);
2223 /* special hack to avoid extra copy */
2224 else if (bs->dtb->next == mail_string_next) ret = bs->curpos;
2225 /* make string copy in memory */
2226 else ret = textcpyoffstring (&md->stream->text,bs,GETPOS (bs),i);
2227 return ret;
2230 /* Read data from stringstruct
2231 * Accepts: stringstruct
2232 * size of data to read
2233 * buffer to read into
2234 * Returns: T, always, stringstruct updated
2237 long mail_read (void *stream,unsigned long size,char *buffer)
2239 unsigned long i;
2240 STRING *s = (STRING *) stream;
2241 while (size) { /* until satisfied */
2242 memcpy (buffer,s->curpos,i = min (s->cursize,size));
2243 buffer += i; /* update buffer */
2244 size -= i; /* note that we read this much */
2245 s->curpos += --i; /* advance that many spaces minus 1 */
2246 s->cursize -= i;
2247 SNX (s); /* now use SNX to advance the last byte */
2249 return T;
2252 /* Mail fetch UID
2253 * Accepts: mail stream
2254 * message number
2255 * Returns: UID or zero if dead stream
2258 unsigned long mail_uid (MAILSTREAM *stream,unsigned long msgno)
2260 unsigned long uid = mail_elt (stream,msgno)->private.uid;
2261 return uid ? uid :
2262 (stream->dtb && stream->dtb->uid) ? (*stream->dtb->uid) (stream,msgno) : 0;
2266 /* Mail fetch msgno from UID
2267 * Accepts: mail stream
2268 * UID
2269 * Returns: msgno or zero if failed
2272 unsigned long mail_msgno (MAILSTREAM *stream,unsigned long uid)
2274 unsigned long msgno,delta,first,firstuid,last,lastuid,middle,miduid;
2275 if (stream->dtb) { /* active stream? */
2276 if (stream->dtb->msgno) /* direct way */
2277 return (*stream->dtb->msgno) (stream,uid);
2278 else if (stream->dtb->uid) {/* indirect way */
2279 /* Placeholder for now, since currently there are no drivers which
2280 * have a uid method but not a msgno method
2282 for (msgno = 1; msgno <= stream->nmsgs; msgno++)
2283 if ((*stream->dtb->uid) (stream,msgno) == uid) return msgno;
2285 /* binary search since have full map */
2286 else for (first = 1,last = stream->nmsgs, delta = (first <= last) ? 1 : 0;
2287 delta &&
2288 (uid >= (firstuid = mail_elt (stream,first)->private.uid)) &&
2289 (uid <= (lastuid = mail_elt (stream,last)->private.uid));) {
2290 /* done if match at an endpoint */
2291 if (uid == firstuid) return first;
2292 if (uid == lastuid) return last;
2293 /* have anything between endpoints? */
2294 if ((delta = ((last - first) / 2)) != 0L){
2295 if ((miduid = mail_elt (stream,middle = first + delta)->private.uid)
2296 == uid)
2297 return middle; /* found match in middle */
2298 else if (uid < miduid) last = middle - 1;
2299 else first = middle + 1;
2303 else { /* dead stream, do linear search for UID */
2304 for (msgno = 1; msgno <= stream->nmsgs; msgno++)
2305 if (mail_elt (stream,msgno)->private.uid == uid) return msgno;
2307 return 0; /* didn't find the UID anywhere */
2310 /* Mail fetch From string for menu
2311 * Accepts: destination string
2312 * mail stream
2313 * message # to fetch
2314 * desired string length
2315 * Returns: string of requested length
2318 void mail_fetchfrom (char *s,MAILSTREAM *stream,unsigned long msgno,
2319 long length)
2321 char *t;
2322 char tmp[MAILTMPLEN];
2323 ENVELOPE *env = mail_fetchenvelope (stream,msgno);
2324 ADDRESS *adr = env ? env->from : NIL;
2325 memset (s,' ',(size_t)length);/* fill it with spaces */
2326 s[length] = '\0'; /* tie off with null */
2327 /* get first from address from envelope */
2328 while (adr && !adr->host) adr = adr->next;
2329 if (adr) { /* if a personal name exists use it */
2330 if (!(t = adr->personal))
2331 sprintf (t = tmp,"%.256s@%.256s",adr->mailbox,adr->host);
2332 memcpy (s,t,(size_t) min (length,(long) strlen (t)));
2337 /* Mail fetch Subject string for menu
2338 * Accepts: destination string
2339 * mail stream
2340 * message # to fetch
2341 * desired string length
2342 * Returns: string of no more than requested length
2345 void mail_fetchsubject (char *s,MAILSTREAM *stream,unsigned long msgno,
2346 long length)
2348 ENVELOPE *env = mail_fetchenvelope (stream,msgno);
2349 memset (s,'\0',(size_t) length+1);
2350 /* copy subject from envelope */
2351 if (env && env->subject) strncpy (s,env->subject,(size_t) length);
2352 else *s = ' '; /* if no subject then just a space */
2355 /* Mail modify flags
2356 * Accepts: mail stream
2357 * sequence
2358 * flag(s)
2359 * option flags
2362 void mail_flag (MAILSTREAM *stream,char *sequence,char *flag,long flags)
2364 MESSAGECACHE *elt;
2365 unsigned long i,uf;
2366 long f;
2367 short nf;
2368 if (!stream->dtb) return; /* no-op if no stream */
2369 if ((stream->dtb->flagmsg || !stream->dtb->flag) &&
2370 ((flags & ST_UID) ? mail_uid_sequence (stream,sequence) :
2371 mail_sequence (stream,sequence)) &&
2372 ((f = mail_parse_flags (stream,flag,&uf)) || uf))
2373 for (i = 1,nf = (flags & ST_SET) ? T : NIL; i <= stream->nmsgs; i++)
2374 if ((elt = mail_elt (stream,i))->sequence) {
2375 struct { /* old flags */
2376 unsigned int valid : 1;
2377 unsigned int seen : 1;
2378 unsigned int deleted : 1;
2379 unsigned int flagged : 1;
2380 unsigned int answered : 1;
2381 unsigned int draft : 1;
2382 unsigned long user_flags;
2383 } old;
2384 old.valid = elt->valid; old.seen = elt->seen;
2385 old.deleted = elt->deleted; old.flagged = elt->flagged;
2386 old.answered = elt->answered; old.draft = elt->draft;
2387 old.user_flags = elt->user_flags;
2388 elt->valid = NIL; /* prepare for flag alteration */
2389 if (stream->dtb->flagmsg) (*stream->dtb->flagmsg) (stream,elt);
2390 if (f&fSEEN) elt->seen = nf;
2391 if (f&fDELETED) elt->deleted = nf;
2392 if (f&fFLAGGED) elt->flagged = nf;
2393 if (f&fANSWERED) elt->answered = nf;
2394 if (f&fDRAFT) elt->draft = nf;
2395 /* user flags */
2396 if (flags & ST_SET) elt->user_flags |= uf;
2397 else elt->user_flags &= ~uf;
2398 elt->valid = T; /* flags now altered */
2399 if ((old.valid != elt->valid) || (old.seen != elt->seen) ||
2400 (old.deleted != elt->deleted) || (old.flagged != elt->flagged) ||
2401 (old.answered != elt->answered) || (old.draft != elt->draft) ||
2402 (old.user_flags != elt->user_flags))
2403 MM_FLAGS (stream,elt->msgno);
2404 if (stream->dtb->flagmsg) (*stream->dtb->flagmsg) (stream,elt);
2406 /* call driver once */
2407 if (stream->dtb->flag) (*stream->dtb->flag) (stream,sequence,flag,flags);
2410 /* Mail search for messages
2411 * Accepts: mail stream
2412 * character set
2413 * search program
2414 * option flags
2415 * Returns: T if successful, NIL if dead stream, NIL searchpgm or bad charset
2418 long mail_search_full (MAILSTREAM *stream,char *charset,SEARCHPGM *pgm,
2419 long flags)
2421 unsigned long i;
2422 long ret = NIL;
2423 if (!(flags & SE_RETAIN)) /* clear search vector unless retaining */
2424 for (i = 1; i <= stream->nmsgs; ++i) mail_elt (stream,i)->searched = NIL;
2425 if (pgm && stream->dtb) /* must have a search program and driver */
2426 ret = (*(stream->dtb->search ? stream->dtb->search : mail_search_default))
2427 (stream,charset,pgm,flags);
2428 /* flush search program if requested */
2429 if (flags & SE_FREE) mail_free_searchpgm (&pgm);
2430 return ret;
2434 /* Mail search for messages default handler
2435 * Accepts: mail stream
2436 * character set
2437 * search program
2438 * option flags
2439 * Returns: T if successful, NIL if bad charset
2442 long mail_search_default (MAILSTREAM *stream,char *charset,SEARCHPGM *pgm,
2443 long flags)
2445 unsigned long i;
2446 char *msg;
2447 /* make sure that charset is good */
2448 if ((msg = utf8_badcharset (charset)) != NULL) {
2449 MM_LOG (msg,ERROR); /* output error */
2450 fs_give ((void **) &msg);
2451 return NIL;
2453 utf8_searchpgm (pgm,charset);
2454 for (i = 1; i <= stream->nmsgs; ++i)
2455 if (mail_search_msg (stream,i,NIL,pgm)) {
2456 if (flags & SE_UID) mm_searched (stream,mail_uid (stream,i));
2457 else { /* mark as searched, notify mail program */
2458 mail_elt (stream,i)->searched = T;
2459 if (!stream->silent) mm_searched (stream,i);
2462 return LONGT; /* search completed */
2465 /* Mail ping mailbox
2466 * Accepts: mail stream
2467 * Returns: stream if still open else NIL
2470 long mail_ping (MAILSTREAM *stream)
2472 unsigned long i,n,uf,len;
2473 char *s,*f,tmp[MAILTMPLEN],flags[MAILTMPLEN];
2474 MAILSTREAM *snarf;
2475 MESSAGECACHE *elt;
2476 STRING bs;
2477 long ret;
2478 /* do driver action */
2479 if ((ret = ((stream && stream->dtb) ? (stream->dtb->ping) (stream) : NIL)) &&
2480 stream->snarf.name && /* time to snarf? */
2481 /* prohibit faster than once/min */
2482 (time (0) > (time_t) (stream->snarf.time + min(60,mailsnarfinterval))) &&
2483 (snarf = mail_open (NIL,stream->snarf.name,
2484 stream->snarf.options | OP_SILENT))) {
2485 if ((n = snarf->nmsgs) && /* yes, have messages to snarf? */
2486 mail_search_full (snarf,NIL,mail_criteria ("UNDELETED"),SE_FREE)) {
2487 for (i = 1; ret && (i <= n); i++) /* for each message */
2488 if ((elt = mail_elt (snarf,i))->searched &&
2489 (s = mail_fetch_message (snarf,i,&len,FT_PEEK)) && len) {
2490 INIT (&bs,mail_string,s,len);
2491 if (mailsnarfpreserve) {
2492 /* yes, make sure have fast data */
2493 if (!elt->valid || !elt->day) {
2494 sprintf (tmp,"%lu",n);
2495 mail_fetch_fast (snarf,tmp,NIL);
2497 /* initialize flag string */
2498 memset (flags,0,MAILTMPLEN);
2499 /* output system flags except \Deleted */
2500 if (elt->seen) strcat (flags," \\Seen");
2501 if (elt->flagged) strcat (flags," \\Flagged");
2502 if (elt->answered) strcat (flags," \\Answered");
2503 if (elt->draft) strcat (flags," \\Draft");
2504 /* any user flags? */
2505 for (uf = elt->user_flags,s = flags + strlen (flags);
2506 uf && (f = stream->user_flags[find_rightmost_bit (&uf)]) &&
2507 ((MAILTMPLEN - (s - tmp)) > (long) (2 + strlen (f)));
2508 s += strlen (s)) sprintf (s," %s",f);
2509 ret = mail_append_full (stream,stream->mailbox,flags + 1,
2510 mail_date (tmp,elt),&bs);
2512 else ret = mail_append (stream,stream->mailbox,&bs);
2514 if (ret) { /* did snarf succeed? */
2515 /* driver has per-message (or no) flag call */
2516 if (snarf->dtb->flagmsg || !snarf->dtb->flag) {
2517 elt->valid = NIL; /* prepare for flag alteration */
2518 if (snarf->dtb->flagmsg) (*snarf->dtb->flagmsg) (snarf,elt);
2519 /* flags now altered */
2520 elt->deleted = elt->seen = elt->valid = T;
2521 if (snarf->dtb->flagmsg) (*snarf->dtb->flagmsg) (snarf,elt);
2523 /* driver has one-time flag call */
2524 if (snarf->dtb->flag) {
2525 sprintf (tmp,"%lu",i);
2526 (*snarf->dtb->flag) (snarf,tmp,"\\Deleted \\Seen",ST_SET);
2529 else { /* copy failed */
2530 sprintf (tmp,"Unable to move message %lu from %s mailbox",
2531 i,snarf->dtb->name);
2532 mm_log (tmp,WARN);
2536 /* expunge the messages */
2537 mail_close_full (snarf,n ? CL_EXPUNGE : NIL);
2538 stream->snarf.time = (unsigned long) time (0);
2539 /* Even if the snarf failed, we don't want to return NIL if the stream
2540 * is still alive. Or at least that's what we currently think.
2542 /* redo the driver's action */
2543 ret = stream->dtb ? (*stream->dtb->ping) (stream) : NIL;
2545 return ret;
2548 /* Mail check mailbox
2549 * Accepts: mail stream
2552 void mail_check (MAILSTREAM *stream)
2554 /* do the driver's action */
2555 if (stream->dtb) (*stream->dtb->check) (stream);
2559 /* Mail expunge mailbox
2560 * Accepts: mail stream
2561 * sequence to expunge if non-NIL
2562 * expunge options
2563 * Returns: T on success, NIL on failure
2566 long mail_expunge_full (MAILSTREAM *stream,char *sequence,long options)
2568 /* do the driver's action */
2569 return stream->dtb ? (*stream->dtb->expunge) (stream,sequence,options) : NIL;
2573 /* Mail copy message(s)
2574 * Accepts: mail stream
2575 * sequence
2576 * destination mailbox
2577 * flags
2580 long mail_copy_full (MAILSTREAM *stream,char *sequence,char *mailbox,
2581 long options)
2583 return stream->dtb ?
2584 SAFE_COPY (stream->dtb,stream,sequence,mailbox,options) : NIL;
2587 /* Append data package to use for old single-message mail_append() interface */
2589 typedef struct mail_append_package {
2590 char *flags; /* initial flags */
2591 char *date; /* message internal date */
2592 STRING *message; /* stringstruct of message */
2593 } APPENDPACKAGE;
2596 /* Single append message string
2597 * Accepts: mail stream
2598 * package pointer (cast as a void *)
2599 * pointer to return initial flags
2600 * pointer to return message internal date
2601 * pointer to return stringstruct of message to append
2602 * Returns: T, always
2605 static long mail_append_single (MAILSTREAM *stream,void *data,char **flags,
2606 char **date,STRING **message)
2608 APPENDPACKAGE *ap = (APPENDPACKAGE *) data;
2609 *flags = ap->flags; /* get desired data from the package */
2610 *date = ap->date;
2611 *message = ap->message;
2612 ap->message = NIL; /* so next callback puts a stop to it */
2613 return LONGT; /* always return success */
2617 /* Mail append message string
2618 * Accepts: mail stream
2619 * destination mailbox
2620 * initial flags
2621 * message internal date
2622 * stringstruct of message to append
2623 * Returns: T on success, NIL on failure
2626 long mail_append_full (MAILSTREAM *stream,char *mailbox,char *flags,char *date,
2627 STRING *message)
2629 APPENDPACKAGE ap;
2630 ap.flags = flags; /* load append package */
2631 ap.date = date;
2632 ap.message = message;
2633 return mail_append_multiple (stream,mailbox,mail_append_single,(void *) &ap);
2636 /* Mail append message(s)
2637 * Accepts: mail stream
2638 * destination mailbox
2639 * append data callback
2640 * arbitrary data for callback use
2641 * Returns: T on success, NIL on failure
2644 long mail_append_multiple (MAILSTREAM *stream,char *mailbox,append_t af,
2645 void *data)
2647 char *s,tmp[MAILTMPLEN];
2648 DRIVER *d = NIL;
2649 long ret = NIL;
2650 /* never allow names with newlines */
2651 if (strpbrk (mailbox,"\015\012"))
2652 MM_LOG ("Can't append to mailbox with such a name",ERROR);
2653 else if (strlen (mailbox) >=
2654 (NETMAXHOST+(NETMAXUSER*2)+NETMAXMBX+NETMAXSRV+50)) {
2655 sprintf (tmp,"Can't append %.80s: %s",mailbox,(*mailbox == '{') ?
2656 "invalid remote specification" : "no such mailbox");
2657 MM_LOG (tmp,ERROR);
2659 /* special driver hack? */
2660 else if (!strncmp (lcase (strcpy (tmp,mailbox)),"#driver.",8)) {
2661 /* yes, tie off name at likely delimiter */
2662 if (!(s = strpbrk (tmp+8,"/\\:"))) {
2663 sprintf (tmp,"Can't append to mailbox %.80s: bad driver syntax",mailbox);
2664 MM_LOG (tmp,ERROR);
2665 return NIL;
2667 *s++ = '\0'; /* tie off at delimiter */
2668 if (!(d = (DRIVER *) mail_parameters (NIL,GET_DRIVER,tmp+8))) {
2669 sprintf (tmp,"Can't append to mailbox %.80s: unknown driver",mailbox);
2670 MM_LOG (tmp,ERROR);
2672 else ret = SAFE_APPEND (d,stream,mailbox + (s - tmp),af,data);
2674 else if ((d = mail_valid (stream,mailbox,NIL)) != NULL)
2675 ret = SAFE_APPEND (d,stream,mailbox,af,data);
2676 /* No driver, try for TRYCREATE if no stream. Note that we use the
2677 * createProto here, not the appendProto, since the dummy driver already
2678 * took care of the appendProto case. Otherwise, if appendProto is set to
2679 * NIL, we won't get a TRYCREATE.
2681 else if (!stream && (stream = default_proto (NIL)) && stream->dtb &&
2682 SAFE_APPEND (stream->dtb,stream,mailbox,af,data))
2683 /* timing race? */
2684 MM_NOTIFY (stream,"Append validity confusion",WARN);
2685 /* generate error message */
2686 else mail_valid (stream,mailbox,"append to mailbox");
2687 return ret;
2690 /* Mail garbage collect stream
2691 * Accepts: mail stream
2692 * garbage collection flags
2695 void mail_gc (MAILSTREAM *stream,long gcflags)
2697 MESSAGECACHE *elt;
2698 unsigned long i;
2699 /* do the driver's action first */
2700 if (stream->dtb && stream->dtb->gc) (*stream->dtb->gc) (stream,gcflags);
2701 stream->msgno = 0; /* nothing cached now */
2702 if (gcflags & GC_ENV) { /* garbage collect envelopes? */
2703 if (stream->env) mail_free_envelope (&stream->env);
2704 if (stream->body) mail_free_body (&stream->body);
2706 if (gcflags & GC_TEXTS) { /* free texts */
2707 if (stream->text.data) fs_give ((void **) &stream->text.data);
2708 stream->text.size = 0;
2710 /* garbage collect per-message stuff */
2711 for (i = 1; i <= stream->nmsgs; i++)
2712 if ((elt = (MESSAGECACHE *) (*mailcache) (stream,i,CH_ELT)) != NULL)
2713 mail_gc_msg (&elt->private.msg,gcflags);
2717 /* Mail garbage collect message
2718 * Accepts: message structure
2719 * garbage collection flags
2722 void mail_gc_msg (MESSAGE *msg,long gcflags)
2724 if (gcflags & GC_ENV) { /* garbage collect envelopes? */
2725 mail_free_envelope (&msg->env);
2726 mail_free_body (&msg->body);
2728 if (gcflags & GC_TEXTS) { /* garbage collect texts */
2729 if (msg->full.text.data) fs_give ((void **) &msg->full.text.data);
2730 if (msg->header.text.data) {
2731 mail_free_stringlist (&msg->lines);
2732 fs_give ((void **) &msg->header.text.data);
2734 if (msg->text.text.data) fs_give ((void **) &msg->text.text.data);
2735 /* now GC all body components */
2736 if (msg->body) mail_gc_body (msg->body);
2740 /* Mail garbage collect texts in BODY structure
2741 * Accepts: BODY structure
2744 void mail_gc_body (BODY *body)
2746 PART *part;
2747 switch (body->type) { /* free contents */
2748 case TYPEMULTIPART: /* multiple part */
2749 for (part = body->nested.part; part; part = part->next)
2750 mail_gc_body (&part->body);
2751 break;
2752 case TYPEMESSAGE: /* encapsulated message */
2753 if (body->subtype && !strcmp (body->subtype,"RFC822")) {
2754 mail_free_stringlist (&body->nested.msg->lines);
2755 mail_gc_msg (body->nested.msg,GC_TEXTS);
2757 break;
2758 default:
2759 break;
2761 if (body->mime.text.data) fs_give ((void **) &body->mime.text.data);
2762 if (body->contents.text.data) fs_give ((void **) &body->contents.text.data);
2764 /* Mail get body section
2765 * Accepts: body of message
2766 * section specifier
2767 * Returns: pointer to body at given section
2770 BODY *mail_body_section (BODY *b, unsigned char *section)
2772 PART *pt;
2773 unsigned long i;
2774 /* make sure have a body */
2775 if (section && *section && b)
2776 while (*section) { /* find desired section */
2777 if (isdigit (*section)) { /* get section specifier */
2778 /* make sure what follows is valid */
2779 if (!(i = strtoul (section,(char **) &section,10)) ||
2780 (*section && ((*section++ != '.') || !*section))) return NIL;
2781 /* multipart content? */
2782 if (b->type == TYPEMULTIPART) {
2783 /* yes, find desired part */
2784 if ((pt = b->nested.part) != NULL) while (--i && (pt = pt->next));
2785 if (!pt) return NIL; /* bad specifier */
2786 b = &pt->body; /* note new body */
2788 /* otherwise must be section 1 */
2789 else if (i != 1) return NIL;
2790 /* need to go down further? */
2791 if (*section) switch (b->type) {
2792 case TYPEMULTIPART: /* multipart */
2793 break;
2794 case TYPEMESSAGE: /* embedded message */
2795 if (!strcmp (b->subtype,"RFC822")) {
2796 b = b->nested.msg->body;
2797 break;
2799 default: /* bogus subpart specification */
2800 return NIL;
2803 else return NIL; /* unknown section specifier */
2805 return b;
2808 /* Mail get body part
2809 * Accepts: mail stream
2810 * message number
2811 * section specifier
2812 * Returns: pointer to body
2815 BODY *mail_body (MAILSTREAM *stream,unsigned long msgno,unsigned char *section)
2817 BODY *b = NIL;
2818 /* make sure have a body */
2819 if (section && *section && mail_fetchstructure (stream,msgno,&b) && b)
2820 return mail_body_section(b, section);
2821 return b;
2824 /* Mail output date from elt fields
2825 * Accepts: character string to write into
2826 * elt to get data data from
2827 * Returns: the character string
2830 const char *days[] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
2832 const char *months[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
2833 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
2835 char *mail_date (char *string,MESSAGECACHE *elt)
2837 sprintf (string,"%2d-%s-%d %02d:%02d:%02d %c%02d%02d",
2838 elt->day ? elt->day : 1,
2839 months[elt->month ? (elt->month - 1) : 0],
2840 elt->year + BASEYEAR,elt->hours,elt->minutes,elt->seconds,
2841 elt->zoccident ? '-' : '+',elt->zhours,elt->zminutes);
2842 return string;
2846 /* Mail output extended-ctime format date from elt fields
2847 * Accepts: character string to write into
2848 * elt to get data data from
2849 * Returns: the character string
2852 char *mail_cdate (char *string,MESSAGECACHE *elt)
2854 char *fmt = "%s %s %2d %02d:%02d:%02d %4d %s%02d%02d\n";
2855 int d = elt->day ? elt->day : 1;
2856 int m = elt->month ? (elt->month - 1) : 0;
2857 int y = elt->year + BASEYEAR;
2858 const char *s = months[m];
2859 if (m < 2) { /* if before March, */
2860 m += 10; /* January = month 10 of previous year */
2861 y--;
2863 else m -= 2; /* March is month 0 */
2864 sprintf (string,fmt,days[(int) (d + 2 + ((7 + 31 * m) / 12)
2865 #ifndef USEJULIANCALENDAR
2866 #ifndef USEORTHODOXCALENDAR /* Gregorian calendar */
2867 + (y / 400)
2868 #ifdef Y4KBUGFIX
2869 - (y / 4000)
2870 #endif
2871 #else /* Orthodox calendar */
2872 + (2 * (y / 900)) + ((y % 900) >= 200)
2873 + ((y % 900) >= 600)
2874 #endif
2875 - (y / 100)
2876 #endif
2877 + y + (y / 4)) % 7],
2878 s,d,elt->hours,elt->minutes,elt->seconds,elt->year + BASEYEAR,
2879 elt->zoccident ? "-" : "+",elt->zhours,elt->zminutes);
2880 return string;
2883 /* Mail parse date into elt fields
2884 * Accepts: elt to write into
2885 * date string to parse
2886 * Returns: T if parse successful, else NIL
2887 * This routine parses dates as follows:
2888 * . leading three alphas followed by comma and space are ignored
2889 * . date accepted in format: mm/dd/yy, mm/dd/yyyy, dd-mmm-yy, dd-mmm-yyyy,
2890 * dd mmm yy, dd mmm yyyy, yyyy-mm-dd, yyyymmdd
2891 * . two and three digit years interpreted according to RFC 2822 rules
2892 * . mandatory end of string if yyyy-mm-dd or yyyymmdd; otherwise optional
2893 * space followed by time:
2894 * . time accepted in format hh:mm:ss or hh:mm
2895 * . end of string accepted
2896 * . timezone accepted: hyphen followed by symbolic timezone, or space
2897 * followed by signed numeric timezone or symbolic timezone
2898 * Examples of normal input:
2899 * . IMAP date-only (SEARCH):
2900 * dd-mmm-yyyy
2901 * . IMAP date-time (INTERNALDATE):
2902 * dd-mmm-yyyy hh:mm:ss +zzzz
2903 * . RFC-822:
2904 * www, dd mmm yy hh:mm:ss zzz
2905 * . RFC-2822:
2906 * www, dd mmm yyyy hh:mm:ss +zzzz
2909 long mail_parse_date (MESSAGECACHE *elt,unsigned char *s)
2911 unsigned long d,m,y;
2912 int mi,ms;
2913 struct tm *t;
2914 time_t tn;
2915 char tmp[MAILTMPLEN];
2916 static unsigned long maxyear = 0;
2917 if (!maxyear) { /* know the end of time yet? */
2918 MESSAGECACHE tmpelt;
2919 memset (&tmpelt,0xff,sizeof (MESSAGECACHE));
2920 maxyear = BASEYEAR + tmpelt.year;
2922 /* clear elt */
2923 elt->zoccident = elt->zhours = elt->zminutes =
2924 elt->hours = elt->minutes = elt->seconds =
2925 elt->day = elt->month = elt->year = 0;
2926 /* make a writeable uppercase copy */
2927 if (s && *s && (strlen (s) < (size_t)MAILTMPLEN)) s = ucase (strcpy (tmp,s));
2928 else return NIL;
2929 /* skip over possible day of week */
2930 if (isalpha (*s) && isalpha (s[1]) && isalpha (s[2]) && (s[3] == ',') &&
2931 (s[4] == ' ')) s += 5;
2932 while (*s == ' ') s++; /* parse first number (probable month) */
2933 if (!(m = strtoul (s,(char **) &s,10))) return NIL;
2935 switch (*s) { /* different parse based on delimiter */
2936 case '/': /* mm/dd/yy format */
2937 if (isdigit (*++s) && (d = strtoul (s,(char **) &s,10)) &&
2938 (*s == '/') && isdigit (*++s)) {
2939 y = strtoul (s,(char **) &s,10);
2940 if (*s == '\0') break; /* must end here */
2942 return NIL; /* bogon */
2943 case ' ': /* dd mmm yy format */
2944 while (s[1] == ' ') s++; /* slurp extra whitespace */
2945 case '-':
2946 if (isdigit (s[1])) { /* possible ISO 8601 date format? */
2947 y = m; /* yes, first number is year */
2948 /* get month and day */
2949 if ((m = strtoul (s+1,(char **) &s,10)) && (*s++ == '-') &&
2950 (d = strtoul (s,(char **) &s,10)) && !*s) break;
2951 return NIL; /* syntax error or time present */
2953 d = m; /* dd-mmm-yy[yy], so first number is a day */
2954 /* make sure string long enough! */
2955 if (strlen (s) < (size_t) 5) return NIL;
2956 /* Some compilers don't allow `<<' and/or longs in case statements. */
2957 /* slurp up the month string */
2958 ms = ((s[1] - 'A') * 1024) + ((s[2] - 'A') * 32) + (s[3] - 'A');
2959 switch (ms) { /* determine the month */
2960 case (('J'-'A') * 1024) + (('A'-'A') * 32) + ('N'-'A'): m = 1; break;
2961 case (('F'-'A') * 1024) + (('E'-'A') * 32) + ('B'-'A'): m = 2; break;
2962 case (('M'-'A') * 1024) + (('A'-'A') * 32) + ('R'-'A'): m = 3; break;
2963 case (('A'-'A') * 1024) + (('P'-'A') * 32) + ('R'-'A'): m = 4; break;
2964 case (('M'-'A') * 1024) + (('A'-'A') * 32) + ('Y'-'A'): m = 5; break;
2965 case (('J'-'A') * 1024) + (('U'-'A') * 32) + ('N'-'A'): m = 6; break;
2966 case (('J'-'A') * 1024) + (('U'-'A') * 32) + ('L'-'A'): m = 7; break;
2967 case (('A'-'A') * 1024) + (('U'-'A') * 32) + ('G'-'A'): m = 8; break;
2968 case (('S'-'A') * 1024) + (('E'-'A') * 32) + ('P'-'A'): m = 9; break;
2969 case (('O'-'A') * 1024) + (('C'-'A') * 32) + ('T'-'A'): m = 10; break;
2970 case (('N'-'A') * 1024) + (('O'-'A') * 32) + ('V'-'A'): m = 11; break;
2971 case (('D'-'A') * 1024) + (('E'-'A') * 32) + ('C'-'A'): m = 12; break;
2972 default: return NIL; /* unknown month */
2974 if (s[4] == *s) s += 5; /* advance to year */
2975 else { /* first three were OK, possibly full name */
2976 mi = *s; /* note delimiter, skip alphas */
2977 for (s += 4; isalpha (*s); s++);
2978 /* error if delimiter not here */
2979 if (mi != *s++) return NIL;
2981 while (*s == ' ') s++; /* parse year */
2982 if (isdigit (*s)) { /* must be a digit here */
2983 y = strtoul (s,(char **) &s,10);
2984 if (*s == '\0' || *s == ' ') break;
2986 case '\0': /* ISO 8601 compact date */
2987 if (m < (BASEYEAR * 10000)) return NIL;
2988 y = m / 10000; /* get year */
2989 d = (m %= 10000) % 100; /* get day */
2990 m /= 100; /* and month */
2991 break;
2992 default:
2993 return NIL; /* unknown date format */
2996 /* minimal validity check of date */
2997 if ((d > 31) || (m > 12)) return NIL;
2998 if (y < 49) y += 2000; /* RFC 2282 rules for two digit years 00-49 */
2999 else if (y < 999) y += 1900; /* 2-digit years 50-99 and 3-digit years */
3000 /* reject prehistoric and far future years */
3001 if ((y < BASEYEAR) || (y > maxyear)) return NIL;
3002 /* set values in elt */
3003 elt->day = d; elt->month = m; elt->year = y - BASEYEAR;
3004 ms = '\0'; /* initially no time zone string */
3005 if (*s) { /* time specification present? */
3006 /* parse time */
3007 d = strtoul (s+1,(char **) &s,10);
3008 if (*s != ':') return NIL;
3009 m = strtoul (++s,(char **) &s,10);
3010 y = (*s == ':') ? strtoul (++s,(char **) &s,10) : 0;
3011 /* validity check time */
3012 if ((d > 23) || (m > 59) || (y > 60)) return NIL;
3013 /* set values in elt */
3014 elt->hours = d; elt->minutes = m; elt->seconds = y;
3015 switch (*s) { /* time zone specifier? */
3016 case ' ': /* numeric time zone */
3017 while (s[1] == ' ') s++; /* slurp extra whitespace */
3018 if (!isalpha (s[1])) { /* treat as '-' case if alphabetic */
3019 /* test for sign character */
3020 if ((elt->zoccident = (*++s == '-')) || (*s == '+')) s++;
3021 /* validate proper timezone */
3022 if (isdigit(*s) && isdigit(s[1]) && isdigit(s[2]) && (s[2] < '6') &&
3023 isdigit(s[3])) {
3024 elt->zhours = (*s - '0') * 10 + (s[1] - '0');
3025 elt->zminutes = (s[2] - '0') * 10 + (s[3] - '0');
3027 return T; /* all done! */
3029 /* falls through */
3030 case '-': /* symbolic time zone */
3031 if (!(ms = *++s)) ms = 'Z';
3032 else if (*++s) { /* multi-character? */
3033 ms -= 'A'; ms *= 1024; /* yes, make compressed three-byte form */
3034 ms += ((*s++ - 'A') * 32);
3035 if (*s) ms += *s++ - 'A';
3036 if (*s) ms = '\0'; /* more than three characters */
3038 default: /* ignore anything else */
3039 break;
3043 /* This is not intended to be a comprehensive list of all possible
3044 * timezone strings. Such a list would be impractical. Rather, this
3045 * listing is intended to incorporate all military, North American, and
3046 * a few special cases such as Japan and the major European zone names,
3047 * such as what might be expected to be found in a Tenex format mailbox
3048 * and spewed from an IMAP server. The trend is to migrate to numeric
3049 * timezones which lack the flavor but also the ambiguity of the names.
3051 * RFC-822 only recognizes UT, GMT, 1-letter military timezones, and the
3052 * 4 CONUS timezones and their summer time variants. [Sorry, Canadian
3053 * Atlantic Provinces, Alaska, and Hawaii.]
3055 switch (ms) { /* determine the timezone */
3056 /* Universal */
3057 case (('U'-'A')*1024)+(('T'-'A')*32):
3058 #ifndef STRICT_RFC822_TIMEZONES
3059 case (('U'-'A')*1024)+(('T'-'A')*32)+'C'-'A':
3060 #endif
3061 /* Greenwich */
3062 case (('G'-'A')*1024)+(('M'-'A')*32)+'T'-'A':
3063 case 'Z': elt->zhours = 0; break;
3065 /* oriental (from Greenwich) timezones */
3066 #ifndef STRICT_RFC822_TIMEZONES
3067 /* Middle Europe */
3068 case (('M'-'A')*1024)+(('E'-'A')*32)+'T'-'A':
3069 #endif
3070 #ifdef BRITISH_SUMMER_TIME
3071 /* British Summer */
3072 case (('B'-'A')*1024)+(('S'-'A')*32)+'T'-'A':
3073 #endif
3074 case 'A': elt->zhours = 1; break;
3075 #ifndef STRICT_RFC822_TIMEZONES
3076 /* Eastern Europe */
3077 case (('E'-'A')*1024)+(('E'-'A')*32)+'T'-'A':
3078 #endif
3079 case 'B': elt->zhours = 2; break;
3080 case 'C': elt->zhours = 3; break;
3081 case 'D': elt->zhours = 4; break;
3082 case 'E': elt->zhours = 5; break;
3083 case 'F': elt->zhours = 6; break;
3084 case 'G': elt->zhours = 7; break;
3085 case 'H': elt->zhours = 8; break;
3086 #ifndef STRICT_RFC822_TIMEZONES
3087 /* Japan */
3088 case (('J'-'A')*1024)+(('S'-'A')*32)+'T'-'A':
3089 #endif
3090 case 'I': elt->zhours = 9; break;
3091 case 'K': elt->zhours = 10; break;
3092 case 'L': elt->zhours = 11; break;
3093 case 'M': elt->zhours = 12; break;
3095 /* occidental (from Greenwich) timezones */
3096 case 'N': elt->zoccident = 1; elt->zhours = 1; break;
3097 case 'O': elt->zoccident = 1; elt->zhours = 2; break;
3098 #ifndef STRICT_RFC822_TIMEZONES
3099 case (('A'-'A')*1024)+(('D'-'A')*32)+'T'-'A':
3100 #endif
3101 case 'P': elt->zoccident = 1; elt->zhours = 3; break;
3102 #ifdef NEWFOUNDLAND_STANDARD_TIME
3103 /* Newfoundland */
3104 case (('N'-'A')*1024)+(('S'-'A')*32)+'T'-'A':
3105 elt->zoccident = 1; elt->zhours = 3; elt->zminutes = 30; break;
3106 #endif
3107 #ifndef STRICT_RFC822_TIMEZONES
3108 /* Atlantic */
3109 case (('A'-'A')*1024)+(('S'-'A')*32)+'T'-'A':
3110 #endif
3111 /* CONUS */
3112 case (('E'-'A')*1024)+(('D'-'A')*32)+'T'-'A':
3113 case 'Q': elt->zoccident = 1; elt->zhours = 4; break;
3114 /* Eastern */
3115 case (('E'-'A')*1024)+(('S'-'A')*32)+'T'-'A':
3116 case (('C'-'A')*1024)+(('D'-'A')*32)+'T'-'A':
3117 case 'R': elt->zoccident = 1; elt->zhours = 5; break;
3118 /* Central */
3119 case (('C'-'A')*1024)+(('S'-'A')*32)+'T'-'A':
3120 case (('M'-'A')*1024)+(('D'-'A')*32)+'T'-'A':
3121 case 'S': elt->zoccident = 1; elt->zhours = 6; break;
3122 /* Mountain */
3123 case (('M'-'A')*1024)+(('S'-'A')*32)+'T'-'A':
3124 case (('P'-'A')*1024)+(('D'-'A')*32)+'T'-'A':
3125 case 'T': elt->zoccident = 1; elt->zhours = 7; break;
3126 /* Pacific */
3127 case (('P'-'A')*1024)+(('S'-'A')*32)+'T'-'A':
3128 #ifndef STRICT_RFC822_TIMEZONES
3129 case (('Y'-'A')*1024)+(('D'-'A')*32)+'T'-'A':
3130 #endif
3131 case 'U': elt->zoccident = 1; elt->zhours = 8; break;
3132 #ifndef STRICT_RFC822_TIMEZONES
3133 /* Yukon */
3134 case (('Y'-'A')*1024)+(('S'-'A')*32)+'T'-'A':
3135 #endif
3136 case 'V': elt->zoccident = 1; elt->zhours = 9; break;
3137 #ifndef STRICT_RFC822_TIMEZONES
3138 /* Hawaii */
3139 case (('H'-'A')*1024)+(('S'-'A')*32)+'T'-'A':
3140 #endif
3141 case 'W': elt->zoccident = 1; elt->zhours = 10; break;
3142 /* Nome/Bering/Samoa */
3143 #ifdef NOME_STANDARD_TIME
3144 case (('N'-'A')*1024)+(('S'-'A')*32)+'T'-'A':
3145 #endif
3146 #ifdef BERING_STANDARD_TIME
3147 case (('B'-'A')*1024)+(('S'-'A')*32)+'T'-'A':
3148 #endif
3149 #ifdef SAMOA_STANDARD_TIME
3150 case (('S'-'A')*1024)+(('S'-'A')*32)+'T'-'A':
3151 #endif
3152 case 'X': elt->zoccident = 1; elt->zhours = 11; break;
3153 case 'Y': elt->zoccident = 1; elt->zhours = 12; break;
3155 default: /* unknown time zones treated as local */
3156 tn = time (0); /* time now... */
3157 t = localtime (&tn); /* get local minutes since midnight */
3158 mi = t->tm_hour * 60 + t->tm_min;
3159 ms = t->tm_yday; /* note Julian day */
3160 if ((t = gmtime (&tn)) != NULL) { /* minus UTC minutes since midnight */
3161 mi -= t->tm_hour * 60 + t->tm_min;
3162 /* ms can be one of:
3163 * 36x local time is December 31, UTC is January 1, offset -24 hours
3164 * 1 local time is 1 day ahead of UTC, offset +24 hours
3165 * 0 local time is same day as UTC, no offset
3166 * -1 local time is 1 day behind UTC, offset -24 hours
3167 * -36x local time is January 1, UTC is December 31, offset +24 hours
3169 if (ms -= t->tm_yday) /* correct offset if different Julian day */
3170 mi += ((ms < 0) == (abs (ms) == 1)) ? -24*60 : 24*60;
3171 if (mi < 0) { /* occidental? */
3172 mi = abs (mi); /* yup, make positive number */
3173 elt->zoccident = 1; /* and note west of UTC */
3175 elt->zhours = mi / 60; /* now break into hours and minutes */
3176 elt->zminutes = mi % 60;
3178 break;
3180 return T;
3183 /* Mail n messages exist
3184 * Accepts: mail stream
3185 * number of messages
3188 void mail_exists (MAILSTREAM *stream,unsigned long nmsgs)
3190 char tmp[MAILTMPLEN];
3191 if (nmsgs > MAXMESSAGES) {
3192 sprintf (tmp,"Mailbox has more messages (%lu) exist than maximum (%lu)",
3193 nmsgs,MAXMESSAGES);
3194 mm_log (tmp,ERROR);
3195 nmsgs = MAXMESSAGES; /* cap to maximum */
3196 /* probably will crash in mail_elt() soon enough... */
3198 /* make sure cache is large enough */
3199 (*mailcache) (stream,nmsgs,CH_SIZE);
3200 stream->nmsgs = nmsgs; /* update stream status */
3201 /* notify main program of change */
3202 if (!stream->silent) MM_EXISTS (stream,nmsgs);
3206 /* Mail n messages are recent
3207 * Accepts: mail stream
3208 * number of recent messages
3211 void mail_recent (MAILSTREAM *stream,unsigned long recent)
3213 char tmp[MAILTMPLEN];
3214 if (recent <= stream->nmsgs) stream->recent = recent;
3215 else {
3216 sprintf (tmp,"Non-existent recent message(s) %lu, nmsgs=%lu",
3217 recent,stream->nmsgs);
3218 mm_log (tmp,ERROR);
3223 /* Mail message n is expunged
3224 * Accepts: mail stream
3225 * message #
3228 void mail_expunged (MAILSTREAM *stream,unsigned long msgno)
3230 char tmp[MAILTMPLEN];
3231 MESSAGECACHE *elt;
3232 if (msgno > stream->nmsgs) {
3233 sprintf (tmp,"Expunge of non-existent message %lu, nmsgs=%lu",
3234 msgno,stream->nmsgs);
3235 mm_log (tmp,ERROR);
3237 else {
3238 elt = (MESSAGECACHE *) (*mailcache) (stream,msgno,CH_ELT);
3239 /* notify main program of change */
3240 if (!stream->silent) MM_EXPUNGED (stream,msgno);
3241 if (elt) { /* if an element is there */
3242 elt->msgno = 0; /* invalidate its message number and free */
3243 (*mailcache) (stream,msgno,CH_FREE);
3244 (*mailcache) (stream,msgno,CH_FREESORTCACHE);
3246 /* expunge the slot */
3247 (*mailcache) (stream,msgno,CH_EXPUNGE);
3248 --stream->nmsgs; /* update stream status */
3249 if (stream->msgno) { /* have stream pointers? */
3250 /* make sure the short cache is nuked */
3251 if (stream->scache) mail_gc (stream,GC_ENV | GC_TEXTS);
3252 else stream->msgno = 0; /* make sure invalidated in any case */
3257 /* Mail stream status routines */
3260 /* Mail lock stream
3261 * Accepts: mail stream
3264 void mail_lock (MAILSTREAM *stream)
3266 if (stream->lock) {
3267 char tmp[MAILTMPLEN];
3268 sprintf (tmp,"Lock when already locked, mbx=%.80s",
3269 stream->mailbox ? stream->mailbox : "???");
3270 fatal (tmp);
3272 else stream->lock = T; /* lock stream */
3276 /* Mail unlock stream
3277 * Accepts: mail stream
3280 void mail_unlock (MAILSTREAM *stream)
3282 if (!stream->lock) fatal ("Unlock when not locked");
3283 else stream->lock = NIL; /* unlock stream */
3287 /* Mail turn on debugging telemetry
3288 * Accepts: mail stream
3291 void mail_debug (MAILSTREAM *stream)
3293 stream->debug = T; /* turn on debugging telemetry */
3294 if (stream->dtb) (*stream->dtb->parameters) (ENABLE_DEBUG,stream);
3298 /* Mail turn off debugging telemetry
3299 * Accepts: mail stream
3302 void mail_nodebug (MAILSTREAM *stream)
3304 stream->debug = NIL; /* turn off debugging telemetry */
3305 if (stream->dtb) (*stream->dtb->parameters) (DISABLE_DEBUG,stream);
3309 /* Mail log to debugging telemetry
3310 * Accepts: message
3311 * flag that data is "sensitive"
3314 void mail_dlog (char *string,long flag)
3316 mm_dlog ((debugsensitive || !flag) ? string : "<suppressed>");
3319 /* Mail parse UID sequence
3320 * Accepts: mail stream
3321 * sequence to parse
3322 * Returns: T if parse successful, else NIL
3325 long mail_uid_sequence (MAILSTREAM *stream,unsigned char *sequence)
3327 unsigned long i,j,k,x,y;
3328 for (i = 1; i <= stream->nmsgs; i++) mail_elt (stream,i)->sequence = NIL;
3329 while (sequence && *sequence){/* while there is something to parse */
3330 if (*sequence == '*') { /* maximum message */
3331 i = stream->nmsgs ? mail_uid (stream,stream->nmsgs) : stream->uid_last;
3332 sequence++; /* skip past * */
3334 /* parse and validate message number */
3335 /* parse and validate message number */
3336 else if (!isdigit (*sequence)) {
3337 MM_LOG ("Syntax error in sequence",ERROR);
3338 return NIL;
3340 else if (!(i = strtoul (sequence,(char **) &sequence,10))) {
3341 MM_LOG ("UID may not be zero",ERROR);
3342 return NIL;
3344 switch (*sequence) { /* see what the delimiter is */
3345 case ':': /* sequence range */
3346 if (*++sequence == '*') { /* maximum message */
3347 j = stream->nmsgs ? mail_uid (stream,stream->nmsgs) : stream->uid_last;
3348 sequence++; /* skip past * */
3350 /* parse end of range */
3351 else if (!(j = strtoul (sequence,(char **) &sequence,10))) {
3352 MM_LOG ("UID sequence range invalid",ERROR);
3353 return NIL;
3355 if (*sequence && *sequence++ != ',') {
3356 MM_LOG ("UID sequence range syntax error",ERROR);
3357 return NIL;
3359 if (i > j) { /* swap the range if backwards */
3360 x = i; i = j; j = x;
3362 x = mail_msgno (stream,i);/* get msgnos */
3363 y = mail_msgno (stream,j);/* for both UIDS (don't && it) */
3364 /* easy if both UIDs valid */
3365 if (x && y) while (x <= y) mail_elt (stream,x++)->sequence = T;
3366 /* start UID valid, end is not */
3367 else if (x) while ((x <= stream->nmsgs) && (mail_uid (stream,x) <= j))
3368 mail_elt (stream,x++)->sequence = T;
3369 /* end UID valid, start is not */
3370 else if (y) for (x = 1; x <= y; x++) {
3371 if (mail_uid (stream,x) >= i) mail_elt (stream,x)->sequence = T;
3373 /* neither is valid, ugh */
3374 else for (x = 1; x <= stream->nmsgs; x++)
3375 if (((k = mail_uid (stream,x)) >= i) && (k <= j))
3376 mail_elt (stream,x)->sequence = T;
3377 break;
3378 case ',': /* single message */
3379 ++sequence; /* skip the delimiter, fall into end case */
3380 case '\0': /* end of sequence, mark this message */
3381 if ((x = mail_msgno (stream,i)) != 0L) mail_elt (stream,x)->sequence = T;
3382 break;
3383 default: /* anything else is a syntax error! */
3384 MM_LOG ("UID sequence syntax error",ERROR);
3385 return NIL;
3388 return T; /* successfully parsed sequence */
3391 /* Mail see if line list matches that in cache
3392 * Accepts: candidate line list
3393 * cached line list
3394 * matching flags
3395 * Returns: T if match, NIL if no match
3398 long mail_match_lines (STRINGLIST *lines,STRINGLIST *msglines,long flags)
3400 unsigned long i;
3401 unsigned char *s,*t;
3402 STRINGLIST *m;
3403 if (!msglines) return T; /* full header is in cache */
3404 /* need full header but filtered in cache */
3405 if ((flags & FT_NOT) || !lines) return NIL;
3406 do { /* make sure all present & accounted for */
3407 for (m = msglines; m; m = m->next) if (lines->text.size == m->text.size) {
3408 for (s = lines->text.data,t = m->text.data,i = lines->text.size;
3409 i && !compare_uchar (*s,*t); s++,t++,i--);
3410 if (!i) break; /* this line matches */
3412 if (!m) return NIL; /* didn't find in the list */
3414 while ((lines = lines->next) != NULL);
3415 return T; /* all lines found */
3418 /* Mail filter text by header lines
3419 * Accepts: text to filter, with trailing null
3420 * length of text
3421 * list of lines
3422 * fetch flags
3423 * Returns: new text size, text overwritten
3426 unsigned long mail_filter (char *text,unsigned long len,STRINGLIST *lines,
3427 long flags)
3429 STRINGLIST *hdrs;
3430 int notfound;
3431 unsigned long i;
3432 char c,*s,*e,*t,tmp[MAILTMPLEN];
3433 char *src = text;
3434 char *dst = src;
3435 char *end = text + len;
3436 text[len] = '\012'; /* guard against running off buffer */
3437 while (src < end) { /* process header */
3438 /* slurp header line name */
3439 for (s = src,e = s + MAILTMPLEN - 1,e = (e < end ? e : end),t = tmp;
3440 (s < e) && ((c = (*s ? *s : (*s = ' '))) != ':') &&
3441 ((c > ' ') ||
3442 ((c != ' ') && (c != '\t') && (c != '\015') && (c != '\012')));
3443 *t++ = *s++);
3444 *t = '\0'; /* tie off */
3445 notfound = T; /* not found yet */
3446 if ((i = t - tmp) != 0L) /* see if found in header */
3447 for (hdrs = lines; hdrs && notfound; hdrs = hdrs->next)
3448 if ((hdrs->text.size == i) && !compare_csizedtext (tmp,&hdrs->text))
3449 notfound = NIL;
3450 /* skip header line if not wanted */
3451 if (i && ((flags & FT_NOT) ? !notfound : notfound))
3452 while (((*src++ != '\012') && (*src++ != '\012') && (*src++ != '\012') &&
3453 (*src++ != '\012') && (*src++ != '\012') && (*src++ != '\012') &&
3454 (*src++ != '\012') && (*src++ != '\012') && (*src++ != '\012') &&
3455 (*src++ != '\012')) ||
3456 ((src < end) && ((*src == ' ') || (*src == '\t'))));
3457 else if (src == dst) { /* copy to self */
3458 while (((*src++ != '\012') && (*src++ != '\012') && (*src++ != '\012') &&
3459 (*src++ != '\012') && (*src++ != '\012') && (*src++ != '\012') &&
3460 (*src++ != '\012') && (*src++ != '\012') && (*src++ != '\012') &&
3461 (*src++ != '\012')) ||
3462 ((src < end) && ((*src == ' ') || (*src == '\t'))));
3463 dst = src; /* update destination */
3465 else { /* copy line and any continuation line */
3466 while ((((*dst++ = *src++) != '\012') && ((*dst++ = *src++) != '\012') &&
3467 ((*dst++ = *src++) != '\012') && ((*dst++ = *src++) != '\012') &&
3468 ((*dst++ = *src++) != '\012') && ((*dst++ = *src++) != '\012') &&
3469 ((*dst++ = *src++) != '\012') && ((*dst++ = *src++) != '\012') &&
3470 ((*dst++ = *src++) != '\012') && ((*dst++ = *src++) != '\012'))||
3471 ((src < end) && ((*src == ' ') || (*src == '\t'))));
3472 /* in case hit the guard LF */
3473 if (src > end) dst -= (src - end);
3476 *dst = '\0'; /* tie off destination */
3477 return dst - text;
3480 /* Local mail search message
3481 * Accepts: MAIL stream
3482 * message number
3483 * optional section specification
3484 * search program
3485 * Returns: T if found, NIL otherwise
3488 long mail_search_msg (MAILSTREAM *stream,unsigned long msgno,char *section,
3489 SEARCHPGM *pgm)
3491 unsigned short d;
3492 char tmp[MAILTMPLEN];
3493 MESSAGECACHE *elt = mail_elt (stream,msgno);
3494 SEARCHHEADER *hdr;
3495 SEARCHOR *or;
3496 SEARCHPGMLIST *not;
3497 unsigned long now = (unsigned long) time (0);
3498 if (pgm->msgno || pgm->uid) { /* message set searches */
3499 SEARCHSET *set;
3500 /* message sequences */
3501 if (pgm->msgno) { /* inside this message sequence set */
3502 for (set = pgm->msgno; set; set = set->next)
3503 if (set->last ? ((set->first <= set->last) ?
3504 ((msgno >= set->first) && (msgno <= set->last)) :
3505 ((msgno >= set->last) && (msgno <= set->first))) :
3506 msgno == set->first) break;
3507 if (!set) return NIL; /* not found within sequence */
3509 if (pgm->uid) { /* inside this unique identifier set */
3510 unsigned long uid = mail_uid (stream,msgno);
3511 for (set = pgm->uid; set; set = set->next)
3512 if (set->last ? ((set->first <= set->last) ?
3513 ((uid >= set->first) && (uid <= set->last)) :
3514 ((uid >= set->last) && (uid <= set->first))) :
3515 uid == set->first) break;
3516 if (!set) return NIL; /* not found within sequence */
3520 /* Fast data searches */
3521 /* need to fetch fast data? */
3522 if ((!elt->rfc822_size && (pgm->larger || pgm->smaller)) ||
3523 (!elt->year && (pgm->before || pgm->on || pgm->since ||
3524 pgm->older || pgm->younger)) ||
3525 (!elt->valid && (pgm->answered || pgm->unanswered ||
3526 pgm->deleted || pgm->undeleted ||
3527 pgm->draft || pgm->undraft ||
3528 pgm->flagged || pgm->unflagged ||
3529 pgm->recent || pgm->old ||
3530 pgm->seen || pgm->unseen ||
3531 pgm->keyword || pgm->unkeyword))) {
3532 unsigned long i;
3533 MESSAGECACHE *ielt;
3534 for (i = elt->msgno; /* find last unloaded message in range */
3535 (i < stream->nmsgs) && (ielt = mail_elt (stream,i+1)) &&
3536 ((!ielt->rfc822_size && (pgm->larger || pgm->smaller)) ||
3537 (!ielt->year && (pgm->before || pgm->on || pgm->since ||
3538 pgm->older || pgm->younger)) ||
3539 (!ielt->valid && (pgm->answered || pgm->unanswered ||
3540 pgm->deleted || pgm->undeleted ||
3541 pgm->draft || pgm->undraft ||
3542 pgm->flagged || pgm->unflagged ||
3543 pgm->recent || pgm->old ||
3544 pgm->seen || pgm->unseen ||
3545 pgm->keyword || pgm->unkeyword))); ++i);
3546 if (i == elt->msgno) sprintf (tmp,"%lu",elt->msgno);
3547 else sprintf (tmp,"%lu:%lu",elt->msgno,i);
3548 mail_fetch_fast (stream,tmp,NIL);
3550 /* size ranges */
3551 if ((pgm->larger && (elt->rfc822_size <= pgm->larger)) ||
3552 (pgm->smaller && (elt->rfc822_size >= pgm->smaller))) return NIL;
3553 /* message flags */
3554 if ((pgm->answered && !elt->answered) ||
3555 (pgm->unanswered && elt->answered) ||
3556 (pgm->deleted && !elt->deleted) ||
3557 (pgm->undeleted && elt->deleted) ||
3558 (pgm->draft && !elt->draft) ||
3559 (pgm->undraft && elt->draft) ||
3560 (pgm->flagged && !elt->flagged) ||
3561 (pgm->unflagged && elt->flagged) ||
3562 (pgm->recent && !elt->recent) ||
3563 (pgm->old && elt->recent) ||
3564 (pgm->seen && !elt->seen) ||
3565 (pgm->unseen && elt->seen)) return NIL;
3566 /* keywords */
3567 if ((pgm->keyword && !mail_search_keyword (stream,elt,pgm->keyword,LONGT)) ||
3568 (pgm->unkeyword && !mail_search_keyword (stream,elt,pgm->unkeyword,NIL)))
3569 return NIL;
3570 /* internal date ranges */
3571 if (pgm->before || pgm->on || pgm->since) {
3572 d = mail_shortdate (elt->year,elt->month,elt->day);
3573 if (pgm->before && (d >= pgm->before)) return NIL;
3574 if (pgm->on && (d != pgm->on)) return NIL;
3575 if (pgm->since && (d < pgm->since)) return NIL;
3577 if (pgm->older || pgm->younger) {
3578 unsigned long msgd = mail_longdate (elt);
3579 if (pgm->older && msgd > (now - pgm->older)) return NIL;
3580 if (pgm->younger && msgd < (now - pgm->younger)) return NIL;
3583 /* envelope searches */
3584 if (pgm->sentbefore || pgm->senton || pgm->sentsince ||
3585 pgm->bcc || pgm->cc || pgm->from || pgm->to || pgm->subject ||
3586 pgm->return_path || pgm->sender || pgm->reply_to || pgm->in_reply_to ||
3587 pgm->message_id || pgm->newsgroups || pgm->followup_to ||
3588 pgm->references) {
3589 ENVELOPE *env;
3590 MESSAGECACHE delt;
3591 if (section) { /* use body part envelope */
3592 BODY *body = mail_body (stream,msgno,section);
3593 env = (body && (body->type == TYPEMESSAGE) && body->subtype &&
3594 !strcmp (body->subtype,"RFC822")) ? body->nested.msg->env : NIL;
3596 else { /* use top level envelope if no section */
3597 if (pgm->header && !stream->scache && !(stream->dtb->flags & DR_LOCAL))
3598 mail_fetch_header(stream,msgno,NIL,NIL,NIL,FT_PEEK|FT_SEARCHLOOKAHEAD);
3599 env = mail_fetchenvelope (stream,msgno);
3601 if (!env) return NIL; /* no envelope obtained */
3602 /* sent date ranges */
3603 if ((pgm->sentbefore || pgm->senton || pgm->sentsince) &&
3604 (!mail_parse_date (&delt,env->date) ||
3605 !(d = mail_shortdate (delt.year,delt.month,delt.day)) ||
3606 (pgm->sentbefore && (d >= pgm->sentbefore)) ||
3607 (pgm->senton && (d != pgm->senton)) ||
3608 (pgm->sentsince && (d < pgm->sentsince)))) return NIL;
3609 /* search headers */
3610 if ((pgm->bcc && !mail_search_addr (env->bcc,pgm->bcc)) ||
3611 (pgm->cc && !mail_search_addr (env->cc,pgm->cc)) ||
3612 (pgm->from && !mail_search_addr (env->from,pgm->from)) ||
3613 (pgm->to && !mail_search_addr (env->to,pgm->to)) ||
3614 (pgm->subject && !mail_search_header_text (env->subject,pgm->subject)))
3615 return NIL;
3616 /* These criteria are not supported by IMAP and have to be emulated */
3617 if ((pgm->return_path &&
3618 !mail_search_addr (env->return_path,pgm->return_path)) ||
3619 (pgm->sender && !mail_search_addr (env->sender,pgm->sender)) ||
3620 (pgm->reply_to && !mail_search_addr (env->reply_to,pgm->reply_to)) ||
3621 (pgm->in_reply_to &&
3622 !mail_search_header_text (env->in_reply_to,pgm->in_reply_to)) ||
3623 (pgm->message_id &&
3624 !mail_search_header_text (env->message_id,pgm->message_id)) ||
3625 (pgm->newsgroups &&
3626 !mail_search_header_text (env->newsgroups,pgm->newsgroups)) ||
3627 (pgm->followup_to &&
3628 !mail_search_header_text (env->followup_to,pgm->followup_to)) ||
3629 (pgm->references &&
3630 !mail_search_header_text (env->references,pgm->references)))
3631 return NIL;
3634 /* search header lines */
3635 for (hdr = pgm->header; hdr; hdr = hdr->next) {
3636 char *t,*e,*v;
3637 SIZEDTEXT s;
3638 STRINGLIST sth,stc;
3639 sth.next = stc.next = NIL; /* only one at a time */
3640 sth.text.data = hdr->line.data;
3641 sth.text.size = hdr->line.size;
3642 /* get the header text */
3643 if ((t = mail_fetch_header (stream,msgno,NIL,&sth,&s.size,
3644 FT_INTERNAL | FT_PEEK |
3645 (section ? NIL : FT_SEARCHLOOKAHEAD))) &&
3646 strchr (t,':')) {
3647 if (hdr->text.size) { /* anything matches empty search string */
3648 /* non-empty, copy field data */
3649 s.data = (unsigned char *) fs_get (s.size + 1);
3650 /* for each line */
3651 for (v = (char *) s.data, e = t + s.size; t < e;) switch (*t) {
3652 default: /* non-continuation, skip leading field name */
3653 while ((t < e) && (*t++ != ':'));
3654 if ((t < e) && (*t == ':')) t++;
3655 case '\t': case ' ': /* copy field data */
3656 while ((t < e) && (*t != '\015') && (*t != '\012')) *v++ = *t++;
3657 *v++ = '\n'; /* tie off line */
3658 while (((*t == '\015') || (*t == '\012')) && (t < e)) t++;
3660 /* calculate true size */
3661 s.size = v - (char *) s.data;
3662 *v = '\0'; /* tie off results */
3663 stc.text.data = hdr->text.data;
3664 stc.text.size = hdr->text.size;
3665 /* search header */
3666 if (mail_search_header (&s,&stc)) fs_give ((void **) &s.data);
3667 else { /* search failed */
3668 fs_give ((void **) &s.data);
3669 return NIL;
3673 else return NIL; /* no matching header text */
3675 /* search strings */
3676 if ((pgm->text && !mail_search_text (stream,msgno,section,pgm->text,LONGT))||
3677 (pgm->body && !mail_search_text (stream,msgno,section,pgm->body,NIL)))
3678 return NIL;
3679 /* logical conditions */
3680 for (or = pgm->or; or; or = or->next)
3681 if (!(mail_search_msg (stream,msgno,section,or->first) ||
3682 mail_search_msg (stream,msgno,section,or->second))) return NIL;
3683 for (not = pgm->not; not; not = not->next)
3684 if (mail_search_msg (stream,msgno,section,not->pgm)) return NIL;
3685 return T;
3688 /* Mail search message header null-terminated text
3689 * Accepts: header text
3690 * strings to search
3691 * Returns: T if search found a match
3694 long mail_search_header_text (char *s,STRINGLIST *st)
3696 SIZEDTEXT h;
3697 /* have any text? */
3698 if ((h.data = (unsigned char *) s) != NULL) {
3699 h.size = strlen (s); /* yes, get its size */
3700 return mail_search_header (&h,st);
3702 return NIL;
3706 /* Mail search message header
3707 * Accepts: header as sized text
3708 * strings to search
3709 * Returns: T if search found a match
3712 long mail_search_header (SIZEDTEXT *hdr,STRINGLIST *st)
3714 SIZEDTEXT h;
3715 long ret = LONGT;
3716 /* make UTF-8 version of header */
3717 utf8_mime2text (hdr,&h,U8T_CANONICAL);
3718 while (h.size && ((h.data[h.size-1]=='\015') || (h.data[h.size-1]=='\012')))
3719 --h.size; /* slice off trailing newlines */
3720 do if (h.size ? /* search non-empty string */
3721 !ssearch (h.data,h.size,st->text.data,st->text.size) : st->text.size)
3722 ret = NIL;
3723 while (ret && (st = st->next));
3724 if (h.data != hdr->data) fs_give ((void **) &h.data);
3725 return ret;
3728 /* Mail search message body
3729 * Accepts: MAIL stream
3730 * message number
3731 * optional section specification
3732 * string list
3733 * flags
3734 * Returns: T if search found a match
3737 long mail_search_text (MAILSTREAM *stream,unsigned long msgno,char *section,
3738 STRINGLIST *st,long flags)
3740 BODY *body;
3741 long ret = NIL;
3742 STRINGLIST *s = mail_newstringlist ();
3743 mailgets_t omg = mailgets;
3744 if (stream->dtb->flags & DR_LOWMEM) mailgets = mail_search_gets;
3745 /* strings to search */
3746 for (stream->private.search.string = s; st;) {
3747 s->text.data = st->text.data;
3748 s->text.size = st->text.size;
3749 if ((st = st->next) != NULL) s = s->next = mail_newstringlist ();
3751 stream->private.search.text = NIL;
3752 if (flags) { /* want header? */
3753 SIZEDTEXT s,t;
3754 s.data = (unsigned char *)
3755 mail_fetch_header (stream,msgno,section,NIL,&s.size,FT_INTERNAL|FT_PEEK);
3756 utf8_mime2text (&s,&t,U8T_CANONICAL);
3757 ret = mail_search_string_work (&t,&stream->private.search.string);
3758 if (t.data != s.data) fs_give ((void **) &t.data);
3760 if (!ret) { /* still looking for match? */
3761 /* no section, get top-level body */
3762 if (!section) mail_fetchstructure (stream,msgno,&body);
3763 /* get body of nested message */
3764 else if ((body = mail_body (stream,msgno,section)) &&
3765 (body->type == TYPEMULTIPART) && body->subtype &&
3766 !strcmp (body->subtype,"RFC822")) body = body->nested.msg->body;
3767 if (body) ret = mail_search_body (stream,msgno,body,NIL,1,flags);
3769 mailgets = omg; /* restore former gets routine */
3770 /* clear searching */
3771 for (s = stream->private.search.string; s; s = s->next) s->text.data = NIL;
3772 mail_free_stringlist (&stream->private.search.string);
3773 stream->private.search.text = NIL;
3774 return ret;
3777 /* Mail search message body text parts
3778 * Accepts: MAIL stream
3779 * message number
3780 * current body pointer
3781 * hierarchical level prefix
3782 * position at current hierarchical level
3783 * string list
3784 * flags
3785 * Returns: T if search found a match
3788 long mail_search_body (MAILSTREAM *stream,unsigned long msgno,BODY *body,
3789 char *prefix,unsigned long section,long flags)
3791 long ret = NIL;
3792 unsigned long i;
3793 char *s,*t,sect[MAILTMPLEN];
3794 SIZEDTEXT st,h;
3795 PART *part;
3796 PARAMETER *param;
3797 if (prefix && (strlen (prefix) > (MAILTMPLEN - 20))) return NIL;
3798 sprintf (sect,"%s%lu",prefix ? prefix : "",section++);
3799 if (flags && prefix) { /* want to search MIME header too? */
3800 st.data = (unsigned char *) mail_fetch_mime (stream,msgno,sect,&st.size,
3801 FT_INTERNAL | FT_PEEK);
3802 if (stream->dtb->flags & DR_LOWMEM) ret = stream->private.search.result;
3803 else {
3804 /* make UTF-8 version of header */
3805 utf8_mime2text (&st,&h,U8T_CANONICAL);
3806 ret = mail_search_string_work (&h,&stream->private.search.string);
3807 if (h.data != st.data) fs_give ((void **) &h.data);
3810 if (!ret) switch (body->type) {
3811 case TYPEMULTIPART:
3812 /* extend prefix if not first time */
3813 s = prefix ? strcat (sect,".") : "";
3814 for (i = 1,part = body->nested.part; part && !ret; i++,part = part->next)
3815 ret = mail_search_body (stream,msgno,&part->body,s,i,flags);
3816 break;
3817 case TYPEMESSAGE:
3818 if (!strcmp (body->subtype,"RFC822")) {
3819 if (flags) { /* want to search nested message header? */
3820 st.data = (unsigned char *)
3821 mail_fetch_header (stream,msgno,sect,NIL,&st.size,
3822 FT_INTERNAL | FT_PEEK);
3823 if (stream->dtb->flags & DR_LOWMEM) ret =stream->private.search.result;
3824 else {
3825 /* make UTF-8 version of header */
3826 utf8_mime2text (&st,&h,U8T_CANONICAL);
3827 ret = mail_search_string_work (&h,&stream->private.search.string);
3828 if (h.data != st.data) fs_give ((void **) &h.data);
3831 if ((body = body->nested.msg->body) != NULL)
3832 ret = (body->type == TYPEMULTIPART) ?
3833 mail_search_body (stream,msgno,body,(prefix ? prefix : ""),
3834 section - 1,flags) :
3835 mail_search_body (stream,msgno,body,strcat (sect,"."),1,flags);
3836 break;
3838 /* non-MESSAGE/RFC822 falls into text case */
3840 case TYPETEXT:
3841 s = mail_fetch_body (stream,msgno,sect,&i,FT_INTERNAL | FT_PEEK);
3842 if (stream->dtb->flags & DR_LOWMEM) ret = stream->private.search.result;
3843 else {
3844 for (t = NIL,param = body->parameter; param && !t; param = param->next)
3845 if (!strcmp (param->attribute,"CHARSET")) t = param->value;
3846 switch (body->encoding) { /* what encoding? */
3847 case ENCBASE64:
3848 if ((st.data = (unsigned char *)
3849 rfc822_base64 ((unsigned char *) s,i,&st.size)) != NULL) {
3850 ret = mail_search_string (&st,t,&stream->private.search.string);
3851 fs_give ((void **) &st.data);
3853 break;
3854 case ENCQUOTEDPRINTABLE:
3855 if ((st.data = rfc822_qprint ((unsigned char *) s,i,&st.size)) != NULL) {
3856 ret = mail_search_string (&st,t,&stream->private.search.string);
3857 fs_give ((void **) &st.data);
3859 break;
3860 default:
3861 st.data = (unsigned char *) s;
3862 st.size = i;
3863 ret = mail_search_string (&st,t,&stream->private.search.string);
3864 break;
3867 break;
3869 return ret;
3872 /* Mail search text
3873 * Accepts: sized text to search
3874 * character set of sized text
3875 * string list of search keys
3876 * Returns: T if search found a match
3879 long mail_search_string (SIZEDTEXT *s,char *charset,STRINGLIST **st)
3881 SIZEDTEXT u;
3882 long ret;
3883 STRINGLIST **sc = st;
3884 /* convert to UTF-8 as best we can */
3885 if (!utf8_text (s,charset,&u,U8T_CANONICAL))
3886 utf8_text (s,NIL,&u,U8T_CANONICAL);
3887 ret = mail_search_string_work (&u,st);
3888 if (u.data != s->data) fs_give ((void **) &u.data);
3889 return ret;
3893 /* Mail search text worker routine
3894 * Accepts: sized text to search
3895 * string list of search keys
3896 * Returns: T if search found a match
3899 long mail_search_string_work (SIZEDTEXT *s,STRINGLIST **st)
3901 void *t;
3902 STRINGLIST **sc = st;
3903 while (*sc) { /* run down criteria list */
3904 if (ssearch (s->data,s->size,(*sc)->text.data,(*sc)->text.size)) {
3905 t = (void *) (*sc); /* found one, need to flush this */
3906 *sc = (*sc)->next; /* remove it from the list */
3907 fs_give (&t); /* flush the buffer */
3909 else sc = &(*sc)->next; /* move to next in list */
3911 return *st ? NIL : LONGT;
3915 /* Mail search keyword
3916 * Accepts: MAIL stream
3917 * elt to get flags from
3918 * keyword list
3919 * T for keyword search, NIL for unkeyword search
3920 * Returns: T if search found a match
3923 long mail_search_keyword (MAILSTREAM *stream,MESSAGECACHE *elt,STRINGLIST *st,
3924 long flag)
3926 int i,j;
3927 unsigned long f = 0;
3928 unsigned long tf;
3929 do {
3930 for (i = 0; (j = (i < NUSERFLAGS) && stream->user_flags[i]); ++i)
3931 if (!compare_csizedtext (stream->user_flags[i],&st->text)) {
3932 f |= (1 << i);
3933 break;
3935 if (flag && !j) return NIL;
3936 } while ((st = st->next) != NULL);
3937 tf = elt->user_flags & f; /* get set flags which match */
3938 return flag ? (f == tf) : !tf;
3941 /* Mail search an address list
3942 * Accepts: address list
3943 * string list
3944 * Returns: T if search found a match
3947 #define SEARCHBUFLEN (size_t) 2000
3948 #define SEARCHBUFSLOP (size_t) 5
3950 long mail_search_addr (ADDRESS *adr,STRINGLIST *st)
3952 ADDRESS *a,tadr;
3953 SIZEDTEXT txt;
3954 char tmp[SENDBUFLEN + 1];
3955 size_t i = SEARCHBUFLEN;
3956 size_t k;
3957 long ret = NIL;
3958 if (adr) {
3959 txt.data = (unsigned char *) fs_get (i + SEARCHBUFSLOP);
3960 /* never an error or next */
3961 tadr.error = NIL,tadr.next = NIL;
3962 /* write address list */
3963 for (txt.size = 0,a = adr; a; a = a->next) {
3964 k = (tadr.mailbox = a->mailbox) ? 4 + 2*strlen (a->mailbox) : 3;
3965 if ((tadr.personal = a->personal) != NULL) k += 3 + 2*strlen (a->personal);
3966 if ((tadr.adl = a->adl) != NULL) k += 3 + 2*strlen (a->adl);
3967 if ((tadr.host = a->host) != NULL) k += 3 + 2*strlen (a->host);
3968 if (tadr.personal || tadr.adl) k += 2;
3969 if (k < (SENDBUFLEN-10)) {/* ignore ridiculous addresses */
3970 tmp[0] = '\0';
3971 rfc822_write_address (tmp,&tadr);
3972 /* resize buffer if necessary */
3973 if (((k = strlen (tmp)) + txt.size) > i)
3974 fs_resize ((void **) &txt.data,SEARCHBUFSLOP + (i += SEARCHBUFLEN));
3975 /* add new address */
3976 memcpy (txt.data + txt.size,tmp,k);
3977 txt.size += k;
3978 /* another address follows */
3979 if (a->next) txt.data[txt.size++] = ',';
3982 txt.data[txt.size] = '\0'; /* tie off string */
3983 ret = mail_search_header (&txt,st);
3984 fs_give ((void **) &txt.data);
3986 return ret;
3989 /* Get string for low-memory searching
3990 * Accepts: readin function pointer
3991 * stream to use
3992 * number of bytes
3993 * gets data packet
3995 * mail stream
3996 * message number
3997 * descriptor string
3998 * option flags
3999 * Returns: NIL, always
4002 #define SEARCHSLOP 128
4004 char *mail_search_gets (readfn_t f,void *stream,unsigned long size,
4005 GETS_DATA *md)
4007 unsigned long i;
4008 char tmp[MAILTMPLEN+SEARCHSLOP+1];
4009 SIZEDTEXT st;
4010 /* better not be called unless searching */
4011 if (!md->stream->private.search.string) {
4012 sprintf (tmp,"Search botch, mbx = %.80s, %s = %lu[%.80s]",
4013 md->stream->mailbox,
4014 (md->flags & FT_UID) ? "UID" : "msg",md->msgno,md->what);
4015 fatal (tmp);
4017 /* initially no match for search */
4018 md->stream->private.search.result = NIL;
4019 /* make sure buffer clear */
4020 memset (st.data = (unsigned char *) tmp,'\0',
4021 (size_t) MAILTMPLEN+SEARCHSLOP+1);
4022 /* read first buffer */
4023 (*f) (stream,st.size = i = min (size,(long) MAILTMPLEN),tmp);
4024 /* search for text */
4025 if (mail_search_string (&st,NIL,&md->stream->private.search.string))
4026 md->stream->private.search.result = T;
4027 else if (size -= i) { /* more to do, blat slop down */
4028 memmove (tmp,tmp+MAILTMPLEN-SEARCHSLOP,(size_t) SEARCHSLOP);
4029 do { /* read subsequent buffers one at a time */
4030 (*f) (stream,i = min (size,(long) MAILTMPLEN),tmp+SEARCHSLOP);
4031 st.size = i + SEARCHSLOP;
4032 if (mail_search_string (&st,NIL,&md->stream->private.search.string))
4033 md->stream->private.search.result = T;
4034 else memmove (tmp,tmp+MAILTMPLEN,(size_t) SEARCHSLOP);
4036 while ((size -= i) && !md->stream->private.search.result);
4038 if (size) { /* toss out everything after that */
4039 do (*f) (stream,i = min (size,(long) MAILTMPLEN),tmp);
4040 while (size -= i);
4042 return NIL;
4045 /* Mail parse search criteria
4046 * Accepts: criteria
4047 * Returns: search program if parse successful, else NIL
4050 SEARCHPGM *mail_criteria (char *criteria)
4052 SEARCHPGM *pgm = NIL;
4053 char *criterion,*r,tmp[MAILTMPLEN];
4054 int f;
4055 if (criteria) { /* only if criteria defined */
4056 /* make writeable copy of criteria */
4057 criteria = cpystr (criteria);
4058 /* for each criterion */
4059 for (pgm = mail_newsearchpgm (), criterion = strtok_r (criteria," ",&r);
4060 criterion; (criterion = strtok_r (NIL," ",&r))) {
4061 f = NIL; /* init then scan the criterion */
4062 switch (*ucase (criterion)) {
4063 case 'A': /* possible ALL, ANSWERED */
4064 if (!strcmp (criterion+1,"LL")) f = T;
4065 else if (!strcmp (criterion+1,"NSWERED")) f = pgm->answered = T;
4066 break;
4067 case 'B': /* possible BCC, BEFORE, BODY */
4068 if (!strcmp (criterion+1,"CC"))
4069 f = mail_criteria_string (&pgm->bcc,&r);
4070 else if (!strcmp (criterion+1,"EFORE"))
4071 f = mail_criteria_date (&pgm->before,&r);
4072 else if (!strcmp (criterion+1,"ODY"))
4073 f = mail_criteria_string (&pgm->body,&r);
4074 break;
4075 case 'C': /* possible CC */
4076 if (!strcmp (criterion+1,"C")) f = mail_criteria_string (&pgm->cc,&r);
4077 break;
4078 case 'D': /* possible DELETED */
4079 if (!strcmp (criterion+1,"ELETED")) f = pgm->deleted = T;
4080 break;
4081 case 'F': /* possible FLAGGED, FROM */
4082 if (!strcmp (criterion+1,"LAGGED")) f = pgm->flagged = T;
4083 else if (!strcmp (criterion+1,"ROM"))
4084 f = mail_criteria_string (&pgm->from,&r);
4085 break;
4086 case 'K': /* possible KEYWORD */
4087 if (!strcmp (criterion+1,"EYWORD"))
4088 f = mail_criteria_string (&pgm->keyword,&r);
4089 break;
4091 case 'N': /* possible NEW */
4092 if (!strcmp (criterion+1,"EW")) f = pgm->recent = pgm->unseen = T;
4093 break;
4094 case 'O': /* possible OLD, ON */
4095 if (!strcmp (criterion+1,"LD")) f = pgm->old = T;
4096 else if (!strcmp (criterion+1,"N"))
4097 f = mail_criteria_date (&pgm->on,&r);
4098 break;
4099 case 'R': /* possible RECENT */
4100 if (!strcmp (criterion+1,"ECENT")) f = pgm->recent = T;
4101 break;
4102 case 'S': /* possible SEEN, SINCE, SUBJECT */
4103 if (!strcmp (criterion+1,"EEN")) f = pgm->seen = T;
4104 else if (!strcmp (criterion+1,"INCE"))
4105 f = mail_criteria_date (&pgm->since,&r);
4106 else if (!strcmp (criterion+1,"UBJECT"))
4107 f = mail_criteria_string (&pgm->subject,&r);
4108 break;
4109 case 'T': /* possible TEXT, TO */
4110 if (!strcmp (criterion+1,"EXT"))
4111 f = mail_criteria_string (&pgm->text,&r);
4112 else if (!strcmp (criterion+1,"O"))
4113 f = mail_criteria_string (&pgm->to,&r);
4114 break;
4115 case 'U': /* possible UN* */
4116 if (criterion[1] == 'N') {
4117 if (!strcmp (criterion+2,"ANSWERED")) f = pgm->unanswered = T;
4118 else if (!strcmp (criterion+2,"DELETED")) f = pgm->undeleted = T;
4119 else if (!strcmp (criterion+2,"FLAGGED")) f = pgm->unflagged = T;
4120 else if (!strcmp (criterion+2,"KEYWORD"))
4121 f = mail_criteria_string (&pgm->unkeyword,&r);
4122 else if (!strcmp (criterion+2,"SEEN")) f = pgm->unseen = T;
4124 break;
4125 default: /* we will barf below */
4126 break;
4128 if (!f) { /* if can't identify criterion */
4129 sprintf (tmp,"Unknown search criterion: %.30s",criterion);
4130 MM_LOG (tmp,ERROR);
4131 mail_free_searchpgm (&pgm);
4132 break;
4135 /* no longer need copy of criteria */
4136 fs_give ((void **) &criteria);
4138 return pgm;
4141 /* Parse a date
4142 * Accepts: pointer to date integer to return
4143 * pointer to strtok state
4144 * Returns: T if successful, else NIL
4147 int mail_criteria_date (unsigned short *date,char **r)
4149 STRINGLIST *s = NIL;
4150 MESSAGECACHE elt;
4151 /* parse the date and return fn if OK */
4152 int ret = (mail_criteria_string (&s,r) &&
4153 mail_parse_date (&elt,(char *) s->text.data) &&
4154 (*date = mail_shortdate (elt.year,elt.month,elt.day))) ?
4155 T : NIL;
4156 if (s) mail_free_stringlist (&s);
4157 return ret;
4160 /* Calculate shortdate from elt values
4161 * Accepts: year (0 = BASEYEAR)
4162 * month (1 = January)
4163 * day
4164 * Returns: shortdate
4167 unsigned short mail_shortdate (unsigned int year,unsigned int month,
4168 unsigned int day)
4170 return (year << 9) + (month << 5) + day;
4173 /* Parse a string
4174 * Accepts: pointer to stringlist
4175 * pointer to strtok state
4176 * Returns: T if successful, else NIL
4179 int mail_criteria_string (STRINGLIST **s,char **r)
4181 unsigned long n;
4182 char e,*d,*end = " ",*c = strtok_r (NIL,"",r);
4183 if (!c) return NIL; /* missing argument */
4184 switch (*c) { /* see what the argument is */
4185 case '{': /* literal string */
4186 n = strtoul (c+1,&d,10); /* get its length */
4187 if ((*d++ == '}') && (*d++ == '\015') && (*d++ == '\012') &&
4188 (!(*(c = d + n)) || (*c == ' '))) {
4189 e = *--c; /* store old delimiter */
4190 *c = '\377'; /* make sure not a space */
4191 strtok_r (c," ",r); /* reset the strtok mechanism */
4192 *c = e; /* put character back */
4193 break;
4195 case '\0': /* catch bogons */
4196 case ' ':
4197 return NIL;
4198 case '"': /* quoted string */
4199 if (strchr (c+1,'"')) end = "\"";
4200 else return NIL; /* falls through */
4201 default: /* atomic string */
4202 if ((d = strtok_r (c,end,r)) != NULL) n = strlen (d);
4203 else return NIL;
4204 break;
4206 while (*s) s = &(*s)->next; /* find tail of list */
4207 *s = mail_newstringlist (); /* make new entry */
4208 /* return the data */
4209 (*s)->text.data = (unsigned char *) cpystr (d);
4210 (*s)->text.size = n;
4211 return T;
4214 /* Mail parse set from string
4215 * Accepts: string to parse
4216 * pointer to updated string pointer for return
4217 * Returns: set with pointer updated, or NIL if error
4220 SEARCHSET *mail_parse_set (char *s,char **ret)
4222 SEARCHSET *cur;
4223 SEARCHSET *set = NIL;
4224 while (isdigit (*s)) {
4225 if (!set) cur = set = mail_newsearchset ();
4226 else cur = cur->next = mail_newsearchset ();
4227 /* parse value */
4228 if (!(cur->first = strtoul (s,&s,10)) ||
4229 ((*s == ':') && !(isdigit (*++s) && (cur->last = strtoul (s,&s,10)))))
4230 break; /* bad value or range */
4231 if (*s == ',') ++s; /* point to next value if more */
4232 else { /* end of set */
4233 *ret = s; /* set return pointer */
4234 return set; /* return set */
4237 mail_free_searchset (&set); /* failure, punt partial set */
4238 return NIL;
4242 /* Mail append to set
4243 * Accepts: head of search set or NIL to do nothing
4244 * message to add
4245 * Returns: tail of search set or NIL if did nothing
4248 SEARCHSET *mail_append_set (SEARCHSET *set,unsigned long msgno)
4250 if (set) { /* find tail */
4251 while (set->next) set = set->next;
4252 /* start of set if no first member */
4253 if (!set->first) set->first = msgno;
4254 else if (msgno == (set->last ? set->last : set->first) + 1)
4255 set->last = msgno; /* extend range if 1 past current */
4256 else (set = set->next = mail_newsearchset ())->first = msgno;
4258 return set;
4261 /* Mail sort messages
4262 * Accepts: mail stream
4263 * character set
4264 * search program
4265 * sort program
4266 * option flags
4267 * Returns: vector of sorted message sequences or NIL if error
4270 unsigned long *mail_sort (MAILSTREAM *stream,char *charset,SEARCHPGM *spg,
4271 SORTPGM *pgm,long flags)
4273 unsigned long *ret = NIL;
4274 if (stream->dtb) /* do the driver's action */
4275 ret = (*(stream->dtb->sort ? stream->dtb->sort : mail_sort_msgs))
4276 (stream,charset,spg,pgm,flags);
4277 /* flush search/sort programs if requested */
4278 if (spg && (flags & SE_FREE)) mail_free_searchpgm (&spg);
4279 if (flags & SO_FREE) mail_free_sortpgm (&pgm);
4280 return ret;
4283 /* Mail sort messages work routine
4284 * Accepts: mail stream
4285 * character set
4286 * search program
4287 * sort program
4288 * option flags
4289 * Returns: vector of sorted message sequences or NIL if error
4292 unsigned long *mail_sort_msgs (MAILSTREAM *stream,char *charset,SEARCHPGM *spg,
4293 SORTPGM *pgm,long flags)
4295 unsigned long i;
4296 SORTCACHE **sc;
4297 unsigned long *ret = NIL;
4298 if (spg) { /* only if a search needs to be done */
4299 int silent = stream->silent;
4300 stream->silent = T; /* don't pass up mm_searched() events */
4301 /* search for messages */
4302 mail_search_full (stream,charset,spg,NIL);
4303 stream->silent = silent; /* restore silence state */
4305 /* initialize progress counters */
4306 pgm->nmsgs = pgm->progress.cached = 0;
4307 /* pass 1: count messages to sort */
4308 for (i = 1; i <= stream->nmsgs; ++i)
4309 if (mail_elt (stream,i)->searched) pgm->nmsgs++;
4310 if (pgm->nmsgs) { /* pass 2: sort cache */
4311 sc = mail_sort_loadcache (stream,pgm);
4312 /* pass 3: sort messages */
4313 if (!pgm->abort) ret = mail_sort_cache (stream,pgm,sc,flags);
4314 fs_give ((void **) &sc); /* don't need sort vector any more */
4316 /* empty sort results */
4317 else ret = (unsigned long *) memset (fs_get (sizeof (unsigned long)),0,
4318 sizeof (unsigned long));
4319 /* also return via callback if requested */
4320 if (mailsortresults) (*mailsortresults) (stream,ret,pgm->nmsgs);
4321 return ret; /* return sort results */
4324 /* Mail sort sortcache vector
4325 * Accepts: mail stream
4326 * sort program
4327 * sortcache vector
4328 * option flags
4329 * Returns: vector of sorted message sequences or NIL if error
4332 unsigned long *mail_sort_cache (MAILSTREAM *stream,SORTPGM *pgm,SORTCACHE **sc,
4333 long flags)
4335 unsigned long i,*ret;
4336 /* pass 3: sort messages */
4337 qsort ((void *) sc,pgm->nmsgs,sizeof (SORTCACHE *),mail_sort_compare);
4338 /* optional post sorting */
4339 if (pgm->postsort) (*pgm->postsort) ((void *) sc);
4340 /* pass 4: return results */
4341 ret = (unsigned long *) fs_get ((pgm->nmsgs+1) * sizeof (unsigned long));
4342 if (flags & SE_UID) /* UID or msgno? */
4343 for (i = 0; i < pgm->nmsgs; i++) ret[i] = mail_uid (stream,sc[i]->num);
4344 else for (i = 0; i < pgm->nmsgs; i++) ret[i] = sc[i]->num;
4345 ret[pgm->nmsgs] = 0; /* tie off message list */
4346 return ret;
4349 /* Mail load sortcache
4350 * Accepts: mail stream, already searched
4351 * sort program
4352 * Returns: vector of sortcache pointers matching search
4355 static STRINGLIST maildateline = {{(unsigned char *) "date",4},NIL};
4356 static STRINGLIST mailrnfromline = {{(unsigned char *) ">from",5},NIL};
4357 static STRINGLIST mailfromline = {{(unsigned char *) "from",4},
4358 &mailrnfromline};
4359 static STRINGLIST mailtonline = {{(unsigned char *) "to",2},NIL};
4360 static STRINGLIST mailccline = {{(unsigned char *) "cc",2},NIL};
4361 static STRINGLIST mailsubline = {{(unsigned char *) "subject",7},NIL};
4363 SORTCACHE **mail_sort_loadcache (MAILSTREAM *stream,SORTPGM *pgm)
4365 char *t,*v,*x,tmp[MAILTMPLEN];
4366 SORTPGM *pg;
4367 SORTCACHE *s,**sc;
4368 MESSAGECACHE *elt,telt;
4369 ENVELOPE *env;
4370 ADDRESS *adr = NIL;
4371 unsigned long i = (pgm->nmsgs) * sizeof (SORTCACHE *);
4372 sc = (SORTCACHE **) memset (fs_get ((size_t) i),0,(size_t) i);
4373 /* see what needs to be loaded */
4374 for (i = 1; !pgm->abort && (i <= stream->nmsgs); i++)
4375 if ((elt = mail_elt (stream,i))->searched) {
4376 sc[pgm->progress.cached++] =
4377 s = (SORTCACHE *) (*mailcache) (stream,i,CH_SORTCACHE);
4378 s->pgm = pgm; /* note sort program */
4379 s->num = i;
4380 /* get envelope if cached */
4381 if (stream->scache) env = (i == stream->msgno) ? stream->env : NIL;
4382 else env = elt->private.msg.env;
4383 for (pg = pgm; pg; pg = pg->next) switch (pg->function) {
4384 case SORTARRIVAL: /* sort by arrival date */
4385 if (!s->arrival) {
4386 /* internal date unknown but can get? */
4387 if (!elt->day && !(stream->dtb->flags & DR_NOINTDATE)) {
4388 sprintf (tmp,"%lu",i);
4389 mail_fetch_fast (stream,tmp,NIL);
4391 /* wrong thing before 3-Jan-1970 */
4392 s->arrival = elt->day ? mail_longdate (elt) : 1;
4393 s->dirty = T;
4395 break;
4396 case SORTSIZE: /* sort by message size */
4397 if (!s->size) {
4398 if (!elt->rfc822_size) {
4399 sprintf (tmp,"%lu",i);
4400 mail_fetch_fast (stream,tmp,NIL);
4402 s->size = elt->rfc822_size ? elt->rfc822_size : 1;
4403 s->dirty = T;
4405 break;
4407 case SORTDATE: /* sort by date */
4408 if (!s->date) {
4409 if (env) t = env->date;
4410 else if ((t = mail_fetch_header (stream,i,NIL,&maildateline,NIL,
4411 FT_INTERNAL | FT_PEEK)) &&
4412 (t = strchr (t,':')))
4413 for (x = ++t; (x = strpbrk (x,"\012\015")) != NULL; x++)
4414 switch (*(v = ((*x == '\015') && (x[1] == '\012')) ? x+2 : x+1)){
4415 case ' ': /* erase continuation newlines */
4416 case '\t':
4417 memmove (x,v,strlen (v));
4418 break;
4419 default: /* tie off extraneous text */
4420 *x = x[1] = '\0';
4422 /* skip leading whitespace */
4423 if (t) while ((*t == ' ') || (*t == '\t')) t++;
4424 /* parse date from Date: header */
4425 if (!(t && mail_parse_date (&telt,t) &&
4426 (s->date = mail_longdate (&telt)))) {
4427 /* failed, use internal date */
4428 if (!(s->date = s->arrival)) {
4429 /* internal date unknown but can get? */
4430 if (!elt->day && !(stream->dtb->flags & DR_NOINTDATE)) {
4431 sprintf (tmp,"%lu",i);
4432 mail_fetch_fast (stream,tmp,NIL);
4434 /* wrong thing before 3-Jan-1970 */
4435 s->date = (s->arrival = elt->day ? mail_longdate (elt) : 1);
4438 s->dirty = T;
4440 break;
4442 case SORTFROM: /* sort by first from */
4443 if (!s->from) {
4444 if (env) s->from = env->from && env->from->mailbox ?
4445 cpystr (env->from->mailbox) : NIL;
4446 else if ((t = mail_fetch_header (stream,i,NIL,&mailfromline,NIL,
4447 FT_INTERNAL | FT_PEEK)) &&
4448 (t = strchr (t,':'))) {
4449 for (x = ++t; (x = strpbrk (x,"\012\015")) != NULL; x++)
4450 switch (*(v = ((*x == '\015') && (x[1] == '\012')) ? x+2 : x+1)){
4451 case ' ': /* erase continuation newlines */
4452 case '\t':
4453 memmove (x,v,strlen (v));
4454 break;
4455 case 'f': /* continuation but with extra "From:" */
4456 case 'F':
4457 if ((v = strchr (v,':')) != NULL) {
4458 memmove (x,v+1,strlen (v+1));
4459 break;
4461 default: /* tie off extraneous text */
4462 *x = x[1] = '\0';
4464 rfc822_parse_adrlist (&adr,t,BADHOST);
4465 if (adr) {
4466 s->from = adr->mailbox;
4467 adr->mailbox = NIL;
4468 mail_free_address (&adr);
4471 if (!s->from) s->from = cpystr ("");
4472 s->dirty = T;
4474 break;
4476 case SORTTO: /* sort by first to */
4477 if (!s->to) {
4478 if (env) s->to = env->to && env->to->mailbox ?
4479 cpystr (env->to->mailbox) : NIL;
4480 else if ((t = mail_fetch_header (stream,i,NIL,&mailtonline,NIL,
4481 FT_INTERNAL | FT_PEEK)) &&
4482 (t = strchr (t,':'))) {
4483 for (x = ++t; (x = strpbrk (x,"\012\015")) != NULL; x++)
4484 switch (*(v = ((*x == '\015') && (x[1] == '\012')) ? x+2 : x+1)){
4485 case ' ': /* erase continuation newlines */
4486 case '\t':
4487 memmove (x,v,strlen (v));
4488 break;
4489 case 't': /* continuation but with extra "To:" */
4490 case 'T':
4491 if ((v = strchr (v,':')) != NULL) {
4492 memmove (x,v+1,strlen (v+1));
4493 break;
4495 default: /* tie off extraneous text */
4496 *x = x[1] = '\0';
4498 rfc822_parse_adrlist (&adr,t,BADHOST);
4499 if (adr) {
4500 s->to = adr->mailbox;
4501 adr->mailbox = NIL;
4502 mail_free_address (&adr);
4505 if (!s->to) s->to = cpystr ("");
4506 s->dirty = T;
4508 break;
4510 case SORTCC: /* sort by first cc */
4511 if (!s->cc) {
4512 if (env) s->cc = env->cc && env->cc->mailbox ?
4513 cpystr (env->cc->mailbox) : NIL;
4514 else if ((t = mail_fetch_header (stream,i,NIL,&mailccline,NIL,
4515 FT_INTERNAL | FT_PEEK)) &&
4516 (t = strchr (t,':'))) {
4517 for (x = ++t; (x = strpbrk (x,"\012\015")) != NULL; x++)
4518 switch (*(v = ((*x == '\015') && (x[1] == '\012')) ? x+2 : x+1)){
4519 case ' ': /* erase continuation newlines */
4520 case '\t':
4521 memmove (x,v,strlen (v));
4522 break;
4523 case 'c': /* continuation but with extra "cc:" */
4524 case 'C':
4525 if ((v = strchr (v,':')) != NULL) {
4526 memmove (x,v+1,strlen (v+1));
4527 break;
4529 default: /* tie off extraneous text */
4530 *x = x[1] = '\0';
4532 rfc822_parse_adrlist (&adr,t,BADHOST);
4533 if (adr) {
4534 s->cc = adr->mailbox;
4535 adr->mailbox = NIL;
4536 mail_free_address (&adr);
4539 if (!s->cc) s->cc = cpystr ("");
4540 s->dirty = T;
4542 break;
4544 case SORTSUBJECT: /* sort by subject */
4545 if (!s->subject) {
4546 /* get subject from envelope if have one */
4547 if (env) t = env->subject ? env->subject : "";
4548 /* otherwise snarf from header text */
4549 else if ((t = mail_fetch_header (stream,i,NIL,&mailsubline,
4550 NIL,FT_INTERNAL | FT_PEEK)) &&
4551 (t = strchr (t,':')))
4552 for (x = ++t; (x = strpbrk (x,"\012\015")) != NULL; x++)
4553 switch (*(v = ((*x == '\015') && (x[1] == '\012')) ? x+2 : x+1)){
4554 case ' ': /* erase continuation newlines */
4555 case '\t':
4556 memmove (x,v,strlen (v));
4557 break;
4558 default: /* tie off extraneous text */
4559 *x = x[1] = '\0';
4561 else t = ""; /* empty subject */
4562 /* strip and cache subject */
4563 s->refwd = mail_strip_subject (t,&s->subject);
4564 s->dirty = T;
4566 break;
4567 default:
4568 fatal ("Unknown sort function");
4571 return sc;
4574 /* Strip subjects of extra spaces and leading and trailing cruft for sorting
4575 * Accepts: unstripped subject
4576 * pointer to return stripped subject, in cpystr form
4577 * Returns: T if subject had a re/fwd, NIL otherwise
4580 unsigned int mail_strip_subject (char *t,char **ret)
4582 SIZEDTEXT src,dst;
4583 unsigned long i,slen;
4584 char c,*s,*x;
4585 unsigned int refwd = NIL;
4586 if ((src.size = strlen (t)) != 0) { /* have non-empty subject? */
4587 src.data = (unsigned char *) t;
4588 /* Step 1 */
4589 /* make copy, convert MIME2 if needed */
4590 *ret = s = (utf8_mime2text (&src,&dst,U8T_CANONICAL) &&
4591 (src.data != dst.data)) ? (char *) dst.data : cpystr (t);
4592 /* convert spaces to tab, strip extra spaces */
4593 for (x = t = s, c = 'x'; *t; t++) {
4594 if (c != ' ') c = *x++ = ((*t == '\t') ? ' ' : *t);
4595 else if ((*t != '\t') && (*t != ' ')) c = *x++ = *t;
4597 *x = '\0'; /* tie off string */
4598 /* Step 2 */
4599 for (slen = dst.size; s; slen = strlen (s)) {
4600 for (t = s + slen; t > s; ) switch (t[-1]) {
4601 case ' ': case '\t': /* WSP */
4602 *--t = '\0'; /* just remove it */
4603 break;
4604 case ')': /* possible "(fwd)" */
4605 if ((t >= (s + 5)) && (t[-5] == '(') &&
4606 ((t[-4] == 'F') || (t[-4] == 'f')) &&
4607 ((t[-3] == 'W') || (t[-3] == 'w')) &&
4608 ((t[-2] == 'D') || (t[-2] == 'd'))) {
4609 *(t -= 5) = '\0'; /* remove "(fwd)" */
4610 refwd = T; /* note a re/fwd */
4611 break;
4613 default: /* not a subj-trailer */
4614 t = s;
4615 break;
4617 /* Steps 3-5 */
4618 for (t = s; t; ) switch (*s) {
4619 case ' ': case '\t': /* WSP */
4620 s = t = mail_strip_subject_wsp (s + 1);
4621 break;
4622 case 'r': case 'R': /* possible "re" */
4623 if (((s[1] == 'E') || (s[1] == 'e')) &&
4624 (t = mail_strip_subject_wsp (s + 2)) &&
4625 (t = mail_strip_subject_blob (t)) && (*t == ':')) {
4626 s = ++t; /* found "re" */
4627 refwd = T; /* definitely a re/fwd at this point */
4629 else t = NIL; /* found subj-middle */
4630 break;
4631 case 'f': case 'F': /* possible "fw" or "fwd" */
4632 if (((s[1] == 'w') || (s[1] == 'W')) &&
4633 (((s[2] == 'd') || (s[2] == 'D')) ?
4634 (t = mail_strip_subject_wsp (s + 3)) :
4635 (t = mail_strip_subject_wsp (s + 2))) &&
4636 (t = mail_strip_subject_blob (t)) && (*t == ':')) {
4637 s = ++t; /* found "fwd" */
4638 refwd = T; /* definitely a re/fwd at this point */
4640 else t = NIL; /* found subj-middle */
4641 break;
4642 case '[': /* possible subj-blob */
4643 if ((t = mail_strip_subject_blob (s)) && *t) s = t;
4644 else t = NIL; /* found subj-middle */
4645 break;
4646 default:
4647 t = NIL; /* found subj-middle */
4648 break;
4650 /* Step 6 */
4651 /* Netscape-style "[Fwd: ...]"? */
4652 if ((*s == '[') && ((s[1] == 'F') || (s[1] == 'f')) &&
4653 ((s[2] == 'W') || (s[2] == 'w')) &&
4654 ((s[3] == 'D') || (s[3] == 'd')) && (s[4] == ':') &&
4655 (s[i = strlen (s) - 1] == ']')) {
4656 s[i] = '\0'; /* flush closing "]" */
4657 s += 5; /* and leading "[Fwd:" */
4658 refwd = T; /* definitely a re/fwd at this point */
4660 else break; /* don't need to loop back to step 2 */
4662 if (s != (t = *ret)) { /* removed leading text? */
4663 s = *ret = cpystr (s); /* yes, make a fresh return copy */
4664 fs_give ((void **) &t); /* flush old copy */
4667 else *ret = cpystr (""); /* empty subject */
4668 return refwd; /* return re/fwd state */
4671 /* Strip subject wsp helper routine
4672 * Accepts: text
4673 * Returns: pointer to text after blob
4676 char *mail_strip_subject_wsp (char *s)
4678 while ((*s == ' ') || (*s == '\t')) s++;
4679 return s;
4683 /* Strip subject blob helper routine
4684 * Accepts: text
4685 * Returns: pointer to text after any blob, NIL if blob-like but not blob
4688 char *mail_strip_subject_blob (char *s)
4690 if (*s != '[') return s; /* not a blob, ignore */
4691 /* search for end of blob */
4692 while (*++s != ']') if ((*s == '[') || !*s) return NIL;
4693 return mail_strip_subject_wsp (s + 1);
4696 /* Sort compare messages
4697 * Accept: first message sort cache element
4698 * second message sort cache element
4699 * Returns: -1 if a1 < a2, 0 if a1 == a2, 1 if a1 > a2
4702 int mail_sort_compare (const void *a1,const void *a2)
4704 int i = 0;
4705 SORTCACHE *s1 = *(SORTCACHE **) a1;
4706 SORTCACHE *s2 = *(SORTCACHE **) a2;
4707 SORTPGM *pgm = s1->pgm;
4708 if (!s1->sorted) { /* this one sorted yet? */
4709 s1->sorted = T;
4710 pgm->progress.sorted++; /* another sorted message */
4712 if (!s2->sorted) { /* this one sorted yet? */
4713 s2->sorted = T;
4714 pgm->progress.sorted++; /* another sorted message */
4716 do {
4717 switch (pgm->function) { /* execute search program */
4718 case SORTDATE: /* sort by date */
4719 i = compare_ulong (s1->date,s2->date);
4720 break;
4721 case SORTARRIVAL: /* sort by arrival date */
4722 i = compare_ulong (s1->arrival,s2->arrival);
4723 break;
4724 case SORTSIZE: /* sort by message size */
4725 i = compare_ulong (s1->size,s2->size);
4726 break;
4727 case SORTFROM: /* sort by first from */
4728 i = compare_string (s1->from,s2->from);
4729 break;
4730 case SORTTO: /* sort by first to */
4731 i = compare_string (s1->to,s2->to);
4732 break;
4733 case SORTCC: /* sort by first cc */
4734 i = compare_string (s1->cc,s2->cc);
4735 break;
4736 case SORTSUBJECT: /* sort by subject */
4737 i = compare_string (s1->subject,s2->subject);
4738 break;
4740 if (pgm->reverse) i = -i; /* flip results if necessary */
4742 while ((pgm = i ? NIL : pgm->next) != NULL);
4743 /* return result, avoid 0 if at all possible */
4744 return i ? i : compare_ulong (s1->num,s2->num);
4747 /* Return message date as an unsigned long seconds since time began
4748 * Accepts: message cache pointer
4749 * Returns: unsigned long of date
4751 * This routine, like most UNIX systems, is clueless about leap seconds.
4752 * Thus, it treats 23:59:60 as equivalent to 00:00:00 the next day.
4754 * This routine forces any early hours on 1-Jan-1970 in oriental timezones
4755 * to be 1-Jan-1970 00:00:00 UTC, so as to avoid negative longdates.
4758 unsigned long mail_longdate (MESSAGECACHE *elt)
4760 unsigned long m = elt->month ? elt->month : 1;
4761 unsigned long yr = elt->year + BASEYEAR;
4762 /* number of days since time began */
4763 unsigned long ret = (elt->day ? (elt->day - 1) : 0)
4764 + 30 * (m - 1) + ((m + (m > 8)) / 2)
4765 #ifndef USEJULIANCALENDAR
4766 #ifndef USEORTHODOXCALENDAR /* Gregorian calendar */
4767 + ((yr / 400) - (BASEYEAR / 400)) - ((yr / 100) - (BASEYEAR / 100))
4768 #ifdef Y4KBUGFIX
4769 - ((yr / 4000) - (BASEYEAR / 4000))
4770 #endif
4771 - ((m < 3) ?
4772 !(yr % 4) && ((yr % 100) || (!(yr % 400)
4773 #ifdef Y4KBUGFIX
4774 && (yr % 4000)
4775 #endif
4776 )) : 2)
4777 #else /* Orthodox calendar */
4778 + ((2*(yr / 900)) - (2*(BASEYEAR / 900)))
4779 + (((yr % 900) >= 200) - ((BASEYEAR % 900) >= 200))
4780 + (((yr % 900) >= 600) - ((BASEYEAR % 900) >= 600))
4781 - ((yr / 100) - (BASEYEAR / 100))
4782 - ((m < 3) ?
4783 !(yr % 4) && ((yr % 100) || ((yr % 900) == 200) || ((yr % 900) == 600))
4784 : 2)
4785 #endif
4786 #endif
4787 + elt->year * 365 + (((unsigned long) (elt->year + (BASEYEAR % 4))) / 4);
4788 ret *= 24; ret += elt->hours; /* date value in hours */
4789 ret *= 60; ret +=elt->minutes;/* date value in minutes */
4790 yr = (elt->zhours * 60) + elt->zminutes;
4791 if (elt->zoccident) ret += yr;/* occidental timezone, make UTC */
4792 else if (ret < yr) return 0; /* still 31-Dec-1969 in UTC */
4793 else ret -= yr; /* oriental timezone, make UTC */
4794 ret *= 60; ret += elt->seconds;
4795 return ret;
4798 /* Mail thread messages
4799 * Accepts: mail stream
4800 * thread type
4801 * character set
4802 * search program
4803 * option flags
4804 * Returns: thread node tree or NIL if error
4807 THREADNODE *mail_thread (MAILSTREAM *stream,char *type,char *charset,
4808 SEARCHPGM *spg,long flags)
4810 THREADNODE *ret = NIL;
4811 if (stream->dtb) /* must have a live driver */
4812 ret = stream->dtb->thread ? /* do driver's action if available */
4813 (*stream->dtb->thread) (stream,type,charset,spg,flags) :
4814 mail_thread_msgs (stream,type,charset,spg,flags,mail_sort_msgs);
4815 /* flush search/sort programs if requested */
4816 if (spg && (flags & SE_FREE)) mail_free_searchpgm (&spg);
4817 return ret;
4821 /* Mail thread messages
4822 * Accepts: mail stream
4823 * thread type
4824 * character set
4825 * search program
4826 * option flags
4827 * sorter routine
4828 * Returns: thread node tree or NIL if error
4831 THREADNODE *mail_thread_msgs (MAILSTREAM *stream,char *type,char *charset,
4832 SEARCHPGM *spg,long flags,sorter_t sorter)
4834 THREADER *t;
4835 for (t = &mailthreadlist; t; t = t->next)
4836 if (!compare_cstring (type,t->name)) {
4837 THREADNODE *ret = (*t->dispatch) (stream,charset,spg,flags,sorter);
4838 if (mailthreadresults) (*mailthreadresults) (stream,ret);
4839 return ret;
4841 MM_LOG ("No such thread type",ERROR);
4842 return NIL;
4845 /* Mail thread ordered subject
4846 * Accepts: mail stream
4847 * character set
4848 * search program
4849 * option flags
4850 * sorter routine
4851 * Returns: thread node tree
4854 THREADNODE *mail_thread_orderedsubject (MAILSTREAM *stream,char *charset,
4855 SEARCHPGM *spg,long flags,
4856 sorter_t sorter)
4858 THREADNODE *thr = NIL;
4859 THREADNODE *cur,*top,**tc;
4860 SORTPGM pgm,pgm2;
4861 SORTCACHE *s;
4862 unsigned long i,j,*lst,*ls;
4863 /* sort by subject+date */
4864 memset (&pgm,0,sizeof (SORTPGM));
4865 memset (&pgm2,0,sizeof (SORTPGM));
4866 pgm.function = SORTSUBJECT;
4867 pgm.next = &pgm2;
4868 pgm2.function = SORTDATE;
4869 if ((lst = (*sorter) (stream,charset,spg,&pgm,flags & ~(SE_FREE | SE_UID))) != NULL){
4870 if (*(ls = lst)) { /* create thread */
4871 /* note first subject */
4872 cur = top = thr = mail_newthreadnode
4873 ((SORTCACHE *) (*mailcache) (stream,*ls++,CH_SORTCACHE));
4874 /* note its number */
4875 cur->num = (flags & SE_UID) ? mail_uid (stream,*lst) : *lst;
4876 i = 1; /* number of threads */
4877 while (*ls) { /* build tree */
4878 /* subjects match? */
4879 s = (SORTCACHE *) (*mailcache) (stream,*ls++,CH_SORTCACHE);
4880 if (compare_cstring (top->sc->subject,s->subject)) {
4881 i++; /* have a new thread */
4882 top = top->branch = cur = mail_newthreadnode (s);
4884 /* start a child of the top */
4885 else if (cur == top) cur = cur->next = mail_newthreadnode (s);
4886 /* sibling of child */
4887 else cur = cur->branch = mail_newthreadnode (s);
4888 /* set to msgno or UID as needed */
4889 cur->num = (flags & SE_UID) ? mail_uid (stream,s->num) : s->num;
4891 /* make threadnode cache */
4892 tc = (THREADNODE **) fs_get (i * sizeof (THREADNODE *));
4893 /* load threadnode cache */
4894 for (j = 0, cur = thr; cur; cur = cur->branch) tc[j++] = cur;
4895 if (i != j) fatal ("Threadnode cache confusion");
4896 qsort ((void *) tc,i,sizeof (THREADNODE *),mail_thread_compare_date);
4897 for (j = 0, --i; j < i; j++) tc[j]->branch = tc[j+1];
4898 tc[j]->branch = NIL; /* end of root */
4899 thr = tc[0]; /* head of data */
4900 fs_give ((void **) &tc);
4902 fs_give ((void **) &lst);
4904 return thr;
4907 /* Mail thread references
4908 * Accepts: mail stream
4909 * character set
4910 * search program
4911 * option flags
4912 * sorter routine
4913 * Returns: thread node tree
4916 #define REFHASHSIZE 1009 /* arbitrary prime for hash table size */
4918 /* Reference threading container, as described in Jamie Zawinski's web page
4919 * (http://www.jwz.org/doc/threading.html) for this algorithm. These are
4920 * stored as extended data in the hash table (called "id_table" in JWZ's
4921 * document) and are maintained by the hash table routines. The hash table
4922 * routines implement extended data as additional void* words at the end of
4923 * each bucket, hence these strange macros instead of a struct which would
4924 * have been more straightforward.
4927 #define THREADLINKS 3 /* number of thread links */
4929 #define CACHE(data) ((SORTCACHE *) (data)[0])
4930 #define PARENT(data) ((container_t) (data)[1])
4931 #define SETPARENT(data,value) ((container_t) (data[1] = value))
4932 #define SIBLING(data) ((container_t) (data)[2])
4933 #define SETSIBLING(data,value) ((container_t) (data[2] = value))
4934 #define CHILD(data) ((container_t) (data)[3])
4935 #define SETCHILD(data,value) ((container_t) (data[3] = value))
4937 THREADNODE *mail_thread_references (MAILSTREAM *stream,char *charset,
4938 SEARCHPGM *spg,long flags,sorter_t sorter)
4940 MESSAGECACHE *elt,telt;
4941 ENVELOPE *env;
4942 SORTCACHE *s;
4943 STRINGLIST *st;
4944 HASHENT *he;
4945 THREADNODE **tc,*cur,*lst,*nxt,*sis,*msg;
4946 container_t con,nxc,prc,sib;
4947 void **sub;
4948 char *t,tmp[MAILTMPLEN];
4949 unsigned long j,nmsgs;
4950 unsigned long i = stream->nmsgs * sizeof (SORTCACHE *);
4951 SORTCACHE **sc = (SORTCACHE **) memset (fs_get ((size_t) i),0,(size_t) i);
4952 HASHTAB *ht = hash_create (REFHASHSIZE);
4953 THREADNODE *root = NIL;
4954 if (spg) { /* only if a search needs to be done */
4955 int silent = stream->silent;
4956 stream->silent = T; /* don't pass up mm_searched() events */
4957 /* search for messages */
4958 mail_search_full (stream,charset,spg,NIL);
4959 stream->silent = silent; /* restore silence state */
4962 /* create SORTCACHE vector of requested msgs */
4963 for (i = 1, nmsgs = 0; i <= stream->nmsgs; ++i)
4964 if (mail_elt (stream,i)->searched)
4965 (sc[nmsgs++] = (SORTCACHE *)(*mailcache)(stream,i,CH_SORTCACHE))->num =i;
4966 /* separate pass so can do overview fetch lookahead */
4967 for (i = 0; i < nmsgs; ++i) { /* for each requested message */
4968 /* is anything missing in its SORTCACHE? */
4969 if (!((s = sc[i])->date && s->subject && s->message_id && s->references)) {
4970 /* driver has an overview mechanism? */
4971 if (stream->dtb && stream->dtb->overview) {
4972 /* yes, find following unloaded entries */
4973 for (j = i + 1; (j < nmsgs) && !sc[j]->references; ++j);
4974 sprintf (tmp,"%lu",mail_uid (stream,s->num));
4975 if (i != --j) /* end of range different? */
4976 sprintf (tmp + strlen (tmp),":%lu",mail_uid (stream,sc[j]->num));
4977 /* load via overview mechanism */
4978 mail_fetch_overview (stream,tmp,mail_thread_loadcache);
4980 /* still missing data? */
4981 if (!s->date || !s->subject || !s->message_id || !s->references) {
4982 /* try to load data from envelope */
4983 if ((env = mail_fetch_structure (stream,s->num,NIL,NIL)) != NULL) {
4984 if (!s->date && env->date && mail_parse_date (&telt,env->date))
4985 s->date = mail_longdate (&telt);
4986 if (!s->subject && env->subject)
4987 s->refwd =
4988 mail_strip_subject (env->subject,&s->subject);
4989 if (!s->message_id && env->message_id && *env->message_id)
4990 s->message_id = mail_thread_parse_msgid (env->message_id,NIL);
4991 if (!s->references && /* use References: or In-Reply-To: */
4992 !(s->references =
4993 mail_thread_parse_references (env->references,T)))
4994 s->references = mail_thread_parse_references(env->in_reply_to,NIL);
4996 /* last resort */
4997 if (!s->date && !(s->date = s->arrival)) {
4998 /* internal date unknown but can get? */
4999 if (!(elt = mail_elt (stream,s->num))->day &&
5000 !(stream->dtb->flags & DR_NOINTDATE)) {
5001 sprintf (tmp,"%lu",s->num);
5002 mail_fetch_fast (stream,tmp,NIL);
5004 /* wrong thing before 3-Jan-1970 */
5005 s->date = (s->arrival = elt->day ? mail_longdate (elt) : 1);
5007 if (!s->subject) s->subject = cpystr ("");
5008 if (!s->references) s->references = mail_newstringlist ();
5009 s->dirty = T;
5013 /* Step 1 (preliminary) */
5014 /* generate unique string */
5015 sprintf (tmp,"%s.%lx.%lx@%s",stream->mailbox,stream->uid_validity,
5016 mail_uid (stream,s->num),mylocalhost ());
5017 /* flush old unique string if not message-id */
5018 if (s->unique && (s->unique != s->message_id))
5019 fs_give ((void **) &s->unique);
5020 s->unique = s->message_id ? /* don't permit Message ID duplicates */
5021 (hash_lookup (ht,s->message_id) ? cpystr (tmp) : s->message_id) :
5022 (s->message_id = cpystr (tmp));
5023 /* add unique string to hash table */
5024 hash_add (ht,s->unique,s,THREADLINKS);
5026 /* Step 1 */
5027 for (i = 0; i < nmsgs; ++i) { /* for each message in sortcache */
5028 /* Step 1A */
5029 if ((st = (s = sc[i])->references) && st->text.data)
5030 for (con = hash_lookup_and_add (ht,(char *) st->text.data,NIL,
5031 THREADLINKS); (st = st->next) != NULL; con = nxc) {
5032 nxc = hash_lookup_and_add (ht,(char *) st->text.data,NIL,THREADLINKS);
5033 /* only if no parent & won't introduce loop */
5034 if (!PARENT (nxc) && !mail_thread_check_child (con,nxc)) {
5035 SETPARENT (nxc,con); /* establish parent/child link */
5036 /* other children become sibling of this one */
5037 SETSIBLING (nxc,CHILD (con));
5038 SETCHILD (con,nxc); /* set as child of parent */
5041 else con = NIL; /* else message has no ancestors */
5042 /* Step 1B */
5043 if ((prc = PARENT ((nxc = hash_lookup (ht,s->unique)))) &&
5044 (prc != con)) { /* break links if have a different parent */
5045 SETPARENT (nxc,NIL); /* easy if direct child */
5046 if (nxc == CHILD (prc)) SETCHILD (prc,SIBLING (nxc));
5047 else { /* otherwise hunt through sisters */
5048 for (sib = CHILD (prc); nxc != SIBLING (sib); sib = SIBLING (sib));
5049 SETSIBLING (sib,SIBLING (nxc));
5051 SETSIBLING (nxc,NIL); /* no more little sisters either */
5052 prc = NIL; /* no more parent set */
5054 /* need to set parent, and parent is good? */
5055 if (!prc && !mail_thread_check_child (con,nxc)) {
5056 SETPARENT (nxc,con); /* establish parent/child link */
5057 if (con) { /* if non-root parent, set parent's child */
5058 if (CHILD (con)) { /* have a child already */
5059 /* find youngest daughter */
5060 for (con = CHILD (con); SIBLING (con); con = SIBLING (con));
5061 SETSIBLING (con,nxc); /* add new baby sister */
5063 else SETCHILD (con,nxc);/* set as only child */
5067 fs_give ((void **) &sc); /* finished with sortcache vector */
5069 /* Step 2 */
5070 /* search hash table for parentless messages */
5071 for (i = 0, prc = con = NIL; i < ht->size; i++)
5072 for (he = ht->table[i]; he; he = he->next)
5073 if (!PARENT ((nxc = he->data))) {
5074 /* sibling of previous parentless message */
5075 if (con) con = SETSIBLING (con,nxc);
5076 else prc = con = nxc; /* first parentless message */
5078 /* Once the dummy containers are pruned, we no longer need the parent
5079 * information, so we can convert the containers to THREADNODEs. Since
5080 * we don't need the id_table any more either, we can reset the hash table
5081 * and reuse it as a subject_table. Resetting the hash table will also
5082 * destroy the containers.
5084 /* Step 3 */
5085 /* prune dummies, convert to threadnode */
5086 root = mail_thread_c2node (stream,mail_thread_prune_dummy (prc,NIL),flags);
5087 /* Step 4 */
5088 /* make buffer for sorting */
5089 tc = (THREADNODE **) fs_get (nmsgs * sizeof (THREADNODE *));
5090 /* load threadcache and count nodes to sort */
5091 for (i = 0, cur = root; cur ; cur = cur->branch) tc[i++] = cur;
5092 if (i > 1) { /* only if need to sort */
5093 qsort ((void *) tc,i,sizeof (THREADNODE *),mail_thread_compare_date);
5094 /* relink siblings */
5095 for (j = 0, --i; j < i; j++) tc[j]->branch = tc[j+1];
5096 tc[j]->branch = NIL; /* end of root */
5097 root = tc[0]; /* establish new root */
5099 /* Step 5A */
5100 hash_reset (ht); /* discard containers, reset ht */
5101 /* Step 5B */
5102 for (cur = root; cur; cur = cur->branch)
5103 if ((t = (nxt = (cur->sc ? cur : cur->next))->sc->subject) && *t) {
5104 /* add new subject to hash table */
5105 if (!(sub = hash_lookup (ht,t))) hash_add (ht,t,cur,0);
5106 /* if one in table not dummy and */
5107 else if ((s = (lst = (THREADNODE *) sub[0])->sc) &&
5108 /* current dummy, or not re/fwd and table is */
5109 (!cur->sc || (!nxt->sc->refwd && s->refwd)))
5110 sub[0] = (void *) cur; /* replace with this message */
5113 /* Step 5C */
5114 for (cur = root, sis = NIL; cur; cur = msg) {
5115 /* do nothing if current message or no sub */
5116 if (!(t = (cur->sc ? cur : cur->next)->sc->subject) || !*t ||
5117 ((lst = (THREADNODE *) (sub = hash_lookup (ht,t))[0]) == cur))
5118 msg = (sis = cur)->branch;
5119 else if (!lst->sc) { /* is message in the table a dummy? */
5120 /* find youngest daughter of msg in table */
5121 for (msg = lst->next; msg->branch; msg = msg->branch);
5122 if (!cur->sc) { /* current message a dummy? */
5123 msg->branch = cur->next;/* current's daughter now dummy's youngest */
5124 msg = cur->branch; /* continue scan at younger sister */
5125 /* now delete this node */
5126 cur->branch = cur->next = NIL;
5127 mail_free_threadnode (&cur);
5129 else { /* current message not a dummy */
5130 msg->branch = cur; /* append as youngest daughter */
5131 msg = cur->branch; /* continue scan at younger sister */
5132 cur->branch = NIL; /* lose our younger sisters */
5135 else { /* no dummies, is current re/fwd, table not? */
5136 if (cur->sc->refwd && !lst->sc->refwd) {
5137 if (lst->next) { /* find youngest daughter of msg in table */
5138 for (msg = lst->next; msg->branch; msg = msg->branch);
5139 msg->branch = cur; /* append as youngest daughter */
5141 else lst->next = cur; /* no children, so make the eldest daughter */
5144 else { /* no re/fwd, create a new dummy */
5145 msg = mail_newthreadnode (NIL);
5146 if (lst == root) { /* msg in table is root? */
5147 root = lst->branch; /* younger sister becomes new root */
5148 /* no longer older sister either */
5149 if (lst == sis) sis = NIL;
5151 else { /* find older sister of msg in table */
5152 for (nxt = root; lst != nxt->branch; nxt = nxt->branch);
5153 /* remove from older sister */
5154 nxt->branch = lst->branch;
5156 msg->next = lst; /* msg in table becomes child */
5157 lst->branch = cur; /* current now little sister of msg in table */
5158 if (sis) { /* have an elder sister? */
5159 if (sis == lst) /* rescan if lost her */
5160 for (sis = root; cur != sis->branch; sis = sis->branch);
5161 sis->branch = msg; /* make dummy younger sister of big sister */
5163 else root = msg; /* otherwise this is the new root */
5164 sub[0] = sis = msg; /* set new msg in table and new big sister */
5166 msg = cur->branch; /* continue scan at younger sister */
5167 cur->branch = NIL; /* lose our younger sisters */
5169 if (sis) sis->branch = msg; /* older sister gets this as younger sister */
5170 else root = msg; /* otherwise this is the new root */
5172 hash_destroy (&ht); /* finished with hash table */
5173 /* Step 6 */
5174 /* sort threads */
5175 root = mail_thread_sort (root,tc);
5176 fs_give ((void **) &tc); /* finished with sort buffer */
5177 return root; /* return sorted list */
5180 /* Fetch overview callback to load sortcache for threading
5181 * Accepts: MAIL stream
5182 * UID of this message
5183 * overview of this message
5184 * msgno of this message
5187 void mail_thread_loadcache (MAILSTREAM *stream,unsigned long uid,OVERVIEW *ov,
5188 unsigned long msgno)
5190 if (msgno && ov) { /* just in case */
5191 MESSAGECACHE telt, *elt;
5192 ENVELOPE *env;
5193 SORTCACHE *s = (SORTCACHE *) (*mailcache) (stream,msgno,CH_SORTCACHE);
5194 if (!s->subject && ov->subject) {
5195 s->refwd = mail_strip_subject (ov->subject,&s->subject);
5196 s->dirty = T;
5198 if (!s->from && ov->from && ov->from->mailbox) {
5199 s->from = cpystr (ov->from->mailbox);
5200 s->dirty = T;
5202 if (!s->date && ov->date && mail_parse_date (&telt,ov->date)) {
5203 s->date = mail_longdate (&telt);
5204 s->dirty = T;
5206 if (!s->message_id && ov->message_id) {
5207 s->message_id = mail_thread_parse_msgid (ov->message_id,NIL);
5208 s->dirty = T;
5210 if (!s->references &&
5211 !(s->references = mail_thread_parse_references (ov->references,T))
5212 && stream->dtb && !strcmp(stream->dtb->name, "imap")
5213 && (elt = mail_elt (stream, msgno)) != NULL
5214 && (env = elt->private.msg.env) != NULL
5215 && env->in_reply_to
5216 && !(s->references = mail_thread_parse_references(env->in_reply_to, NIL))) {
5217 /* don't do In-Reply-To with NNTP mailboxes */
5218 s->references = mail_newstringlist ();
5219 s->dirty = T;
5221 if (!s->size && ov->optional.octets) {
5222 s->size = ov->optional.octets;
5223 s->dirty = T;
5228 /* Thread parse Message ID
5229 * Accepts: pointer to purported Message ID
5230 * pointer to return pointer
5231 * Returns: Message ID or NIL, return pointer updated
5234 char *mail_thread_parse_msgid (char *s,char **ss)
5236 char *ret = NIL;
5237 char *t = NIL;
5238 ADDRESS *adr;
5239 if (s) { /* only for non-NIL strings */
5240 rfc822_skipws (&s); /* skip whitespace */
5241 /* ignore phrases */
5242 if (((*s == '<') || (s = rfc822_parse_phrase (s))) &&
5243 (adr = rfc822_parse_routeaddr (s,&t,BADHOST))) {
5244 /* make return msgid */
5245 if (adr->mailbox && adr->host)
5246 sprintf (ret = (char *) fs_get (strlen (adr->mailbox) +
5247 strlen (adr->host) + 2),"%s@%s",
5248 adr->mailbox,adr->host);
5249 mail_free_address (&adr); /* don't need temporary address */
5252 if (ss) *ss = t; /* update return pointer */
5253 return ret;
5257 /* Thread parse references
5258 * Accepts: pointer to purported references
5259 * parse multiple references flag
5260 * Returns: references or NIL
5263 STRINGLIST *mail_thread_parse_references (char *s,long flag)
5265 char *t;
5266 STRINGLIST *ret = NIL;
5267 STRINGLIST *cur;
5268 /* found first reference? */
5269 if ((t = mail_thread_parse_msgid (s,&s)) != NULL) {
5270 (ret = mail_newstringlist ())->text.data = (unsigned char *) t;
5271 ret->text.size = strlen (t);
5272 if (flag) /* parse subsequent references */
5273 for (cur = ret; (t = mail_thread_parse_msgid (s,&s)) != NULL; cur = cur->next) {
5274 (cur->next = mail_newstringlist ())->text.data = (unsigned char *) t;
5275 cur->next->text.size = strlen (t);
5278 return ret;
5281 /* Prune dummy messages
5282 * Accepts: candidate container to prune
5283 * older sibling of container, if any
5284 * Returns: container in this position, possibly pruned
5285 * All children and younger siblings are also pruned
5288 container_t mail_thread_prune_dummy (container_t msg,container_t ane)
5290 /* prune container and children */
5291 container_t ret = msg ? mail_thread_prune_dummy_work (msg,ane) : NIL;
5292 /* prune all younger sisters */
5293 if (ret) for (ane = ret; ane && (msg = SIBLING (ane)); ane = msg)
5294 msg = mail_thread_prune_dummy_work (msg,ane);
5295 return ret;
5299 /* Prune dummy messages worker routine
5300 * Accepts: candidate container to prune
5301 * older sibling of container, if any
5302 * Returns: container in this position, possibly pruned
5303 * All children are also pruned
5306 container_t mail_thread_prune_dummy_work (container_t msg,container_t ane)
5308 container_t cur;
5309 /* get children, if any */
5310 container_t nxt = mail_thread_prune_dummy (CHILD (msg),NIL);
5311 /* just update children if container has msg */
5312 if (CACHE (msg)) SETCHILD (msg,nxt);
5313 else if (!nxt) { /* delete dummy with no children */
5314 nxt = SIBLING (msg); /* get younger sister */
5315 if (ane) SETSIBLING (ane,nxt);
5316 /* prune younger sister if exists */
5317 msg = nxt ? mail_thread_prune_dummy_work (nxt,ane) : NIL;
5319 /* not if parent root & multiple children */
5320 else if ((cur = PARENT (msg)) || !SIBLING (nxt)) {
5321 /* OK to promote, try younger sister of aunt */
5322 if (ane) SETSIBLING (ane,nxt);
5323 /* otherwise promote to child of grandmother */
5324 else if (cur) SETCHILD (cur,nxt);
5325 SETPARENT (nxt,cur); /* set parent as well */
5326 /* look for end of siblings in new container */
5327 for (cur = nxt; SIBLING (cur); cur = SIBLING (cur));
5328 /* reattach deleted container's siblings */
5329 SETSIBLING (cur,SIBLING (msg));
5330 /* prune and return new container */
5331 msg = mail_thread_prune_dummy_work (nxt,ane);
5333 else SETCHILD (msg,nxt); /* in case child pruned */
5334 return msg; /* return this message */
5337 /* Test that purported mother is not a child of purported daughter
5338 * Accepts: mother
5339 * purported daugher
5340 * Returns: T if circular parentage exists, else NIL
5343 long mail_thread_check_child (container_t mother,container_t daughter)
5345 if (mother) { /* only if mother non-NIL */
5346 if (mother == daughter) return T;
5347 for (daughter = CHILD (daughter); daughter; daughter = SIBLING (daughter))
5348 if (mail_thread_check_child (mother,daughter)) return T;
5350 return NIL;
5354 /* Generate threadnodes from containers
5355 * Accepts: Mail stream
5356 * container
5357 * flags
5358 * Return: threadnode list
5361 THREADNODE *mail_thread_c2node (MAILSTREAM *stream,container_t con,long flags)
5363 THREADNODE *ret,*cur;
5364 SORTCACHE *s;
5365 container_t nxt;
5366 /* for each container */
5367 for (ret = cur = NIL; con; con = SIBLING (con)) {
5368 s = CACHE (con); /* yes, get its sortcache */
5369 /* create node for it */
5370 if (ret) cur = cur->branch = mail_newthreadnode (s);
5371 else ret = cur = mail_newthreadnode (s);
5372 /* attach sequence or UID for non-dummy */
5373 if (s) cur->num = (flags & SE_UID) ? mail_uid (stream,s->num) : s->num;
5374 /* attach the children */
5375 if ((nxt = CHILD (con)) != NULL) cur->next = mail_thread_c2node (stream,nxt,flags);
5377 return ret;
5380 /* Sort thread tree by date
5381 * Accepts: thread tree to sort
5382 * qsort vector to sort
5383 * Returns: sorted thread tree
5386 THREADNODE *mail_thread_sort (THREADNODE *thr,THREADNODE **tc)
5388 unsigned long i,j;
5389 THREADNODE *cur;
5390 /* sort children of each thread */
5391 for (cur = thr; cur; cur = cur->branch)
5392 if (cur->next) cur->next = mail_thread_sort (cur->next,tc);
5393 /* Must do this in a separate pass since recursive call will clobber tc */
5394 /* load threadcache and count nodes to sort */
5395 for (i = 0, cur = thr; cur; cur = cur->branch) tc[i++] = cur;
5396 if (i > 1) { /* only if need to sort */
5397 qsort ((void *) tc,i,sizeof (THREADNODE *),mail_thread_compare_date);
5398 /* relink root siblings */
5399 for (j = 0, --i; j < i; j++) tc[j]->branch = tc[j+1];
5400 tc[j]->branch = NIL; /* end of root */
5402 return i ? tc[0] : NIL; /* return new head of list */
5406 /* Thread compare date
5407 * Accept: first message sort cache element
5408 * second message sort cache element
5409 * Returns: -1 if a1 < a2, 1 if a1 > a2
5411 * This assumes that a sort cache element is either a message (with a
5412 * sortcache entry) or a dummy with a message (with sortcache entry) child.
5413 * This is true of both the ORDEREDSUBJECT (no dummies) and REFERENCES
5414 * (dummies only at top-level, and with non-dummy children).
5416 * If a new algorithm allows a dummy parent to have a dummy child, this
5417 * routine must be changed if it is to be used by that algorithm.
5419 * Messages with bogus dates are always sorted at the top.
5422 int mail_thread_compare_date (const void *a1,const void *a2)
5424 THREADNODE *t1 = *(THREADNODE **) a1;
5425 THREADNODE *t2 = *(THREADNODE **) a2;
5426 SORTCACHE *s1 = t1->sc ? t1->sc : t1->next->sc;
5427 SORTCACHE *s2 = t2->sc ? t2->sc : t2->next->sc;
5428 int ret = compare_ulong (s1->date,s2->date);
5429 /* use number as final tie-breaker */
5430 return ret ? ret : compare_ulong (s1->num,s2->num);
5433 /* Mail parse sequence
5434 * Accepts: mail stream
5435 * sequence to parse
5436 * Returns: T if parse successful, else NIL
5439 long mail_sequence (MAILSTREAM *stream,unsigned char *sequence)
5441 unsigned long i,j,x;
5442 for (i = 1; i <= stream->nmsgs; i++) mail_elt (stream,i)->sequence = NIL;
5443 while (sequence && *sequence){/* while there is something to parse */
5444 if (*sequence == '*') { /* maximum message */
5445 if (stream->nmsgs) i = stream->nmsgs;
5446 else {
5447 MM_LOG ("No messages, so no maximum message number",ERROR);
5448 return NIL;
5450 sequence++; /* skip past * */
5452 /* parse and validate message number */
5453 else if (!isdigit (*sequence)) {
5454 MM_LOG ("Syntax error in sequence",ERROR);
5455 return NIL;
5457 else if (!(i = strtoul (sequence,(char **) &sequence,10)) ||
5458 (i > stream->nmsgs)) {
5459 MM_LOG ("Sequence out of range",ERROR);
5460 return NIL;
5462 switch (*sequence) { /* see what the delimiter is */
5463 case ':': /* sequence range */
5464 if (*++sequence == '*') { /* maximum message */
5465 if (stream->nmsgs) j = stream->nmsgs;
5466 else {
5467 MM_LOG ("No messages, so no maximum message number",ERROR);
5468 return NIL;
5470 sequence++; /* skip past * */
5472 /* parse end of range */
5473 else if (!(j = strtoul (sequence,(char **) &sequence,10)) ||
5474 (j > stream->nmsgs)) {
5475 MM_LOG ("Sequence range invalid",ERROR);
5476 return NIL;
5478 if (*sequence && *sequence++ != ',') {
5479 MM_LOG ("Sequence range syntax error",ERROR);
5480 return NIL;
5482 if (i > j) { /* swap the range if backwards */
5483 x = i; i = j; j = x;
5485 /* mark each item in the sequence */
5486 while (i <= j) mail_elt (stream,j--)->sequence = T;
5487 break;
5488 case ',': /* single message */
5489 ++sequence; /* skip the delimiter, fall into end case */
5490 case '\0': /* end of sequence, mark this message */
5491 mail_elt (stream,i)->sequence = T;
5492 break;
5493 default: /* anything else is a syntax error! */
5494 MM_LOG ("Sequence syntax error",ERROR);
5495 return NIL;
5498 return T; /* successfully parsed sequence */
5501 /* Parse flag list
5502 * Accepts: MAIL stream
5503 * flag list as a character string
5504 * pointer to user flags to return
5505 * Returns: system flags
5508 long mail_parse_flags (MAILSTREAM *stream,char *flag,unsigned long *uf)
5510 char *t,*n,*s,tmp[MAILTMPLEN],msg[MAILTMPLEN];
5511 short f = 0;
5512 long i,j;
5513 *uf = 0; /* initially no user flags */
5514 if (flag && *flag) { /* no-op if no flag string */
5515 /* check if a list and make sure valid */
5516 if (((i = (*flag == '(')) ^ (flag[strlen (flag)-1] == ')')) ||
5517 (strlen (flag) >= MAILTMPLEN)) {
5518 MM_LOG ("Bad flag list",ERROR);
5519 return NIL;
5521 /* copy the flag string w/o list construct */
5522 strncpy (n = tmp,flag+i,(j = strlen (flag) - (2*i)));
5523 tmp[j] = '\0';
5524 while ((t = n) && *t) { /* parse the flags */
5525 /* find end of flag */
5526 if ((n = strchr (t,' ')) != NULL) *n++ = '\0';
5527 if (*t == '\\') { /* system flag? */
5528 if (!compare_cstring (t+1,"SEEN")) f |= fSEEN;
5529 else if (!compare_cstring (t+1,"DELETED")) f |= fDELETED;
5530 else if (!compare_cstring (t+1,"FLAGGED")) f |= fFLAGGED;
5531 else if (!compare_cstring (t+1,"ANSWERED")) f |= fANSWERED;
5532 else if (!compare_cstring (t+1,"DRAFT")) f |= fDRAFT;
5533 else {
5534 sprintf (msg,"Unsupported system flag: %.80s",t);
5535 MM_LOG (msg,WARN);
5539 else { /* keyword flag */
5540 for (i = j = 0; /* user flag, search through table */
5541 !i && (j < NUSERFLAGS) && (s = stream->user_flags[j]); ++j)
5542 if (!compare_cstring (t,s)) *uf |= i = 1 << j;
5543 if (!i) { /* flag not found, can it be created? */
5544 if (stream->kwd_create && (j < NUSERFLAGS) && *t &&
5545 (strlen (t) <= MAXUSERFLAG)) {
5546 for (s = t; t && *s; s++) switch (*s) {
5547 default: /* all other characters */
5548 /* SPACE, CTL, or not CHAR */
5549 if ((*s > ' ') && (*s < 0x7f)) break;
5550 case '*': case '%': /* list_wildcards */
5551 case '"': case '\\':/* quoted-specials */
5552 /* atom_specials */
5553 case '(': case ')': case '{':
5554 case ']': /* resp-specials */
5555 sprintf (msg,"Invalid flag: %.80s",t);
5556 MM_LOG (msg,WARN);
5557 t = NIL;
5559 if (t) { /* only if valid */
5560 *uf |= 1 << j; /* set the bit */
5561 stream->user_flags[j] = cpystr (t);
5562 /* if out of user flags */
5563 if (j == NUSERFLAGS - 1) stream->kwd_create = NIL;
5566 else {
5567 if (*t) sprintf (msg,"Unknown flag: %.80s",t);
5568 else strcpy (msg,"Empty flag invalid");
5569 MM_LOG (msg,WARN);
5575 return f;
5578 /* Mail check network stream for usability with new name
5579 * Accepts: MAIL stream
5580 * candidate new name
5581 * Returns: T if stream can be used, NIL otherwise
5584 long mail_usable_network_stream (MAILSTREAM *stream,char *name)
5586 NETMBX smb,nmb,omb;
5587 char *s = NIL;
5588 long ret= (stream && stream->dtb && !(stream->dtb->flags & DR_LOCAL) &&
5589 mail_valid_net_parse (name,&nmb) &&
5590 mail_valid_net_parse (stream->mailbox,&smb) &&
5591 mail_valid_net_parse (stream->original_mailbox,&omb) &&
5592 ((!compare_cstring (smb.host,trustdns ?
5593 (s = tcp_canonical (nmb.host)) : nmb.host) &&
5594 !strcmp (smb.service,nmb.service) &&
5595 (!nmb.port || (smb.port == nmb.port)) &&
5596 (nmb.anoflag == stream->anonymous) &&
5597 (!nmb.user[0] || !strcmp (smb.user,nmb.user))) ||
5598 (!compare_cstring (omb.host,nmb.host) &&
5599 !strcmp (omb.service,nmb.service) &&
5600 (!nmb.port || (omb.port == nmb.port)) &&
5601 (nmb.anoflag == stream->anonymous) &&
5602 (!nmb.user[0] || !strcmp (omb.user,nmb.user))))) ? LONGT : NIL;
5603 if(s) fs_give((void **) &s);
5604 return ret;
5607 /* Mail data structure instantiation routines */
5610 /* Mail instantiate cache elt
5611 * Accepts: initial message number
5612 * Returns: new cache elt
5615 MESSAGECACHE *mail_new_cache_elt (unsigned long msgno)
5617 MESSAGECACHE *elt = (MESSAGECACHE *) memset (fs_get (sizeof (MESSAGECACHE)),
5618 0,sizeof (MESSAGECACHE));
5619 elt->lockcount = 1; /* initially only cache references it */
5620 elt->msgno = msgno; /* message number */
5621 return elt;
5625 /* Mail instantiate envelope
5626 * Returns: new envelope
5629 ENVELOPE *mail_newenvelope (void)
5631 return (ENVELOPE *) memset (fs_get (sizeof (ENVELOPE)),0,sizeof (ENVELOPE));
5635 /* Mail instantiate address
5636 * Returns: new address
5639 ADDRESS *mail_newaddr (void)
5641 return (ADDRESS *) memset (fs_get (sizeof (ADDRESS)),0,sizeof (ADDRESS));
5644 /* Mail instantiate body
5645 * Returns: new body
5648 BODY *mail_newbody (void)
5650 return mail_initbody ((BODY *) fs_get (sizeof (BODY)));
5654 /* Mail initialize body
5655 * Accepts: body
5656 * Returns: body
5659 BODY *mail_initbody (BODY *body)
5661 memset ((void *) body,0,sizeof (BODY));
5662 body->type = TYPETEXT; /* content type */
5663 body->encoding = ENC7BIT; /* content encoding */
5664 return body;
5668 /* Mail instantiate body parameter
5669 * Returns: new body part
5672 PARAMETER *mail_newbody_parameter (void)
5674 return (PARAMETER *) memset (fs_get (sizeof(PARAMETER)),0,sizeof(PARAMETER));
5678 /* Mail instantiate body part
5679 * Returns: new body part
5682 PART *mail_newbody_part (void)
5684 PART *part = (PART *) memset (fs_get (sizeof (PART)),0,sizeof (PART));
5685 mail_initbody (&part->body); /* initialize the body */
5686 return part;
5690 /* Mail instantiate body message part
5691 * Returns: new body message part
5694 MESSAGE *mail_newmsg (void)
5696 return (MESSAGE *) memset (fs_get (sizeof (MESSAGE)),0,sizeof (MESSAGE));
5699 /* Mail instantiate string list
5700 * Returns: new string list
5703 STRINGLIST *mail_newstringlist (void)
5705 return (STRINGLIST *) memset (fs_get (sizeof (STRINGLIST)),0,
5706 sizeof (STRINGLIST));
5710 /* Mail instantiate new search program
5711 * Returns: new search program
5714 SEARCHPGM *mail_newsearchpgm (void)
5716 return (SEARCHPGM *) memset (fs_get (sizeof(SEARCHPGM)),0,sizeof(SEARCHPGM));
5720 /* Mail instantiate new search program
5721 * Accepts: header line name
5722 * Returns: new search program
5725 SEARCHHEADER *mail_newsearchheader (char *line,char *text)
5727 SEARCHHEADER *hdr = (SEARCHHEADER *) memset (fs_get (sizeof (SEARCHHEADER)),
5728 0,sizeof (SEARCHHEADER));
5729 hdr->line.size = strlen ((char *) (hdr->line.data =
5730 (unsigned char *) cpystr (line)));
5731 hdr->text.size = strlen ((char *) (hdr->text.data =
5732 (unsigned char *) cpystr (text)));
5733 return hdr;
5737 /* Mail instantiate new search set
5738 * Returns: new search set
5741 SEARCHSET *mail_newsearchset (void)
5743 return (SEARCHSET *) memset (fs_get (sizeof(SEARCHSET)),0,sizeof(SEARCHSET));
5747 /* Mail instantiate new search or
5748 * Returns: new search or
5751 SEARCHOR *mail_newsearchor (void)
5753 SEARCHOR *or = (SEARCHOR *) memset (fs_get (sizeof (SEARCHOR)),0,
5754 sizeof (SEARCHOR));
5755 or->first = mail_newsearchpgm ();
5756 or->second = mail_newsearchpgm ();
5757 return or;
5760 /* Mail instantiate new searchpgmlist
5761 * Returns: new searchpgmlist
5764 SEARCHPGMLIST *mail_newsearchpgmlist (void)
5766 SEARCHPGMLIST *pgl = (SEARCHPGMLIST *)
5767 memset (fs_get (sizeof (SEARCHPGMLIST)),0,sizeof (SEARCHPGMLIST));
5768 pgl->pgm = mail_newsearchpgm ();
5769 return pgl;
5773 /* Mail instantiate new sortpgm
5774 * Returns: new sortpgm
5777 SORTPGM *mail_newsortpgm (void)
5779 return (SORTPGM *) memset (fs_get (sizeof (SORTPGM)),0,sizeof (SORTPGM));
5783 /* Mail instantiate new threadnode
5784 * Accepts: sort cache for thread node
5785 * Returns: new threadnode
5788 THREADNODE *mail_newthreadnode (SORTCACHE *sc)
5790 THREADNODE *thr = (THREADNODE *) memset (fs_get (sizeof (THREADNODE)),0,
5791 sizeof (THREADNODE));
5792 if (sc) thr->sc = sc; /* initialize sortcache */
5793 return thr;
5797 /* Mail instantiate new acllist
5798 * Returns: new acllist
5801 ACLLIST *mail_newacllist (void)
5803 return (ACLLIST *) memset (fs_get (sizeof (ACLLIST)),0,sizeof (ACLLIST));
5807 /* Mail instantiate new quotalist
5808 * Returns: new quotalist
5811 QUOTALIST *mail_newquotalist (void)
5813 return (QUOTALIST *) memset (fs_get (sizeof (QUOTALIST)),0,
5814 sizeof (QUOTALIST));
5817 /* Mail garbage collection routines */
5820 /* Mail garbage collect body
5821 * Accepts: pointer to body pointer
5824 void mail_free_body (BODY **body)
5826 if (*body) { /* only free if exists */
5827 mail_free_body_data (*body);/* free its data */
5828 fs_give ((void **) body); /* return body to free storage */
5833 /* Mail garbage collect body data
5834 * Accepts: body pointer
5837 void mail_free_body_data (BODY *body)
5839 switch (body->type) { /* free contents */
5840 case TYPEMULTIPART: /* multiple part */
5841 mail_free_body_part (&body->nested.part);
5842 break;
5843 case TYPEMESSAGE: /* encapsulated message */
5844 if (body->subtype && !strcmp (body->subtype,"RFC822")) {
5845 mail_free_stringlist (&body->nested.msg->lines);
5846 mail_gc_msg (body->nested.msg,GC_ENV | GC_TEXTS);
5848 if (body->nested.msg) fs_give ((void **) &body->nested.msg);
5849 break;
5850 default:
5851 break;
5853 if (body->subtype) fs_give ((void **) &body->subtype);
5854 mail_free_body_parameter (&body->parameter);
5855 if (body->id) fs_give ((void **) &body->id);
5856 if (body->description) fs_give ((void **) &body->description);
5857 if (body->disposition.type) fs_give ((void **) &body->disposition.type);
5858 if (body->disposition.parameter)
5859 mail_free_body_parameter (&body->disposition.parameter);
5860 if (body->language) mail_free_stringlist (&body->language);
5861 if (body->location) fs_give ((void **) &body->location);
5862 if (body->mime.text.data) fs_give ((void **) &body->mime.text.data);
5863 if (body->contents.text.data) fs_give ((void **) &body->contents.text.data);
5864 if (body->md5) fs_give ((void **) &body->md5);
5865 if (mailfreebodysparep && body->sparep)
5866 (*mailfreebodysparep) (&body->sparep);
5869 /* Mail garbage collect body parameter
5870 * Accepts: pointer to body parameter pointer
5873 void mail_free_body_parameter (PARAMETER **parameter)
5875 if (*parameter) { /* only free if exists */
5876 if ((*parameter)->attribute) fs_give ((void **) &(*parameter)->attribute);
5877 if ((*parameter)->value) fs_give ((void **) &(*parameter)->value);
5878 /* run down the list as necessary */
5879 mail_free_body_parameter (&(*parameter)->next);
5880 /* return body part to free storage */
5881 fs_give ((void **) parameter);
5886 /* Mail garbage collect body part
5887 * Accepts: pointer to body part pointer
5890 void mail_free_body_part (PART **part)
5892 if (*part) { /* only free if exists */
5893 mail_free_body_data (&(*part)->body);
5894 /* run down the list as necessary */
5895 mail_free_body_part (&(*part)->next);
5896 fs_give ((void **) part); /* return body part to free storage */
5900 /* Mail garbage collect message cache
5901 * Accepts: mail stream
5903 * The message cache is set to NIL when this function finishes.
5906 void mail_free_cache (MAILSTREAM *stream)
5908 /* do driver specific stuff first */
5909 mail_gc (stream,GC_ELT | GC_ENV | GC_TEXTS);
5910 /* flush the cache */
5911 (*mailcache) (stream,(long) 0,CH_INIT);
5915 /* Mail garbage collect cache element
5916 * Accepts: pointer to cache element pointer
5919 void mail_free_elt (MESSAGECACHE **elt)
5921 /* only free if exists and no sharers */
5922 if (*elt && !--(*elt)->lockcount) {
5923 mail_gc_msg (&(*elt)->private.msg,GC_ENV | GC_TEXTS);
5924 if (mailfreeeltsparep && (*elt)->sparep)
5925 (*mailfreeeltsparep) (&(*elt)->sparep);
5926 fs_give ((void **) elt);
5928 else *elt = NIL; /* else simply drop pointer */
5931 /* Mail garbage collect envelope
5932 * Accepts: pointer to envelope pointer
5935 void mail_free_envelope (ENVELOPE **env)
5937 if (*env) { /* only free if exists */
5938 if ((*env)->remail) fs_give ((void **) &(*env)->remail);
5939 mail_free_address (&(*env)->return_path);
5940 if ((*env)->date) fs_give ((void **) &(*env)->date);
5941 mail_free_address (&(*env)->from);
5942 mail_free_address (&(*env)->sender);
5943 mail_free_address (&(*env)->reply_to);
5944 if ((*env)->subject) fs_give ((void **) &(*env)->subject);
5945 mail_free_address (&(*env)->to);
5946 mail_free_address (&(*env)->cc);
5947 mail_free_address (&(*env)->bcc);
5948 if ((*env)->in_reply_to) fs_give ((void **) &(*env)->in_reply_to);
5949 if ((*env)->message_id) fs_give ((void **) &(*env)->message_id);
5950 if ((*env)->newsgroups) fs_give ((void **) &(*env)->newsgroups);
5951 if ((*env)->followup_to) fs_give ((void **) &(*env)->followup_to);
5952 if ((*env)->references) fs_give ((void **) &(*env)->references);
5953 if (mailfreeenvelopesparep && (*env)->sparep)
5954 (*mailfreeenvelopesparep) (&(*env)->sparep);
5955 fs_give ((void **) env); /* return envelope to free storage */
5960 /* Mail garbage collect address
5961 * Accepts: pointer to address pointer
5964 void mail_free_address (ADDRESS **address)
5966 if (*address) { /* only free if exists */
5967 if ((*address)->personal) fs_give ((void **) &(*address)->personal);
5968 if ((*address)->adl) fs_give ((void **) &(*address)->adl);
5969 if ((*address)->mailbox) fs_give ((void **) &(*address)->mailbox);
5970 if ((*address)->host) fs_give ((void **) &(*address)->host);
5971 if ((*address)->error) fs_give ((void **) &(*address)->error);
5972 if ((*address)->orcpt.type) fs_give ((void **) &(*address)->orcpt.type);
5973 if ((*address)->orcpt.addr) fs_give ((void **) &(*address)->orcpt.addr);
5974 mail_free_address (&(*address)->next);
5975 fs_give ((void **) address);/* return address to free storage */
5980 /* Mail garbage collect stringlist
5981 * Accepts: pointer to stringlist pointer
5984 void mail_free_stringlist (STRINGLIST **string)
5986 if (*string) { /* only free if exists */
5987 if ((*string)->text.data) fs_give ((void **) &(*string)->text.data);
5988 mail_free_stringlist (&(*string)->next);
5989 fs_give ((void **) string); /* return string to free storage */
5993 /* Mail garbage collect searchpgm
5994 * Accepts: pointer to searchpgm pointer
5997 void mail_free_searchpgm (SEARCHPGM **pgm)
5999 if (*pgm) { /* only free if exists */
6000 mail_free_searchset (&(*pgm)->msgno);
6001 mail_free_searchset (&(*pgm)->uid);
6002 mail_free_searchor (&(*pgm)->or);
6003 mail_free_searchpgmlist (&(*pgm)->not);
6004 mail_free_searchheader (&(*pgm)->header);
6005 mail_free_stringlist (&(*pgm)->bcc);
6006 mail_free_stringlist (&(*pgm)->body);
6007 mail_free_stringlist (&(*pgm)->cc);
6008 mail_free_stringlist (&(*pgm)->from);
6009 mail_free_stringlist (&(*pgm)->keyword);
6010 mail_free_stringlist (&(*pgm)->subject);
6011 mail_free_stringlist (&(*pgm)->text);
6012 mail_free_stringlist (&(*pgm)->to);
6013 mail_free_stringlist (&(*pgm)->x_gm_ext1);
6014 fs_give ((void **) pgm); /* return program to free storage */
6019 /* Mail garbage collect searchheader
6020 * Accepts: pointer to searchheader pointer
6023 void mail_free_searchheader (SEARCHHEADER **hdr)
6025 if (*hdr) { /* only free if exists */
6026 if ((*hdr)->line.data) fs_give ((void **) &(*hdr)->line.data);
6027 if ((*hdr)->text.data) fs_give ((void **) &(*hdr)->text.data);
6028 mail_free_searchheader (&(*hdr)->next);
6029 fs_give ((void **) hdr); /* return header to free storage */
6034 /* Mail garbage collect searchset
6035 * Accepts: pointer to searchset pointer
6038 void mail_free_searchset (SEARCHSET **set)
6040 if (*set) { /* only free if exists */
6041 mail_free_searchset (&(*set)->next);
6042 fs_give ((void **) set); /* return set to free storage */
6046 /* Mail garbage collect searchor
6047 * Accepts: pointer to searchor pointer
6050 void mail_free_searchor (SEARCHOR **orl)
6052 if (*orl) { /* only free if exists */
6053 mail_free_searchpgm (&(*orl)->first);
6054 mail_free_searchpgm (&(*orl)->second);
6055 mail_free_searchor (&(*orl)->next);
6056 fs_give ((void **) orl); /* return searchor to free storage */
6061 /* Mail garbage collect search program list
6062 * Accepts: pointer to searchpgmlist pointer
6065 void mail_free_searchpgmlist (SEARCHPGMLIST **pgl)
6067 if (*pgl) { /* only free if exists */
6068 mail_free_searchpgm (&(*pgl)->pgm);
6069 mail_free_searchpgmlist (&(*pgl)->next);
6070 fs_give ((void **) pgl); /* return searchpgmlist to free storage */
6075 /* Mail garbage collect namespace
6076 * Accepts: poiner to namespace
6079 void mail_free_namespace (NAMESPACE **n)
6081 if (*n) {
6082 fs_give ((void **) &(*n)->name);
6083 mail_free_namespace (&(*n)->next);
6084 mail_free_body_parameter (&(*n)->param);
6085 fs_give ((void **) n); /* return namespace to free storage */
6089 /* Mail garbage collect sort program
6090 * Accepts: pointer to sortpgm pointer
6093 void mail_free_sortpgm (SORTPGM **pgm)
6095 if (*pgm) { /* only free if exists */
6096 mail_free_sortpgm (&(*pgm)->next);
6097 fs_give ((void **) pgm); /* return sortpgm to free storage */
6102 /* Mail garbage collect thread node
6103 * Accepts: pointer to threadnode pointer
6106 void mail_free_threadnode (THREADNODE **thr)
6108 if (*thr) { /* only free if exists */
6109 mail_free_threadnode (&(*thr)->branch);
6110 mail_free_threadnode (&(*thr)->next);
6111 fs_give ((void **) thr); /* return threadnode to free storage */
6116 /* Mail garbage collect acllist
6117 * Accepts: pointer to acllist pointer
6120 void mail_free_acllist (ACLLIST **al)
6122 if (*al) { /* only free if exists */
6123 if ((*al)->identifier) fs_give ((void **) &(*al)->identifier);
6124 if ((*al)->rights) fs_give ((void **) &(*al)->rights);
6125 mail_free_acllist (&(*al)->next);
6126 fs_give ((void **) al); /* return acllist to free storage */
6131 /* Mail garbage collect quotalist
6132 * Accepts: pointer to quotalist pointer
6135 void mail_free_quotalist (QUOTALIST **ql)
6137 if (*ql) { /* only free if exists */
6138 if ((*ql)->name) fs_give ((void **) &(*ql)->name);
6139 mail_free_quotalist (&(*ql)->next);
6140 fs_give ((void **) ql); /* return quotalist to free storage */
6144 /* Link authenicator
6145 * Accepts: authenticator to add to list
6148 void auth_link (AUTHENTICATOR *auth)
6150 if (!auth->valid || (*auth->valid) ()) {
6151 AUTHENTICATOR **a = &mailauthenticators;
6152 while (*a) a = &(*a)->next; /* find end of list of authenticators */
6153 *a = auth; /* put authenticator at the end */
6154 auth->next = NIL; /* this authenticator is the end of the list */
6159 /* Authenticate access
6160 * Accepts: mechanism name
6161 * responder function
6162 * argument count
6163 * argument vector
6164 * Returns: authenticated user name or NIL
6167 char *mail_auth (char *mechanism,authresponse_t resp,int argc,char *argv[])
6169 AUTHENTICATOR *auth;
6170 for (auth = mailauthenticators; auth; auth = auth->next)
6171 if (auth->server && !compare_cstring (auth->name,mechanism))
6172 return (!(auth->flags & AU_DISABLE) &&
6173 ((auth->flags & AU_SECURE) ||
6174 !mail_parameters (NIL,GET_DISABLEPLAINTEXT,NIL))) ?
6175 (*auth->server) (resp,argc,argv) : NIL;
6176 return NIL; /* no authenticator found */
6179 /* Lookup authenticator index
6180 * Accepts: authenticator index
6181 * Returns: authenticator, or 0 if not found
6184 AUTHENTICATOR *mail_lookup_auth (unsigned long i)
6186 AUTHENTICATOR *auth = mailauthenticators;
6187 while (auth && --i) auth = auth->next;
6188 return auth;
6192 /* Lookup authenticator name
6193 * Accepts: authenticator name
6194 * required authenticator flags
6195 * Returns: index in authenticator chain, or 0 if not found
6198 unsigned int mail_lookup_auth_name (char *mechanism,long flags)
6200 int i;
6201 AUTHENTICATOR *auth;
6202 for (i = 1, auth = mailauthenticators; auth; i++, auth = auth->next)
6203 if (auth->client && !(flags & ~auth->flags) &&
6204 !(auth->flags & AU_DISABLE) && !compare_cstring (auth->name,mechanism))
6205 return i;
6206 return 0;
6209 /* Standard TCP/IP network driver */
6211 static NETDRIVER tcpdriver = {
6212 tcp_open, /* open connection */
6213 tcp_aopen, /* open preauthenticated connection */
6214 tcp_getline, /* get a line */
6215 tcp_getbuffer, /* get a buffer */
6216 tcp_soutr, /* output pushed data */
6217 tcp_sout, /* output string */
6218 tcp_close, /* close connection */
6219 tcp_host, /* return host name */
6220 tcp_remotehost, /* return remote host name */
6221 tcp_port, /* return port number */
6222 tcp_localhost, /* return local host name */
6223 tcp_getsize /* read a specific number of bytes */
6227 /* Network open
6228 * Accepts: NETMBX specifier to open
6229 * default network driver
6230 * default port
6231 * SSL driver
6232 * SSL service name
6233 * SSL driver port
6234 * Returns: Network stream if success, else NIL
6237 NETSTREAM *net_open (NETMBX *mb,NETDRIVER *dv,unsigned long port,
6238 NETDRIVER *ssld,char *ssls,unsigned long sslp)
6240 NETSTREAM *stream = NIL;
6241 char tmp[MAILTMPLEN];
6242 unsigned long flags = mb->novalidate ? NET_NOVALIDATECERT : 0;
6243 flags |= mb->tls1 ? NET_TRYTLS1
6244 : mb->tls1_1 ? NET_TRYTLS1_1
6245 : mb->tls1_2 ? NET_TRYTLS1_2
6246 : mb->tls1_3 ? NET_TRYTLS1_3 : 0;
6247 if (strlen (mb->host) >= NETMAXHOST) {
6248 sprintf (tmp,"Invalid host name: %.80s",mb->host);
6249 MM_LOG (tmp,ERROR);
6251 /* use designated driver if given */
6252 else if (dv) stream = net_open_work (dv,mb->host,mb->service,port,mb->port,
6253 flags);
6254 else if (mb->sslflag && ssld) /* use ssl if sslflag lit */
6255 stream = net_open_work (ssld,mb->host,ssls,sslp,mb->port,flags);
6256 /* if trysslfirst and can open ssl... */
6257 else if ((mb->trysslflag || trysslfirst) && ssld &&
6258 (stream = net_open_work (ssld,mb->host,ssls,sslp,mb->port,
6259 flags | NET_SILENT | NET_TRYSSL))) {
6260 if (net_sout (stream,"",0)) mb->sslflag = T;
6261 else {
6262 net_close (stream); /* flush fake SSL stream */
6263 stream = NIL;
6266 /* default to TCP driver */
6267 else stream = net_open_work (&tcpdriver,mb->host,mb->service,port,mb->port,
6268 flags);
6269 return stream;
6272 /* Network open worker routine
6273 * Accepts: network driver
6274 * host name
6275 * service name to look up port
6276 * port number if service name not found
6277 * port number to override service name
6278 * flags (passed on top of port)
6279 * Returns: Network stream if success, else NIL
6282 NETSTREAM *net_open_work (NETDRIVER *dv,char *host,char *service,
6283 unsigned long port,unsigned long portoverride,
6284 unsigned long flags)
6286 NETSTREAM *stream = NIL;
6287 void *tstream;
6288 if (service && (*service == '*')) {
6289 flags |= NET_NOOPENTIMEOUT; /* mark that no timeout is desired */
6290 ++service; /* no longer need the no timeout indicator */
6292 if (portoverride) { /* explicit port number? */
6293 service = NIL; /* yes, override service name */
6294 port = portoverride; /* use that instead of default port */
6296 if ((tstream = (*dv->open) (host,service,port | flags)) != NULL){
6297 stream = (NETSTREAM *) fs_get (sizeof (NETSTREAM));
6298 stream->stream = tstream;
6299 stream->dtb = dv;
6301 return stream;
6305 /* Network authenticated open
6306 * Accepts: network driver
6307 * NETMBX specifier
6308 * service specifier
6309 * return user name buffer
6310 * Returns: Network stream if success else NIL
6313 NETSTREAM *net_aopen (NETDRIVER *dv,NETMBX *mb,char *service,char *user)
6315 NETSTREAM *stream = NIL;
6316 void *tstream;
6317 if (!dv) dv = &tcpdriver; /* default to TCP driver */
6318 if ((tstream = (*dv->aopen) (mb,service,user)) != NULL) {
6319 stream = (NETSTREAM *) fs_get (sizeof (NETSTREAM));
6320 stream->stream = tstream;
6321 stream->dtb = dv;
6323 return stream;
6326 /* Network receive line
6327 * Accepts: Network stream
6328 * Returns: text line string or NIL if failure
6331 char *net_getline (NETSTREAM *stream)
6333 return (*stream->dtb->getline) (stream->stream);
6337 char *net_getsize (NETSTREAM *stream, unsigned long size)
6339 return (*stream->dtb->getsize) (stream->stream, size);
6344 /* Network receive buffer
6345 * Accepts: Network stream (must be void * for use as readfn_t)
6346 * size in bytes
6347 * buffer to read into
6348 * Returns: T if success, NIL otherwise
6351 long net_getbuffer (void *st,unsigned long size,char *buffer)
6353 NETSTREAM *stream = (NETSTREAM *) st;
6354 return (*stream->dtb->getbuffer) (stream->stream,size,buffer);
6358 /* Network send null-terminated string
6359 * Accepts: Network stream
6360 * string pointer
6361 * Returns: T if success else NIL
6364 long net_soutr (NETSTREAM *stream,char *string)
6366 return (*stream->dtb->soutr) (stream->stream,string);
6370 /* Network send string
6371 * Accepts: Network stream
6372 * string pointer
6373 * byte count
6374 * Returns: T if success else NIL
6377 long net_sout (NETSTREAM *stream,char *string,unsigned long size)
6379 return (*stream->dtb->sout) (stream->stream,string,size);
6382 /* Network close
6383 * Accepts: Network stream
6386 void net_close (NETSTREAM *stream)
6388 if (stream->stream) (*stream->dtb->close) (stream->stream);
6389 fs_give ((void **) &stream);
6393 /* Network get host name
6394 * Accepts: Network stream
6395 * Returns: host name for this stream
6398 char *net_host (NETSTREAM *stream)
6400 return (*stream->dtb->host) (stream->stream);
6404 /* Network get remote host name
6405 * Accepts: Network stream
6406 * Returns: host name for this stream
6409 char *net_remotehost (NETSTREAM *stream)
6411 return (*stream->dtb->remotehost) (stream->stream);
6414 /* Network return port for this stream
6415 * Accepts: Network stream
6416 * Returns: port number for this stream
6419 unsigned long net_port (NETSTREAM *stream)
6421 return (*stream->dtb->port) (stream->stream);
6425 /* Network get local host name
6426 * Accepts: Network stream
6427 * Returns: local host name
6430 char *net_localhost (NETSTREAM *stream)
6432 return (*stream->dtb->localhost) (stream->stream);
6435 void free_c_client_module_globals(void)
6437 env_end();
6438 tcp_end();