* Rewrite support for specific SSL encryption protocols, including
[alpine.git] / imap / src / c-client / imap4r1.c
blobb74230561fa56e04e4cb8c0e5828ef343434ada8
1 /*
2 * Copyright 2016-2018 Eduardo Chappa
4 * Last Edited: May 5, 2018 Eduardo Chappa <alpine.chappa@gmx.com>
6 */
7 /* ========================================================================
8 * Copyright 2008-2011 Mark Crispin
9 * ========================================================================
12 * Program: Interactive Message Access Protocol 4rev1 (IMAP4R1) routines
14 * Author: Mark Crispin
16 * Date: 15 June 1988
17 * Last Edited: 3 October 2011
19 * Previous versions of this file were
21 * Copyright 1988-2008 University of Washington
23 * Licensed under the Apache License, Version 2.0 (the "License");
24 * you may not use this file except in compliance with the License.
25 * You may obtain a copy of the License at
27 * http://www.apache.org/licenses/LICENSE-2.0
29 * This original version of this file is
30 * Copyright 1988 Stanford University
31 * and was developed in the Symbolic Systems Resources Group of the Knowledge
32 * Systems Laboratory at Stanford University in 1987-88, and was funded by the
33 * Biomedical Research Technology Program of the National Institutes of Health
34 * under grant number RR-00785.
38 #include <ctype.h>
39 #include <stdio.h>
40 #include <time.h>
41 #include "c-client.h"
42 #include "imap4r1.h"
44 /* Parameters */
46 #define IMAPLOOKAHEAD 20 /* envelope lookahead */
47 #define IMAPUIDLOOKAHEAD 1000 /* UID lookahead */
48 #define IMAPTCPPORT (long) 143 /* assigned TCP contact port */
49 #define IMAPSSLPORT (long) 993 /* assigned SSL TCP contact port */
50 #define MAXCOMMAND 1000 /* RFC 2683 guideline for cmd line length */
51 #define IDLETIMEOUT (long) 30 /* defined in RFC 3501 */
52 #define MAXSERVERLIT 0x7ffffffe /* maximum server literal size
53 * must be smaller than 4294967295
57 /* Parsed reply message from imap_reply */
59 typedef struct imap_parsed_reply {
60 unsigned char *line; /* original reply string pointer */
61 unsigned char *tag; /* command tag this reply is for */
62 unsigned char *key; /* reply keyword */
63 unsigned char *text; /* subsequent text */
64 } IMAPPARSEDREPLY;
67 #define IMAPTMPLEN 16*MAILTMPLEN
70 /* IMAP4 I/O stream local data */
72 typedef struct imap_local {
73 NETSTREAM *netstream; /* TCP I/O stream */
74 IMAPPARSEDREPLY reply; /* last parsed reply */
75 MAILSTATUS *stat; /* status to fill in */
76 IMAPCAP cap; /* server capabilities */
77 char *appendmailbox; /* mailbox being appended to */
78 unsigned int uidsearch : 1; /* UID searching */
79 unsigned int byeseen : 1; /* saw a BYE response */
80 /* got implicit capabilities */
81 unsigned int gotcapability : 1;
82 unsigned int setid : 1; /* set id of app */
83 unsigned int sensitive : 1; /* sensitive data in progress */
84 unsigned int tlsflag : 1; /* TLS session */
85 unsigned int tlssslv23 : 1; /* TLS using SSLv23 client method */
86 unsigned int notlsflag : 1; /* TLS not used in session */
87 unsigned int sslflag : 1; /* SSL session */
88 unsigned int tls1 : 1; /* using TLSv1 over SSL */
89 unsigned int tls1_1 : 1; /* using TLSv1_1 over SSL */
90 unsigned int tls1_2 : 1; /* using TLSv1_2 over SSL */
91 unsigned int tls1_3 : 1; /* using TLSv1_3 over SSL */
92 unsigned int novalidate : 1; /* certificate not validated */
93 unsigned int filter : 1; /* filter SEARCH/SORT/THREAD results */
94 unsigned int loser : 1; /* server is a loser */
95 unsigned int saslcancel : 1; /* SASL cancelled by protocol */
96 long authflags; /* required flags for authenticators */
97 unsigned long sortsize; /* sort return data size */
98 unsigned long *sortdata; /* sort return data */
99 struct {
100 unsigned long uid; /* last UID returned */
101 unsigned long msgno; /* last msgno returned */
102 } lastuid;
103 NAMESPACE **namespace; /* namespace return data */
104 THREADNODE *threaddata; /* thread return data */
105 char *referral; /* last referral */
106 char *prefix; /* find prefix */
107 char *user; /* logged-in user */
108 char *reform; /* reformed sequence */
109 char tmp[IMAPTMPLEN]; /* temporary buffer */
110 SEARCHSET *lookahead; /* fetch lookahead */
111 IDLIST *id; /* id of stream */
112 } IMAPLOCAL;
115 /* Convenient access to local data */
117 #define LOCAL ((IMAPLOCAL *) stream->local)
119 /* Arguments to imap_send() */
121 typedef struct imap_argument {
122 int type; /* argument type */
123 void *text; /* argument text */
124 } IMAPARG;
127 /* imap_send() argument types */
129 #define ATOM 0
130 #define NUMBER 1
131 #define FLAGS 2
132 #define ASTRING 3
133 #define LITERAL 4
134 #define LIST 5
135 #define SEARCHPROGRAM 6
136 #define SORTPROGRAM 7
137 #define BODYTEXT 8
138 #define BODYPEEK 9
139 #define BODYCLOSE 10
140 #define SEQUENCE 11
141 #define LISTMAILBOX 12
142 #define MULTIAPPEND 13
143 #define SNLIST 14
144 #define MULTIAPPENDREDO 15
147 /* Append data */
149 typedef struct append_data {
150 append_t af;
151 void *data;
152 char *flags;
153 char *date;
154 STRING *message;
155 } APPENDDATA;
157 /* Function prototypes */
159 DRIVER *imap_valid (char *name);
160 void *imap_parameters (long function,void *value);
161 void imap_scan (MAILSTREAM *stream,char *ref,char *pat,char *contents);
162 void imap_list (MAILSTREAM *stream,char *ref,char *pat);
163 void imap_lsub (MAILSTREAM *stream,char *ref,char *pat);
164 void imap_list_work (MAILSTREAM *stream,char *cmd,char *ref,char *pat,
165 char *contents);
166 long imap_subscribe (MAILSTREAM *stream,char *mailbox);
167 long imap_unsubscribe (MAILSTREAM *stream,char *mailbox);
168 long imap_create (MAILSTREAM *stream,char *mailbox);
169 long imap_delete (MAILSTREAM *stream,char *mailbox);
170 long imap_rename (MAILSTREAM *stream,char *old,char *newname);
171 long imap_manage (MAILSTREAM *stream,char *mailbox,char *command,char *arg2);
172 long imap_status (MAILSTREAM *stream,char *mbx,long flags);
173 MAILSTREAM *imap_open (MAILSTREAM *stream);
174 IMAPPARSEDREPLY *imap_rimap (MAILSTREAM *stream,char *service,NETMBX *mb,
175 char *usr,char *tmp);
176 long imap_anon (MAILSTREAM *stream,char *tmp);
177 long imap_auth (MAILSTREAM *stream,NETMBX *mb,char *tmp,char *usr);
178 long imap_login (MAILSTREAM *stream,NETMBX *mb,char *pwd,char *usr);
179 void *imap_challenge (void *stream,unsigned long *len);
180 long imap_response (void *stream,char *s,unsigned long size);
181 void imap_close (MAILSTREAM *stream,long options);
182 void imap_fast (MAILSTREAM *stream,char *sequence,long flags);
183 void imap_flags (MAILSTREAM *stream,char *sequence,long flags);
184 long imap_overview (MAILSTREAM *stream,overview_t ofn);
185 ENVELOPE *imap_structure (MAILSTREAM *stream,unsigned long msgno,BODY **body,
186 long flags);
187 long imap_msgdata (MAILSTREAM *stream,unsigned long msgno,char *section,
188 unsigned long first,unsigned long last,STRINGLIST *lines,
189 long flags);
190 unsigned long imap_uid (MAILSTREAM *stream,unsigned long msgno);
191 unsigned long imap_msgno (MAILSTREAM *stream,unsigned long uid);
192 void imap_flag (MAILSTREAM *stream,char *sequence,char *flag,long flags);
193 long imap_search (MAILSTREAM *stream,char *charset,SEARCHPGM *pgm,long flags);
194 long imap_search_x_gm_ext1 (MAILSTREAM *stream,char *charset,SEARCHPGM *pgm,long flags);
195 unsigned long *imap_sort (MAILSTREAM *stream,char *charset,SEARCHPGM *spg,
196 SORTPGM *pgm,long flags);
197 THREADNODE *imap_thread (MAILSTREAM *stream,char *type,char *charset,
198 SEARCHPGM *spg,long flags);
199 THREADNODE *imap_thread_work (MAILSTREAM *stream,char *type,char *charset,
200 SEARCHPGM *spg,long flags);
201 long imap_ping (MAILSTREAM *stream);
202 void imap_check (MAILSTREAM *stream);
203 long imap_expunge (MAILSTREAM *stream,char *sequence,long options);
204 long imap_copy (MAILSTREAM *stream,char *sequence,char *mailbox,long options);
205 long imap_append (MAILSTREAM *stream,char *mailbox,append_t af,void *data);
206 long imap_append_referral (char *mailbox,char *tmp,append_t af,void *data,
207 char *flags,char *date,STRING *message,
208 APPENDDATA *map,long options);
209 IMAPPARSEDREPLY *imap_append_single (MAILSTREAM *stream,char *mailbox,
210 char *flags,char *date,STRING *message);
212 void imap_gc (MAILSTREAM *stream,long gcflags);
213 void imap_gc_body (BODY *body);
214 void imap_capability (MAILSTREAM *stream);
215 long imap_acl_work (MAILSTREAM *stream,char *command,IMAPARG *args[]);
217 IMAPPARSEDREPLY *imap_send (MAILSTREAM *stream,char *cmd,IMAPARG *args[]);
218 IMAPPARSEDREPLY *imap_sout (MAILSTREAM *stream,char *tag,char *base,char **s);
219 long imap_soutr (MAILSTREAM *stream,char *string);
220 IMAPPARSEDREPLY *imap_send_astring (MAILSTREAM *stream,char *tag,char **s,
221 SIZEDTEXT *as,long wildok,char *limit);
222 IMAPPARSEDREPLY *imap_send_literal (MAILSTREAM *stream,char *tag,char **s,
223 STRING *st);
224 IMAPPARSEDREPLY *imap_send_spgm (MAILSTREAM *stream,char *tag,char *base,
225 char **s,SEARCHPGM *pgm,char *limit);
226 char *imap_send_spgm_trim (char *base,char *s,char *text);
227 IMAPPARSEDREPLY *imap_send_sset (MAILSTREAM *stream,char *tag,char *base,
228 char **s,SEARCHSET *set,char *prefix,
229 char *limit);
230 IMAPPARSEDREPLY *imap_send_slist (MAILSTREAM *stream,char *tag,char *base,
231 char **s,char *name,STRINGLIST *list,
232 char *limit);
233 void imap_send_sdate (char **s,char *name,unsigned short date);
234 IMAPPARSEDREPLY *imap_reply (MAILSTREAM *stream,char *tag);
235 IMAPPARSEDREPLY *imap_parse_reply (MAILSTREAM *stream,char *text);
236 IMAPPARSEDREPLY *imap_fake (MAILSTREAM *stream,char *tag,char *text);
237 long imap_OK (MAILSTREAM *stream,IMAPPARSEDREPLY *reply);
238 void imap_parse_unsolicited (MAILSTREAM *stream,IMAPPARSEDREPLY *reply);
239 void imap_parse_response (MAILSTREAM *stream,char *text,long errflg,long ntfy);
240 NAMESPACE *imap_parse_namespace (MAILSTREAM *stream,unsigned char **txtptr,
241 IMAPPARSEDREPLY *reply);
242 THREADNODE *imap_parse_thread (MAILSTREAM *stream,unsigned char **txtptr);
243 void imap_parse_header (MAILSTREAM *stream,ENVELOPE **env,SIZEDTEXT *hdr,
244 STRINGLIST *stl);
245 void imap_parse_envelope (MAILSTREAM *stream,ENVELOPE **env,
246 unsigned char **txtptr,IMAPPARSEDREPLY *reply);
247 ADDRESS *imap_parse_adrlist (MAILSTREAM *stream,unsigned char **txtptr,
248 IMAPPARSEDREPLY *reply);
249 ADDRESS *imap_parse_address (MAILSTREAM *stream,unsigned char **txtptr,
250 IMAPPARSEDREPLY *reply);
251 void imap_parse_flags (MAILSTREAM *stream,MESSAGECACHE *elt,
252 unsigned char **txtptr);
253 unsigned long imap_parse_user_flag (MAILSTREAM *stream,char *flag);
254 unsigned char *imap_parse_astring (MAILSTREAM *stream,unsigned char **txtptr,
255 IMAPPARSEDREPLY *reply,unsigned long *len);
256 unsigned char *imap_parse_string (MAILSTREAM *stream,unsigned char **txtptr,
257 IMAPPARSEDREPLY *reply,GETS_DATA *md,
258 unsigned long *len,long flags);
259 void imap_parse_body (GETS_DATA *md,char *seg,unsigned char **txtptr,
260 IMAPPARSEDREPLY *reply);
261 void imap_parse_body_structure (MAILSTREAM *stream,BODY *body,
262 unsigned char **txtptr,IMAPPARSEDREPLY *reply);
263 PARAMETER *imap_parse_body_parameter (MAILSTREAM *stream,
264 unsigned char **txtptr,
265 IMAPPARSEDREPLY *reply);
266 void imap_parse_disposition (MAILSTREAM *stream,BODY *body,
267 unsigned char **txtptr,IMAPPARSEDREPLY *reply);
268 STRINGLIST *imap_parse_language (MAILSTREAM *stream,unsigned char **txtptr,
269 IMAPPARSEDREPLY *reply);
270 STRINGLIST *imap_parse_stringlist (MAILSTREAM *stream,unsigned char **txtptr,
271 IMAPPARSEDREPLY *reply);
272 void imap_parse_extension (MAILSTREAM *stream,unsigned char **txtptr,
273 IMAPPARSEDREPLY *reply);
274 void imap_parse_capabilities (MAILSTREAM *stream,char *t);
275 IMAPPARSEDREPLY *imap_fetch (MAILSTREAM *stream,char *sequence,long flags);
276 char *imap_reform_sequence (MAILSTREAM *stream,char *sequence,long flags);
277 long imap_setid(MAILSTREAM *stream, IDLIST *idlist);
278 IDLIST *imap_parse_idlist(char *text);
280 /* Driver dispatch used by MAIL */
282 DRIVER imapdriver = {
283 "imap", /* driver name */
284 /* driver flags */
285 DR_MAIL|DR_NEWS|DR_NAMESPACE|DR_CRLF|DR_RECYCLE|DR_HALFOPEN,
286 (DRIVER *) NIL, /* next driver */
287 imap_valid, /* mailbox is valid for us */
288 imap_parameters, /* manipulate parameters */
289 imap_scan, /* scan mailboxes */
290 imap_list, /* find mailboxes */
291 imap_lsub, /* find subscribed mailboxes */
292 imap_subscribe, /* subscribe to mailbox */
293 imap_unsubscribe, /* unsubscribe from mailbox */
294 imap_create, /* create mailbox */
295 imap_delete, /* delete mailbox */
296 imap_rename, /* rename mailbox */
297 imap_status, /* status of mailbox */
298 imap_open, /* open mailbox */
299 imap_close, /* close mailbox */
300 imap_fast, /* fetch message "fast" attributes */
301 imap_flags, /* fetch message flags */
302 imap_overview, /* fetch overview */
303 imap_structure, /* fetch message envelopes */
304 NIL, /* fetch message header */
305 NIL, /* fetch message body */
306 imap_msgdata, /* fetch partial message */
307 imap_uid, /* unique identifier */
308 imap_msgno, /* message number */
309 imap_flag, /* modify flags */
310 NIL, /* per-message modify flags */
311 imap_search, /* search for message based on criteria */
312 imap_sort, /* sort messages */
313 imap_thread, /* thread messages */
314 imap_ping, /* ping mailbox to see if still alive */
315 imap_check, /* check for new messages */
316 imap_expunge, /* expunge deleted messages */
317 imap_copy, /* copy messages to another mailbox */
318 imap_append, /* append string message to mailbox */
319 imap_gc /* garbage collect stream */
322 /* prototype stream */
323 MAILSTREAM imapproto = {&imapdriver};
325 /* driver parameters */
326 static unsigned long imap_maxlogintrials = MAXLOGINTRIALS;
327 static long imap_lookahead = IMAPLOOKAHEAD;
328 static long imap_uidlookahead = IMAPUIDLOOKAHEAD;
329 static long imap_fetchlookaheadlimit = IMAPLOOKAHEAD;
330 static long imap_defaultport = 0;
331 static long imap_sslport = 0;
332 static long imap_tryssl = NIL;
333 static long imap_prefetch = IMAPLOOKAHEAD;
334 static long imap_closeonerror = NIL;
335 static imapenvelope_t imap_envelope = NIL;
336 static imapreferral_t imap_referral = NIL;
337 static char *imap_extrahdrs = NIL;
339 /* constants */
340 static char *hdrheader[] = {
341 "BODY.PEEK[HEADER.FIELDS (Newsgroups Content-MD5 Content-Disposition Content-Language Content-Location",
342 "BODY.PEEK[HEADER.FIELDS (Newsgroups Content-Disposition Content-Language Content-Location",
343 "BODY.PEEK[HEADER.FIELDS (Newsgroups Content-Language Content-Location",
344 "BODY.PEEK[HEADER.FIELDS (Newsgroups Content-Location",
345 "BODY.PEEK[HEADER.FIELDS (Newsgroups"
347 static char *hdrtrailer ="Followup-To References)]";
349 /* IMAP validate mailbox
350 * Accepts: mailbox name
351 * Returns: our driver if name is valid, NIL otherwise
354 DRIVER *imap_valid (char *name)
356 return mail_valid_net (name,&imapdriver,NIL,NIL);
360 /* IMAP manipulate driver parameters
361 * Accepts: function code
362 * function-dependent value
363 * Returns: function-dependent return value
366 void *imap_parameters (long function,void *value)
368 switch ((int) function) {
369 case GET_NAMESPACE:
370 if (((IMAPLOCAL *) ((MAILSTREAM *) value)->local)->cap.namespace &&
371 !((IMAPLOCAL *) ((MAILSTREAM *) value)->local)->namespace)
372 imap_send (((MAILSTREAM *) value),"NAMESPACE",NIL);
373 value = (void *) &((IMAPLOCAL *) ((MAILSTREAM *) value)->local)->namespace;
374 break;
375 case GET_THREADERS:
376 value = (void *)
377 ((IMAPLOCAL *) ((MAILSTREAM *) value)->local)->cap.threader;
378 break;
379 case SET_FETCHLOOKAHEAD: /* must use pointer from GET_FETCHLOOKAHEAD */
380 fatal ("SET_FETCHLOOKAHEAD not permitted");
381 case GET_FETCHLOOKAHEAD:
382 value = (void *) &((IMAPLOCAL *) ((MAILSTREAM *) value)->local)->lookahead;
383 break;
384 case SET_MAXLOGINTRIALS:
385 imap_maxlogintrials = (long) value;
386 break;
387 case GET_MAXLOGINTRIALS:
388 value = (void *) imap_maxlogintrials;
389 break;
390 case SET_LOOKAHEAD:
391 imap_lookahead = (long) value;
392 break;
393 case GET_LOOKAHEAD:
394 value = (void *) imap_lookahead;
395 break;
396 case SET_UIDLOOKAHEAD:
397 imap_uidlookahead = (long) value;
398 break;
399 case GET_UIDLOOKAHEAD:
400 value = (void *) imap_uidlookahead;
401 break;
403 case SET_IMAPPORT:
404 imap_defaultport = (long) value;
405 break;
406 case GET_IMAPPORT:
407 value = (void *) imap_defaultport;
408 break;
409 case SET_SSLIMAPPORT:
410 imap_sslport = (long) value;
411 break;
412 case GET_SSLIMAPPORT:
413 value = (void *) imap_sslport;
414 break;
415 case SET_PREFETCH:
416 imap_prefetch = (long) value;
417 break;
418 case GET_PREFETCH:
419 value = (void *) imap_prefetch;
420 break;
421 case SET_CLOSEONERROR:
422 imap_closeonerror = (long) value;
423 break;
424 case GET_CLOSEONERROR:
425 value = (void *) imap_closeonerror;
426 break;
427 case SET_IMAPENVELOPE:
428 imap_envelope = (imapenvelope_t) value;
429 break;
430 case GET_IMAPENVELOPE:
431 value = (void *) imap_envelope;
432 break;
433 case SET_IMAPREFERRAL:
434 imap_referral = (imapreferral_t) value;
435 break;
436 case GET_IMAPREFERRAL:
437 value = (void *) imap_referral;
438 break;
439 case SET_IMAPEXTRAHEADERS:
440 imap_extrahdrs = (char *) value;
441 break;
442 case GET_IMAPEXTRAHEADERS:
443 value = (void *) imap_extrahdrs;
444 break;
445 case SET_IMAPTRYSSL:
446 imap_tryssl = (long) value;
447 break;
448 case GET_IMAPTRYSSL:
449 value = (void *) imap_tryssl;
450 break;
451 case SET_FETCHLOOKAHEADLIMIT:
452 imap_fetchlookaheadlimit = (long) value;
453 break;
454 case GET_FETCHLOOKAHEADLIMIT:
455 value = (void *) imap_fetchlookaheadlimit;
456 break;
458 case SET_IDLETIMEOUT:
459 fatal ("SET_IDLETIMEOUT not permitted");
460 case GET_IDLETIMEOUT:
461 value = (void *) IDLETIMEOUT;
462 break;
463 case SET_IDSTREAM: /* set IMAP server ID */
464 fatal ("SET_IDSTREAM not permitted");
465 case GET_IDSTREAM: /* get IMAP server ID */
466 value = (void *) &((IMAPLOCAL *) ((MAILSTREAM *) value)->local)->id;
467 break;
468 default:
469 value = NIL; /* error case */
470 break;
472 return value;
475 /* IMAP scan mailboxes
476 * Accepts: mail stream
477 * reference
478 * pattern to search
479 * string to scan
482 void imap_scan (MAILSTREAM *stream,char *ref,char *pat,char *contents)
484 imap_list_work (stream,"SCAN",ref,pat,contents);
488 /* IMAP list mailboxes
489 * Accepts: mail stream
490 * reference
491 * pattern to search
494 void imap_list (MAILSTREAM *stream,char *ref,char *pat)
496 imap_list_work (stream,"LIST",ref,pat,NIL);
500 /* IMAP list subscribed mailboxes
501 * Accepts: mail stream
502 * reference
503 * pattern to search
506 void imap_lsub (MAILSTREAM *stream,char *ref,char *pat)
508 void *sdb = NIL;
509 char *s,mbx[MAILTMPLEN],tmp[MAILTMPLEN];
510 /* do it on the server */
511 imap_list_work (stream,"LSUB",ref,pat,NIL);
512 if (*pat == '{') { /* if remote pattern, must be IMAP */
513 if (!imap_valid (pat)) return;
514 ref = NIL; /* good IMAP pattern, punt reference */
516 /* if remote reference, must be valid IMAP */
517 if (ref && (*ref == '{') && !imap_valid (ref)) return;
518 /* kludgy application of reference */
519 if (ref && *ref) sprintf (mbx,"%s%s",ref,pat);
520 else strcpy (mbx,pat);
522 if ((s = sm_read (tmp,&sdb)) != NULL) do if (imap_valid (s) && pmatch (s,mbx))
523 mm_lsub (stream,NIL,s,NIL);
524 /* until no more subscriptions */
525 while ((s = sm_read (tmp,&sdb)) != NULL);
528 /* IMAP find list of mailboxes
529 * Accepts: mail stream
530 * list command
531 * reference
532 * pattern to search
533 * string to scan
536 void imap_list_work (MAILSTREAM *stream,char *cmd,char *ref,char *pat,
537 char *contents)
539 MAILSTREAM *st = stream;
540 int pl;
541 char *s,prefix[MAILTMPLEN],mbx[MAILTMPLEN];
542 IMAPARG *args[4],aref,apat,acont;
543 if (ref && *ref) { /* have a reference? */
544 if (!(imap_valid (ref) && /* make sure valid IMAP name and open stream */
545 ((stream && LOCAL && LOCAL->netstream) ||
546 (stream = mail_open (NIL,ref,OP_HALFOPEN|OP_SILENT))))) return;
547 /* calculate prefix length */
548 pl = strchr (ref,'}') + 1 - ref;
549 strncpy (prefix,ref,pl); /* build prefix */
550 prefix[pl] = '\0'; /* tie off prefix */
551 ref += pl; /* update reference */
553 else {
554 if (!(imap_valid (pat) && /* make sure valid IMAP name and open stream */
555 ((stream && LOCAL && LOCAL->netstream) ||
556 (stream = mail_open (NIL,pat,OP_HALFOPEN|OP_SILENT))))) return;
557 /* calculate prefix length */
558 pl = strchr (pat,'}') + 1 - pat;
559 strncpy (prefix,pat,pl); /* build prefix */
560 prefix[pl] = '\0'; /* tie off prefix */
561 pat += pl; /* update reference */
563 LOCAL->prefix = prefix; /* note prefix */
564 if (contents) { /* want to do a scan? */
565 if (LEVELSCAN (stream)) { /* make sure permitted */
566 args[0] = &aref; args[1] = &apat; args[2] = &acont; args[3] = NIL;
567 aref.type = ASTRING; aref.text = (void *) (ref ? ref : "");
568 apat.type = LISTMAILBOX; apat.text = (void *) pat;
569 acont.type = ASTRING; acont.text = (void *) contents;
570 imap_send (stream,cmd,args);
572 else mm_log ("Scan not valid on this IMAP server",ERROR);
575 else if (LEVELIMAP4 (stream)){/* easy if IMAP4 */
576 args[0] = &aref; args[1] = &apat; args[2] = NIL;
577 aref.type = ASTRING; aref.text = (void *) (ref ? ref : "");
578 apat.type = LISTMAILBOX; apat.text = (void *) pat;
579 /* referrals armed? */
580 if (LOCAL->cap.mbx_ref && mail_parameters (stream,GET_IMAPREFERRAL,NIL)) {
581 /* yes, convert LIST -> RLIST */
582 if (!compare_cstring (cmd,"LIST")) cmd = "RLIST";
583 /* and convert LSUB -> RLSUB */
584 else if (!compare_cstring (cmd,"LSUB")) cmd = "RLSUB";
586 imap_send (stream,cmd,args);
588 else if (LEVEL1176 (stream)) {/* convert to IMAP2 format wildcard */
589 /* kludgy application of reference */
590 if (ref && *ref) sprintf (mbx,"%s%s",ref,pat);
591 else strcpy (mbx,pat);
592 for (s = mbx; *s; s++) if (*s == '%') *s = '*';
593 args[0] = &apat; args[1] = NIL;
594 apat.type = LISTMAILBOX; apat.text = (void *) mbx;
595 if (!(strstr (cmd,"LIST") &&/* if list, try IMAP2bis, then RFC-1176 */
596 strcmp (imap_send (stream,"FIND ALL.MAILBOXES",args)->key,"BAD")) &&
597 !strcmp (imap_send (stream,"FIND MAILBOXES",args)->key,"BAD"))
598 LOCAL->cap.rfc1176 = NIL; /* must be RFC-1064 */
600 LOCAL->prefix = NIL; /* no more prefix */
601 /* close temporary stream if we made one */
602 if (stream != st) mail_close (stream);
605 /* IMAP subscribe to mailbox
606 * Accepts: mail stream
607 * mailbox to add to subscription list
608 * Returns: T on success, NIL on failure
611 long imap_subscribe (MAILSTREAM *stream,char *mailbox)
613 MAILSTREAM *st = stream;
614 long ret = ((stream && LOCAL && LOCAL->netstream) ||
615 (stream = mail_open (NIL,mailbox,OP_HALFOPEN|OP_SILENT))) ?
616 imap_manage (stream,mailbox,LEVELIMAP4 (stream) ?
617 "Subscribe" : "Subscribe Mailbox",NIL) : NIL;
618 /* toss out temporary stream */
619 if (st != stream) mail_close (stream);
620 return ret;
624 /* IMAP unsubscribe to mailbox
625 * Accepts: mail stream
626 * mailbox to delete from manage list
627 * Returns: T on success, NIL on failure
630 long imap_unsubscribe (MAILSTREAM *stream,char *mailbox)
632 MAILSTREAM *st = stream;
633 long ret = ((stream && LOCAL && LOCAL->netstream) ||
634 (stream = mail_open (NIL,mailbox,OP_HALFOPEN|OP_SILENT))) ?
635 imap_manage (stream,mailbox,LEVELIMAP4 (stream) ?
636 "Unsubscribe" : "Unsubscribe Mailbox",NIL) : NIL;
637 /* toss out temporary stream */
638 if (st != stream) mail_close (stream);
639 return ret;
642 /* IMAP create mailbox
643 * Accepts: mail stream
644 * mailbox name to create
645 * Returns: T on success, NIL on failure
648 long imap_create (MAILSTREAM *stream,char *mailbox)
650 return imap_manage (stream,mailbox,"Create",NIL);
654 /* IMAP delete mailbox
655 * Accepts: mail stream
656 * mailbox name to delete
657 * Returns: T on success, NIL on failure
660 long imap_delete (MAILSTREAM *stream,char *mailbox)
662 return imap_manage (stream,mailbox,"Delete",NIL);
666 /* IMAP rename mailbox
667 * Accepts: mail stream
668 * old mailbox name
669 * new mailbox name
670 * Returns: T on success, NIL on failure
673 long imap_rename (MAILSTREAM *stream,char *old,char *newname)
675 return imap_manage (stream,old,"Rename",newname);
678 /* IMAP manage a mailbox
679 * Accepts: mail stream
680 * mailbox to manipulate
681 * command to execute
682 * optional second argument
683 * Returns: T on success, NIL on failure
686 long imap_manage (MAILSTREAM *stream,char *mailbox,char *command,char *arg2)
688 MAILSTREAM *st = stream;
689 IMAPPARSEDREPLY *reply;
690 long ret = NIL;
691 char mbx[MAILTMPLEN],mbx2[MAILTMPLEN];
692 IMAPARG *args[3],ambx,amb2;
693 imapreferral_t ir =
694 (imapreferral_t) mail_parameters (stream,GET_IMAPREFERRAL,NIL);
695 ambx.type = amb2.type = ASTRING; ambx.text = (void *) mbx;
696 amb2.text = (void *) mbx2;
697 args[0] = &ambx; args[1] = args[2] = NIL;
698 /* require valid names and open stream */
699 if (mail_valid_net (mailbox,&imapdriver,NIL,mbx) &&
700 (arg2 ? mail_valid_net (arg2,&imapdriver,NIL,mbx2) : &imapdriver) &&
701 ((stream && LOCAL && LOCAL->netstream) ||
702 (stream = mail_open (NIL,mailbox,OP_HALFOPEN|OP_SILENT)))) {
703 if (arg2) args[1] = &amb2; /* second arg present? */
704 if (!(ret = (imap_OK (stream,reply = imap_send (stream,command,args)))) &&
705 ir && LOCAL->referral) {
706 long code = -1;
707 switch (*command) { /* which command was it? */
708 case 'S': code = REFSUBSCRIBE; break;
709 case 'U': code = REFUNSUBSCRIBE; break;
710 case 'C': code = REFCREATE; break;
711 case 'D': code = REFDELETE; break;
712 case 'R': code = REFRENAME; break;
713 default:
714 fatal ("impossible referral command");
716 if ((code >= 0) && (mailbox = (*ir) (stream,LOCAL->referral,code)))
717 ret = imap_manage (NIL,mailbox,command,(*command == 'R') ?
718 (mailbox + strlen (mailbox) + 1) : NIL);
720 mm_log (reply->text,ret ? NIL : ERROR);
721 /* toss out temporary stream */
722 if (st != stream) mail_close (stream);
724 return ret;
727 /* IMAP status
728 * Accepts: mail stream
729 * mailbox name
730 * status flags
731 * Returns: T on success, NIL on failure
734 long imap_status (MAILSTREAM *stream,char *mbx,long flags)
736 IMAPARG *args[3],ambx,aflg;
737 char tmp[MAILTMPLEN];
738 NETMBX mb;
739 unsigned long i;
740 long ret = NIL;
741 MAILSTREAM *tstream = NIL;
742 /* use given stream if (rev1 or halfopen) and
743 right host */
744 if (!((stream && (LEVELIMAP4rev1 (stream) || stream->halfopen) &&
745 mail_usable_network_stream (stream,mbx)) ||
746 (stream = tstream = mail_open (NIL,mbx,OP_HALFOPEN|OP_SILENT))))
747 return NIL;
748 /* parse mailbox name */
749 mail_valid_net_parse (mbx,&mb);
750 args[0] = &ambx;args[1] = NIL;/* set up first argument as mailbox */
751 ambx.type = ASTRING; ambx.text = (void *) mb.mailbox;
752 if (LEVELIMAP4rev1 (stream)) {/* have STATUS command? */
753 imapreferral_t ir;
754 aflg.type = FLAGS; aflg.text = (void *) tmp;
755 args[1] = &aflg; args[2] = NIL;
756 tmp[0] = tmp[1] = '\0'; /* build flag list */
757 if (flags & SA_MESSAGES) strcat (tmp," MESSAGES");
758 if (flags & SA_RECENT) strcat (tmp," RECENT");
759 if (flags & SA_UNSEEN) strcat (tmp," UNSEEN");
760 if (flags & SA_UIDNEXT) strcat (tmp," UIDNEXT");
761 if (flags & SA_UIDVALIDITY) strcat (tmp," UIDVALIDITY");
762 tmp[0] = '(';
763 strcat (tmp,")");
764 /* send "STATUS mailbox flag" */
765 if (imap_OK (stream,imap_send (stream,"STATUS",args))) ret = T;
766 else if ((ir = (imapreferral_t)
767 mail_parameters (stream,GET_IMAPREFERRAL,NIL)) &&
768 LOCAL->referral &&
769 (mbx = (*ir) (stream,LOCAL->referral,REFSTATUS)))
770 ret = imap_status (NIL,mbx,flags | (stream->debug ? SA_DEBUG : NIL));
773 /* IMAP2 way */
774 else if (imap_OK (stream,imap_send (stream,"EXAMINE",args))) {
775 MAILSTATUS status;
776 status.flags = flags & ~ (SA_UIDNEXT | SA_UIDVALIDITY);
777 status.messages = stream->nmsgs;
778 status.recent = stream->recent;
779 status.unseen = 0;
780 if (flags & SA_UNSEEN) { /* must search to get unseen messages */
781 /* clear search vector */
782 for (i = 1; i <= stream->nmsgs; ++i) mail_elt (stream,i)->searched = NIL;
783 if (imap_OK (stream,imap_send (stream,"SEARCH UNSEEN",NIL)))
784 for (i = 1,status.unseen = 0; i <= stream->nmsgs; i++)
785 if (mail_elt (stream,i)->searched) status.unseen++;
787 strcpy (strchr (strcpy (tmp,stream->mailbox),'}') + 1,mb.mailbox);
788 /* pass status to main program */
789 mm_status (stream,tmp,&status);
790 ret = T; /* note success */
792 if (tstream) mail_close (tstream);
793 return ret; /* success */
796 /* IMAP open
797 * Accepts: stream to open
798 * Returns: stream to use on success, NIL on failure
801 MAILSTREAM *imap_open (MAILSTREAM *stream)
803 unsigned long i,j;
804 char *s,tmp[MAILTMPLEN],usr[MAILTMPLEN];
805 NETMBX mb;
806 IMAPPARSEDREPLY *reply = NIL;
807 imapreferral_t ir =
808 (imapreferral_t) mail_parameters (stream,GET_IMAPREFERRAL,NIL);
809 /* return prototype for OP_PROTOTYPE call */
810 if (!stream) return &imapproto;
811 mail_valid_net_parse (stream->mailbox,&mb);
812 usr[0] = '\0'; /* initially no user name */
813 if (LOCAL) { /* if stream opened earlier by us */
814 /* recycle if still alive */
815 if (LOCAL->netstream && (!stream->halfopen || LOCAL->cap.unselect)) {
816 i = stream->silent; /* temporarily mark silent */
817 stream->silent = T; /* don't give mm_exists() events */
818 j = imap_ping (stream); /* learn if stream still alive */
819 stream->silent = i; /* restore prior state */
820 if (j) { /* was stream still alive? */
821 sprintf (tmp,"Reusing connection to %s",net_host (LOCAL->netstream));
822 if (LOCAL->user) sprintf (tmp + strlen (tmp),"/user=\"%s\"",
823 LOCAL->user);
824 if (!stream->silent) mm_log (tmp,(long) NIL);
825 /* unselect if now want halfopen */
826 if (stream->halfopen) imap_send (stream,"UNSELECT",NIL);
828 else imap_close (stream,NIL);
830 else imap_close (stream,NIL);
832 /* copy flags from name */
833 if (mb.dbgflag) stream->debug = T;
834 if (mb.readonlyflag) stream->rdonly = T;
835 if (mb.anoflag) stream->anonymous = T;
836 if (mb.secflag) stream->secure = T;
837 if (mb.trysslflag || imap_tryssl) stream->tryssl = T;
839 if (!LOCAL) { /* open new connection if no recycle */
840 NETDRIVER *ssld = (NETDRIVER *) mail_parameters (NIL,GET_SSLDRIVER,NIL);
841 unsigned long defprt = imap_defaultport ? imap_defaultport : IMAPTCPPORT;
842 unsigned long sslport = imap_sslport ? imap_sslport : IMAPSSLPORT;
843 stream->local = /* instantiate localdata */
844 (void *) memset (fs_get (sizeof (IMAPLOCAL)),0,sizeof (IMAPLOCAL));
845 /* assume IMAP2bis server */
846 LOCAL->cap.imap2bis = LOCAL->cap.rfc1176 = T;
847 /* in case server is a loser */
848 if (mb.loser) LOCAL->loser = T;
849 /* desirable authenticators */
850 LOCAL->authflags = (stream->secure ? AU_SECURE : NIL) |
851 (mb.authuser[0] ? AU_AUTHUSER : NIL);
852 /* IMAP connection open logic is more complex than net_open() normally
853 * deals with, because of the simap and rimap hacks.
854 * If the session is anonymous, a specific port is given, or if /ssl or
855 * /tls is set, do net_open() since those conditions override everything
856 * else.
858 if (stream->anonymous || mb.port || mb.sslflag || mb.tlsflag)
859 reply = (LOCAL->netstream = net_open (&mb,NIL,defprt,ssld,"*imaps",
860 sslport)) ?
861 imap_reply (stream,NIL) : NIL;
863 * No overriding conditions, so get the best connection that we can. In
864 * order, attempt to open via simap, tryssl, rimap, and finally TCP.
866 /* try simap */
867 else if ((reply = imap_rimap (stream,"*imap",&mb,usr,tmp)) != NULL);
868 else if (ssld && /* try tryssl if enabled */
869 (stream->tryssl || mail_parameters (NIL,GET_TRYSSLFIRST,NIL)) &&
870 (LOCAL->netstream =
871 net_open_work (ssld,mb.host,"*imaps",sslport,mb.port,
872 (mb.novalidate ? NET_NOVALIDATECERT : 0) |
873 NET_SILENT | NET_TRYSSL))) {
874 if (net_sout (LOCAL->netstream,"",0)) {
875 mb.sslflag = T;
876 reply = imap_reply (stream,NIL);
878 else { /* flush fake SSL stream */
879 net_close (LOCAL->netstream);
880 LOCAL->netstream = NIL;
883 /* try rimap first, then TCP */
884 else if (!(reply = imap_rimap (stream,"imap",&mb,usr,tmp)) &&
885 (LOCAL->netstream = net_open (&mb,NIL,defprt,NIL,NIL,NIL)))
886 reply = imap_reply (stream,NIL);
887 /* make sure greeting is good */
888 if (!reply || strcmp (reply->tag,"*") ||
889 (strcmp (reply->key,"OK") && strcmp (reply->key,"PREAUTH"))) {
890 if (reply) mm_log (reply->text,ERROR);
891 return NIL; /* lost during greeting */
894 /* if connected and not preauthenticated */
895 if (LOCAL->netstream && strcmp (reply->key,"PREAUTH")) {
896 sslstart_t stls = (sslstart_t) mail_parameters (NIL,GET_SSLSTART,NIL);
897 /* get server capabilities */
898 if (!LOCAL->gotcapability) imap_capability (stream);
899 if (LOCAL->netstream && /* does server support STARTTLS? */
900 stls && LOCAL->cap.starttls && !mb.sslflag && !mb.notlsflag &&
901 imap_OK (stream,imap_send (stream,"STARTTLS",NIL))) {
902 mb.tlsflag = T; /* TLS OK, get into TLS at this end */
903 LOCAL->netstream->dtb = ssld;
904 if (!(LOCAL->netstream->stream =
905 (*stls) (LOCAL->netstream->stream,mb.host,
906 SSL_MTHD(mb) | (mb.novalidate ? NET_NOVALIDATECERT : NIL)))) {
907 /* drat, drop this connection */
908 if (LOCAL->netstream) net_close (LOCAL->netstream);
909 LOCAL->netstream = NIL;
911 /* get capabilities now that TLS in effect */
912 if (LOCAL->netstream) imap_capability (stream);
914 else if (mb.tlsflag) { /* user specified /tls but can't do it */
915 mm_log ("Unable to negotiate TLS with this server",ERROR);
916 return NIL;
918 if (LOCAL->netstream) { /* still in the land of the living? */
919 if ((long) mail_parameters (NIL,GET_TRUSTDNS,NIL)) {
920 /* remote name for authentication */
921 strncpy (mb.host,(long) mail_parameters(NIL,GET_SASLUSESPTRNAME,NIL)?
922 net_remotehost (LOCAL->netstream) :
923 net_host (LOCAL->netstream),NETMAXHOST-1);
924 mb.host[NETMAXHOST-1] = '\0';
926 /* need new capabilities after login */
927 LOCAL->gotcapability = NIL;
928 if (!(stream->anonymous ? imap_anon (stream,tmp) :
929 (LOCAL->cap.auth ? imap_auth (stream,&mb,tmp,usr) :
930 imap_login (stream,&mb,tmp,usr)))) {
931 /* failed, is there a referral? */
932 if (mb.tlsflag) LOCAL->tlsflag = T;
933 if (ir && LOCAL->referral &&
934 (s = (*ir) (stream,LOCAL->referral,REFAUTHFAILED))) {
935 imap_close (stream,NIL);
936 fs_give ((void **) &stream->mailbox);
937 /* set as new mailbox name to open */
938 stream->mailbox = s;
939 return imap_open (stream);
941 return NIL; /* authentication failed */
943 else if (ir && LOCAL->referral &&
944 (s = (*ir) (stream,LOCAL->referral,REFAUTH))) {
945 imap_close (stream,NIL);
946 fs_give ((void **) &stream->mailbox);
947 stream->mailbox = s; /* set as new mailbox name to open */
948 /* recurse to log in on real site */
949 return imap_open (stream);
953 /* get server capabilities again */
954 if (LOCAL->netstream && !LOCAL->gotcapability) imap_capability (stream);
955 /* save state for future recycling */
956 if (mb.tlsflag) LOCAL->tlsflag = T;
957 if (mb.tls1) LOCAL->tls1 = T;
958 if (mb.tls1_1) LOCAL->tls1_1 = T;
959 if (mb.tls1_2) LOCAL->tls1_2 = T;
960 if (mb.tls1_3) LOCAL->tls1_3 = T;
961 if (mb.tlssslv23) LOCAL->tlssslv23 = T;
962 if (mb.notlsflag) LOCAL->notlsflag = T;
963 if (mb.sslflag) LOCAL->sslflag = T;
964 if (mb.novalidate) LOCAL->novalidate = T;
965 if (mb.loser) LOCAL->loser = T;
968 if (LOCAL->netstream) { /* still have a connection? */
969 stream->perm_seen = stream->perm_deleted = stream->perm_answered =
970 stream->perm_draft = LEVELIMAP4 (stream) ? NIL : T;
971 stream->perm_user_flags = LEVELIMAP4 (stream) ? NIL : 0xffffffff;
972 stream->sequence++; /* bump sequence number */
973 sprintf (tmp,"{%s",(long) mail_parameters (NIL,GET_TRUSTDNS,NIL) ?
974 net_host (LOCAL->netstream) : mb.host);
975 if (!((i = net_port (LOCAL->netstream)) & 0xffff0000))
976 sprintf (tmp + strlen (tmp),":%lu",i);
977 strcat (tmp,"/imap");
978 if (LOCAL->tlsflag) strcat (tmp,"/tls");
979 if (LOCAL->tls1) strcat (tmp,"/tls1");
980 if (LOCAL->tls1_1) strcat (tmp,"/tls1_1");
981 if (LOCAL->tls1_2) strcat (tmp,"/tls1_2");
982 if (LOCAL->tls1_3) strcat (tmp,"/tls1_3");
983 if (LOCAL->tlssslv23) strcat (tmp,"/tls-sslv23");
984 if (LOCAL->notlsflag) strcat (tmp,"/notls");
985 if (LOCAL->sslflag) strcat (tmp,"/ssl");
986 if (LOCAL->novalidate) strcat (tmp,"/novalidate-cert");
987 if (LOCAL->loser) strcat (tmp,"/loser");
988 if (stream->secure) strcat (tmp,"/secure");
989 if (stream->rdonly) strcat (tmp,"/readonly");
990 if (stream->anonymous) strcat (tmp,"/anonymous");
991 else { /* record user name */
992 if (!LOCAL->user && usr[0]) LOCAL->user = cpystr (usr);
993 if (LOCAL->user) sprintf (tmp + strlen (tmp),"/user=\"%s\"",
994 LOCAL->user);
996 strcat (tmp,"}");
998 if(LEVELID(stream)){ /* Set ID of app */
999 IDLIST *idapp = (IDLIST *) mail_parameters(NIL, GET_IDPARAMS, NIL);
1000 if(idapp && !LOCAL->setid){
1001 imap_setid(stream, idapp);
1002 LOCAL->setid++;
1005 if (!stream->halfopen) { /* wants to open a mailbox? */
1006 IMAPARG *args[2];
1007 IMAPARG ambx;
1008 ambx.type = ASTRING;
1009 ambx.text = (void *) mb.mailbox;
1010 args[0] = &ambx; args[1] = NIL;
1011 stream->nmsgs = 0;
1012 if (imap_OK (stream,reply = imap_send (stream,stream->rdonly ?
1013 "EXAMINE": "SELECT",args))) {
1014 strcat (tmp,mb.mailbox);/* mailbox name */
1015 if (!stream->nmsgs && !stream->silent)
1016 mm_log ("Mailbox is empty",(long) NIL);
1017 /* note if an INBOX or not */
1018 stream->inbox = !compare_cstring (mb.mailbox,"INBOX");
1020 else if (ir && LOCAL->referral &&
1021 (s = (*ir) (stream,LOCAL->referral,REFSELECT))) {
1022 imap_close (stream,NIL);
1023 fs_give ((void **) &stream->mailbox);
1024 stream->mailbox = s; /* set as new mailbox name to open */
1025 return imap_open (stream);
1027 else {
1028 mm_log (reply->text,ERROR);
1029 if (imap_closeonerror) return NIL;
1030 stream->halfopen = T; /* let him keep it half-open */
1033 if (stream->halfopen) { /* half-open connection? */
1034 strcat (tmp,"<no_mailbox>");
1035 /* make sure dummy message counts */
1036 mail_exists (stream,(long) 0);
1037 mail_recent (stream,(long) 0);
1039 fs_give ((void **) &stream->mailbox);
1040 stream->mailbox = cpystr (tmp);
1042 /* success if stream open */
1043 return LOCAL->netstream ? stream : NIL;
1046 /* IMAP rimap connect
1047 * Accepts: MAIL stream
1048 * NETMBX specification
1049 * service to use
1050 * user name
1051 * scratch buffer
1052 * Returns: parsed reply if success, else NIL
1055 IMAPPARSEDREPLY *imap_rimap (MAILSTREAM *stream,char *service,NETMBX *mb,
1056 char *usr,char *tmp)
1058 unsigned long i;
1059 char c[2];
1060 NETSTREAM *tstream;
1061 IMAPPARSEDREPLY *reply = NIL;
1062 /* try rimap open */
1063 if (!mb->norsh && (tstream = net_aopen (NIL,mb,service,usr))) {
1064 /* if success, see if reasonable banner */
1065 if (net_getbuffer (tstream,(long) 1,c) && (*c == '*')) {
1066 i = 0; /* copy to buffer */
1067 do tmp[i++] = *c;
1068 while (net_getbuffer (tstream,(long) 1,c) && (*c != '\015') &&
1069 (*c != '\012') && (i < (MAILTMPLEN-1)));
1070 tmp[i] = '\0'; /* tie off */
1071 /* snarfed a valid greeting? */
1072 if ((*c == '\015') && net_getbuffer (tstream,(long) 1,c) &&
1073 (*c == '\012') &&
1074 !strcmp ((reply = imap_parse_reply (stream,cpystr (tmp)))->tag,"*")){
1075 /* parse line as IMAP */
1076 imap_parse_unsolicited (stream,reply);
1077 /* make sure greeting is good */
1078 if (!strcmp (reply->key,"OK") || !strcmp (reply->key,"PREAUTH")) {
1079 LOCAL->netstream = tstream;
1080 return reply; /* return success */
1084 net_close (tstream); /* failed, punt the temporary netstream */
1086 return NIL;
1089 /* IMAP log in as anonymous
1090 * Accepts: stream to authenticate
1091 * scratch buffer
1092 * Returns: T on success, NIL on failure
1095 long imap_anon (MAILSTREAM *stream,char *tmp)
1097 IMAPPARSEDREPLY *reply;
1098 char *s = net_localhost (LOCAL->netstream);
1099 if (LOCAL->cap.authanon) {
1100 char tag[16];
1101 unsigned long i;
1102 char *broken = "[CLOSED] IMAP connection broken (anonymous auth)";
1103 sprintf (tag,"%08lx",0xffffffff & (stream->gensym++));
1104 /* build command */
1105 sprintf (tmp,"%s AUTHENTICATE ANONYMOUS",tag);
1106 if (!imap_soutr (stream,tmp)) {
1107 mm_log (broken,ERROR);
1108 return NIL;
1110 if (imap_challenge (stream,&i)) imap_response (stream,s,strlen (s));
1111 /* get response */
1112 if (!(reply = &LOCAL->reply)->tag) reply = imap_fake (stream,tag,broken);
1113 /* what we wanted? */
1114 if (compare_cstring (reply->tag,tag)) {
1115 /* abort if don't have tagged response */
1116 while (compare_cstring ((reply = imap_reply (stream,tag))->tag,tag))
1117 imap_soutr (stream,"*");
1120 else {
1121 IMAPARG *args[2];
1122 IMAPARG ausr;
1123 ausr.type = ASTRING;
1124 ausr.text = (void *) s;
1125 args[0] = &ausr; args[1] = NIL;
1126 /* send "LOGIN anonymous <host>" */
1127 reply = imap_send (stream,"LOGIN ANONYMOUS",args);
1129 /* success if reply OK */
1130 if (imap_OK (stream,reply)) return T;
1131 mm_log (reply->text,ERROR);
1132 return NIL;
1135 /* IMAP authenticate
1136 * Accepts: stream to authenticate
1137 * parsed network mailbox structure
1138 * scratch buffer
1139 * place to return user name
1140 * Returns: T on success, NIL on failure
1143 long imap_auth (MAILSTREAM *stream,NETMBX *mb,char *tmp,char *usr)
1145 unsigned long trial,ua;
1146 int ok;
1147 char tag[16];
1148 char *lsterr = NIL;
1149 AUTHENTICATOR *at;
1150 IMAPPARSEDREPLY *reply;
1151 for (ua = LOCAL->cap.auth, LOCAL->saslcancel = NIL; LOCAL->netstream && ua &&
1152 (at = mail_lookup_auth (find_rightmost_bit (&ua) + 1));) {
1153 if (lsterr) { /* previous authenticator failed? */
1154 sprintf (tmp,"Retrying using %s authentication after %.80s",
1155 at->name,lsterr);
1156 mm_log (tmp,NIL);
1157 fs_give ((void **) &lsterr);
1159 trial = 0; /* initial trial count */
1160 tmp[0] = '\0'; /* no error */
1161 do { /* gensym a new tag */
1162 if (lsterr) { /* previous attempt with this one failed? */
1163 sprintf (tmp,"Retrying %s authentication after %.80s",at->name,lsterr);
1164 mm_log (tmp,WARN);
1165 fs_give ((void **) &lsterr);
1167 LOCAL->saslcancel = NIL;
1168 sprintf (tag,"%08lx",0xffffffff & (stream->gensym++));
1169 /* build command */
1170 sprintf (tmp,"%s AUTHENTICATE %s",tag,at->name);
1171 if (imap_soutr (stream,tmp)) {
1172 /* hide client authentication responses */
1173 if (!(at->flags & AU_SECURE)) LOCAL->sensitive = T;
1174 ok = (*at->client) (imap_challenge,imap_response,"imap",mb,stream,
1175 &trial,usr);
1176 LOCAL->sensitive = NIL; /* unhide */
1177 /* make sure have a response */
1178 if (!(reply = &LOCAL->reply)->tag)
1179 reply = imap_fake (stream,tag,
1180 "[CLOSED] IMAP connection broken (authenticate)");
1181 else if (compare_cstring (reply->tag,tag))
1182 while (compare_cstring ((reply = imap_reply (stream,tag))->tag,tag))
1183 imap_soutr (stream,"*");
1184 /* good if SASL ok and success response */
1185 if (ok && imap_OK (stream,reply)) return T;
1186 if (!trial) { /* if main program requested cancellation */
1187 mm_log ("IMAP Authentication cancelled",ERROR);
1188 return NIL;
1190 /* no error if protocol-initiated cancel */
1191 lsterr = cpystr (reply->text);
1194 while (LOCAL->netstream && !LOCAL->byeseen && trial &&
1195 (trial < imap_maxlogintrials));
1197 if (lsterr) { /* previous authenticator failed? */
1198 if (!LOCAL->saslcancel) { /* don't do this if a cancel */
1199 sprintf (tmp,"Can not authenticate to IMAP server: %.80s",lsterr);
1200 mm_log (tmp,ERROR);
1202 fs_give ((void **) &lsterr);
1204 return NIL; /* ran out of authenticators */
1207 /* IMAP login
1208 * Accepts: stream to login
1209 * parsed network mailbox structure
1210 * scratch buffer of length MAILTMPLEN
1211 * place to return user name
1212 * Returns: T on success, NIL on failure
1215 long imap_login (MAILSTREAM *stream,NETMBX *mb,char *pwd,char *usr)
1217 unsigned long trial = 0;
1218 IMAPPARSEDREPLY *reply;
1219 IMAPARG *args[3];
1220 IMAPARG ausr,apwd;
1221 long ret = NIL;
1222 if (stream->secure) /* never do LOGIN if want security */
1223 mm_log ("Can't do secure authentication with this server",ERROR);
1224 /* never do LOGIN if server disabled it */
1225 else if (LOCAL->cap.logindisabled)
1226 mm_log ("Server disables LOGIN, no recognized SASL authenticator",ERROR);
1227 else if (mb->authuser[0]) /* never do LOGIN with /authuser */
1228 mm_log ("Can't do /authuser with this server",ERROR);
1229 else { /* OK to try login */
1230 ausr.type = apwd.type = ASTRING;
1231 ausr.text = (void *) usr;
1232 apwd.text = (void *) pwd;
1233 args[0] = &ausr; args[1] = &apwd; args[2] = NIL;
1234 do {
1235 pwd[0] = 0; /* prompt user for password */
1236 mm_login (mb,usr,pwd,trial++);
1237 if (pwd[0]) { /* send login command if have password */
1238 LOCAL->sensitive = T; /* hide this command */
1239 /* send "LOGIN usr pwd" */
1240 if (imap_OK (stream,reply = imap_send (stream,"LOGIN",args)))
1241 ret = LONGT; /* success */
1242 else {
1243 mm_log (reply->text,WARN);
1244 if (!LOCAL->referral && (trial == imap_maxlogintrials))
1245 mm_log ("Too many login failures",ERROR);
1247 LOCAL->sensitive = NIL; /* unhide */
1249 /* user refused to give password */
1250 else mm_log ("Login aborted",ERROR);
1251 } while (!ret && pwd[0] && (trial < imap_maxlogintrials) &&
1252 LOCAL->netstream && !LOCAL->byeseen && !LOCAL->referral);
1254 memset (pwd,0,MAILTMPLEN); /* erase password */
1255 return ret;
1258 /* Get challenge to authenticator in binary
1259 * Accepts: stream
1260 * pointer to returned size
1261 * Returns: challenge or NIL if not challenge
1264 void *imap_challenge (void *s,unsigned long *len)
1266 char tmp[MAILTMPLEN];
1267 void *ret = NIL;
1268 MAILSTREAM *stream = (MAILSTREAM *) s;
1269 IMAPPARSEDREPLY *reply = NIL;
1270 /* get tagged response or challenge */
1271 while (stream && LOCAL->netstream &&
1272 (reply = imap_parse_reply (stream,net_getline (LOCAL->netstream))) &&
1273 !strcmp (reply->tag,"*")) imap_parse_unsolicited (stream,reply);
1274 /* parse challenge if have one */
1275 if (stream && LOCAL->netstream && reply && reply->tag &&
1276 (*reply->tag == '+') && !reply->tag[1] && reply->text &&
1277 !(ret = rfc822_base64 ((unsigned char *) reply->text,
1278 strlen (reply->text),len))) {
1279 sprintf (tmp,"IMAP SERVER BUG (invalid challenge): %.80s",
1280 (char *) reply->text);
1281 mm_log (tmp,ERROR);
1283 return ret;
1287 /* Send authenticator response in BASE64
1288 * Accepts: MAIL stream
1289 * string to send
1290 * length of string
1291 * Returns: T if successful, else NIL
1294 long imap_response (void *s,char *response,unsigned long size)
1296 MAILSTREAM *stream = (MAILSTREAM *) s;
1297 unsigned long i,j,ret;
1298 char *t,*u;
1299 if (response) { /* make CRLFless BASE64 string */
1300 if (size) {
1301 for (t = (char *) rfc822_binary ((void *) response,size,&i),u = t,j = 0;
1302 j < i; j++) if (t[j] > ' ') *u++ = t[j];
1303 *u = '\0'; /* tie off string for mm_dlog() */
1304 if (stream->debug) mail_dlog (t,LOCAL->sensitive);
1305 /* append CRLF */
1306 *u++ = '\015'; *u++ = '\012';
1307 ret = net_sout (LOCAL->netstream,t,u - t);
1308 fs_give ((void **) &t);
1310 else ret = imap_soutr (stream,"");
1312 else { /* abort requested */
1313 ret = imap_soutr (stream,"*");
1314 LOCAL->saslcancel = T; /* mark protocol-requested SASL cancel */
1316 return ret;
1319 /* IMAP close
1320 * Accepts: MAIL stream
1321 * option flags
1324 void imap_close (MAILSTREAM *stream,long options)
1326 THREADER *thr,*t;
1327 IMAPPARSEDREPLY *reply;
1328 if (stream && LOCAL) { /* send "LOGOUT" */
1329 if (!LOCAL->byeseen) { /* don't even think of doing it if saw a BYE */
1330 /* expunge silently if requested */
1331 if (options & CL_EXPUNGE)
1332 imap_send (stream,LEVELIMAP4 (stream) ? "CLOSE" : "EXPUNGE",NIL);
1333 if (LOCAL->netstream &&
1334 !imap_OK (stream,reply = imap_send (stream,"LOGOUT",NIL)))
1335 mm_log (reply->text,WARN);
1337 /* close NET connection if still open */
1338 if (LOCAL->netstream) net_close (LOCAL->netstream);
1339 LOCAL->netstream = NIL;
1340 /* free up memory */
1341 if (LOCAL->sortdata) fs_give ((void **) &LOCAL->sortdata);
1342 if (LOCAL->namespace) {
1343 mail_free_namespace (&LOCAL->namespace[0]);
1344 mail_free_namespace (&LOCAL->namespace[1]);
1345 mail_free_namespace (&LOCAL->namespace[2]);
1346 fs_give ((void **) &LOCAL->namespace);
1348 if (LOCAL->threaddata) mail_free_threadnode (&LOCAL->threaddata);
1349 /* flush threaders */
1350 if ((thr = LOCAL->cap.threader) != NULL) while ((t = thr) != NULL) {
1351 fs_give ((void **) &t->name);
1352 thr = t->next;
1353 fs_give ((void **) &t);
1355 if (LOCAL->referral) fs_give ((void **) &LOCAL->referral);
1356 if (LOCAL->user) fs_give ((void **) &LOCAL->user);
1357 if (LOCAL->reply.line) fs_give ((void **) &LOCAL->reply.line);
1358 if (LOCAL->reform) fs_give ((void **) &LOCAL->reform);
1359 if (LOCAL->id) mail_free_idlist(&LOCAL->id);
1360 /* nuke the local data */
1361 fs_give ((void **) &stream->local);
1365 /* IMAP fetch fast information
1366 * Accepts: MAIL stream
1367 * sequence
1368 * option flags
1370 * Generally, imap_structure is preferred
1373 void imap_fast (MAILSTREAM *stream,char *sequence,long flags)
1375 IMAPPARSEDREPLY *reply = imap_fetch (stream,sequence,flags & FT_UID);
1376 if (!imap_OK (stream,reply)) mm_log (reply->text,ERROR);
1380 /* IMAP fetch flags
1381 * Accepts: MAIL stream
1382 * sequence
1383 * option flags
1386 void imap_flags (MAILSTREAM *stream,char *sequence,long flags)
1387 { /* send "FETCH sequence FLAGS" */
1388 char *cmd = (LEVELIMAP4 (stream) && (flags & FT_UID)) ? "UID FETCH":"FETCH";
1389 IMAPPARSEDREPLY *reply;
1390 IMAPARG *args[3],aseq,aatt;
1391 if (LOCAL->loser) sequence = imap_reform_sequence (stream,sequence,
1392 flags & FT_UID);
1393 aseq.type = SEQUENCE; aseq.text = (void *) sequence;
1394 aatt.type = ATOM; aatt.text = (void *) "FLAGS";
1395 args[0] = &aseq; args[1] = &aatt; args[2] = NIL;
1396 if (!imap_OK (stream,reply = imap_send (stream,cmd,args)))
1397 mm_log (reply->text,ERROR);
1400 /* IMAP fetch overview
1401 * Accepts: MAIL stream, sequence bits set
1402 * pointer to overview return function
1403 * Returns: T if successful, NIL otherwise
1406 long imap_overview (MAILSTREAM *stream,overview_t ofn)
1408 MESSAGECACHE *elt;
1409 ENVELOPE *env;
1410 OVERVIEW ov;
1411 char *s,*t;
1412 unsigned long i,start,last,len,slen;
1413 if (!LOCAL->netstream) return NIL;
1414 /* build overview sequence */
1415 for (i = 1,len = start = last = 0,s = t = NIL; i <= stream->nmsgs; ++i)
1416 if ((elt = mail_elt (stream,i))->sequence) {
1417 if (!elt->private.msg.env) {
1418 if (s) { /* continuing a sequence */
1419 if (i == last + 1) last = i;
1420 else { /* end of range */
1421 if (last != start) sprintf (t,":%lu,%lu",last,i);
1422 else sprintf (t,",%lu",i);
1423 if ((len - (slen = (t += strlen (t)) - s)) < 20) {
1424 fs_resize ((void **) &s,len += MAILTMPLEN);
1425 t = s + slen; /* relocate current pointer */
1427 start = last = i; /* begin a new range */
1430 else { /* first time, start new buffer */
1431 s = (char *) fs_get (len = MAILTMPLEN);
1432 sprintf (s,"%lu",start = last = i);
1433 t = s + strlen (s); /* end of buffer */
1437 /* last sequence */
1438 if (last != start) sprintf (t,":%lu",last);
1439 if (s) { /* prefetch as needed */
1440 imap_fetch (stream,s,FT_NEEDENV);
1441 fs_give ((void **) &s);
1443 ov.optional.lines = 0; /* now overview each message */
1444 ov.optional.xref = NIL;
1445 if (ofn) for (i = 1; i <= stream->nmsgs; i++)
1446 if (((elt = mail_elt (stream,i))->sequence) &&
1447 (env = mail_fetch_structure (stream,i,NIL,NIL)) && ofn) {
1448 ov.subject = env->subject;
1449 ov.from = env->from;
1450 ov.date = env->date;
1451 ov.message_id = env->message_id;
1452 ov.references = env->references;
1453 ov.optional.octets = elt->rfc822_size;
1454 (*ofn) (stream,mail_uid (stream,i),&ov,i);
1456 return LONGT;
1459 /* IMAP fetch structure
1460 * Accepts: MAIL stream
1461 * message # to fetch
1462 * pointer to return body
1463 * option flags
1464 * Returns: envelope of this message, body returned in body value
1466 * Fetches the "fast" information as well
1469 ENVELOPE *imap_structure (MAILSTREAM *stream,unsigned long msgno,BODY **body,
1470 long flags)
1472 unsigned long i,j,k,x;
1473 char *s,seq[MAILTMPLEN],tmp[MAILTMPLEN];
1474 MESSAGECACHE *elt;
1475 ENVELOPE **env;
1476 BODY **b;
1477 IMAPPARSEDREPLY *reply = NIL;
1478 IMAPARG *args[3],aseq,aatt;
1479 SEARCHSET *set = LOCAL->lookahead;
1480 LOCAL->lookahead = NIL;
1481 args[0] = &aseq; args[1] = &aatt; args[2] = NIL;
1482 aseq.type = SEQUENCE; aseq.text = (void *) seq;
1483 aatt.type = ATOM; aatt.text = NIL;
1484 if (flags & FT_UID) /* see if can find msgno from UID */
1485 for (i = 1; i <= stream->nmsgs; i++)
1486 if ((elt = mail_elt (stream,i))->private.uid == msgno) {
1487 msgno = i; /* found msgno, use it from now on */
1488 flags &= ~FT_UID; /* no longer a UID fetch */
1490 sprintf (s = seq,"%lu",msgno);/* initial sequence */
1491 if (LEVELIMAP4 (stream) && (flags & FT_UID)) {
1492 /* UID fetching is requested and we can't map the UID to a message sequence
1493 * number. Assume that the message isn't cached at all.
1495 if (!imap_OK (stream,reply = imap_fetch (stream,seq,FT_NEEDENV +
1496 (body ? FT_NEEDBODY : NIL) +
1497 (flags & (FT_UID + FT_NOHDRS)))))
1498 mm_log (reply->text,ERROR);
1499 /* now hunt for this UID */
1500 for (i = 1; i <= stream->nmsgs; i++)
1501 if ((elt = mail_elt (stream,i))->private.uid == msgno) {
1502 if (body) *body = elt->private.msg.body;
1503 return elt->private.msg.env;
1505 if (body) *body = NIL; /* can't find the UID */
1506 return NIL;
1508 elt = mail_elt (stream,msgno);/* get cache pointer */
1509 if (stream->scache) { /* short caching? */
1510 env = &stream->env; /* use temporaries on the stream */
1511 b = &stream->body;
1512 if (msgno != stream->msgno){/* flush old poop if a different message */
1513 mail_free_envelope (env);
1514 mail_free_body (b);
1515 stream->msgno = msgno; /* this is now the current short cache msg */
1519 else { /* normal cache */
1520 env = &elt->private.msg.env;/* get envelope and body pointers */
1521 b = &elt->private.msg.body;
1522 /* prefetch if don't have envelope */
1523 if (!(flags & FT_NOLOOKAHEAD) &&
1524 ((!*env || (*env)->incomplete) ||
1525 (body && !*b && LEVELIMAP2bis (stream)))) {
1526 if (set) { /* have a lookahead list? */
1527 MESSAGE *msg;
1528 for (k = imap_fetchlookaheadlimit;
1529 k && set && (((s += strlen (s)) - seq) < (MAXCOMMAND - 30));
1530 set = set->next) {
1531 i = (set->first == 0xffffffff) ? stream->nmsgs :
1532 min (set->first,stream->nmsgs);
1533 if ((j = (set->last == 0xffffffff) ? stream->nmsgs :
1534 min (set->last,stream->nmsgs)) != 0L) {
1535 if (i > j) { /* swap the range if backwards */
1536 x = i; i = j; j = x;
1538 /* find first message not msgno or in cache */
1539 while (((i == msgno) ||
1540 ((msg = &(mail_elt (stream,i)->private.msg))->env &&
1541 (!body || msg->body))) && (i++ < j));
1542 /* until range or lookahead finished */
1543 while (k && (i <= j)) {
1544 /* find first cached message in range */
1545 for (x = i + 1; (x <= j) &&
1546 !((msg = &(mail_elt (stream,x)->private.msg))->env &&
1547 (!body || msg->body)); x++);
1548 if (i == --x) { /* only one message? */
1549 sprintf (s += strlen (s),",%lu",i++);
1550 k--; /* prefetching one message */
1552 else { /* a range to prefetch */
1553 sprintf (s += strlen (s),",%lu:%lu",i,x);
1554 i = 1 + x - i; /* number of messages in this range */
1555 /* still can look ahead some more? */
1556 if ((k = (k > i) ? k - i : 0) != 0)
1557 /* yes, scan further in this range */
1558 for (i = x + 2; (i <= j) &&
1559 ((i == msgno) ||
1560 ((msg = &(mail_elt (stream,i)->private.msg))->env &&
1561 (!body || msg->body)));
1562 i++);
1566 else if ((i != msgno) && !mail_elt (stream,i)->private.msg.env) {
1567 sprintf (s += strlen (s),",%lu",i);
1568 k--; /* prefetching one message */
1572 /* build message number list */
1573 else for (i = msgno+1,k = imap_lookahead; k && (i <= stream->nmsgs); i++)
1574 if (!mail_elt (stream,i)->private.msg.env) {
1575 s += strlen (s); /* find string end, see if nearing end */
1576 if ((s - seq) > (MAILTMPLEN - 20)) break;
1577 sprintf (s,",%lu",i); /* append message */
1578 for (j = i + 1, k--; /* hunt for last message without an envelope */
1579 k && (j <= stream->nmsgs) &&
1580 !mail_elt (stream,j)->private.msg.env; j++, k--);
1581 /* if different, make a range */
1582 if (i != --j) sprintf (s + strlen (s),":%lu",i = j);
1587 if (!stream->lock) { /* no-op if stream locked */
1588 /* Build the fetch attributes. Unlike imap_fetch(), this tries not to
1589 * fetch data that is already cached. However, since it is based on the
1590 * message requested and not on any of the prefetched messages, it can
1591 * goof, either by fetching data already cached or not prefetching data
1592 * that isn't cached (but was cached in the message requested).
1593 * Fortunately, no great harm is done. If it doesn't prefetch the data,
1594 * it will get it when the affected message(s) are requested.
1596 if (!elt->private.uid && LEVELIMAP4 (stream)) strcpy (tmp," UID");
1597 else tmp[0] = '\0'; /* initialize command */
1598 /* need envelope? */
1599 if (!*env || (*env)->incomplete) {
1600 strcat (tmp," ENVELOPE"); /* yes, get it and possible extra poop */
1601 if (!(flags & FT_NOHDRS) && LEVELIMAP4rev1 (stream)) {
1602 if (imap_extrahdrs) sprintf (tmp + strlen (tmp)," %s %s %s",
1603 hdrheader[LOCAL->cap.extlevel],
1604 imap_extrahdrs,hdrtrailer);
1605 else sprintf (tmp + strlen (tmp)," %s %s",
1606 hdrheader[LOCAL->cap.extlevel],hdrtrailer);
1609 /* need body? */
1610 if (body && !*b && LEVELIMAP2bis (stream))
1611 strcat (tmp,LEVELIMAP4 (stream) ? " BODYSTRUCTURE" : " BODY");
1612 if (!elt->day) strcat (tmp," INTERNALDATE");
1613 if (!elt->rfc822_size) strcat (tmp," RFC822.SIZE");
1614 if (tmp[0]) { /* anything to do? */
1615 tmp[0] = '('; /* make into a list */
1616 strcat (tmp," FLAGS)"); /* always get current flags */
1617 aatt.text = (void *) tmp; /* do the built command */
1618 if (!imap_OK (stream,reply = imap_send (stream,"FETCH",args))) {
1619 /* failed, probably RFC-1176 server */
1620 if (!LEVELIMAP4 (stream) && LEVELIMAP2bis (stream) && body && !*b){
1621 aatt.text = (void *) "ALL";
1622 if (imap_OK (stream,reply = imap_send (stream,"FETCH",args)))
1623 /* doesn't have body capabilities */
1624 LOCAL->cap.imap2bis = NIL;
1625 else mm_log (reply->text,ERROR);
1627 else mm_log (reply->text,ERROR);
1631 if (body) { /* wants to return body */
1632 if (!*b && !LEVELIMAP2bis (stream)) {
1633 /* simulate body structure fetch for IMAP2 */
1634 *b = mail_initbody (mail_newbody ());
1635 (*b)->subtype = cpystr (rfc822_default_subtype ((*b)->type));
1636 ((*b)->parameter = mail_newbody_parameter ())->attribute =
1637 cpystr ("CHARSET");
1638 (*b)->parameter->value = cpystr ("US-ASCII");
1639 s = mail_fetch_text (stream,msgno,NIL,&i,flags);
1640 (*b)->size.bytes = i;
1641 while (i--) if (*s++ == '\n') (*b)->size.lines++;
1643 *body = *b; /* return the body */
1645 return *env; /* return the envelope */
1648 /* IMAP fetch message data
1649 * Accepts: MAIL stream
1650 * message number
1651 * section specifier
1652 * offset of first designated byte or 0 to start at beginning
1653 * maximum number of bytes or 0 for all bytes
1654 * lines to fetch if header
1655 * flags
1656 * Returns: T on success, NIL on failure
1659 long imap_msgdata (MAILSTREAM *stream,unsigned long msgno,char *section,
1660 unsigned long first,unsigned long last,STRINGLIST *lines,
1661 long flags)
1663 int i;
1664 char *t,tmp[MAILTMPLEN],partial[40],seq[40];
1665 char *noextend,*nopartial,*nolines,*nopeek,*nononpeek;
1666 char *cmd = (LEVELIMAP4 (stream) && (flags & FT_UID)) ? "UID FETCH":"FETCH";
1667 IMAPPARSEDREPLY *reply;
1668 IMAPARG *args[5],*auxargs[3],aseq,aatt,alns,acls,aflg;
1669 noextend = nopartial = nolines = nopeek = nononpeek = NIL;
1670 /* does searching desire a lookahead? */
1671 if ((flags & FT_SEARCHLOOKAHEAD) && (msgno < stream->nmsgs) &&
1672 !stream->scache) {
1673 sprintf (seq,"%lu:%lu",msgno,
1674 (unsigned long) min (msgno + IMAPLOOKAHEAD,stream->nmsgs));
1675 aseq.type = SEQUENCE;
1676 aseq.text = (void *) seq;
1678 else { /* no, do it the easy way */
1679 aseq.type = NUMBER;
1680 aseq.text = (void *) msgno;
1682 aatt.type = ATOM; /* assume atomic attribute */
1683 alns.type = LIST; alns.text = (void *) lines;
1684 acls.type = BODYCLOSE; acls.text = (void *) partial;
1685 aflg.type = ATOM; aflg.text = (void *) "FLAGS";
1686 args[0] = &aseq; args[1] = &aatt; args[2] = args[3] = args[4] = NIL;
1687 auxargs[0] = &aseq; auxargs[1] = &aflg; auxargs[2] = NIL;
1688 partial[0] = '\0'; /* initially no partial specifier */
1689 if (LEVELIMAP4rev1 (stream)) {/* easy if IMAP4rev1 server */
1690 /* HEADER fetching with special handling? */
1691 if (!strcmp (section,"HEADER") && (lines || (flags & FT_PREFETCHTEXT))) {
1692 if (lines) { /* want specific header lines? */
1693 aatt.type = (flags & FT_PEEK) ? BODYPEEK : BODYTEXT;
1694 aatt.text = (void *) ((flags & FT_NOT) ?
1695 "HEADER.FIELDS.NOT" : "HEADER.FIELDS");
1696 args[2] = &alns; args[3] = &acls;
1698 /* must be prefetching */
1699 else aatt.text = (void *) ((flags & FT_PEEK) ?
1700 "(BODY.PEEK[HEADER] BODY.PEEK[TEXT])" :
1701 "(BODY[HEADER] BODY[TEXT])");
1703 else { /* simple case */
1704 aatt.type = (flags & FT_PEEK) ? BODYPEEK : BODYTEXT;
1705 aatt.text = (void *) section;
1706 args[2] = &acls;
1708 if (first || last) sprintf (partial,"<%lu.%lu>",first,last ? last:-1);
1711 /* IMAP4 did not have:
1712 * . HEADER body part (can simulate with BODY[0] or BODY.PEEK[0])
1713 * . TEXT body part (can simulate top-level with RFC822.TEXT or
1714 * RFC822.TEXT.PEEK)
1715 * . MIME body part
1716 * . (usable) partial fetching
1717 * . (usable) selective header line fetching
1719 else if (LEVEL1730 (stream)) {/* IMAP4 (RFC 1730) compatibility */
1720 /* BODY[HEADER] becomes BODY.PEEK[0] */
1721 if (!strcmp (section,"HEADER"))
1722 aatt.text = (void *)
1723 ((flags & FT_PREFETCHTEXT) ?
1724 ((flags & FT_PEEK) ? "(BODY.PEEK[0] RFC822.TEXT.PEEK)" :
1725 "(BODY[0] RFC822.TEXT)") :
1726 ((flags & FT_PEEK) ? "BODY.PEEK[0]" : "BODY[0]"));
1727 /* BODY[TEXT] becomes RFC822.TEXT */
1728 else if (!strcmp (section,"TEXT"))
1729 aatt.text = (void *) ((flags & FT_PEEK) ? "RFC822.TEXT.PEEK" :
1730 "RFC822.TEXT");
1731 else if (!section[0]) /* BODY[] becomes RFC822 */
1732 aatt.text = (void *) ((flags & FT_PEEK) ? "RFC822.PEEK" : "RFC822");
1733 /* nested header */
1734 else if ((t = strstr (section,".HEADER")) != NULL) {
1735 aatt.type = (flags & FT_PEEK) ? BODYPEEK : BODYTEXT;
1736 args[2] = &acls; /* will need to close section */
1737 aatt.text = (void *) tmp; /* convert .HEADER to .0 */
1738 strncpy (tmp,section,t-section);
1739 strcpy (tmp+(t-section),".0");
1741 else { /* IMAP4 body part */
1742 aatt.type = (flags & FT_PEEK) ? BODYPEEK : BODYTEXT;
1743 args[2] = &acls; /* will need to close section */
1744 aatt.text = (void *) section;
1746 if (strstr (section,".MIME") || strstr (section,".TEXT")) noextend = "4";
1747 if (first || last) nopartial = "4";
1748 if (lines) nolines = "4";
1751 /* IMAP2bis did not have:
1752 * . HEADER body part (can simulate peeking top-level with RFC822.HEADER)
1753 * . TEXT body part (can simulate non-peeking top-level with RFC822.TEXT)
1754 * . MIME body part
1755 * . partial fetching
1756 * . selective header line fetching
1757 * . non-peeking header fetching
1758 * . peeking body fetching
1760 /* IMAP2bis compatibility */
1761 else if (LEVELIMAP2bis (stream)) {
1762 /* BODY[HEADER] becomes RFC822.HEADER */
1763 if (!strcmp (section,"HEADER")) {
1764 aatt.text = (void *)
1765 ((flags & FT_PREFETCHTEXT) ?
1766 "(RFC822.HEADER RFC822.TEXT)" : "RFC822.HEADER");
1767 if (flags & FT_PEEK) flags &= ~FT_PEEK;
1768 else nononpeek = "2bis";
1770 /* BODY[TEXT] becomes RFC822.TEXT */
1771 else if (!strcmp (section,"TEXT")) aatt.text = (void *) "RFC822.TEXT";
1772 /* BODY[] becomes RFC822 */
1773 else if (!section[0]) aatt.text = (void *) "RFC822";
1774 else { /* IMAP2bis body part */
1775 aatt.type = BODYTEXT;
1776 args[2] = &acls; /* will need to close section */
1777 aatt.text = (void *) section;
1779 if (strstr (section,".HEADER") || strstr (section,".MIME") ||
1780 strstr (section,".TEXT")) noextend = "2bis";
1781 if (first || last) nopartial = "2bis";
1782 if (lines) nolines = "2bis";
1783 if (flags & FT_PEEK) nopeek = "2bis";
1786 /* IMAP2 did not have:
1787 * . HEADER body part (can simulate peeking top-level with RFC822.HEADER)
1788 * . TEXT body part (can simulate non-peeking top-level with RFC822.TEXT)
1789 * . MIME body part
1790 * . multiple body parts (can simulate BODY[1] with RFC822.TEXT)
1791 * . partial fetching
1792 * . selective header line fetching
1793 * . non-peeking header fetching
1794 * . peeking body fetching
1796 else { /* IMAP2 (RFC 1176/1064) compatibility */
1797 /* BODY[HEADER] */
1798 if (!strcmp (section,"HEADER")) {
1799 aatt.text = (void *) ((flags & FT_PREFETCHTEXT) ?
1800 "(RFC822.HEADER RFC822.TEXT)" : "RFC822.HEADER");
1801 if (flags & FT_PEEK) flags &= ~FT_PEEK;
1802 nononpeek = "2";
1804 /* BODY[TEXT] becomes RFC822.TEXT */
1805 else if (!strcmp (section,"TEXT")) aatt.text = (void *) "RFC822.TEXT";
1806 /* BODY[1] treated like RFC822.TEXT */
1807 else if (!strcmp (section,"1")) {
1808 SIZEDTEXT text;
1809 MESSAGECACHE *elt = mail_elt (stream,msgno);
1810 /* have a cached RFC822.TEXT? */
1811 if (elt->private.msg.text.text.data) {
1812 text.size = elt->private.msg.text.text.size;
1813 /* should move instead of copy */
1814 text.data = memcpy (fs_get (text.size+1),
1815 elt->private.msg.text.text.data,text.size);
1816 (t = (char *) text.data)[text.size] = '\0';
1817 imap_cache (stream,msgno,"1",NIL,&text);
1818 return LONGT; /* don't have to do any fetches */
1820 /* otherwise do RFC822.TEXT */
1821 aatt.text = (void *) "RFC822.TEXT";
1823 /* BODY[] becomes RFC822 */
1824 else if (!section[0]) aatt.text = (void *) "RFC822";
1825 else noextend = "2"; /* how did we get here? */
1826 if (flags & FT_PEEK) nopeek = "2";
1827 if (first || last) nopartial = "2";
1828 if (lines) nolines = "2";
1831 /* Report unavailable functionalities. The application can use the helpful
1832 * LEVELIMAPREV1, LEVELIMAP4, and LEVELIMAP2bis operations provided in
1833 * imap4r1.h to avoid triggering these errors. There aren't any workarounds
1834 * for these restrictions.
1836 if (noextend) {
1837 sprintf (tmp,"[NOTIMAP4REV1] IMAP%s server can't do extended body fetch",
1838 noextend);
1839 mm_log (tmp,ERROR);
1840 return NIL; /* can't do anything close either */
1842 if (nopartial) {
1843 sprintf (tmp,"[NOTIMAP4REV1] IMAP%s server can't do partial fetch",
1844 nopartial);
1845 mm_notify (stream,tmp,WARN);
1847 if (nolines) {
1848 sprintf(tmp,"[NOTIMAP4REV1] IMAP%s server can't do selective header fetch",
1849 nolines);
1850 mm_notify (stream,tmp,WARN);
1853 /* trying to do unsupported peek behavior? */
1854 if ((t = nopeek) || (t = nononpeek)) {
1855 /* get most recent \Seen setting */
1856 if (!imap_OK (stream,reply = imap_send (stream,cmd,auxargs)))
1857 mm_log (reply->text,WARN);
1858 /* note current setting of \Seen flag */
1859 if (!(i = mail_elt (stream,msgno)->seen)) {
1860 sprintf (tmp,nopeek ? /* only babble if \Seen not set */
1861 "[NOTIMAP4] Simulating peeking fetch in IMAP%s" :
1862 "[NOTIMAP4] Simulating non-peeking header fetch in IMAP%s",t);
1863 mm_notify (stream,tmp,NIL);
1865 /* send the fetch command */
1866 if (!imap_OK (stream,reply = imap_send (stream,cmd,args))) {
1867 mm_log (reply->text,ERROR);
1868 return NIL; /* failure */
1870 /* send command if need to reset \Seen */
1871 if (((nopeek && !i && mail_elt (stream,msgno)->seen &&
1872 (aflg.text = "-FLAGS \\Seen")) ||
1873 ((nononpeek && !mail_elt (stream,msgno)->seen) &&
1874 (aflg.text = "+FLAGS \\Seen"))) &&
1875 !imap_OK (stream,reply = imap_send (stream,"STORE",auxargs)))
1876 mm_log (reply->text,WARN);
1878 /* simple case if traditional behavior */
1879 else if (!imap_OK (stream,reply = imap_send (stream,cmd,args))) {
1880 mm_log (reply->text,ERROR);
1881 return NIL; /* failure */
1883 /* simulate BODY[1] return for RFC 1064/1176 */
1884 if (!LEVELIMAP2bis (stream) && !strcmp (section,"1")) {
1885 SIZEDTEXT text;
1886 MESSAGECACHE *elt = mail_elt (stream,msgno);
1887 text.size = elt->private.msg.text.text.size;
1888 /* should move instead of copy */
1889 text.data = memcpy (fs_get (text.size+1),elt->private.msg.text.text.data,
1890 text.size);
1891 (t = (char *) text.data)[text.size] = '\0';
1892 imap_cache (stream,msgno,"1",NIL,&text);
1894 return LONGT;
1897 /* IMAP fetch UID
1898 * Accepts: MAIL stream
1899 * message number
1900 * Returns: UID
1903 unsigned long imap_uid (MAILSTREAM *stream,unsigned long msgno)
1905 MESSAGECACHE *elt;
1906 IMAPPARSEDREPLY *reply;
1907 IMAPARG *args[3],aseq,aatt;
1908 char *s,seq[MAILTMPLEN];
1909 unsigned long i,j,k;
1910 /* IMAP2 didn't have UIDs */
1911 if (!LEVELIMAP4 (stream)) return msgno;
1912 /* do we know its UID yet? */
1913 if (!(elt = mail_elt (stream,msgno))->private.uid) {
1914 aseq.type = SEQUENCE; aseq.text = (void *) seq;
1915 aatt.type = ATOM; aatt.text = (void *) "UID";
1916 args[0] = &aseq; args[1] = &aatt; args[2] = NIL;
1917 sprintf (seq,"%lu",msgno);
1918 if ((k = imap_uidlookahead) != 0L) {/* build UID list */
1919 for (i = msgno + 1, s = seq; k && (i <= stream->nmsgs); i++)
1920 if (!mail_elt (stream,i)->private.uid) {
1921 s += strlen (s); /* find string end, see if nearing end */
1922 if ((s - seq) > (MAILTMPLEN - 20)) break;
1923 sprintf (s,",%lu",i); /* append message */
1924 for (j = i + 1, k--; /* hunt for last message without a UID */
1925 k && (j <= stream->nmsgs) && !mail_elt (stream,j)->private.uid;
1926 j++, k--);
1927 /* if different, make a range */
1928 if (i != --j) sprintf (s + strlen (s),":%lu",i = j);
1931 /* send "FETCH msgno UID" */
1932 if (!imap_OK (stream,reply = imap_send (stream,"FETCH",args)))
1933 mm_log (reply->text,ERROR);
1935 return elt->private.uid; /* return our UID now */
1938 /* IMAP fetch message number from UID
1939 * Accepts: MAIL stream
1940 * UID
1941 * Returns: message number
1944 unsigned long imap_msgno (MAILSTREAM *stream,unsigned long uid)
1946 IMAPPARSEDREPLY *reply;
1947 IMAPARG *args[3],aseq,aatt;
1948 char seq[MAILTMPLEN];
1949 int holes = 0;
1950 unsigned long i,msgno;
1951 /* IMAP2 didn't have UIDs */
1952 if (!LEVELIMAP4 (stream)) return uid;
1953 /* This really should be a binary search, but since there are likely to be
1954 * holes in the msgno->UID map it's hard to do.
1956 for (msgno = 1; msgno <= stream->nmsgs; msgno++) {
1957 if (!(i = mail_elt (stream,msgno)->private.uid)) holes = T;
1958 else if (i == uid) return msgno;
1960 if (holes) { /* have holes in cache? */
1961 /* yes, have server hunt for UID */
1962 LOCAL->lastuid.uid = LOCAL->lastuid.msgno = 0;
1963 aseq.type = SEQUENCE; aseq.text = (void *) seq;
1964 aatt.type = ATOM; aatt.text = (void *) "UID";
1965 args[0] = &aseq; args[1] = &aatt; args[2] = NIL;
1966 sprintf (seq,"%lu",uid);
1967 /* send "UID FETCH uid UID" */
1968 if (!imap_OK (stream,reply = imap_send (stream,"UID FETCH",args)))
1969 mm_log (reply->text,ERROR);
1970 if (LOCAL->lastuid.uid) { /* got any results from FETCH? */
1971 if ((LOCAL->lastuid.uid == uid) &&
1972 /* what, me paranoid? */
1973 (LOCAL->lastuid.msgno <= stream->nmsgs) &&
1974 (mail_elt (stream,LOCAL->lastuid.msgno)->private.uid == uid))
1975 /* got it the easy way */
1976 return LOCAL->lastuid.msgno;
1977 /* sigh, do another linear search... */
1978 for (msgno = 1; msgno <= stream->nmsgs; msgno++)
1979 if (mail_elt (stream,msgno)->private.uid == uid) return msgno;
1982 return 0; /* didn't find the UID anywhere */
1985 /* IMAP modify flags
1986 * Accepts: MAIL stream
1987 * sequence
1988 * flag(s)
1989 * option flags
1992 void imap_flag (MAILSTREAM *stream,char *sequence,char *flag,long flags)
1994 char *cmd = (LEVELIMAP4 (stream) && (flags & ST_UID)) ? "UID STORE":"STORE";
1995 IMAPPARSEDREPLY *reply;
1996 IMAPARG *args[4],aseq,ascm,aflg;
1997 if (LOCAL->loser) sequence = imap_reform_sequence (stream,sequence,
1998 flags & ST_UID);
1999 aseq.type = SEQUENCE; aseq.text = (void *) sequence;
2000 ascm.type = ATOM; ascm.text = (void *)
2001 ((flags & ST_SET) ?
2002 ((LEVELIMAP4 (stream) && (flags & ST_SILENT)) ?
2003 "+Flags.silent" : "+Flags") :
2004 ((LEVELIMAP4 (stream) && (flags & ST_SILENT)) ?
2005 "-Flags.silent" : "-Flags"));
2006 aflg.type = FLAGS; aflg.text = (void *) flag;
2007 args[0] = &aseq; args[1] = &ascm; args[2] = &aflg; args[3] = NIL;
2008 /* send "STORE sequence +Flags flag" */
2009 if (!imap_OK (stream,reply = imap_send (stream,cmd,args)))
2010 mm_log (reply->text,ERROR);
2013 /* IMAP search for messages
2014 * Accepts: MAIL stream
2015 * character set
2016 * search program
2017 * option flags
2018 * Returns: T on success, NIL on failure
2021 long imap_search (MAILSTREAM *stream,char *charset,SEARCHPGM *pgm,long flags)
2023 unsigned long i,j,k;
2024 char *s;
2025 IMAPPARSEDREPLY *reply;
2026 MESSAGECACHE *elt;
2028 if(LOCAL->cap.x_gm_ext1 && pgm && pgm->x_gm_ext1)
2029 return imap_search_x_gm_ext1(stream, charset, pgm, flags);
2031 if ((flags & SE_NOSERVER) || /* if want to do local search */
2032 LOCAL->loser || /* or loser */
2033 (!LEVELIMAP4 (stream) && /* or old server but new functions... */
2034 (charset || (flags & SE_UID) || pgm->msgno || pgm->uid || pgm->or ||
2035 pgm->not || pgm->header || pgm->larger || pgm->smaller ||
2036 pgm->sentbefore || pgm->senton || pgm->sentsince || pgm->draft ||
2037 pgm->undraft || pgm->return_path || pgm->sender || pgm->reply_to ||
2038 pgm->message_id || pgm->in_reply_to || pgm->newsgroups ||
2039 pgm->followup_to || pgm->references)) ||
2040 (!LEVELWITHIN (stream) && (pgm->older || pgm->younger))) {
2041 if ((flags & SE_NOLOCAL) ||
2042 !mail_search_default (stream,charset,pgm,flags | SE_NOSERVER))
2043 return NIL;
2045 /* do silly ALL or seq-only search locally */
2046 else if (!(flags & (SE_NOLOCAL|SE_SILLYOK)) &&
2047 !(pgm->uid || pgm->or || pgm->not ||
2048 pgm->header || pgm->from || pgm->to || pgm->cc || pgm->bcc ||
2049 pgm->subject || pgm->body || pgm->text ||
2050 pgm->larger || pgm->smaller ||
2051 pgm->sentbefore || pgm->senton || pgm->sentsince ||
2052 pgm->before || pgm->on || pgm->since ||
2053 pgm->answered || pgm->unanswered ||
2054 pgm->deleted || pgm->undeleted || pgm->draft || pgm->undraft ||
2055 pgm->flagged || pgm->unflagged || pgm->recent || pgm->old ||
2056 pgm->seen || pgm->unseen ||
2057 pgm->keyword || pgm->unkeyword ||
2058 pgm->return_path || pgm->sender ||
2059 pgm->reply_to || pgm->in_reply_to || pgm->message_id ||
2060 pgm->newsgroups || pgm->followup_to || pgm->references)) {
2061 if (!mail_search_default (stream,NIL,pgm,flags | SE_NOSERVER))
2062 fatal ("impossible mail_search_default() failure");
2065 else { /* do server-based SEARCH */
2066 char *cmd = (flags & SE_UID) ? "UID SEARCH" : "SEARCH";
2067 IMAPARG *args[4],apgm,aatt,achs;
2068 SEARCHSET *ss,*set;
2069 args[1] = args[2] = args[3] = NIL;
2070 apgm.type = SEARCHPROGRAM; apgm.text = (void *) pgm;
2071 if (charset) { /* optional charset argument requested */
2072 args[0] = &aatt; args[1] = &achs; args[2] = &apgm;
2073 aatt.type = ATOM; aatt.text = (void *) "CHARSET";
2074 achs.type = ASTRING; achs.text = (void *) charset;
2076 else args[0] = &apgm; /* no charset argument */
2077 /* tell receiver that these will be UIDs */
2078 LOCAL->uidsearch = (flags & SE_UID) ? T : NIL;
2079 reply = imap_send (stream,cmd,args);
2080 /* did server barf with that searchpgm? */
2081 if (!(flags & SE_UID) && pgm && (ss = pgm->msgno) &&
2082 !strcmp (reply->key,"BAD")) {
2083 LOCAL->filter = T; /* retry, filtering SEARCH results */
2084 for (i = 1; i <= stream->nmsgs; i++)
2085 mail_elt (stream,i)->private.filter = NIL;
2086 for (set = ss; set; set = set->next) if ((i = set->first) != 0L) {
2087 /* single message becomes one-message range */
2088 if (!(j = set->last)) j = i;
2089 else if (j < i) { /* swap reversed range */
2090 i = set->last; j = set->first;
2092 while (i <= j) mail_elt (stream,i++)->private.filter = T;
2094 pgm->msgno = NIL; /* and without the searchset */
2095 reply = imap_send (stream,cmd,args);
2096 pgm->msgno = ss; /* restore searchset */
2097 LOCAL->filter = NIL; /* turn off filtering */
2099 LOCAL->uidsearch = NIL;
2100 /* do locally if server won't grok */
2101 if (!strcmp (reply->key,"BAD")) {
2102 if ((flags & SE_NOLOCAL) ||
2103 !mail_search_default (stream,charset,pgm,flags | SE_NOSERVER))
2104 return NIL;
2106 else if (!imap_OK (stream,reply)) {
2107 mm_log (reply->text,ERROR);
2108 return NIL;
2112 /* can never pre-fetch with a short cache */
2113 if ((k = imap_prefetch) && !(flags & (SE_NOPREFETCH | SE_UID)) &&
2114 !stream->scache) { /* only if prefetching permitted */
2115 s = LOCAL->tmp; /* build sequence in temporary buffer */
2116 *s = '\0'; /* initially nothing */
2117 /* search through mailbox */
2118 for (i = 1; k && (i <= stream->nmsgs); ++i)
2119 /* for searched messages with no envelope */
2120 if ((elt = mail_elt (stream,i)) && elt->searched &&
2121 !mail_elt (stream,i)->private.msg.env) {
2122 /* prepend with comma if not first time */
2123 if (LOCAL->tmp[0]) *s++ = ',';
2124 sprintf (s,"%lu",j = i);/* output message number */
2125 s += strlen (s); /* point at end of string */
2126 k--; /* count one up */
2127 /* search for possible end of range */
2128 while (k && (i < stream->nmsgs) &&
2129 (elt = mail_elt (stream,i+1))->searched &&
2130 !elt->private.msg.env) i++,k--;
2131 if (i != j) { /* if a range */
2132 sprintf (s,":%lu",i); /* output delimiter and end of range */
2133 s += strlen (s); /* point at end of string */
2135 if ((s - LOCAL->tmp) > (IMAPTMPLEN - 50)) break;
2137 if (LOCAL->tmp[0]) { /* anything to pre-fetch? */
2138 /* pre-fetch envelopes for the first imap_prefetch number of messages */
2139 if (!imap_OK (stream,reply =
2140 imap_fetch (stream,s = cpystr (LOCAL->tmp),FT_NEEDENV +
2141 ((flags & SE_NOHDRS) ? FT_NOHDRS : NIL) +
2142 ((flags & SE_NEEDBODY) ? FT_NEEDBODY : NIL))))
2143 mm_log (reply->text,ERROR);
2144 fs_give ((void **) &s); /* flush copy of sequence */
2147 return LONGT;
2150 /* IMAP sort messages
2151 * Accepts: mail stream
2152 * character set
2153 * search program
2154 * sort program
2155 * option flags
2156 * Returns: vector of sorted message sequences or NIL if error
2159 unsigned long *imap_sort (MAILSTREAM *stream,char *charset,SEARCHPGM *spg,
2160 SORTPGM *pgm,long flags)
2162 unsigned long i,j,start,last;
2163 unsigned long *ret = NIL;
2164 pgm->nmsgs = 0; /* start off with no messages */
2165 /* can use server-based sort? */
2166 if (LEVELSORT (stream) && !(flags & SE_NOSERVER) &&
2167 (!spg || (LEVELWITHIN (stream) || !(spg->older || spg->younger)))) {
2168 char *cmd = (flags & SE_UID) ? "UID SORT" : "SORT";
2169 IMAPARG *args[4],apgm,achs,aspg;
2170 IMAPPARSEDREPLY *reply;
2171 SEARCHSET *ss = NIL;
2172 SEARCHPGM *tsp = NIL;
2173 apgm.type = SORTPROGRAM; apgm.text = (void *) pgm;
2174 achs.type = ASTRING; achs.text = (void *) (charset ? charset : "US-ASCII");
2175 aspg.type = SEARCHPROGRAM;
2176 /* did he provide a searchpgm? */
2177 if (!(aspg.text = (void *) spg)) {
2178 for (i = 1,start = last = 0; i <= stream->nmsgs; ++i)
2179 if (mail_elt (stream,i)->searched) {
2180 if (ss) { /* continuing a sequence */
2181 if (i == last + 1) last = i;
2182 else { /* end of range */
2183 if (last != start) ss->last = last;
2184 (ss = ss->next = mail_newsearchset ())->first = i;
2185 start = last = i; /* begin a new range */
2188 else { /* first time, start new searchpgm */
2189 (tsp = mail_newsearchpgm ())->msgno = ss = mail_newsearchset ();
2190 ss->first = start = last = i;
2193 /* nothing to sort if no messages */
2194 if (!(aspg.text = (void *) tsp)) return NIL;
2195 /* else install last sequence */
2196 if (last != start) ss->last = last;
2199 args[0] = &apgm; args[1] = &achs; args[2] = &aspg; args[3] = NIL;
2200 /* ask server to do it */
2201 reply = imap_send (stream,cmd,args);
2202 if (tsp) { /* was there a temporary searchpgm? */
2203 aspg.text = NIL; /* yes, flush it */
2204 mail_free_searchpgm (&tsp);
2205 /* did server barf with that searchpgm? */
2206 if (!(flags & SE_UID) && !strcmp (reply->key,"BAD")) {
2207 LOCAL->filter = T; /* retry, filtering SORT/THREAD results */
2208 reply = imap_send (stream,cmd,args);
2209 LOCAL->filter = NIL; /* turn off filtering */
2212 /* do locally if server barfs */
2213 if (!strcmp (reply->key,"BAD"))
2214 return (flags & SE_NOLOCAL) ? NIL :
2215 imap_sort (stream,charset,spg,pgm,flags | SE_NOSERVER);
2216 /* server sorted OK? */
2217 else if (imap_OK (stream,reply)) {
2218 pgm->nmsgs = LOCAL->sortsize;
2219 ret = LOCAL->sortdata;
2220 LOCAL->sortdata = NIL; /* mail program is responsible for flushing */
2222 else mm_log (reply->text,ERROR);
2225 /* not much can do if short caching */
2226 else if (stream->scache) ret = mail_sort_msgs (stream,charset,spg,pgm,flags);
2227 else { /* try to be a bit more clever */
2228 char *s,*t;
2229 unsigned long len;
2230 MESSAGECACHE *elt;
2231 SORTCACHE **sc;
2232 SORTPGM *sp;
2233 long ftflags = 0;
2234 /* see if need envelopes */
2235 for (sp = pgm; sp && !ftflags; sp = sp->next) switch (sp->function) {
2236 case SORTDATE: case SORTFROM: case SORTSUBJECT: case SORTTO: case SORTCC:
2237 ftflags = FT_NEEDENV + ((flags & SE_NOHDRS) ? FT_NOHDRS : NIL);
2239 if (spg) { /* only if a search needs to be done */
2240 int silent = stream->silent;
2241 stream->silent = T; /* don't pass up mm_searched() events */
2242 /* search for messages */
2243 mail_search_full (stream,charset,spg,flags & SE_NOSERVER);
2244 stream->silent = silent; /* restore silence state */
2246 /* initialize progress counters */
2247 pgm->nmsgs = pgm->progress.cached = 0;
2248 /* pass 1: count messages to sort */
2249 for (i = 1,len = start = last = 0,s = t = NIL; i <= stream->nmsgs; ++i)
2250 if ((elt = mail_elt (stream,i))->searched) {
2251 pgm->nmsgs++;
2252 if (ftflags ? !elt->private.msg.env : !elt->day) {
2253 if (s) { /* continuing a sequence */
2254 if (i == last + 1) last = i;
2255 else { /* end of range */
2256 if (last != start) sprintf (t,":%lu,%lu",last,i);
2257 else sprintf (t,",%lu",i);
2258 start = last = i; /* begin a new range */
2259 if ((len - (j = ((t += strlen (t)) - s)) < 20)) {
2260 fs_resize ((void **) &s,len += MAILTMPLEN);
2261 t = s + j; /* relocate current pointer */
2265 else { /* first time, start new buffer */
2266 s = (char *) fs_get (len = MAILTMPLEN);
2267 sprintf (s,"%lu",start = last = i);
2268 t = s + strlen (s); /* end of buffer */
2272 /* last sequence */
2273 if (last != start) sprintf (t,":%lu",last);
2274 if (s) { /* load cache for all messages being sorted */
2275 imap_fetch (stream,s,ftflags);
2276 fs_give ((void **) &s);
2278 if (pgm->nmsgs) { /* pass 2: sort cache */
2279 sortresults_t sr = (sortresults_t)
2280 mail_parameters (NIL,GET_SORTRESULTS,NIL);
2281 sc = mail_sort_loadcache (stream,pgm);
2282 /* pass 3: sort messages */
2283 if (!pgm->abort) ret = mail_sort_cache (stream,pgm,sc,flags);
2284 fs_give ((void **) &sc); /* don't need sort vector any more */
2285 /* also return via callback if requested */
2286 if (sr) (*sr) (stream,ret,pgm->nmsgs);
2289 return ret;
2292 /* IMAP thread messages
2293 * Accepts: mail stream
2294 * thread type
2295 * character set
2296 * search program
2297 * option flags
2298 * Returns: thread node tree or NIL if error
2301 THREADNODE *imap_thread (MAILSTREAM *stream,char *type,char *charset,
2302 SEARCHPGM *spg,long flags)
2304 THREADER *thr;
2305 if (!(flags & SE_NOSERVER) &&
2306 (!spg || (LEVELWITHIN (stream) || !(spg->older || spg->younger))))
2307 /* does server have this threader type? */
2308 for (thr = LOCAL->cap.threader; thr; thr = thr->next)
2309 if (!compare_cstring (thr->name,type))
2310 return imap_thread_work (stream,type,charset,spg,flags);
2311 /* server doesn't support it, do locally */
2312 return (flags & SE_NOLOCAL) ? NIL:
2313 mail_thread_msgs (stream,type,charset,spg,flags | SE_NOSERVER,imap_sort);
2316 /* IMAP thread messages worker routine
2317 * Accepts: mail stream
2318 * thread type
2319 * character set
2320 * search program
2321 * option flags
2322 * Returns: thread node tree
2325 THREADNODE *imap_thread_work (MAILSTREAM *stream,char *type,char *charset,
2326 SEARCHPGM *spg,long flags)
2328 unsigned long i,start,last;
2329 char *cmd = (flags & SE_UID) ? "UID THREAD" : "THREAD";
2330 IMAPARG *args[4],apgm,achs,aspg;
2331 IMAPPARSEDREPLY *reply;
2332 THREADNODE *ret = NIL;
2333 SEARCHSET *ss = NIL;
2334 SEARCHPGM *tsp = NIL;
2335 apgm.type = ATOM; apgm.text = (void *) type;
2336 achs.type = ASTRING;
2337 achs.text = (void *) (charset ? charset : "US-ASCII");
2338 aspg.type = SEARCHPROGRAM;
2339 /* did he provide a searchpgm? */
2340 if (!(aspg.text = (void *) spg)) {
2341 for (i = 1,start = last = 0; i <= stream->nmsgs; ++i)
2342 if (mail_elt (stream,i)->searched) {
2343 if (ss) { /* continuing a sequence */
2344 if (i == last + 1) last = i;
2345 else { /* end of range */
2346 if (last != start) ss->last = last;
2347 (ss = ss->next = mail_newsearchset ())->first = i;
2348 start = last =i; /* begin a new range */
2351 else { /* first time, start new searchpgm */
2352 (tsp = mail_newsearchpgm ())->msgno = ss = mail_newsearchset ();
2353 ss->first = start = last = i;
2356 /* nothing to sort if no messages */
2357 if (!(aspg.text = (void *) tsp)) return NIL;
2358 /* else install last sequence */
2359 if (last != start) ss->last = last;
2362 args[0] = &apgm; args[1] = &achs; args[2] = &aspg; args[3] = NIL;
2363 /* ask server to do it */
2364 reply = imap_send (stream,cmd,args);
2365 if (tsp) { /* was there a temporary searchpgm? */
2366 aspg.text = NIL; /* yes, flush it */
2367 mail_free_searchpgm (&tsp);
2368 /* did server barf with that searchpgm? */
2369 if (!(flags & SE_UID) && !strcmp (reply->key,"BAD")) {
2370 LOCAL->filter = T; /* retry, filtering SORT/THREAD results */
2371 reply = imap_send (stream,cmd,args);
2372 LOCAL->filter = NIL; /* turn off filtering */
2375 /* do locally if server barfs */
2376 if (!strcmp (reply->key,"BAD"))
2377 ret = (flags & SE_NOLOCAL) ? NIL:
2378 mail_thread_msgs (stream,type,charset,spg,flags | SE_NOSERVER,imap_sort);
2379 /* server threaded OK? */
2380 else if (imap_OK (stream,reply)) {
2381 ret = LOCAL->threaddata;
2382 LOCAL->threaddata = NIL; /* mail program is responsible for flushing */
2384 else mm_log (reply->text,ERROR);
2385 return ret;
2388 /* IMAP ping mailbox
2389 * Accepts: MAIL stream
2390 * Returns: T if stream still alive, else NIL
2393 long imap_ping (MAILSTREAM *stream)
2395 return (LOCAL->netstream && /* send "NOOP" */
2396 imap_OK (stream,imap_send (stream,"NOOP",NIL))) ? T : NIL;
2400 /* IMAP check mailbox
2401 * Accepts: MAIL stream
2404 void imap_check (MAILSTREAM *stream)
2406 /* send "CHECK" */
2407 IMAPPARSEDREPLY *reply = imap_send (stream,"CHECK",NIL);
2408 mm_log (reply->text,imap_OK (stream,reply) ? (long) NIL : ERROR);
2411 /* IMAP expunge mailbox
2412 * Accepts: MAIL stream
2413 * sequence to expunge if non-NIL
2414 * expunge options
2415 * Returns: T if success, NIL if failure
2418 long imap_expunge (MAILSTREAM *stream,char *sequence,long options)
2420 long ret = NIL;
2421 IMAPPARSEDREPLY *reply = NIL;
2422 if (sequence) { /* wants selective expunging? */
2423 if (options & EX_UID) { /* UID EXPUNGE form? */
2424 if (LEVELUIDPLUS (stream)) {/* server support UIDPLUS? */
2425 IMAPARG *args[2],aseq;
2426 aseq.type = SEQUENCE; aseq.text = (void *) sequence;
2427 args[0] = &aseq; args[1] = NIL;
2428 ret = imap_OK (stream,reply = imap_send (stream,"UID EXPUNGE",args));
2430 else mm_log ("[NOTUIDPLUS] Can't do UID EXPUNGE with this server",ERROR);
2432 /* otherwise try to make into UID EXPUNGE */
2433 else if (mail_sequence (stream,sequence)) {
2434 unsigned long i,j;
2435 char *t = (char *) fs_get (IMAPTMPLEN);
2436 char *s = t;
2437 /* search through mailbox */
2438 for (*s = '\0', i = 1; i <= stream->nmsgs; ++i)
2439 if (mail_elt (stream,i)->sequence) {
2440 if (t[0]) *s++ = ','; /* prepend with comma if not first time */
2441 sprintf (s,"%lu",mail_uid (stream,j = i));
2442 s += strlen (s); /* point at end of string */
2443 /* search for possible end of range */
2444 while ((i < stream->nmsgs) && mail_elt (stream,i+1)->sequence) i++;
2445 if (i != j) { /* output end of range */
2446 sprintf (s,":%lu",mail_uid (stream,i));
2447 s += strlen (s); /* point at end of string */
2449 if ((s - t) > (IMAPTMPLEN - 50)) {
2450 mm_log ("Excessively complex sequence",ERROR);
2451 return NIL;
2454 /* now do as UID EXPUNGE */
2455 ret = imap_expunge (stream,t,EX_UID);
2456 fs_give ((void **) &t);
2459 /* ordinary EXPUNGE */
2460 else ret = imap_OK (stream,reply = imap_send (stream,"EXPUNGE",NIL));
2461 if (reply) mm_log (reply->text,ret ? (long) NIL : ERROR);
2462 return ret;
2465 /* IMAP copy message(s)
2466 * Accepts: MAIL stream
2467 * sequence
2468 * destination mailbox
2469 * option flags
2470 * Returns: T if successful else NIL
2473 long imap_copy (MAILSTREAM *stream,char *sequence,char *mailbox,long flags)
2475 char *cmd = (LEVELIMAP4 (stream) && (flags & CP_UID)) ? "UID COPY" : "COPY";
2476 char *s;
2477 long ret = NIL;
2478 IMAPPARSEDREPLY *reply;
2479 IMAPARG *args[3],aseq,ambx;
2480 imapreferral_t ir =
2481 (imapreferral_t) mail_parameters (stream,GET_IMAPREFERRAL,NIL);
2482 mailproxycopy_t pc =
2483 (mailproxycopy_t) mail_parameters (stream,GET_MAILPROXYCOPY,NIL);
2484 if (LOCAL->loser) sequence = imap_reform_sequence (stream,sequence,
2485 flags & CP_UID);
2486 aseq.type = SEQUENCE; aseq.text = (void *) sequence;
2487 ambx.type = ASTRING; ambx.text = (void *) mailbox;
2488 args[0] = &aseq; args[1] = &ambx; args[2] = NIL;
2489 /* note mailbox in case APPENDUID */
2490 LOCAL->appendmailbox = mailbox;
2491 /* send "COPY sequence mailbox" */
2492 ret = imap_OK (stream,reply = imap_send (stream,cmd,args));
2493 LOCAL->appendmailbox = NIL; /* no longer appending */
2494 if (ret) { /* success, delete messages if move */
2495 if (flags & CP_MOVE) imap_flag (stream,sequence,"\\Deleted",
2496 ST_SET + ((flags&CP_UID) ? ST_UID : NIL));
2498 /* failed, do referral action if any */
2499 else if (ir && pc && LOCAL->referral && mail_sequence (stream,sequence) &&
2500 (s = (*ir) (stream,LOCAL->referral,REFCOPY)))
2501 ret = (*pc) (stream,sequence,s,flags | (stream->debug ? CP_DEBUG : NIL));
2502 /* otherwise issue error message */
2503 else mm_log (reply->text,ERROR);
2504 return ret;
2507 /* IMAP mail append message from stringstruct
2508 * Accepts: MAIL stream
2509 * destination mailbox
2510 * append callback
2511 * data for callback
2512 * Returns: T if append successful, else NIL
2515 long imap_append (MAILSTREAM *stream,char *mailbox,append_t af,void *data)
2517 MAILSTREAM *st = stream;
2518 IMAPARG *args[3],ambx,amap;
2519 IMAPPARSEDREPLY *reply = NIL;
2520 APPENDDATA map;
2521 char tmp[MAILTMPLEN];
2522 long debug = stream ? stream->debug : NIL;
2523 long ret = NIL;
2524 imapreferral_t ir =
2525 (imapreferral_t) mail_parameters (stream,GET_IMAPREFERRAL,NIL);
2526 /* mailbox must be good */
2527 if (mail_valid_net (mailbox,&imapdriver,NIL,tmp)) {
2528 /* create a stream if given one no good */
2529 if ((stream && LOCAL && LOCAL->netstream) ||
2530 (stream = mail_open (NIL,mailbox,OP_HALFOPEN|OP_SILENT |
2531 (debug ? OP_DEBUG : NIL)))) {
2532 /* note mailbox in case APPENDUID */
2533 LOCAL->appendmailbox = mailbox;
2534 /* use multi-append? */
2535 if (LEVELMULTIAPPEND (stream)) {
2536 ambx.type = ASTRING; ambx.text = (void *) tmp;
2537 amap.type = MULTIAPPEND; amap.text = (void *) &map;
2538 map.af = af; map.data = data;
2539 args[0] = &ambx; args[1] = &amap; args[2] = NIL;
2540 /* success if OK */
2541 ret = imap_OK (stream,reply = imap_send (stream,"APPEND",args));
2542 LOCAL->appendmailbox = NIL;
2544 /* do succession of single appends */
2545 else while ((*af) (stream,data,&map.flags,&map.date,&map.message) &&
2546 map.message &&
2547 (ret = imap_OK (stream,reply =
2548 imap_append_single (stream,tmp,map.flags,
2549 map.date,map.message))));
2550 LOCAL->appendmailbox = NIL;
2551 /* don't do referrals if success or no reply */
2552 if (ret || !reply) mailbox = NIL;
2553 /* otherwise generate referral */
2554 else if (!(mailbox = (ir && LOCAL->referral) ?
2555 (*ir) (stream,LOCAL->referral,REFAPPEND) : NIL))
2556 mm_log (reply->text,ERROR);
2557 /* close temporary stream */
2558 if (st != stream) stream = mail_close (stream);
2559 if (mailbox) /* chase referral if any */
2560 ret = imap_append_referral (mailbox,tmp,af,data,map.flags,map.date,
2561 map.message,&map,debug);
2563 else mm_log ("Can't access server for append",ERROR);
2565 return ret; /* return */
2568 /* IMAP mail append message referral retry
2569 * Accepts: destination mailbox
2570 * temporary buffer
2571 * append callback
2572 * data for callback
2573 * flags from previous attempt
2574 * date from previous attempt
2575 * message stringstruct from previous attempt
2576 * options (currently non-zero to set OP_DEBUG)
2577 * Returns: T if append successful, else NIL
2580 long imap_append_referral (char *mailbox,char *tmp,append_t af,void *data,
2581 char *flags,char *date,STRING *message,
2582 APPENDDATA *map,long options)
2584 MAILSTREAM *stream;
2585 IMAPARG *args[3],ambx,amap;
2586 IMAPPARSEDREPLY *reply;
2587 imapreferral_t ir =
2588 (imapreferral_t) mail_parameters (NIL,GET_IMAPREFERRAL,NIL);
2589 /* barf if bad mailbox */
2590 while (mailbox && mail_valid_net (mailbox,&imapdriver,NIL,tmp)) {
2591 /* create a stream if given one no good */
2592 if (!(stream = mail_open (NIL,mailbox,OP_HALFOPEN|OP_SILENT |
2593 (options ? OP_DEBUG : NIL)))) {
2594 sprintf (tmp,"Can't access referral server: %.80s",mailbox);
2595 mm_log (tmp,ERROR);
2596 return NIL;
2598 /* got referral server, use multi-append? */
2599 if (LEVELMULTIAPPEND (stream)) {
2600 ambx.type = ASTRING; ambx.text = (void *) tmp;
2601 amap.type = MULTIAPPENDREDO; amap.text = (void *) map;
2602 args[0] = &ambx; args[1] = &amap; args[2] = NIL;
2603 /* do multiappend on referral site */
2604 if (imap_OK (stream,reply = imap_send (stream,"APPEND",args))) {
2605 mail_close (stream); /* multiappend OK, close stream */
2606 return LONGT; /* all done */
2609 /* do multiple single appends */
2610 else while (imap_OK (stream,reply =
2611 imap_append_single (stream,tmp,flags,date,message)))
2612 if (!((*af) (stream,data,&flags,&date,&message) && message)) {
2613 mail_close (stream); /* last message, close stream */
2614 return LONGT; /* all done */
2616 /* generate error if no nested referral */
2617 if (!(mailbox = (ir && LOCAL->referral) ?
2618 (*ir) (stream,LOCAL->referral,REFAPPEND) : NIL))
2619 mm_log (reply->text,ERROR);
2620 mail_close (stream); /* close previous referral stream */
2622 return NIL; /* bogus mailbox */
2625 /* IMAP append single message
2626 * Accepts: mail stream
2627 * destination mailbox
2628 * initial flags
2629 * internal date
2630 * stringstruct of message to append
2631 * Returns: reply from append
2634 IMAPPARSEDREPLY *imap_append_single (MAILSTREAM *stream,char *mailbox,
2635 char *flags,char *date,STRING *message)
2637 MESSAGECACHE elt;
2638 IMAPARG *args[5],ambx,aflg,adat,amsg;
2639 IMAPPARSEDREPLY *reply;
2640 char tmp[MAILTMPLEN];
2641 int i;
2642 ambx.type = ASTRING; ambx.text = (void *) mailbox;
2643 args[i = 0] = &ambx;
2644 if (flags) {
2645 aflg.type = FLAGS; aflg.text = (void *) flags;
2646 args[++i] = &aflg;
2648 if (date) { /* ensure date in INTERNALDATE format */
2649 if (!mail_parse_date (&elt,date)) {
2650 /* flush previous reply */
2651 if (LOCAL->reply.line) fs_give ((void **) &LOCAL->reply.line);
2652 /* build new fake reply */
2653 LOCAL->reply.tag = LOCAL->reply.line = cpystr ("*");
2654 LOCAL->reply.key = "BAD";
2655 LOCAL->reply.text = "Bad date in append";
2656 return &LOCAL->reply;
2658 adat.type = ASTRING;
2659 adat.text = (void *) (date = mail_date (tmp,&elt));
2660 args[++i] = &adat;
2662 amsg.type = LITERAL; amsg.text = (void *) message;
2663 args[++i] = &amsg;
2664 args[++i] = NIL;
2665 /* easy if IMAP4[rev1] */
2666 if (LEVELIMAP4 (stream)) reply = imap_send (stream,"APPEND",args);
2667 else { /* try the IMAP2bis way */
2668 args[1] = &amsg; args[2] = NIL;
2669 reply = imap_send (stream,"APPEND",args);
2671 return reply;
2674 /* IMAP garbage collect stream
2675 * Accepts: Mail stream
2676 * garbage collection flags
2679 void imap_gc (MAILSTREAM *stream,long gcflags)
2681 unsigned long i;
2682 MESSAGECACHE *elt;
2683 mailcache_t mc = (mailcache_t) mail_parameters (NIL,GET_CACHE,NIL);
2684 /* make sure the cache is large enough */
2685 (*mc) (stream,stream->nmsgs,CH_SIZE);
2686 if (gcflags & GC_TEXTS) { /* garbage collect texts? */
2687 if (!stream->scache) for (i = 1; i <= stream->nmsgs; ++i)
2688 if ((elt = (MESSAGECACHE *) (*mc) (stream,i,CH_ELT)) != NULL)
2689 imap_gc_body (elt->private.msg.body);
2690 imap_gc_body (stream->body);
2692 /* gc cache if requested and unlocked */
2693 if (gcflags & GC_ELT) for (i = 1; i <= stream->nmsgs; ++i)
2694 if ((elt = (MESSAGECACHE *) (*mc) (stream,i,CH_ELT)) &&
2695 (elt->lockcount == 1)) (*mc) (stream,i,CH_FREE);
2698 /* IMAP garbage collect body texts
2699 * Accepts: body to GC
2702 void imap_gc_body (BODY *body)
2704 PART *part;
2705 if (body) { /* have a body? */
2706 if (body->mime.text.data) /* flush MIME data */
2707 fs_give ((void **) &body->mime.text.data);
2708 /* flush text contents */
2709 if (body->contents.text.data)
2710 fs_give ((void **) &body->contents.text.data);
2711 body->mime.text.size = body->contents.text.size = 0;
2712 /* multipart? */
2713 if (body->type == TYPEMULTIPART)
2714 for (part = body->nested.part; part; part = part->next)
2715 imap_gc_body (&part->body);
2716 /* MESSAGE/RFC822? */
2717 else if ((body->type == TYPEMESSAGE) && !strcmp (body->subtype,"RFC822")) {
2718 imap_gc_body (body->nested.msg->body);
2719 if (body->nested.msg->full.text.data)
2720 fs_give ((void **) &body->nested.msg->full.text.data);
2721 if (body->nested.msg->header.text.data)
2722 fs_give ((void **) &body->nested.msg->header.text.data);
2723 if (body->nested.msg->text.text.data)
2724 fs_give ((void **) &body->nested.msg->text.text.data);
2725 body->nested.msg->full.text.size = body->nested.msg->header.text.size =
2726 body->nested.msg->text.text.size = 0;
2731 /* IMAP get capabilities
2732 * Accepts: mail stream
2735 void imap_capability (MAILSTREAM *stream)
2737 THREADER *thr,*t;
2738 LOCAL->gotcapability = NIL; /* flush any previous capabilities */
2739 /* request new capabilities */
2740 imap_send (stream,"CAPABILITY",NIL);
2741 if (!LOCAL->gotcapability) { /* did server get any? */
2742 /* no, flush threaders just in case */
2743 if ((thr = LOCAL->cap.threader) != NULL) while ((t = thr) != NULL) {
2744 fs_give ((void **) &t->name);
2745 thr = t->next;
2746 fs_give ((void **) &t);
2748 /* zap most capabilities */
2749 memset (&LOCAL->cap,0,sizeof (LOCAL->cap));
2750 /* assume IMAP2bis server if failure */
2751 LOCAL->cap.imap2bis = LOCAL->cap.rfc1176 = T;
2755 /* IMAP set ACL
2756 * Accepts: mail stream
2757 * mailbox name
2758 * authentication identifer
2759 * new access rights
2760 * Returns: T on success, NIL on failure
2763 long imap_setacl (MAILSTREAM *stream,char *mailbox,char *id,char *rights)
2765 IMAPARG *args[4],ambx,aid,art;
2766 ambx.type = aid.type = art.type = ASTRING;
2767 ambx.text = (void *) mailbox; aid.text = (void *) id;
2768 art.text = (void *) rights;
2769 args[0] = &ambx; args[1] = &aid; args[2] = &art; args[3] = NIL;
2770 return imap_acl_work (stream,"SETACL",args);
2774 /* IMAP delete ACL
2775 * Accepts: mail stream
2776 * mailbox name
2777 * authentication identifer
2778 * Returns: T on success, NIL on failure
2781 long imap_deleteacl (MAILSTREAM *stream,char *mailbox,char *id)
2783 IMAPARG *args[3],ambx,aid;
2784 ambx.type = aid.type = ASTRING;
2785 ambx.text = (void *) mailbox; aid.text = (void *) id;
2786 args[0] = &ambx; args[1] = &aid; args[2] = NIL;
2787 return imap_acl_work (stream,"DELETEACL",args);
2791 /* IMAP get ACL
2792 * Accepts: mail stream
2793 * mailbox name
2794 * Returns: T on success with data returned via callback, NIL on failure
2797 long imap_getacl (MAILSTREAM *stream,char *mailbox)
2799 IMAPARG *args[2],ambx;
2800 ambx.type = ASTRING; ambx.text = (void *) mailbox;
2801 args[0] = &ambx; args[1] = NIL;
2802 return imap_acl_work (stream,"GETACL",args);
2805 /* IMAP list rights
2806 * Accepts: mail stream
2807 * mailbox name
2808 * authentication identifer
2809 * Returns: T on success with data returned via callback, NIL on failure
2812 long imap_listrights (MAILSTREAM *stream,char *mailbox,char *id)
2814 IMAPARG *args[3],ambx,aid;
2815 ambx.type = aid.type = ASTRING;
2816 ambx.text = (void *) mailbox; aid.text = (void *) id;
2817 args[0] = &ambx; args[1] = &aid; args[2] = NIL;
2818 return imap_acl_work (stream,"LISTRIGHTS",args);
2822 /* IMAP my rights
2823 * Accepts: mail stream
2824 * mailbox name
2825 * Returns: T on success with data returned via callback, NIL on failure
2828 long imap_myrights (MAILSTREAM *stream,char *mailbox)
2830 IMAPARG *args[2],ambx;
2831 ambx.type = ASTRING; ambx.text = (void *) mailbox;
2832 args[0] = &ambx; args[1] = NIL;
2833 return imap_acl_work (stream,"MYRIGHTS",args);
2837 /* IMAP ACL worker routine
2838 * Accepts: mail stream
2839 * command
2840 * command arguments
2841 * Returns: T on success, NIL on failure
2844 long imap_acl_work (MAILSTREAM *stream,char *command,IMAPARG *args[])
2846 long ret = NIL;
2847 if (LEVELACL (stream)) { /* send command */
2848 IMAPPARSEDREPLY *reply;
2849 if (imap_OK (stream,reply = imap_send (stream,command,args)))
2850 ret = LONGT;
2851 else mm_log (reply->text,ERROR);
2853 else mm_log ("ACL not available on this IMAP server",ERROR);
2854 return ret;
2857 /* IMAP set quota
2858 * Accepts: mail stream
2859 * quota root name
2860 * resource limit list as a stringlist
2861 * Returns: T on success with data returned via callback, NIL on failure
2864 long imap_setquota (MAILSTREAM *stream,char *qroot,STRINGLIST *limits)
2866 long ret = NIL;
2867 if (LEVELQUOTA (stream)) { /* send "SETQUOTA" */
2868 IMAPPARSEDREPLY *reply;
2869 IMAPARG *args[3],aqrt,alim;
2870 aqrt.type = ASTRING; aqrt.text = (void *) qroot;
2871 alim.type = SNLIST; alim.text = (void *) limits;
2872 args[0] = &aqrt; args[1] = &alim; args[2] = NIL;
2873 if (imap_OK (stream,reply = imap_send (stream,"SETQUOTA",args)))
2874 ret = LONGT;
2875 else mm_log (reply->text,ERROR);
2877 else mm_log ("Quota not available on this IMAP server",ERROR);
2878 return ret;
2881 IDLIST *imap_parse_idlist (char *text)
2883 IDLIST *ret = NULL;
2884 char *s;
2885 char tmp[MAILTMPLEN];
2887 if(text == NULL) return NULL;
2888 for(s = text; *s == ' '; s++); /* move past spaces */
2889 if(*s == '(') s++;
2890 if(*s++ == '"'){
2891 char *t;
2892 for(t = s; *t && *t != '"'; t++);
2893 if(*t == '"'){
2894 ret = fs_get(sizeof(IDLIST));
2895 *t = '\0';
2896 ret->name = cpystr(s);
2897 *t = '"';
2898 for(s = t+1; *s == ' '; s++); /* move past spaces */
2899 if(*s++ == '"'){
2900 for(t = s; *t && *t != '"'; t++);
2901 if(*t == '"'){
2902 *t = '\0';
2903 ret->value = cpystr(s);
2904 *t++ = '"';
2905 ret->next = imap_parse_idlist(t);
2907 else {
2908 sprintf(tmp,"ID value not found for name %.80s, at %.80s", ret->name, s);
2909 fs_give((void **)&ret->name);
2910 fs_give((void **)&ret);
2911 mm_log (tmp, NIL); /* this is an technically an error */
2914 else { /* failed!, quit */
2915 sprintf(tmp,"ID name \"%.80s\" has no value", ret->name);
2916 fs_give((void **)&ret->name);
2917 fs_give((void **)&ret);
2918 mm_log (tmp, NIL); /* this is an technically an error */
2922 return ret;
2925 long imap_setid (MAILSTREAM *stream, IDLIST *idlist)
2927 long ret = NIL;
2928 if (LEVELID (stream)) { /* send "ID (params)" */
2929 IMAPPARSEDREPLY *reply;
2930 IMAPARG *args[2],aqrt;
2931 IDLIST *list;
2932 char *qroot, *p;
2933 long len = 0L;
2935 if(idlist == NULL) return ret;
2936 for (list = idlist; list != NULL; list = list->next)
2937 len += strlen(list->name) + strlen(list->value) + 6;
2938 if(len > 0){
2939 len += 1L; /* in case there is only one field */
2940 qroot = fs_get(len+1);
2941 memset((void *)&qroot[0], 0, len+1);
2942 p = qroot;
2943 for (list = idlist; list != NULL; list = list->next){
2944 sprintf(p, " \"%s\" \"%s\"", list->name, list->value);
2945 p += strlen(p);
2947 *p = ')';
2948 qroot[0] = '(';
2949 aqrt.type = ATOM; aqrt.text = (void *) qroot;
2950 args[0] = &aqrt; args[1] = NIL;
2951 if (imap_OK (stream,reply = imap_send (stream,"ID",args)))
2952 ret = LONGT;
2953 else mm_log (reply->text,ERROR);
2954 if(qroot) fs_give((void **) &qroot);
2955 } else mm_log("Empty or malformed ID list", ERROR);
2957 else mm_log ("ID capability not available on this IMAP server",ERROR);
2958 return ret;
2961 /* IMAP get quota
2962 * Accepts: mail stream
2963 * quota root name
2964 * Returns: T on success with data returned via callback, NIL on failure
2967 long imap_getquota (MAILSTREAM *stream,char *qroot)
2969 long ret = NIL;
2970 if (LEVELQUOTA (stream)) { /* send "GETQUOTA" */
2971 IMAPPARSEDREPLY *reply;
2972 IMAPARG *args[2],aqrt;
2973 aqrt.type = ASTRING; aqrt.text = (void *) qroot;
2974 args[0] = &aqrt; args[1] = NIL;
2975 if (imap_OK (stream,reply = imap_send (stream,"GETQUOTA",args)))
2976 ret = LONGT;
2977 else mm_log (reply->text,ERROR);
2979 else mm_log ("Quota not available on this IMAP server",ERROR);
2980 return ret;
2984 /* IMAP get quota root
2985 * Accepts: mail stream
2986 * mailbox name
2987 * Returns: T on success with data returned via callback, NIL on failure
2990 long imap_getquotaroot (MAILSTREAM *stream,char *mailbox)
2992 long ret = NIL;
2993 if (LEVELQUOTA (stream)) { /* send "GETQUOTAROOT" */
2994 IMAPPARSEDREPLY *reply;
2995 IMAPARG *args[2],ambx;
2996 ambx.type = ASTRING; ambx.text = (void *) mailbox;
2997 args[0] = &ambx; args[1] = NIL;
2998 if (imap_OK (stream,reply = imap_send (stream,"GETQUOTAROOT",args)))
2999 ret = LONGT;
3000 else mm_log (reply->text,ERROR);
3002 else mm_log ("Quota not available on this IMAP server",ERROR);
3003 return ret;
3006 /* Internal routines */
3009 /* IMAP send command
3010 * Accepts: MAIL stream
3011 * command
3012 * argument list
3013 * Returns: parsed reply
3016 #define CMDBASE LOCAL->tmp /* command base */
3018 IMAPPARSEDREPLY *imap_send (MAILSTREAM *stream,char *cmd,IMAPARG *args[])
3020 IMAPPARSEDREPLY *reply;
3021 IMAPARG *arg,**arglst;
3022 SORTPGM *spg;
3023 STRINGLIST *list;
3024 SIZEDTEXT st;
3025 APPENDDATA *map;
3026 sendcommand_t sc = (sendcommand_t) mail_parameters (NIL,GET_SENDCOMMAND,NIL);
3027 size_t i;
3028 void *a;
3029 char c,*s,*t,tag[10];
3030 stream->unhealthy = NIL; /* make stream healthy again */
3031 /* gensym a new tag */
3032 sprintf (tag,"%08lx",0xffffffff & (stream->gensym++));
3033 if (!LOCAL->netstream) /* make sure have a session */
3034 return imap_fake (stream,tag,"[CLOSED] IMAP connection lost");
3035 mail_lock (stream); /* lock up the stream */
3036 if (sc) /* tell client sending a command */
3037 (*sc) (stream,cmd,((compare_cstring (cmd,"FETCH") &&
3038 compare_cstring (cmd,"STORE") &&
3039 compare_cstring (cmd,"SEARCH")) ?
3040 NIL : SC_EXPUNGEDEFERRED));
3041 /* ignore referral from previous command */
3042 if (LOCAL->referral) fs_give ((void **) &LOCAL->referral);
3043 sprintf (CMDBASE,"%s %s",tag,cmd);
3044 s = CMDBASE + strlen (CMDBASE);
3045 if ((arglst = args) != NULL) while ((arg = *arglst++) != NULL) {
3046 *s++ = ' '; /* delimit argument with space */
3047 switch (arg->type) {
3048 case ATOM: /* atom */
3049 for (t = (char *) arg->text; *t; *s++ = *t++);
3050 break;
3051 case NUMBER: /* number */
3052 sprintf (s,"%lu",(unsigned long) arg->text);
3053 s += strlen (s);
3054 break;
3055 case FLAGS: /* flag list as a single string */
3056 if (*(t = (char *) arg->text) != '(') {
3057 *s++ = '('; /* wrap parens around string */
3058 while (*t) *s++ = *t++;
3059 *s++ = ')'; /* wrap parens around string */
3061 else while (*t) *s++ = *t++;
3062 break;
3063 case ASTRING: /* atom or string, must be literal? */
3064 st.size = strlen ((char *) (st.data = (unsigned char *) arg->text));
3065 if ((reply = imap_send_astring (stream,tag,&s,&st,NIL,CMDBASE+MAXCOMMAND)) != NULL)
3066 return reply;
3067 break;
3068 case LITERAL: /* literal, as a stringstruct */
3069 if ((reply = imap_send_literal (stream,tag,&s,arg->text)) != NULL) return reply;
3070 break;
3072 case LIST: /* list of strings */
3073 list = (STRINGLIST *) arg->text;
3074 c = '('; /* open paren */
3075 do { /* for each list item */
3076 *s++ = c; /* write prefix character */
3077 if ((reply = imap_send_astring (stream,tag,&s,&list->text,NIL,
3078 CMDBASE+MAXCOMMAND)) != NULL) return reply;
3079 c = ' '; /* prefix character for subsequent strings */
3081 while ((list = list->next) != NULL);
3082 *s++ = ')'; /* close list */
3083 break;
3084 case SEARCHPROGRAM: /* search program */
3085 if ((reply = imap_send_spgm (stream,tag,CMDBASE,&s,arg->text,
3086 CMDBASE+MAXCOMMAND)) != NULL)
3087 return reply;
3088 break;
3089 case SORTPROGRAM: /* search program */
3090 c = '('; /* open paren */
3091 for (spg = (SORTPGM *) arg->text; spg; spg = spg->next) {
3092 *s++ = c; /* write prefix */
3093 if (spg->reverse) for (t = "REVERSE "; *t; *s++ = *t++);
3094 switch (spg->function) {
3095 case SORTDATE:
3096 for (t = "DATE"; *t; *s++ = *t++);
3097 break;
3098 case SORTARRIVAL:
3099 for (t = "ARRIVAL"; *t; *s++ = *t++);
3100 break;
3101 case SORTFROM:
3102 for (t = "FROM"; *t; *s++ = *t++);
3103 break;
3104 case SORTSUBJECT:
3105 for (t = "SUBJECT"; *t; *s++ = *t++);
3106 break;
3107 case SORTTO:
3108 for (t = "TO"; *t; *s++ = *t++);
3109 break;
3110 case SORTCC:
3111 for (t = "CC"; *t; *s++ = *t++);
3112 break;
3113 case SORTSIZE:
3114 for (t = "SIZE"; *t; *s++ = *t++);
3115 break;
3116 default:
3117 fatal ("Unknown sort program function in imap_send()!");
3119 c = ' '; /* prefix character for subsequent items */
3121 *s++ = ')'; /* close list */
3122 break;
3124 case BODYTEXT: /* body section */
3125 for (t = "BODY["; *t; *s++ = *t++);
3126 for (t = (char *) arg->text; *t; *s++ = *t++);
3127 break;
3128 case BODYPEEK: /* body section */
3129 for (t = "BODY.PEEK["; *t; *s++ = *t++);
3130 for (t = (char *) arg->text; *t; *s++ = *t++);
3131 break;
3132 case BODYCLOSE: /* close bracket and possible length */
3133 s[-1] = ']'; /* no leading space */
3134 for (t = (char *) arg->text; *t; *s++ = *t++);
3135 break;
3136 case SEQUENCE: /* sequence */
3137 if ((i = strlen (t = (char *) arg->text)) <= (size_t) MAXCOMMAND)
3138 while (*t) *s++ = *t++; /* easy case */
3139 else {
3140 mail_unlock (stream); /* unlock stream */
3141 a = arg->text; /* save original sequence pointer */
3142 arg->type = ATOM; /* make recursive call be faster */
3143 do { /* break up into multiple commands */
3144 if (i <= MAXCOMMAND) {/* final part? */
3145 reply = imap_send (stream,cmd,args);
3146 i = 0; /* and mark as done */
3148 else { /* still needs to be split further */
3149 if (!(t = strchr (t + MAXCOMMAND - 30,',')) ||
3150 ((t - (char *) arg->text) > MAXCOMMAND))
3151 fatal ("impossible over-long sequence");
3152 *t = '\0'; /* tie off sequence at point of split*/
3153 /* recurse to do this part */
3154 reply = imap_send (stream,cmd,args);
3155 *t++ = ','; /* restore the comma in case something cares */
3156 /* punt if error */
3157 if (!imap_OK (stream,reply)) break;
3158 /* calculate size of remaining sequence */
3159 i -= (t - (char *) arg->text);
3160 /* point to new remaining sequence */
3161 arg->text = (void *) t;
3163 } while (i);
3164 arg->type = SEQUENCE; /* restore in case something cares */
3165 arg->text = a;
3166 return reply; /* return result */
3168 break;
3169 case LISTMAILBOX: /* astring with wildcards */
3170 st.size = strlen ((char *) (st.data = (unsigned char *) arg->text));
3171 if ((reply = imap_send_astring (stream,tag,&s,&st,T,CMDBASE+MAXCOMMAND)) != NULL)
3172 return reply;
3173 break;
3175 case MULTIAPPEND: /* append multiple messages */
3176 /* get package pointer */
3177 map = (APPENDDATA *) arg->text;
3178 if (!(*map->af) (stream,map->data,&map->flags,&map->date,&map->message)||
3179 !map->message) {
3180 STRING es;
3181 INIT (&es,mail_string,"",0);
3182 return (reply = imap_send_literal (stream,tag,&s,&es)) ?
3183 reply : imap_fake (stream,tag,"Server zero-length literal error");
3185 case MULTIAPPENDREDO: /* redo multiappend */
3186 /* get package pointer */
3187 map = (APPENDDATA *) arg->text;
3188 do { /* make sure date valid if given */
3189 char datetmp[MAILTMPLEN];
3190 MESSAGECACHE elt;
3191 STRING es;
3192 if (!map->date || mail_parse_date (&elt,map->date)) {
3193 if ((t = map->flags) != NULL) { /* flags given? */
3194 if (*t != '(') {
3195 *s++ = '('; /* wrap parens around string */
3196 while (*t) *s++ = *t++;
3197 *s++ = ')'; /* wrap parens around string */
3199 else while (*t) *s++ = *t++;
3200 *s++ = ' '; /* delimit with space */
3202 if (map->date) { /* date given? */
3203 st.size = strlen ((char *) (st.data = (unsigned char *)
3204 mail_date (datetmp,&elt)));
3205 if ((reply = imap_send_astring (stream,tag,&s,&st,NIL,
3206 CMDBASE+MAXCOMMAND)) != NULL) return reply;
3207 *s++ = ' '; /* delimit with space */
3209 if ((reply = imap_send_literal (stream,tag,&s,map->message)) != NULL)
3210 return reply;
3211 /* get next message */
3212 if ((*map->af) (stream,map->data,&map->flags,&map->date,
3213 &map->message)) {
3214 /* have a message, delete next in command */
3215 if (map->message) *s++ = ' ';
3216 continue; /* loop back for next message */
3219 /* bad date or need to abort */
3220 INIT (&es,mail_string,"",0);
3221 return (reply = imap_send_literal (stream,tag,&s,&es)) ?
3222 reply : imap_fake (stream,tag,"Server zero-length literal error");
3223 break; /* exit the loop */
3224 } while (map->message);
3225 break;
3227 case SNLIST: /* list of string/number pairs */
3228 list = (STRINGLIST *) arg->text;
3229 c = '('; /* open paren */
3230 do { /* for each list item */
3231 *s++ = c; /* write prefix character */
3232 if (list) { /* sigh, QUOTA has bizarre syntax! */
3233 for (t = (char *) list->text.data; *t; *s++ = *t++);
3234 sprintf (s," %lu",list->text.size);
3235 s += strlen (s);
3236 c = ' '; /* prefix character for subsequent strings */
3239 while ((list = list->next) != NULL);
3240 *s++ = ')'; /* close list */
3241 break;
3242 default:
3243 fatal ("Unknown argument type in imap_send()!");
3246 /* send the command */
3247 reply = imap_sout (stream,tag,CMDBASE,&s);
3248 mail_unlock (stream); /* unlock stream */
3249 return reply;
3252 /* IMAP send atom-string
3253 * Accepts: MAIL stream
3254 * reply tag
3255 * pointer to current position pointer of output bigbuf
3256 * atom-string to output
3257 * flag if list_wildcards allowed
3258 * maximum to write as atom or qstring
3259 * Returns: error reply or NIL if success
3262 IMAPPARSEDREPLY *imap_send_astring (MAILSTREAM *stream,char *tag,char **s,
3263 SIZEDTEXT *as,long wildok,char *limit)
3265 unsigned long j;
3266 char c;
3267 STRING st;
3268 /* default to atom unless empty or loser */
3269 int qflag = (as->size && !LOCAL->loser) ? NIL : T;
3270 /* in case needed */
3271 INIT (&st,mail_string,(void *) as->data,as->size);
3272 /* always write literal if no space */
3273 if ((*s + as->size) > limit) return imap_send_literal (stream,tag,s,&st);
3274 for (j = 0; j < as->size; j++) switch (c = as->data[j]) {
3275 default: /* all other characters */
3276 if (!(c & 0x80)) { /* must not be 8bit */
3277 if (c <= ' ') qflag = T; /* must quote if a CTL */
3278 break;
3280 case '\0': /* not a CHAR */
3281 case '\012': case '\015': /* not a TEXT-CHAR */
3282 case '"': case '\\': /* quoted-specials (IMAP2 required this) */
3283 return imap_send_literal (stream,tag,s,&st);
3284 case '*': case '%': /* list_wildcards */
3285 if (wildok) break; /* allowed if doing the wild thing */
3286 /* atom_specials */
3287 case '(': case ')': case '{': case ' ': case 0x7f:
3288 #if 0
3289 case '"': case '\\': /* quoted-specials (could work in IMAP4) */
3290 #endif
3291 qflag = T; /* must use quoted string format */
3292 break;
3294 if (qflag) *(*s)++ = '"'; /* write open quote */
3295 for (j = 0; j < as->size; j++) *(*s)++ = as->data[j];
3296 if (qflag) *(*s)++ = '"'; /* write close quote */
3297 return NIL;
3300 /* IMAP send literal
3301 * Accepts: MAIL stream
3302 * reply tag
3303 * pointer to current position pointer of output bigbuf
3304 * literal to output as stringstruct
3305 * Returns: error reply or NIL if success
3308 IMAPPARSEDREPLY *imap_send_literal (MAILSTREAM *stream,char *tag,char **s,
3309 STRING *st)
3311 IMAPPARSEDREPLY *reply;
3312 unsigned long i = SIZE (st);
3313 unsigned long j;
3314 sprintf (*s,"{%lu}",i); /* write literal count */
3315 *s += strlen (*s); /* size of literal count */
3316 /* send the command */
3317 reply = imap_sout (stream,tag,CMDBASE,s);
3318 if (strcmp (reply->tag,"+")) {/* prompt for more data? */
3319 mail_unlock (stream); /* no, give up */
3320 return reply;
3322 while (i) { /* dump the text */
3323 if (st->cursize) { /* if text to do in this chunk */
3324 /* RFC 3501 technically forbids NULs in literals. Normally, the
3325 * delivering MTA would take care of MIME converting the message text
3326 * so that it is NUL-free. If it doesn't, then we have the choice of
3327 * either violating IMAP by sending NULs, corrupting the data, or going
3328 * to lots of work to do MIME conversion in the IMAP server.
3330 * No current stringstruct driver objects to having its buffer patched.
3331 * If this ever changes, it will be necessary to change this kludge.
3333 /* patch NULs to C1 control */
3334 for (j = 0; j < st->cursize; ++j)
3335 if (!st->curpos[j]) st->curpos[j] = 0x80;
3336 if (!net_sout (LOCAL->netstream,st->curpos,st->cursize)) {
3337 mail_unlock (stream);
3338 return imap_fake (stream,tag,"[CLOSED] IMAP connection broken (data)");
3340 i -= st->cursize; /* note that we wrote out this much */
3341 st->curpos += (st->cursize - 1);
3342 st->cursize = 0;
3344 (*st->dtb->next) (st); /* advance to next buffer's worth */
3346 return NIL; /* success */
3349 #define ADD_STRING(X, Y) { \
3350 if(remain > 0){ \
3351 sprintf (u, (X), (Y)); \
3352 len = strlen(u); \
3353 if(len < remain){ \
3354 remain -= len; \
3355 strncpy(t, u, strlen(u)); \
3356 t[strlen(u)] = '\0'; \
3357 t += strlen (t); \
3363 long imap_search_x_gm_ext1 (MAILSTREAM *stream, char *charset, SEARCHPGM *pgm, long flags)
3365 char *cmd = (flags & SE_UID) ? "UID SEARCH X-GM-RAW" : "SEARCH X-GM-RAW";
3366 char *t, s[MAILTMPLEN+1], u[MAILTMPLEN];
3367 IMAPARG *args[4],apgm;
3368 IMAPPARSEDREPLY *reply;
3369 unsigned long i,j,k;
3370 MESSAGECACHE *elt;
3371 size_t remain = sizeof(s) - 1, len;
3373 u[0] = s[0] = '\0';
3374 t = s;
3375 args[1] = args[2] = args[3] = NIL;
3377 if(pgm->x_gm_ext1)
3378 ADD_STRING(" %s", pgm->x_gm_ext1->text.data);
3380 #if 0 /* maybe later */
3381 if (pgm->larger)
3382 ADD_STRING(" larger:%lu", pgm->larger);
3384 if (pgm->smaller)
3385 ADD_STRING(" smaller:%lu", pgm->smaller);
3387 if (pgm->deleted)
3388 ADD_STRING(" %s", "in:trash");
3390 if (pgm->undeleted)
3391 ADD_STRING(" %s", "-in:trash");
3393 if (pgm->draft)
3394 ADD_STRING(" %s", "in:drafts");
3396 if (pgm->undraft)
3397 ADD_STRING(" %s", "-in:drafts");
3399 if (pgm->flagged)
3400 ADD_STRING(" %s", "is:starred");
3402 if (pgm->unflagged)
3403 ADD_STRING(" %s", "-is:starred");
3405 if (pgm->seen)
3406 ADD_STRING(" %s", "-is:unread");
3408 if (pgm->unseen)
3409 ADD_STRING(" %s", "is:unread");
3411 if (pgm->keyword){
3412 STRINGLIST *sl;
3413 for(sl = pgm->keyword; remain > 0 && sl; sl = sl->next)
3414 ADD_STRING(" label:%s", sl->text.data);
3417 if (pgm->unkeyword){
3418 STRINGLIST *sl;
3419 for(sl = pgm->unkeyword; remain > 0 && sl; sl = sl->next)
3420 ADD_STRING(" -label:%s", sl->text.data);
3423 if (pgm->sentbefore){
3424 unsigned short date = pgm->sentbefore;
3425 sprintf(v, "%d/%d/%d", BASEYEAR + (date >> 9),
3426 (date >> 5) & 0xf, date & 0x1f);
3427 ADD_STRING(" before:%s", v);
3430 if (pgm->sentsince){
3431 unsigned short date = pgm->sentsince;
3432 sprintf(v, "%d/%d/%d", BASEYEAR + (date >> 9),
3433 (date >> 5) & 0xf, date & 0x1f);
3434 ADD_STRING(" older:%s", v);
3437 if (pgm->before){
3438 unsigned short date = pgm->before;
3439 sprintf(v, "%d/%d/%d", BASEYEAR + (date >> 9),
3440 (date >> 5) & 0xf, date & 0x1f);
3441 ADD_STRING(" before:%s", v);
3444 if (pgm->since){
3445 unsigned short date = pgm->since;
3446 sprintf(v, "%d/%d/%d", BASEYEAR + (date >> 9),
3447 (date >> 5) & 0xf, date & 0x1f);
3448 ADD_STRING(" before:%s", v);
3451 if (pgm->older){
3452 sprintf(v, "%dd", pgm->older/86400);
3453 ADD_STRING(" older_than:%s", v);
3456 if (pgm->younger){
3457 sprintf(v, "%dd", pgm->younger/86400);
3458 ADD_STRING(" newer_than:%s", v);
3461 if(pgm->bcc){
3462 STRINGLIST *sl;
3463 ADD_STRING("%s", pgm->bcc->next ? " {" : " ");
3464 for(sl = pgm->bcc; remain > 0 && sl; sl = sl->next){
3465 ADD_STRING("bcc:%s", sl->text.data);
3466 ADD_STRING("%s", sl->next ? " " : "}");
3470 if(pgm->cc){
3471 STRINGLIST *sl;
3472 ADD_STRING("%s", pgm->cc->next ? " {" : " ");
3473 for(sl = pgm->cc; remain > 0 && sl; sl = sl->next){
3474 ADD_STRING("cc:%s", sl->text.data);
3475 ADD_STRING("%s", sl->next ? " " : "}");
3479 if(pgm->from){
3480 STRINGLIST *sl;
3481 ADD_STRING("%s", pgm->from->next ? " {" : " ");
3482 for(sl = pgm->from; remain > 0 && sl; sl = sl->next){
3483 ADD_STRING("from:%s", sl->text.data);
3484 ADD_STRING("%s", sl->next ? " " : (pgm->from->next ? "}" : ""));
3488 if(pgm->to){
3489 STRINGLIST *sl;
3490 ADD_STRING("%s", pgm->to->next ? " {" : " ");
3491 for(sl = pgm->to; remain > 0 && sl; sl = sl->next){
3492 ADD_STRING("to:%s", sl->text.data);
3493 ADD_STRING("%s", sl->next ? " " : (pgm->to->next ? "}" : ""));
3497 if(pgm->subject){
3498 STRINGLIST *sl;
3499 ADD_STRING("%s", pgm->subject->next ? " {" : " ");
3500 for(sl = pgm->subject; remain > 0 && sl; sl = sl->next){
3501 ADD_STRING("subject:(%s)", sl->text.data);
3502 ADD_STRING("%s", sl->next ? " " : (pgm->subject->next ? "}" : ""));
3506 if(pgm->body){
3507 STRINGLIST *sl;
3508 ADD_STRING("%s", pgm->body->next ? " {" : " ");
3509 for(sl = pgm->body; remain > 0 && sl; sl = sl->next){
3510 ADD_STRING(" %s", sl->text.data);
3511 ADD_STRING("%s", sl->next ? " " : (pgm->body->next ? "}" : ""));
3515 if (mail_valid_net_parse (stream->mailbox,&mb)){
3516 p = strchr(mb.mailbox, '/');
3517 ADD_STRING(" in:%s", p ? p+1 : "inbox");
3520 #endif /* maybe later */
3522 s[0] = '\"';
3523 strcat(t, "\"");
3525 apgm.type = ATOM; apgm.text = (void *) s;
3526 args[0] = &apgm;
3527 args[1] = NIL;
3528 LOCAL->uidsearch = (flags & SE_UID) ? T : NIL;
3529 reply = imap_send (stream,cmd,args);
3530 LOCAL->uidsearch = NIL;
3531 /* do locally if server won't grok */
3532 if (!strcmp (reply->key,"BAD")) {
3533 if ((flags & SE_NOLOCAL) ||
3534 !mail_search_default (stream,charset,pgm,flags | SE_NOSERVER))
3535 return NIL;
3537 else if (!imap_OK (stream,reply)) {
3538 mm_log (reply->text,ERROR);
3539 return NIL;
3542 /* can never pre-fetch with a short cache */
3543 if ((k = imap_prefetch) && !(flags & (SE_NOPREFETCH | SE_UID)) &&
3544 !stream->scache) { /* only if prefetching permitted */
3545 t = LOCAL->tmp; /* build sequence in temporary buffer */
3546 *t = '\0'; /* initially nothing */
3547 /* search through mailbox */
3548 for (i = 1; k && (i <= stream->nmsgs); ++i)
3549 /* for searched messages with no envelope */
3550 if ((elt = mail_elt (stream,i)) && elt->searched &&
3551 !mail_elt (stream,i)->private.msg.env) {
3552 /* prepend with comma if not first time */
3553 if (LOCAL->tmp[0]) *t++ = ',';
3554 sprintf (t,"%lu",j = i);/* output message number */
3555 t += strlen (t); /* point at end of string */
3556 k--; /* count one up */
3557 /* search for possible end of range */
3558 while (k && (i < stream->nmsgs) &&
3559 (elt = mail_elt (stream,i+1))->searched &&
3560 !elt->private.msg.env) i++,k--;
3561 if (i != j) { /* if a range */
3562 sprintf (t,":%lu",i); /* output delimiter and end of range */
3563 t += strlen (t); /* point at end of string */
3565 if ((t - LOCAL->tmp) > (IMAPTMPLEN - 50)) break;
3567 if (LOCAL->tmp[0]) { /* anything to pre-fetch? */
3568 /* pre-fetch envelopes for the first imap_prefetch number of messages */
3569 if (!imap_OK (stream,reply =
3570 imap_fetch (stream,t = cpystr (LOCAL->tmp),FT_NEEDENV +
3571 ((flags & SE_NOHDRS) ? FT_NOHDRS : NIL) +
3572 ((flags & SE_NEEDBODY) ? FT_NEEDBODY : NIL))))
3573 mm_log (reply->text,ERROR);
3574 fs_give ((void **) &t); /* flush copy of sequence */
3577 return LONGT;
3580 /* IMAP send search program
3581 * Accepts: MAIL stream
3582 * reply tag
3583 * base pointer if trimming needed
3584 * pointer to current position pointer of output bigbuf
3585 * search program to output
3586 * pointer to limit guideline
3587 * Returns: error reply or NIL if success
3591 IMAPPARSEDREPLY *imap_send_spgm (MAILSTREAM *stream,char *tag,char *base,
3592 char **s,SEARCHPGM *pgm,char *limit)
3594 IMAPPARSEDREPLY *reply;
3595 SEARCHHEADER *hdr;
3596 SEARCHOR *pgo;
3597 SEARCHPGMLIST *pgl;
3598 char *t;
3599 /* trim if called recursively */
3600 if (base) *s = imap_send_spgm_trim (base,*s,NIL);
3601 base = *s; /* this is the new base */
3602 /* default searchpgm */
3603 for (t = "ALL"; *t; *(*s)++ = *t++);
3604 if (!pgm) return NIL; /* done if NIL searchpgm */
3605 if ((pgm->msgno && /* message sequences */
3606 (pgm->msgno->next || /* trim away first:last */
3607 (pgm->msgno->first != 1) || (pgm->msgno->last != stream->nmsgs)) &&
3608 (reply = imap_send_sset (stream,tag,base,s,pgm->msgno," ",limit))) ||
3609 (pgm->uid &&
3610 (reply = imap_send_sset (stream,tag,base,s,pgm->uid," UID ",limit))))
3611 return reply;
3612 /* message sizes */
3613 if (pgm->larger) {
3614 sprintf (*s," LARGER %lu",pgm->larger);
3615 *s += strlen (*s);
3617 if (pgm->smaller) {
3618 sprintf (*s," SMALLER %lu",pgm->smaller);
3619 *s += strlen (*s);
3622 /* message flags */
3623 if (pgm->answered) for (t = " ANSWERED"; *t; *(*s)++ = *t++);
3624 if (pgm->unanswered) for (t =" UNANSWERED"; *t; *(*s)++ = *t++);
3625 if (pgm->deleted) for (t =" DELETED"; *t; *(*s)++ = *t++);
3626 if (pgm->undeleted) for (t =" UNDELETED"; *t; *(*s)++ = *t++);
3627 if (pgm->draft) for (t =" DRAFT"; *t; *(*s)++ = *t++);
3628 if (pgm->undraft) for (t =" UNDRAFT"; *t; *(*s)++ = *t++);
3629 if (pgm->flagged) for (t =" FLAGGED"; *t; *(*s)++ = *t++);
3630 if (pgm->unflagged) for (t =" UNFLAGGED"; *t; *(*s)++ = *t++);
3631 if (pgm->recent) for (t =" RECENT"; *t; *(*s)++ = *t++);
3632 if (pgm->old) for (t =" OLD"; *t; *(*s)++ = *t++);
3633 if (pgm->seen) for (t =" SEEN"; *t; *(*s)++ = *t++);
3634 if (pgm->unseen) for (t =" UNSEEN"; *t; *(*s)++ = *t++);
3635 if ((pgm->keyword && /* keywords */
3636 (reply = imap_send_slist (stream,tag,base,s," KEYWORD ",pgm->keyword,
3637 limit))) ||
3638 (pgm->unkeyword &&
3639 (reply = imap_send_slist (stream,tag,base,s," UNKEYWORD ",
3640 pgm->unkeyword,limit))))
3641 return reply;
3642 /* sent date ranges */
3643 if (pgm->sentbefore) imap_send_sdate (s,"SENTBEFORE",pgm->sentbefore);
3644 if (pgm->senton) imap_send_sdate (s,"SENTON",pgm->senton);
3645 if (pgm->sentsince) imap_send_sdate (s,"SENTSINCE",pgm->sentsince);
3646 /* internal date ranges */
3647 if (pgm->before) imap_send_sdate (s,"BEFORE",pgm->before);
3648 if (pgm->on) imap_send_sdate (s,"ON",pgm->on);
3649 if (pgm->since) imap_send_sdate (s,"SINCE",pgm->since);
3650 if (pgm->older) {
3651 sprintf (*s," OLDER %lu",pgm->older);
3652 *s += strlen (*s);
3654 if (pgm->younger) {
3655 sprintf (*s," YOUNGER %lu",pgm->younger);
3656 *s += strlen (*s);
3658 /* search texts */
3659 if ((pgm->bcc && (reply = imap_send_slist (stream,tag,base,s," BCC ",
3660 pgm->bcc,limit))) ||
3661 (pgm->cc && (reply = imap_send_slist (stream,tag,base,s," CC ",pgm->cc,
3662 limit))) ||
3663 (pgm->from && (reply = imap_send_slist (stream,tag,base,s," FROM ",
3664 pgm->from,limit))) ||
3665 (pgm->to && (reply = imap_send_slist (stream,tag,base,s," TO ",pgm->to,
3666 limit))))
3667 return reply;
3668 if ((pgm->subject && (reply = imap_send_slist (stream,tag,base,s," SUBJECT ",
3669 pgm->subject,limit))) ||
3670 (pgm->body && (reply = imap_send_slist (stream,tag,base,s," BODY ",
3671 pgm->body,limit))) ||
3672 (pgm->text && (reply = imap_send_slist (stream,tag,base,s," TEXT ",
3673 pgm->text,limit))))
3674 return reply;
3676 /* Note that these criteria are not supported by IMAP and have to be
3677 emulated */
3678 if ((pgm->return_path &&
3679 (reply = imap_send_slist (stream,tag,base,s," HEADER Return-Path ",
3680 pgm->return_path,limit))) ||
3681 (pgm->sender &&
3682 (reply = imap_send_slist (stream,tag,base,s," HEADER Sender ",
3683 pgm->sender,limit))) ||
3684 (pgm->reply_to &&
3685 (reply = imap_send_slist (stream,tag,base,s," HEADER Reply-To ",
3686 pgm->reply_to,limit))) ||
3687 (pgm->in_reply_to &&
3688 (reply = imap_send_slist (stream,tag,base,s," HEADER In-Reply-To ",
3689 pgm->in_reply_to,limit))) ||
3690 (pgm->message_id &&
3691 (reply = imap_send_slist (stream,tag,base,s," HEADER Message-ID ",
3692 pgm->message_id,limit))) ||
3693 (pgm->newsgroups &&
3694 (reply = imap_send_slist (stream,tag,base,s," HEADER Newsgroups ",
3695 pgm->newsgroups,limit))) ||
3696 (pgm->followup_to &&
3697 (reply = imap_send_slist (stream,tag,base,s," HEADER Followup-To ",
3698 pgm->followup_to,limit))) ||
3699 (pgm->references &&
3700 (reply = imap_send_slist (stream,tag,base,s," HEADER References ",
3701 pgm->references,limit)))) return reply;
3703 /* all other headers */
3704 if ((hdr = pgm->header) != NULL) do {
3705 *s = imap_send_spgm_trim (base,*s," HEADER ");
3706 if ((reply = imap_send_astring (stream,tag,s,&hdr->line,NIL,limit)) != NULL)
3707 return reply;
3708 *(*s)++ = ' ';
3709 if ((reply = imap_send_astring (stream,tag,s,&hdr->text,NIL,limit)) != NULL)
3710 return reply;
3711 } while ((hdr = hdr->next) != NULL);
3712 for (pgo = pgm->or; pgo; pgo = pgo->next) {
3713 *s = imap_send_spgm_trim (base,*s," OR (");
3714 if ((reply = imap_send_spgm (stream,tag,base,s,pgo->first,limit)) != NULL)
3715 return reply;
3716 for (t = ") ("; *t; *(*s)++ = *t++);
3717 if ((reply = imap_send_spgm (stream,tag,base,s,pgo->second,limit)) != NULL)
3718 return reply;
3719 *(*s)++ = ')';
3721 for (pgl = pgm->not; pgl; pgl = pgl->next) {
3722 *s = imap_send_spgm_trim (base,*s," NOT (");
3723 if ((reply = imap_send_spgm (stream,tag,base,s,pgl->pgm,limit)) != NULL)
3724 return reply;
3725 *(*s)++ = ')';
3727 /* trim if needed */
3728 *s = imap_send_spgm_trim (base,*s,NIL);
3729 return NIL; /* search program written OK */
3733 /* Write new text and trim extraneous "ALL" from searchpgm
3734 * Accepts: pointer to start of searchpgm or NIL
3735 * current end pointer
3736 * new text to write or NIL
3737 * Returns: new end pointer, trimmed if needed
3740 char *imap_send_spgm_trim (char *base,char *s,char *text)
3742 char *t;
3743 /* write new text */
3744 if (text) for (t = text; *t; *s++ = *t++);
3745 /* need to trim? */
3746 if (base && (s > (t = (base + 4))) && (*base == 'A') && (base[1] == 'L') &&
3747 (base[2] == 'L') && (base[3] == ' ')) {
3748 memmove (base,t,s - t); /* yes, blat down remaining text */
3749 s -= 4; /* and reduce current pointer */
3751 return s; /* return new end pointer */
3754 /* IMAP send search set
3755 * Accepts: MAIL stream
3756 * current command tag
3757 * base pointer if trimming needed
3758 * pointer to current position pointer of output bigbuf
3759 * search set to output
3760 * message prefix
3761 * maximum output pointer
3762 * Returns: NIL if success, error reply if error
3765 IMAPPARSEDREPLY *imap_send_sset (MAILSTREAM *stream,char *tag,char *base,
3766 char **s,SEARCHSET *set,char *prefix,
3767 char *limit)
3769 IMAPPARSEDREPLY *reply;
3770 STRING st;
3771 char c,*t;
3772 char *start = *s;
3773 /* trim and write prefix */
3774 *s = imap_send_spgm_trim (base,*s,prefix);
3775 /* run down search list */
3776 for (c = NIL; set && (*s < limit); set = set->next, c = ',') {
3777 if (c) *(*s)++ = c; /* write delimiter and first value */
3778 if (set->first == 0xffffffff) *(*s)++ = '*';
3779 else {
3780 sprintf (*s,"%lu",set->first);
3781 *s += strlen (*s);
3783 /* have a second value? */
3784 if (set->last && (set->first != set->last)) {
3785 *(*s)++ = ':'; /* write delimiter and second value */
3786 if (set->last == 0xffffffff) *(*s)++ = '*';
3787 else {
3788 sprintf (*s,"%lu",set->last);
3789 *s += strlen (*s);
3793 if (set) { /* insert "OR" in front of incomplete set */
3794 memmove (start + 3,start,*s - start);
3795 memcpy (start," OR",3);
3796 *s += 3; /* point to end of buffer */
3797 /* write glue that is equivalent to ALL */
3798 for (t =" ((OR BCC FOO NOT BCC "; *t; *(*s)++ = *t++);
3799 /* but broken by a literal */
3800 INIT (&st,mail_string,(void *) "FOO",3);
3801 if ((reply = imap_send_literal (stream,tag,s,&st)) != NULL) return reply;
3802 *(*s)++ = ')'; /* close glue */
3803 if ((reply = imap_send_sset (stream,tag,NIL,s,set,prefix,limit)) != NULL)
3804 return reply;
3805 *(*s)++ = ')'; /* close second OR argument */
3807 return NIL;
3810 /* IMAP send search list
3811 * Accepts: MAIL stream
3812 * reply tag
3813 * base pointer if trimming needed
3814 * pointer to current position pointer of output bigbuf
3815 * name of search list
3816 * search list to output
3817 * maximum output pointer
3818 * Returns: NIL if success, error reply if error
3821 IMAPPARSEDREPLY *imap_send_slist (MAILSTREAM *stream,char *tag,char *base,
3822 char **s,char *name,STRINGLIST *list,
3823 char *limit)
3825 IMAPPARSEDREPLY *reply;
3826 do {
3827 *s = imap_send_spgm_trim (base,*s,name);
3828 base = NIL; /* no longer need trimming */
3829 reply = imap_send_astring (stream,tag,s,&list->text,NIL,limit);
3831 while (!reply && (list = list->next));
3832 return reply;
3836 /* IMAP send search date
3837 * Accepts: pointer to current position pointer of output bigbuf
3838 * field name
3839 * search date to output
3842 void imap_send_sdate (char **s,char *name,unsigned short date)
3844 sprintf (*s," %s %d-%s-%d",name,date & 0x1f,
3845 months[((date >> 5) & 0xf) - 1],BASEYEAR + (date >> 9));
3846 *s += strlen (*s);
3849 /* IMAP send buffered command to sender
3850 * Accepts: MAIL stream
3851 * reply tag
3852 * string
3853 * pointer to string tail pointer
3854 * Returns: reply
3857 IMAPPARSEDREPLY *imap_sout (MAILSTREAM *stream,char *tag,char *base,char **s)
3859 IMAPPARSEDREPLY *reply;
3860 if (stream->debug) { /* output debugging telemetry */
3861 **s = '\0';
3862 mail_dlog (base,LOCAL->sensitive);
3864 *(*s)++ = '\015'; /* append CRLF */
3865 *(*s)++ = '\012';
3866 **s = '\0';
3867 reply = net_sout (LOCAL->netstream,base,*s - base) ?
3868 imap_reply (stream,tag) :
3869 imap_fake (stream,tag,"[CLOSED] IMAP connection broken (command)");
3870 *s = base; /* restart buffer */
3871 return reply;
3875 /* IMAP send null-terminated string to sender
3876 * Accepts: MAIL stream
3877 * string
3878 * Returns: T if success, else NIL
3881 long imap_soutr (MAILSTREAM *stream,char *string)
3883 long ret;
3884 unsigned long i;
3885 char *s;
3886 if (stream->debug) mm_dlog (string);
3887 sprintf (s = (char *) fs_get ((i = strlen (string) + 2) + 1),
3888 "%s\015\012",string);
3889 ret = net_sout (LOCAL->netstream,s,i);
3890 fs_give ((void **) &s);
3891 return ret;
3894 /* IMAP get reply
3895 * Accepts: MAIL stream
3896 * tag to search or NIL if want a greeting
3897 * Returns: parsed reply, never NIL
3900 IMAPPARSEDREPLY *imap_reply (MAILSTREAM *stream,char *tag)
3902 IMAPPARSEDREPLY *reply;
3903 while (LOCAL->netstream) { /* parse reply from server */
3904 if ((reply = imap_parse_reply (stream,net_getline (LOCAL->netstream))) != NULL) {
3905 /* continuation ready? */
3906 if (!strcmp (reply->tag,"+")) return reply;
3907 /* untagged data? */
3908 else if (!strcmp (reply->tag,"*")) {
3909 imap_parse_unsolicited (stream,reply);
3910 if (!tag) return reply; /* return if just wanted greeting */
3912 else { /* tagged data */
3913 if (tag && !compare_cstring (tag,reply->tag)) return reply;
3914 /* report bogon */
3915 sprintf (LOCAL->tmp,"Unexpected tagged response: %.80s %.80s %.80s",
3916 (char *) reply->tag,(char *) reply->key,(char *) reply->text);
3917 mm_notify (stream,LOCAL->tmp,WARN);
3918 stream->unhealthy = T;
3922 return imap_fake (stream,tag,
3923 "[CLOSED] IMAP connection broken (server response)");
3926 /* IMAP parse reply
3927 * Accepts: MAIL stream
3928 * text of reply
3929 * Returns: parsed reply, or NIL if can't parse at least a tag and key
3933 IMAPPARSEDREPLY *imap_parse_reply (MAILSTREAM *stream,char *text)
3935 char *r;
3936 if (LOCAL->reply.line) fs_give ((void **) &LOCAL->reply.line);
3937 /* init fields in case error */
3938 LOCAL->reply.key = LOCAL->reply.text = LOCAL->reply.tag = NIL;
3939 if (!(LOCAL->reply.line = text)) {
3940 /* NIL text means the stream died */
3941 if (LOCAL->netstream) net_close (LOCAL->netstream);
3942 LOCAL->netstream = NIL;
3943 return NIL;
3945 if (stream->debug) mm_dlog (LOCAL->reply.line);
3946 if (!(LOCAL->reply.tag = strtok_r (LOCAL->reply.line," ",&r))) {
3947 mm_notify (stream,"IMAP server sent a blank line",WARN);
3948 stream->unhealthy = T;
3949 return NIL;
3951 /* non-continuation replies */
3952 if (strcmp (LOCAL->reply.tag,"+")) {
3953 /* parse key */
3954 if (!(LOCAL->reply.key = strtok_r (NIL," ",&r))) {
3955 /* determine what is missing */
3956 sprintf (LOCAL->tmp,"Missing IMAP reply key: %.80s",
3957 (char *) LOCAL->reply.tag);
3958 mm_notify (stream,LOCAL->tmp,WARN);
3959 stream->unhealthy = T;
3960 return NIL; /* can't parse this text */
3962 ucase (LOCAL->reply.key); /* canonicalize key to upper */
3963 /* get text as well, allow empty text */
3964 if (!(LOCAL->reply.text = strtok_r (NIL,"\n",&r)))
3965 LOCAL->reply.text = LOCAL->reply.key + strlen (LOCAL->reply.key);
3967 else { /* special handling of continuation */
3968 LOCAL->reply.key = "BAD"; /* so it barfs if not expecting continuation */
3969 if (!(LOCAL->reply.text = strtok_r (NIL,"\n",&r)))
3970 LOCAL->reply.text = "";
3972 return &LOCAL->reply; /* return parsed reply */
3975 /* IMAP fake reply when stream determined to be dead
3976 * Accepts: MAIL stream
3977 * tag
3978 * text of fake reply (must start with "[CLOSED]")
3979 * Returns: parsed reply
3982 IMAPPARSEDREPLY *imap_fake (MAILSTREAM *stream,char *tag,char *text)
3984 mm_notify (stream,text,BYE); /* send bye alert */
3985 if (LOCAL->netstream) net_close (LOCAL->netstream);
3986 LOCAL->netstream = NIL; /* farewell, dear NET stream... */
3987 /* flush previous reply */
3988 if (LOCAL->reply.line) fs_give ((void **) &LOCAL->reply.line);
3989 /* build new fake reply */
3990 LOCAL->reply.tag = LOCAL->reply.line = cpystr (tag ? tag : "*");
3991 LOCAL->reply.key = "NO";
3992 LOCAL->reply.text = text;
3993 return &LOCAL->reply; /* return parsed reply */
3997 /* IMAP check for OK response in tagged reply
3998 * Accepts: MAIL stream
3999 * parsed reply
4000 * Returns: T if OK else NIL
4003 long imap_OK (MAILSTREAM *stream,IMAPPARSEDREPLY *reply)
4005 long ret = NIL;
4006 /* OK - operation succeeded */
4007 if (!strcmp (reply->key,"OK")) {
4008 imap_parse_response (stream,reply->text,NIL,NIL);
4009 ret = T;
4011 /* NO - operation failed */
4012 else if (!strcmp (reply->key,"NO"))
4013 imap_parse_response (stream,reply->text,WARN,NIL);
4014 else { /* BAD - operation rejected */
4015 if (!strcmp (reply->key,"BAD")) {
4016 imap_parse_response (stream,reply->text,ERROR,NIL);
4017 sprintf (LOCAL->tmp,"IMAP protocol error: %.80s",(char *) reply->text);
4019 /* bad protocol received */
4020 else sprintf (LOCAL->tmp,"Unexpected IMAP response: %.80s %.80s",
4021 (char *) reply->key,(char *) reply->text);
4022 mm_log (LOCAL->tmp,ERROR); /* either way, this is not good */
4024 return ret;
4027 /* IMAP parse and act upon unsolicited reply
4028 * Accepts: MAIL stream
4029 * parsed reply
4032 void imap_parse_unsolicited (MAILSTREAM *stream,IMAPPARSEDREPLY *reply)
4034 unsigned long i = 0;
4035 unsigned long j,msgno;
4036 unsigned char *s,*t;
4037 char *r;
4038 /* see if key is a number */
4039 if (isdigit (*reply->key)) {
4040 msgno = strtoul (reply->key,(char **) &s,10);
4041 if (*s) { /* better be nothing after number */
4042 sprintf (LOCAL->tmp,"Unexpected untagged message: %.80s",
4043 (char *) reply->key);
4044 mm_notify (stream,LOCAL->tmp,WARN);
4045 stream->unhealthy = T;
4046 return;
4048 if (!reply->text) { /* better be some data */
4049 mm_notify (stream,"Missing message data",WARN);
4050 stream->unhealthy = T;
4051 return;
4053 /* get message data type, canonicalize upper */
4054 s = ucase (strtok_r (reply->text," ",&r));
4055 t = strtok_r (NIL,"\n",&r); /* and locate the text after it */
4056 /* now take the action */
4057 /* change in size of mailbox */
4058 if (!strcmp (s,"EXISTS") && (msgno >= stream->nmsgs))
4059 mail_exists (stream,msgno);
4060 else if (!strcmp (s,"RECENT") && (msgno <= stream->nmsgs))
4061 mail_recent (stream,msgno);
4062 else if (!strcmp (s,"EXPUNGE") && msgno && (msgno <= stream->nmsgs)) {
4063 mailcache_t mc = (mailcache_t) mail_parameters (NIL,GET_CACHE,NIL);
4064 MESSAGECACHE *elt = (MESSAGECACHE *) (*mc) (stream,msgno,CH_ELT);
4065 if (elt) imap_gc_body (elt->private.msg.body);
4066 /* notify upper level */
4067 mail_expunged (stream,msgno);
4070 else if (t && (!strcmp (s,"FETCH") || !strcmp (s,"STORE")) &&
4071 msgno && (msgno <= stream->nmsgs)) {
4072 char *prop;
4073 GETS_DATA md;
4074 ENVELOPE **e;
4075 MESSAGECACHE *elt = mail_elt (stream,msgno);
4076 ENVELOPE *env = NIL;
4077 imapenvelope_t ie =
4078 (imapenvelope_t) mail_parameters (stream,GET_IMAPENVELOPE,NIL);
4079 ++t; /* skip past open parenthesis */
4080 /* parse Lisp-form property list */
4081 while ((prop = (strtok_r (t," )",&r))) && (t = strtok_r (NIL,"\n",&r))) {
4082 INIT_GETS (md,stream,elt->msgno,NIL,0,0);
4083 e = NIL; /* not pointing at any envelope yet */
4084 /* canonicalize property, parse it */
4085 if (!strcmp (ucase (prop),"FLAGS")) imap_parse_flags (stream,elt,&t);
4086 else if (!strcmp (prop,"INTERNALDATE") &&
4087 (s = imap_parse_string (stream,&t,reply,NIL,NIL,LONGT))) {
4088 if (!mail_parse_date (elt,s)) {
4089 sprintf (LOCAL->tmp,"Bogus date: %.80s",(char *) s);
4090 mm_notify (stream,LOCAL->tmp,WARN);
4091 stream->unhealthy = T;
4092 /* slam in default so we don't try again */
4093 mail_parse_date (elt,"01-Jan-1970 00:00:00 +0000");
4095 fs_give ((void **) &s);
4097 /* unique identifier */
4098 else if (!strcmp (prop,"UID")) {
4099 LOCAL->lastuid.uid = elt->private.uid = strtoul (t,(char **) &t,10);
4100 LOCAL->lastuid.msgno = elt->msgno;
4102 else if (!strcmp (prop,"ENVELOPE")) {
4103 if (stream->scache) { /* short cache, flush old stuff */
4104 mail_free_body (&stream->body);
4105 stream->msgno = elt->msgno;
4106 e = &stream->env; /* get pointer to envelope */
4108 else e = &elt->private.msg.env;
4109 imap_parse_envelope (stream,e,&t,reply);
4111 else if (!strncmp (prop,"BODY",4)) {
4112 if (!prop[4] || !strcmp (prop+4,"STRUCTURE")) {
4113 BODY **body;
4114 if (stream->scache){/* short cache, flush old stuff */
4115 if (stream->msgno != msgno) {
4116 mail_free_envelope (&stream->env);
4117 sprintf (LOCAL->tmp,"Body received for %lu but current is %lu",
4118 msgno,stream->msgno);
4119 stream->msgno = msgno;
4121 /* get pointer to body */
4122 body = &stream->body;
4124 else body = &elt->private.msg.body;
4125 /* flush any prior body */
4126 mail_free_body (body);
4127 /* instantiate and parse a new body */
4128 imap_parse_body_structure (stream,*body = mail_newbody(),&t,reply);
4131 else if (prop[4] == '[') {
4132 STRINGLIST *stl = NIL;
4133 SIZEDTEXT text;
4134 /* will want to return envelope data */
4135 if (!strcmp (md.what = cpystr (prop + 5),"HEADER]") ||
4136 !strcmp (md.what,"0]"))
4137 e = stream->scache ? &stream->env : &elt->private.msg.env;
4138 LOCAL->tmp[0] ='\0';/* no errors yet */
4139 /* found end of section? */
4140 if (!(s = strchr (md.what,']'))) {
4141 /* skip leading nesting */
4142 for (s = md.what; *s && (isdigit (*s) || (*s == '.')); s++);
4143 /* better be one of these */
4144 if (strncmp (s,"HEADER.FIELDS",13) &&
4145 (!s[13] || strcmp (s+13,".NOT")))
4146 sprintf (LOCAL->tmp,"Unterminated section: %.80s",md.what);
4147 /* get list of headers */
4148 else if (!(stl = imap_parse_stringlist (stream,&t,reply)))
4149 sprintf (LOCAL->tmp,"Bogus header field list: %.80s",
4150 (char *) t);
4151 else if (*t != ']')
4152 sprintf (LOCAL->tmp,"Unterminated header section: %.80s",
4153 (char *) t);
4154 /* point after the text */
4155 else if ((t = strchr (s = t,' ')) != NULL) *t++ = '\0';
4157 if (s && !LOCAL->tmp[0]) {
4158 *s++ = '\0'; /* tie off section specifier */
4159 if (*s == '<') { /* partial specifier? */
4160 md.first = strtoul (s+1,(char **) &s,10) + 1;
4161 if (*s++ != '>') /* make sure properly terminated */
4162 sprintf (LOCAL->tmp,"Unterminated partial data: %.80s",
4163 (char *) s-1);
4165 if (!LOCAL->tmp[0] && *s)
4166 sprintf (LOCAL->tmp,"Junk after section: %.80s",(char *) s);
4168 if (LOCAL->tmp[0]) { /* got any errors? */
4169 mm_notify (stream,LOCAL->tmp,WARN);
4170 stream->unhealthy = T;
4171 mail_free_stringlist (&stl);
4173 else { /* parse text from server */
4174 text.data = (unsigned char *)
4175 imap_parse_string (stream,&t,reply,
4176 ((md.what[0] && (md.what[0] != 'H')) ||
4177 md.first || md.last) ? &md : NIL,
4178 &text.size,NIL);
4179 /* all done if partial */
4180 if (md.first || md.last) mail_free_stringlist (&stl);
4181 /* otherwise register it in the cache */
4182 else imap_cache (stream,msgno,md.what,stl,&text);
4184 fs_give ((void **) &md.what);
4186 else {
4187 sprintf (LOCAL->tmp,"Unknown body message property: %.80s",prop);
4188 mm_notify (stream,LOCAL->tmp,WARN);
4189 stream->unhealthy = T;
4193 /* one of the RFC822 props? */
4194 else if (!strncmp (prop,"RFC822",6) && (!prop[6] || (prop[6] == '.'))){
4195 SIZEDTEXT text;
4196 if (!prop[6]) { /* cache full message */
4197 md.what = "";
4198 text.data = (unsigned char *)
4199 imap_parse_string (stream,&t,reply,&md,&text.size,NIL);
4200 imap_cache (stream,msgno,md.what,NIL,&text);
4202 else if (!strcmp (prop+7,"SIZE"))
4203 elt->rfc822_size = strtoul (t,(char **) &t,10);
4204 /* legacy properties */
4205 else if (!strcmp (prop+7,"HEADER")) {
4206 text.data = (unsigned char *)
4207 imap_parse_string (stream,&t,reply,NIL,&text.size,NIL);
4208 imap_cache (stream,msgno,"HEADER",NIL,&text);
4209 e = stream->scache ? &stream->env : &elt->private.msg.env;
4211 else if (!strcmp (prop+7,"TEXT")) {
4212 md.what = "TEXT";
4213 text.data = (unsigned char *)
4214 imap_parse_string (stream,&t,reply,&md,&text.size,NIL);
4215 imap_cache (stream,msgno,md.what,NIL,&text);
4217 else {
4218 sprintf (LOCAL->tmp,"Unknown RFC822 message property: %.80s",prop);
4219 mm_notify (stream,LOCAL->tmp,WARN);
4220 stream->unhealthy = T;
4223 else {
4224 sprintf (LOCAL->tmp,"Unknown message property: %.80s",prop);
4225 mm_notify (stream,LOCAL->tmp,WARN);
4226 stream->unhealthy = T;
4228 if (e && *e) env = *e; /* note envelope if we got one */
4230 if (prop) {
4231 sprintf (LOCAL->tmp,"Missing data for property: %.80s",prop);
4232 mm_notify (stream,LOCAL->tmp,WARN);
4233 stream->unhealthy = T;
4235 /* do callback if requested */
4236 if (ie && env) (*ie) (stream,msgno,env);
4238 /* obsolete response to COPY */
4239 else if (strcmp (s,"COPY")) {
4240 sprintf (LOCAL->tmp,"Unknown message data: %lu %.80s",msgno,(char *) s);
4241 mm_notify (stream,LOCAL->tmp,WARN);
4242 stream->unhealthy = T;
4246 else if (!strcmp (reply->key,"FLAGS") && reply->text &&
4247 (*reply->text == '(') &&
4248 (s = strtok_r (reply->text+1," )",&r)))
4249 do if (*s != '\\') {
4250 for (i = 0; (i < NUSERFLAGS) && stream->user_flags[i] &&
4251 compare_cstring (s,stream->user_flags[i]); i++);
4252 if (i > NUSERFLAGS) {
4253 sprintf (LOCAL->tmp,"Too many server flags, discarding: %.80s",
4254 (char *) s);
4255 mm_notify (stream,LOCAL->tmp,WARN);
4257 else if (!stream->user_flags[i]) stream->user_flags[i++] = cpystr (s);
4259 while ((s = strtok_r (NIL," )",&r)) != NULL);
4260 else if (!strcmp (reply->key,"SEARCH")) {
4261 /* only do something if have text */
4262 if (reply->text && (t = strtok_r (reply->text," ",&r))) do
4263 if ((i = strtoul (t,NIL,10)) != 0L) {
4264 /* UIDs always passed to main program */
4265 if (LOCAL->uidsearch) mm_searched (stream,i);
4266 /* should be a msgno then */
4267 else if ((i <= stream->nmsgs) &&
4268 (!LOCAL->filter || mail_elt (stream,i)->private.filter)) {
4269 mail_elt (stream,i)->searched = T;
4270 if (!stream->silent) mm_searched (stream,i);
4272 } while ((t = strtok_r (NIL," ",&r)) != NULL);
4274 else if (!strcmp (reply->key,"SORT")) {
4275 sortresults_t sr = (sortresults_t)
4276 mail_parameters (NIL,GET_SORTRESULTS,NIL);
4277 LOCAL->sortsize = 0; /* initialize sort data */
4278 if (LOCAL->sortdata) fs_give ((void **) &LOCAL->sortdata);
4279 LOCAL->sortdata = (unsigned long *)
4280 fs_get ((stream->nmsgs + 1) * sizeof (unsigned long));
4281 /* only do something if have text */
4282 if (reply->text && (t = strtok_r (reply->text," ",&r))) {
4283 do if ((i = atol (t)) && (LOCAL->filter ?
4284 mail_elt (stream,i)->searched : T))
4285 LOCAL->sortdata[LOCAL->sortsize++] = i;
4286 while ((t = strtok_r (NIL," ",&r)) && (LOCAL->sortsize < stream->nmsgs));
4288 LOCAL->sortdata[LOCAL->sortsize] = 0;
4289 /* also return via callback if requested */
4290 if (sr) (*sr) (stream,LOCAL->sortdata,LOCAL->sortsize);
4292 else if (!strcmp (reply->key,"THREAD")) {
4293 threadresults_t tr = (threadresults_t)
4294 mail_parameters (NIL,GET_THREADRESULTS,NIL);
4295 if (LOCAL->threaddata) mail_free_threadnode (&LOCAL->threaddata);
4296 if ((s = reply->text) != NULL) {
4297 LOCAL->threaddata = imap_parse_thread (stream,&s);
4298 if (tr) (*tr) (stream,LOCAL->threaddata);
4299 if (s && *s) {
4300 sprintf (LOCAL->tmp,"Junk at end of thread: %.80s",(char *) s);
4301 mm_notify (stream,LOCAL->tmp,WARN);
4302 stream->unhealthy = T;
4307 else if (!strcmp (reply->key,"STATUS") && reply->text) {
4308 MAILSTATUS status;
4309 unsigned char *txt = reply->text;
4310 if ((t = imap_parse_astring (stream,&txt,reply,&j)) && txt &&
4311 (*txt++ == ' ') && (*txt++ == '(') && (s = strchr (txt,')')) &&
4312 (s - txt)) {
4313 *s = '\0'; /* tie off status data */
4314 /* initialize data block */
4315 status.flags = status.messages = status.recent = status.unseen =
4316 status.uidnext = status.uidvalidity = 0;
4317 while (*txt && (s = strchr (txt,' '))) {
4318 *s++ = '\0'; /* tie off status attribute name */
4319 /* get attribute value */
4320 i = strtoul (s,(char **) &s,10);
4321 if (!compare_cstring (txt,"MESSAGES")) {
4322 status.flags |= SA_MESSAGES;
4323 status.messages = i;
4325 else if (!compare_cstring (txt,"RECENT")) {
4326 status.flags |= SA_RECENT;
4327 status.recent = i;
4329 else if (!compare_cstring (txt,"UNSEEN")) {
4330 status.flags |= SA_UNSEEN;
4331 status.unseen = i;
4333 else if (!compare_cstring (txt,"UIDNEXT")) {
4334 status.flags |= SA_UIDNEXT;
4335 status.uidnext = i;
4337 else if (!compare_cstring (txt,"UIDVALIDITY")) {
4338 status.flags |= SA_UIDVALIDITY;
4339 status.uidvalidity = i;
4341 /* next attribute */
4342 txt = (*s == ' ') ? s + 1 : s;
4344 if (((i = 1 + strchr (stream->mailbox,'}') - stream->mailbox) + j) <
4345 IMAPTMPLEN) {
4346 strcpy (strncpy (LOCAL->tmp,stream->mailbox,i) + i,t);
4347 /* pass status to main program */
4348 mm_status (stream,LOCAL->tmp,&status);
4351 if (t) fs_give ((void **) &t);
4354 else if ((!strcmp (reply->key,"LIST") || !strcmp (reply->key,"LSUB")) &&
4355 reply->text && (*reply->text == '(') &&
4356 (s = strchr (reply->text,')')) && (s[1] == ' ')) {
4357 char delimiter = '\0';
4358 *s++ = '\0'; /* tie off attribute list */
4359 /* parse attribute list */
4360 if ((t = strtok_r (reply->text+1," ",&r)) != NULL) do {
4361 if (!compare_cstring (t,"\\NoInferiors")) i |= LATT_NOINFERIORS;
4362 else if (!compare_cstring (t,"\\NoSelect")) i |= LATT_NOSELECT;
4363 else if (!compare_cstring (t,"\\Marked")) i |= LATT_MARKED;
4364 else if (!compare_cstring (t,"\\Unmarked")) i |= LATT_UNMARKED;
4365 else if (!compare_cstring (t,"\\HasChildren")) i |= LATT_HASCHILDREN;
4366 else if (!compare_cstring (t,"\\HasNoChildren")) i |= LATT_HASNOCHILDREN;
4367 else if (!compare_cstring (t,"\\All")) i |= LATT_ALL;
4368 else if (!compare_cstring (t,"\\Archive")) i |= LATT_ARCHIVE;
4369 else if (!compare_cstring (t,"\\Drafts")) i |= LATT_DRAFTS;
4370 else if (!compare_cstring (t,"\\Flagged")) i |= LATT_FLAGGED;
4371 else if (!compare_cstring (t,"\\Junk")) i |= LATT_JUNK;
4372 else if (!compare_cstring (t,"\\Sent")) i |= LATT_SENT;
4373 else if (!compare_cstring (t,"\\Trash")) i |= LATT_TRASH;
4374 /* ignore extension flags */
4376 while ((t = strtok_r (NIL," ",&r)) != NULL);
4377 switch (*++s) { /* process delimiter */
4378 case 'N': /* NIL */
4379 case 'n':
4380 s += 4; /* skip over NIL<space> */
4381 break;
4382 case '"': /* have a delimiter */
4383 delimiter = (*++s == '\\') ? *++s : *s;
4384 s += 3; /* skip over <delimiter><quote><space> */
4386 /* parse the mailbox name */
4387 if ((t = imap_parse_astring (stream,&s,reply,&j)) != NULL) {
4388 /* prepend prefix if requested */
4389 if (LOCAL->prefix && ((strlen (LOCAL->prefix) + j) < IMAPTMPLEN))
4390 sprintf (s = LOCAL->tmp,"%s%s",LOCAL->prefix,(char *) t);
4391 else s = t; /* otherwise just mailbox name */
4392 /* pass data to main program */
4393 if (reply->key[1] == 'S') mm_lsub (stream,delimiter,s,i);
4394 else mm_list (stream,delimiter,s,i);
4395 fs_give ((void **) &t); /* flush mailbox name */
4398 else if (!strcmp (reply->key,"NAMESPACE")) {
4399 if (LOCAL->namespace) {
4400 mail_free_namespace (&LOCAL->namespace[0]);
4401 mail_free_namespace (&LOCAL->namespace[1]);
4402 mail_free_namespace (&LOCAL->namespace[2]);
4404 else LOCAL->namespace = (NAMESPACE **) fs_get (3 * sizeof (NAMESPACE *));
4405 if ((s = reply->text) != NULL) { /* parse namespace results */
4406 LOCAL->namespace[0] = imap_parse_namespace (stream,&s,reply);
4407 LOCAL->namespace[1] = imap_parse_namespace (stream,&s,reply);
4408 LOCAL->namespace[2] = imap_parse_namespace (stream,&s,reply);
4409 if (s && *s) {
4410 sprintf (LOCAL->tmp,"Junk after namespace list: %.80s",(char *) s);
4411 mm_notify (stream,LOCAL->tmp,WARN);
4412 stream->unhealthy = T;
4415 else {
4416 mm_notify (stream,"Missing namespace list",WARN);
4417 stream->unhealthy = T;
4421 else if (!strcmp (reply->key,"ACL") && (s = reply->text) &&
4422 (t = imap_parse_astring (stream,&s,reply,NIL))) {
4423 getacl_t ar = (getacl_t) mail_parameters (NIL,GET_ACL,NIL);
4424 if (s && (*s++ == ' ')) {
4425 ACLLIST *al = mail_newacllist ();
4426 ACLLIST *ac = al;
4427 do if ((ac->identifier = imap_parse_astring (stream,&s,reply,NIL)) &&
4428 s && (*s++ == ' '))
4429 ac->rights = imap_parse_astring (stream,&s,reply,NIL);
4430 while (ac->rights && s && (*s == ' ') && s++ &&
4431 (ac = ac->next = mail_newacllist ()));
4432 if (!ac->rights || (s && *s)) {
4433 sprintf (LOCAL->tmp,"Invalid ACL identifer/rights for %.80s",
4434 (char *) t);
4435 mm_notify (stream,LOCAL->tmp,WARN);
4436 stream->unhealthy = T;
4438 else if (ar) (*ar) (stream,t,al);
4439 mail_free_acllist (&al); /* clean up */
4441 /* no optional rights */
4442 else if (ar) (*ar) (stream,t,NIL);
4443 fs_give ((void **) &t); /* free mailbox name */
4446 else if (!strcmp (reply->key,"LISTRIGHTS") && (s = reply->text) &&
4447 (t = imap_parse_astring (stream,&s,reply,NIL))) {
4448 listrights_t lr = (listrights_t) mail_parameters (NIL,GET_LISTRIGHTS,NIL);
4449 char *id,*r;
4450 if (s && (*s++ == ' ') && (id = imap_parse_astring (stream,&s,reply,NIL))){
4451 if (s && (*s++ == ' ') &&
4452 (r = imap_parse_astring (stream,&s,reply,NIL))) {
4453 if (s && (*s++ == ' ')) {
4454 STRINGLIST *rl = mail_newstringlist ();
4455 STRINGLIST *rc = rl;
4456 do rc->text.data = (unsigned char *)
4457 imap_parse_astring (stream,&s,reply,&rc->text.size);
4458 while (rc->text.data && s && (*s == ' ') && s++ &&
4459 (rc = rc->next = mail_newstringlist ()));
4460 if (!rc->text.data || (s && *s)) {
4461 sprintf (LOCAL->tmp,"Invalid optional LISTRIGHTS for %.80s",
4462 (char *) t);
4463 mm_notify (stream,LOCAL->tmp,WARN);
4464 stream->unhealthy = T;
4466 else if (lr) (*lr) (stream,t,id,r,rl);
4467 /* clean up */
4468 mail_free_stringlist (&rl);
4470 /* no optional rights */
4471 else if (lr) (*lr) (stream,t,id,r,NIL);
4472 fs_give ((void **) &r); /* free rights */
4474 else {
4475 sprintf (LOCAL->tmp,"Missing LISTRIGHTS rights for %.80s",(char *) t);
4476 mm_notify (stream,LOCAL->tmp,WARN);
4477 stream->unhealthy = T;
4479 fs_give ((void **) &id); /* free identifier */
4481 else {
4482 sprintf (LOCAL->tmp,"Missing LISTRIGHTS identifer for %.80s",(char *) t);
4483 mm_notify (stream,LOCAL->tmp,WARN);
4484 stream->unhealthy = T;
4486 fs_give ((void **) &t); /* free mailbox name */
4489 else if (!strcmp (reply->key,"MYRIGHTS") && (s = reply->text) &&
4490 (t = imap_parse_astring (stream,&s,reply,NIL))) {
4491 myrights_t mr = (myrights_t) mail_parameters (NIL,GET_MYRIGHTS,NIL);
4492 char *r;
4493 if (s && (*s++ == ' ') && (r = imap_parse_astring (stream,&s,reply,NIL))) {
4494 if (s && *s) {
4495 sprintf (LOCAL->tmp,"Junk after MYRIGHTS for %.80s",(char *) t);
4496 mm_notify (stream,LOCAL->tmp,WARN);
4497 stream->unhealthy = T;
4499 else if (mr) (*mr) (stream,t,r);
4500 fs_give ((void **) &r); /* free rights */
4502 else {
4503 sprintf (LOCAL->tmp,"Missing MYRIGHTS for %.80s",(char *) t);
4504 mm_notify (stream,LOCAL->tmp,WARN);
4505 stream->unhealthy = T;
4507 fs_give ((void **) &t); /* free mailbox name */
4510 /* this response has a bizarre syntax! */
4511 else if (!strcmp (reply->key,"QUOTA") && (s = reply->text) &&
4512 (t = imap_parse_astring (stream,&s,reply,NIL))) {
4513 /* in case error */
4514 sprintf (LOCAL->tmp,"Bad quota resource list for %.80s",(char *) t);
4515 if (s && (*s++ == ' ') && (*s++ == '(') && *s && ((*s != ')') || !s[1])) {
4516 quota_t qt = (quota_t) mail_parameters (NIL,GET_QUOTA,NIL);
4517 QUOTALIST *ql = NIL;
4518 QUOTALIST *qc;
4519 /* parse non-empty quota resource list */
4520 if (*s != ')') for (ql = qc = mail_newquotalist (); T;
4521 qc = qc->next = mail_newquotalist ()) {
4522 if ((qc->name = imap_parse_astring (stream,&s,reply,NIL)) && s &&
4523 (*s++ == ' ') && (isdigit (*s) || (LOCAL->loser && (*s == '-')))) {
4524 if (isdigit (*s)) qc->usage = strtoul (s,(char **) &s,10);
4525 else if ((t = strchr (s,' ')) != NULL) t = s;
4526 if ((*s++ == ' ') && (isdigit (*s) || (LOCAL->loser &&(*s == '-')))){
4527 if (isdigit (*s)) qc->limit = strtoul (s,(char **) &s,10);
4528 else if ((t = strpbrk (s," )")) != NULL) t = s;
4529 /* another resource follows? */
4530 if (*s == ' ') continue;
4531 /* end of resource list? */
4532 if ((*s == ')') && !s[1]) {
4533 if (qt) (*qt) (stream,t,ql);
4534 break; /* all done */
4538 /* something bad happened */
4539 mm_notify (stream,LOCAL->tmp,WARN);
4540 stream->unhealthy = T;
4541 break; /* parse failed */
4543 /* all done with quota resource list now */
4544 if (ql) mail_free_quotalist (&ql);
4546 else {
4547 mm_notify (stream,LOCAL->tmp,WARN);
4548 stream->unhealthy = T;
4550 fs_give ((void **) &t); /* free root name */
4552 else if (!strcmp (reply->key,"ID") && (s = reply->text)){
4553 if(compare_cstring (s,"NIL")) LOCAL->id = imap_parse_idlist(s);
4555 else if (!strcmp (reply->key,"QUOTAROOT") && (s = reply->text) &&
4556 (t = imap_parse_astring (stream,&s,reply,NIL))) {
4557 sprintf (LOCAL->tmp,"Bad quota root list for %.80s",(char *) t);
4558 if (s && (*s++ == ' ')) {
4559 quotaroot_t qr = (quotaroot_t) mail_parameters (NIL,GET_QUOTAROOT,NIL);
4560 STRINGLIST *rl = mail_newstringlist ();
4561 STRINGLIST *rc = rl;
4562 do rc->text.data = (unsigned char *)
4563 imap_parse_astring (stream,&s,reply,&rc->text.size);
4564 while (rc->text.data && *s && (*s++ == ' ') &&
4565 (rc = rc->next = mail_newstringlist ()));
4566 if (!rc->text.data || (s && *s)) {
4567 mm_notify (stream,LOCAL->tmp,WARN);
4568 stream->unhealthy = T;
4570 else if (qr) (*qr) (stream,t,rl);
4571 /* clean up */
4572 mail_free_stringlist (&rl);
4574 else {
4575 mm_notify (stream,LOCAL->tmp,WARN);
4576 stream->unhealthy = T;
4578 fs_give ((void **) &t);
4581 else if (!strcmp (reply->key,"OK") || !strcmp (reply->key,"PREAUTH"))
4582 imap_parse_response (stream,reply->text,NIL,T);
4583 else if (!strcmp (reply->key,"NO"))
4584 imap_parse_response (stream,reply->text,WARN,T);
4585 else if (!strcmp (reply->key,"BAD"))
4586 imap_parse_response (stream,reply->text,ERROR,T);
4587 else if (!strcmp (reply->key,"BYE")) {
4588 LOCAL->byeseen = T; /* note that a BYE seen */
4589 imap_parse_response (stream,reply->text,BYE,T);
4591 else if (!strcmp (reply->key,"CAPABILITY") && reply->text)
4592 imap_parse_capabilities (stream,reply->text);
4593 else if (!strcmp (reply->key,"MAILBOX") && reply->text) {
4594 if (LOCAL->prefix &&
4595 ((strlen (LOCAL->prefix) + strlen (reply->text)) < IMAPTMPLEN))
4596 sprintf (t = LOCAL->tmp,"%s%s",LOCAL->prefix,(char *) reply->text);
4597 else t = reply->text;
4598 mm_list (stream,NIL,t,NIL);
4600 else {
4601 sprintf (LOCAL->tmp,"Unexpected untagged message: %.80s",
4602 (char *) reply->key);
4603 mm_notify (stream,LOCAL->tmp,WARN);
4604 stream->unhealthy = T;
4608 /* Parse human-readable response text
4609 * Accepts: mail stream
4610 * text
4611 * error level for mm_notify()
4612 * non-NIL if want mm_notify() event even if no response code
4615 void imap_parse_response (MAILSTREAM *stream,char *text,long errflg,long ntfy)
4617 char *s,*t,*r;
4618 size_t i;
4619 unsigned long j;
4620 MESSAGECACHE *elt;
4621 copyuid_t cu;
4622 appenduid_t au;
4623 SEARCHSET *source = NIL;
4624 SEARCHSET *dest = NIL;
4625 if (text && (*text == '[') && (t = strchr (s = text + 1,']')) &&
4626 ((i = t - s) < IMAPTMPLEN)) {
4627 LOCAL->tmp[i] = '\0'; /* make mungable copy of text code */
4628 if ((s = strchr (strncpy (t = LOCAL->tmp,s,i),' ')) != NULL) *s++ = '\0';
4629 if (s) { /* have argument? */
4630 ntfy = NIL; /* suppress mm_notify if normal SELECT data */
4631 if (!compare_cstring (t,"CAPABILITY")) imap_parse_capabilities(stream,s);
4632 else if (!compare_cstring (t,"PERMANENTFLAGS") && (*s == '(') &&
4633 (t[i-1] == ')')) {
4634 t[i-1] = '\0'; /* tie off flags */
4635 stream->perm_seen = stream->perm_deleted = stream->perm_answered =
4636 stream->perm_draft = stream->kwd_create = NIL;
4637 stream->perm_user_flags = NIL;
4638 if ((s = strtok_r (s+1," ",&r)) != NULL) do {
4639 if (*s == '\\') { /* system flags */
4640 if (!compare_cstring (s,"\\Seen")) stream->perm_seen = T;
4641 else if (!compare_cstring (s,"\\Deleted"))
4642 stream->perm_deleted = T;
4643 else if (!compare_cstring (s,"\\Flagged"))
4644 stream->perm_flagged = T;
4645 else if (!compare_cstring (s,"\\Answered"))
4646 stream->perm_answered = T;
4647 else if (!compare_cstring (s,"\\Draft")) stream->perm_draft = T;
4648 else if (!strcmp (s,"\\*")) stream->kwd_create = T;
4650 else stream->perm_user_flags |= imap_parse_user_flag (stream,s);
4652 while ((s = strtok_r (NIL," ",&r)) != NULL);
4655 else if (!compare_cstring (t,"UIDVALIDITY") && (j = strtoul (s,NIL,10))){
4656 /* do this in separate if because of ntfy */
4657 if (j != stream->uid_validity) {
4658 mailcache_t mc = (mailcache_t) mail_parameters (NIL,GET_CACHE,NIL);
4659 stream->uid_validity = j;
4660 /* purge any UIDs in cache */
4661 for (j = 1; j <= stream->nmsgs; j++)
4662 if ((elt = (MESSAGECACHE *) (*mc) (stream,j,CH_ELT)) != NULL)
4663 elt->private.uid = 0;
4666 else if (!compare_cstring (t,"UIDNEXT"))
4667 stream->uid_last = strtoul (s,NIL,10) - 1;
4668 else if ((j = LEVELUIDPLUS (stream) && LOCAL->appendmailbox) &&
4669 !compare_cstring (t,"COPYUID") &&
4670 (cu = (copyuid_t) mail_parameters (NIL,GET_COPYUID,NIL)) &&
4671 isdigit (*s) && (j = strtoul (s,&s,10)) && (*s++ == ' ') &&
4672 (source = mail_parse_set (s,&s)) && (*s++ == ' ') &&
4673 (dest = mail_parse_set (s,&s)) && !*s)
4674 (*cu) (stream,LOCAL->appendmailbox,j,source,dest);
4675 else if (j && !compare_cstring (t,"APPENDUID") &&
4676 (au = (appenduid_t) mail_parameters (NIL,GET_APPENDUID,NIL)) &&
4677 isdigit (*s) && (j = strtoul (s,&s,10)) && (*s++ == ' ') &&
4678 (dest = mail_parse_set (s,&s)) && !*s)
4679 (*au) (LOCAL->appendmailbox,j,dest);
4680 else { /* all other response code events */
4681 ntfy = T; /* must mm_notify() */
4682 if (!compare_cstring (t,"REFERRAL"))
4683 LOCAL->referral = cpystr (t + 9);
4685 mail_free_searchset (&source);
4686 mail_free_searchset (&dest);
4688 else { /* no arguments */
4689 if (!compare_cstring (t,"UIDNOTSTICKY")) {
4690 ntfy = NIL;
4691 stream->uid_nosticky = T;
4693 else if (!compare_cstring (t,"READ-ONLY")) stream->rdonly = T;
4694 else if (!compare_cstring (t,"READ-WRITE"))
4695 stream->rdonly = NIL;
4696 else if (!compare_cstring (t,"PARSE") && !errflg)
4697 errflg = PARSE;
4700 /* give event to main program */
4701 if (ntfy && !stream->silent) mm_notify (stream,text ? text : "",errflg);
4704 /* Parse a namespace
4705 * Accepts: mail stream
4706 * current text pointer
4707 * parsed reply
4708 * Returns: namespace list, text pointer updated
4711 NAMESPACE *imap_parse_namespace (MAILSTREAM *stream,unsigned char **txtptr,
4712 IMAPPARSEDREPLY *reply)
4714 NAMESPACE *ret = NIL;
4715 NAMESPACE *nam = NIL;
4716 NAMESPACE *prev = NIL;
4717 PARAMETER *par = NIL;
4718 if (*txtptr) { /* only if argument given */
4719 /* ignore leading space */
4720 while (**txtptr == ' ') ++*txtptr;
4721 switch (**txtptr) {
4722 case 'N': /* if NIL */
4723 case 'n':
4724 ++*txtptr; /* bump past "N" */
4725 ++*txtptr; /* bump past "I" */
4726 ++*txtptr; /* bump past "L" */
4727 break;
4728 case '(':
4729 ++*txtptr; /* skip past open paren */
4730 while (**txtptr == '(') {
4731 ++*txtptr; /* skip past open paren */
4732 prev = nam; /* note previous if any */
4733 nam = (NAMESPACE *) memset (fs_get (sizeof (NAMESPACE)),0,
4734 sizeof (NAMESPACE));
4735 if (!ret) ret = nam; /* if first time note first namespace */
4736 /* if previous link new block to it */
4737 if (prev) prev->next = nam;
4738 nam->name = imap_parse_string (stream,txtptr,reply,NIL,NIL,NIL);
4739 /* ignore whitespace */
4740 while (**txtptr == ' ') ++*txtptr;
4741 switch (**txtptr) { /* parse delimiter */
4742 case 'N':
4743 case 'n':
4744 *txtptr += 3; /* bump past "NIL" */
4745 break;
4746 case '"':
4747 if (*++*txtptr == '\\') nam->delimiter = *++*txtptr;
4748 else nam->delimiter = **txtptr;
4749 *txtptr += 2; /* bump past character and closing quote */
4750 break;
4751 default:
4752 sprintf (LOCAL->tmp,"Missing delimiter in namespace: %.80s",
4753 (char *) *txtptr);
4754 mm_notify (stream,LOCAL->tmp,WARN);
4755 stream->unhealthy = T;
4756 *txtptr = NIL; /* stop parse */
4757 return ret;
4760 while (**txtptr == ' '){/* append new parameter to tail */
4761 if (nam->param) par = par->next = mail_newbody_parameter ();
4762 else nam->param = par = mail_newbody_parameter ();
4763 if (!(par->attribute = imap_parse_string (stream,txtptr,reply,NIL,
4764 NIL,NIL))) {
4765 mm_notify (stream,"Missing namespace extension attribute",WARN);
4766 stream->unhealthy = T;
4767 par->attribute = cpystr ("UNKNOWN");
4769 /* skip space */
4770 while (**txtptr == ' ') ++*txtptr;
4771 if (**txtptr == '(') {/* have value list? */
4772 char *att = par->attribute;
4773 ++*txtptr; /* yes */
4774 do { /* parse each value */
4775 if (!(par->value = imap_parse_string (stream,txtptr,reply,NIL,
4776 NIL,LONGT))) {
4777 sprintf (LOCAL->tmp,
4778 "Missing value for namespace attribute %.80s",att);
4779 mm_notify (stream,LOCAL->tmp,WARN);
4780 stream->unhealthy = T;
4781 par->value = cpystr ("UNKNOWN");
4783 /* is there another value? */
4784 if (**txtptr == ' ') par = par->next = mail_newbody_parameter ();
4785 } while (!par->value);
4787 else {
4788 sprintf (LOCAL->tmp,"Missing values for namespace attribute %.80s",
4789 par->attribute);
4790 mm_notify (stream,LOCAL->tmp,WARN);
4791 stream->unhealthy = T;
4792 par->value = cpystr ("UNKNOWN");
4795 if (**txtptr == ')') ++*txtptr;
4796 else { /* missing trailing paren */
4797 sprintf (LOCAL->tmp,"Junk at end of namespace: %.80s",
4798 (char *) *txtptr);
4799 mm_notify (stream,LOCAL->tmp,WARN);
4800 stream->unhealthy = T;
4801 return ret;
4804 if (**txtptr == ')') { /* expected trailing paren? */
4805 ++*txtptr; /* got it! */
4806 break;
4808 default:
4809 sprintf (LOCAL->tmp,"Not a namespace: %.80s",(char *) *txtptr);
4810 mm_notify (stream,LOCAL->tmp,WARN);
4811 stream->unhealthy = T;
4812 *txtptr = NIL; /* stop parse now */
4813 break;
4816 return ret;
4819 /* Parse a thread node list
4820 * Accepts: mail stream
4821 * current text pointer
4822 * Returns: thread node list, text pointer updated
4825 THREADNODE *imap_parse_thread (MAILSTREAM *stream,unsigned char **txtptr)
4827 char *s;
4828 THREADNODE *ret = NIL; /* returned tree */
4829 THREADNODE *last = NIL; /* last branch in this tree */
4830 THREADNODE *parent = NIL; /* parent of current node */
4831 THREADNODE *cur; /* current node */
4832 while (**txtptr == '(') { /* see a thread? */
4833 ++*txtptr; /* skip past open paren */
4834 while (**txtptr != ')') { /* parse thread */
4835 if (**txtptr == '(') { /* thread branch */
4836 cur = imap_parse_thread (stream,txtptr);
4837 /* add to parent */
4838 if (parent) parent = parent->next = cur;
4839 else { /* no parent, create dummy */
4840 if (last) last = last->branch = mail_newthreadnode (NIL);
4841 /* new tree */
4842 else ret = last = mail_newthreadnode (NIL);
4843 /* add to dummy parent */
4844 last->next = parent = cur;
4847 /* threaded message number */
4848 else if (isdigit (*(s = *txtptr)) &&
4849 ((cur = mail_newthreadnode (NIL))->num =
4850 strtoul (*txtptr,(char **) txtptr,10))) {
4851 if (LOCAL->filter && !mail_elt (stream,cur->num)->searched)
4852 cur->num = NIL; /* make dummy if filtering and not searched */
4853 /* add to parent */
4854 if (parent) parent = parent->next = cur;
4855 /* no parent, start new thread */
4856 else if (last) last = last->branch = parent = cur;
4857 /* create new tree */
4858 else ret = last = parent = cur;
4860 else { /* anything else is a bogon */
4861 char tmp[MAILTMPLEN];
4862 sprintf (tmp,"Bogus thread member: %.80s",s);
4863 mm_notify (stream,tmp,WARN);
4864 stream->unhealthy = T;
4865 return ret;
4867 /* skip past any space */
4868 if (**txtptr == ' ') ++*txtptr;
4870 ++*txtptr; /* skip pase end of thread */
4871 parent = NIL; /* close this thread */
4873 return ret; /* return parsed thread */
4876 /* Parse RFC822 message header
4877 * Accepts: MAIL stream
4878 * envelope to parse into
4879 * header as sized text
4880 * stringlist if partial header
4883 void imap_parse_header (MAILSTREAM *stream,ENVELOPE **env,SIZEDTEXT *hdr,
4884 STRINGLIST *stl)
4886 ENVELOPE *nenv;
4887 /* parse what we can from this header */
4888 rfc822_parse_msg (&nenv,NIL,(char *) hdr->data,hdr->size,NIL,
4889 net_host (LOCAL->netstream),stream->dtb->flags);
4890 if (*env) { /* need to merge this header into envelope? */
4891 if (!(*env)->newsgroups) { /* need Newsgroups? */
4892 (*env)->newsgroups = nenv->newsgroups;
4893 (*env)->ngpathexists = nenv->ngpathexists;
4894 nenv->newsgroups = NIL;
4896 if (!(*env)->followup_to) { /* need Followup-To? */
4897 (*env)->followup_to = nenv->followup_to;
4898 nenv->followup_to = NIL;
4900 if (!(*env)->references) { /* need References? */
4901 (*env)->references = nenv->references;
4902 nenv->references = NIL;
4904 if (!(*env)->sparep) { /* need spare pointer? */
4905 (*env)->sparep = nenv->sparep;
4906 nenv->sparep = NIL;
4908 mail_free_envelope (&nenv);
4909 (*env)->imapenvonly = NIL; /* have complete envelope now */
4911 /* otherwise set it to this envelope */
4912 else (*env = nenv)->incomplete = stl ? T : NIL;
4915 /* IMAP parse envelope
4916 * Accepts: MAIL stream
4917 * pointer to envelope pointer
4918 * current text pointer
4919 * parsed reply
4921 * Updates text pointer
4924 void imap_parse_envelope (MAILSTREAM *stream,ENVELOPE **env,
4925 unsigned char **txtptr,IMAPPARSEDREPLY *reply)
4927 ENVELOPE *oenv = *env;
4928 char c = **txtptr; /* grab first character */
4929 /* ignore leading spaces */
4930 while (c == ' ') c = *++*txtptr;
4931 if (c) ++*txtptr; /* skip past first character */
4932 switch (c) { /* dispatch on first character */
4933 case '(': /* if envelope S-expression */
4934 *env = mail_newenvelope (); /* parse the new envelope */
4935 (*env)->date = imap_parse_string (stream,txtptr,reply,NIL,NIL,LONGT);
4936 (*env)->subject = imap_parse_string (stream,txtptr,reply,NIL,NIL,LONGT);
4937 (*env)->from = imap_parse_adrlist (stream,txtptr,reply);
4938 (*env)->sender = imap_parse_adrlist (stream,txtptr,reply);
4939 (*env)->reply_to = imap_parse_adrlist (stream,txtptr,reply);
4940 (*env)->to = imap_parse_adrlist (stream,txtptr,reply);
4941 (*env)->cc = imap_parse_adrlist (stream,txtptr,reply);
4942 (*env)->bcc = imap_parse_adrlist (stream,txtptr,reply);
4943 (*env)->in_reply_to = imap_parse_string (stream,txtptr,reply,NIL,NIL,
4944 LONGT);
4945 (*env)->message_id = imap_parse_string (stream,txtptr,reply,NIL,NIL,LONGT);
4946 if (oenv) { /* need to merge old envelope? */
4947 (*env)->newsgroups = oenv->newsgroups;
4948 oenv->newsgroups = NIL;
4949 (*env)->ngpathexists = oenv->ngpathexists;
4950 (*env)->followup_to = oenv->followup_to;
4951 oenv->followup_to = NIL;
4952 (*env)->references = oenv->references;
4953 oenv->references = NIL;
4954 mail_free_envelope(&oenv);/* free old envelope */
4956 /* have IMAP envelope components only */
4957 else (*env)->imapenvonly = T;
4958 if (**txtptr != ')') {
4959 sprintf (LOCAL->tmp,"Junk at end of envelope: %.80s",(char *) *txtptr);
4960 mm_notify (stream,LOCAL->tmp,WARN);
4961 stream->unhealthy = T;
4963 else ++*txtptr; /* skip past delimiter */
4964 break;
4965 case 'N': /* if NIL */
4966 case 'n':
4967 ++*txtptr; /* bump past "I" */
4968 ++*txtptr; /* bump past "L" */
4969 break;
4970 default:
4971 sprintf (LOCAL->tmp,"Not an envelope: %.80s",(char *) *txtptr);
4972 mm_notify (stream,LOCAL->tmp,WARN);
4973 stream->unhealthy = T;
4974 break;
4978 /* IMAP parse address list
4979 * Accepts: MAIL stream
4980 * current text pointer
4981 * parsed reply
4982 * Returns: address list, NIL on failure
4984 * Updates text pointer
4987 ADDRESS *imap_parse_adrlist (MAILSTREAM *stream,unsigned char **txtptr,
4988 IMAPPARSEDREPLY *reply)
4990 ADDRESS *adr = NIL;
4991 char c = **txtptr; /* sniff at first character */
4992 /* ignore leading spaces */
4993 while (c == ' ') c = *++*txtptr;
4994 if (c) ++*txtptr; /* skip past open paren */
4995 switch (c) {
4996 case '(': /* if envelope S-expression */
4997 adr = imap_parse_address (stream,txtptr,reply);
4998 if (**txtptr != ')') {
4999 sprintf (LOCAL->tmp,"Junk at end of address list: %.80s",
5000 (char *) *txtptr);
5001 mm_notify (stream,LOCAL->tmp,WARN);
5002 stream->unhealthy = T;
5004 else ++*txtptr; /* skip past delimiter */
5005 break;
5006 case 'N': /* if NIL */
5007 case 'n':
5008 ++*txtptr; /* bump past "I" */
5009 ++*txtptr; /* bump past "L" */
5010 break;
5011 default:
5012 sprintf (LOCAL->tmp,"Not an address: %.80s",(char *) *txtptr);
5013 mm_notify (stream,LOCAL->tmp,WARN);
5014 stream->unhealthy = T;
5015 break;
5017 return adr;
5020 /* IMAP parse address
5021 * Accepts: MAIL stream
5022 * current text pointer
5023 * parsed reply
5024 * Returns: address, NIL on failure
5026 * Updates text pointer
5029 ADDRESS *imap_parse_address (MAILSTREAM *stream,unsigned char **txtptr,
5030 IMAPPARSEDREPLY *reply)
5032 long ingroup = 0;
5033 ADDRESS *adr = NIL;
5034 ADDRESS *ret = NIL;
5035 ADDRESS *prev = NIL;
5036 char c = **txtptr; /* sniff at first address character */
5037 switch (c) {
5038 case '(': /* if envelope S-expression */
5039 while (c == '(') { /* recursion dies on small stack machines */
5040 ++*txtptr; /* skip past open paren */
5041 if (adr) prev = adr; /* note previous if any */
5042 adr = mail_newaddr (); /* instantiate address and parse its fields */
5043 adr->personal = imap_parse_string (stream,txtptr,reply,NIL,NIL,LONGT);
5044 adr->adl = imap_parse_string (stream,txtptr,reply,NIL,NIL,LONGT);
5045 adr->mailbox = imap_parse_string (stream,txtptr,reply,NIL,NIL,LONGT);
5046 adr->host = imap_parse_string (stream,txtptr,reply,NIL,NIL,LONGT);
5047 if (**txtptr != ')') { /* handle trailing paren */
5048 sprintf (LOCAL->tmp,"Junk at end of address: %.80s",(char *) *txtptr);
5049 mm_notify (stream,LOCAL->tmp,WARN);
5050 stream->unhealthy = T;
5052 else ++*txtptr; /* skip past close paren */
5053 c = **txtptr; /* set up for while test */
5054 /* ignore leading spaces in front of next */
5055 while (c == ' ') c = *++*txtptr;
5057 if (!adr->mailbox) { /* end of group? */
5058 /* decrement group if all looks well */
5059 if (ingroup && !(adr->personal || adr->adl || adr->host)) --ingroup;
5060 else {
5061 if (ingroup) { /* in a group? */
5062 sprintf (LOCAL->tmp,/* yes, must be bad syntax */
5063 "Junk in end of group: pn=%.80s al=%.80s dn=%.80s",
5064 adr->personal ? adr->personal : "",
5065 adr->adl ? adr->adl : "",
5066 adr->host ? adr->host : "");
5067 mm_notify (stream,LOCAL->tmp,WARN);
5069 else mm_notify (stream,"End of group encountered when not in group",
5070 WARN);
5071 stream->unhealthy = T;
5072 mail_free_address (&adr);
5073 adr = prev;
5074 prev = NIL;
5077 else if (!adr->host) { /* start of group? */
5078 if (adr->personal || adr->adl) {
5079 sprintf (LOCAL->tmp,"Junk in start of group: pn=%.80s al=%.80s",
5080 adr->personal ? adr->personal : "",
5081 adr->adl ? adr->adl : "");
5082 mm_notify (stream,LOCAL->tmp,WARN);
5083 stream->unhealthy = T;
5084 mail_free_address (&adr);
5085 adr = prev;
5086 prev = NIL;
5088 else ++ingroup; /* in a group now */
5090 if (adr) { /* good address */
5091 if (!ret) ret = adr; /* if first time note first adr */
5092 /* if previous link new block to it */
5093 if (prev) prev->next = adr;
5094 /* flush bogus personal name */
5095 if (LOCAL->loser && adr->personal && strchr (adr->personal,'@'))
5096 fs_give ((void **) &adr->personal);
5099 break;
5100 case 'N': /* if NIL */
5101 case 'n':
5102 *txtptr += 3; /* bump past NIL */
5103 break;
5104 default:
5105 sprintf (LOCAL->tmp,"Not an address: %.80s",(char *) *txtptr);
5106 mm_notify (stream,LOCAL->tmp,WARN);
5107 stream->unhealthy = T;
5108 break;
5110 return ret;
5113 /* IMAP parse flags
5114 * Accepts: current message cache
5115 * current text pointer
5117 * Updates text pointer
5120 void imap_parse_flags (MAILSTREAM *stream,MESSAGECACHE *elt,
5121 unsigned char **txtptr)
5123 char *flag;
5124 char c = '\0';
5125 struct { /* old flags */
5126 unsigned int valid : 1;
5127 unsigned int seen : 1;
5128 unsigned int deleted : 1;
5129 unsigned int flagged : 1;
5130 unsigned int answered : 1;
5131 unsigned int draft : 1;
5132 unsigned long user_flags;
5133 } old;
5134 old.valid = elt->valid; old.seen = elt->seen; old.deleted = elt->deleted;
5135 old.flagged = elt->flagged; old.answered = elt->answered;
5136 old.draft = elt->draft; old.user_flags = elt->user_flags;
5137 elt->valid = T; /* mark have valid flags now */
5138 elt->user_flags = NIL; /* zap old flag values */
5139 elt->seen = elt->deleted = elt->flagged = elt->answered = elt->draft =
5140 elt->recent = NIL;
5141 do { /* parse list of flags */
5142 /* point at a flag */
5143 while (*(flag = ++*txtptr) == ' ');
5144 /* scan for end of flag */
5145 while (**txtptr && (**txtptr != ' ') && (**txtptr != ')')) ++*txtptr;
5146 c = **txtptr; /* save delimiter */
5147 **txtptr = '\0'; /* tie off flag */
5148 if (!*flag) break; /* null flag */
5149 /* if starts with \ must be sys flag */
5150 else if (*flag == '\\') {
5151 if (!compare_cstring (flag,"\\Seen")) elt->seen = T;
5152 else if (!compare_cstring (flag,"\\Deleted")) elt->deleted = T;
5153 else if (!compare_cstring (flag,"\\Flagged")) elt->flagged = T;
5154 else if (!compare_cstring (flag,"\\Answered")) elt->answered = T;
5155 else if (!compare_cstring (flag,"\\Recent")) elt->recent = T;
5156 else if (!compare_cstring (flag,"\\Draft")) elt->draft = T;
5158 /* otherwise user flag */
5159 else elt->user_flags |= imap_parse_user_flag (stream,flag);
5160 } while (c && (c != ')'));
5161 if (c) ++*txtptr; /* bump past delimiter */
5162 else {
5163 mm_notify (stream,"Unterminated flags list",WARN);
5164 stream->unhealthy = T;
5166 if (!old.valid || (old.seen != elt->seen) ||
5167 (old.deleted != elt->deleted) || (old.flagged != elt->flagged) ||
5168 (old.answered != elt->answered) || (old.draft != elt->draft) ||
5169 (old.user_flags != elt->user_flags)) mm_flags (stream,elt->msgno);
5173 /* IMAP parse user flag
5174 * Accepts: MAIL stream
5175 * flag name
5176 * Returns: flag bit position
5179 unsigned long imap_parse_user_flag (MAILSTREAM *stream,char *flag)
5181 long i;
5182 /* sniff through all user flags */
5183 for (i = 0; i < NUSERFLAGS; ++i) if (stream->user_flags[i])
5184 if (!compare_cstring (flag,stream->user_flags[i])) return (1 << i);
5185 return (unsigned long) 0; /* not found */
5188 /* IMAP parse atom-string
5189 * Accepts: MAIL stream
5190 * current text pointer
5191 * parsed reply
5192 * returned string length
5193 * Returns: string
5195 * Updates text pointer
5198 unsigned char *imap_parse_astring (MAILSTREAM *stream,unsigned char **txtptr,
5199 IMAPPARSEDREPLY *reply,unsigned long *len)
5201 unsigned long i;
5202 unsigned char c,*s,*ret;
5203 /* ignore leading spaces */
5204 for (c = **txtptr; c == ' '; c = *++*txtptr);
5205 switch (c) {
5206 case '"': /* quoted string? */
5207 case '{': /* literal? */
5208 ret = imap_parse_string (stream,txtptr,reply,NIL,len,NIL);
5209 break;
5210 default: /* must be atom */
5211 for (c = *(s = *txtptr); /* find end of atom */
5212 c && (c > ' ') && (c != '(') && (c != ')') && (c != '{') &&
5213 (c != '%') && (c != '*') && (c != '"') && (c != '\\') && (c < 0x80);
5214 c = *++*txtptr);
5215 if ((i = *txtptr - s) != 0L) { /* atom ends at atom_special */
5216 if (len) *len = i; /* return length of atom */
5217 ret = strncpy ((char *) fs_get (i + 1),s,i);
5218 ret[i] = '\0'; /* tie off string */
5220 else { /* no atom found */
5221 sprintf (LOCAL->tmp,"Not an atom: %.80s",(char *) *txtptr);
5222 mm_notify (stream,LOCAL->tmp,WARN);
5223 stream->unhealthy = T;
5224 if (len) *len = 0;
5225 ret = NIL;
5227 break;
5229 return ret;
5232 /* IMAP parse string
5233 * Accepts: MAIL stream
5234 * current text pointer
5235 * parsed reply
5236 * mailgets data
5237 * returned string length
5238 * filter newline flag
5239 * Returns: string
5241 * Updates text pointer
5244 unsigned char *imap_parse_string (MAILSTREAM *stream,unsigned char **txtptr,
5245 IMAPPARSEDREPLY *reply,GETS_DATA *md,
5246 unsigned long *len,long flags)
5248 char *st;
5249 char *string = NIL;
5250 unsigned long i,j,k;
5251 int bogon = NIL;
5252 unsigned char c = **txtptr; /* sniff at first character */
5253 mailgets_t mg = (mailgets_t) mail_parameters (NIL,GET_GETS,NIL);
5254 readprogress_t rp =
5255 (readprogress_t) mail_parameters (NIL,GET_READPROGRESS,NIL);
5256 /* ignore leading spaces */
5257 while (c == ' ') c = *++*txtptr;
5258 if (c) st = ++*txtptr; /* remember start of string */
5259 switch (c) {
5260 case '"': /* if quoted string */
5261 i = 0; /* initial byte count */
5262 /* search for end of string */
5263 for (c = **txtptr; c != '"'; ++i,c = *++*txtptr) {
5264 /* backslash quotes next character */
5265 if (c == '\\') c = *++*txtptr;
5266 /* CHAR8 not permitted in quoted string */
5267 if (!bogon && (bogon = (c & 0x80))) {
5268 sprintf (LOCAL->tmp,"Invalid CHAR in quoted string: %x",
5269 (unsigned int) c);
5270 mm_notify (stream,LOCAL->tmp,WARN);
5271 stream->unhealthy = T;
5273 else if (!c) { /* NUL not permitted either */
5274 mm_notify (stream,"Unterminated quoted string",WARN);
5275 stream->unhealthy = T;
5276 if (len) *len = 0; /* punt, since may be at end of string */
5277 return NIL;
5280 ++*txtptr; /* bump past delimiter */
5281 string = (char *) fs_get ((size_t) i + 1);
5282 for (j = 0; j < i; j++) { /* copy the string */
5283 if (*st == '\\') ++st; /* quoted character */
5284 string[j] = *st++;
5286 string[j] = '\0'; /* tie off string */
5287 if (len) *len = i; /* set return value too */
5288 if (md && mg) { /* have special routine to slurp string? */
5289 STRING bs;
5290 if (md->first) { /* partial fetch? */
5291 md->first--; /* restore origin octet */
5292 md->last = i; /* number of octets that we got */
5294 INIT (&bs,mail_string,string,i);
5295 (*mg) (mail_read,&bs,i,md);
5297 break;
5299 case 'N': /* if NIL */
5300 case 'n':
5301 ++*txtptr; /* bump past "I" */
5302 ++*txtptr; /* bump past "L" */
5303 if (len) *len = 0;
5304 break;
5305 case '{': /* if literal string */
5306 if (!isdigit (**txtptr)) {
5307 sprintf (LOCAL->tmp,"Invalid server literal length %.80s",*txtptr);
5308 mm_notify (stream,LOCAL->tmp,WARN);
5309 stream->unhealthy = T; /* read and discard */
5310 i = 0;
5312 /* get size of string */
5313 else if ((i = strtoul (*txtptr,(char **) txtptr,10)) > MAXSERVERLIT) {
5314 sprintf (LOCAL->tmp,"Absurd server literal length %lu",i);
5315 mm_notify (stream,LOCAL->tmp,WARN);
5316 stream->unhealthy = T; /* read and discard */
5317 for (j = IMAPTMPLEN - 1; i; i -= j) {
5318 if (j > i) j = i;
5319 net_getbuffer (LOCAL->netstream,j,LOCAL->tmp);
5322 if (len) *len = i; /* set return value */
5323 if (md && mg) { /* have special routine to slurp string? */
5324 if (md->first) { /* partial fetch? */
5325 md->first--; /* restore origin octet */
5326 md->last = i; /* number of octets that we got */
5328 else md->flags |= MG_COPY;/* otherwise flag need to copy */
5329 string = (*mg) (net_getbuffer,LOCAL->netstream,i,md);
5331 else { /* must slurp into free storage */
5332 string = (char *) fs_get ((size_t) i + 1);
5333 *string = '\0'; /* init in case getbuffer fails */
5334 /* get the literal */
5335 if (rp) for (k = 0; (j = min ((long) MAILTMPLEN,(long) i)) != 0L; i -= j) {
5336 net_getbuffer (LOCAL->netstream,j,string + k);
5337 (*rp) (md,k += j);
5339 else net_getbuffer (LOCAL->netstream,i,string);
5341 fs_give ((void **) &reply->line);
5342 if (flags && string) /* need to filter newlines? */
5343 for (st = string; (st = strpbrk (st,"\015\012\011")) != NULL; *st++ = ' ');
5344 /* get new reply text line */
5345 if (!(reply->line = net_getline (LOCAL->netstream)))
5346 reply->line = cpystr ("");
5347 if (stream->debug) mm_dlog (reply->line);
5348 *txtptr = reply->line; /* set text pointer to point at it */
5349 break;
5350 default:
5351 sprintf (LOCAL->tmp,"Not a string: %c%.80s",c,(char *) *txtptr);
5352 mm_notify (stream,LOCAL->tmp,WARN);
5353 stream->unhealthy = T;
5354 if (len) *len = 0;
5355 break;
5357 return (unsigned char *) string;
5360 /* Register text in IMAP cache
5361 * Accepts: MAIL stream
5362 * message number
5363 * IMAP segment specifier
5364 * header string list (if a HEADER section specifier)
5365 * sized text to register
5366 * Returns: non-zero if cache non-empty
5369 long imap_cache (MAILSTREAM *stream,unsigned long msgno,char *seg,
5370 STRINGLIST *stl,SIZEDTEXT *text)
5372 char *t,tmp[MAILTMPLEN];
5373 unsigned long i;
5374 BODY *b;
5375 SIZEDTEXT *ret;
5376 STRINGLIST *stc;
5377 MESSAGECACHE *elt = mail_elt (stream,msgno);
5378 /* top-level header never does mailgets */
5379 if (!strcmp (seg,"HEADER") || !strcmp (seg,"0") ||
5380 !strcmp (seg,"HEADER.FIELDS") || !strcmp (seg,"HEADER.FIELDS.NOT")) {
5381 ret = &elt->private.msg.header.text;
5382 if (text) { /* don't do this if no text */
5383 if (ret->data) fs_give ((void **) &ret->data);
5384 mail_free_stringlist (&elt->private.msg.lines);
5385 elt->private.msg.lines = stl;
5386 /* prevent cache reuse of .NOT */
5387 if ((seg[0] == 'H') && (seg[6] == '.') && (seg[13] == '.'))
5388 for (stc = stl; stc; stc = stc->next) stc->text.size = 0;
5389 if (stream->scache) { /* short caching puts it in the stream */
5390 if (stream->msgno != msgno) {
5391 /* flush old stuff */
5392 mail_free_envelope (&stream->env);
5393 mail_free_body (&stream->body);
5394 stream->msgno = msgno;
5396 imap_parse_header (stream,&stream->env,text,stl);
5398 /* regular caching */
5399 else imap_parse_header (stream,&elt->private.msg.env,text,stl);
5402 /* top level text */
5403 else if (!strcmp (seg,"TEXT")) {
5404 ret = &elt->private.msg.text.text;
5405 if (text && ret->data) fs_give ((void **) &ret->data);
5407 else if (!*seg) { /* full message */
5408 ret = &elt->private.msg.full.text;
5409 if (text && ret->data) fs_give ((void **) &ret->data);
5412 else { /* nested, find non-contents specifier */
5413 for (t = seg; *t && !((*t == '.') && (isalpha(t[1]) || !atol (t+1))); t++);
5414 if (*t) *t++ = '\0'; /* tie off section from data specifier */
5415 if (!(b = mail_body (stream,msgno,seg))) {
5416 sprintf (tmp,"Unknown section number: %.80s",seg);
5417 mm_notify (stream,tmp,WARN);
5418 stream->unhealthy = T;
5419 return NIL;
5421 if (*t) { /* if a non-numberic subpart */
5422 if ((i = (b->type == TYPEMESSAGE) && (!strcmp (b->subtype,"RFC822"))) &&
5423 (!strcmp (t,"HEADER") || !strcmp (t,"0") ||
5424 !strcmp (t,"HEADER.FIELDS") || !strcmp (t,"HEADER.FIELDS.NOT"))) {
5425 ret = &b->nested.msg->header.text;
5426 if (text) {
5427 if (ret->data) fs_give ((void **) &ret->data);
5428 mail_free_stringlist (&b->nested.msg->lines);
5429 b->nested.msg->lines = stl;
5430 /* prevent cache reuse of .NOT */
5431 if ((t[0] == 'H') && (t[6] == '.') && (t[13] == '.'))
5432 for (stc = stl; stc; stc = stc->next) stc->text.size = 0;
5433 imap_parse_header (stream,&b->nested.msg->env,text,stl);
5436 else if (i && !strcmp (t,"TEXT")) {
5437 ret = &b->nested.msg->text.text;
5438 if (text && ret->data) fs_give ((void **) &ret->data);
5440 /* otherwise it must be MIME */
5441 else if (!strcmp (t,"MIME")) {
5442 ret = &b->mime.text;
5443 if (text && ret->data) fs_give ((void **) &ret->data);
5445 else {
5446 sprintf (tmp,"Unknown section specifier: %.80s.%.80s",seg,t);
5447 mm_notify (stream,tmp,WARN);
5448 stream->unhealthy = T;
5449 return NIL;
5452 else { /* ordinary contents */
5453 ret = &b->contents.text;
5454 if (text && ret->data) fs_give ((void **) &ret->data);
5457 if (text) { /* update cache if requested */
5458 ret->data = text->data;
5459 ret->size = text->size;
5461 return ret->data ? LONGT : NIL;
5464 /* IMAP parse body structure
5465 * Accepts: MAIL stream
5466 * body structure to write into
5467 * current text pointer
5468 * parsed reply
5470 * Updates text pointer
5473 void imap_parse_body_structure (MAILSTREAM *stream,BODY *body,
5474 unsigned char **txtptr,IMAPPARSEDREPLY *reply)
5476 int i;
5477 char *s;
5478 PART *part = NIL;
5479 char c = **txtptr; /* grab first character */
5480 /* ignore leading spaces */
5481 while (c == ' ') c = *++*txtptr;
5482 if (c) ++*txtptr; /* skip past first character */
5483 switch (c) { /* dispatch on first character */
5484 case '(': /* body structure list */
5485 if (**txtptr == '(') { /* multipart body? */
5486 body->type= TYPEMULTIPART;/* yes, set its type */
5487 do { /* instantiate new body part */
5488 if (part) part = part->next = mail_newbody_part ();
5489 else body->nested.part = part = mail_newbody_part ();
5490 /* parse it */
5491 imap_parse_body_structure (stream,&part->body,txtptr,reply);
5492 } while (**txtptr == '(');/* for each body part */
5493 if ((body->subtype = imap_parse_string(stream,txtptr,reply,NIL,NIL,LONGT)) != NULL)
5494 ucase (body->subtype);
5495 else {
5496 mm_notify (stream,"Missing multipart subtype",WARN);
5497 stream->unhealthy = T;
5498 body->subtype = cpystr (rfc822_default_subtype (body->type));
5500 if (**txtptr == ' ') /* multipart parameters */
5501 body->parameter = imap_parse_body_parameter (stream,txtptr,reply);
5502 if (**txtptr == ' ') { /* disposition */
5503 imap_parse_disposition (stream,body,txtptr,reply);
5504 if (LOCAL->cap.extlevel < BODYEXTDSP) LOCAL->cap.extlevel = BODYEXTDSP;
5506 if (**txtptr == ' ') { /* language */
5507 body->language = imap_parse_language (stream,txtptr,reply);
5508 if (LOCAL->cap.extlevel < BODYEXTLANG)
5509 LOCAL->cap.extlevel = BODYEXTLANG;
5511 if (**txtptr == ' ') { /* location */
5512 body->location = imap_parse_string (stream,txtptr,reply,NIL,NIL,LONGT);
5513 if (LOCAL->cap.extlevel < BODYEXTLOC) LOCAL->cap.extlevel = BODYEXTLOC;
5515 while (**txtptr == ' ') imap_parse_extension (stream,txtptr,reply);
5516 if (**txtptr != ')') { /* validate ending */
5517 sprintf (LOCAL->tmp,"Junk at end of multipart body: %.80s",
5518 (char *) *txtptr);
5519 mm_notify (stream,LOCAL->tmp,WARN);
5520 stream->unhealthy = T;
5522 else ++*txtptr; /* skip past delimiter */
5525 else { /* not multipart, parse type name */
5526 if (**txtptr == ')') { /* empty body? */
5527 ++*txtptr; /* bump past it */
5528 break; /* and punt */
5530 body->type = TYPEOTHER; /* assume unknown type */
5531 body->encoding = ENCOTHER;/* and unknown encoding */
5532 /* parse type */
5533 if ((s = imap_parse_string (stream,txtptr,reply,NIL,NIL,LONGT)) != NULL) {
5534 ucase (s); /* application always gets uppercase form */
5535 for (i = 0; /* look in existing table */
5536 (i <= TYPEMAX) && body_types[i] && strcmp (s,body_types[i]); i++);
5537 if (i <= TYPEMAX) { /* only if found a slot */
5538 body->type = i; /* set body type */
5539 if (!body_types[i]) { /* assign empty slot */
5540 body_types[i] = s;
5541 s = NIL; /* don't free this string */
5544 if (s) fs_give ((void **) &s);
5546 if ((body->subtype = imap_parse_string(stream,txtptr,reply,NIL,NIL,LONGT)) != NULL)
5547 ucase (body->subtype); /* parse subtype */
5548 else {
5549 mm_notify (stream,"Missing body subtype",WARN);
5550 stream->unhealthy = T;
5551 body->subtype = cpystr (rfc822_default_subtype (body->type));
5553 body->parameter = imap_parse_body_parameter (stream,txtptr,reply);
5554 body->id = imap_parse_string (stream,txtptr,reply,NIL,NIL,LONGT);
5555 body->description = imap_parse_string (stream,txtptr,reply,NIL,NIL,
5556 LONGT);
5557 if ((s = imap_parse_string (stream,txtptr,reply,NIL,NIL,LONGT)) != NULL) {
5558 ucase (s); /* application always gets uppercase form */
5559 for (i = 0; /* search for body encoding */
5560 (i <= ENCMAX) && body_encodings[i] && strcmp(s,body_encodings[i]);
5561 i++);
5562 if (i > ENCMAX) body->encoding = ENCOTHER;
5563 else { /* only if found a slot */
5564 body->encoding = i; /* set body encoding */
5565 /* assign empty slot */
5566 if (!body_encodings[i]) {
5567 body_encodings[i] = s;
5568 s = NIL; /* don't free this string */
5571 if (s) fs_give ((void **) &s);
5573 \f /* parse size of contents in bytes */
5574 body->size.bytes = strtoul (*txtptr,(char **) txtptr,10);
5575 switch (body->type) { /* possible extra stuff */
5576 case TYPEMESSAGE: /* message envelope and body */
5577 /* non MESSAGE/RFC822 is basic type */
5578 if (strcmp (body->subtype,"RFC822")) break;
5579 { /* make certain server sends an envelope */
5580 ENVELOPE *env = NIL;
5581 imap_parse_envelope (stream,&env,txtptr,reply);
5582 if (!env) {
5583 mm_notify (stream,"Missing body message envelope",WARN);
5584 stream->unhealthy = T;
5585 fs_give ((void **) &body->subtype);
5586 body->subtype = cpystr ("RFC822_MISSING_ENVELOPE");
5587 break;
5589 (body->nested.msg = mail_newmsg ())->env = env;
5591 body->nested.msg->body = mail_newbody ();
5592 imap_parse_body_structure (stream,body->nested.msg->body,txtptr,reply);
5593 /* drop into text case */
5594 case TYPETEXT: /* size in lines */
5595 body->size.lines = strtoul (*txtptr,(char **) txtptr,10);
5596 break;
5597 default: /* otherwise nothing special */
5598 break;
5601 if (**txtptr == ' ') { /* extension data - md5 */
5602 body->md5 = imap_parse_string (stream,txtptr,reply,NIL,NIL,LONGT);
5603 if (LOCAL->cap.extlevel < BODYEXTMD5) LOCAL->cap.extlevel = BODYEXTMD5;
5605 if (**txtptr == ' ') { /* disposition */
5606 imap_parse_disposition (stream,body,txtptr,reply);
5607 if (LOCAL->cap.extlevel < BODYEXTDSP) LOCAL->cap.extlevel = BODYEXTDSP;
5609 if (**txtptr == ' ') { /* language */
5610 body->language = imap_parse_language (stream,txtptr,reply);
5611 if (LOCAL->cap.extlevel < BODYEXTLANG)
5612 LOCAL->cap.extlevel = BODYEXTLANG;
5614 if (**txtptr == ' ') { /* location */
5615 body->location = imap_parse_string (stream,txtptr,reply,NIL,NIL,LONGT);
5616 if (LOCAL->cap.extlevel < BODYEXTLOC) LOCAL->cap.extlevel = BODYEXTLOC;
5618 while (**txtptr == ' ') imap_parse_extension (stream,txtptr,reply);
5619 if (**txtptr != ')') { /* validate ending */
5620 sprintf (LOCAL->tmp,"Junk at end of body part: %.80s",
5621 (char *) *txtptr);
5622 mm_notify (stream,LOCAL->tmp,WARN);
5623 stream->unhealthy = T;
5625 else ++*txtptr; /* skip past delimiter */
5627 break;
5628 case 'N': /* if NIL */
5629 case 'n':
5630 ++*txtptr; /* bump past "I" */
5631 ++*txtptr; /* bump past "L" */
5632 break;
5633 default: /* otherwise quite bogus */
5634 sprintf (LOCAL->tmp,"Bogus body structure: %.80s",(char *) *txtptr);
5635 mm_notify (stream,LOCAL->tmp,WARN);
5636 stream->unhealthy = T;
5637 break;
5641 /* IMAP parse body parameter
5642 * Accepts: MAIL stream
5643 * current text pointer
5644 * parsed reply
5645 * Returns: body parameter
5646 * Updates text pointer
5649 PARAMETER *imap_parse_body_parameter (MAILSTREAM *stream,
5650 unsigned char **txtptr,
5651 IMAPPARSEDREPLY *reply)
5653 PARAMETER *ret = NIL;
5654 PARAMETER *par = NIL;
5655 char c,*s;
5656 /* ignore leading spaces */
5657 while ((c = *(*txtptr)++) == ' ');
5658 if (c == '(') do { /* parse parameter list */
5659 /* append new parameter to tail */
5660 if (ret) par = par->next = mail_newbody_parameter ();
5661 else ret = par = mail_newbody_parameter ();
5662 if(!(par->attribute=imap_parse_string (stream,txtptr,reply,NIL,NIL,
5663 LONGT))) {
5664 mm_notify (stream,"Missing parameter attribute",WARN);
5665 stream->unhealthy = T;
5666 par->attribute = cpystr ("UNKNOWN");
5668 if (!(par->value = imap_parse_string (stream,txtptr,reply,NIL,NIL,LONGT))){
5669 sprintf (LOCAL->tmp,"Missing value for parameter %.80s",par->attribute);
5670 mm_notify (stream,LOCAL->tmp,WARN);
5671 stream->unhealthy = T;
5672 par->value = cpystr ("UNKNOWN");
5674 switch (c = **txtptr) { /* see what comes after */
5675 case ' ': /* flush whitespace */
5676 while ((c = *++*txtptr) == ' ');
5677 break;
5678 case ')': /* end of attribute/value pairs */
5679 ++*txtptr; /* skip past closing paren */
5680 break;
5681 case '\0':
5682 mm_notify (stream,"Unterminated parameter list", WARN);
5683 stream->unhealthy = T;
5684 break;
5685 default:
5686 sprintf (LOCAL->tmp,"Junk at end of parameter: %.80s",(char *) *txtptr);
5687 mm_notify (stream,LOCAL->tmp,WARN);
5688 stream->unhealthy = T;
5689 break;
5691 } while (c && (c != ')'));
5692 /* empty parameter, must be NIL */
5693 else if (((c == 'N') || (c == 'n')) &&
5694 ((*(s = *txtptr) == 'I') || (*s == 'i')) &&
5695 ((s[1] == 'L') || (s[1] == 'l'))) *txtptr += 2;
5696 else {
5697 sprintf (LOCAL->tmp,"Bogus body parameter: %c%.80s",c,
5698 (char *) (*txtptr) - 1);
5699 mm_notify (stream,LOCAL->tmp,WARN);
5700 stream->unhealthy = T;
5702 return ret;
5705 /* IMAP parse body disposition
5706 * Accepts: MAIL stream
5707 * body structure to write into
5708 * current text pointer
5709 * parsed reply
5712 void imap_parse_disposition (MAILSTREAM *stream,BODY *body,
5713 unsigned char **txtptr,IMAPPARSEDREPLY *reply)
5715 switch (*++*txtptr) {
5716 case '(':
5717 ++*txtptr; /* skip open paren */
5718 body->disposition.type = imap_parse_string (stream,txtptr,reply,NIL,NIL,
5719 LONGT);
5720 body->disposition.parameter =
5721 imap_parse_body_parameter (stream,txtptr,reply);
5722 if (**txtptr != ')') { /* validate ending */
5723 sprintf (LOCAL->tmp,"Junk at end of disposition: %.80s",
5724 (char *) *txtptr);
5725 mm_notify (stream,LOCAL->tmp,WARN);
5726 stream->unhealthy = T;
5728 else ++*txtptr; /* skip past delimiter */
5729 break;
5730 case 'N': /* if NIL */
5731 case 'n':
5732 ++*txtptr; /* bump past "N" */
5733 ++*txtptr; /* bump past "I" */
5734 ++*txtptr; /* bump past "L" */
5735 break;
5736 default:
5737 sprintf (LOCAL->tmp,"Unknown body disposition: %.80s",(char *) *txtptr);
5738 mm_notify (stream,LOCAL->tmp,WARN);
5739 stream->unhealthy = T;
5740 /* try to skip to next space */
5741 while (**txtptr && (*++*txtptr != ' ') && (**txtptr != ')'));
5742 break;
5746 /* IMAP parse body language
5747 * Accepts: MAIL stream
5748 * current text pointer
5749 * parsed reply
5750 * Returns: string list or NIL if empty or error
5753 STRINGLIST *imap_parse_language (MAILSTREAM *stream,unsigned char **txtptr,
5754 IMAPPARSEDREPLY *reply)
5756 unsigned long i;
5757 char *s;
5758 STRINGLIST *ret = NIL;
5759 /* language is a list */
5760 if (*++*txtptr == '(') ret = imap_parse_stringlist (stream,txtptr,reply);
5761 else if ((s = imap_parse_string (stream,txtptr,reply,NIL,&i,LONGT)) != NULL) {
5762 (ret = mail_newstringlist ())->text.data = (unsigned char *) s;
5763 ret->text.size = i;
5765 return ret;
5768 /* IMAP parse string list
5769 * Accepts: MAIL stream
5770 * current text pointer
5771 * parsed reply
5772 * Returns: string list or NIL if empty or error
5775 STRINGLIST *imap_parse_stringlist (MAILSTREAM *stream,unsigned char **txtptr,
5776 IMAPPARSEDREPLY *reply)
5778 STRINGLIST *stl = NIL;
5779 STRINGLIST *stc = NIL;
5780 unsigned char *t = *txtptr;
5781 /* parse the list */
5782 if (*t++ == '(') while (*t != ')') {
5783 if (stl) stc = stc->next = mail_newstringlist ();
5784 else stc = stl = mail_newstringlist ();
5785 /* parse astring */
5786 if (!(stc->text.data =
5787 imap_parse_astring (stream,&t,reply,&stc->text.size))) {
5788 sprintf (LOCAL->tmp,"Bogus string list member: %.80s",(char *) t);
5789 mm_notify (stream,LOCAL->tmp,WARN);
5790 stream->unhealthy = T;
5791 mail_free_stringlist (&stl);
5792 break;
5794 else if (*t == ' ') ++t; /* another token follows */
5796 if (stl) *txtptr = ++t; /* update return string */
5797 return stl;
5800 /* IMAP parse unknown body extension data
5801 * Accepts: MAIL stream
5802 * current text pointer
5803 * parsed reply
5805 * Updates text pointer
5808 void imap_parse_extension (MAILSTREAM *stream,unsigned char **txtptr,
5809 IMAPPARSEDREPLY *reply)
5811 unsigned long i,j;
5812 switch (*++*txtptr) { /* action depends upon first character */
5813 case '(':
5814 while (**txtptr && (**txtptr != ')'))
5815 imap_parse_extension (stream,txtptr,reply);
5816 if (**txtptr) ++*txtptr; /* bump past closing parenthesis */
5817 break;
5818 case '"': /* if quoted string */
5819 while ((*++*txtptr != '"') && **txtptr) if (**txtptr == '\\') ++*txtptr;
5820 if (**txtptr) ++*txtptr; /* bump past closing quote */
5821 break;
5822 case 'N': /* if NIL */
5823 case 'n':
5824 ++*txtptr; /* bump past "N" */
5825 ++*txtptr; /* bump past "I" */
5826 ++*txtptr; /* bump past "L" */
5827 break;
5828 case '{': /* get size of literal */
5829 ++*txtptr; /* bump past open squiggle */
5830 if ((i = strtoul (*txtptr,(char **) txtptr,10)) != 0L) do
5831 net_getbuffer (LOCAL->netstream,j = min (i,(long) IMAPTMPLEN - 1),
5832 LOCAL->tmp);
5833 while (i -= j);
5834 /* get new reply text line */
5835 if (!(reply->line = net_getline (LOCAL->netstream)))
5836 reply->line = cpystr ("");
5837 if (stream->debug) mm_dlog (reply->line);
5838 *txtptr = reply->line; /* set text pointer to point at it */
5839 break;
5840 case '0': case '1': case '2': case '3': case '4':
5841 case '5': case '6': case '7': case '8': case '9':
5842 strtoul (*txtptr,(char **) txtptr,10);
5843 break;
5844 default:
5845 sprintf (LOCAL->tmp,"Unknown extension token: %.80s",(char *) *txtptr);
5846 mm_notify (stream,LOCAL->tmp,WARN);
5847 stream->unhealthy = T;
5848 /* try to skip to next space */
5849 while (**txtptr && (*++*txtptr != ' ') && (**txtptr != ')'));
5850 break;
5854 /* IMAP parse capabilities
5855 * Accepts: MAIL stream
5856 * capability list
5859 void imap_parse_capabilities (MAILSTREAM *stream,char *t)
5861 char *s,*r;
5862 unsigned long i;
5863 THREADER *thr,*th;
5864 if (!LOCAL->gotcapability) { /* need to save previous capabilities? */
5865 /* no, flush threaders */
5866 if ((thr = LOCAL->cap.threader) != NULL) while ((th = thr) != NULL) {
5867 fs_give ((void **) &th->name);
5868 thr = th->next;
5869 fs_give ((void **) &th);
5871 /* zap capabilities */
5872 memset (&LOCAL->cap,0,sizeof (LOCAL->cap));
5873 LOCAL->gotcapability = T; /* flag that capabilities arrived */
5875 for (t = strtok_r (t," ",&r); t; t = strtok_r (NIL," ",&r)) {
5876 if (!compare_cstring (t,"IMAP4"))
5877 LOCAL->cap.imap4 = LOCAL->cap.imap2bis = LOCAL->cap.rfc1176 = T;
5878 else if (!compare_cstring (t,"IMAP4rev1"))
5879 LOCAL->cap.imap4rev1 = LOCAL->cap.imap2bis = LOCAL->cap.rfc1176 = T;
5880 else if (!compare_cstring (t,"IMAP2")) LOCAL->cap.rfc1176 = T;
5881 else if (!compare_cstring (t,"IMAP2bis"))
5882 LOCAL->cap.imap2bis = LOCAL->cap.rfc1176 = T;
5883 else if (!compare_cstring (t,"ACL")) LOCAL->cap.acl = T;
5884 else if (!compare_cstring (t,"QUOTA")) LOCAL->cap.quota = T;
5885 else if (!compare_cstring (t,"LITERAL+")) LOCAL->cap.litplus = T;
5886 else if (!compare_cstring (t,"IDLE")) LOCAL->cap.idle = T;
5887 else if (!compare_cstring (t,"MAILBOX-REFERRALS")) LOCAL->cap.mbx_ref = T;
5888 else if (!compare_cstring (t,"LOGIN-REFERRALS")) LOCAL->cap.log_ref = T;
5889 else if (!compare_cstring (t,"NAMESPACE")) LOCAL->cap.namespace = T;
5890 else if (!compare_cstring (t,"UIDPLUS")) LOCAL->cap.uidplus = T;
5891 else if (!compare_cstring (t,"STARTTLS")) LOCAL->cap.starttls = T;
5892 else if (!compare_cstring (t,"LOGINDISABLED"))LOCAL->cap.logindisabled = T;
5893 else if (!compare_cstring (t,"ID")) LOCAL->cap.id = T;
5894 else if (!compare_cstring (t,"CHILDREN")) LOCAL->cap.children = T;
5895 else if (!compare_cstring (t,"MULTIAPPEND")) LOCAL->cap.multiappend = T;
5896 else if (!compare_cstring (t,"BINARY")) LOCAL->cap.binary = T;
5897 else if (!compare_cstring (t,"UNSELECT")) LOCAL->cap.unselect = T;
5898 else if (!compare_cstring (t,"SASL-IR")) LOCAL->cap.sasl_ir = T;
5899 else if (!compare_cstring (t,"SCAN")) LOCAL->cap.scan = T;
5900 else if (!compare_cstring (t,"URLAUTH")) LOCAL->cap.urlauth = T;
5901 else if (!compare_cstring (t,"CATENATE")) LOCAL->cap.catenate = T;
5902 else if (!compare_cstring (t,"CONDSTORE")) LOCAL->cap.condstore = T;
5903 else if (!compare_cstring (t,"ESEARCH")) LOCAL->cap.esearch = T;
5904 else if (!compare_cstring (t,"X-GM-EXT-1")) LOCAL->cap.x_gm_ext1 = T;
5905 else if (((t[0] == 'S') || (t[0] == 's')) &&
5906 ((t[1] == 'O') || (t[1] == 'o')) &&
5907 ((t[2] == 'R') || (t[2] == 'r')) &&
5908 ((t[3] == 'T') || (t[3] == 't'))) LOCAL->cap.sort = T;
5909 /* capability with value? */
5910 else if ((s = strchr (t,'=')) != NULL) {
5911 *s++ = '\0'; /* separate token from value */
5912 if (!compare_cstring (t,"THREAD") && !LOCAL->loser) {
5913 THREADER *thread = (THREADER *) fs_get (sizeof (THREADER));
5914 thread->name = cpystr (s);
5915 thread->dispatch = NIL;
5916 thread->next = LOCAL->cap.threader;
5917 LOCAL->cap.threader = thread;
5919 else if (!compare_cstring (t,"AUTH")) {
5920 if ((i = mail_lookup_auth_name (s,LOCAL->authflags)) &&
5921 (--i < MAXAUTHENTICATORS)) LOCAL->cap.auth |= (1 << i);
5922 else if (!compare_cstring (s,"ANONYMOUS")) LOCAL->cap.authanon = T;
5925 /* ignore other capabilities */
5927 /* disable LOGIN if PLAIN also advertised */
5928 if ((i = mail_lookup_auth_name ("PLAIN",NIL)) && (--i < MAXAUTHENTICATORS) &&
5929 (LOCAL->cap.auth & (1 << i)) &&
5930 (i = mail_lookup_auth_name ("LOGIN",NIL)) && (--i < MAXAUTHENTICATORS))
5931 LOCAL->cap.auth &= ~(1 << i);
5934 /* IMAP load cache
5935 * Accepts: MAIL stream
5936 * sequence
5937 * flags
5938 * Returns: parsed reply from fetch
5941 IMAPPARSEDREPLY *imap_fetch (MAILSTREAM *stream,char *sequence,long flags)
5943 int i = 2;
5944 char *cmd = (LEVELIMAP4 (stream) && (flags & FT_UID)) ?
5945 "UID FETCH" : "FETCH";
5946 IMAPARG *args[9],aseq,aarg,aenv,ahhr,axtr,ahtr,abdy,atrl;
5947 if (LOCAL->loser) sequence = imap_reform_sequence (stream,sequence,
5948 flags & FT_UID);
5949 args[0] = &aseq; aseq.type = SEQUENCE; aseq.text = (void *) sequence;
5950 args[1] = &aarg; aarg.type = ATOM;
5951 aenv.type = ATOM; aenv.text = (void *) "ENVELOPE";
5952 ahhr.type = ATOM; ahhr.text = (void *) hdrheader[LOCAL->cap.extlevel];
5953 axtr.type = ATOM; axtr.text = (void *) imap_extrahdrs;
5954 ahtr.type = ATOM; ahtr.text = (void *) hdrtrailer;
5955 abdy.type = ATOM; abdy.text = (void *) "BODYSTRUCTURE";
5956 atrl.type = ATOM; atrl.text = (void *) "INTERNALDATE RFC822.SIZE FLAGS)";
5957 if (LEVELIMAP4 (stream)) { /* include UID if IMAP4 or IMAP4rev1 */
5958 aarg.text = (void *) "(UID";
5959 if (flags & FT_NEEDENV) { /* if need envelopes */
5960 args[i++] = &aenv; /* include envelope */
5961 /* extra header poop if IMAP4rev1 */
5962 if (!(flags & FT_NOHDRS) && LEVELIMAP4rev1 (stream)) {
5963 args[i++] = &ahhr; /* header header */
5964 if (axtr.text) args[i++] = &axtr;
5965 args[i++] = &ahtr; /* header trailer */
5967 /* fetch body if requested */
5968 if (flags & FT_NEEDBODY) args[i++] = &abdy;
5970 args[i++] = &atrl; /* fetch trailer */
5972 /* easy if IMAP2 */
5973 else aarg.text = (void *) (flags & FT_NEEDENV) ?
5974 ((flags & FT_NEEDBODY) ?
5975 "(RFC822.HEADER BODY INTERNALDATE RFC822.SIZE FLAGS)" :
5976 "(RFC822.HEADER INTERNALDATE RFC822.SIZE FLAGS)") : "FAST";
5977 args[i] = NIL; /* tie off command */
5978 return imap_send (stream,cmd,args);
5981 /* Reform sequence for losing server that doesn't handle ranges right
5982 * Accepts: MAIL stream
5983 * sequence
5984 * non-zero if UID
5985 * Returns: sequence
5988 char *imap_reform_sequence (MAILSTREAM *stream,char *sequence,long flags)
5990 unsigned long i,j,star;
5991 char *s,*t,*tl,*rs;
5992 /* can't win if empty */
5993 if (!stream->nmsgs) return sequence;
5994 /* get highest possible range value */
5995 star = flags ? mail_uid (stream,stream->nmsgs) : stream->nmsgs;
5996 /* flush old reformed sequence */
5997 if (LOCAL->reform) fs_give ((void **) &LOCAL->reform);
5998 rs = LOCAL->reform = (char *) fs_get (1+ strlen (sequence));
5999 for (s = sequence; (t = strpbrk (s,",:")) != NULL; ) switch (*t++) {
6000 case ',': /* single message */
6001 strncpy (rs,s,i = t - s); /* copy string up to that point */
6002 rs += i; /* advance destination pointer */
6003 s += i; /* and source */
6004 break;
6005 case ':': /* message range */
6006 i = (*s == '*') ? star : strtoul (s,NIL,10);
6007 if (*t == '*') { /* range ends with star */
6008 j = star;
6009 tl = t+1;
6011 else { /* numeric range end */
6012 j = strtoul (t,(char **) &tl,10);
6013 if (!tl) tl = t + strlen (t);
6015 if (i <= j) { /* if first less than second */
6016 if (*tl) tl++; /* skip past end of range if present */
6017 strncpy (rs,s,i = tl - s);/* copy string up to that point */
6018 rs += i; /* advance destination and source pointers */
6019 s += i;
6021 else { /* here's the workaround for losing servers */
6022 strncpy (rs,t,i = tl - t);/* swap the order */
6023 rs[i] = ':'; /* delimit */
6024 strncpy (rs+i+1,s,j = (t-1) - s);
6025 rs += i + 1 + j; /* advance destination pointer */
6026 if (*tl) *rs++ = *tl++; /* write trailing delimiter if present */
6027 s = tl; /* advance source pointer */
6030 if (*s) strcpy (rs,s); /* write remainder of sequence */
6031 else *rs = '\0'; /* tie off string */
6032 return LOCAL->reform;
6035 /* IMAP return host name
6036 * Accepts: MAIL stream
6037 * Returns: host name
6040 char *imap_host (MAILSTREAM *stream)
6042 if (stream->dtb != &imapdriver)
6043 fatal ("imap_host called on non-IMAP stream!");
6044 /* return host name on stream if open */
6045 return (LOCAL && LOCAL->netstream) ? net_host (LOCAL->netstream) :
6046 ".NO-IMAP-CONNECTION.";
6050 /* IMAP return IMAP capability structure
6051 * Accepts: MAIL stream
6052 * Returns: IMAP capability structure
6055 IMAPCAP *imap_cap (MAILSTREAM *stream)
6057 if (stream->dtb != &imapdriver)
6058 fatal ("imap_cap called on non-IMAP stream!");
6059 return &LOCAL->cap; /* return capability structure */