imapext-2007

view src/c-client/mail.c @ 1:28a55bc1110c

[mq]: imapext
author yuuji@gentei.org
date Mon, 14 Sep 2009 19:23:11 +0900
parents ada5e610ab86
children 2366b362676d
line source
1 /* ========================================================================
2 * Copyright 1988-2008 University of Washington
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 *
11 * ========================================================================
12 */
14 /*
15 * Program: Mailbox Access routines
16 *
17 * Author: Mark Crispin
18 * UW Technology
19 * University of Washington
20 * Seattle, WA 98195
21 * Internet: MRC@Washington.EDU
22 *
23 * Date: 22 November 1989
24 * Last Edited: 15 April 2008
25 */
28 #include <ctype.h>
29 #include <stdio.h>
30 #include <time.h>
31 #include "c-client.h"
33 char *UW_copyright = "Copyright 1988-2007 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";
35 /* c-client global data */
37 /* version of this library */
38 static char *mailcclientversion = CCLIENTVERSION;
39 /* list of mail drivers */
40 static DRIVER *maildrivers = NIL;
41 /* list of authenticators */
42 static AUTHENTICATOR *mailauthenticators = NIL;
43 /* SSL driver pointer */
44 static NETDRIVER *mailssldriver = NIL;
45 /* pointer to alternate gets function */
46 static mailgets_t mailgets = NIL;
47 /* pointer to read progress function */
48 static readprogress_t mailreadprogress = NIL;
49 /* mail cache manipulation function */
50 static mailcache_t mailcache = mm_cache;
51 /* RFC-822 output generator */
52 static rfc822out_t mail822out = NIL;
53 /* RFC-822 output generator (new style) */
54 static rfc822outfull_t mail822outfull = NIL;
55 /* SMTP verbose callback */
56 static smtpverbose_t mailsmtpverbose = mm_dlog;
57 /* proxy copy routine */
58 static mailproxycopy_t mailproxycopy = NIL;
59 /* RFC-822 external line parse */
60 static parseline_t mailparseline = NIL;
61 /* RFC-822 external phrase parser */
62 static parsephrase_t mailparsephrase = NIL;
63 static kinit_t mailkinit = NIL; /* application kinit callback */
64 /* note network sent command */
65 static sendcommand_t mailsendcommand = NIL;
66 /* newsrc file name decision function */
67 static newsrcquery_t mailnewsrcquery = NIL;
68 /* ACL results callback */
69 static getacl_t mailaclresults = NIL;
70 /* list rights results callback */
71 static listrights_t maillistrightsresults = NIL;
72 /* my rights results callback */
73 static myrights_t mailmyrightsresults = NIL;
74 /* quota results callback */
75 static quota_t mailquotaresults = NIL;
76 /* quota root results callback */
77 static quotaroot_t mailquotarootresults = NIL;
78 /* sorted results callback */
79 static sortresults_t mailsortresults = NIL;
80 /* threaded results callback */
81 static threadresults_t mailthreadresults = NIL;
82 /* COPY UID results */
83 static copyuid_t mailcopyuid = NIL;
84 /* APPEND UID results */
85 static appenduid_t mailappenduid = NIL;
86 /* free elt extra stuff callback */
87 static freeeltsparep_t mailfreeeltsparep = NIL;
88 /* free envelope extra stuff callback */
89 static freeenvelopesparep_t mailfreeenvelopesparep = NIL;
90 /* free body extra stuff callback */
91 static freebodysparep_t mailfreebodysparep = NIL;
92 /* free stream extra stuff callback */
93 static freestreamsparep_t mailfreestreamsparep = NIL;
94 /* SSL start routine */
95 static sslstart_t mailsslstart = NIL;
96 /* SSL certificate query */
97 static sslcertificatequery_t mailsslcertificatequery = NIL;
98 /* SSL client certificate */
99 static sslclientcert_t mailsslclientcert = NIL;
100 /* SSL client private key */
101 static sslclientkey_t mailsslclientkey = NIL;
102 /* SSL failure notify */
103 static sslfailure_t mailsslfailure = NIL;
104 /* snarf interval */
105 static long mailsnarfinterval = 60;
106 /* snarf preservation */
107 static long mailsnarfpreserve = NIL;
108 /* newsrc name uses canonical host */
109 static long mailnewsrccanon = LONGT;
111 /* supported threaders */
112 static THREADER mailthreadordsub = {
113 "ORDEREDSUBJECT",mail_thread_orderedsubject,NIL
114 };
115 static THREADER mailthreadlist = {
116 "REFERENCES",mail_thread_references,&mailthreadordsub
117 };
119 /* server name */
120 static char *servicename = "unknown";
121 /* server externally-set authentication ID */
122 static char *externalauthid = NIL;
123 static int expungeatping = T; /* mail_ping() may call mm_expunged() */
124 static int trysslfirst = NIL; /* always try SSL first */
125 static int notimezones = NIL; /* write timezones in "From " header */
126 static int trustdns = T; /* do DNS canonicalization */
127 static int saslusesptrname = T; /* SASL uses name from DNS PTR lookup */
128 /* trustdns also must be set */
129 static int debugsensitive = NIL;/* debug telemetry includes sensitive data */
131 /* Default mail cache handler
132 * Accepts: pointer to cache handle
133 * message number
134 * caching function
135 * Returns: cache data
136 */
138 void *mm_cache (MAILSTREAM *stream,unsigned long msgno,long op)
139 {
140 size_t n;
141 void *ret = NIL;
142 unsigned long i;
143 switch ((int) op) { /* what function? */
144 case CH_INIT: /* initialize cache */
145 if (stream->cache) { /* flush old cache contents */
146 while (stream->cachesize) {
147 mm_cache (stream,stream->cachesize,CH_FREE);
148 mm_cache (stream,stream->cachesize--,CH_FREESORTCACHE);
149 }
150 fs_give ((void **) &stream->cache);
151 fs_give ((void **) &stream->sc);
152 stream->nmsgs = 0; /* can't have any messages now */
153 }
154 break;
155 case CH_SIZE: /* (re-)size the cache */
156 if (!stream->cache) { /* have a cache already? */
157 /* no, create new cache */
158 n = (stream->cachesize = msgno + CACHEINCREMENT) * sizeof (void *);
159 stream->cache = (MESSAGECACHE **) memset (fs_get (n),0,n);
160 stream->sc = (SORTCACHE **) memset (fs_get (n),0,n);
161 }
162 /* is existing cache size large neough */
163 else if (msgno > stream->cachesize) {
164 i = stream->cachesize; /* remember old size */
165 n = (stream->cachesize = msgno + CACHEINCREMENT) * sizeof (void *);
166 fs_resize ((void **) &stream->cache,n);
167 fs_resize ((void **) &stream->sc,n);
168 while (i < stream->cachesize) {
169 stream->cache[i] = NIL;
170 stream->sc[i++] = NIL;
171 }
172 }
173 break;
175 case CH_MAKEELT: /* return elt, make if necessary */
176 if (!stream->cache[msgno - 1])
177 stream->cache[msgno - 1] = mail_new_cache_elt (msgno);
178 /* falls through */
179 case CH_ELT: /* return elt */
180 ret = (void *) stream->cache[msgno - 1];
181 break;
182 case CH_SORTCACHE: /* return sortcache entry, make if needed */
183 if (!stream->sc[msgno - 1]) stream->sc[msgno - 1] =
184 (SORTCACHE *) memset (fs_get (sizeof (SORTCACHE)),0,sizeof (SORTCACHE));
185 ret = (void *) stream->sc[msgno - 1];
186 break;
187 case CH_FREE: /* free elt */
188 mail_free_elt (&stream->cache[msgno - 1]);
189 break;
190 case CH_FREESORTCACHE:
191 if (stream->sc[msgno - 1]) {
192 if (stream->sc[msgno - 1]->from)
193 fs_give ((void **) &stream->sc[msgno - 1]->from);
194 if (stream->sc[msgno - 1]->to)
195 fs_give ((void **) &stream->sc[msgno - 1]->to);
196 if (stream->sc[msgno - 1]->cc)
197 fs_give ((void **) &stream->sc[msgno - 1]->cc);
198 if (stream->sc[msgno - 1]->subject)
199 fs_give ((void **) &stream->sc[msgno - 1]->subject);
200 if (stream->sc[msgno - 1]->unique &&
201 (stream->sc[msgno - 1]->unique != stream->sc[msgno - 1]->message_id))
202 fs_give ((void **) &stream->sc[msgno - 1]->unique);
203 if (stream->sc[msgno - 1]->message_id)
204 fs_give ((void **) &stream->sc[msgno - 1]->message_id);
205 if (stream->sc[msgno - 1]->references)
206 mail_free_stringlist (&stream->sc[msgno - 1]->references);
207 fs_give ((void **) &stream->sc[msgno - 1]);
208 }
209 break;
210 case CH_EXPUNGE: /* expunge cache slot */
211 for (i = msgno - 1; msgno < stream->nmsgs; i++,msgno++) {
212 if (stream->cache[i] = stream->cache[msgno])
213 stream->cache[i]->msgno = msgno;
214 stream->sc[i] = stream->sc[msgno];
215 }
216 stream->cache[i] = NIL; /* top of cache goes away */
217 stream->sc[i] = NIL;
218 break;
219 default:
220 fatal ("Bad mm_cache op");
221 break;
222 }
223 return ret;
224 }
226 /* Dummy string driver for complete in-memory strings */
228 static void mail_string_init (STRING *s,void *data,unsigned long size);
229 static char mail_string_next (STRING *s);
230 static void mail_string_setpos (STRING *s,unsigned long i);
232 STRINGDRIVER mail_string = {
233 mail_string_init, /* initialize string structure */
234 mail_string_next, /* get next byte in string structure */
235 mail_string_setpos /* set position in string structure */
236 };
239 /* Initialize mail string structure for in-memory string
240 * Accepts: string structure
241 * pointer to string
242 * size of string
243 */
245 static void mail_string_init (STRING *s,void *data,unsigned long size)
246 {
247 /* set initial string pointers */
248 s->chunk = s->curpos = (char *) (s->data = data);
249 /* and sizes */
250 s->size = s->chunksize = s->cursize = size;
251 s->data1 = s->offset = 0; /* never any offset */
252 }
255 /* Get next character from string
256 * Accepts: string structure
257 * Returns: character, string structure chunk refreshed
258 */
260 static char mail_string_next (STRING *s)
261 {
262 return *s->curpos++; /* return the last byte */
263 }
266 /* Set string pointer position
267 * Accepts: string structure
268 * new position
269 */
271 static void mail_string_setpos (STRING *s,unsigned long i)
272 {
273 s->curpos = s->chunk + i; /* set new position */
274 s->cursize = s->chunksize - i;/* and new size */
275 }
277 /* Mail routines
278 *
279 * mail_xxx routines are the interface between this module and the outside
280 * world. Only these routines should be referenced by external callers.
281 *
282 * Note that there is an important difference between a "sequence" and a
283 * "message #" (msgno). A sequence is a string representing a sequence in
284 * {"n", "n:m", or combination separated by commas} format, whereas a msgno
285 * is a single integer.
286 *
287 */
289 /* Mail version check
290 * Accepts: version
291 */
293 void mail_versioncheck (char *version)
294 {
295 /* attempt to protect again wrong .h */
296 if (strcmp (version,mailcclientversion)) {
297 char tmp[MAILTMPLEN];
298 sprintf (tmp,"c-client library version skew, app=%.100s library=%.100s",
299 version,mailcclientversion);
300 fatal (tmp);
301 }
302 }
305 /* Mail link driver
306 * Accepts: driver to add to list
307 */
309 void mail_link (DRIVER *driver)
310 {
311 DRIVER **d = &maildrivers;
312 while (*d) d = &(*d)->next; /* find end of list of drivers */
313 *d = driver; /* put driver at the end */
314 driver->next = NIL; /* this driver is the end of the list */
315 }
317 /* Mail manipulate driver parameters
318 * Accepts: mail stream
319 * function code
320 * function-dependent value
321 * Returns: function-dependent return value
322 */
324 void *mail_parameters (MAILSTREAM *stream,long function,void *value)
325 {
326 void *r,*ret = NIL;
327 DRIVER *d;
328 AUTHENTICATOR *a;
329 switch ((int) function) {
330 case SET_INBOXPATH:
331 fatal ("SET_INBOXPATH not permitted");
332 case GET_INBOXPATH:
333 if ((stream || (stream = mail_open (NIL,"INBOX",OP_PROTOTYPE))) &&
334 stream->dtb) ret = (*stream->dtb->parameters) (function,value);
335 break;
336 case SET_THREADERS:
337 fatal ("SET_THREADERS not permitted");
338 case GET_THREADERS: /* use stream dtb instead of global */
339 ret = (stream && stream->dtb) ?
340 /* KLUDGE ALERT: note stream passed as value */
341 (*stream->dtb->parameters) (function,stream) : (void *) &mailthreadlist;
342 break;
343 case SET_NAMESPACE:
344 fatal ("SET_NAMESPACE not permitted");
345 break;
346 case SET_NEWSRC: /* too late on open stream */
347 if (stream && stream->dtb && (stream != ((*stream->dtb->open) (NIL))))
348 fatal ("SET_NEWSRC not permitted");
349 else ret = env_parameters (function,value);
350 break;
351 case GET_NAMESPACE:
352 case GET_NEWSRC: /* use stream dtb instead of environment */
353 ret = (stream && stream->dtb) ?
354 /* KLUDGE ALERT: note stream passed as value */
355 (*stream->dtb->parameters) (function,stream) :
356 env_parameters (function,value);
357 break;
358 case ENABLE_DEBUG:
359 fatal ("ENABLE_DEBUG not permitted");
360 case DISABLE_DEBUG:
361 fatal ("DISABLE_DEBUG not permitted");
362 case SET_DIRFMTTEST:
363 fatal ("SET_DIRFMTTEST not permitted");
364 case GET_DIRFMTTEST:
365 if (!(stream && stream->dtb &&
366 (ret = (*stream->dtb->parameters) (function,NIL))))
367 fatal ("GET_DIRFMTTEST not permitted");
368 break;
370 case SET_DRIVERS:
371 fatal ("SET_DRIVERS not permitted");
372 case GET_DRIVERS: /* always return global */
373 ret = (void *) maildrivers;
374 break;
375 case SET_DRIVER:
376 fatal ("SET_DRIVER not permitted");
377 case GET_DRIVER:
378 for (d = maildrivers; d && compare_cstring (d->name,(char *) value);
379 d = d->next);
380 ret = (void *) d;
381 break;
382 case ENABLE_DRIVER:
383 for (d = maildrivers; d && compare_cstring (d->name,(char *) value);
384 d = d->next);
385 if (ret = (void *) d) d->flags &= ~DR_DISABLE;
386 break;
387 case DISABLE_DRIVER:
388 for (d = maildrivers; d && compare_cstring (d->name,(char *) value);
389 d = d->next);
390 if (ret = (void *) d) d->flags |= DR_DISABLE;
391 break;
392 case ENABLE_AUTHENTICATOR:
393 for (a = mailauthenticators;/* scan authenticators */
394 a && compare_cstring (a->name,(char *) value); a = a->next);
395 if (ret = (void *) a) a->flags &= ~AU_DISABLE;
396 break;
397 case DISABLE_AUTHENTICATOR:
398 for (a = mailauthenticators;/* scan authenticators */
399 a && compare_cstring (a->name,(char *) value); a = a->next);
400 if (ret = (void *) a) a->flags |= AU_DISABLE;
401 break;
402 case UNHIDE_AUTHENTICATOR:
403 for (a = mailauthenticators;/* scan authenticators */
404 a && compare_cstring (a->name,(char *) value); a = a->next);
405 if (ret = (void *) a) a->flags &= ~AU_HIDE;
406 break;
407 case HIDE_AUTHENTICATOR:
408 for (a = mailauthenticators;/* scan authenticators */
409 a && compare_cstring (a->name,(char *) value); a = a->next);
410 if (ret = (void *) a) a->flags |= AU_HIDE;
411 break;
412 case SET_EXTERNALAUTHID:
413 if (value) { /* setting external authentication ID */
414 externalauthid = cpystr ((char *) value);
415 mail_parameters (NIL,UNHIDE_AUTHENTICATOR,"EXTERNAL");
416 }
417 else { /* clearing external authentication ID */
418 if (externalauthid) fs_give ((void **) &externalauthid);
419 mail_parameters (NIL,HIDE_AUTHENTICATOR,"EXTERNAL");
420 }
421 case GET_EXTERNALAUTHID:
422 ret = (void *) externalauthid;
423 break;
425 case SET_GETS:
426 mailgets = (mailgets_t) value;
427 case GET_GETS:
428 ret = (void *) mailgets;
429 break;
430 case SET_READPROGRESS:
431 mailreadprogress = (readprogress_t) value;
432 case GET_READPROGRESS:
433 ret = (void *) mailreadprogress;
434 break;
435 case SET_CACHE:
436 mailcache = (mailcache_t) value;
437 case GET_CACHE:
438 ret = (void *) mailcache;
439 break;
440 case SET_RFC822OUTPUT:
441 mail822out = (rfc822out_t) value;
442 case GET_RFC822OUTPUT:
443 ret = (void *) mail822out;
444 break;
445 case SET_RFC822OUTPUTFULL:
446 mail822outfull = (rfc822outfull_t) value;
447 case GET_RFC822OUTPUTFULL:
448 ret = (void *) mail822outfull;
449 break;
450 case SET_SMTPVERBOSE:
451 mailsmtpverbose = (smtpverbose_t) value;
452 case GET_SMTPVERBOSE:
453 ret = (void *) mailsmtpverbose;
454 break;
455 case SET_MAILPROXYCOPY:
456 mailproxycopy = (mailproxycopy_t) value;
457 case GET_MAILPROXYCOPY:
458 ret = (void *) mailproxycopy;
459 break;
460 case SET_PARSELINE:
461 mailparseline = (parseline_t) value;
462 case GET_PARSELINE:
463 ret = (void *) mailparseline;
464 break;
465 case SET_PARSEPHRASE:
466 mailparsephrase = (parsephrase_t) value;
467 case GET_PARSEPHRASE:
468 ret = (void *) mailparsephrase;
469 break;
470 case SET_NEWSRCQUERY:
471 mailnewsrcquery = (newsrcquery_t) value;
472 case GET_NEWSRCQUERY:
473 ret = (void *) mailnewsrcquery;
474 break;
475 case SET_NEWSRCCANONHOST:
476 mailnewsrccanon = (long) value;
477 case GET_NEWSRCCANONHOST:
478 ret = (void *) mailnewsrccanon;
479 break;
481 case SET_COPYUID:
482 mailcopyuid = (copyuid_t) value;
483 case GET_COPYUID:
484 ret = (void *) mailcopyuid;
485 break;
486 case SET_APPENDUID:
487 mailappenduid = (appenduid_t) value;
488 case GET_APPENDUID:
489 ret = (void *) mailappenduid;
490 break;
491 case SET_FREEENVELOPESPAREP:
492 mailfreeenvelopesparep = (freeenvelopesparep_t) value;
493 case GET_FREEENVELOPESPAREP:
494 ret = (void *) mailfreeenvelopesparep;
495 break;
496 case SET_FREEELTSPAREP:
497 mailfreeeltsparep = (freeeltsparep_t) value;
498 case GET_FREEELTSPAREP:
499 ret = (void *) mailfreeeltsparep;
500 break;
501 case SET_FREESTREAMSPAREP:
502 mailfreestreamsparep = (freestreamsparep_t) value;
503 case GET_FREESTREAMSPAREP:
504 ret = (void *) mailfreestreamsparep;
505 break;
506 case SET_FREEBODYSPAREP:
507 mailfreebodysparep = (freebodysparep_t) value;
508 case GET_FREEBODYSPAREP:
509 ret = (void *) mailfreebodysparep;
510 break;
512 case SET_SSLSTART:
513 mailsslstart = (sslstart_t) value;
514 case GET_SSLSTART:
515 ret = (void *) mailsslstart;
516 break;
517 case SET_SSLCERTIFICATEQUERY:
518 mailsslcertificatequery = (sslcertificatequery_t) value;
519 case GET_SSLCERTIFICATEQUERY:
520 ret = (void *) mailsslcertificatequery;
521 break;
522 case SET_SSLCLIENTCERT:
523 mailsslclientcert = (sslclientcert_t) value;
524 case GET_SSLCLIENTCERT:
525 ret = (void *) mailsslclientcert;
526 break;
527 case SET_SSLCLIENTKEY:
528 mailsslclientkey = (sslclientkey_t) value;
529 case GET_SSLCLIENTKEY:
530 ret = (void *) mailsslclientkey;
531 break;
532 case SET_SSLFAILURE:
533 mailsslfailure = (sslfailure_t) value;
534 case GET_SSLFAILURE:
535 ret = (void *) mailsslfailure;
536 break;
537 case SET_KINIT:
538 mailkinit = (kinit_t) value;
539 case GET_KINIT:
540 ret = (void *) mailkinit;
541 break;
542 case SET_SENDCOMMAND:
543 mailsendcommand = (sendcommand_t) value;
544 case GET_SENDCOMMAND:
545 ret = (void *) mailsendcommand;
546 break;
548 case SET_SERVICENAME:
549 servicename = (char *) value;
550 case GET_SERVICENAME:
551 ret = (void *) servicename;
552 break;
553 case SET_EXPUNGEATPING:
554 expungeatping = (value ? T : NIL);
555 case GET_EXPUNGEATPING:
556 ret = (void *) (expungeatping ? VOIDT : NIL);
557 break;
558 case SET_SORTRESULTS:
559 mailsortresults = (sortresults_t) value;
560 case GET_SORTRESULTS:
561 ret = (void *) mailsortresults;
562 break;
563 case SET_THREADRESULTS:
564 mailthreadresults = (threadresults_t) value;
565 case GET_THREADRESULTS:
566 ret = (void *) mailthreadresults;
567 break;
568 case SET_SSLDRIVER:
569 mailssldriver = (NETDRIVER *) value;
570 case GET_SSLDRIVER:
571 ret = (void *) mailssldriver;
572 break;
573 case SET_TRYSSLFIRST:
574 trysslfirst = (value ? T : NIL);
575 case GET_TRYSSLFIRST:
576 ret = (void *) (trysslfirst ? VOIDT : NIL);
577 break;
578 case SET_NOTIMEZONES:
579 notimezones = (value ? T : NIL);
580 case GET_NOTIMEZONES:
581 ret = (void *) (notimezones ? VOIDT : NIL);
582 break;
583 case SET_TRUSTDNS:
584 trustdns = (value ? T : NIL);
585 case GET_TRUSTDNS:
586 ret = (void *) (trustdns ? VOIDT : NIL);
587 break;
588 case SET_SASLUSESPTRNAME:
589 saslusesptrname = (value ? T : NIL);
590 case GET_SASLUSESPTRNAME:
591 ret = (void *) (saslusesptrname ? VOIDT : NIL);
592 break;
593 case SET_DEBUGSENSITIVE:
594 debugsensitive = (value ? T : NIL);
595 case GET_DEBUGSENSITIVE:
596 ret = (void *) (debugsensitive ? VOIDT : NIL);
597 break;
599 case SET_ACL:
600 mailaclresults = (getacl_t) value;
601 case GET_ACL:
602 ret = (void *) mailaclresults;
603 break;
604 case SET_LISTRIGHTS:
605 maillistrightsresults = (listrights_t) value;
606 case GET_LISTRIGHTS:
607 ret = (void *) maillistrightsresults;
608 break;
609 case SET_MYRIGHTS:
610 mailmyrightsresults = (myrights_t) value;
611 case GET_MYRIGHTS:
612 ret = (void *) mailmyrightsresults;
613 break;
614 case SET_QUOTA:
615 mailquotaresults = (quota_t) value;
616 case GET_QUOTA:
617 ret = (void *) mailquotaresults;
618 break;
619 case SET_QUOTAROOT:
620 mailquotarootresults = (quotaroot_t) value;
621 case GET_QUOTAROOT:
622 ret = (void *) mailquotarootresults;
623 break;
624 case SET_SNARFINTERVAL:
625 mailsnarfinterval = (long) value;
626 case GET_SNARFINTERVAL:
627 ret = (void *) mailsnarfinterval;
628 break;
629 case SET_SNARFPRESERVE:
630 mailsnarfpreserve = (long) value;
631 case GET_SNARFPRESERVE:
632 ret = (void *) mailsnarfpreserve;
633 break;
634 case SET_SNARFMAILBOXNAME:
635 if (stream) { /* have a stream? */
636 if (stream->snarf.name) fs_give ((void **) &stream->snarf.name);
637 stream->snarf.name = cpystr ((char *) value);
638 }
639 else fatal ("SET_SNARFMAILBOXNAME with no stream");
640 case GET_SNARFMAILBOXNAME:
641 if (stream) ret = (void *) stream->snarf.name;
642 break;
643 default:
644 if (r = smtp_parameters (function,value)) ret = r;
645 if (r = env_parameters (function,value)) ret = r;
646 if (r = tcp_parameters (function,value)) ret = r;
647 if (stream && stream->dtb) {/* if have stream, do for its driver only */
648 if (r = (*stream->dtb->parameters) (function,value)) ret = r;
649 }
650 /* else do all drivers */
651 else for (d = maildrivers; d; d = d->next)
652 if (r = (d->parameters) (function,value)) ret = r;
653 break;
654 }
655 return ret;
656 }
658 /* Mail validate mailbox name
659 * Accepts: MAIL stream
660 * mailbox name
661 * purpose string for error message
662 * Return: driver factory on success, NIL on failure
663 */
665 DRIVER *mail_valid (MAILSTREAM *stream,char *mailbox,char *purpose)
666 {
667 char tmp[MAILTMPLEN];
668 DRIVER *factory = NIL;
669 /* never allow names with newlines */
670 if (strpbrk (mailbox,"\015\012")) {
671 if (purpose) { /* if want an error message */
672 sprintf (tmp,"Can't %s with such a name",purpose);
673 MM_LOG (tmp,ERROR);
674 }
675 return NIL;
676 }
677 /* validate name, find driver factory */
678 if (strlen (mailbox) < (NETMAXHOST+(NETMAXUSER*2)+NETMAXMBX+NETMAXSRV+50))
679 for (factory = maildrivers; factory &&
680 ((factory->flags & DR_DISABLE) ||
681 ((factory->flags & DR_LOCAL) && (*mailbox == '{')) ||
682 !(*factory->valid) (mailbox));
683 factory = factory->next);
684 /* validate factory against non-dummy stream */
685 if (factory && stream && stream->dtb && (stream->dtb != factory) &&
686 strcmp (stream->dtb->name,"dummy"))
687 /* factory invalid; if dummy, use stream */
688 factory = strcmp (factory->name,"dummy") ? NIL : stream->dtb;
689 if (!factory && purpose) { /* if want an error message */
690 sprintf (tmp,"Can't %s %.80s: %s",purpose,mailbox,(*mailbox == '{') ?
691 "invalid remote specification" : "no such mailbox");
692 MM_LOG (tmp,ERROR);
693 }
694 return factory; /* return driver factory */
695 }
697 /* Mail validate network mailbox name
698 * Accepts: mailbox name
699 * mailbox driver to validate against
700 * pointer to where to return host name if non-NIL
701 * pointer to where to return mailbox name if non-NIL
702 * Returns: driver on success, NIL on failure
703 */
705 DRIVER *mail_valid_net (char *name,DRIVER *drv,char *host,char *mailbox)
706 {
707 NETMBX mb;
708 if (!mail_valid_net_parse (name,&mb) || strcmp (mb.service,drv->name))
709 return NIL;
710 if (host) strcpy (host,mb.host);
711 if (mailbox) strcpy (mailbox,mb.mailbox);
712 return drv;
713 }
716 /* Mail validate network mailbox name
717 * Accepts: mailbox name
718 * NETMBX structure to return values
719 * Returns: T on success, NIL on failure
720 */
722 long mail_valid_net_parse (char *name,NETMBX *mb)
723 {
724 return mail_valid_net_parse_work (name,mb,"imap");
725 }
727 /* Mail validate network mailbox name worker routine
728 * Accepts: mailbox name
729 * NETMBX structure to return values
730 * default service
731 * Returns: T on success, NIL on failure
732 */
734 long mail_valid_net_parse_work (char *name,NETMBX *mb,char *service)
735 {
736 int i,j;
737 char c,*s,*t,*v,tmp[MAILTMPLEN],arg[MAILTMPLEN];
738 /* initialize structure */
739 memset (mb,'\0',sizeof (NETMBX));
740 /* must have host specification */
741 if (*name++ != '{') return NIL;
742 if (*name == '[') { /* if domain literal, find its ending */
743 if (!((v = strpbrk (name,"]}")) && (*v++ == ']'))) return NIL;
744 }
745 /* find end of host name */
746 else if (!(v = strpbrk (name,"/:}"))) return NIL;
747 /* validate length, find mailbox part */
748 if (!((i = v - name) && (i < NETMAXHOST) && (t = strchr (v,'}')) &&
749 ((j = t - v) < MAILTMPLEN) && (strlen (t+1) < (size_t) NETMAXMBX)))
750 return NIL; /* invalid mailbox */
751 strncpy (mb->host,name,i); /* set host name */
752 strncpy (mb->orighost,name,i);
753 mb->host[i] = mb->orighost[i] = '\0';
754 strcpy (mb->mailbox,t+1); /* set mailbox name */
755 if (t - v) { /* any switches or port specification? */
756 strncpy (t = tmp,v,j); /* copy it */
757 tmp[j] = '\0'; /* tie it off */
758 c = *t++; /* get first delimiter */
759 do switch (c) { /* act based upon the character */
760 case ':': /* port specification */
761 if (mb->port || !(mb->port = strtoul (t,&t,10))) return NIL;
762 c = t ? *t++ : '\0'; /* get delimiter, advance pointer */
763 break;
764 case '/': /* switch */
765 /* find delimiter */
766 if (t = strpbrk (s = t,"/:=")) {
767 c = *t; /* remember delimiter for later */
768 *t++ = '\0'; /* tie off switch name */
769 }
770 else c = '\0'; /* no delimiter */
771 if (c == '=') { /* parse switches which take arguments */
772 if (*t == '"') { /* quoted string? */
773 for (v = arg,i = 0,++t; (c = *t++) != '"';) {
774 if (!c) return NIL; /* unterminated string */
775 /* quote next character */
776 if (c == '\\') c = *t++;
777 if (!c) return NIL; /* can't quote NUL either */
778 arg[i++] = c;
779 }
780 c = *t++; /* remember delimiter for later */
781 arg[i] = '\0'; /* tie off argument */
782 }
783 else { /* non-quoted argument */
784 if (t = strpbrk (v = t,"/:")) {
785 c = *t; /* remember delimiter for later */
786 *t++ = '\0'; /* tie off switch name */
787 }
788 else c = '\0'; /* no delimiter */
789 i = strlen (v); /* length of argument */
790 }
791 if (!compare_cstring (s,"service") && (i < NETMAXSRV) && !*mb->service)
792 lcase (strcpy (mb->service,v));
793 else if (!compare_cstring (s,"user") && (i < NETMAXUSER) && !*mb->user)
794 strcpy (mb->user,v);
795 else if (!compare_cstring (s,"authuser") && (i < NETMAXUSER) &&
796 !*mb->authuser) strcpy (mb->authuser,v);
797 else return NIL;
798 }
800 else { /* non-argument switch */
801 if (!compare_cstring (s,"anonymous")) mb->anoflag = T;
802 else if (!compare_cstring (s,"debug")) mb->dbgflag = T;
803 else if (!compare_cstring (s,"readonly")) mb->readonlyflag = T;
804 else if (!compare_cstring (s,"secure")) mb->secflag = T;
805 else if (!compare_cstring (s,"norsh")) mb->norsh = T;
806 else if (!compare_cstring (s,"loser")) mb->loser = T;
807 else if (!compare_cstring (s,"tls") && !mb->notlsflag)
808 mb->tlsflag = T;
809 else if (!compare_cstring (s,"tls-sslv23") && !mb->notlsflag)
810 mb->tlssslv23 = mb->tlsflag = T;
811 else if (!compare_cstring (s,"notls") && !mb->tlsflag)
812 mb->notlsflag = T;
813 else if (!compare_cstring (s,"tryssl"))
814 mb->trysslflag = mailssldriver? T : NIL;
815 else if (mailssldriver && !compare_cstring (s,"ssl") && !mb->tlsflag)
816 mb->sslflag = mb->notlsflag = T;
817 else if (mailssldriver && !compare_cstring (s,"novalidate-cert"))
818 mb->novalidate = T;
819 /* hack for compatibility with the past */
820 else if (mailssldriver && !compare_cstring (s,"validate-cert"));
821 /* service switches below here */
822 else if (*mb->service) return NIL;
823 else if (!compare_cstring (s,"imap") ||
824 !compare_cstring (s,"nntp") ||
825 !compare_cstring (s,"pop3") ||
826 !compare_cstring (s,"smtp") ||
827 !compare_cstring (s,"submit"))
828 lcase (strcpy (mb->service,s));
829 else if (!compare_cstring (s,"imap2") ||
830 !compare_cstring (s,"imap2bis") ||
831 !compare_cstring (s,"imap4") ||
832 !compare_cstring (s,"imap4rev1"))
833 strcpy (mb->service,"imap");
834 else if (!compare_cstring (s,"pop"))
835 strcpy (mb->service,"pop3");
836 else return NIL; /* invalid non-argument switch */
837 }
838 break;
839 default: /* anything else is bogus */
840 return NIL;
841 } while (c); /* see if anything more to parse */
842 }
843 /* default mailbox name */
844 if (!*mb->mailbox) strcpy (mb->mailbox,"INBOX");
845 /* default service name */
846 if (!*mb->service) strcpy (mb->service,service);
847 /* /norsh only valid if imap */
848 if (mb->norsh && strcmp (mb->service,"imap")) return NIL;
849 return T;
850 }
852 /* Mail scan mailboxes for string
853 * Accepts: mail stream
854 * reference
855 * pattern to search
856 * contents to search
857 */
859 void mail_scan (MAILSTREAM *stream,char *ref,char *pat,char *contents)
860 {
861 int remote = ((*pat == '{') || (ref && *ref == '{'));
862 DRIVER *d;
863 if (ref && (strlen (ref) > NETMAXMBX)) {
864 char tmp[MAILTMPLEN];
865 sprintf (tmp,"Invalid LIST reference specification: %.80s",ref);
866 MM_LOG (tmp,ERROR);
867 return;
868 }
869 if (strlen (pat) > NETMAXMBX) {
870 char tmp[MAILTMPLEN];
871 sprintf (tmp,"Invalid LIST pattern specification: %.80s",pat);
872 MM_LOG (tmp,ERROR);
873 return;
874 }
875 if (*pat == '{') ref = NIL; /* ignore reference if pattern is remote */
876 if (stream) { /* if have a stream, do it for that stream */
877 if ((d = stream->dtb) && d->scan &&
878 !(((d->flags & DR_LOCAL) && remote)))
879 (*d->scan) (stream,ref,pat,contents);
880 }
881 /* otherwise do for all DTB's */
882 else for (d = maildrivers; d; d = d->next)
883 if (d->scan && !((d->flags & DR_DISABLE) ||
884 ((d->flags & DR_LOCAL) && remote)))
885 (d->scan) (NIL,ref,pat,contents);
886 }
888 /* Mail list mailboxes
889 * Accepts: mail stream
890 * reference
891 * pattern to search
892 */
894 void mail_list (MAILSTREAM *stream,char *ref,char *pat)
895 {
896 int remote = ((*pat == '{') || (ref && *ref == '{'));
897 DRIVER *d = maildrivers;
898 if (ref && (strlen (ref) > NETMAXMBX)) {
899 char tmp[MAILTMPLEN];
900 sprintf (tmp,"Invalid LIST reference specification: %.80s",ref);
901 MM_LOG (tmp,ERROR);
902 return;
903 }
904 if (strlen (pat) > NETMAXMBX) {
905 char tmp[MAILTMPLEN];
906 sprintf (tmp,"Invalid LIST pattern specification: %.80s",pat);
907 MM_LOG (tmp,ERROR);
908 return;
909 }
910 if (*pat == '{') ref = NIL; /* ignore reference if pattern is remote */
911 if (stream && stream->dtb) { /* if have a stream, do it for that stream */
912 if (!(((d = stream->dtb)->flags & DR_LOCAL) && remote))
913 (*d->list) (stream,ref,pat);
914 }
915 /* otherwise do for all DTB's */
916 else do if (!((d->flags & DR_DISABLE) ||
917 ((d->flags & DR_LOCAL) && remote)))
918 (d->list) (NIL,ref,pat);
919 while (d = d->next); /* until at the end */
920 }
922 /* Mail list subscribed mailboxes
923 * Accepts: mail stream
924 * pattern to search
925 */
927 void mail_lsub (MAILSTREAM *stream,char *ref,char *pat)
928 {
929 int remote = ((*pat == '{') || (ref && *ref == '{'));
930 DRIVER *d = maildrivers;
931 if (ref && (strlen (ref) > NETMAXMBX)) {
932 char tmp[MAILTMPLEN];
933 sprintf (tmp,"Invalid LSUB reference specification: %.80s",ref);
934 MM_LOG (tmp,ERROR);
935 return;
936 }
937 if (strlen (pat) > NETMAXMBX) {
938 char tmp[MAILTMPLEN];
939 sprintf (tmp,"Invalid LSUB pattern specification: %.80s",pat);
940 MM_LOG (tmp,ERROR);
941 return;
942 }
943 if (*pat == '{') ref = NIL; /* ignore reference if pattern is remote */
944 if (stream && stream->dtb) { /* if have a stream, do it for that stream */
945 if (!(((d = stream->dtb)->flags & DR_LOCAL) && remote))
946 (*d->lsub) (stream,ref,pat);
947 }
948 /* otherwise do for all DTB's */
949 else do if (!((d->flags & DR_DISABLE) ||
950 ((d->flags & DR_LOCAL) && remote)))
951 (d->lsub) (NIL,ref,pat);
952 while (d = d->next); /* until at the end */
953 }
955 /* Mail subscribe to mailbox
956 * Accepts: mail stream
957 * mailbox to add to subscription list
958 * Returns: T on success, NIL on failure
959 */
961 long mail_subscribe (MAILSTREAM *stream,char *mailbox)
962 {
963 DRIVER *factory = mail_valid (stream,mailbox,"subscribe to mailbox");
964 return factory ?
965 (factory->subscribe ?
966 (*factory->subscribe) (stream,mailbox) : sm_subscribe (mailbox)) : NIL;
967 }
970 /* Mail unsubscribe to mailbox
971 * Accepts: mail stream
972 * mailbox to delete from subscription list
973 * Returns: T on success, NIL on failure
974 */
976 long mail_unsubscribe (MAILSTREAM *stream,char *mailbox)
977 {
978 DRIVER *factory = mail_valid (stream,mailbox,NIL);
979 return (factory && factory->unsubscribe) ?
980 (*factory->unsubscribe) (stream,mailbox) : sm_unsubscribe (mailbox);
981 }
983 /* Mail create mailbox
984 * Accepts: mail stream
985 * mailbox name to create
986 * Returns: T on success, NIL on failure
987 */
989 long mail_create (MAILSTREAM *stream,char *mailbox)
990 {
991 MAILSTREAM *ts;
992 char *s,*t,tmp[MAILTMPLEN];
993 size_t i;
994 DRIVER *d;
995 /* never allow names with newlines */
996 if (s = strpbrk (mailbox,"\015\012")) {
997 MM_LOG ("Can't create mailbox with such a name",ERROR);
998 return NIL;
999 }
1000 if (strlen (mailbox) >= (NETMAXHOST+(NETMAXUSER*2)+NETMAXMBX+NETMAXSRV+50)) {
1001 sprintf (tmp,"Can't create %.80s: %s",mailbox,(*mailbox == '{') ?
1002 "invalid remote specification" : "no such mailbox");
1003 MM_LOG (tmp,ERROR);
1004 return NIL;
1006 /* create of INBOX invalid */
1007 if (!compare_cstring (mailbox,"INBOX")) {
1008 MM_LOG ("Can't create INBOX",ERROR);
1009 return NIL;
1011 /* validate name */
1012 if (s = mail_utf7_valid (mailbox)) {
1013 sprintf (tmp,"Can't create %s: %.80s",s,mailbox);
1014 MM_LOG (tmp,ERROR);
1015 return NIL;
1018 /* see if special driver hack */
1019 if ((mailbox[0] == '#') && ((mailbox[1] == 'd') || (mailbox[1] == 'D')) &&
1020 ((mailbox[2] == 'r') || (mailbox[2] == 'R')) &&
1021 ((mailbox[3] == 'i') || (mailbox[3] == 'I')) &&
1022 ((mailbox[4] == 'v') || (mailbox[4] == 'V')) &&
1023 ((mailbox[5] == 'e') || (mailbox[5] == 'E')) &&
1024 ((mailbox[6] == 'r') || (mailbox[6] == 'R')) && (mailbox[7] == '.')) {
1025 /* copy driver until likely delimiter */
1026 if ((s = strpbrk (t = mailbox+8,"/\\:")) && (i = s - t)) {
1027 strncpy (tmp,t,i);
1028 tmp[i] = '\0';
1030 else {
1031 sprintf (tmp,"Can't create mailbox %.80s: bad driver syntax",mailbox);
1032 MM_LOG (tmp,ERROR);
1033 return NIL;
1035 for (d = maildrivers; d && strcmp (d->name,tmp); d = d->next);
1036 if (d) mailbox = ++s; /* skip past driver specification */
1037 else {
1038 sprintf (tmp,"Can't create mailbox %.80s: unknown driver",mailbox);
1039 MM_LOG (tmp,ERROR);
1040 return NIL;
1043 /* use stream if one given or deterministic */
1044 else if ((stream && stream->dtb) ||
1045 (((*mailbox == '{') || (*mailbox == '#')) &&
1046 (stream = mail_open (NIL,mailbox,OP_PROTOTYPE | OP_SILENT))))
1047 d = stream->dtb;
1048 else if ((*mailbox != '{') && (ts = default_proto (NIL))) d = ts->dtb;
1049 else { /* failed utterly */
1050 sprintf (tmp,"Can't create mailbox %.80s: indeterminate format",mailbox);
1051 MM_LOG (tmp,ERROR);
1052 return NIL;
1054 return (*d->create) (stream,mailbox);
1057 /* Mail delete mailbox
1058 * Accepts: mail stream
1059 * mailbox name to delete
1060 * Returns: T on success, NIL on failure
1061 */
1063 long mail_delete (MAILSTREAM *stream,char *mailbox)
1065 DRIVER *dtb = mail_valid (stream,mailbox,"delete mailbox");
1066 if (!dtb) return NIL;
1067 if (((mailbox[0] == 'I') || (mailbox[0] == 'i')) &&
1068 ((mailbox[1] == 'N') || (mailbox[1] == 'n')) &&
1069 ((mailbox[2] == 'B') || (mailbox[2] == 'b')) &&
1070 ((mailbox[3] == 'O') || (mailbox[3] == 'o')) &&
1071 ((mailbox[4] == 'X') || (mailbox[4] == 'x')) && !mailbox[5]) {
1072 MM_LOG ("Can't delete INBOX",ERROR);
1073 return NIL;
1075 return SAFE_DELETE (dtb,stream,mailbox);
1079 /* Mail rename mailbox
1080 * Accepts: mail stream
1081 * old mailbox name
1082 * new mailbox name
1083 * Returns: T on success, NIL on failure
1084 */
1086 long mail_rename (MAILSTREAM *stream,char *old,char *newname)
1088 char *s,tmp[MAILTMPLEN];
1089 DRIVER *dtb = mail_valid (stream,old,"rename mailbox");
1090 if (!dtb) return NIL;
1091 /* validate name */
1092 if (s = mail_utf7_valid (newname)) {
1093 sprintf (tmp,"Can't rename to %s: %.80s",s,newname);
1094 MM_LOG (tmp,ERROR);
1095 return NIL;
1097 if ((*old != '{') && (*old != '#') && mail_valid (NIL,newname,NIL)) {
1098 sprintf (tmp,"Can't rename %.80s: mailbox %.80s already exists",
1099 old,newname);
1100 MM_LOG (tmp,ERROR);
1101 return NIL;
1103 return SAFE_RENAME (dtb,stream,old,newname);
1106 /* Validate mailbox as Modified UTF-7
1107 * Accepts: candidate mailbox name
1108 * Returns: error string if error, NIL if valid
1109 */
1111 char *mail_utf7_valid (char *mailbox)
1113 char *s;
1114 for (s = mailbox; *s; s++) { /* make sure valid name */
1115 /* reserved for future use with UTF-8 */
1116 if (*s & 0x80) return "mailbox name with 8-bit octet";
1117 /* validate modified UTF-7 */
1118 else if (*s == '&') while (*++s != '-') switch (*s) {
1119 case '\0':
1120 return "unterminated modified UTF-7 name";
1121 case '+': /* valid modified BASE64 */
1122 case ',':
1123 break; /* all OK so far */
1124 default: /* must be alphanumeric */
1125 if (!isalnum (*s)) return "invalid modified UTF-7 name";
1126 break;
1129 return NIL; /* all OK */
1132 /* Mail status of mailbox
1133 * Accepts: mail stream if open on this mailbox
1134 * mailbox name
1135 * status flags
1136 * Returns: T on success, NIL on failure
1137 */
1139 long mail_status (MAILSTREAM *stream,char *mbx,long flags)
1141 DRIVER *dtb = mail_valid (stream,mbx,"get status of mailbox");
1142 if (!dtb) return NIL; /* only if valid */
1143 if (stream && ((dtb != stream->dtb) ||
1144 ((dtb->flags & DR_LOCAL) && strcmp (mbx,stream->mailbox) &&
1145 strcmp (mbx,stream->original_mailbox))))
1146 stream = NIL; /* stream not suitable */
1147 return SAFE_STATUS (dtb,stream,mbx,flags);
1151 /* Mail status of mailbox default handler
1152 * Accepts: mail stream
1153 * mailbox name
1154 * status flags
1155 * Returns: T on success, NIL on failure
1156 */
1158 long mail_status_default (MAILSTREAM *stream,char *mbx,long flags)
1160 MAILSTATUS status;
1161 unsigned long i;
1162 MAILSTREAM *tstream = NIL;
1163 /* make temporary stream (unless this mbx) */
1164 if (!stream && !(stream = tstream =
1165 mail_open (NIL,mbx,OP_READONLY|OP_SILENT))) return NIL;
1166 status.flags = flags; /* return status values */
1167 status.messages = stream->nmsgs;
1168 status.recent = stream->recent;
1169 if (flags & SA_UNSEEN) /* must search to get unseen messages */
1170 for (i = 1,status.unseen = 0; i <= stream->nmsgs; i++)
1171 if (!mail_elt (stream,i)->seen) status.unseen++;
1172 status.uidnext = stream->uid_last + 1;
1173 status.uidvalidity = stream->uid_validity;
1174 MM_STATUS(stream,mbx,&status);/* pass status to main program */
1175 if (tstream) mail_close (tstream);
1176 return T; /* success */
1179 /* Mail open
1180 * Accepts: candidate stream for recycling
1181 * mailbox name
1182 * open options
1183 * Returns: stream to use on success, NIL on failure
1184 */
1186 MAILSTREAM *mail_open (MAILSTREAM *stream,char *name,long options)
1188 int i;
1189 char c,*s,tmp[MAILTMPLEN];
1190 NETMBX mb;
1191 DRIVER *d;
1192 switch (name[0]) { /* see if special handling */
1193 case '#': /* possible special hacks */
1194 if (((name[1] == 'M') || (name[1] == 'm')) &&
1195 ((name[2] == 'O') || (name[2] == 'o')) &&
1196 ((name[3] == 'V') || (name[3] == 'v')) &&
1197 ((name[4] == 'E') || (name[4] == 'e')) && (c = name[5]) &&
1198 (s = strchr (name+6,c)) && (i = s - (name + 6)) && (i < MAILTMPLEN)) {
1199 if (stream = mail_open (stream,s+1,options)) {
1200 strncpy (tmp,name+6,i); /* copy snarf mailbox name */
1201 tmp[i] = '\0'; /* tie off name */
1202 mail_parameters (stream,SET_SNARFMAILBOXNAME,(void *) tmp);
1203 stream->snarf.options = options;
1204 mail_ping (stream); /* do initial snarf */
1205 /* punt if can't do initial snarf */
1206 if (!stream->snarf.time) stream = mail_close (stream);
1208 return stream;
1210 /* special POP hack */
1211 else if (((name[1] == 'P') || (name[1] == 'p')) &&
1212 ((name[2] == 'O') || (name[2] == 'o')) &&
1213 ((name[3] == 'P') || (name[3] == 'p')) &&
1214 mail_valid_net_parse_work (name+4,&mb,"pop3") &&
1215 !strcmp (mb.service,"pop3") && !mb.anoflag && !mb.readonlyflag) {
1216 if (stream = mail_open (stream,mb.mailbox,options)) {
1217 sprintf (tmp,"{%.255s",mb.host);
1218 if (mb.port) sprintf (tmp + strlen (tmp),":%lu",mb.port);
1219 if (mb.user[0]) sprintf (tmp + strlen (tmp),"/user=%.64s",mb.user);
1220 if (mb.dbgflag) strcat (tmp,"/debug");
1221 if (mb.secflag) strcat (tmp,"/secure");
1222 if (mb.tlsflag) strcat (tmp,"/tls");
1223 if (mb.notlsflag) strcat (tmp,"/notls");
1224 if (mb.sslflag) strcat (tmp,"/ssl");
1225 if (mb.trysslflag) strcat (tmp,"/tryssl");
1226 if (mb.novalidate) strcat (tmp,"/novalidate-cert");
1227 strcat (tmp,"/pop3/loser}");
1228 mail_parameters (stream,SET_SNARFMAILBOXNAME,(void *) tmp);
1229 mail_ping (stream); /* do initial snarf */
1231 return stream; /* return local mailbox stream */
1234 else if ((options & OP_PROTOTYPE) &&
1235 ((name[1] == 'D') || (name[1] == 'd')) &&
1236 ((name[2] == 'R') || (name[2] == 'r')) &&
1237 ((name[3] == 'I') || (name[3] == 'i')) &&
1238 ((name[4] == 'V') || (name[4] == 'v')) &&
1239 ((name[5] == 'E') || (name[5] == 'e')) &&
1240 ((name[6] == 'R') || (name[6] == 'r')) && (name[7] == '.')) {
1241 sprintf (tmp,"%.80s",name+8);
1242 /* tie off name at likely delimiter */
1243 if (s = strpbrk (tmp,"/\\:")) *s++ = '\0';
1244 else {
1245 sprintf (tmp,"Can't resolve mailbox %.80s: bad driver syntax",name);
1246 MM_LOG (tmp,ERROR);
1247 return mail_close (stream);
1249 for (d = maildrivers; d && compare_cstring (d->name,tmp); d = d->next);
1250 if (d) return (*d->open) (NIL);
1251 sprintf (tmp,"Can't resolve mailbox %.80s: unknown driver",name);
1252 MM_LOG (tmp,ERROR);
1253 return mail_close (stream);
1255 /* fall through to default case */
1256 default: /* not special hack (but could be # name */
1257 d = mail_valid (NIL,name,(options & OP_SILENT) ?
1258 (char *) NIL : "open mailbox");
1260 return d ? mail_open_work (d,stream,name,options) : stream;
1263 /* Mail open worker routine
1264 * Accepts: factory
1265 * candidate stream for recycling
1266 * mailbox name
1267 * open options
1268 * Returns: stream to use on success, NIL on failure
1269 */
1271 MAILSTREAM *mail_open_work (DRIVER *d,MAILSTREAM *stream,char *name,
1272 long options)
1274 int i;
1275 char tmp[MAILTMPLEN];
1276 NETMBX mb;
1277 if (options & OP_PROTOTYPE) return (*d->open) (NIL);
1278 /* name is copied here in case the caller does a re-open using
1279 * stream->mailbox or stream->original_mailbox as the argument.
1280 */
1281 name = cpystr (name); /* make copy of name */
1282 if (stream) { /* recycling requested? */
1283 if ((stream->dtb == d) && (d->flags & DR_RECYCLE) &&
1284 ((d->flags & DR_HALFOPEN) || !(options & OP_HALFOPEN)) &&
1285 mail_usable_network_stream (stream,name)) {
1286 /* yes, checkpoint if needed */
1287 if (d->flags & DR_XPOINT) mail_check (stream);
1288 mail_free_cache (stream); /* clean up stream */
1289 if (stream->mailbox) fs_give ((void **) &stream->mailbox);
1290 if (stream->original_mailbox)
1291 fs_give ((void **) &stream->original_mailbox);
1292 /* flush user flags */
1293 for (i = 0; i < NUSERFLAGS; i++)
1294 if (stream->user_flags[i]) fs_give ((void **) &stream->user_flags[i]);
1296 else { /* stream not recycleable, babble if net */
1297 if (!stream->silent && stream->dtb && !(stream->dtb->flags&DR_LOCAL) &&
1298 mail_valid_net_parse (stream->mailbox,&mb)) {
1299 sprintf (tmp,"Closing connection to %.80s",mb.host);
1300 MM_LOG (tmp,(long) NIL);
1302 /* flush the old stream */
1303 stream = mail_close (stream);
1306 /* check if driver does not support halfopen */
1307 else if ((options & OP_HALFOPEN) && !(d->flags & DR_HALFOPEN)) {
1308 fs_give ((void **) &name);
1309 return NIL;
1312 /* instantiate new stream if not recycling */
1313 if (!stream) (*mailcache) (stream = (MAILSTREAM *)
1314 memset (fs_get (sizeof (MAILSTREAM)),0,
1315 sizeof (MAILSTREAM)),(long) 0,CH_INIT);
1316 stream->dtb = d; /* set dispatch */
1317 /* set mailbox name */
1318 stream->mailbox = cpystr (stream->original_mailbox = name);
1319 /* initialize stream flags */
1320 stream->inbox = stream->lock = NIL;
1321 stream->debug = (options & OP_DEBUG) ? T : NIL;
1322 stream->rdonly = (options & OP_READONLY) ? T : NIL;
1323 stream->anonymous = (options & OP_ANONYMOUS) ? T : NIL;
1324 stream->scache = (options & OP_SHORTCACHE) ? T : NIL;
1325 stream->silent = (options & OP_SILENT) ? T : NIL;
1326 stream->halfopen = (options & OP_HALFOPEN) ? T : NIL;
1327 stream->secure = (options & OP_SECURE) ? T : NIL;
1328 stream->tryssl = (options & OP_TRYSSL) ? T : NIL;
1329 stream->mulnewsrc = (options & OP_MULNEWSRC) ? T : NIL;
1330 stream->nokod = (options & OP_NOKOD) ? T : NIL;
1331 stream->sniff = (options & OP_SNIFF) ? T : NIL;
1332 stream->perm_seen = stream->perm_deleted = stream->perm_flagged =
1333 stream->perm_answered = stream->perm_draft = stream->kwd_create = NIL;
1334 stream->uid_nosticky = (d->flags & DR_NOSTICKY) ? T : NIL;
1335 stream->uid_last = 0; /* default UID validity */
1336 stream->uid_validity = (unsigned long) time (0);
1337 /* have driver open, flush if failed */
1338 return ((*d->open) (stream)) ? stream : mail_close (stream);
1341 /* Mail close
1342 * Accepts: mail stream
1343 * close options
1344 * Returns: NIL, always
1345 */
1347 MAILSTREAM *mail_close_full (MAILSTREAM *stream,long options)
1349 int i;
1350 if (stream) { /* make sure argument given */
1351 /* do the driver's close action */
1352 if (stream->dtb) (*stream->dtb->close) (stream,options);
1353 stream->dtb = NIL; /* resign driver */
1354 if (stream->mailbox) fs_give ((void **) &stream->mailbox);
1355 if (stream->original_mailbox)
1356 fs_give ((void **) &stream->original_mailbox);
1357 if (stream->snarf.name) fs_give ((void **) &stream->snarf.name);
1358 stream->sequence++; /* invalidate sequence */
1359 /* flush user flags */
1360 for (i = 0; i < NUSERFLAGS; i++)
1361 if (stream->user_flags[i]) fs_give ((void **) &stream->user_flags[i]);
1362 mail_free_cache (stream); /* finally free the stream's storage */
1363 if (mailfreestreamsparep && stream->sparep)
1364 (*mailfreestreamsparep) (&stream->sparep);
1365 if (!stream->use) fs_give ((void **) &stream);
1367 return NIL;
1370 /* Mail make handle
1371 * Accepts: mail stream
1372 * Returns: handle
1374 * Handles provide a way to have multiple pointers to a stream yet allow the
1375 * stream's owner to nuke it or recycle it.
1376 */
1378 MAILHANDLE *mail_makehandle (MAILSTREAM *stream)
1380 MAILHANDLE *handle = (MAILHANDLE *) fs_get (sizeof (MAILHANDLE));
1381 handle->stream = stream; /* copy stream */
1382 /* and its sequence */
1383 handle->sequence = stream->sequence;
1384 stream->use++; /* let stream know another handle exists */
1385 return handle;
1389 /* Mail release handle
1390 * Accepts: Mail handle
1391 */
1393 void mail_free_handle (MAILHANDLE **handle)
1395 MAILSTREAM *s;
1396 if (*handle) { /* only free if exists */
1397 /* resign stream, flush unreferenced zombies */
1398 if ((!--(s = (*handle)->stream)->use) && !s->dtb) fs_give ((void **) &s);
1399 fs_give ((void **) handle); /* now flush the handle */
1404 /* Mail get stream handle
1405 * Accepts: Mail handle
1406 * Returns: mail stream or NIL if stream gone
1407 */
1409 MAILSTREAM *mail_stream (MAILHANDLE *handle)
1411 MAILSTREAM *s = handle->stream;
1412 return (s->dtb && (handle->sequence == s->sequence)) ? s : NIL;
1415 /* Mail fetch cache element
1416 * Accepts: mail stream
1417 * message # to fetch
1418 * Returns: cache element of this message
1419 * Can also be used to create cache elements for new messages.
1420 */
1422 MESSAGECACHE *mail_elt (MAILSTREAM *stream,unsigned long msgno)
1424 if (msgno < 1 || msgno > stream->nmsgs) {
1425 char tmp[MAILTMPLEN];
1426 sprintf (tmp,"Bad msgno %lu in mail_elt, nmsgs = %lu, mbx=%.80s",
1427 msgno,stream->nmsgs,stream->mailbox ? stream->mailbox : "???");
1428 fatal (tmp);
1430 return (MESSAGECACHE *) (*mailcache) (stream,msgno,CH_MAKEELT);
1434 /* Mail fetch fast information
1435 * Accepts: mail stream
1436 * sequence
1437 * option flags
1439 * Generally, mail_fetch_structure is preferred
1440 */
1442 void mail_fetch_fast (MAILSTREAM *stream,char *sequence,long flags)
1444 /* do the driver's action */
1445 if (stream->dtb && stream->dtb->fast)
1446 (*stream->dtb->fast) (stream,sequence,flags);
1450 /* Mail fetch flags
1451 * Accepts: mail stream
1452 * sequence
1453 * option flags
1454 */
1456 void mail_fetch_flags (MAILSTREAM *stream,char *sequence,long flags)
1458 /* do the driver's action */
1459 if (stream->dtb && stream->dtb->msgflags)
1460 (*stream->dtb->msgflags) (stream,sequence,flags);
1463 /* Mail fetch message overview
1464 * Accepts: mail stream
1465 * UID sequence to fetch
1466 * pointer to overview return function
1467 */
1469 void mail_fetch_overview (MAILSTREAM *stream,char *sequence,overview_t ofn)
1471 if (stream->dtb && mail_uid_sequence (stream,sequence) &&
1472 !(stream->dtb->overview && (*stream->dtb->overview) (stream,ofn)) &&
1473 mail_ping (stream))
1474 mail_fetch_overview_default (stream,ofn);
1478 /* Mail fetch message overview using sequence numbers instead of UIDs
1479 * Accepts: mail stream
1480 * sequence to fetch
1481 * pointer to overview return function
1482 */
1484 void mail_fetch_overview_sequence (MAILSTREAM *stream,char *sequence,
1485 overview_t ofn)
1487 if (stream->dtb && mail_sequence (stream,sequence) &&
1488 !(stream->dtb->overview && (*stream->dtb->overview) (stream,ofn)) &&
1489 mail_ping (stream))
1490 mail_fetch_overview_default (stream,ofn);
1494 /* Mail fetch message overview default handler
1495 * Accepts: mail stream with sequence bits lit
1496 * pointer to overview return function
1497 */
1499 void mail_fetch_overview_default (MAILSTREAM *stream,overview_t ofn)
1501 MESSAGECACHE *elt;
1502 ENVELOPE *env;
1503 OVERVIEW ov;
1504 unsigned long i;
1505 ov.optional.lines = 0;
1506 ov.optional.xref = NIL;
1507 for (i = 1; i <= stream->nmsgs; i++)
1508 if (((elt = mail_elt (stream,i))->sequence) &&
1509 (env = mail_fetch_structure (stream,i,NIL,NIL)) && ofn) {
1510 ov.subject = env->subject;
1511 ov.from = env->from;
1512 ov.date = env->date;
1513 ov.message_id = env->message_id;
1514 ov.references = env->references;
1515 ov.optional.octets = elt->rfc822_size;
1516 (*ofn) (stream,mail_uid (stream,i),&ov,i);
1520 /* Mail fetch message structure
1521 * Accepts: mail stream
1522 * message # to fetch
1523 * pointer to return body
1524 * option flags
1525 * Returns: envelope of this message, body returned in body value
1527 * Fetches the "fast" information as well
1528 */
1530 ENVELOPE *mail_fetch_structure (MAILSTREAM *stream,unsigned long msgno,
1531 BODY **body,long flags)
1533 ENVELOPE **env;
1534 BODY **b;
1535 MESSAGECACHE *elt;
1536 char c,*s,*hdr;
1537 unsigned long hdrsize;
1538 STRING bs;
1539 /* do the driver's action if specified */
1540 if (stream->dtb && stream->dtb->structure)
1541 return (*stream->dtb->structure) (stream,msgno,body,flags);
1542 if (flags & FT_UID) { /* UID form of call */
1543 if (msgno = mail_msgno (stream,msgno)) flags &= ~FT_UID;
1544 else return NIL; /* must get UID/msgno map first */
1546 elt = mail_elt (stream,msgno);/* get elt for real message number */
1547 if (stream->scache) { /* short caching */
1548 if (msgno != stream->msgno){/* garbage collect if not same message */
1549 mail_gc (stream,GC_ENV | GC_TEXTS);
1550 stream->msgno = msgno; /* this is the current message now */
1552 env = &stream->env; /* get pointers to envelope and body */
1553 b = &stream->body;
1555 else { /* get pointers to elt envelope and body */
1556 env = &elt->private.msg.env;
1557 b = &elt->private.msg.body;
1560 if (stream->dtb && ((body && !*b) || !*env || (*env)->incomplete)) {
1561 mail_free_envelope (env); /* flush old envelope and body */
1562 mail_free_body (b);
1563 /* see if need to fetch the whole thing */
1564 if (body || !elt->rfc822_size) {
1565 s = (*stream->dtb->header) (stream,msgno,&hdrsize,flags & ~FT_INTERNAL);
1566 /* make copy in case body fetch smashes it */
1567 hdr = (char *) memcpy (fs_get ((size_t) hdrsize+1),s,(size_t) hdrsize);
1568 hdr[hdrsize] = '\0'; /* tie off header */
1569 (*stream->dtb->text) (stream,msgno,&bs,(flags & ~FT_INTERNAL) | FT_PEEK);
1570 if (!elt->rfc822_size) elt->rfc822_size = hdrsize + SIZE (&bs);
1571 if (body) /* only parse body if requested */
1572 rfc822_parse_msg (env,b,hdr,hdrsize,&bs,BADHOST,stream->dtb->flags);
1573 else
1574 rfc822_parse_msg (env,NIL,hdr,hdrsize,NIL,BADHOST,stream->dtb->flags);
1575 fs_give ((void **) &hdr); /* flush header */
1577 else { /* can save memory doing it this way */
1578 hdr = (*stream->dtb->header) (stream,msgno,&hdrsize,flags | FT_INTERNAL);
1579 if (hdrsize) { /* in case null header */
1580 c = hdr[hdrsize]; /* preserve what's there */
1581 hdr[hdrsize] = '\0'; /* tie off header */
1582 rfc822_parse_msg (env,NIL,hdr,hdrsize,NIL,BADHOST,stream->dtb->flags);
1583 hdr[hdrsize] = c; /* restore in case cached data */
1585 else *env = mail_newenvelope ();
1588 /* if need date, have date in envelope? */
1589 if (!elt->day && *env && (*env)->date) mail_parse_date (elt,(*env)->date);
1590 /* sigh, fill in bogus default */
1591 if (!elt->day) elt->day = elt->month = 1;
1592 if (body) *body = *b; /* return the body */
1593 return *env; /* return the envelope */
1596 /* Mail mark single message (internal use only)
1597 * Accepts: mail stream
1598 * elt to mark
1599 * fetch flags
1600 */
1602 static void markseen (MAILSTREAM *stream,MESSAGECACHE *elt,long flags)
1604 unsigned long i;
1605 char sequence[20];
1606 MESSAGECACHE *e;
1607 /* non-peeking and needs to set \Seen? */
1608 if (!(flags & FT_PEEK) && !elt->seen) {
1609 if (stream->dtb->flagmsg){ /* driver wants per-message call? */
1610 elt->valid = NIL; /* do pre-alteration driver call */
1611 (*stream->dtb->flagmsg) (stream,elt);
1612 /* set seen, do post-alteration driver call */
1613 elt->seen = elt->valid = T;
1614 (*stream->dtb->flagmsg) (stream,elt);
1616 if (stream->dtb->flag) { /* driver wants one-time call? */
1617 /* better safe than sorry, save seq bits */
1618 for (i = 1; i <= stream->nmsgs; i++) {
1619 e = mail_elt (stream,i);
1620 e->private.sequence = e->sequence;
1622 /* call driver to set the message */
1623 sprintf (sequence,"%lu",elt->msgno);
1624 (*stream->dtb->flag) (stream,sequence,"\\Seen",ST_SET);
1625 /* restore sequence bits */
1626 for (i = 1; i <= stream->nmsgs; i++) {
1627 e = mail_elt (stream,i);
1628 e->sequence = e->private.sequence;
1631 /* notify mail program of flag change */
1632 MM_FLAGS (stream,elt->msgno);
1636 /* Mail fetch message
1637 * Accepts: mail stream
1638 * message # to fetch
1639 * pointer to returned length
1640 * flags
1641 * Returns: message text
1642 */
1644 char *mail_fetch_message (MAILSTREAM *stream,unsigned long msgno,
1645 unsigned long *len,long flags)
1647 GETS_DATA md;
1648 SIZEDTEXT *t;
1649 STRING bs;
1650 MESSAGECACHE *elt;
1651 char *s,*u;
1652 unsigned long i,j;
1653 if (len) *len = 0; /* default return size */
1654 if (flags & FT_UID) { /* UID form of call */
1655 if (msgno = mail_msgno (stream,msgno)) flags &= ~FT_UID;
1656 else return ""; /* must get UID/msgno map first */
1658 /* initialize message data identifier */
1659 INIT_GETS (md,stream,msgno,"",0,0);
1660 /* is data already cached? */
1661 if ((t = &(elt = mail_elt (stream,msgno))->private.msg.full.text)->data) {
1662 markseen (stream,elt,flags);/* mark message seen */
1663 return mail_fetch_text_return (&md,t,len);
1665 if (!stream->dtb) return ""; /* not in cache, must have live driver */
1666 if (stream->dtb->msgdata) return
1667 ((*stream->dtb->msgdata) (stream,msgno,"",0,0,NIL,flags) && t->data) ?
1668 mail_fetch_text_return (&md,t,len) : "";
1669 /* ugh, have to do this the crufty way */
1670 u = mail_fetch_header (stream,msgno,NIL,NIL,&i,flags);
1671 /* copy in case text method stomps on it */
1672 s = (char *) memcpy (fs_get ((size_t) i),u,(size_t) i);
1673 if ((*stream->dtb->text) (stream,msgno,&bs,flags)) {
1674 t = &stream->text; /* build combined copy */
1675 if (t->data) fs_give ((void **) &t->data);
1676 t->data = (unsigned char *) fs_get ((t->size = i + SIZE (&bs)) + 1);
1677 if (!elt->rfc822_size) elt->rfc822_size = t->size;
1678 else if (elt->rfc822_size != t->size) {
1679 char tmp[MAILTMPLEN];
1680 sprintf (tmp,"Calculated RFC822.SIZE (%lu) != reported size (%lu)",
1681 t->size,elt->rfc822_size);
1682 mm_log (tmp,WARN); /* bug trap */
1684 memcpy (t->data,s,(size_t) i);
1685 for (u = (char *) t->data + i, j = SIZE (&bs); j;) {
1686 memcpy (u,bs.curpos,bs.cursize);
1687 u += bs.cursize; /* update text */
1688 j -= bs.cursize;
1689 bs.curpos += (bs.cursize -1);
1690 bs.cursize = 0;
1691 (*bs.dtb->next) (&bs); /* advance to next buffer's worth */
1693 *u = '\0'; /* tie off data */
1694 u = mail_fetch_text_return (&md,t,len);
1696 else u = "";
1697 fs_give ((void **) &s); /* finished with copy of header */
1698 return u;
1701 /* Mail fetch message header
1702 * Accepts: mail stream
1703 * message # to fetch
1704 * MIME section specifier (#.#.#...#)
1705 * list of lines to fetch
1706 * pointer to returned length
1707 * flags
1708 * Returns: message header in RFC822 format
1710 * Note: never calls a mailgets routine
1711 */
1713 char *mail_fetch_header (MAILSTREAM *stream,unsigned long msgno,char *section,
1714 STRINGLIST *lines,unsigned long *len,long flags)
1716 STRING bs;
1717 BODY *b = NIL;
1718 SIZEDTEXT *t = NIL,rt;
1719 MESSAGE *m = NIL;
1720 MESSAGECACHE *elt;
1721 char tmp[MAILTMPLEN];
1722 if (len) *len = 0; /* default return size */
1723 if (section && (strlen (section) > (MAILTMPLEN - 20))) return "";
1724 if (flags & FT_UID) { /* UID form of call */
1725 if (msgno = mail_msgno (stream,msgno)) flags &= ~FT_UID;
1726 else return ""; /* must get UID/msgno map first */
1728 elt = mail_elt (stream,msgno);/* get cache data */
1729 if (section && *section) { /* nested body header wanted? */
1730 if (!((b = mail_body (stream,msgno,section)) &&
1731 (b->type == TYPEMESSAGE) && !strcmp (b->subtype,"RFC822")))
1732 return ""; /* lose if no body or not MESSAGE/RFC822 */
1733 m = b->nested.msg; /* point to nested message */
1735 /* else top-level message header wanted */
1736 else m = &elt->private.msg;
1737 if (m->header.text.data && mail_match_lines (lines,m->lines,flags)) {
1738 if (lines) textcpy (t = &stream->text,&m->header.text);
1739 else t = &m->header.text; /* in cache, and cache is valid */
1740 markseen (stream,elt,flags);/* mark message seen */
1743 else if (stream->dtb) { /* not in cache, has live driver? */
1744 if (stream->dtb->msgdata) { /* has driver section fetch? */
1745 /* build driver section specifier */
1746 if (section && *section) sprintf (tmp,"%s.HEADER",section);
1747 else strcpy (tmp,"HEADER");
1748 if ((*stream->dtb->msgdata) (stream,msgno,tmp,0,0,lines,flags)) {
1749 t = &m->header.text; /* fetch data */
1750 /* don't need to postprocess lines */
1751 if (m->lines) lines = NIL;
1752 else if (lines) textcpy (t = &stream->text,&m->header.text);
1755 else if (b) { /* nested body wanted? */
1756 if (stream->private.search.text) {
1757 rt.data = (unsigned char *) stream->private.search.text +
1758 b->nested.msg->header.offset;
1759 rt.size = b->nested.msg->header.text.size;
1760 t = &rt;
1762 else if ((*stream->dtb->text) (stream,msgno,&bs,flags & ~FT_INTERNAL)) {
1763 if ((bs.dtb->next == mail_string_next) && !lines) {
1764 rt.data = (unsigned char *) bs.curpos + b->nested.msg->header.offset;
1765 rt.size = b->nested.msg->header.text.size;
1766 if (stream->private.search.string)
1767 stream->private.search.text = bs.curpos;
1768 t = &rt; /* special hack to avoid extra copy */
1770 else textcpyoffstring (t = &stream->text,&bs,
1771 b->nested.msg->header.offset,
1772 b->nested.msg->header.text.size);
1775 else { /* top-level header fetch */
1776 /* mark message seen */
1777 markseen (stream,elt,flags);
1778 if (rt.data = (unsigned char *)
1779 (*stream->dtb->header) (stream,msgno,&rt.size,flags)) {
1780 /* make a safe copy if need to filter */
1781 if (lines) textcpy (t = &stream->text,&rt);
1782 else t = &rt; /* top level header */
1786 if (!t || !t->data) return "";/* error if no string */
1787 /* filter headers if requested */
1788 if (lines) t->size = mail_filter ((char *) t->data,t->size,lines,flags);
1789 if (len) *len = t->size; /* return size if requested */
1790 return (char *) t->data; /* and text */
1793 /* Mail fetch message text
1794 * Accepts: mail stream
1795 * message # to fetch
1796 * MIME section specifier (#.#.#...#)
1797 * pointer to returned length
1798 * flags
1799 * Returns: message text
1800 */
1802 char *mail_fetch_text (MAILSTREAM *stream,unsigned long msgno,char *section,
1803 unsigned long *len,long flags)
1805 GETS_DATA md;
1806 PARTTEXT *p;
1807 STRING bs;
1808 MESSAGECACHE *elt;
1809 BODY *b = NIL;
1810 char tmp[MAILTMPLEN];
1811 unsigned long i;
1812 if (len) *len = 0; /* default return size */
1813 memset (&stream->private.string,NIL,sizeof (STRING));
1814 if (section && (strlen (section) > (MAILTMPLEN - 20))) return "";
1815 if (flags & FT_UID) { /* UID form of call */
1816 if (msgno = mail_msgno (stream,msgno)) flags &= ~FT_UID;
1817 else return ""; /* must get UID/msgno map first */
1819 elt = mail_elt (stream,msgno);/* get cache data */
1820 if (section && *section) { /* nested body text wanted? */
1821 if (!((b = mail_body (stream,msgno,section)) &&
1822 (b->type == TYPEMESSAGE) && !strcmp (b->subtype,"RFC822")))
1823 return ""; /* lose if no body or not MESSAGE/RFC822 */
1824 p = &b->nested.msg->text; /* point at nested message */
1825 /* build IMAP-format section specifier */
1826 sprintf (tmp,"%s.TEXT",section);
1827 flags &= ~FT_INTERNAL; /* can't win with this set */
1829 else { /* top-level message text wanted */
1830 p = &elt->private.msg.text;
1831 strcpy (tmp,"TEXT");
1833 /* initialize message data identifier */
1834 INIT_GETS (md,stream,msgno,section,0,0);
1835 if (p->text.data) { /* is data already cached? */
1836 markseen (stream,elt,flags);/* mark message seen */
1837 return mail_fetch_text_return (&md,&p->text,len);
1839 if (!stream->dtb) return ""; /* not in cache, must have live driver */
1840 if (stream->dtb->msgdata) return
1841 ((*stream->dtb->msgdata) (stream,msgno,tmp,0,0,NIL,flags) && p->text.data)?
1842 mail_fetch_text_return (&md,&p->text,len) : "";
1843 if (!(*stream->dtb->text) (stream,msgno,&bs,flags)) return "";
1844 if (section && *section) { /* nested is more complex */
1845 SETPOS (&bs,p->offset);
1846 i = p->text.size; /* just want this much */
1848 else i = SIZE (&bs); /* want entire text */
1849 return mail_fetch_string_return (&md,&bs,i,len,flags);
1852 /* Mail fetch message body part MIME headers
1853 * Accepts: mail stream
1854 * message # to fetch
1855 * MIME section specifier (#.#.#...#)
1856 * pointer to returned length
1857 * flags
1858 * Returns: message text
1859 */
1861 char *mail_fetch_mime (MAILSTREAM *stream,unsigned long msgno,char *section,
1862 unsigned long *len,long flags)
1864 PARTTEXT *p;
1865 STRING bs;
1866 BODY *b;
1867 char tmp[MAILTMPLEN];
1868 if (len) *len = 0; /* default return size */
1869 if (section && (strlen (section) > (MAILTMPLEN - 20))) return "";
1870 if (flags & FT_UID) { /* UID form of call */
1871 if (msgno = mail_msgno (stream,msgno)) flags &= ~FT_UID;
1872 else return ""; /* must get UID/msgno map first */
1874 flags &= ~FT_INTERNAL; /* can't win with this set */
1875 if (!(section && *section && (b = mail_body (stream,msgno,section))))
1876 return ""; /* not valid section */
1877 /* in cache? */
1878 if ((p = &b->mime)->text.data) {
1879 /* mark message seen */
1880 markseen (stream,mail_elt (stream,msgno),flags);
1881 if (len) *len = p->text.size;
1882 return (char *) p->text.data;
1884 if (!stream->dtb) return ""; /* not in cache, must have live driver */
1885 if (stream->dtb->msgdata) { /* has driver fetch? */
1886 /* build driver section specifier */
1887 sprintf (tmp,"%s.MIME",section);
1888 if ((*stream->dtb->msgdata) (stream,msgno,tmp,0,0,NIL,flags) &&
1889 p->text.data) {
1890 if (len) *len = p->text.size;
1891 return (char *) p->text.data;
1893 else return "";
1895 if (len) *len = b->mime.text.size;
1896 if (!b->mime.text.size) { /* empty MIME header -- mark seen anyway */
1897 markseen (stream,mail_elt (stream,msgno),flags);
1898 return "";
1900 /* have to get it from offset */
1901 if (stream->private.search.text)
1902 return stream->private.search.text + b->mime.offset;
1903 if (!(*stream->dtb->text) (stream,msgno,&bs,flags)) {
1904 if (len) *len = 0;
1905 return "";
1907 if (bs.dtb->next == mail_string_next) {
1908 if (stream->private.search.string) stream->private.search.text = bs.curpos;
1909 return bs.curpos + b->mime.offset;
1911 return textcpyoffstring (&stream->text,&bs,b->mime.offset,b->mime.text.size);
1914 /* Mail fetch message body part
1915 * Accepts: mail stream
1916 * message # to fetch
1917 * MIME section specifier (#.#.#...#)
1918 * pointer to returned length
1919 * flags
1920 * Returns: message body
1921 */
1923 char *mail_fetch_body (MAILSTREAM *stream,unsigned long msgno,char *section,
1924 unsigned long *len,long flags)
1926 GETS_DATA md;
1927 PARTTEXT *p;
1928 STRING bs;
1929 BODY *b;
1930 SIZEDTEXT *t;
1931 char *s,tmp[MAILTMPLEN];
1932 memset (&stream->private.string,NIL,sizeof (STRING));
1933 if (!(section && *section)) /* top-level text wanted? */
1934 return mail_fetch_message (stream,msgno,len,flags);
1935 else if (strlen (section) > (MAILTMPLEN - 20)) return "";
1936 flags &= ~FT_INTERNAL; /* can't win with this set */
1937 /* initialize message data identifier */
1938 INIT_GETS (md,stream,msgno,section,0,0);
1939 /* kludge for old section 0 header */
1940 if (!strcmp (s = strcpy (tmp,section),"0") ||
1941 ((s = strstr (tmp,".0")) && !s[2])) {
1942 SIZEDTEXT ht;
1943 *s = '\0'; /* tie off section */
1944 /* this silly way so it does mailgets */
1945 ht.data = (unsigned char *) mail_fetch_header (stream,msgno,
1946 tmp[0] ? tmp : NIL,NIL,
1947 &ht.size,flags);
1948 /* may have UIDs here */
1949 md.flags = (flags & FT_UID) ? MG_UID : NIL;
1950 return mail_fetch_text_return (&md,&ht,len);
1952 if (len) *len = 0; /* default return size */
1953 if (flags & FT_UID) { /* UID form of call */
1954 if (msgno = mail_msgno (stream,msgno)) flags &= ~FT_UID;
1955 else return ""; /* must get UID/msgno map first */
1957 /* must have body */
1958 if (!(b = mail_body (stream,msgno,section))) return "";
1959 /* have cached text? */
1960 if ((t = &(p = &b->contents)->text)->data) {
1961 /* mark message seen */
1962 markseen (stream,mail_elt (stream,msgno),flags);
1963 return mail_fetch_text_return (&md,t,len);
1965 if (!stream->dtb) return ""; /* not in cache, must have live driver */
1966 if (stream->dtb->msgdata) return
1967 ((*stream->dtb->msgdata)(stream,msgno,section,0,0,NIL,flags) && t->data) ?
1968 mail_fetch_text_return (&md,t,len) : "";
1969 if (len) *len = t->size;
1970 if (!t->size) { /* empty body part -- mark seen anyway */
1971 markseen (stream,mail_elt (stream,msgno),flags);
1972 return "";
1974 /* copy body from stringstruct offset */
1975 if (stream->private.search.text)
1976 return stream->private.search.text + p->offset;
1977 if (!(*stream->dtb->text) (stream,msgno,&bs,flags)) {
1978 if (len) *len = 0;
1979 return "";
1981 if (bs.dtb->next == mail_string_next) {
1982 if (stream->private.search.string) stream->private.search.text = bs.curpos;
1983 return bs.curpos + p->offset;
1985 SETPOS (&bs,p->offset);
1986 return mail_fetch_string_return (&md,&bs,t->size,len,flags);
1989 /* Mail fetch partial message text
1990 * Accepts: mail stream
1991 * message # to fetch
1992 * MIME section specifier (#.#.#...#)
1993 * offset of first designed byte or 0 to start at beginning
1994 * maximum number of bytes or 0 for all bytes
1995 * flags
1996 * Returns: T if successful, else NIL
1997 */
1999 long mail_partial_text (MAILSTREAM *stream,unsigned long msgno,char *section,
2000 unsigned long first,unsigned long last,long flags)
2002 GETS_DATA md;
2003 PARTTEXT *p = NIL;
2004 MESSAGECACHE *elt;
2005 STRING bs;
2006 BODY *b;
2007 char tmp[MAILTMPLEN];
2008 unsigned long i;
2009 if (!mailgets) fatal ("mail_partial_text() called without a mailgets!");
2010 if (section && (strlen (section) > (MAILTMPLEN - 20))) return NIL;
2011 if (flags & FT_UID) { /* UID form of call */
2012 if (msgno = mail_msgno (stream,msgno)) flags &= ~FT_UID;
2013 else return NIL; /* must get UID/msgno map first */
2015 elt = mail_elt (stream,msgno);/* get cache data */
2016 flags &= ~FT_INTERNAL; /* bogus if this is set */
2017 if (section && *section) { /* nested body text wanted? */
2018 if (!((b = mail_body (stream,msgno,section)) &&
2019 (b->type == TYPEMESSAGE) && !strcmp (b->subtype,"RFC822")))
2020 return NIL; /* lose if no body or not MESSAGE/RFC822 */
2021 p = &b->nested.msg->text; /* point at nested message */
2022 /* build IMAP-format section specifier */
2023 sprintf (tmp,"%s.TEXT",section);
2025 else { /* else top-level message text wanted */
2026 p = &elt->private.msg.text;
2027 strcpy (tmp,"TEXT");
2030 /* initialize message data identifier */
2031 INIT_GETS (md,stream,msgno,tmp,first,last);
2032 if (p->text.data) { /* is data already cached? */
2033 INIT (&bs,mail_string,p->text.data,i = p->text.size);
2034 markseen (stream,elt,flags);/* mark message seen */
2036 else { /* else get data from driver */
2037 if (!stream->dtb) return NIL;
2038 if (stream->dtb->msgdata) /* driver will handle this */
2039 return (*stream->dtb->msgdata) (stream,msgno,tmp,first,last,NIL,flags);
2040 if (!(*stream->dtb->text) (stream,msgno,&bs,flags)) return NIL;
2041 if (section && *section) { /* nexted if more complex */
2042 SETPOS (&bs,p->offset); /* offset stringstruct to data */
2043 i = p->text.size; /* maximum size of data */
2045 else i = SIZE (&bs); /* just want this much */
2047 if (i <= first) i = first = 0;/* first byte is beyond end of text */
2048 /* truncate as needed */
2049 else { /* offset and truncate */
2050 SETPOS (&bs,first + GETPOS (&bs));
2051 i -= first; /* reduced size */
2052 if (last && (i > last)) i = last;
2054 /* do the mailgets thing */
2055 (*mailgets) (mail_read,&bs,i,&md);
2056 return T; /* success */
2059 /* Mail fetch partial message body part
2060 * Accepts: mail stream
2061 * message # to fetch
2062 * MIME section specifier (#.#.#...#)
2063 * offset of first designed byte or 0 to start at beginning
2064 * maximum number of bytes or 0 for all bytes
2065 * flags
2066 * Returns: T if successful, else NIL
2067 */
2069 long mail_partial_body (MAILSTREAM *stream,unsigned long msgno,char *section,
2070 unsigned long first,unsigned long last,long flags)
2072 GETS_DATA md;
2073 PARTTEXT *p;
2074 STRING bs;
2075 BODY *b;
2076 SIZEDTEXT *t;
2077 unsigned long i;
2078 if (!(section && *section)) /* top-level text wanted? */
2079 return mail_partial_text (stream,msgno,NIL,first,last,flags);
2080 if (!mailgets) fatal ("mail_partial_body() called without a mailgets!");
2081 if (flags & FT_UID) { /* UID form of call */
2082 if (msgno = mail_msgno (stream,msgno)) flags &= ~FT_UID;
2083 else return NIL; /* must get UID/msgno map first */
2085 /* must have body */
2086 if (!(b = mail_body (stream,msgno,section))) return NIL;
2087 flags &= ~FT_INTERNAL; /* bogus if this is set */
2089 /* initialize message data identifier */
2090 INIT_GETS (md,stream,msgno,section,first,last);
2091 /* have cached text? */
2092 if ((t = &(p = &b->contents)->text)->data) {
2093 /* mark message seen */
2094 markseen (stream,mail_elt (stream,msgno),flags);
2095 INIT (&bs,mail_string,t->data,i = t->size);
2097 else { /* else get data from driver */
2098 if (!stream->dtb) return NIL;
2099 if (stream->dtb->msgdata) /* driver will handle this */
2100 return (*stream->dtb->msgdata) (stream,msgno,section,first,last,NIL,
2101 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 = t->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 else { /* offset and truncate */
2111 SETPOS (&bs,first + GETPOS (&bs));
2112 i -= first; /* reduced size */
2113 if (last && (i > last)) i = last;
2115 /* do the mailgets thing */
2116 (*mailgets) (mail_read,&bs,i,&md);
2117 return T; /* success */
2120 /* Mail return message text
2121 * Accepts: identifier data
2122 * sized text
2123 * pointer to returned length
2124 * Returns: text
2125 */
2127 char *mail_fetch_text_return (GETS_DATA *md,SIZEDTEXT *t,unsigned long *len)
2129 STRING bs;
2130 if (len) *len = t->size; /* return size */
2131 if (t->size && mailgets) { /* have to do the mailgets thing? */
2132 /* silly but do it anyway for consistency */
2133 INIT (&bs,mail_string,t->data,t->size);
2134 return (*mailgets) (mail_read,&bs,t->size,md);
2136 return t->size ? (char *) t->data : "";
2140 /* Mail return message string
2141 * Accepts: identifier data
2142 * stringstruct
2143 * text length
2144 * pointer to returned length
2145 * flags
2146 * Returns: text, or NIL if stringstruct returned
2147 */
2149 char *mail_fetch_string_return (GETS_DATA *md,STRING *bs,unsigned long i,
2150 unsigned long *len,long flags)
2152 char *ret = NIL;
2153 if (len) *len = i; /* return size */
2154 /* return stringstruct hack */
2155 if (flags & FT_RETURNSTRINGSTRUCT) {
2156 memcpy (&md->stream->private.string,bs,sizeof (STRING));
2157 SETPOS (&md->stream->private.string,GETPOS (&md->stream->private.string));
2159 /* have to do the mailgets thing? */
2160 else if (mailgets) ret = (*mailgets) (mail_read,bs,i,md);
2161 /* special hack to avoid extra copy */
2162 else if (bs->dtb->next == mail_string_next) ret = bs->curpos;
2163 /* make string copy in memory */
2164 else ret = textcpyoffstring (&md->stream->text,bs,GETPOS (bs),i);
2165 return ret;
2168 /* Read data from stringstruct
2169 * Accepts: stringstruct
2170 * size of data to read
2171 * buffer to read into
2172 * Returns: T, always, stringstruct updated
2173 */
2175 long mail_read (void *stream,unsigned long size,char *buffer)
2177 unsigned long i;
2178 STRING *s = (STRING *) stream;
2179 while (size) { /* until satisfied */
2180 memcpy (buffer,s->curpos,i = min (s->cursize,size));
2181 buffer += i; /* update buffer */
2182 size -= i; /* note that we read this much */
2183 s->curpos += --i; /* advance that many spaces minus 1 */
2184 s->cursize -= i;
2185 SNX (s); /* now use SNX to advance the last byte */
2187 return T;
2190 /* Mail fetch UID
2191 * Accepts: mail stream
2192 * message number
2193 * Returns: UID or zero if dead stream
2194 */
2196 unsigned long mail_uid (MAILSTREAM *stream,unsigned long msgno)
2198 unsigned long uid = mail_elt (stream,msgno)->private.uid;
2199 return uid ? uid :
2200 (stream->dtb && stream->dtb->uid) ? (*stream->dtb->uid) (stream,msgno) : 0;
2204 /* Mail fetch msgno from UID
2205 * Accepts: mail stream
2206 * UID
2207 * Returns: msgno or zero if failed
2208 */
2210 unsigned long mail_msgno (MAILSTREAM *stream,unsigned long uid)
2212 unsigned long msgno,delta,first,firstuid,last,lastuid,middle,miduid;
2213 if (stream->dtb) { /* active stream? */
2214 if (stream->dtb->msgno) /* direct way */
2215 return (*stream->dtb->msgno) (stream,uid);
2216 else if (stream->dtb->uid) {/* indirect way */
2217 /* Placeholder for now, since currently there are no drivers which
2218 * have a uid method but not a msgno method
2219 */
2220 for (msgno = 1; msgno <= stream->nmsgs; msgno++)
2221 if ((*stream->dtb->uid) (stream,msgno) == uid) return msgno;
2223 /* binary search since have full map */
2224 else for (first = 1,last = stream->nmsgs, delta = (first <= last) ? 1 : 0;
2225 delta &&
2226 (uid >= (firstuid = mail_elt (stream,first)->private.uid)) &&
2227 (uid <= (lastuid = mail_elt (stream,last)->private.uid));) {
2228 /* done if match at an endpoint */
2229 if (uid == firstuid) return first;
2230 if (uid == lastuid) return last;
2231 /* have anything between endpoints? */
2232 if (delta = ((last - first) / 2)) {
2233 if ((miduid = mail_elt (stream,middle = first + delta)->private.uid)
2234 == uid)
2235 return middle; /* found match in middle */
2236 else if (uid < miduid) last = middle - 1;
2237 else first = middle + 1;
2241 else { /* dead stream, do linear search for UID */
2242 for (msgno = 1; msgno <= stream->nmsgs; msgno++)
2243 if (mail_elt (stream,msgno)->private.uid == uid) return msgno;
2245 return 0; /* didn't find the UID anywhere */
2248 /* Mail fetch From string for menu
2249 * Accepts: destination string
2250 * mail stream
2251 * message # to fetch
2252 * desired string length
2253 * Returns: string of requested length
2254 */
2256 void mail_fetchfrom (char *s,MAILSTREAM *stream,unsigned long msgno,
2257 long length)
2259 char *t;
2260 char tmp[MAILTMPLEN];
2261 ENVELOPE *env = mail_fetchenvelope (stream,msgno);
2262 ADDRESS *adr = env ? env->from : NIL;
2263 memset (s,' ',(size_t)length);/* fill it with spaces */
2264 s[length] = '\0'; /* tie off with null */
2265 /* get first from address from envelope */
2266 while (adr && !adr->host) adr = adr->next;
2267 if (adr) { /* if a personal name exists use it */
2268 if (!(t = adr->personal))
2269 sprintf (t = tmp,"%.256s@%.256s",adr->mailbox,adr->host);
2270 memcpy (s,t,(size_t) min (length,(long) strlen (t)));
2275 /* Mail fetch Subject string for menu
2276 * Accepts: destination string
2277 * mail stream
2278 * message # to fetch
2279 * desired string length
2280 * Returns: string of no more than requested length
2281 */
2283 void mail_fetchsubject (char *s,MAILSTREAM *stream,unsigned long msgno,
2284 long length)
2286 ENVELOPE *env = mail_fetchenvelope (stream,msgno);
2287 memset (s,'\0',(size_t) length+1);
2288 /* copy subject from envelope */
2289 if (env && env->subject) strncpy (s,env->subject,(size_t) length);
2290 else *s = ' '; /* if no subject then just a space */
2293 /* Mail modify flags
2294 * Accepts: mail stream
2295 * sequence
2296 * flag(s)
2297 * option flags
2298 */
2300 void mail_flag (MAILSTREAM *stream,char *sequence,char *flag,long flags)
2302 MESSAGECACHE *elt;
2303 unsigned long i,uf;
2304 long f;
2305 short nf;
2306 if (!stream->dtb) return; /* no-op if no stream */
2307 if ((stream->dtb->flagmsg || !stream->dtb->flag) &&
2308 ((flags & ST_UID) ? mail_uid_sequence (stream,sequence) :
2309 mail_sequence (stream,sequence)) &&
2310 ((f = mail_parse_flags (stream,flag,&uf)) || uf))
2311 for (i = 1,nf = (flags & ST_SET) ? T : NIL; i <= stream->nmsgs; i++)
2312 if ((elt = mail_elt (stream,i))->sequence) {
2313 struct { /* old flags */
2314 unsigned int valid : 1;
2315 unsigned int seen : 1;
2316 unsigned int deleted : 1;
2317 unsigned int flagged : 1;
2318 unsigned int answered : 1;
2319 unsigned int draft : 1;
2320 unsigned long user_flags;
2321 } old;
2322 old.valid = elt->valid; old.seen = elt->seen;
2323 old.deleted = elt->deleted; old.flagged = elt->flagged;
2324 old.answered = elt->answered; old.draft = elt->draft;
2325 old.user_flags = elt->user_flags;
2326 elt->valid = NIL; /* prepare for flag alteration */
2327 if (stream->dtb->flagmsg) (*stream->dtb->flagmsg) (stream,elt);
2328 if (f&fSEEN) elt->seen = nf;
2329 if (f&fDELETED) elt->deleted = nf;
2330 if (f&fFLAGGED) elt->flagged = nf;
2331 if (f&fANSWERED) elt->answered = nf;
2332 if (f&fDRAFT) elt->draft = nf;
2333 /* user flags */
2334 if (flags & ST_SET) elt->user_flags |= uf;
2335 else elt->user_flags &= ~uf;
2336 elt->valid = T; /* flags now altered */
2337 if ((old.valid != elt->valid) || (old.seen != elt->seen) ||
2338 (old.deleted != elt->deleted) || (old.flagged != elt->flagged) ||
2339 (old.answered != elt->answered) || (old.draft != elt->draft) ||
2340 (old.user_flags != elt->user_flags))
2341 MM_FLAGS (stream,elt->msgno);
2342 if (stream->dtb->flagmsg) (*stream->dtb->flagmsg) (stream,elt);
2344 /* call driver once */
2345 if (stream->dtb->flag) (*stream->dtb->flag) (stream,sequence,flag,flags);
2348 /* Mail search for messages
2349 * Accepts: mail stream
2350 * character set
2351 * search program
2352 * option flags
2353 * Returns: T if successful, NIL if dead stream, NIL searchpgm or bad charset
2354 */
2356 long mail_search_full (MAILSTREAM *stream,char *charset,SEARCHPGM *pgm,
2357 long flags)
2359 unsigned long i;
2360 long ret = NIL;
2361 if (!(flags & SE_RETAIN)) /* clear search vector unless retaining */
2362 for (i = 1; i <= stream->nmsgs; ++i) mail_elt (stream,i)->searched = NIL;
2363 if (pgm && stream->dtb) /* must have a search program and driver */
2364 ret = (*(stream->dtb->search ? stream->dtb->search : mail_search_default))
2365 (stream,charset,pgm,flags);
2366 /* flush search program if requested */
2367 if (flags & SE_FREE) mail_free_searchpgm (&pgm);
2368 return ret;
2372 /* Mail search for messages default handler
2373 * Accepts: mail stream
2374 * character set
2375 * search program
2376 * option flags
2377 * Returns: T if successful, NIL if bad charset
2378 */
2380 long mail_search_default (MAILSTREAM *stream,char *charset,SEARCHPGM *pgm,
2381 long flags)
2383 unsigned long i;
2384 char *msg;
2385 /* make sure that charset is good */
2386 if (msg = utf8_badcharset (charset)) {
2387 MM_LOG (msg,ERROR); /* output error */
2388 fs_give ((void **) &msg);
2389 return NIL;
2391 utf8_searchpgm (pgm,charset);
2392 for (i = 1; i <= stream->nmsgs; ++i)
2393 if (mail_search_msg (stream,i,NIL,pgm)) {
2394 if (flags & SE_UID) mm_searched (stream,mail_uid (stream,i));
2395 else { /* mark as searched, notify mail program */
2396 mail_elt (stream,i)->searched = T;
2397 if (!stream->silent) mm_searched (stream,i);
2400 return LONGT; /* search completed */
2403 /* Mail ping mailbox
2404 * Accepts: mail stream
2405 * Returns: stream if still open else NIL
2406 */
2408 long mail_ping (MAILSTREAM *stream)
2410 unsigned long i,n,uf,len;
2411 char *s,*f,tmp[MAILTMPLEN],flags[MAILTMPLEN];
2412 MAILSTREAM *snarf;
2413 MESSAGECACHE *elt;
2414 STRING bs;
2415 long ret;
2416 /* do driver action */
2417 if ((ret = ((stream && stream->dtb) ? (stream->dtb->ping) (stream) : NIL)) &&
2418 stream->snarf.name && /* time to snarf? */
2419 /* prohibit faster than once/min */
2420 (time (0) > (time_t) (stream->snarf.time + min(60,mailsnarfinterval))) &&
2421 (snarf = mail_open (NIL,stream->snarf.name,
2422 stream->snarf.options | OP_SILENT))) {
2423 if ((n = snarf->nmsgs) && /* yes, have messages to snarf? */
2424 mail_search_full (snarf,NIL,mail_criteria ("UNDELETED"),SE_FREE)) {
2425 for (i = 1; ret && (i <= n); i++) /* for each message */
2426 if ((elt = mail_elt (snarf,i))->searched &&
2427 (s = mail_fetch_message (snarf,i,&len,FT_PEEK)) && len) {
2428 INIT (&bs,mail_string,s,len);
2429 if (mailsnarfpreserve) {
2430 /* yes, make sure have fast data */
2431 if (!elt->valid || !elt->day) {
2432 sprintf (tmp,"%lu",n);
2433 mail_fetch_fast (snarf,tmp,NIL);
2435 /* initialize flag string */
2436 memset (flags,0,MAILTMPLEN);
2437 /* output system flags except \Deleted */
2438 if (elt->seen) strcat (flags," \\Seen");
2439 if (elt->flagged) strcat (flags," \\Flagged");
2440 if (elt->answered) strcat (flags," \\Answered");
2441 if (elt->draft) strcat (flags," \\Draft");
2442 /* any user flags? */
2443 for (uf = elt->user_flags,s = flags + strlen (flags);
2444 uf && (f = stream->user_flags[find_rightmost_bit (&uf)]) &&
2445 ((MAILTMPLEN - (s - tmp)) > (long) (2 + strlen (f)));
2446 s += strlen (s)) sprintf (s," %s",f);
2447 ret = mail_append_full (stream,stream->mailbox,flags + 1,
2448 mail_date (tmp,elt),&bs);
2450 else ret = mail_append (stream,stream->mailbox,&bs);
2452 if (ret) { /* did snarf succeed? */
2453 /* driver has per-message (or no) flag call */
2454 if (snarf->dtb->flagmsg || !snarf->dtb->flag) {
2455 elt->valid = NIL; /* prepare for flag alteration */
2456 if (snarf->dtb->flagmsg) (*snarf->dtb->flagmsg) (snarf,elt);
2457 /* flags now altered */
2458 elt->deleted = elt->seen = elt->valid = T;
2459 if (snarf->dtb->flagmsg) (*snarf->dtb->flagmsg) (snarf,elt);
2461 /* driver has one-time flag call */
2462 if (snarf->dtb->flag) {
2463 sprintf (tmp,"%lu",i);
2464 (*snarf->dtb->flag) (snarf,tmp,"\\Deleted \\Seen",ST_SET);
2467 else { /* copy failed */
2468 sprintf (tmp,"Unable to move message %lu from %s mailbox",
2469 i,snarf->dtb->name);
2470 mm_log (tmp,WARN);
2474 /* expunge the messages */
2475 mail_close_full (snarf,n ? CL_EXPUNGE : NIL);
2476 stream->snarf.time = (unsigned long) time (0);
2477 /* Even if the snarf failed, we don't want to return NIL if the stream
2478 * is still alive. Or at least that's what we currently think.
2479 */
2480 /* redo the driver's action */
2481 ret = stream->dtb ? (*stream->dtb->ping) (stream) : NIL;
2483 return ret;
2486 /* Mail check mailbox
2487 * Accepts: mail stream
2488 */
2490 void mail_check (MAILSTREAM *stream)
2492 /* do the driver's action */
2493 if (stream->dtb) (*stream->dtb->check) (stream);
2497 /* Mail expunge mailbox
2498 * Accepts: mail stream
2499 * sequence to expunge if non-NIL
2500 * expunge options
2501 * Returns: T on success, NIL on failure
2502 */
2504 long mail_expunge_full (MAILSTREAM *stream,char *sequence,long options)
2506 /* do the driver's action */
2507 return stream->dtb ? (*stream->dtb->expunge) (stream,sequence,options) : NIL;
2511 /* Mail copy message(s)
2512 * Accepts: mail stream
2513 * sequence
2514 * destination mailbox
2515 * flags
2516 */
2518 long mail_copy_full (MAILSTREAM *stream,char *sequence,char *mailbox,
2519 long options)
2521 return stream->dtb ?
2522 SAFE_COPY (stream->dtb,stream,sequence,mailbox,options) : NIL;
2525 /* Append data package to use for old single-message mail_append() interface */
2527 typedef struct mail_append_package {
2528 char *flags; /* initial flags */
2529 char *date; /* message internal date */
2530 STRING *message; /* stringstruct of message */
2531 } APPENDPACKAGE;
2534 /* Single append message string
2535 * Accepts: mail stream
2536 * package pointer (cast as a void *)
2537 * pointer to return initial flags
2538 * pointer to return message internal date
2539 * pointer to return stringstruct of message to append
2540 * Returns: T, always
2541 */
2543 static long mail_append_single (MAILSTREAM *stream,void *data,char **flags,
2544 char **date,STRING **message)
2546 APPENDPACKAGE *ap = (APPENDPACKAGE *) data;
2547 *flags = ap->flags; /* get desired data from the package */
2548 *date = ap->date;
2549 *message = ap->message;
2550 ap->message = NIL; /* so next callback puts a stop to it */
2551 return LONGT; /* always return success */
2555 /* Mail append message string
2556 * Accepts: mail stream
2557 * destination mailbox
2558 * initial flags
2559 * message internal date
2560 * stringstruct of message to append
2561 * Returns: T on success, NIL on failure
2562 */
2564 long mail_append_full (MAILSTREAM *stream,char *mailbox,char *flags,char *date,
2565 STRING *message)
2567 APPENDPACKAGE ap;
2568 ap.flags = flags; /* load append package */
2569 ap.date = date;
2570 ap.message = message;
2571 return mail_append_multiple (stream,mailbox,mail_append_single,(void *) &ap);
2574 /* Mail append message(s)
2575 * Accepts: mail stream
2576 * destination mailbox
2577 * append data callback
2578 * arbitrary data for callback use
2579 * Returns: T on success, NIL on failure
2580 */
2582 long mail_append_multiple (MAILSTREAM *stream,char *mailbox,append_t af,
2583 void *data)
2585 char *s,tmp[MAILTMPLEN];
2586 DRIVER *d = NIL;
2587 long ret = NIL;
2588 /* never allow names with newlines */
2589 if (strpbrk (mailbox,"\015\012"))
2590 MM_LOG ("Can't append to mailbox with such a name",ERROR);
2591 else if (strlen (mailbox) >=
2592 (NETMAXHOST+(NETMAXUSER*2)+NETMAXMBX+NETMAXSRV+50)) {
2593 sprintf (tmp,"Can't append %.80s: %s",mailbox,(*mailbox == '{') ?
2594 "invalid remote specification" : "no such mailbox");
2595 MM_LOG (tmp,ERROR);
2597 /* special driver hack? */
2598 else if (!strncmp (lcase (strcpy (tmp,mailbox)),"#driver.",8)) {
2599 /* yes, tie off name at likely delimiter */
2600 if (!(s = strpbrk (tmp+8,"/\\:"))) {
2601 sprintf (tmp,"Can't append to mailbox %.80s: bad driver syntax",mailbox);
2602 MM_LOG (tmp,ERROR);
2603 return NIL;
2605 *s++ = '\0'; /* tie off at delimiter */
2606 if (!(d = (DRIVER *) mail_parameters (NIL,GET_DRIVER,tmp+8))) {
2607 sprintf (tmp,"Can't append to mailbox %.80s: unknown driver",mailbox);
2608 MM_LOG (tmp,ERROR);
2610 else ret = SAFE_APPEND (d,stream,mailbox + (s - tmp),af,data);
2612 else if (d = mail_valid (stream,mailbox,NIL))
2613 ret = SAFE_APPEND (d,stream,mailbox,af,data);
2614 /* No driver, try for TRYCREATE if no stream. Note that we use the
2615 * createProto here, not the appendProto, since the dummy driver already
2616 * took care of the appendProto case. Otherwise, if appendProto is set to
2617 * NIL, we won't get a TRYCREATE.
2618 */
2619 else if (!stream && (stream = default_proto (NIL)) && stream->dtb &&
2620 SAFE_APPEND (stream->dtb,stream,mailbox,af,data))
2621 /* timing race? */
2622 MM_NOTIFY (stream,"Append validity confusion",WARN);
2623 /* generate error message */
2624 else mail_valid (stream,mailbox,"append to mailbox");
2625 return ret;
2628 /* Mail garbage collect stream
2629 * Accepts: mail stream
2630 * garbage collection flags
2631 */
2633 void mail_gc (MAILSTREAM *stream,long gcflags)
2635 MESSAGECACHE *elt;
2636 unsigned long i;
2637 /* do the driver's action first */
2638 if (stream->dtb && stream->dtb->gc) (*stream->dtb->gc) (stream,gcflags);
2639 stream->msgno = 0; /* nothing cached now */
2640 if (gcflags & GC_ENV) { /* garbage collect envelopes? */
2641 if (stream->env) mail_free_envelope (&stream->env);
2642 if (stream->body) mail_free_body (&stream->body);
2644 if (gcflags & GC_TEXTS) { /* free texts */
2645 if (stream->text.data) fs_give ((void **) &stream->text.data);
2646 stream->text.size = 0;
2648 /* garbage collect per-message stuff */
2649 for (i = 1; i <= stream->nmsgs; i++)
2650 if (elt = (MESSAGECACHE *) (*mailcache) (stream,i,CH_ELT))
2651 mail_gc_msg (&elt->private.msg,gcflags);
2655 /* Mail garbage collect message
2656 * Accepts: message structure
2657 * garbage collection flags
2658 */
2660 void mail_gc_msg (MESSAGE *msg,long gcflags)
2662 if (gcflags & GC_ENV) { /* garbage collect envelopes? */
2663 mail_free_envelope (&msg->env);
2664 mail_free_body (&msg->body);
2666 if (gcflags & GC_TEXTS) { /* garbage collect texts */
2667 if (msg->full.text.data) fs_give ((void **) &msg->full.text.data);
2668 if (msg->header.text.data) {
2669 mail_free_stringlist (&msg->lines);
2670 fs_give ((void **) &msg->header.text.data);
2672 if (msg->text.text.data) fs_give ((void **) &msg->text.text.data);
2673 /* now GC all body components */
2674 if (msg->body) mail_gc_body (msg->body);
2678 /* Mail garbage collect texts in BODY structure
2679 * Accepts: BODY structure
2680 */
2682 void mail_gc_body (BODY *body)
2684 PART *part;
2685 switch (body->type) { /* free contents */
2686 case TYPEMULTIPART: /* multiple part */
2687 for (part = body->nested.part; part; part = part->next)
2688 mail_gc_body (&part->body);
2689 break;
2690 case TYPEMESSAGE: /* encapsulated message */
2691 if (body->subtype && !strcmp (body->subtype,"RFC822")) {
2692 mail_free_stringlist (&body->nested.msg->lines);
2693 mail_gc_msg (body->nested.msg,GC_TEXTS);
2695 break;
2696 default:
2697 break;
2699 if (body->mime.text.data) fs_give ((void **) &body->mime.text.data);
2700 if (body->contents.text.data) fs_give ((void **) &body->contents.text.data);
2703 /* Mail get body part
2704 * Accepts: mail stream
2705 * message number
2706 * section specifier
2707 * Returns: pointer to body
2708 */
2710 BODY *mail_body (MAILSTREAM *stream,unsigned long msgno,unsigned char *section)
2712 BODY *b = NIL;
2713 PART *pt;
2714 unsigned long i;
2715 /* make sure have a body */
2716 if (section && *section && mail_fetchstructure (stream,msgno,&b) && b)
2717 while (*section) { /* find desired section */
2718 if (isdigit (*section)) { /* get section specifier */
2719 /* make sure what follows is valid */
2720 if (!(i = strtoul (section,(char **) &section,10)) ||
2721 (*section && ((*section++ != '.') || !*section))) return NIL;
2722 /* multipart content? */
2723 if (b->type == TYPEMULTIPART) {
2724 /* yes, find desired part */
2725 if (pt = b->nested.part) while (--i && (pt = pt->next));
2726 if (!pt) return NIL; /* bad specifier */
2727 b = &pt->body; /* note new body */
2729 /* otherwise must be section 1 */
2730 else if (i != 1) return NIL;
2731 /* need to go down further? */
2732 if (*section) switch (b->type) {
2733 case TYPEMULTIPART: /* multipart */
2734 break;
2735 case TYPEMESSAGE: /* embedded message */
2736 if (!strcmp (b->subtype,"RFC822")) {
2737 b = b->nested.msg->body;
2738 break;
2740 default: /* bogus subpart specification */
2741 return NIL;
2744 else return NIL; /* unknown section specifier */
2746 return b;
2749 /* Mail output date from elt fields
2750 * Accepts: character string to write into
2751 * elt to get data data from
2752 * Returns: the character string
2753 */
2755 const char *days[] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
2757 const char *months[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
2758 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
2760 char *mail_date (char *string,MESSAGECACHE *elt)
2762 sprintf (string,"%2d-%s-%d %02d:%02d:%02d %c%02d%02d",
2763 elt->day ? elt->day : 1,
2764 months[elt->month ? (elt->month - 1) : 0],
2765 elt->year + BASEYEAR,elt->hours,elt->minutes,elt->seconds,
2766 elt->zoccident ? '-' : '+',elt->zhours,elt->zminutes);
2767 return string;
2771 /* Mail output extended-ctime format date from elt fields
2772 * Accepts: character string to write into
2773 * elt to get data data from
2774 * Returns: the character string
2775 */
2777 char *mail_cdate (char *string,MESSAGECACHE *elt)
2779 char *fmt = "%s %s %2d %02d:%02d:%02d %4d %s%02d%02d\n";
2780 int d = elt->day ? elt->day : 1;
2781 int m = elt->month ? (elt->month - 1) : 0;
2782 int y = elt->year + BASEYEAR;
2783 const char *s = months[m];
2784 if (m < 2) { /* if before March, */
2785 m += 10; /* January = month 10 of previous year */
2786 y--;
2788 else m -= 2; /* March is month 0 */
2789 sprintf (string,fmt,days[(int) (d + 2 + ((7 + 31 * m) / 12)
2790 #ifndef USEJULIANCALENDAR
2791 #ifndef USEORTHODOXCALENDAR /* Gregorian calendar */
2792 + (y / 400)
2793 #ifdef Y4KBUGFIX
2794 - (y / 4000)
2795 #endif
2796 #else /* Orthodox calendar */
2797 + (2 * (y / 900)) + ((y % 900) >= 200)
2798 + ((y % 900) >= 600)
2799 #endif
2800 - (y / 100)
2801 #endif
2802 + y + (y / 4)) % 7],
2803 s,d,elt->hours,elt->minutes,elt->seconds,elt->year + BASEYEAR,
2804 elt->zoccident ? "-" : "+",elt->zhours,elt->zminutes);
2805 return string;
2808 /* Mail parse date into elt fields
2809 * Accepts: elt to write into
2810 * date string to parse
2811 * Returns: T if parse successful, else NIL
2812 * This routine parses dates as follows:
2813 * . leading three alphas followed by comma and space are ignored
2814 * . date accepted in format: mm/dd/yy, mm/dd/yyyy, dd-mmm-yy, dd-mmm-yyyy,
2815 * dd mmm yy, dd mmm yyyy, yyyy-mm-dd, yyyymmdd
2816 * . two and three digit years interpreted according to RFC 2822 rules
2817 * . mandatory end of string if yyyy-mm-dd or yyyymmdd; otherwise optional
2818 * space followed by time:
2819 * . time accepted in format hh:mm:ss or hh:mm
2820 * . end of string accepted
2821 * . timezone accepted: hyphen followed by symbolic timezone, or space
2822 * followed by signed numeric timezone or symbolic timezone
2823 * Examples of normal input:
2824 * . IMAP date-only (SEARCH):
2825 * dd-mmm-yyyy
2826 * . IMAP date-time (INTERNALDATE):
2827 * dd-mmm-yyyy hh:mm:ss +zzzz
2828 * . RFC-822:
2829 * www, dd mmm yy hh:mm:ss zzz
2830 * . RFC-2822:
2831 * www, dd mmm yyyy hh:mm:ss +zzzz
2832 */
2834 long mail_parse_date (MESSAGECACHE *elt,unsigned char *s)
2836 unsigned long d,m,y;
2837 int mi,ms;
2838 struct tm *t;
2839 time_t tn;
2840 char tmp[MAILTMPLEN];
2841 static unsigned long maxyear = 0;
2842 if (!maxyear) { /* know the end of time yet? */
2843 MESSAGECACHE tmpelt;
2844 memset (&tmpelt,0xff,sizeof (MESSAGECACHE));
2845 maxyear = BASEYEAR + tmpelt.year;
2847 /* clear elt */
2848 elt->zoccident = elt->zhours = elt->zminutes =
2849 elt->hours = elt->minutes = elt->seconds =
2850 elt->day = elt->month = elt->year = 0;
2851 /* make a writeable uppercase copy */
2852 if (s && *s && (strlen (s) < (size_t)MAILTMPLEN)) s = ucase (strcpy (tmp,s));
2853 else return NIL;
2854 /* skip over possible day of week */
2855 if (isalpha (*s) && isalpha (s[1]) && isalpha (s[2]) && (s[3] == ',') &&
2856 (s[4] == ' ')) s += 5;
2857 while (*s == ' ') s++; /* parse first number (probable month) */
2858 if (!(m = strtoul (s,(char **) &s,10))) return NIL;
2860 switch (*s) { /* different parse based on delimiter */
2861 case '/': /* mm/dd/yy format */
2862 if (isdigit (*++s) && (d = strtoul (s,(char **) &s,10)) &&
2863 (*s == '/') && isdigit (*++s)) {
2864 y = strtoul (s,(char **) &s,10);
2865 if (*s == '\0') break; /* must end here */
2867 return NIL; /* bogon */
2868 case ' ': /* dd mmm yy format */
2869 while (s[1] == ' ') s++; /* slurp extra whitespace */
2870 case '-':
2871 if (isdigit (s[1])) { /* possible ISO 8601 date format? */
2872 y = m; /* yes, first number is year */
2873 /* get month and day */
2874 if ((m = strtoul (s+1,(char **) &s,10)) && (*s++ == '-') &&
2875 (d = strtoul (s,(char **) &s,10)) && !*s) break;
2876 return NIL; /* syntax error or time present */
2878 d = m; /* dd-mmm-yy[yy], so first number is a day */
2879 /* make sure string long enough! */
2880 if (strlen (s) < (size_t) 5) return NIL;
2881 /* Some compilers don't allow `<<' and/or longs in case statements. */
2882 /* slurp up the month string */
2883 ms = ((s[1] - 'A') * 1024) + ((s[2] - 'A') * 32) + (s[3] - 'A');
2884 switch (ms) { /* determine the month */
2885 case (('J'-'A') * 1024) + (('A'-'A') * 32) + ('N'-'A'): m = 1; break;
2886 case (('F'-'A') * 1024) + (('E'-'A') * 32) + ('B'-'A'): m = 2; break;
2887 case (('M'-'A') * 1024) + (('A'-'A') * 32) + ('R'-'A'): m = 3; break;
2888 case (('A'-'A') * 1024) + (('P'-'A') * 32) + ('R'-'A'): m = 4; break;
2889 case (('M'-'A') * 1024) + (('A'-'A') * 32) + ('Y'-'A'): m = 5; break;
2890 case (('J'-'A') * 1024) + (('U'-'A') * 32) + ('N'-'A'): m = 6; break;
2891 case (('J'-'A') * 1024) + (('U'-'A') * 32) + ('L'-'A'): m = 7; break;
2892 case (('A'-'A') * 1024) + (('U'-'A') * 32) + ('G'-'A'): m = 8; break;
2893 case (('S'-'A') * 1024) + (('E'-'A') * 32) + ('P'-'A'): m = 9; break;
2894 case (('O'-'A') * 1024) + (('C'-'A') * 32) + ('T'-'A'): m = 10; break;
2895 case (('N'-'A') * 1024) + (('O'-'A') * 32) + ('V'-'A'): m = 11; break;
2896 case (('D'-'A') * 1024) + (('E'-'A') * 32) + ('C'-'A'): m = 12; break;
2897 default: return NIL; /* unknown month */
2899 if (s[4] == *s) s += 5; /* advance to year */
2900 else { /* first three were OK, possibly full name */
2901 mi = *s; /* note delimiter, skip alphas */
2902 for (s += 4; isalpha (*s); s++);
2903 /* error if delimiter not here */
2904 if (mi != *s++) return NIL;
2906 while (*s == ' ') s++; /* parse year */
2907 if (isdigit (*s)) { /* must be a digit here */
2908 y = strtoul (s,(char **) &s,10);
2909 if (*s == '\0' || *s == ' ') break;
2911 case '\0': /* ISO 8601 compact date */
2912 if (m < (BASEYEAR * 10000)) return NIL;
2913 y = m / 10000; /* get year */
2914 d = (m %= 10000) % 100; /* get day */
2915 m /= 100; /* and month */
2916 break;
2917 default:
2918 return NIL; /* unknown date format */
2921 /* minimal validity check of date */
2922 if ((d > 31) || (m > 12)) return NIL;
2923 if (y < 49) y += 2000; /* RFC 2282 rules for two digit years 00-49 */
2924 else if (y < 999) y += 1900; /* 2-digit years 50-99 and 3-digit years */
2925 /* reject prehistoric and far future years */
2926 if ((y < BASEYEAR) || (y > maxyear)) return NIL;
2927 /* set values in elt */
2928 elt->day = d; elt->month = m; elt->year = y - BASEYEAR;
2929 ms = '\0'; /* initially no time zone string */
2930 if (*s) { /* time specification present? */
2931 /* parse time */
2932 d = strtoul (s+1,(char **) &s,10);
2933 if (*s != ':') return NIL;
2934 m = strtoul (++s,(char **) &s,10);
2935 y = (*s == ':') ? strtoul (++s,(char **) &s,10) : 0;
2936 /* validity check time */
2937 if ((d > 23) || (m > 59) || (y > 60)) return NIL;
2938 /* set values in elt */
2939 elt->hours = d; elt->minutes = m; elt->seconds = y;
2940 switch (*s) { /* time zone specifier? */
2941 case ' ': /* numeric time zone */
2942 while (s[1] == ' ') s++; /* slurp extra whitespace */
2943 if (!isalpha (s[1])) { /* treat as '-' case if alphabetic */
2944 /* test for sign character */
2945 if ((elt->zoccident = (*++s == '-')) || (*s == '+')) s++;
2946 /* validate proper timezone */
2947 if (isdigit(*s) && isdigit(s[1]) && isdigit(s[2]) && (s[2] < '6') &&
2948 isdigit(s[3])) {
2949 elt->zhours = (*s - '0') * 10 + (s[1] - '0');
2950 elt->zminutes = (s[2] - '0') * 10 + (s[3] - '0');
2952 return T; /* all done! */
2954 /* falls through */
2955 case '-': /* symbolic time zone */
2956 if (!(ms = *++s)) ms = 'Z';
2957 else if (*++s) { /* multi-character? */
2958 ms -= 'A'; ms *= 1024; /* yes, make compressed three-byte form */
2959 ms += ((*s++ - 'A') * 32);
2960 if (*s) ms += *s++ - 'A';
2961 if (*s) ms = '\0'; /* more than three characters */
2963 default: /* ignore anything else */
2964 break;
2968 /* This is not intended to be a comprehensive list of all possible
2969 * timezone strings. Such a list would be impractical. Rather, this
2970 * listing is intended to incorporate all military, North American, and
2971 * a few special cases such as Japan and the major European zone names,
2972 * such as what might be expected to be found in a Tenex format mailbox
2973 * and spewed from an IMAP server. The trend is to migrate to numeric
2974 * timezones which lack the flavor but also the ambiguity of the names.
2976 * RFC-822 only recognizes UT, GMT, 1-letter military timezones, and the
2977 * 4 CONUS timezones and their summer time variants. [Sorry, Canadian
2978 * Atlantic Provinces, Alaska, and Hawaii.]
2979 */
2980 switch (ms) { /* determine the timezone */
2981 /* Universal */
2982 case (('U'-'A')*1024)+(('T'-'A')*32):
2983 #ifndef STRICT_RFC822_TIMEZONES
2984 case (('U'-'A')*1024)+(('T'-'A')*32)+'C'-'A':
2985 #endif
2986 /* Greenwich */
2987 case (('G'-'A')*1024)+(('M'-'A')*32)+'T'-'A':
2988 case 'Z': elt->zhours = 0; break;
2990 /* oriental (from Greenwich) timezones */
2991 #ifndef STRICT_RFC822_TIMEZONES
2992 /* Middle Europe */
2993 case (('M'-'A')*1024)+(('E'-'A')*32)+'T'-'A':
2994 #endif
2995 #ifdef BRITISH_SUMMER_TIME
2996 /* British Summer */
2997 case (('B'-'A')*1024)+(('S'-'A')*32)+'T'-'A':
2998 #endif
2999 case 'A': elt->zhours = 1; break;
3000 #ifndef STRICT_RFC822_TIMEZONES
3001 /* Eastern Europe */
3002 case (('E'-'A')*1024)+(('E'-'A')*32)+'T'-'A':
3003 #endif
3004 case 'B': elt->zhours = 2; break;
3005 case 'C': elt->zhours = 3; break;
3006 case 'D': elt->zhours = 4; break;
3007 case 'E': elt->zhours = 5; break;
3008 case 'F': elt->zhours = 6; break;
3009 case 'G': elt->zhours = 7; break;
3010 case 'H': elt->zhours = 8; break;
3011 #ifndef STRICT_RFC822_TIMEZONES
3012 /* Japan */
3013 case (('J'-'A')*1024)+(('S'-'A')*32)+'T'-'A':
3014 #endif
3015 case 'I': elt->zhours = 9; break;
3016 case 'K': elt->zhours = 10; break;
3017 case 'L': elt->zhours = 11; break;
3018 case 'M': elt->zhours = 12; break;
3020 /* occidental (from Greenwich) timezones */
3021 case 'N': elt->zoccident = 1; elt->zhours = 1; break;
3022 case 'O': elt->zoccident = 1; elt->zhours = 2; break;
3023 #ifndef STRICT_RFC822_TIMEZONES
3024 case (('A'-'A')*1024)+(('D'-'A')*32)+'T'-'A':
3025 #endif
3026 case 'P': elt->zoccident = 1; elt->zhours = 3; break;
3027 #ifdef NEWFOUNDLAND_STANDARD_TIME
3028 /* Newfoundland */
3029 case (('N'-'A')*1024)+(('S'-'A')*32)+'T'-'A':
3030 elt->zoccident = 1; elt->zhours = 3; elt->zminutes = 30; break;
3031 #endif
3032 #ifndef STRICT_RFC822_TIMEZONES
3033 /* Atlantic */
3034 case (('A'-'A')*1024)+(('S'-'A')*32)+'T'-'A':
3035 #endif
3036 /* CONUS */
3037 case (('E'-'A')*1024)+(('D'-'A')*32)+'T'-'A':
3038 case 'Q': elt->zoccident = 1; elt->zhours = 4; break;
3039 /* Eastern */
3040 case (('E'-'A')*1024)+(('S'-'A')*32)+'T'-'A':
3041 case (('C'-'A')*1024)+(('D'-'A')*32)+'T'-'A':
3042 case 'R': elt->zoccident = 1; elt->zhours = 5; break;
3043 /* Central */
3044 case (('C'-'A')*1024)+(('S'-'A')*32)+'T'-'A':
3045 case (('M'-'A')*1024)+(('D'-'A')*32)+'T'-'A':
3046 case 'S': elt->zoccident = 1; elt->zhours = 6; break;
3047 /* Mountain */
3048 case (('M'-'A')*1024)+(('S'-'A')*32)+'T'-'A':
3049 case (('P'-'A')*1024)+(('D'-'A')*32)+'T'-'A':
3050 case 'T': elt->zoccident = 1; elt->zhours = 7; break;
3051 /* Pacific */
3052 case (('P'-'A')*1024)+(('S'-'A')*32)+'T'-'A':
3053 #ifndef STRICT_RFC822_TIMEZONES
3054 case (('Y'-'A')*1024)+(('D'-'A')*32)+'T'-'A':
3055 #endif
3056 case 'U': elt->zoccident = 1; elt->zhours = 8; break;
3057 #ifndef STRICT_RFC822_TIMEZONES
3058 /* Yukon */
3059 case (('Y'-'A')*1024)+(('S'-'A')*32)+'T'-'A':
3060 #endif
3061 case 'V': elt->zoccident = 1; elt->zhours = 9; break;
3062 #ifndef STRICT_RFC822_TIMEZONES
3063 /* Hawaii */
3064 case (('H'-'A')*1024)+(('S'-'A')*32)+'T'-'A':
3065 #endif
3066 case 'W': elt->zoccident = 1; elt->zhours = 10; break;
3067 /* Nome/Bering/Samoa */
3068 #ifdef NOME_STANDARD_TIME
3069 case (('N'-'A')*1024)+(('S'-'A')*32)+'T'-'A':
3070 #endif
3071 #ifdef BERING_STANDARD_TIME
3072 case (('B'-'A')*1024)+(('S'-'A')*32)+'T'-'A':
3073 #endif
3074 #ifdef SAMOA_STANDARD_TIME
3075 case (('S'-'A')*1024)+(('S'-'A')*32)+'T'-'A':
3076 #endif
3077 case 'X': elt->zoccident = 1; elt->zhours = 11; break;
3078 case 'Y': elt->zoccident = 1; elt->zhours = 12; break;
3080 default: /* unknown time zones treated as local */
3081 tn = time (0); /* time now... */
3082 t = localtime (&tn); /* get local minutes since midnight */
3083 mi = t->tm_hour * 60 + t->tm_min;
3084 ms = t->tm_yday; /* note Julian day */
3085 if (t = gmtime (&tn)) { /* minus UTC minutes since midnight */
3086 mi -= t->tm_hour * 60 + t->tm_min;
3087 /* ms can be one of:
3088 * 36x local time is December 31, UTC is January 1, offset -24 hours
3089 * 1 local time is 1 day ahead of UTC, offset +24 hours
3090 * 0 local time is same day as UTC, no offset
3091 * -1 local time is 1 day behind UTC, offset -24 hours
3092 * -36x local time is January 1, UTC is December 31, offset +24 hours
3093 */
3094 if (ms -= t->tm_yday) /* correct offset if different Julian day */
3095 mi += ((ms < 0) == (abs (ms) == 1)) ? -24*60 : 24*60;
3096 if (mi < 0) { /* occidental? */
3097 mi = abs (mi); /* yup, make positive number */
3098 elt->zoccident = 1; /* and note west of UTC */
3100 elt->zhours = mi / 60; /* now break into hours and minutes */
3101 elt->zminutes = mi % 60;
3103 break;
3105 return T;
3108 /* Mail n messages exist
3109 * Accepts: mail stream
3110 * number of messages
3111 */
3113 void mail_exists (MAILSTREAM *stream,unsigned long nmsgs)
3115 char tmp[MAILTMPLEN];
3116 if (nmsgs > MAXMESSAGES) {
3117 sprintf (tmp,"Mailbox has more messages (%lu) exist than maximum (%lu)",
3118 nmsgs,MAXMESSAGES);
3119 mm_log (tmp,ERROR);
3120 nmsgs = MAXMESSAGES; /* cap to maximum */
3121 /* probably will crash in mail_elt() soon enough... */
3123 /* make sure cache is large enough */
3124 (*mailcache) (stream,nmsgs,CH_SIZE);
3125 stream->nmsgs = nmsgs; /* update stream status */
3126 /* notify main program of change */
3127 if (!stream->silent) MM_EXISTS (stream,nmsgs);
3131 /* Mail n messages are recent
3132 * Accepts: mail stream
3133 * number of recent messages
3134 */
3136 void mail_recent (MAILSTREAM *stream,unsigned long recent)
3138 char tmp[MAILTMPLEN];
3139 if (recent <= stream->nmsgs) stream->recent = recent;
3140 else {
3141 sprintf (tmp,"Non-existent recent message(s) %lu, nmsgs=%lu",
3142 recent,stream->nmsgs);
3143 mm_log (tmp,ERROR);
3148 /* Mail message n is expunged
3149 * Accepts: mail stream
3150 * message #
3151 */
3153 void mail_expunged (MAILSTREAM *stream,unsigned long msgno)
3155 char tmp[MAILTMPLEN];
3156 MESSAGECACHE *elt;
3157 if (msgno > stream->nmsgs) {
3158 sprintf (tmp,"Expunge of non-existent message %lu, nmsgs=%lu",
3159 msgno,stream->nmsgs);
3160 mm_log (tmp,ERROR);
3162 else {
3163 elt = (MESSAGECACHE *) (*mailcache) (stream,msgno,CH_ELT);
3164 /* notify main program of change */
3165 if (!stream->silent) MM_EXPUNGED (stream,msgno);
3166 if (elt) { /* if an element is there */
3167 elt->msgno = 0; /* invalidate its message number and free */
3168 (*mailcache) (stream,msgno,CH_FREE);
3169 (*mailcache) (stream,msgno,CH_FREESORTCACHE);
3171 /* expunge the slot */
3172 (*mailcache) (stream,msgno,CH_EXPUNGE);
3173 --stream->nmsgs; /* update stream status */
3174 if (stream->msgno) { /* have stream pointers? */
3175 /* make sure the short cache is nuked */
3176 if (stream->scache) mail_gc (stream,GC_ENV | GC_TEXTS);
3177 else stream->msgno = 0; /* make sure invalidated in any case */
3182 /* Mail stream status routines */
3185 /* Mail lock stream
3186 * Accepts: mail stream
3187 */
3189 void mail_lock (MAILSTREAM *stream)
3191 if (stream->lock) {
3192 char tmp[MAILTMPLEN];
3193 sprintf (tmp,"Lock when already locked, mbx=%.80s",
3194 stream->mailbox ? stream->mailbox : "???");
3195 fatal (tmp);
3197 else stream->lock = T; /* lock stream */
3201 /* Mail unlock stream
3202 * Accepts: mail stream
3203 */
3205 void mail_unlock (MAILSTREAM *stream)
3207 if (!stream->lock) fatal ("Unlock when not locked");
3208 else stream->lock = NIL; /* unlock stream */
3212 /* Mail turn on debugging telemetry
3213 * Accepts: mail stream
3214 */
3216 void mail_debug (MAILSTREAM *stream)
3218 stream->debug = T; /* turn on debugging telemetry */
3219 if (stream->dtb) (*stream->dtb->parameters) (ENABLE_DEBUG,stream);
3223 /* Mail turn off debugging telemetry
3224 * Accepts: mail stream
3225 */
3227 void mail_nodebug (MAILSTREAM *stream)
3229 stream->debug = NIL; /* turn off debugging telemetry */
3230 if (stream->dtb) (*stream->dtb->parameters) (DISABLE_DEBUG,stream);
3234 /* Mail log to debugging telemetry
3235 * Accepts: message
3236 * flag that data is "sensitive"
3237 */
3239 void mail_dlog (char *string,long flag)
3241 mm_dlog ((debugsensitive || !flag) ? string : "<suppressed>");
3244 /* Mail parse UID sequence
3245 * Accepts: mail stream
3246 * sequence to parse
3247 * Returns: T if parse successful, else NIL
3248 */
3250 long mail_uid_sequence (MAILSTREAM *stream,unsigned char *sequence)
3252 unsigned long i,j,k,x,y;
3253 for (i = 1; i <= stream->nmsgs; i++) mail_elt (stream,i)->sequence = NIL;
3254 while (sequence && *sequence){/* while there is something to parse */
3255 if (*sequence == '*') { /* maximum message */
3256 i = stream->nmsgs ? mail_uid (stream,stream->nmsgs) : stream->uid_last;
3257 sequence++; /* skip past * */
3259 /* parse and validate message number */
3260 /* parse and validate message number */
3261 else if (!isdigit (*sequence)) {
3262 MM_LOG ("Syntax error in sequence",ERROR);
3263 return NIL;
3265 else if (!(i = strtoul (sequence,(char **) &sequence,10))) {
3266 MM_LOG ("UID may not be zero",ERROR);
3267 return NIL;
3269 switch (*sequence) { /* see what the delimiter is */
3270 case ':': /* sequence range */
3271 if (*++sequence == '*') { /* maximum message */
3272 j = stream->nmsgs ? mail_uid (stream,stream->nmsgs) : stream->uid_last;
3273 sequence++; /* skip past * */
3275 /* parse end of range */
3276 else if (!(j = strtoul (sequence,(char **) &sequence,10))) {
3277 MM_LOG ("UID sequence range invalid",ERROR);
3278 return NIL;
3280 if (*sequence && *sequence++ != ',') {
3281 MM_LOG ("UID sequence range syntax error",ERROR);
3282 return NIL;
3284 if (i > j) { /* swap the range if backwards */
3285 x = i; i = j; j = x;
3287 x = mail_msgno (stream,i);/* get msgnos */
3288 y = mail_msgno (stream,j);/* for both UIDS (don't && it) */
3289 /* easy if both UIDs valid */
3290 if (x && y) while (x <= y) mail_elt (stream,x++)->sequence = T;
3291 /* start UID valid, end is not */
3292 else if (x) while ((x <= stream->nmsgs) && (mail_uid (stream,x) <= j))
3293 mail_elt (stream,x++)->sequence = T;
3294 /* end UID valid, start is not */
3295 else if (y) for (x = 1; x <= y; x++) {
3296 if (mail_uid (stream,x) >= i) mail_elt (stream,x)->sequence = T;
3298 /* neither is valid, ugh */
3299 else for (x = 1; x <= stream->nmsgs; x++)
3300 if (((k = mail_uid (stream,x)) >= i) && (k <= j))
3301 mail_elt (stream,x)->sequence = T;
3302 break;
3303 case ',': /* single message */
3304 ++sequence; /* skip the delimiter, fall into end case */
3305 case '\0': /* end of sequence, mark this message */
3306 if (x = mail_msgno (stream,i)) mail_elt (stream,x)->sequence = T;
3307 break;
3308 default: /* anything else is a syntax error! */
3309 MM_LOG ("UID sequence syntax error",ERROR);
3310 return NIL;
3313 return T; /* successfully parsed sequence */
3316 /* Mail see if line list matches that in cache
3317 * Accepts: candidate line list
3318 * cached line list
3319 * matching flags
3320 * Returns: T if match, NIL if no match
3321 */
3323 long mail_match_lines (STRINGLIST *lines,STRINGLIST *msglines,long flags)
3325 unsigned long i;
3326 unsigned char *s,*t;
3327 STRINGLIST *m;
3328 if (!msglines) return T; /* full header is in cache */
3329 /* need full header but filtered in cache */
3330 if ((flags & FT_NOT) || !lines) return NIL;
3331 do { /* make sure all present & accounted for */
3332 for (m = msglines; m; m = m->next) if (lines->text.size == m->text.size) {
3333 for (s = lines->text.data,t = m->text.data,i = lines->text.size;
3334 i && !compare_uchar (*s,*t); s++,t++,i--);
3335 if (!i) break; /* this line matches */
3337 if (!m) return NIL; /* didn't find in the list */
3339 while (lines = lines->next);
3340 return T; /* all lines found */
3343 /* Mail filter text by header lines
3344 * Accepts: text to filter, with trailing null
3345 * length of text
3346 * list of lines
3347 * fetch flags
3348 * Returns: new text size, text overwritten
3349 */
3351 unsigned long mail_filter (char *text,unsigned long len,STRINGLIST *lines,
3352 long flags)
3354 STRINGLIST *hdrs;
3355 int notfound;
3356 unsigned long i;
3357 char c,*s,*e,*t,tmp[MAILTMPLEN];
3358 char *src = text;
3359 char *dst = src;
3360 char *end = text + len;
3361 text[len] = '\012'; /* guard against running off buffer */
3362 while (src < end) { /* process header */
3363 /* slurp header line name */
3364 for (s = src,e = s + MAILTMPLEN - 1,e = (e < end ? e : end),t = tmp;
3365 (s < e) && ((c = (*s ? *s : (*s = ' '))) != ':') &&
3366 ((c > ' ') ||
3367 ((c != ' ') && (c != '\t') && (c != '\015') && (c != '\012')));
3368 *t++ = *s++);
3369 *t = '\0'; /* tie off */
3370 notfound = T; /* not found yet */
3371 if (i = t - tmp) /* see if found in header */
3372 for (hdrs = lines; hdrs && notfound; hdrs = hdrs->next)
3373 if ((hdrs->text.size == i) && !compare_csizedtext (tmp,&hdrs->text))
3374 notfound = NIL;
3375 /* skip header line if not wanted */
3376 if (i && ((flags & FT_NOT) ? !notfound : notfound))
3377 while (((*src++ != '\012') && (*src++ != '\012') && (*src++ != '\012') &&
3378 (*src++ != '\012') && (*src++ != '\012') && (*src++ != '\012') &&
3379 (*src++ != '\012') && (*src++ != '\012') && (*src++ != '\012') &&
3380 (*src++ != '\012')) || ((*src == ' ') || (*src == '\t')));
3381 else if (src == dst) { /* copy to self */
3382 while (((*src++ != '\012') && (*src++ != '\012') && (*src++ != '\012') &&
3383 (*src++ != '\012') && (*src++ != '\012') && (*src++ != '\012') &&
3384 (*src++ != '\012') && (*src++ != '\012') && (*src++ != '\012') &&
3385 (*src++ != '\012')) || ((*src == ' ') || (*src == '\t')));
3386 dst = src; /* update destination */
3388 else { /* copy line and any continuation line */
3389 while ((((*dst++ = *src++) != '\012') && ((*dst++ = *src++) != '\012') &&
3390 ((*dst++ = *src++) != '\012') && ((*dst++ = *src++) != '\012') &&
3391 ((*dst++ = *src++) != '\012') && ((*dst++ = *src++) != '\012') &&
3392 ((*dst++ = *src++) != '\012') && ((*dst++ = *src++) != '\012') &&
3393 ((*dst++ = *src++) != '\012') && ((*dst++ = *src++) != '\012'))||
3394 ((*src == ' ') || (*src == '\t')));
3395 /* in case hit the guard LF */
3396 if (src > end) dst -= (src - end);
3399 *dst = '\0'; /* tie off destination */
3400 return dst - text;
3403 /* Local mail search message
3404 * Accepts: MAIL stream
3405 * message number
3406 * optional section specification
3407 * search program
3408 * Returns: T if found, NIL otherwise
3409 */
3411 long mail_search_msg (MAILSTREAM *stream,unsigned long msgno,char *section,
3412 SEARCHPGM *pgm)
3414 unsigned short d;
3415 char tmp[MAILTMPLEN];
3416 MESSAGECACHE *elt = mail_elt (stream,msgno);
3417 SEARCHHEADER *hdr;
3418 SEARCHOR *or;
3419 SEARCHPGMLIST *not;
3420 unsigned long now = (unsigned long) time (0);
3421 if (pgm->msgno || pgm->uid) { /* message set searches */
3422 SEARCHSET *set;
3423 /* message sequences */
3424 if (pgm->msgno) { /* inside this message sequence set */
3425 for (set = pgm->msgno; set; set = set->next)
3426 if (set->last ? ((set->first <= set->last) ?
3427 ((msgno >= set->first) && (msgno <= set->last)) :
3428 ((msgno >= set->last) && (msgno <= set->first))) :
3429 msgno == set->first) break;
3430 if (!set) return NIL; /* not found within sequence */
3432 if (pgm->uid) { /* inside this unique identifier set */
3433 unsigned long uid = mail_uid (stream,msgno);
3434 for (set = pgm->uid; set; set = set->next)
3435 if (set->last ? ((set->first <= set->last) ?
3436 ((uid >= set->first) && (uid <= set->last)) :
3437 ((uid >= set->last) && (uid <= set->first))) :
3438 uid == set->first) break;
3439 if (!set) return NIL; /* not found within sequence */
3443 /* Fast data searches */
3444 /* need to fetch fast data? */
3445 if ((!elt->rfc822_size && (pgm->larger || pgm->smaller)) ||
3446 (!elt->year && (pgm->before || pgm->on || pgm->since ||
3447 pgm->older || pgm->younger)) ||
3448 (!elt->valid && (pgm->answered || pgm->unanswered ||
3449 pgm->deleted || pgm->undeleted ||
3450 pgm->draft || pgm->undraft ||
3451 pgm->flagged || pgm->unflagged ||
3452 pgm->recent || pgm->old ||
3453 pgm->seen || pgm->unseen ||
3454 pgm->keyword || pgm->unkeyword))) {
3455 unsigned long i;
3456 MESSAGECACHE *ielt;
3457 for (i = elt->msgno; /* find last unloaded message in range */
3458 (i < stream->nmsgs) && (ielt = mail_elt (stream,i+1)) &&
3459 ((!ielt->rfc822_size && (pgm->larger || pgm->smaller)) ||
3460 (!ielt->year && (pgm->before || pgm->on || pgm->since ||
3461 pgm->older || pgm->younger)) ||
3462 (!ielt->valid && (pgm->answered || pgm->unanswered ||
3463 pgm->deleted || pgm->undeleted ||
3464 pgm->draft || pgm->undraft ||
3465 pgm->flagged || pgm->unflagged ||
3466 pgm->recent || pgm->old ||
3467 pgm->seen || pgm->unseen ||
3468 pgm->keyword || pgm->unkeyword))); ++i);
3469 if (i == elt->msgno) sprintf (tmp,"%lu",elt->msgno);
3470 else sprintf (tmp,"%lu:%lu",elt->msgno,i);
3471 mail_fetch_fast (stream,tmp,NIL);
3473 /* size ranges */
3474 if ((pgm->larger && (elt->rfc822_size <= pgm->larger)) ||
3475 (pgm->smaller && (elt->rfc822_size >= pgm->smaller))) return NIL;
3476 /* message flags */
3477 if ((pgm->answered && !elt->answered) ||
3478 (pgm->unanswered && elt->answered) ||
3479 (pgm->deleted && !elt->deleted) ||
3480 (pgm->undeleted && elt->deleted) ||
3481 (pgm->draft && !elt->draft) ||
3482 (pgm->undraft && elt->draft) ||
3483 (pgm->flagged && !elt->flagged) ||
3484 (pgm->unflagged && elt->flagged) ||
3485 (pgm->recent && !elt->recent) ||
3486 (pgm->old && elt->recent) ||
3487 (pgm->seen && !elt->seen) ||
3488 (pgm->unseen && elt->seen)) return NIL;
3489 /* keywords */
3490 if ((pgm->keyword && !mail_search_keyword (stream,elt,pgm->keyword,LONGT)) ||
3491 (pgm->unkeyword && !mail_search_keyword (stream,elt,pgm->unkeyword,NIL)))
3492 return NIL;
3493 /* internal date ranges */
3494 if (pgm->before || pgm->on || pgm->since) {
3495 d = mail_shortdate (elt->year,elt->month,elt->day);
3496 if (pgm->before && (d >= pgm->before)) return NIL;
3497 if (pgm->on && (d != pgm->on)) return NIL;
3498 if (pgm->since && (d < pgm->since)) return NIL;
3500 if (pgm->older || pgm->younger) {
3501 unsigned long msgd = mail_longdate (elt);
3502 if (pgm->older && msgd > (now - pgm->older)) return NIL;
3503 if (pgm->younger && msgd < (now - pgm->younger)) return NIL;
3506 /* envelope searches */
3507 if (pgm->sentbefore || pgm->senton || pgm->sentsince ||
3508 pgm->bcc || pgm->cc || pgm->from || pgm->to || pgm->subject ||
3509 pgm->return_path || pgm->sender || pgm->reply_to || pgm->in_reply_to ||
3510 pgm->message_id || pgm->newsgroups || pgm->followup_to ||
3511 pgm->references) {
3512 ENVELOPE *env;
3513 MESSAGECACHE delt;
3514 if (section) { /* use body part envelope */
3515 BODY *body = mail_body (stream,msgno,section);
3516 env = (body && (body->type == TYPEMESSAGE) && body->subtype &&
3517 !strcmp (body->subtype,"RFC822")) ? body->nested.msg->env : NIL;
3519 else { /* use top level envelope if no section */
3520 if (pgm->header && !stream->scache && !(stream->dtb->flags & DR_LOCAL))
3521 mail_fetch_header(stream,msgno,NIL,NIL,NIL,FT_PEEK|FT_SEARCHLOOKAHEAD);
3522 env = mail_fetchenvelope (stream,msgno);
3524 if (!env) return NIL; /* no envelope obtained */
3525 /* sent date ranges */
3526 if ((pgm->sentbefore || pgm->senton || pgm->sentsince) &&
3527 (!mail_parse_date (&delt,env->date) ||
3528 !(d = mail_shortdate (delt.year,delt.month,delt.day)) ||
3529 (pgm->sentbefore && (d >= pgm->sentbefore)) ||
3530 (pgm->senton && (d != pgm->senton)) ||
3531 (pgm->sentsince && (d < pgm->sentsince)))) return NIL;
3532 /* search headers */
3533 if ((pgm->bcc && !mail_search_addr (env->bcc,pgm->bcc)) ||
3534 (pgm->cc && !mail_search_addr (env->cc,pgm->cc)) ||
3535 (pgm->from && !mail_search_addr (env->from,pgm->from)) ||
3536 (pgm->to && !mail_search_addr (env->to,pgm->to)) ||
3537 (pgm->subject && !mail_search_header_text (env->subject,pgm->subject)))
3538 return NIL;
3539 /* These criteria are not supported by IMAP and have to be emulated */
3540 if ((pgm->return_path &&
3541 !mail_search_addr (env->return_path,pgm->return_path)) ||
3542 (pgm->sender && !mail_search_addr (env->sender,pgm->sender)) ||
3543 (pgm->reply_to && !mail_search_addr (env->reply_to,pgm->reply_to)) ||
3544 (pgm->in_reply_to &&
3545 !mail_search_header_text (env->in_reply_to,pgm->in_reply_to)) ||
3546 (pgm->message_id &&
3547 !mail_search_header_text (env->message_id,pgm->message_id)) ||
3548 (pgm->newsgroups &&
3549 !mail_search_header_text (env->newsgroups,pgm->newsgroups)) ||
3550 (pgm->followup_to &&
3551 !mail_search_header_text (env->followup_to,pgm->followup_to)) ||
3552 (pgm->references &&
3553 !mail_search_header_text (env->references,pgm->references)))
3554 return NIL;
3557 /* search header lines */
3558 for (hdr = pgm->header; hdr; hdr = hdr->next) {
3559 char *t,*e,*v;
3560 SIZEDTEXT s;
3561 STRINGLIST sth,stc;
3562 sth.next = stc.next = NIL; /* only one at a time */
3563 sth.text.data = hdr->line.data;
3564 sth.text.size = hdr->line.size;
3565 /* get the header text */
3566 if ((t = mail_fetch_header (stream,msgno,NIL,&sth,&s.size,
3567 FT_INTERNAL | FT_PEEK |
3568 (section ? NIL : FT_SEARCHLOOKAHEAD))) &&
3569 strchr (t,':')) {
3570 if (hdr->text.size) { /* anything matches empty search string */
3571 /* non-empty, copy field data */
3572 s.data = (unsigned char *) fs_get (s.size + 1);
3573 /* for each line */
3574 for (v = (char *) s.data, e = t + s.size; t < e;) switch (*t) {
3575 default: /* non-continuation, skip leading field name */
3576 while ((t < e) && (*t++ != ':'));
3577 if ((t < e) && (*t == ':')) t++;
3578 case '\t': case ' ': /* copy field data */
3579 while ((t < e) && (*t != '\015') && (*t != '\012')) *v++ = *t++;
3580 *v++ = '\n'; /* tie off line */
3581 while (((*t == '\015') || (*t == '\012')) && (t < e)) t++;
3583 /* calculate true size */
3584 s.size = v - (char *) s.data;
3585 *v = '\0'; /* tie off results */
3586 stc.text.data = hdr->text.data;
3587 stc.text.size = hdr->text.size;
3588 /* search header */
3589 if (mail_search_header (&s,&stc)) fs_give ((void **) &s.data);
3590 else { /* search failed */
3591 fs_give ((void **) &s.data);
3592 return NIL;
3596 else return NIL; /* no matching header text */
3598 /* search strings */
3599 if ((pgm->text && !mail_search_text (stream,msgno,section,pgm->text,LONGT))||
3600 (pgm->body && !mail_search_text (stream,msgno,section,pgm->body,NIL)))
3601 return NIL;
3602 /* logical conditions */
3603 for (or = pgm->or; or; or = or->next)
3604 if (!(mail_search_msg (stream,msgno,section,or->first) ||
3605 mail_search_msg (stream,msgno,section,or->second))) return NIL;
3606 for (not = pgm->not; not; not = not->next)
3607 if (mail_search_msg (stream,msgno,section,not->pgm)) return NIL;
3608 return T;
3611 /* Mail search message header null-terminated text
3612 * Accepts: header text
3613 * strings to search
3614 * Returns: T if search found a match
3615 */
3617 long mail_search_header_text (char *s,STRINGLIST *st)
3619 SIZEDTEXT h;
3620 /* have any text? */
3621 if (h.data = (unsigned char *) s) {
3622 h.size = strlen (s); /* yes, get its size */
3623 return mail_search_header (&h,st);
3625 return NIL;
3629 /* Mail search message header
3630 * Accepts: header as sized text
3631 * strings to search
3632 * Returns: T if search found a match
3633 */
3635 long mail_search_header (SIZEDTEXT *hdr,STRINGLIST *st)
3637 SIZEDTEXT h;
3638 long ret = LONGT;
3639 /* make UTF-8 version of header */
3640 utf8_mime2text (hdr,&h,U8T_CANONICAL);
3641 while (h.size && ((h.data[h.size-1]=='\015') || (h.data[h.size-1]=='\012')))
3642 --h.size; /* slice off trailing newlines */
3643 do if (h.size ? /* search non-empty string */
3644 !ssearch (h.data,h.size,st->text.data,st->text.size) : st->text.size)
3645 ret = NIL;
3646 while (ret && (st = st->next));
3647 if (h.data != hdr->data) fs_give ((void **) &h.data);
3648 return ret;
3651 /* Mail search message body
3652 * Accepts: MAIL stream
3653 * message number
3654 * optional section specification
3655 * string list
3656 * flags
3657 * Returns: T if search found a match
3658 */
3660 long mail_search_text (MAILSTREAM *stream,unsigned long msgno,char *section,
3661 STRINGLIST *st,long flags)
3663 BODY *body;
3664 long ret = NIL;
3665 STRINGLIST *s = mail_newstringlist ();
3666 mailgets_t omg = mailgets;
3667 if (stream->dtb->flags & DR_LOWMEM) mailgets = mail_search_gets;
3668 /* strings to search */
3669 for (stream->private.search.string = s; st;) {
3670 s->text.data = st->text.data;
3671 s->text.size = st->text.size;
3672 if (st = st->next) s = s->next = mail_newstringlist ();
3674 stream->private.search.text = NIL;
3675 if (flags) { /* want header? */
3676 SIZEDTEXT s,t;
3677 s.data = (unsigned char *)
3678 mail_fetch_header (stream,msgno,section,NIL,&s.size,FT_INTERNAL|FT_PEEK);
3679 utf8_mime2text (&s,&t,U8T_CANONICAL);
3680 ret = mail_search_string_work (&t,&stream->private.search.string);
3681 if (t.data != s.data) fs_give ((void **) &t.data);
3683 if (!ret) { /* still looking for match? */
3684 /* no section, get top-level body */
3685 if (!section) mail_fetchstructure (stream,msgno,&body);
3686 /* get body of nested message */
3687 else if ((body = mail_body (stream,msgno,section)) &&
3688 (body->type == TYPEMULTIPART) && body->subtype &&
3689 !strcmp (body->subtype,"RFC822")) body = body->nested.msg->body;
3690 if (body) ret = mail_search_body (stream,msgno,body,NIL,1,flags);
3692 mailgets = omg; /* restore former gets routine */
3693 /* clear searching */
3694 for (s = stream->private.search.string; s; s = s->next) s->text.data = NIL;
3695 mail_free_stringlist (&stream->private.search.string);
3696 stream->private.search.text = NIL;
3697 return ret;
3700 /* Mail search message body text parts
3701 * Accepts: MAIL stream
3702 * message number
3703 * current body pointer
3704 * hierarchical level prefix
3705 * position at current hierarchical level
3706 * string list
3707 * flags
3708 * Returns: T if search found a match
3709 */
3711 long mail_search_body (MAILSTREAM *stream,unsigned long msgno,BODY *body,
3712 char *prefix,unsigned long section,long flags)
3714 long ret = NIL;
3715 unsigned long i;
3716 char *s,*t,sect[MAILTMPLEN];
3717 SIZEDTEXT st,h;
3718 PART *part;
3719 PARAMETER *param;
3720 if (prefix && (strlen (prefix) > (MAILTMPLEN - 20))) return NIL;
3721 sprintf (sect,"%s%lu",prefix ? prefix : "",section++);
3722 if (flags && prefix) { /* want to search MIME header too? */
3723 st.data = (unsigned char *) mail_fetch_mime (stream,msgno,sect,&st.size,
3724 FT_INTERNAL | FT_PEEK);
3725 if (stream->dtb->flags & DR_LOWMEM) ret = stream->private.search.result;
3726 else {
3727 /* make UTF-8 version of header */
3728 utf8_mime2text (&st,&h,U8T_CANONICAL);
3729 ret = mail_search_string_work (&h,&stream->private.search.string);
3730 if (h.data != st.data) fs_give ((void **) &h.data);
3733 if (!ret) switch (body->type) {
3734 case TYPEMULTIPART:
3735 /* extend prefix if not first time */
3736 s = prefix ? strcat (sect,".") : "";
3737 for (i = 1,part = body->nested.part; part && !ret; i++,part = part->next)
3738 ret = mail_search_body (stream,msgno,&part->body,s,i,flags);
3739 break;
3740 case TYPEMESSAGE:
3741 if (!strcmp (body->subtype,"RFC822")) {
3742 if (flags) { /* want to search nested message header? */
3743 st.data = (unsigned char *)
3744 mail_fetch_header (stream,msgno,sect,NIL,&st.size,
3745 FT_INTERNAL | FT_PEEK);
3746 if (stream->dtb->flags & DR_LOWMEM) ret =stream->private.search.result;
3747 else {
3748 /* make UTF-8 version of header */
3749 utf8_mime2text (&st,&h,U8T_CANONICAL);
3750 ret = mail_search_string_work (&h,&stream->private.search.string);
3751 if (h.data != st.data) fs_give ((void **) &h.data);
3754 if (body = body->nested.msg->body)
3755 ret = (body->type == TYPEMULTIPART) ?
3756 mail_search_body (stream,msgno,body,(prefix ? prefix : ""),
3757 section - 1,flags) :
3758 mail_search_body (stream,msgno,body,strcat (sect,"."),1,flags);
3759 break;
3761 /* non-MESSAGE/RFC822 falls into text case */
3763 case TYPETEXT:
3764 s = mail_fetch_body (stream,msgno,sect,&i,FT_INTERNAL | FT_PEEK);
3765 if (stream->dtb->flags & DR_LOWMEM) ret = stream->private.search.result;
3766 else {
3767 for (t = NIL,param = body->parameter; param && !t; param = param->next)
3768 if (!strcmp (param->attribute,"CHARSET")) t = param->value;
3769 switch (body->encoding) { /* what encoding? */
3770 case ENCBASE64:
3771 if (st.data = (unsigned char *)
3772 rfc822_base64 ((unsigned char *) s,i,&st.size)) {
3773 ret = mail_search_string (&st,t,&stream->private.search.string);
3774 fs_give ((void **) &st.data);
3776 break;
3777 case ENCQUOTEDPRINTABLE:
3778 if (st.data = rfc822_qprint ((unsigned char *) s,i,&st.size)) {
3779 ret = mail_search_string (&st,t,&stream->private.search.string);
3780 fs_give ((void **) &st.data);
3782 break;
3783 default:
3784 st.data = (unsigned char *) s;
3785 st.size = i;
3786 ret = mail_search_string (&st,t,&stream->private.search.string);
3787 break;
3790 break;
3792 return ret;
3795 /* Mail search text
3796 * Accepts: sized text to search
3797 * character set of sized text
3798 * string list of search keys
3799 * Returns: T if search found a match
3800 */
3802 long mail_search_string (SIZEDTEXT *s,char *charset,STRINGLIST **st)
3804 SIZEDTEXT u;
3805 long ret;
3806 STRINGLIST **sc = st;
3807 /* convert to UTF-8 as best we can */
3808 if (!utf8_text (s,charset,&u,U8T_CANONICAL))
3809 utf8_text (s,NIL,&u,U8T_CANONICAL);
3810 ret = mail_search_string_work (&u,st);
3811 if (u.data != s->data) fs_give ((void **) &u.data);
3812 return ret;
3816 /* Mail search text worker routine
3817 * Accepts: sized text to search
3818 * string list of search keys
3819 * Returns: T if search found a match
3820 */
3822 long mail_search_string_work (SIZEDTEXT *s,STRINGLIST **st)
3824 void *t;
3825 STRINGLIST **sc = st;
3826 while (*sc) { /* run down criteria list */
3827 if (ssearch (s->data,s->size,(*sc)->text.data,(*sc)->text.size)) {
3828 t = (void *) (*sc); /* found one, need to flush this */
3829 *sc = (*sc)->next; /* remove it from the list */
3830 fs_give (&t); /* flush the buffer */
3832 else sc = &(*sc)->next; /* move to next in list */
3834 return *st ? NIL : LONGT;
3838 /* Mail search keyword
3839 * Accepts: MAIL stream
3840 * elt to get flags from
3841 * keyword list
3842 * T for keyword search, NIL for unkeyword search
3843 * Returns: T if search found a match
3844 */
3846 long mail_search_keyword (MAILSTREAM *stream,MESSAGECACHE *elt,STRINGLIST *st,
3847 long flag)
3849 int i,j;
3850 unsigned long f = 0;
3851 unsigned long tf;
3852 do {
3853 for (i = 0; (j = (i < NUSERFLAGS) && stream->user_flags[i]); ++i)
3854 if (!compare_csizedtext (stream->user_flags[i],&st->text)) {
3855 f |= (1 << i);
3856 break;
3858 if (flag && !j) return NIL;
3859 } while (st = st->next);
3860 tf = elt->user_flags & f; /* get set flags which match */
3861 return flag ? (f == tf) : !tf;
3864 /* Mail search an address list
3865 * Accepts: address list
3866 * string list
3867 * Returns: T if search found a match
3868 */
3870 #define SEARCHBUFLEN (size_t) 2000
3871 #define SEARCHBUFSLOP (size_t) 5
3873 long mail_search_addr (ADDRESS *adr,STRINGLIST *st)
3875 ADDRESS *a,tadr;
3876 SIZEDTEXT txt;
3877 char tmp[SENDBUFLEN + 1];
3878 size_t i = SEARCHBUFLEN;
3879 size_t k;
3880 long ret = NIL;
3881 if (adr) {
3882 txt.data = (unsigned char *) fs_get (i + SEARCHBUFSLOP);
3883 /* never an error or next */
3884 tadr.error = NIL,tadr.next = NIL;
3885 /* write address list */
3886 for (txt.size = 0,a = adr; a; a = a->next) {
3887 k = (tadr.mailbox = a->mailbox) ? 4 + 2*strlen (a->mailbox) : 3;
3888 if (tadr.personal = a->personal) k += 3 + 2*strlen (a->personal);
3889 if (tadr.adl = a->adl) k += 3 + 2*strlen (a->adl);
3890 if (tadr.host = a->host) k += 3 + 2*strlen (a->host);
3891 if (tadr.personal || tadr.adl) k += 2;
3892 if (k < (SENDBUFLEN-10)) {/* ignore ridiculous addresses */
3893 tmp[0] = '\0';
3894 rfc822_write_address (tmp,&tadr);
3895 /* resize buffer if necessary */
3896 if (((k = strlen (tmp)) + txt.size) > i)
3897 fs_resize ((void **) &txt.data,SEARCHBUFSLOP + (i += SEARCHBUFLEN));
3898 /* add new address */
3899 memcpy (txt.data + txt.size,tmp,k);
3900 txt.size += k;
3901 /* another address follows */
3902 if (a->next) txt.data[txt.size++] = ',';
3905 txt.data[txt.size] = '\0'; /* tie off string */
3906 ret = mail_search_header (&txt,st);
3907 fs_give ((void **) &txt.data);
3909 return ret;
3912 /* Get string for low-memory searching
3913 * Accepts: readin function pointer
3914 * stream to use
3915 * number of bytes
3916 * gets data packet
3918 * mail stream
3919 * message number
3920 * descriptor string
3921 * option flags
3922 * Returns: NIL, always
3923 */
3925 #define SEARCHSLOP 128
3927 char *mail_search_gets (readfn_t f,void *stream,unsigned long size,
3928 GETS_DATA *md)
3930 unsigned long i;
3931 char tmp[MAILTMPLEN+SEARCHSLOP+1];
3932 SIZEDTEXT st;
3933 /* better not be called unless searching */
3934 if (!md->stream->private.search.string) {
3935 sprintf (tmp,"Search botch, mbx = %.80s, %s = %lu[%.80s]",
3936 md->stream->mailbox,
3937 (md->flags & FT_UID) ? "UID" : "msg",md->msgno,md->what);
3938 fatal (tmp);
3940 /* initially no match for search */
3941 md->stream->private.search.result = NIL;
3942 /* make sure buffer clear */
3943 memset (st.data = (unsigned char *) tmp,'\0',
3944 (size_t) MAILTMPLEN+SEARCHSLOP+1);
3945 /* read first buffer */
3946 (*f) (stream,st.size = i = min (size,(long) MAILTMPLEN),tmp);
3947 /* search for text */
3948 if (mail_search_string (&st,NIL,&md->stream->private.search.string))
3949 md->stream->private.search.result = T;
3950 else if (size -= i) { /* more to do, blat slop down */
3951 memmove (tmp,tmp+MAILTMPLEN-SEARCHSLOP,(size_t) SEARCHSLOP);
3952 do { /* read subsequent buffers one at a time */
3953 (*f) (stream,i = min (size,(long) MAILTMPLEN),tmp+SEARCHSLOP);
3954 st.size = i + SEARCHSLOP;
3955 if (mail_search_string (&st,NIL,&md->stream->private.search.string))
3956 md->stream->private.search.result = T;
3957 else memmove (tmp,tmp+MAILTMPLEN,(size_t) SEARCHSLOP);
3959 while ((size -= i) && !md->stream->private.search.result);
3961 if (size) { /* toss out everything after that */
3962 do (*f) (stream,i = min (size,(long) MAILTMPLEN),tmp);
3963 while (size -= i);
3965 return NIL;
3968 /* Mail parse search criteria
3969 * Accepts: criteria
3970 * Returns: search program if parse successful, else NIL
3971 */
3973 SEARCHPGM *mail_criteria (char *criteria)
3975 SEARCHPGM *pgm = NIL;
3976 char *criterion,*r,tmp[MAILTMPLEN];
3977 int f;
3978 if (criteria) { /* only if criteria defined */
3979 /* make writeable copy of criteria */
3980 criteria = cpystr (criteria);
3981 /* for each criterion */
3982 for (pgm = mail_newsearchpgm (), criterion = strtok_r (criteria," ",&r);
3983 criterion; (criterion = strtok_r (NIL," ",&r))) {
3984 f = NIL; /* init then scan the criterion */
3985 switch (*ucase (criterion)) {
3986 case 'A': /* possible ALL, ANSWERED */
3987 if (!strcmp (criterion+1,"LL")) f = T;
3988 else if (!strcmp (criterion+1,"NSWERED")) f = pgm->answered = T;
3989 break;
3990 case 'B': /* possible BCC, BEFORE, BODY */
3991 if (!strcmp (criterion+1,"CC"))
3992 f = mail_criteria_string (&pgm->bcc,&r);
3993 else if (!strcmp (criterion+1,"EFORE"))
3994 f = mail_criteria_date (&pgm->before,&r);
3995 else if (!strcmp (criterion+1,"ODY"))
3996 f = mail_criteria_string (&pgm->body,&r);
3997 break;
3998 case 'C': /* possible CC */
3999 if (!strcmp (criterion+1,"C")) f = mail_criteria_string (&pgm->cc,&r);
4000 break;
4001 case 'D': /* possible DELETED */
4002 if (!strcmp (criterion+1,"ELETED")) f = pgm->deleted = T;
4003 break;
4004 case 'F': /* possible FLAGGED, FROM */
4005 if (!strcmp (criterion+1,"LAGGED")) f = pgm->flagged = T;
4006 else if (!strcmp (criterion+1,"ROM"))
4007 f = mail_criteria_string (&pgm->from,&r);
4008 break;
4009 case 'K': /* possible KEYWORD */
4010 if (!strcmp (criterion+1,"EYWORD"))
4011 f = mail_criteria_string (&pgm->keyword,&r);
4012 break;
4014 case 'N': /* possible NEW */
4015 if (!strcmp (criterion+1,"EW")) f = pgm->recent = pgm->unseen = T;
4016 break;
4017 case 'O': /* possible OLD, ON */
4018 if (!strcmp (criterion+1,"LD")) f = pgm->old = T;
4019 else if (!strcmp (criterion+1,"N"))
4020 f = mail_criteria_date (&pgm->on,&r);
4021 break;
4022 case 'R': /* possible RECENT */
4023 if (!strcmp (criterion+1,"ECENT")) f = pgm->recent = T;
4024 break;
4025 case 'S': /* possible SEEN, SINCE, SUBJECT */
4026 if (!strcmp (criterion+1,"EEN")) f = pgm->seen = T;
4027 else if (!strcmp (criterion+1,"INCE"))
4028 f = mail_criteria_date (&pgm->since,&r);
4029 else if (!strcmp (criterion+1,"UBJECT"))
4030 f = mail_criteria_string (&pgm->subject,&r);
4031 break;
4032 case 'T': /* possible TEXT, TO */
4033 if (!strcmp (criterion+1,"EXT"))
4034 f = mail_criteria_string (&pgm->text,&r);
4035 else if (!strcmp (criterion+1,"O"))
4036 f = mail_criteria_string (&pgm->to,&r);
4037 break;
4038 case 'U': /* possible UN* */
4039 if (criterion[1] == 'N') {
4040 if (!strcmp (criterion+2,"ANSWERED")) f = pgm->unanswered = T;
4041 else if (!strcmp (criterion+2,"DELETED")) f = pgm->undeleted = T;
4042 else if (!strcmp (criterion+2,"FLAGGED")) f = pgm->unflagged = T;
4043 else if (!strcmp (criterion+2,"KEYWORD"))
4044 f = mail_criteria_string (&pgm->unkeyword,&r);
4045 else if (!strcmp (criterion+2,"SEEN")) f = pgm->unseen = T;
4047 break;
4048 default: /* we will barf below */
4049 break;
4051 if (!f) { /* if can't identify criterion */
4052 sprintf (tmp,"Unknown search criterion: %.30s",criterion);
4053 MM_LOG (tmp,ERROR);
4054 mail_free_searchpgm (&pgm);
4055 break;
4058 /* no longer need copy of criteria */
4059 fs_give ((void **) &criteria);
4061 return pgm;
4064 /* Parse a date
4065 * Accepts: pointer to date integer to return
4066 * pointer to strtok state
4067 * Returns: T if successful, else NIL
4068 */
4070 int mail_criteria_date (unsigned short *date,char **r)
4072 STRINGLIST *s = NIL;
4073 MESSAGECACHE elt;
4074 /* parse the date and return fn if OK */
4075 int ret = (mail_criteria_string (&s,r) &&
4076 mail_parse_date (&elt,(char *) s->text.data) &&
4077 (*date = mail_shortdate (elt.year,elt.month,elt.day))) ?
4078 T : NIL;
4079 if (s) mail_free_stringlist (&s);
4080 return ret;
4083 /* Calculate shortdate from elt values
4084 * Accepts: year (0 = BASEYEAR)
4085 * month (1 = January)
4086 * day
4087 * Returns: shortdate
4088 */
4090 unsigned short mail_shortdate (unsigned int year,unsigned int month,
4091 unsigned int day)
4093 return (year << 9) + (month << 5) + day;
4096 /* Parse a string
4097 * Accepts: pointer to stringlist
4098 * pointer to strtok state
4099 * Returns: T if successful, else NIL
4100 */
4102 int mail_criteria_string (STRINGLIST **s,char **r)
4104 unsigned long n;
4105 char e,*d,*end = " ",*c = strtok_r (NIL,"",r);
4106 if (!c) return NIL; /* missing argument */
4107 switch (*c) { /* see what the argument is */
4108 case '{': /* literal string */
4109 n = strtoul (c+1,&d,10); /* get its length */
4110 if ((*d++ == '}') && (*d++ == '\015') && (*d++ == '\012') &&
4111 (!(*(c = d + n)) || (*c == ' '))) {
4112 e = *--c; /* store old delimiter */
4113 *c = '\377'; /* make sure not a space */
4114 strtok_r (c," ",r); /* reset the strtok mechanism */
4115 *c = e; /* put character back */
4116 break;
4118 case '\0': /* catch bogons */
4119 case ' ':
4120 return NIL;
4121 case '"': /* quoted string */
4122 if (strchr (c+1,'"')) end = "\"";
4123 else return NIL; /* falls through */
4124 default: /* atomic string */
4125 if (d = strtok_r (c,end,r)) n = strlen (d);
4126 else return NIL;
4127 break;
4129 while (*s) s = &(*s)->next; /* find tail of list */
4130 *s = mail_newstringlist (); /* make new entry */
4131 /* return the data */
4132 (*s)->text.data = (unsigned char *) cpystr (d);
4133 (*s)->text.size = n;
4134 return T;
4137 /* Mail parse set from string
4138 * Accepts: string to parse
4139 * pointer to updated string pointer for return
4140 * Returns: set with pointer updated, or NIL if error
4141 */
4143 SEARCHSET *mail_parse_set (char *s,char **ret)
4145 SEARCHSET *cur;
4146 SEARCHSET *set = NIL;
4147 while (isdigit (*s)) {
4148 if (!set) cur = set = mail_newsearchset ();
4149 else cur = cur->next = mail_newsearchset ();
4150 /* parse value */
4151 if (!(cur->first = strtoul (s,&s,10)) ||
4152 ((*s == ':') && !(isdigit (*++s) && (cur->last = strtoul (s,&s,10)))))
4153 break; /* bad value or range */
4154 if (*s == ',') ++s; /* point to next value if more */
4155 else { /* end of set */
4156 *ret = s; /* set return pointer */
4157 return set; /* return set */
4160 mail_free_searchset (&set); /* failure, punt partial set */
4161 return NIL;
4165 /* Mail append to set
4166 * Accepts: head of search set or NIL to do nothing
4167 * message to add
4168 * Returns: tail of search set or NIL if did nothing
4169 */
4171 SEARCHSET *mail_append_set (SEARCHSET *set,unsigned long msgno)
4173 if (set) { /* find tail */
4174 while (set->next) set = set->next;
4175 /* start of set if no first member */
4176 if (!set->first) set->first = msgno;
4177 else if (msgno == (set->last ? set->last : set->first) + 1)
4178 set->last = msgno; /* extend range if 1 past current */
4179 else (set = set->next = mail_newsearchset ())->first = msgno;
4181 return set;
4184 /* Mail sort messages
4185 * Accepts: mail stream
4186 * character set
4187 * search program
4188 * sort program
4189 * option flags
4190 * Returns: vector of sorted message sequences or NIL if error
4191 */
4193 unsigned long *mail_sort (MAILSTREAM *stream,char *charset,SEARCHPGM *spg,
4194 SORTPGM *pgm,long flags)
4196 unsigned long *ret = NIL;
4197 if (stream->dtb) /* do the driver's action */
4198 ret = (*(stream->dtb->sort ? stream->dtb->sort : mail_sort_msgs))
4199 (stream,charset,spg,pgm,flags);
4200 /* flush search/sort programs if requested */
4201 if (spg && (flags & SE_FREE)) mail_free_searchpgm (&spg);
4202 if (flags & SO_FREE) mail_free_sortpgm (&pgm);
4203 return ret;
4206 /* Mail sort messages work routine
4207 * Accepts: mail stream
4208 * character set
4209 * search program
4210 * sort program
4211 * option flags
4212 * Returns: vector of sorted message sequences or NIL if error
4213 */
4215 unsigned long *mail_sort_msgs (MAILSTREAM *stream,char *charset,SEARCHPGM *spg,
4216 SORTPGM *pgm,long flags)
4218 unsigned long i;
4219 SORTCACHE **sc;
4220 unsigned long *ret = NIL;
4221 if (spg) { /* only if a search needs to be done */
4222 int silent = stream->silent;
4223 stream->silent = T; /* don't pass up mm_searched() events */
4224 /* search for messages */
4225 mail_search_full (stream,charset,spg,NIL);
4226 stream->silent = silent; /* restore silence state */
4228 /* initialize progress counters */
4229 pgm->nmsgs = pgm->progress.cached = 0;
4230 /* pass 1: count messages to sort */
4231 for (i = 1; i <= stream->nmsgs; ++i)
4232 if (mail_elt (stream,i)->searched) pgm->nmsgs++;
4233 if (pgm->nmsgs) { /* pass 2: sort cache */
4234 sc = mail_sort_loadcache (stream,pgm);
4235 /* pass 3: sort messages */
4236 if (!pgm->abort) ret = mail_sort_cache (stream,pgm,sc,flags);
4237 fs_give ((void **) &sc); /* don't need sort vector any more */
4239 /* empty sort results */
4240 else ret = (unsigned long *) memset (fs_get (sizeof (unsigned long)),0,
4241 sizeof (unsigned long));
4242 /* also return via callback if requested */
4243 if (mailsortresults) (*mailsortresults) (stream,ret,pgm->nmsgs);
4244 return ret; /* return sort results */
4247 /* Mail sort sortcache vector
4248 * Accepts: mail stream
4249 * sort program
4250 * sortcache vector
4251 * option flags
4252 * Returns: vector of sorted message sequences or NIL if error
4253 */
4255 unsigned long *mail_sort_cache (MAILSTREAM *stream,SORTPGM *pgm,SORTCACHE **sc,
4256 long flags)
4258 unsigned long i,*ret;
4259 /* pass 3: sort messages */
4260 qsort ((void *) sc,pgm->nmsgs,sizeof (SORTCACHE *),mail_sort_compare);
4261 /* optional post sorting */
4262 if (pgm->postsort) (*pgm->postsort) ((void *) sc);
4263 /* pass 4: return results */
4264 ret = (unsigned long *) fs_get ((pgm->nmsgs+1) * sizeof (unsigned long));
4265 if (flags & SE_UID) /* UID or msgno? */
4266 for (i = 0; i < pgm->nmsgs; i++) ret[i] = mail_uid (stream,sc[i]->num);
4267 else for (i = 0; i < pgm->nmsgs; i++) ret[i] = sc[i]->num;
4268 ret[pgm->nmsgs] = 0; /* tie off message list */
4269 return ret;
4272 /* Mail load sortcache
4273 * Accepts: mail stream, already searched
4274 * sort program
4275 * Returns: vector of sortcache pointers matching search
4276 */
4278 static STRINGLIST maildateline = {{(unsigned char *) "date",4},NIL};
4279 static STRINGLIST mailrnfromline = {{(unsigned char *) ">from",5},NIL};
4280 static STRINGLIST mailfromline = {{(unsigned char *) "from",4},
4281 &mailrnfromline};
4282 static STRINGLIST mailtonline = {{(unsigned char *) "to",2},NIL};
4283 static STRINGLIST mailccline = {{(unsigned char *) "cc",2},NIL};
4284 static STRINGLIST mailsubline = {{(unsigned char *) "subject",7},NIL};
4286 SORTCACHE **mail_sort_loadcache (MAILSTREAM *stream,SORTPGM *pgm)
4288 char *t,*v,*x,tmp[MAILTMPLEN];
4289 SORTPGM *pg;
4290 SORTCACHE *s,**sc;
4291 MESSAGECACHE *elt,telt;
4292 ENVELOPE *env;
4293 ADDRESS *adr = NIL;
4294 unsigned long i = (pgm->nmsgs) * sizeof (SORTCACHE *);
4295 sc = (SORTCACHE **) memset (fs_get ((size_t) i),0,(size_t) i);
4296 /* see what needs to be loaded */
4297 for (i = 1; !pgm->abort && (i <= stream->nmsgs); i++)
4298 if ((elt = mail_elt (stream,i))->searched) {
4299 sc[pgm->progress.cached++] =
4300 s = (SORTCACHE *) (*mailcache) (stream,i,CH_SORTCACHE);
4301 s->pgm = pgm; /* note sort program */
4302 s->num = i;
4303 /* get envelope if cached */
4304 if (stream->scache) env = (i == stream->msgno) ? stream->env : NIL;
4305 else env = elt->private.msg.env;
4306 for (pg = pgm; pg; pg = pg->next) switch (pg->function) {
4307 case SORTARRIVAL: /* sort by arrival date */
4308 if (!s->arrival) {
4309 /* internal date unknown but can get? */
4310 if (!elt->day && !(stream->dtb->flags & DR_NOINTDATE)) {
4311 sprintf (tmp,"%lu",i);
4312 mail_fetch_fast (stream,tmp,NIL);
4314 /* wrong thing before 3-Jan-1970 */
4315 s->arrival = elt->day ? mail_longdate (elt) : 1;
4316 s->dirty = T;
4318 break;
4319 case SORTSIZE: /* sort by message size */
4320 if (!s->size) {
4321 if (!elt->rfc822_size) {
4322 sprintf (tmp,"%lu",i);
4323 mail_fetch_fast (stream,tmp,NIL);
4325 s->size = elt->rfc822_size ? elt->rfc822_size : 1;
4326 s->dirty = T;
4328 break;
4330 case SORTDATE: /* sort by date */
4331 if (!s->date) {
4332 if (env) t = env->date;
4333 else if ((t = mail_fetch_header (stream,i,NIL,&maildateline,NIL,
4334 FT_INTERNAL | FT_PEEK)) &&
4335 (t = strchr (t,':')))
4336 for (x = ++t; x = strpbrk (x,"\012\015"); x++)
4337 switch (*(v = ((*x == '\015') && (x[1] == '\012')) ? x+2 : x+1)){
4338 case ' ': /* erase continuation newlines */
4339 case '\t':
4340 memmove (x,v,strlen (v));
4341 break;
4342 default: /* tie off extraneous text */
4343 *x = x[1] = '\0';
4345 /* skip leading whitespace */
4346 if (t) while ((*t == ' ') || (*t == '\t')) t++;
4347 /* parse date from Date: header */
4348 if (!(t && mail_parse_date (&telt,t) &&
4349 (s->date = mail_longdate (&telt)))) {
4350 /* failed, use internal date */
4351 if (!(s->date = s->arrival)) {
4352 /* internal date unknown but can get? */
4353 if (!elt->day && !(stream->dtb->flags & DR_NOINTDATE)) {
4354 sprintf (tmp,"%lu",i);
4355 mail_fetch_fast (stream,tmp,NIL);
4357 /* wrong thing before 3-Jan-1970 */
4358 s->date = (s->arrival = elt->day ? mail_longdate (elt) : 1);
4361 s->dirty = T;
4363 break;
4365 case SORTFROM: /* sort by first from */
4366 if (!s->from) {
4367 if (env) s->from = env->from && env->from->mailbox ?
4368 cpystr (env->from->mailbox) : NIL;
4369 else if ((t = mail_fetch_header (stream,i,NIL,&mailfromline,NIL,
4370 FT_INTERNAL | FT_PEEK)) &&
4371 (t = strchr (t,':'))) {
4372 for (x = ++t; x = strpbrk (x,"\012\015"); x++)
4373 switch (*(v = ((*x == '\015') && (x[1] == '\012')) ? x+2 : x+1)){
4374 case ' ': /* erase continuation newlines */
4375 case '\t':
4376 memmove (x,v,strlen (v));
4377 break;
4378 case 'f': /* continuation but with extra "From:" */
4379 case 'F':
4380 if (v = strchr (v,':')) {
4381 memmove (x,v+1,strlen (v+1));
4382 break;
4384 default: /* tie off extraneous text */
4385 *x = x[1] = '\0';
4387 if (adr = rfc822_parse_address (&adr,adr,&t,BADHOST,0)) {
4388 s->from = adr->mailbox;
4389 adr->mailbox = NIL;
4390 mail_free_address (&adr);
4393 if (!s->from) s->from = cpystr ("");
4394 s->dirty = T;
4396 break;
4398 case SORTTO: /* sort by first to */
4399 if (!s->to) {
4400 if (env) s->to = env->to && env->to->mailbox ?
4401 cpystr (env->to->mailbox) : NIL;
4402 else if ((t = mail_fetch_header (stream,i,NIL,&mailtonline,NIL,
4403 FT_INTERNAL | FT_PEEK)) &&
4404 (t = strchr (t,':'))) {
4405 for (x = ++t; x = strpbrk (x,"\012\015"); x++)
4406 switch (*(v = ((*x == '\015') && (x[1] == '\012')) ? x+2 : x+1)){
4407 case ' ': /* erase continuation newlines */
4408 case '\t':
4409 memmove (x,v,strlen (v));
4410 break;
4411 case 't': /* continuation but with extra "To:" */
4412 case 'T':
4413 if (v = strchr (v,':')) {
4414 memmove (x,v+1,strlen (v+1));
4415 break;
4417 default: /* tie off extraneous text */
4418 *x = x[1] = '\0';
4420 if (adr = rfc822_parse_address (&adr,adr,&t,BADHOST,0)) {
4421 s->to = adr->mailbox;
4422 adr->mailbox = NIL;
4423 mail_free_address (&adr);
4426 if (!s->to) s->to = cpystr ("");
4427 s->dirty = T;
4429 break;
4431 case SORTCC: /* sort by first cc */
4432 if (!s->cc) {
4433 if (env) s->cc = env->cc && env->cc->mailbox ?
4434 cpystr (env->cc->mailbox) : NIL;
4435 else if ((t = mail_fetch_header (stream,i,NIL,&mailccline,NIL,
4436 FT_INTERNAL | FT_PEEK)) &&
4437 (t = strchr (t,':'))) {
4438 for (x = ++t; x = strpbrk (x,"\012\015"); x++)
4439 switch (*(v = ((*x == '\015') && (x[1] == '\012')) ? x+2 : x+1)){
4440 case ' ': /* erase continuation newlines */
4441 case '\t':
4442 memmove (x,v,strlen (v));
4443 break;
4444 case 't': /* continuation but with extra "To:" */
4445 case 'T':
4446 if (v = strchr (v,':')) {
4447 memmove (x,v+1,strlen (v+1));
4448 break;
4450 default: /* tie off extraneous text */
4451 *x = x[1] = '\0';
4453 if (adr = rfc822_parse_address (&adr,adr,&t,BADHOST,0)) {
4454 s->cc = adr->mailbox;
4455 adr->mailbox = NIL;
4456 mail_free_address (&adr);
4459 if (!s->cc) s->cc = cpystr ("");
4460 s->dirty = T;
4462 break;
4464 case SORTSUBJECT: /* sort by subject */
4465 if (!s->subject) {
4466 /* get subject from envelope if have one */
4467 if (env) t = env->subject ? env->subject : "";
4468 /* otherwise snarf from header text */
4469 else if ((t = mail_fetch_header (stream,i,NIL,&mailsubline,
4470 NIL,FT_INTERNAL | FT_PEEK)) &&
4471 (t = strchr (t,':')))
4472 for (x = ++t; x = strpbrk (x,"\012\015"); x++)
4473 switch (*(v = ((*x == '\015') && (x[1] == '\012')) ? x+2 : x+1)){
4474 case ' ': /* erase continuation newlines */
4475 case '\t':
4476 memmove (x,v,strlen (v));
4477 break;
4478 default: /* tie off extraneous text */
4479 *x = x[1] = '\0';
4481 else t = ""; /* empty subject */
4482 /* strip and cache subject */
4483 s->refwd = mail_strip_subject (t,&s->subject);
4484 s->dirty = T;
4486 break;
4487 default:
4488 fatal ("Unknown sort function");
4491 return sc;
4494 /* Strip subjects of extra spaces and leading and trailing cruft for sorting
4495 * Accepts: unstripped subject
4496 * pointer to return stripped subject, in cpystr form
4497 * Returns: T if subject had a re/fwd, NIL otherwise
4498 */
4500 unsigned int mail_strip_subject (char *t,char **ret)
4502 SIZEDTEXT src,dst;
4503 unsigned long i,slen;
4504 char c,*s,*x;
4505 unsigned int refwd = NIL;
4506 if (src.size = strlen (t)) { /* have non-empty subject? */
4507 src.data = (unsigned char *) t;
4508 /* Step 1 */
4509 /* make copy, convert MIME2 if needed */
4510 *ret = s = (utf8_mime2text (&src,&dst,U8T_CANONICAL) &&
4511 (src.data != dst.data)) ? (char *) dst.data : cpystr (t);
4512 /* convert spaces to tab, strip extra spaces */
4513 for (x = t = s, c = 'x'; *t; t++) {
4514 if (c != ' ') c = *x++ = ((*t == '\t') ? ' ' : *t);
4515 else if ((*t != '\t') && (*t != ' ')) c = *x++ = *t;
4517 *x = '\0'; /* tie off string */
4518 /* Step 2 */
4519 for (slen = dst.size; s; slen = strlen (s)) {
4520 for (t = s + slen; t > s; ) switch (t[-1]) {
4521 case ' ': case '\t': /* WSP */
4522 *--t = '\0'; /* just remove it */
4523 break;
4524 case ')': /* possible "(fwd)" */
4525 if ((t >= (s + 5)) && (t[-5] == '(') &&
4526 ((t[-4] == 'F') || (t[-4] == 'f')) &&
4527 ((t[-3] == 'W') || (t[-3] == 'w')) &&
4528 ((t[-2] == 'D') || (t[-2] == 'd'))) {
4529 *(t -= 5) = '\0'; /* remove "(fwd)" */
4530 refwd = T; /* note a re/fwd */
4531 break;
4533 default: /* not a subj-trailer */
4534 t = s;
4535 break;
4537 /* Steps 3-5 */
4538 for (t = s; t; ) switch (*s) {
4539 case ' ': case '\t': /* WSP */
4540 s = t = mail_strip_subject_wsp (s + 1);
4541 break;
4542 case 'r': case 'R': /* possible "re" */
4543 if (((s[1] == 'E') || (s[1] == 'e')) &&
4544 (t = mail_strip_subject_wsp (s + 2)) &&
4545 (t = mail_strip_subject_blob (t)) && (*t == ':')) {
4546 s = ++t; /* found "re" */
4547 refwd = T; /* definitely a re/fwd at this point */
4549 else t = NIL; /* found subj-middle */
4550 break;
4551 case 'f': case 'F': /* possible "fw" or "fwd" */
4552 if (((s[1] == 'w') || (s[1] == 'W')) &&
4553 (((s[2] == 'd') || (s[2] == 'D')) ?
4554 (t = mail_strip_subject_wsp (s + 3)) :
4555 (t = mail_strip_subject_wsp (s + 2))) &&
4556 (t = mail_strip_subject_blob (t)) && (*t == ':')) {
4557 s = ++t; /* found "fwd" */
4558 refwd = T; /* definitely a re/fwd at this point */
4560 else t = NIL; /* found subj-middle */
4561 break;
4562 case '[': /* possible subj-blob */
4563 if ((t = mail_strip_subject_blob (s)) && *t) s = t;
4564 else t = NIL; /* found subj-middle */
4565 break;
4566 default:
4567 t = NIL; /* found subj-middle */
4568 break;
4570 /* Step 6 */
4571 /* Netscape-style "[Fwd: ...]"? */
4572 if ((*s == '[') && ((s[1] == 'F') || (s[1] == 'f')) &&
4573 ((s[2] == 'W') || (s[2] == 'w')) &&
4574 ((s[3] == 'D') || (s[3] == 'd')) && (s[4] == ':') &&
4575 (s[i = strlen (s) - 1] == ']')) {
4576 s[i] = '\0'; /* flush closing "]" */
4577 s += 5; /* and leading "[Fwd:" */
4578 refwd = T; /* definitely a re/fwd at this point */
4580 else break; /* don't need to loop back to step 2 */
4582 if (s != (t = *ret)) { /* removed leading text? */
4583 s = *ret = cpystr (s); /* yes, make a fresh return copy */
4584 fs_give ((void **) &t); /* flush old copy */
4587 else *ret = cpystr (""); /* empty subject */
4588 return refwd; /* return re/fwd state */
4591 /* Strip subject wsp helper routine
4592 * Accepts: text
4593 * Returns: pointer to text after blob
4594 */
4596 char *mail_strip_subject_wsp (char *s)
4598 while ((*s == ' ') || (*s == '\t')) s++;
4599 return s;
4603 /* Strip subject blob helper routine
4604 * Accepts: text
4605 * Returns: pointer to text after any blob, NIL if blob-like but not blob
4606 */
4608 char *mail_strip_subject_blob (char *s)
4610 if (*s != '[') return s; /* not a blob, ignore */
4611 /* search for end of blob */
4612 while (*++s != ']') if ((*s == '[') || !*s) return NIL;
4613 return mail_strip_subject_wsp (s + 1);
4616 /* Sort compare messages
4617 * Accept: first message sort cache element
4618 * second message sort cache element
4619 * Returns: -1 if a1 < a2, 0 if a1 == a2, 1 if a1 > a2
4620 */
4622 int mail_sort_compare (const void *a1,const void *a2)
4624 int i = 0;
4625 SORTCACHE *s1 = *(SORTCACHE **) a1;
4626 SORTCACHE *s2 = *(SORTCACHE **) a2;
4627 SORTPGM *pgm = s1->pgm;
4628 if (!s1->sorted) { /* this one sorted yet? */
4629 s1->sorted = T;
4630 pgm->progress.sorted++; /* another sorted message */
4632 if (!s2->sorted) { /* this one sorted yet? */
4633 s2->sorted = T;
4634 pgm->progress.sorted++; /* another sorted message */
4636 do {
4637 switch (pgm->function) { /* execute search program */
4638 case SORTDATE: /* sort by date */
4639 i = compare_ulong (s1->date,s2->date);
4640 break;
4641 case SORTARRIVAL: /* sort by arrival date */
4642 i = compare_ulong (s1->arrival,s2->arrival);
4643 break;
4644 case SORTSIZE: /* sort by message size */
4645 i = compare_ulong (s1->size,s2->size);
4646 break;
4647 case SORTFROM: /* sort by first from */
4648 i = compare_cstring (s1->from,s2->from);
4649 break;
4650 case SORTTO: /* sort by first to */
4651 i = compare_cstring (s1->to,s2->to);
4652 break;
4653 case SORTCC: /* sort by first cc */
4654 i = compare_cstring (s1->cc,s2->cc);
4655 break;
4656 case SORTSUBJECT: /* sort by subject */
4657 i = compare_cstring (s1->subject,s2->subject);
4658 break;
4660 if (pgm->reverse) i = -i; /* flip results if necessary */
4662 while (pgm = i ? NIL : pgm->next);
4663 /* return result, avoid 0 if at all possible */
4664 return i ? i : compare_ulong (s1->num,s2->num);
4667 /* Return message date as an unsigned long seconds since time began
4668 * Accepts: message cache pointer
4669 * Returns: unsigned long of date
4671 * This routine, like most UNIX systems, is clueless about leap seconds.
4672 * Thus, it treats 23:59:60 as equivalent to 00:00:00 the next day.
4674 * This routine forces any early hours on 1-Jan-1970 in oriental timezones
4675 * to be 1-Jan-1970 00:00:00 UTC, so as to avoid negative longdates.
4676 */
4678 unsigned long mail_longdate (MESSAGECACHE *elt)
4680 unsigned long m = elt->month ? elt->month : 1;
4681 unsigned long yr = elt->year + BASEYEAR;
4682 /* number of days since time began */
4683 unsigned long ret = (elt->day ? (elt->day - 1) : 0)
4684 + 30 * (m - 1) + ((m + (m > 8)) / 2)
4685 #ifndef USEJULIANCALENDAR
4686 #ifndef USEORTHODOXCALENDAR /* Gregorian calendar */
4687 + ((yr / 400) - (BASEYEAR / 400)) - ((yr / 100) - (BASEYEAR / 100))
4688 #ifdef Y4KBUGFIX
4689 - ((yr / 4000) - (BASEYEAR / 4000))
4690 #endif
4691 - ((m < 3) ?
4692 !(yr % 4) && ((yr % 100) || (!(yr % 400)
4693 #ifdef Y4KBUGFIX
4694 && (yr % 4000)
4695 #endif
4696 )) : 2)
4697 #else /* Orthodox calendar */
4698 + ((2*(yr / 900)) - (2*(BASEYEAR / 900)))
4699 + (((yr % 900) >= 200) - ((BASEYEAR % 900) >= 200))
4700 + (((yr % 900) >= 600) - ((BASEYEAR % 900) >= 600))
4701 - ((yr / 100) - (BASEYEAR / 100))
4702 - ((m < 3) ?
4703 !(yr % 4) && ((yr % 100) || ((yr % 900) == 200) || ((yr % 900) == 600))
4704 : 2)
4705 #endif
4706 #endif
4707 + elt->year * 365 + (((unsigned long) (elt->year + (BASEYEAR % 4))) / 4);
4708 ret *= 24; ret += elt->hours; /* date value in hours */
4709 ret *= 60; ret +=elt->minutes;/* date value in minutes */
4710 yr = (elt->zhours * 60) + elt->zminutes;
4711 if (elt->zoccident) ret += yr;/* occidental timezone, make UTC */
4712 else if (ret < yr) return 0; /* still 31-Dec-1969 in UTC */
4713 else ret -= yr; /* oriental timezone, make UTC */
4714 ret *= 60; ret += elt->seconds;
4715 return ret;
4718 /* Mail thread messages
4719 * Accepts: mail stream
4720 * thread type
4721 * character set
4722 * search program
4723 * option flags
4724 * Returns: thread node tree or NIL if error
4725 */
4727 THREADNODE *mail_thread (MAILSTREAM *stream,char *type,char *charset,
4728 SEARCHPGM *spg,long flags)
4730 THREADNODE *ret = NIL;
4731 if (stream->dtb) /* must have a live driver */
4732 ret = stream->dtb->thread ? /* do driver's action if available */
4733 (*stream->dtb->thread) (stream,type,charset,spg,flags) :
4734 mail_thread_msgs (stream,type,charset,spg,flags,mail_sort_msgs);
4735 /* flush search/sort programs if requested */
4736 if (spg && (flags & SE_FREE)) mail_free_searchpgm (&spg);
4737 return ret;
4741 /* Mail thread messages
4742 * Accepts: mail stream
4743 * thread type
4744 * character set
4745 * search program
4746 * option flags
4747 * sorter routine
4748 * Returns: thread node tree or NIL if error
4749 */
4751 THREADNODE *mail_thread_msgs (MAILSTREAM *stream,char *type,char *charset,
4752 SEARCHPGM *spg,long flags,sorter_t sorter)
4754 THREADER *t;
4755 for (t = &mailthreadlist; t; t = t->next)
4756 if (!compare_cstring (type,t->name)) {
4757 THREADNODE *ret = (*t->dispatch) (stream,charset,spg,flags,sorter);
4758 if (mailthreadresults) (*mailthreadresults) (stream,ret);
4759 return ret;
4761 MM_LOG ("No such thread type",ERROR);
4762 return NIL;
4765 /* Mail thread ordered subject
4766 * Accepts: mail stream
4767 * character set
4768 * search program
4769 * option flags
4770 * sorter routine
4771 * Returns: thread node tree
4772 */
4774 THREADNODE *mail_thread_orderedsubject (MAILSTREAM *stream,char *charset,
4775 SEARCHPGM *spg,long flags,
4776 sorter_t sorter)
4778 THREADNODE *thr = NIL;
4779 THREADNODE *cur,*top,**tc;
4780 SORTPGM pgm,pgm2;
4781 SORTCACHE *s;
4782 unsigned long i,j,*lst,*ls;
4783 /* sort by subject+date */
4784 memset (&pgm,0,sizeof (SORTPGM));
4785 memset (&pgm2,0,sizeof (SORTPGM));
4786 pgm.function = SORTSUBJECT;
4787 pgm.next = &pgm2;
4788 pgm2.function = SORTDATE;
4789 if (lst = (*sorter) (stream,charset,spg,&pgm,flags & ~(SE_FREE | SE_UID))){
4790 if (*(ls = lst)) { /* create thread */
4791 /* note first subject */
4792 cur = top = thr = mail_newthreadnode
4793 ((SORTCACHE *) (*mailcache) (stream,*ls++,CH_SORTCACHE));
4794 /* note its number */
4795 cur->num = (flags & SE_UID) ? mail_uid (stream,*lst) : *lst;
4796 i = 1; /* number of threads */
4797 while (*ls) { /* build tree */
4798 /* subjects match? */
4799 s = (SORTCACHE *) (*mailcache) (stream,*ls++,CH_SORTCACHE);
4800 if (compare_cstring (top->sc->subject,s->subject)) {
4801 i++; /* have a new thread */
4802 top = top->branch = cur = mail_newthreadnode (s);
4804 /* start a child of the top */
4805 else if (cur == top) cur = cur->next = mail_newthreadnode (s);
4806 /* sibling of child */
4807 else cur = cur->branch = mail_newthreadnode (s);
4808 /* set to msgno or UID as needed */
4809 cur->num = (flags & SE_UID) ? mail_uid (stream,s->num) : s->num;
4811 /* make threadnode cache */
4812 tc = (THREADNODE **) fs_get (i * sizeof (THREADNODE *));
4813 /* load threadnode cache */
4814 for (j = 0, cur = thr; cur; cur = cur->branch) tc[j++] = cur;
4815 if (i != j) fatal ("Threadnode cache confusion");
4816 qsort ((void *) tc,i,sizeof (THREADNODE *),mail_thread_compare_date);
4817 for (j = 0, --i; j < i; j++) tc[j]->branch = tc[j+1];
4818 tc[j]->branch = NIL; /* end of root */
4819 thr = tc[0]; /* head of data */
4820 fs_give ((void **) &tc);
4822 fs_give ((void **) &lst);
4824 return thr;
4827 /* Mail thread references
4828 * Accepts: mail stream
4829 * character set
4830 * search program
4831 * option flags
4832 * sorter routine
4833 * Returns: thread node tree
4834 */
4836 #define REFHASHSIZE 1009 /* arbitrary prime for hash table size */
4838 /* Reference threading container, as described in Jamie Zawinski's web page
4839 * (http://www.jwz.org/doc/threading.html) for this algorithm. These are
4840 * stored as extended data in the hash table (called "id_table" in JWZ's
4841 * document) and are maintained by the hash table routines. The hash table
4842 * routines implement extended data as additional void* words at the end of
4843 * each bucket, hence these strange macros instead of a struct which would
4844 * have been more straightforward.
4845 */
4847 #define THREADLINKS 3 /* number of thread links */
4849 #define CACHE(data) ((SORTCACHE *) (data)[0])
4850 #define PARENT(data) ((container_t) (data)[1])
4851 #define SETPARENT(data,value) ((container_t) (data[1] = value))
4852 #define SIBLING(data) ((container_t) (data)[2])
4853 #define SETSIBLING(data,value) ((container_t) (data[2] = value))
4854 #define CHILD(data) ((container_t) (data)[3])
4855 #define SETCHILD(data,value) ((container_t) (data[3] = value))
4857 THREADNODE *mail_thread_references (MAILSTREAM *stream,char *charset,
4858 SEARCHPGM *spg,long flags,sorter_t sorter)
4860 MESSAGECACHE *elt,telt;
4861 ENVELOPE *env;
4862 SORTCACHE *s;
4863 STRINGLIST *st;
4864 HASHENT *he;
4865 THREADNODE **tc,*cur,*lst,*nxt,*sis,*msg;
4866 container_t con,nxc,prc,sib;
4867 void **sub;
4868 char *t,tmp[MAILTMPLEN];
4869 unsigned long j,nmsgs;
4870 unsigned long i = stream->nmsgs * sizeof (SORTCACHE *);
4871 SORTCACHE **sc = (SORTCACHE **) memset (fs_get ((size_t) i),0,(size_t) i);
4872 HASHTAB *ht = hash_create (REFHASHSIZE);
4873 THREADNODE *root = NIL;
4874 if (spg) { /* only if a search needs to be done */
4875 int silent = stream->silent;
4876 stream->silent = T; /* don't pass up mm_searched() events */
4877 /* search for messages */
4878 mail_search_full (stream,charset,spg,NIL);
4879 stream->silent = silent; /* restore silence state */
4882 /* create SORTCACHE vector of requested msgs */
4883 for (i = 1, nmsgs = 0; i <= stream->nmsgs; ++i)
4884 if (mail_elt (stream,i)->searched)
4885 (sc[nmsgs++] = (SORTCACHE *)(*mailcache)(stream,i,CH_SORTCACHE))->num =i;
4886 /* separate pass so can do overview fetch lookahead */
4887 for (i = 0; i < nmsgs; ++i) { /* for each requested message */
4888 /* is anything missing in its SORTCACHE? */
4889 if (!((s = sc[i])->date && s->subject && s->message_id && s->references)) {
4890 /* driver has an overview mechanism? */
4891 if (stream->dtb && stream->dtb->overview) {
4892 /* yes, find following unloaded entries */
4893 for (j = i + 1; (j < nmsgs) && !sc[j]->references; ++j);
4894 sprintf (tmp,"%lu",mail_uid (stream,s->num));
4895 if (i != --j) /* end of range different? */
4896 sprintf (tmp + strlen (tmp),":%lu",mail_uid (stream,sc[j]->num));
4897 /* load via overview mechanism */
4898 mail_fetch_overview (stream,tmp,mail_thread_loadcache);
4900 /* still missing data? */
4901 if (!s->date || !s->subject || !s->message_id || !s->references) {
4902 /* try to load data from envelope */
4903 if (env = mail_fetch_structure (stream,s->num,NIL,NIL)) {
4904 if (!s->date && env->date && mail_parse_date (&telt,env->date))
4905 s->date = mail_longdate (&telt);
4906 if (!s->subject && env->subject)
4907 s->refwd =
4908 mail_strip_subject (env->subject,&s->subject);
4909 if (!s->message_id && env->message_id && *env->message_id)
4910 s->message_id = mail_thread_parse_msgid (env->message_id,NIL);
4911 if (!s->references && /* use References: or In-Reply-To: */
4912 !(s->references =
4913 mail_thread_parse_references (env->references,T)))
4914 s->references = mail_thread_parse_references(env->in_reply_to,NIL);
4916 /* last resort */
4917 if (!s->date && !(s->date = s->arrival)) {
4918 /* internal date unknown but can get? */
4919 if (!(elt = mail_elt (stream,s->num))->day &&
4920 !(stream->dtb->flags & DR_NOINTDATE)) {
4921 sprintf (tmp,"%lu",s->num);
4922 mail_fetch_fast (stream,tmp,NIL);
4924 /* wrong thing before 3-Jan-1970 */
4925 s->date = (s->arrival = elt->day ? mail_longdate (elt) : 1);
4927 if (!s->subject) s->subject = cpystr ("");
4928 if (!s->references) s->references = mail_newstringlist ();
4929 s->dirty = T;
4933 /* Step 1 (preliminary) */
4934 /* generate unique string */
4935 sprintf (tmp,"%s.%lx.%lx@%s",stream->mailbox,stream->uid_validity,
4936 mail_uid (stream,s->num),mylocalhost ());
4937 /* flush old unique string if not message-id */
4938 if (s->unique && (s->unique != s->message_id))
4939 fs_give ((void **) &s->unique);
4940 s->unique = s->message_id ? /* don't permit Message ID duplicates */
4941 (hash_lookup (ht,s->message_id) ? cpystr (tmp) : s->message_id) :
4942 (s->message_id = cpystr (tmp));
4943 /* add unique string to hash table */
4944 hash_add (ht,s->unique,s,THREADLINKS);
4946 /* Step 1 */
4947 for (i = 0; i < nmsgs; ++i) { /* for each message in sortcache */
4948 /* Step 1A */
4949 if ((st = (s = sc[i])->references) && st->text.data)
4950 for (con = hash_lookup_and_add (ht,(char *) st->text.data,NIL,
4951 THREADLINKS); st = st->next; con = nxc) {
4952 nxc = hash_lookup_and_add (ht,(char *) st->text.data,NIL,THREADLINKS);
4953 /* only if no parent & won't introduce loop */
4954 if (!PARENT (nxc) && !mail_thread_check_child (con,nxc)) {
4955 SETPARENT (nxc,con); /* establish parent/child link */
4956 /* other children become sibling of this one */
4957 SETSIBLING (nxc,CHILD (con));
4958 SETCHILD (con,nxc); /* set as child of parent */
4961 else con = NIL; /* else message has no ancestors */
4962 /* Step 1B */
4963 if ((prc = PARENT ((nxc = hash_lookup (ht,s->unique)))) &&
4964 (prc != con)) { /* break links if have a different parent */
4965 SETPARENT (nxc,NIL); /* easy if direct child */
4966 if (nxc == CHILD (prc)) SETCHILD (prc,SIBLING (nxc));
4967 else { /* otherwise hunt through sisters */
4968 for (sib = CHILD (prc); nxc != SIBLING (sib); sib = SIBLING (sib));
4969 SETSIBLING (sib,SIBLING (nxc));
4971 SETSIBLING (nxc,NIL); /* no more little sisters either */
4972 prc = NIL; /* no more parent set */
4974 /* need to set parent, and parent is good? */
4975 if (!prc && !mail_thread_check_child (con,nxc)) {
4976 SETPARENT (nxc,con); /* establish parent/child link */
4977 if (con) { /* if non-root parent, set parent's child */
4978 if (CHILD (con)) { /* have a child already */
4979 /* find youngest daughter */
4980 for (con = CHILD (con); SIBLING (con); con = SIBLING (con));
4981 SETSIBLING (con,nxc); /* add new baby sister */
4983 else SETCHILD (con,nxc);/* set as only child */
4987 fs_give ((void **) &sc); /* finished with sortcache vector */
4989 /* Step 2 */
4990 /* search hash table for parentless messages */
4991 for (i = 0, prc = con = NIL; i < ht->size; i++)
4992 for (he = ht->table[i]; he; he = he->next)
4993 if (!PARENT ((nxc = he->data))) {
4994 /* sibling of previous parentless message */
4995 if (con) con = SETSIBLING (con,nxc);
4996 else prc = con = nxc; /* first parentless message */
4998 /* Once the dummy containers are pruned, we no longer need the parent
4999 * information, so we can convert the containers to THREADNODEs. Since
5000 * we don't need the id_table any more either, we can reset the hash table
5001 * and reuse it as a subject_table. Resetting the hash table will also
5002 * destroy the containers.
5003 */
5004 /* Step 3 */
5005 /* prune dummies, convert to threadnode */
5006 root = mail_thread_c2node (stream,mail_thread_prune_dummy (prc,NIL),flags);
5007 /* Step 4 */
5008 /* make buffer for sorting */
5009 tc = (THREADNODE **) fs_get (nmsgs * sizeof (THREADNODE *));
5010 /* load threadcache and count nodes to sort */
5011 for (i = 0, cur = root; cur ; cur = cur->branch) tc[i++] = cur;
5012 if (i > 1) { /* only if need to sort */
5013 qsort ((void *) tc,i,sizeof (THREADNODE *),mail_thread_compare_date);
5014 /* relink siblings */
5015 for (j = 0, --i; j < i; j++) tc[j]->branch = tc[j+1];
5016 tc[j]->branch = NIL; /* end of root */
5017 root = tc[0]; /* establish new root */
5019 /* Step 5A */
5020 hash_reset (ht); /* discard containers, reset ht */
5021 /* Step 5B */
5022 for (cur = root; cur; cur = cur->branch)
5023 if ((t = (nxt = (cur->sc ? cur : cur->next))->sc->subject) && *t) {
5024 /* add new subject to hash table */
5025 if (!(sub = hash_lookup (ht,t))) hash_add (ht,t,cur,0);
5026 /* if one in table not dummy and */
5027 else if ((s = (lst = (THREADNODE *) sub[0])->sc) &&
5028 /* current dummy, or not re/fwd and table is */
5029 (!cur->sc || (!nxt->sc->refwd && s->refwd)))
5030 sub[0] = (void *) cur; /* replace with this message */
5033 /* Step 5C */
5034 for (cur = root, sis = NIL; cur; cur = msg) {
5035 /* do nothing if current message or no sub */
5036 if (!(t = (cur->sc ? cur : cur->next)->sc->subject) || !*t ||
5037 ((lst = (THREADNODE *) (sub = hash_lookup (ht,t))[0]) == cur))
5038 msg = (sis = cur)->branch;
5039 else if (!lst->sc) { /* is message in the table a dummy? */
5040 /* find youngest daughter of msg in table */
5041 for (msg = lst->next; msg->branch; msg = msg->branch);
5042 if (!cur->sc) { /* current message a dummy? */
5043 msg->branch = cur->next;/* current's daughter now dummy's youngest */
5044 msg = cur->branch; /* continue scan at younger sister */
5045 /* now delete this node */
5046 cur->branch = cur->next = NIL;
5047 mail_free_threadnode (&cur);
5049 else { /* current message not a dummy */
5050 msg->branch = cur; /* append as youngest daughter */
5051 msg = cur->branch; /* continue scan at younger sister */
5052 cur->branch = NIL; /* lose our younger sisters */
5055 else { /* no dummies, is current re/fwd, table not? */
5056 if (cur->sc->refwd && !lst->sc->refwd) {
5057 if (lst->next) { /* find youngest daughter of msg in table */
5058 for (msg = lst->next; msg->branch; msg = msg->branch);
5059 msg->branch = cur; /* append as youngest daughter */
5061 else lst->next = cur; /* no children, so make the eldest daughter */
5064 else { /* no re/fwd, create a new dummy */
5065 msg = mail_newthreadnode (NIL);
5066 if (lst == root) { /* msg in table is root? */
5067 root = lst->branch; /* younger sister becomes new root */
5068 /* no longer older sister either */
5069 if (lst == sis) sis = NIL;
5071 else { /* find older sister of msg in table */
5072 for (nxt = root; lst != nxt->branch; nxt = nxt->branch);
5073 /* remove from older sister */
5074 nxt->branch = lst->branch;
5076 msg->next = lst; /* msg in table becomes child */
5077 lst->branch = cur; /* current now little sister of msg in table */
5078 if (sis) { /* have an elder sister? */
5079 if (sis == lst) /* rescan if lost her */
5080 for (sis = root; cur != sis->branch; sis = sis->branch);
5081 sis->branch = msg; /* make dummy younger sister of big sister */
5083 else root = msg; /* otherwise this is the new root */
5084 sub[0] = sis = msg; /* set new msg in table and new big sister */
5086 msg = cur->branch; /* continue scan at younger sister */
5087 cur->branch = NIL; /* lose our younger sisters */
5089 if (sis) sis->branch = msg; /* older sister gets this as younger sister */
5090 else root = msg; /* otherwise this is the new root */
5092 hash_destroy (&ht); /* finished with hash table */
5093 /* Step 6 */
5094 /* sort threads */
5095 root = mail_thread_sort (root,tc);
5096 fs_give ((void **) &tc); /* finished with sort buffer */
5097 return root; /* return sorted list */
5100 /* Fetch overview callback to load sortcache for threading
5101 * Accepts: MAIL stream
5102 * UID of this message
5103 * overview of this message
5104 * msgno of this message
5105 */
5107 void mail_thread_loadcache (MAILSTREAM *stream,unsigned long uid,OVERVIEW *ov,
5108 unsigned long msgno)
5110 if (msgno && ov) { /* just in case */
5111 MESSAGECACHE telt;
5112 SORTCACHE *s = (SORTCACHE *) (*mailcache) (stream,msgno,CH_SORTCACHE);
5113 if (!s->subject && ov->subject) {
5114 s->refwd = mail_strip_subject (ov->subject,&s->subject);
5115 s->dirty = T;
5117 if (!s->from && ov->from && ov->from->mailbox) {
5118 s->from = cpystr (ov->from->mailbox);
5119 s->dirty = T;
5121 if (!s->date && ov->date && mail_parse_date (&telt,ov->date)) {
5122 s->date = mail_longdate (&telt);
5123 s->dirty = T;
5125 if (!s->message_id && ov->message_id) {
5126 s->message_id = mail_thread_parse_msgid (ov->message_id,NIL);
5127 s->dirty = T;
5129 if (!s->references &&
5130 !(s->references = mail_thread_parse_references (ov->references,T))) {
5131 /* don't do In-Reply-To with NNTP mailboxes */
5132 s->references = mail_newstringlist ();
5133 s->dirty = T;
5135 if (!s->size && ov->optional.octets) {
5136 s->size = ov->optional.octets;
5137 s->dirty = T;
5142 /* Thread parse Message ID
5143 * Accepts: pointer to purported Message ID
5144 * pointer to return pointer
5145 * Returns: Message ID or NIL, return pointer updated
5146 */
5148 char *mail_thread_parse_msgid (char *s,char **ss)
5150 char *ret = NIL;
5151 char *t = NIL;
5152 ADDRESS *adr;
5153 if (s) { /* only for non-NIL strings */
5154 rfc822_skipws (&s); /* skip whitespace */
5155 /* ignore phrases */
5156 if (((*s == '<') || (s = rfc822_parse_phrase (s))) &&
5157 (adr = rfc822_parse_routeaddr (s,&t,BADHOST))) {
5158 /* make return msgid */
5159 if (adr->mailbox && adr->host)
5160 sprintf (ret = (char *) fs_get (strlen (adr->mailbox) +
5161 strlen (adr->host) + 2),"%s@%s",
5162 adr->mailbox,adr->host);
5163 mail_free_address (&adr); /* don't need temporary address */
5166 if (ss) *ss = t; /* update return pointer */
5167 return ret;
5171 /* Thread parse references
5172 * Accepts: pointer to purported references
5173 * parse multiple references flag
5174 * Returns: references or NIL
5175 */
5177 STRINGLIST *mail_thread_parse_references (char *s,long flag)
5179 char *t;
5180 STRINGLIST *ret = NIL;
5181 STRINGLIST *cur;
5182 /* found first reference? */
5183 if (t = mail_thread_parse_msgid (s,&s)) {
5184 (ret = mail_newstringlist ())->text.data = (unsigned char *) t;
5185 ret->text.size = strlen (t);
5186 if (flag) /* parse subsequent references */
5187 for (cur = ret; t = mail_thread_parse_msgid (s,&s); cur = cur->next) {
5188 (cur->next = mail_newstringlist ())->text.data = (unsigned char *) t;
5189 cur->next->text.size = strlen (t);
5192 return ret;
5195 /* Prune dummy messages
5196 * Accepts: candidate container to prune
5197 * older sibling of container, if any
5198 * Returns: container in this position, possibly pruned
5199 * All children and younger siblings are also pruned
5200 */
5202 container_t mail_thread_prune_dummy (container_t msg,container_t ane)
5204 /* prune container and children */
5205 container_t ret = msg ? mail_thread_prune_dummy_work (msg,ane) : NIL;
5206 /* prune all younger sisters */
5207 if (ret) for (ane = ret; ane && (msg = SIBLING (ane)); ane = msg)
5208 msg = mail_thread_prune_dummy_work (msg,ane);
5209 return ret;
5213 /* Prune dummy messages worker routine
5214 * Accepts: candidate container to prune
5215 * older sibling of container, if any
5216 * Returns: container in this position, possibly pruned
5217 * All children are also pruned
5218 */
5220 container_t mail_thread_prune_dummy_work (container_t msg,container_t ane)
5222 container_t cur;
5223 /* get children, if any */
5224 container_t nxt = mail_thread_prune_dummy (CHILD (msg),NIL);
5225 /* just update children if container has msg */
5226 if (CACHE (msg)) SETCHILD (msg,nxt);
5227 else if (!nxt) { /* delete dummy with no children */
5228 nxt = SIBLING (msg); /* get younger sister */
5229 if (ane) SETSIBLING (ane,nxt);
5230 /* prune younger sister if exists */
5231 msg = nxt ? mail_thread_prune_dummy_work (nxt,ane) : NIL;
5233 /* not if parent root & multiple children */
5234 else if ((cur = PARENT (msg)) || !SIBLING (nxt)) {
5235 /* OK to promote, try younger sister of aunt */
5236 if (ane) SETSIBLING (ane,nxt);
5237 /* otherwise promote to child of grandmother */
5238 else if (cur) SETCHILD (cur,nxt);
5239 SETPARENT (nxt,cur); /* set parent as well */
5240 /* look for end of siblings in new container */
5241 for (cur = nxt; SIBLING (cur); cur = SIBLING (cur));
5242 /* reattach deleted container's siblings */
5243 SETSIBLING (cur,SIBLING (msg));
5244 /* prune and return new container */
5245 msg = mail_thread_prune_dummy_work (nxt,ane);
5247 else SETCHILD (msg,nxt); /* in case child pruned */
5248 return msg; /* return this message */
5251 /* Test that purported mother is not a child of purported daughter
5252 * Accepts: mother
5253 * purported daugher
5254 * Returns: T if circular parentage exists, else NIL
5255 */
5257 long mail_thread_check_child (container_t mother,container_t daughter)
5259 if (mother) { /* only if mother non-NIL */
5260 if (mother == daughter) return T;
5261 for (daughter = CHILD (daughter); daughter; daughter = SIBLING (daughter))
5262 if (mail_thread_check_child (mother,daughter)) return T;
5264 return NIL;
5268 /* Generate threadnodes from containers
5269 * Accepts: Mail stream
5270 * container
5271 * flags
5272 * Return: threadnode list
5273 */
5275 THREADNODE *mail_thread_c2node (MAILSTREAM *stream,container_t con,long flags)
5277 THREADNODE *ret,*cur;
5278 SORTCACHE *s;
5279 container_t nxt;
5280 /* for each container */
5281 for (ret = cur = NIL; con; con = SIBLING (con)) {
5282 s = CACHE (con); /* yes, get its sortcache */
5283 /* create node for it */
5284 if (ret) cur = cur->branch = mail_newthreadnode (s);
5285 else ret = cur = mail_newthreadnode (s);
5286 /* attach sequence or UID for non-dummy */
5287 if (s) cur->num = (flags & SE_UID) ? mail_uid (stream,s->num) : s->num;
5288 /* attach the children */
5289 if (nxt = CHILD (con)) cur->next = mail_thread_c2node (stream,nxt,flags);
5291 return ret;
5294 /* Sort thread tree by date
5295 * Accepts: thread tree to sort
5296 * qsort vector to sort
5297 * Returns: sorted thread tree
5298 */
5300 THREADNODE *mail_thread_sort (THREADNODE *thr,THREADNODE **tc)
5302 unsigned long i,j;
5303 THREADNODE *cur;
5304 /* sort children of each thread */
5305 for (cur = thr; cur; cur = cur->branch)
5306 if (cur->next) cur->next = mail_thread_sort (cur->next,tc);
5307 /* Must do this in a separate pass since recursive call will clobber tc */
5308 /* load threadcache and count nodes to sort */
5309 for (i = 0, cur = thr; cur; cur = cur->branch) tc[i++] = cur;
5310 if (i > 1) { /* only if need to sort */
5311 qsort ((void *) tc,i,sizeof (THREADNODE *),mail_thread_compare_date);
5312 /* relink root siblings */
5313 for (j = 0, --i; j < i; j++) tc[j]->branch = tc[j+1];
5314 tc[j]->branch = NIL; /* end of root */
5316 return i ? tc[0] : NIL; /* return new head of list */
5320 /* Thread compare date
5321 * Accept: first message sort cache element
5322 * second message sort cache element
5323 * Returns: -1 if a1 < a2, 1 if a1 > a2
5325 * This assumes that a sort cache element is either a message (with a
5326 * sortcache entry) or a dummy with a message (with sortcache entry) child.
5327 * This is true of both the ORDEREDSUBJECT (no dummies) and REFERENCES
5328 * (dummies only at top-level, and with non-dummy children).
5330 * If a new algorithm allows a dummy parent to have a dummy child, this
5331 * routine must be changed if it is to be used by that algorithm.
5333 * Messages with bogus dates are always sorted at the top.
5334 */
5336 int mail_thread_compare_date (const void *a1,const void *a2)
5338 THREADNODE *t1 = *(THREADNODE **) a1;
5339 THREADNODE *t2 = *(THREADNODE **) a2;
5340 SORTCACHE *s1 = t1->sc ? t1->sc : t1->next->sc;
5341 SORTCACHE *s2 = t2->sc ? t2->sc : t2->next->sc;
5342 int ret = compare_ulong (s1->date,s2->date);
5343 /* use number as final tie-breaker */
5344 return ret ? ret : compare_ulong (s1->num,s2->num);
5347 /* Mail parse sequence
5348 * Accepts: mail stream
5349 * sequence to parse
5350 * Returns: T if parse successful, else NIL
5351 */
5353 long mail_sequence (MAILSTREAM *stream,unsigned char *sequence)
5355 unsigned long i,j,x;
5356 for (i = 1; i <= stream->nmsgs; i++) mail_elt (stream,i)->sequence = NIL;
5357 while (sequence && *sequence){/* while there is something to parse */
5358 if (*sequence == '*') { /* maximum message */
5359 if (stream->nmsgs) i = stream->nmsgs;
5360 else {
5361 MM_LOG ("No messages, so no maximum message number",ERROR);
5362 return NIL;
5364 sequence++; /* skip past * */
5366 /* parse and validate message number */
5367 else if (!isdigit (*sequence)) {
5368 MM_LOG ("Syntax error in sequence",ERROR);
5369 return NIL;
5371 else if (!(i = strtoul (sequence,(char **) &sequence,10)) ||
5372 (i > stream->nmsgs)) {
5373 MM_LOG ("Sequence out of range",ERROR);
5374 return NIL;
5376 switch (*sequence) { /* see what the delimiter is */
5377 case ':': /* sequence range */
5378 if (*++sequence == '*') { /* maximum message */
5379 if (stream->nmsgs) j = stream->nmsgs;
5380 else {
5381 MM_LOG ("No messages, so no maximum message number",ERROR);
5382 return NIL;
5384 sequence++; /* skip past * */
5386 /* parse end of range */
5387 else if (!(j = strtoul (sequence,(char **) &sequence,10)) ||
5388 (j > stream->nmsgs)) {
5389 MM_LOG ("Sequence range invalid",ERROR);
5390 return NIL;
5392 if (*sequence && *sequence++ != ',') {
5393 MM_LOG ("Sequence range syntax error",ERROR);
5394 return NIL;
5396 if (i > j) { /* swap the range if backwards */
5397 x = i; i = j; j = x;
5399 /* mark each item in the sequence */
5400 while (i <= j) mail_elt (stream,j--)->sequence = T;
5401 break;
5402 case ',': /* single message */
5403 ++sequence; /* skip the delimiter, fall into end case */
5404 case '\0': /* end of sequence, mark this message */
5405 mail_elt (stream,i)->sequence = T;
5406 break;
5407 default: /* anything else is a syntax error! */
5408 MM_LOG ("Sequence syntax error",ERROR);
5409 return NIL;
5412 return T; /* successfully parsed sequence */
5415 /* Parse flag list
5416 * Accepts: MAIL stream
5417 * flag list as a character string
5418 * pointer to user flags to return
5419 * Returns: system flags
5420 */
5422 long mail_parse_flags (MAILSTREAM *stream,char *flag,unsigned long *uf)
5424 char *t,*n,*s,tmp[MAILTMPLEN],msg[MAILTMPLEN];
5425 short f = 0;
5426 long i,j;
5427 *uf = 0; /* initially no user flags */
5428 if (flag && *flag) { /* no-op if no flag string */
5429 /* check if a list and make sure valid */
5430 if (((i = (*flag == '(')) ^ (flag[strlen (flag)-1] == ')')) ||
5431 (strlen (flag) >= MAILTMPLEN)) {
5432 MM_LOG ("Bad flag list",ERROR);
5433 return NIL;
5435 /* copy the flag string w/o list construct */
5436 strncpy (n = tmp,flag+i,(j = strlen (flag) - (2*i)));
5437 tmp[j] = '\0';
5438 while ((t = n) && *t) { /* parse the flags */
5439 /* find end of flag */
5440 if (n = strchr (t,' ')) *n++ = '\0';
5441 if (*t == '\\') { /* system flag? */
5442 if (!compare_cstring (t+1,"SEEN")) f |= fSEEN;
5443 else if (!compare_cstring (t+1,"DELETED")) f |= fDELETED;
5444 else if (!compare_cstring (t+1,"FLAGGED")) f |= fFLAGGED;
5445 else if (!compare_cstring (t+1,"ANSWERED")) f |= fANSWERED;
5446 else if (!compare_cstring (t+1,"DRAFT")) f |= fDRAFT;
5447 else {
5448 sprintf (msg,"Unsupported system flag: %.80s",t);
5449 MM_LOG (msg,WARN);
5453 else { /* keyword flag */
5454 for (i = j = 0; /* user flag, search through table */
5455 !i && (j < NUSERFLAGS) && (s = stream->user_flags[j]); ++j)
5456 if (!compare_cstring (t,s)) *uf |= i = 1 << j;
5457 if (!i) { /* flag not found, can it be created? */
5458 if (stream->kwd_create && (j < NUSERFLAGS) && *t &&
5459 (strlen (t) <= MAXUSERFLAG)) {
5460 for (s = t; t && *s; s++) switch (*s) {
5461 default: /* all other characters */
5462 /* SPACE, CTL, or not CHAR */
5463 if ((*s > ' ') && (*s < 0x7f)) break;
5464 case '*': case '%': /* list_wildcards */
5465 case '"': case '\\':/* quoted-specials */
5466 /* atom_specials */
5467 case '(': case ')': case '{':
5468 case ']': /* resp-specials */
5469 sprintf (msg,"Invalid flag: %.80s",t);
5470 MM_LOG (msg,WARN);
5471 t = NIL;
5473 if (t) { /* only if valid */
5474 *uf |= 1 << j; /* set the bit */
5475 stream->user_flags[j] = cpystr (t);
5476 /* if out of user flags */
5477 if (j == NUSERFLAGS - 1) stream->kwd_create = NIL;
5480 else {
5481 if (*t) sprintf (msg,"Unknown flag: %.80s",t);
5482 else strcpy (msg,"Empty flag invalid");
5483 MM_LOG (msg,WARN);
5489 return f;
5492 /* Mail check network stream for usability with new name
5493 * Accepts: MAIL stream
5494 * candidate new name
5495 * Returns: T if stream can be used, NIL otherwise
5496 */
5498 long mail_usable_network_stream (MAILSTREAM *stream,char *name)
5500 NETMBX smb,nmb,omb;
5501 return (stream && stream->dtb && !(stream->dtb->flags & DR_LOCAL) &&
5502 mail_valid_net_parse (name,&nmb) &&
5503 mail_valid_net_parse (stream->mailbox,&smb) &&
5504 mail_valid_net_parse (stream->original_mailbox,&omb) &&
5505 ((!compare_cstring (smb.host,
5506 trustdns ? tcp_canonical (nmb.host) : nmb.host)&&
5507 !strcmp (smb.service,nmb.service) &&
5508 (!nmb.port || (smb.port == nmb.port)) &&
5509 (nmb.anoflag == stream->anonymous) &&
5510 (!nmb.user[0] || !strcmp (smb.user,nmb.user))) ||
5511 (!compare_cstring (omb.host,nmb.host) &&
5512 !strcmp (omb.service,nmb.service) &&
5513 (!nmb.port || (omb.port == nmb.port)) &&
5514 (nmb.anoflag == stream->anonymous) &&
5515 (!nmb.user[0] || !strcmp (omb.user,nmb.user))))) ? LONGT : NIL;
5518 /* Mail data structure instantiation routines */
5521 /* Mail instantiate cache elt
5522 * Accepts: initial message number
5523 * Returns: new cache elt
5524 */
5526 MESSAGECACHE *mail_new_cache_elt (unsigned long msgno)
5528 MESSAGECACHE *elt = (MESSAGECACHE *) memset (fs_get (sizeof (MESSAGECACHE)),
5529 0,sizeof (MESSAGECACHE));
5530 elt->lockcount = 1; /* initially only cache references it */
5531 elt->msgno = msgno; /* message number */
5532 return elt;
5536 /* Mail instantiate envelope
5537 * Returns: new envelope
5538 */
5540 ENVELOPE *mail_newenvelope (void)
5542 return (ENVELOPE *) memset (fs_get (sizeof (ENVELOPE)),0,sizeof (ENVELOPE));
5546 /* Mail instantiate address
5547 * Returns: new address
5548 */
5550 ADDRESS *mail_newaddr (void)
5552 return (ADDRESS *) memset (fs_get (sizeof (ADDRESS)),0,sizeof (ADDRESS));
5555 /* Mail instantiate body
5556 * Returns: new body
5557 */
5559 BODY *mail_newbody (void)
5561 return mail_initbody ((BODY *) fs_get (sizeof (BODY)));
5565 /* Mail initialize body
5566 * Accepts: body
5567 * Returns: body
5568 */
5570 BODY *mail_initbody (BODY *body)
5572 memset ((void *) body,0,sizeof (BODY));
5573 body->type = TYPETEXT; /* content type */
5574 body->encoding = ENC7BIT; /* content encoding */
5575 return body;
5579 /* Mail instantiate body parameter
5580 * Returns: new body part
5581 */
5583 PARAMETER *mail_newbody_parameter (void)
5585 return (PARAMETER *) memset (fs_get (sizeof(PARAMETER)),0,sizeof(PARAMETER));
5589 /* Mail instantiate body part
5590 * Returns: new body part
5591 */
5593 PART *mail_newbody_part (void)
5595 PART *part = (PART *) memset (fs_get (sizeof (PART)),0,sizeof (PART));
5596 mail_initbody (&part->body); /* initialize the body */
5597 return part;
5601 /* Mail instantiate body message part
5602 * Returns: new body message part
5603 */
5605 MESSAGE *mail_newmsg (void)
5607 return (MESSAGE *) memset (fs_get (sizeof (MESSAGE)),0,sizeof (MESSAGE));
5610 /* Mail instantiate string list
5611 * Returns: new string list
5612 */
5614 STRINGLIST *mail_newstringlist (void)
5616 return (STRINGLIST *) memset (fs_get (sizeof (STRINGLIST)),0,
5617 sizeof (STRINGLIST));
5621 /* Mail instantiate new search program
5622 * Returns: new search program
5623 */
5625 SEARCHPGM *mail_newsearchpgm (void)
5627 return (SEARCHPGM *) memset (fs_get (sizeof(SEARCHPGM)),0,sizeof(SEARCHPGM));
5631 /* Mail instantiate new search program
5632 * Accepts: header line name
5633 * Returns: new search program
5634 */
5636 SEARCHHEADER *mail_newsearchheader (char *line,char *text)
5638 SEARCHHEADER *hdr = (SEARCHHEADER *) memset (fs_get (sizeof (SEARCHHEADER)),
5639 0,sizeof (SEARCHHEADER));
5640 hdr->line.size = strlen ((char *) (hdr->line.data =
5641 (unsigned char *) cpystr (line)));
5642 hdr->text.size = strlen ((char *) (hdr->text.data =
5643 (unsigned char *) cpystr (text)));
5644 return hdr;
5648 /* Mail instantiate new search set
5649 * Returns: new search set
5650 */
5652 SEARCHSET *mail_newsearchset (void)
5654 return (SEARCHSET *) memset (fs_get (sizeof(SEARCHSET)),0,sizeof(SEARCHSET));
5658 /* Mail instantiate new search or
5659 * Returns: new search or
5660 */
5662 SEARCHOR *mail_newsearchor (void)
5664 SEARCHOR *or = (SEARCHOR *) memset (fs_get (sizeof (SEARCHOR)),0,
5665 sizeof (SEARCHOR));
5666 or->first = mail_newsearchpgm ();
5667 or->second = mail_newsearchpgm ();
5668 return or;
5671 /* Mail instantiate new searchpgmlist
5672 * Returns: new searchpgmlist
5673 */
5675 SEARCHPGMLIST *mail_newsearchpgmlist (void)
5677 SEARCHPGMLIST *pgl = (SEARCHPGMLIST *)
5678 memset (fs_get (sizeof (SEARCHPGMLIST)),0,sizeof (SEARCHPGMLIST));
5679 pgl->pgm = mail_newsearchpgm ();
5680 return pgl;
5684 /* Mail instantiate new sortpgm
5685 * Returns: new sortpgm
5686 */
5688 SORTPGM *mail_newsortpgm (void)
5690 return (SORTPGM *) memset (fs_get (sizeof (SORTPGM)),0,sizeof (SORTPGM));
5694 /* Mail instantiate new threadnode
5695 * Accepts: sort cache for thread node
5696 * Returns: new threadnode
5697 */
5699 THREADNODE *mail_newthreadnode (SORTCACHE *sc)
5701 THREADNODE *thr = (THREADNODE *) memset (fs_get (sizeof (THREADNODE)),0,
5702 sizeof (THREADNODE));
5703 if (sc) thr->sc = sc; /* initialize sortcache */
5704 return thr;
5708 /* Mail instantiate new acllist
5709 * Returns: new acllist
5710 */
5712 ACLLIST *mail_newacllist (void)
5714 return (ACLLIST *) memset (fs_get (sizeof (ACLLIST)),0,sizeof (ACLLIST));
5718 /* Mail instantiate new quotalist
5719 * Returns: new quotalist
5720 */
5722 QUOTALIST *mail_newquotalist (void)
5724 return (QUOTALIST *) memset (fs_get (sizeof (QUOTALIST)),0,
5725 sizeof (QUOTALIST));
5728 /* Mail garbage collection routines */
5731 /* Mail garbage collect body
5732 * Accepts: pointer to body pointer
5733 */
5735 void mail_free_body (BODY **body)
5737 if (*body) { /* only free if exists */
5738 mail_free_body_data (*body);/* free its data */
5739 fs_give ((void **) body); /* return body to free storage */
5744 /* Mail garbage collect body data
5745 * Accepts: body pointer
5746 */
5748 void mail_free_body_data (BODY *body)
5750 switch (body->type) { /* free contents */
5751 case TYPEMULTIPART: /* multiple part */
5752 mail_free_body_part (&body->nested.part);
5753 break;
5754 case TYPEMESSAGE: /* encapsulated message */
5755 if (body->subtype && !strcmp (body->subtype,"RFC822")) {
5756 mail_free_stringlist (&body->nested.msg->lines);
5757 mail_gc_msg (body->nested.msg,GC_ENV | GC_TEXTS);
5759 if (body->nested.msg) fs_give ((void **) &body->nested.msg);
5760 break;
5761 default:
5762 break;
5764 if (body->subtype) fs_give ((void **) &body->subtype);
5765 mail_free_body_parameter (&body->parameter);
5766 if (body->id) fs_give ((void **) &body->id);
5767 if (body->description) fs_give ((void **) &body->description);
5768 if (body->disposition.type) fs_give ((void **) &body->disposition.type);
5769 if (body->disposition.parameter)
5770 mail_free_body_parameter (&body->disposition.parameter);
5771 if (body->language) mail_free_stringlist (&body->language);
5772 if (body->location) fs_give ((void **) &body->location);
5773 if (body->mime.text.data) fs_give ((void **) &body->mime.text.data);
5774 if (body->contents.text.data) fs_give ((void **) &body->contents.text.data);
5775 if (body->md5) fs_give ((void **) &body->md5);
5776 if (mailfreebodysparep && body->sparep)
5777 (*mailfreebodysparep) (&body->sparep);
5780 /* Mail garbage collect body parameter
5781 * Accepts: pointer to body parameter pointer
5782 */
5784 void mail_free_body_parameter (PARAMETER **parameter)
5786 if (*parameter) { /* only free if exists */
5787 if ((*parameter)->attribute) fs_give ((void **) &(*parameter)->attribute);
5788 if ((*parameter)->value) fs_give ((void **) &(*parameter)->value);
5789 /* run down the list as necessary */
5790 mail_free_body_parameter (&(*parameter)->next);
5791 /* return body part to free storage */
5792 fs_give ((void **) parameter);
5797 /* Mail garbage collect body part
5798 * Accepts: pointer to body part pointer
5799 */
5801 void mail_free_body_part (PART **part)
5803 if (*part) { /* only free if exists */
5804 mail_free_body_data (&(*part)->body);
5805 /* run down the list as necessary */
5806 mail_free_body_part (&(*part)->next);
5807 fs_give ((void **) part); /* return body part to free storage */
5811 /* Mail garbage collect message cache
5812 * Accepts: mail stream
5814 * The message cache is set to NIL when this function finishes.
5815 */
5817 void mail_free_cache (MAILSTREAM *stream)
5819 /* do driver specific stuff first */
5820 mail_gc (stream,GC_ELT | GC_ENV | GC_TEXTS);
5821 /* flush the cache */
5822 (*mailcache) (stream,(long) 0,CH_INIT);
5826 /* Mail garbage collect cache element
5827 * Accepts: pointer to cache element pointer
5828 */
5830 void mail_free_elt (MESSAGECACHE **elt)
5832 /* only free if exists and no sharers */
5833 if (*elt && !--(*elt)->lockcount) {
5834 mail_gc_msg (&(*elt)->private.msg,GC_ENV | GC_TEXTS);
5835 if (mailfreeeltsparep && (*elt)->sparep)
5836 (*mailfreeeltsparep) (&(*elt)->sparep);
5837 fs_give ((void **) elt);
5839 else *elt = NIL; /* else simply drop pointer */
5842 /* Mail garbage collect envelope
5843 * Accepts: pointer to envelope pointer
5844 */
5846 void mail_free_envelope (ENVELOPE **env)
5848 if (*env) { /* only free if exists */
5849 if ((*env)->remail) fs_give ((void **) &(*env)->remail);
5850 mail_free_address (&(*env)->return_path);
5851 if ((*env)->date) fs_give ((void **) &(*env)->date);
5852 mail_free_address (&(*env)->from);
5853 mail_free_address (&(*env)->sender);
5854 mail_free_address (&(*env)->reply_to);
5855 if ((*env)->subject) fs_give ((void **) &(*env)->subject);
5856 mail_free_address (&(*env)->to);
5857 mail_free_address (&(*env)->cc);
5858 mail_free_address (&(*env)->bcc);
5859 if ((*env)->in_reply_to) fs_give ((void **) &(*env)->in_reply_to);
5860 if ((*env)->message_id) fs_give ((void **) &(*env)->message_id);
5861 if ((*env)->newsgroups) fs_give ((void **) &(*env)->newsgroups);
5862 if ((*env)->followup_to) fs_give ((void **) &(*env)->followup_to);
5863 if ((*env)->references) fs_give ((void **) &(*env)->references);
5864 if (mailfreeenvelopesparep && (*env)->sparep)
5865 (*mailfreeenvelopesparep) (&(*env)->sparep);
5866 fs_give ((void **) env); /* return envelope to free storage */
5871 /* Mail garbage collect address
5872 * Accepts: pointer to address pointer
5873 */
5875 void mail_free_address (ADDRESS **address)
5877 if (*address) { /* only free if exists */
5878 if ((*address)->personal) fs_give ((void **) &(*address)->personal);
5879 if ((*address)->adl) fs_give ((void **) &(*address)->adl);
5880 if ((*address)->mailbox) fs_give ((void **) &(*address)->mailbox);
5881 if ((*address)->host) fs_give ((void **) &(*address)->host);
5882 if ((*address)->error) fs_give ((void **) &(*address)->error);
5883 if ((*address)->orcpt.type) fs_give ((void **) &(*address)->orcpt.type);
5884 if ((*address)->orcpt.addr) fs_give ((void **) &(*address)->orcpt.addr);
5885 mail_free_address (&(*address)->next);
5886 fs_give ((void **) address);/* return address to free storage */
5891 /* Mail garbage collect stringlist
5892 * Accepts: pointer to stringlist pointer
5893 */
5895 void mail_free_stringlist (STRINGLIST **string)
5897 if (*string) { /* only free if exists */
5898 if ((*string)->text.data) fs_give ((void **) &(*string)->text.data);
5899 mail_free_stringlist (&(*string)->next);
5900 fs_give ((void **) string); /* return string to free storage */
5904 /* Mail garbage collect searchpgm
5905 * Accepts: pointer to searchpgm pointer
5906 */
5908 void mail_free_searchpgm (SEARCHPGM **pgm)
5910 if (*pgm) { /* only free if exists */
5911 mail_free_searchset (&(*pgm)->msgno);
5912 mail_free_searchset (&(*pgm)->uid);
5913 mail_free_searchor (&(*pgm)->or);
5914 mail_free_searchpgmlist (&(*pgm)->not);
5915 mail_free_searchheader (&(*pgm)->header);
5916 mail_free_stringlist (&(*pgm)->bcc);
5917 mail_free_stringlist (&(*pgm)->body);
5918 mail_free_stringlist (&(*pgm)->cc);
5919 mail_free_stringlist (&(*pgm)->from);
5920 mail_free_stringlist (&(*pgm)->keyword);
5921 mail_free_stringlist (&(*pgm)->subject);
5922 mail_free_stringlist (&(*pgm)->text);
5923 mail_free_stringlist (&(*pgm)->to);
5924 fs_give ((void **) pgm); /* return program to free storage */
5929 /* Mail garbage collect searchheader
5930 * Accepts: pointer to searchheader pointer
5931 */
5933 void mail_free_searchheader (SEARCHHEADER **hdr)
5935 if (*hdr) { /* only free if exists */
5936 if ((*hdr)->line.data) fs_give ((void **) &(*hdr)->line.data);
5937 if ((*hdr)->text.data) fs_give ((void **) &(*hdr)->text.data);
5938 mail_free_searchheader (&(*hdr)->next);
5939 fs_give ((void **) hdr); /* return header to free storage */
5944 /* Mail garbage collect searchset
5945 * Accepts: pointer to searchset pointer
5946 */
5948 void mail_free_searchset (SEARCHSET **set)
5950 if (*set) { /* only free if exists */
5951 mail_free_searchset (&(*set)->next);
5952 fs_give ((void **) set); /* return set to free storage */
5956 /* Mail garbage collect searchor
5957 * Accepts: pointer to searchor pointer
5958 */
5960 void mail_free_searchor (SEARCHOR **orl)
5962 if (*orl) { /* only free if exists */
5963 mail_free_searchpgm (&(*orl)->first);
5964 mail_free_searchpgm (&(*orl)->second);
5965 mail_free_searchor (&(*orl)->next);
5966 fs_give ((void **) orl); /* return searchor to free storage */
5971 /* Mail garbage collect search program list
5972 * Accepts: pointer to searchpgmlist pointer
5973 */
5975 void mail_free_searchpgmlist (SEARCHPGMLIST **pgl)
5977 if (*pgl) { /* only free if exists */
5978 mail_free_searchpgm (&(*pgl)->pgm);
5979 mail_free_searchpgmlist (&(*pgl)->next);
5980 fs_give ((void **) pgl); /* return searchpgmlist to free storage */
5985 /* Mail garbage collect namespace
5986 * Accepts: poiner to namespace
5987 */
5989 void mail_free_namespace (NAMESPACE **n)
5991 if (*n) {
5992 fs_give ((void **) &(*n)->name);
5993 mail_free_namespace (&(*n)->next);
5994 mail_free_body_parameter (&(*n)->param);
5995 fs_give ((void **) n); /* return namespace to free storage */
5999 /* Mail garbage collect sort program
6000 * Accepts: pointer to sortpgm pointer
6001 */
6003 void mail_free_sortpgm (SORTPGM **pgm)
6005 if (*pgm) { /* only free if exists */
6006 mail_free_sortpgm (&(*pgm)->next);
6007 fs_give ((void **) pgm); /* return sortpgm to free storage */
6012 /* Mail garbage collect thread node
6013 * Accepts: pointer to threadnode pointer
6014 */
6016 void mail_free_threadnode (THREADNODE **thr)
6018 if (*thr) { /* only free if exists */
6019 mail_free_threadnode (&(*thr)->branch);
6020 mail_free_threadnode (&(*thr)->next);
6021 fs_give ((void **) thr); /* return threadnode to free storage */
6026 /* Mail garbage collect acllist
6027 * Accepts: pointer to acllist pointer
6028 */
6030 void mail_free_acllist (ACLLIST **al)
6032 if (*al) { /* only free if exists */
6033 if ((*al)->identifier) fs_give ((void **) &(*al)->identifier);
6034 if ((*al)->rights) fs_give ((void **) &(*al)->rights);
6035 mail_free_acllist (&(*al)->next);
6036 fs_give ((void **) al); /* return acllist to free storage */
6041 /* Mail garbage collect quotalist
6042 * Accepts: pointer to quotalist pointer
6043 */
6045 void mail_free_quotalist (QUOTALIST **ql)
6047 if (*ql) { /* only free if exists */
6048 if ((*ql)->name) fs_give ((void **) &(*ql)->name);
6049 mail_free_quotalist (&(*ql)->next);
6050 fs_give ((void **) ql); /* return quotalist to free storage */
6054 /* Link authenicator
6055 * Accepts: authenticator to add to list
6056 */
6058 void auth_link (AUTHENTICATOR *auth)
6060 if (!auth->valid || (*auth->valid) ()) {
6061 AUTHENTICATOR **a = &mailauthenticators;
6062 while (*a) a = &(*a)->next; /* find end of list of authenticators */
6063 *a = auth; /* put authenticator at the end */
6064 auth->next = NIL; /* this authenticator is the end of the list */
6069 /* Authenticate access
6070 * Accepts: mechanism name
6071 * responder function
6072 * argument count
6073 * argument vector
6074 * Returns: authenticated user name or NIL
6075 */
6077 char *mail_auth (char *mechanism,authresponse_t resp,int argc,char *argv[])
6079 AUTHENTICATOR *auth;
6080 for (auth = mailauthenticators; auth; auth = auth->next)
6081 if (auth->server && !compare_cstring (auth->name,mechanism))
6082 return (!(auth->flags & AU_DISABLE) &&
6083 ((auth->flags & AU_SECURE) ||
6084 #ifdef QMAIL
6085 getenv("INTRANET") ||
6086 #endif
6087 !mail_parameters (NIL,GET_DISABLEPLAINTEXT,NIL))) ?
6088 (*auth->server) (resp,argc,argv) : NIL;
6089 return NIL; /* no authenticator found */
6092 /* Lookup authenticator index
6093 * Accepts: authenticator index
6094 * Returns: authenticator, or 0 if not found
6095 */
6097 AUTHENTICATOR *mail_lookup_auth (unsigned long i)
6099 AUTHENTICATOR *auth = mailauthenticators;
6100 while (auth && --i) auth = auth->next;
6101 return auth;
6105 /* Lookup authenticator name
6106 * Accepts: authenticator name
6107 * required authenticator flags
6108 * Returns: index in authenticator chain, or 0 if not found
6109 */
6111 unsigned int mail_lookup_auth_name (char *mechanism,long flags)
6113 int i;
6114 AUTHENTICATOR *auth;
6115 for (i = 1, auth = mailauthenticators; auth; i++, auth = auth->next)
6116 if (auth->client && !(flags & ~auth->flags) &&
6117 !(auth->flags & AU_DISABLE) && !compare_cstring (auth->name,mechanism))
6118 return i;
6119 return 0;
6122 /* Standard TCP/IP network driver */
6124 static NETDRIVER tcpdriver = {
6125 tcp_open, /* open connection */
6126 tcp_aopen, /* open preauthenticated connection */
6127 tcp_getline, /* get a line */
6128 tcp_getbuffer, /* get a buffer */
6129 tcp_soutr, /* output pushed data */
6130 tcp_sout, /* output string */
6131 tcp_close, /* close connection */
6132 tcp_host, /* return host name */
6133 tcp_remotehost, /* return remote host name */
6134 tcp_port, /* return port number */
6135 tcp_localhost /* return local host name */
6136 };
6139 /* Network open
6140 * Accepts: NETMBX specifier to open
6141 * default network driver
6142 * default port
6143 * SSL driver
6144 * SSL service name
6145 * SSL driver port
6146 * Returns: Network stream if success, else NIL
6147 */
6149 NETSTREAM *net_open (NETMBX *mb,NETDRIVER *dv,unsigned long port,
6150 NETDRIVER *ssld,char *ssls,unsigned long sslp)
6152 NETSTREAM *stream = NIL;
6153 char tmp[MAILTMPLEN];
6154 unsigned long flags = mb->novalidate ? NET_NOVALIDATECERT : 0;
6155 if (strlen (mb->host) >= NETMAXHOST) {
6156 sprintf (tmp,"Invalid host name: %.80s",mb->host);
6157 MM_LOG (tmp,ERROR);
6159 /* use designated driver if given */
6160 else if (dv) stream = net_open_work (dv,mb->host,mb->service,port,mb->port,
6161 flags);
6162 else if (mb->sslflag && ssld) /* use ssl if sslflag lit */
6163 stream = net_open_work (ssld,mb->host,ssls,sslp,mb->port,flags);
6164 /* if trysslfirst and can open ssl... */
6165 else if ((mb->trysslflag || trysslfirst) && ssld &&
6166 (stream = net_open_work (ssld,mb->host,ssls,sslp,mb->port,
6167 flags | NET_SILENT | NET_TRYSSL))) {
6168 if (net_sout (stream,"",0)) mb->sslflag = T;
6169 else {
6170 net_close (stream); /* flush fake SSL stream */
6171 stream = NIL;
6174 /* default to TCP driver */
6175 else stream = net_open_work (&tcpdriver,mb->host,mb->service,port,mb->port,
6176 flags);
6177 return stream;
6180 /* Network open worker routine
6181 * Accepts: network driver
6182 * host name
6183 * service name to look up port
6184 * port number if service name not found
6185 * port number to override service name
6186 * flags (passed on top of port)
6187 * Returns: Network stream if success, else NIL
6188 */
6190 NETSTREAM *net_open_work (NETDRIVER *dv,char *host,char *service,
6191 unsigned long port,unsigned long portoverride,
6192 unsigned long flags)
6194 NETSTREAM *stream = NIL;
6195 void *tstream;
6196 if (service && (*service == '*')) {
6197 flags |= NET_NOOPENTIMEOUT; /* mark that no timeout is desired */
6198 ++service; /* no longer need the no timeout indicator */
6200 if (portoverride) { /* explicit port number? */
6201 service = NIL; /* yes, override service name */
6202 port = portoverride; /* use that instead of default port */
6204 if (tstream = (*dv->open) (host,service,port | flags)) {
6205 stream = (NETSTREAM *) fs_get (sizeof (NETSTREAM));
6206 stream->stream = tstream;
6207 stream->dtb = dv;
6209 return stream;
6213 /* Network authenticated open
6214 * Accepts: network driver
6215 * NETMBX specifier
6216 * service specifier
6217 * return user name buffer
6218 * Returns: Network stream if success else NIL
6219 */
6221 NETSTREAM *net_aopen (NETDRIVER *dv,NETMBX *mb,char *service,char *user)
6223 NETSTREAM *stream = NIL;
6224 void *tstream;
6225 if (!dv) dv = &tcpdriver; /* default to TCP driver */
6226 if (tstream = (*dv->aopen) (mb,service,user)) {
6227 stream = (NETSTREAM *) fs_get (sizeof (NETSTREAM));
6228 stream->stream = tstream;
6229 stream->dtb = dv;
6231 return stream;
6234 /* Network receive line
6235 * Accepts: Network stream
6236 * Returns: text line string or NIL if failure
6237 */
6239 char *net_getline (NETSTREAM *stream)
6241 return (*stream->dtb->getline) (stream->stream);
6245 /* Network receive buffer
6246 * Accepts: Network stream (must be void * for use as readfn_t)
6247 * size in bytes
6248 * buffer to read into
6249 * Returns: T if success, NIL otherwise
6250 */
6252 long net_getbuffer (void *st,unsigned long size,char *buffer)
6254 NETSTREAM *stream = (NETSTREAM *) st;
6255 return (*stream->dtb->getbuffer) (stream->stream,size,buffer);
6259 /* Network send null-terminated string
6260 * Accepts: Network stream
6261 * string pointer
6262 * Returns: T if success else NIL
6263 */
6265 long net_soutr (NETSTREAM *stream,char *string)
6267 return (*stream->dtb->soutr) (stream->stream,string);
6271 /* Network send string
6272 * Accepts: Network stream
6273 * string pointer
6274 * byte count
6275 * Returns: T if success else NIL
6276 */
6278 long net_sout (NETSTREAM *stream,char *string,unsigned long size)
6280 return (*stream->dtb->sout) (stream->stream,string,size);
6283 /* Network close
6284 * Accepts: Network stream
6285 */
6287 void net_close (NETSTREAM *stream)
6289 if (stream->stream) (*stream->dtb->close) (stream->stream);
6290 fs_give ((void **) &stream);
6294 /* Network get host name
6295 * Accepts: Network stream
6296 * Returns: host name for this stream
6297 */
6299 char *net_host (NETSTREAM *stream)
6301 return (*stream->dtb->host) (stream->stream);
6305 /* Network get remote host name
6306 * Accepts: Network stream
6307 * Returns: host name for this stream
6308 */
6310 char *net_remotehost (NETSTREAM *stream)
6312 return (*stream->dtb->remotehost) (stream->stream);
6315 /* Network return port for this stream
6316 * Accepts: Network stream
6317 * Returns: port number for this stream
6318 */
6320 unsigned long net_port (NETSTREAM *stream)
6322 return (*stream->dtb->port) (stream->stream);
6326 /* Network get local host name
6327 * Accepts: Network stream
6328 * Returns: local host name
6329 */
6331 char *net_localhost (NETSTREAM *stream)
6333 return (*stream->dtb->localhost) (stream->stream);

UW-IMAP'd extensions by yuuji