]> Pileus Git - ~andy/fetchmail/blob - imap.c
Do STARTTLS/STLS negotiation in IMAP/POP3 if it is mandatory ignoring server capabilities
[~andy/fetchmail] / imap.c
1 /*
2  * imap.c -- IMAP2bis/IMAP4 protocol methods
3  *
4  * Copyright 1997 by Eric S. Raymond
5  * For license terms, see the file COPYING in this directory.
6  */
7
8 #include  "config.h"
9 #include  <stdio.h>
10 #include  <string.h>
11 #include  <strings.h>
12 #include  <ctype.h>
13 #if defined(STDC_HEADERS)
14 #include  <stdlib.h>
15 #include  <limits.h>
16 #include  <errno.h>
17 #endif
18 #include  "fetchmail.h"
19 #include  "socket.h"
20
21 #include  "i18n.h"
22
23 /* imap_version values */
24 #define IMAP2           -1      /* IMAP2 or IMAP2BIS, RFC1176 */
25 #define IMAP4           0       /* IMAP4 rev 0, RFC1730 */
26 #define IMAP4rev1       1       /* IMAP4 rev 1, RFC2060 */
27
28 /* global variables: please reinitialize them explicitly for proper
29  * working in daemon mode */
30
31 /* TODO: session variables to be initialized before server greeting */
32 static int preauth = FALSE;
33
34 /* session variables initialized in capa_probe() or imap_getauth() */
35 static char capabilities[MSGBUFSIZE+1];
36 static int imap_version = IMAP4;
37 static flag do_idle = FALSE, has_idle = FALSE;
38 static int expunge_period = 1;
39
40 /* mailbox variables initialized in imap_getrange() */
41 static int count = 0, oldcount = 0, recentcount = 0, unseen = 0, deletions = 0;
42 static unsigned int startcount = 1;
43 static int expunged = 0;
44 static unsigned int *unseen_messages;
45
46 /* for "IMAP> EXPUNGE" */
47 static int actual_deletions = 0;
48
49 /* for "IMAP> IDLE" */
50 static int saved_timeout = 0, idle_timeout = 0;
51 static time_t idle_start_time = 0;
52
53 static int imap_untagged_response(int sock, const char *buf)
54 /* interpret untagged status responses */
55 {
56     /* For each individual check, use a BLANK before the word to avoid
57      * confusion with the \Recent flag or similar */
58     if (stage == STAGE_GETAUTH
59             && !strncmp(buf, "* CAPABILITY", 12))
60     {
61         strlcpy(capabilities, buf + 12, sizeof(capabilities));
62     }
63     else if (stage == STAGE_GETAUTH
64             && !strncmp(buf, "* PREAUTH", 9))
65     {
66         preauth = TRUE;
67     }
68     else if (stage != STAGE_LOGOUT
69             && !strncmp(buf, "* BYE", 5))
70     {
71         /* log the unexpected bye from server as we expect the
72          * connection to be cut-off after this */
73         if (outlevel > O_SILENT)
74             report(stderr, GT_("Received BYE response from IMAP server: %s"), buf + 5);
75     }
76     else if (strstr(buf, " EXISTS"))
77     {
78         char *t; unsigned long u;
79         errno = 0;
80         u = strtoul(buf+2, &t, 10);
81         /*
82          * Don't trust the message count passed by the server.
83          * Without this check, it might be possible to do a
84          * DNS-spoofing attack that would pass back a ridiculous 
85          * count, and allocate a malloc area that would overlap
86          * a portion of the stack.
87          */
88         if (errno /* strtoul failed */
89                 || t == buf+2 /* no valid data */
90                 || u > (unsigned long)(INT_MAX/sizeof(int)) /* too large */)
91         {
92             report(stderr, GT_("bogus message count in \"%s\"!"), buf);
93             return(PS_PROTOCOL);
94         }
95         count = u; /* safe as long as count <= INT_MAX - checked above */
96
97         if ((recentcount = count - oldcount) < 0)
98             recentcount = 0;
99
100         /*
101          * Nasty kluge to handle RFC2177 IDLE.  If we know we're idling
102          * we can't wait for the tag matching the IDLE; we have to tell the
103          * server the IDLE is finished by shipping back a DONE when we
104          * see an EXISTS.  Only after that will a tagged response be
105          * shipped.  The idling flag also gets cleared on a timeout.
106          */
107         if (stage == STAGE_IDLE)
108         {
109             /* If IDLE isn't supported, we were only sending NOOPs anyway. */
110             if (has_idle)
111             {
112                 /* we do our own write and report here to disable tagging */
113                 SockWrite(sock, "DONE\r\n", 6);
114                 if (outlevel >= O_MONITOR)
115                     report(stdout, "IMAP> DONE\n");
116             }
117
118             mytimeout = saved_timeout;
119             stage = STAGE_GETRANGE;
120         }
121     }
122     /* we now compute recentcount as a difference between
123      * new and old EXISTS, hence disable RECENT check */
124 # if 0
125     else if (strstr(buf, " RECENT"))
126     {
127         /* fixme: use strto[u]l and error checking */
128         recentcount = atoi(buf+2);
129     }
130 # endif
131     else if (strstr(buf, " EXPUNGE"))
132     {
133         unsigned long u; char *t;
134         /* the response "* 10 EXPUNGE" means that the currently
135          * tenth (i.e. only one) message has been deleted */
136         errno = 0;
137         u = strtoul(buf+2, &t, 10);
138         if (errno /* conversion error */ || t == buf+2 /* no number found */) {
139             report(stderr, GT_("bogus EXPUNGE count in \"%s\"!"), buf);
140             return PS_PROTOCOL;
141         }
142         if (u > 0)
143         {
144             if (count > 0)
145                 count--;
146             if (oldcount > 0)
147                 oldcount--;
148             /* We do expect an EXISTS response immediately
149              * after this, so this updation of recentcount is
150              * just a precaution! */
151             if ((recentcount = count - oldcount) < 0)
152                 recentcount = 0;
153             actual_deletions++;
154         }
155     }
156     /*
157      * The server may decide to make the mailbox read-only, 
158      * which causes fetchmail to go into a endless loop
159      * fetching the same message over and over again. 
160      * 
161      * However, for check_only, we use EXAMINE which will
162      * mark the mailbox read-only as per the RFC.
163      * 
164      * This checks for the condition and aborts if 
165      * the mailbox is read-only. 
166      *
167      * See RFC 2060 section 6.3.1 (SELECT).
168      * See RFC 2060 section 6.3.2 (EXAMINE).
169      */ 
170     else if (stage == STAGE_GETRANGE
171             && !check_only && strstr(buf, "[READ-ONLY]"))
172     {
173         return(PS_LOCKBUSY);
174     }
175     else
176     {
177         return(PS_UNTAGGED);
178     }
179     return(PS_SUCCESS);
180 }
181
182 static int imap_response(int sock, char *argbuf)
183 /* parse command response */
184 {
185     char buf[MSGBUFSIZE+1];
186
187     do {
188         int     ok;
189         char    *cp;
190
191         if ((ok = gen_recv(sock, buf, sizeof(buf))))
192             return(ok);
193
194         /* all tokens in responses are caseblind */
195         for (cp = buf; *cp; cp++)
196             if (islower((unsigned char)*cp))
197                 *cp = toupper((unsigned char)*cp);
198
199         /* untagged responses start with "* " */
200         if (buf[0] == '*' && buf[1] == ' ') {
201             ok = imap_untagged_response(sock, buf);
202             if (ok == PS_UNTAGGED)
203             {
204                 if (argbuf && stage != STAGE_IDLE && tag[0] != '\0')
205                 {
206                     /* if there is an unmatched response, pass it back to
207                      * the calling function for further analysis. The
208                      * calling function should call imap_response() again
209                      * to read the remaining response */
210                     strcpy(argbuf, buf);
211                     return(ok);
212                 }
213             }
214             else if (ok != PS_SUCCESS)
215                 return(ok);
216         }
217
218         if (stage == STAGE_IDLE)
219         {
220             /* reduce the timeout: servers may not reset their timeout
221              * when they send some information asynchronously */
222             mytimeout = idle_timeout - (time((time_t *) NULL) - idle_start_time);
223             if (mytimeout <= 0)
224                 return(PS_IDLETIMEOUT);
225         }
226     } while
227         (tag[0] != '\0' && strncmp(buf, tag, strlen(tag)));
228
229     if (tag[0] == '\0')
230     {
231         if (argbuf)
232             strcpy(argbuf, buf);
233         return(PS_SUCCESS); 
234     }
235     else
236     {
237         char    *cp;
238
239         /* skip the tag */
240         for (cp = buf; !isspace((unsigned char)*cp); cp++)
241             continue;
242         while (isspace((unsigned char)*cp))
243             cp++;
244
245         if (strncasecmp(cp, "OK", 2) == 0)
246         {
247             if (argbuf)
248                 strcpy(argbuf, cp);
249             return(PS_SUCCESS);
250         }
251         else if (strncasecmp(cp, "BAD", 3) == 0)
252             return(PS_ERROR);
253         else if (strncasecmp(cp, "NO", 2) == 0)
254         {
255             if (stage == STAGE_GETAUTH) 
256                 return(PS_AUTHFAIL);    /* RFC2060, 6.2.2 */
257             else if (stage == STAGE_GETSIZES)
258                 return(PS_SUCCESS);     /* see comments in imap_getpartialsizes() */
259             else
260                 return(PS_ERROR);
261         }
262         else
263             return(PS_PROTOCOL);
264     }
265 }
266
267 static int imap_ok(int sock, char *argbuf)
268 /* parse command response */
269 {
270     int ok;
271
272     while ((ok = imap_response(sock, argbuf)) == PS_UNTAGGED)
273         ; /* wait for the tagged response */
274     return(ok);
275 }
276
277 #ifdef NTLM_ENABLE
278 #include "ntlm.h"
279
280 /*
281  * NTLM support by Grant Edwards.
282  *
283  * Handle MS-Exchange NTLM authentication method.  This is the same
284  * as the NTLM auth used by Samba for SMB related services. We just
285  * encode the packets in base64 instead of sending them out via a
286  * network interface.
287  * 
288  * Much source (ntlm.h, smb*.c smb*.h) was borrowed from Samba.
289  */
290
291 static int do_imap_ntlm(int sock, struct query *ctl)
292 {
293     int result;
294
295     gen_send(sock, "AUTHENTICATE NTLM");
296
297     if ((result = ntlm_helper(sock, ctl, "IMAP")))
298         return result;
299
300     result = imap_ok (sock, NULL);
301     if (result == PS_SUCCESS)
302         return PS_SUCCESS;
303     else
304         return PS_AUTHFAIL;
305 }
306 #endif /* NTLM */
307
308 static void imap_canonicalize(char *result, char *raw, size_t maxlen)
309 /* encode an IMAP password as per RFC1730's quoting conventions */
310 {
311     size_t i, j;
312
313     j = 0;
314     for (i = 0; i < strlen(raw) && i < maxlen; i++)
315     {
316         if ((raw[i] == '\\') || (raw[i] == '"'))
317             result[j++] = '\\';
318         result[j++] = raw[i];
319     }
320     result[j] = '\0';
321 }
322
323 static void capa_probe(int sock, struct query *ctl)
324 /* set capability variables from a CAPA probe */
325 {
326     int ok;
327
328     /* probe to see if we're running IMAP4 and can use RFC822.PEEK */
329     capabilities[0] = '\0';
330     if ((ok = gen_transact(sock, "CAPABILITY")) == PS_SUCCESS)
331     {
332         char    *cp;
333
334         /* capability checks are supposed to be caseblind */
335         for (cp = capabilities; *cp; cp++)
336             *cp = toupper((unsigned char)*cp);
337
338         /* UW-IMAP server 10.173 notifies in all caps, but RFC2060 says we
339            should expect a response in mixed-case */
340         if (strstr(capabilities, "IMAP4REV1"))
341         {
342             imap_version = IMAP4rev1;
343             if (outlevel >= O_DEBUG)
344                 report(stdout, GT_("Protocol identified as IMAP4 rev 1\n"));
345         }
346         else
347         {
348             imap_version = IMAP4;
349             if (outlevel >= O_DEBUG)
350                 report(stdout, GT_("Protocol identified as IMAP4 rev 0\n"));
351         }
352     }
353     else if (ok == PS_ERROR)
354     {
355         imap_version = IMAP2;
356         if (outlevel >= O_DEBUG)
357             report(stdout, GT_("Protocol identified as IMAP2 or IMAP2BIS\n"));
358     }
359
360     /* 
361      * Handle idling.  We depend on coming through here on startup
362      * and after each timeout (including timeouts during idles).
363      */
364     do_idle = ctl->idle;
365     if (ctl->idle)
366     {
367         if (strstr(capabilities, "IDLE"))
368             has_idle = TRUE;
369         else
370             has_idle = FALSE;
371         if (outlevel >= O_VERBOSE)
372             report(stdout, GT_("will idle after poll\n"));
373     }
374
375     peek_capable = (imap_version >= IMAP4);
376 }
377
378 static int do_authcert (int sock, const char *command, const char *name)
379 /* do authentication "external" (authentication provided by client cert) */
380 {
381     char buf[256];
382
383     if (name && name[0])
384     {
385         size_t len = strlen(name);
386         if ((len / 3) + ((len % 3) ? 4 : 0)  < sizeof(buf))
387             to64frombits (buf, name, strlen(name));
388         else
389             return PS_AUTHFAIL; /* buffer too small. */
390     }
391     else
392         buf[0]=0;
393     return gen_transact(sock, "%s EXTERNAL %s",command,buf);
394 }
395
396 static int imap_getauth(int sock, struct query *ctl, char *greeting)
397 /* apply for connection authorization */
398 {
399     int ok = 0;
400     (void)greeting;
401
402     /*
403      * Assumption: expunges are cheap, so we want to do them
404      * after every message unless user said otherwise.
405      */
406     if (NUM_SPECIFIED(ctl->expunge))
407         expunge_period = NUM_VALUE_OUT(ctl->expunge);
408     else
409         expunge_period = 1;
410
411     capa_probe(sock, ctl);
412
413     /* 
414      * If either (a) we saw a PREAUTH token in the greeting, or
415      * (b) the user specified ssh preauthentication, then we're done.
416      */
417     if (preauth || ctl->server.authenticate == A_SSH)
418     {
419         preauth = FALSE;  /* reset for the next session */
420         return(PS_SUCCESS);
421     }
422
423 #ifdef SSL_ENABLE
424     if (maybe_tls(ctl)) {
425         char *commonname;
426
427         commonname = ctl->server.pollname;
428         if (ctl->server.via)
429             commonname = ctl->server.via;
430         if (ctl->sslcommonname)
431             commonname = ctl->sslcommonname;
432
433         if (strstr(capabilities, "STARTTLS")
434                 || must_tls(ctl)) /* if TLS is mandatory, ignore capabilities */
435         {
436             /* Use "tls1" rather than ctl->sslproto because tls1 is the only
437              * protocol that will work with STARTTLS.  Don't need to worry
438              * whether TLS is mandatory or opportunistic unless SSLOpen() fails
439              * (see below). */
440             if (gen_transact(sock, "STARTTLS") == PS_SUCCESS
441                     && SSLOpen(sock, ctl->sslcert, ctl->sslkey, "tls1", ctl->sslcertck,
442                         ctl->sslcertfile, ctl->sslcertpath, ctl->sslfingerprint, commonname,
443                         ctl->server.pollname, &ctl->remotename) != -1)
444             {
445                 /*
446                  * RFC 2595 says this:
447                  *
448                  * "Once TLS has been started, the client MUST discard cached
449                  * information about server capabilities and SHOULD re-issue the
450                  * CAPABILITY command.  This is necessary to protect against
451                  * man-in-the-middle attacks which alter the capabilities list prior
452                  * to STARTTLS.  The server MAY advertise different capabilities
453                  * after STARTTLS."
454                  *
455                  * Now that we're confident in our TLS connection we can
456                  * guarantee a secure capability re-probe.
457                  */
458                 capa_probe(sock, ctl);
459                 if (outlevel >= O_VERBOSE)
460                 {
461                     report(stdout, GT_("%s: upgrade to TLS succeeded.\n"), commonname);
462                 }
463             } else if (must_tls(ctl)) {
464                 /* Config required TLS but we couldn't guarantee it, so we must
465                  * stop. */
466                 report(stderr, GT_("%s: upgrade to TLS failed.\n"), commonname);
467                 return PS_SOCKET;
468             } else {
469                 if (outlevel >= O_VERBOSE) {
470                     report(stdout, GT_("%s: opportunistic upgrade to TLS failed, trying to continue\n"), commonname);
471                 }
472                 /* We don't know whether the connection is in a working state, so
473                  * test by issuing a NOOP. */
474                 if (gen_transact(sock, "NOOP") != PS_SUCCESS) {
475                     /* Not usable.  Empty sslproto to force an unencrypted
476                      * connection on the next attempt, and repoll. */
477                     ctl->sslproto = xstrdup("");
478                     return PS_REPOLL;
479                 }
480                 /* Usable.  Proceed with authenticating insecurely. */
481             }
482         }
483     }
484 #endif /* SSL_ENABLE */
485
486     /*
487      * Time to authenticate the user.
488      * Try the protocol variants that don't require passwords first.
489      */
490     ok = PS_AUTHFAIL;
491
492     /* Yahoo hack - we'll just try ID if it was offered by the server,
493      * and IGNORE errors. */
494     {
495         char *tmp = strstr(capabilities, " ID");
496         if (tmp && !isalnum((unsigned char)tmp[3]) && strstr(ctl->server.via ? ctl->server.via : ctl->server.pollname, "yahoo.com")) {
497                 (void)gen_transact(sock, "ID (\"guid\" \"1\")");
498         }
499     }
500
501     if ((ctl->server.authenticate == A_ANY 
502          || ctl->server.authenticate == A_EXTERNAL)
503         && strstr(capabilities, "AUTH=EXTERNAL"))
504     {
505         ok = do_authcert(sock, "AUTHENTICATE", ctl->remotename);
506         if (ok)
507         {
508             /* SASL cancellation of authentication */
509             gen_send(sock, "*");
510             if (ctl->server.authenticate != A_ANY)
511                 return ok;
512         } else {
513             return ok;
514         }
515     }
516
517 #ifdef GSSAPI
518     if (((ctl->server.authenticate == A_ANY && check_gss_creds("imap", ctl->server.truename) == PS_SUCCESS)
519          || ctl->server.authenticate == A_GSSAPI)
520         && strstr(capabilities, "AUTH=GSSAPI"))
521     {
522         if ((ok = do_gssauth(sock, "AUTHENTICATE", "imap",
523                         ctl->server.truename, ctl->remotename)))
524         {
525             if (ctl->server.authenticate != A_ANY)
526                 return ok;
527         } else  {
528             return ok;
529         }
530     }
531 #endif /* GSSAPI */
532
533 #ifdef KERBEROS_V4
534     if ((ctl->server.authenticate == A_ANY 
535          || ctl->server.authenticate == A_KERBEROS_V4
536          || ctl->server.authenticate == A_KERBEROS_V5) 
537         && strstr(capabilities, "AUTH=KERBEROS_V4"))
538     {
539         if ((ok = do_rfc1731(sock, "AUTHENTICATE", ctl->server.truename)))
540         {
541             /* SASL cancellation of authentication */
542             gen_send(sock, "*");
543             if(ctl->server.authenticate != A_ANY)
544                 return ok;
545         }
546         else
547             return ok;
548     }
549 #endif /* KERBEROS_V4 */
550
551     /*
552      * No such luck.  OK, now try the variants that mask your password
553      * in a challenge-response.
554      */
555
556     if ((ctl->server.authenticate == A_ANY && strstr(capabilities, "AUTH=CRAM-MD5"))
557         || ctl->server.authenticate == A_CRAM_MD5)
558     {
559         if ((ok = do_cram_md5 (sock, "AUTHENTICATE", ctl, NULL)))
560         {
561             if(ctl->server.authenticate != A_ANY)
562                 return ok;
563         }
564         else
565             return ok;
566     }
567
568 #ifdef OPIE_ENABLE
569     if ((ctl->server.authenticate == A_ANY 
570          || ctl->server.authenticate == A_OTP)
571         && strstr(capabilities, "AUTH=X-OTP")) {
572         if ((ok = do_otp(sock, "AUTHENTICATE", ctl)))
573         {
574             /* SASL cancellation of authentication */
575             gen_send(sock, "*");
576             if(ctl->server.authenticate != A_ANY)
577                 return ok;
578         } else {
579             return ok;
580         }
581     }
582 #else
583     if (ctl->server.authenticate == A_OTP)
584     {
585         report(stderr, 
586            GT_("Required OTP capability not compiled into fetchmail\n"));
587     }
588 #endif /* OPIE_ENABLE */
589
590 #ifdef NTLM_ENABLE
591     if ((ctl->server.authenticate == A_ANY 
592          || ctl->server.authenticate == A_NTLM) 
593         && strstr (capabilities, "AUTH=NTLM")) {
594         if ((ok = do_imap_ntlm(sock, ctl)))
595         {
596             if(ctl->server.authenticate != A_ANY)
597                 return ok;
598         }
599         else
600             return(ok);
601     }
602 #else
603     if (ctl->server.authenticate == A_NTLM)
604     {
605         report(stderr, 
606            GT_("Required NTLM capability not compiled into fetchmail\n"));
607     }
608 #endif /* NTLM_ENABLE */
609
610 #ifdef __UNUSED__       /* The Cyrus IMAP4rev1 server chokes on this */
611     /* this handles either AUTH=LOGIN or AUTH-LOGIN */
612     if ((imap_version >= IMAP4rev1) && (!strstr(capabilities, "LOGIN")))
613     {
614         report(stderr, 
615                GT_("Required LOGIN capability not supported by server\n"));
616     }
617 #endif /* __UNUSED__ */
618
619     /* 
620      * We're stuck with sending the password en clair.
621      * The reason for this odd-looking logic is that some
622      * servers return LOGINDISABLED even though login 
623      * actually works.  So arrange things in such a way that
624      * setting auth passwd makes it ignore this capability.
625      */
626     if((ctl->server.authenticate==A_ANY&&!strstr(capabilities,"LOGINDISABLED"))
627         || ctl->server.authenticate == A_PASSWORD)
628     {
629         /* these sizes guarantee no buffer overflow */
630         char *remotename, *password;
631         size_t rnl, pwl;
632         rnl = 2 * strlen(ctl->remotename) + 1;
633         pwl = 2 * strlen(ctl->password) + 1;
634         remotename = (char *)xmalloc(rnl);
635         password = (char *)xmalloc(pwl);
636
637         imap_canonicalize(remotename, ctl->remotename, rnl);
638         imap_canonicalize(password, ctl->password, pwl);
639
640         snprintf(shroud, sizeof (shroud), "\"%s\"", password);
641         ok = gen_transact(sock, "LOGIN \"%s\" \"%s\"", remotename, password);
642         memset(shroud, 0x55, sizeof(shroud));
643         shroud[0] = '\0';
644         memset(password, 0x55, strlen(password));
645         free(password);
646         free(remotename);
647         if (ok)
648         {
649             if(ctl->server.authenticate != A_ANY)
650                 return ok;
651         }
652         else
653             return(ok);
654     }
655
656     return(ok);
657 }
658
659 static int internal_expunge(int sock)
660 /* ship an expunge, resetting associated counters */
661 {
662     int ok;
663
664     actual_deletions = 0;
665
666     if ((ok = gen_transact(sock, "EXPUNGE")))
667         return(ok);
668
669     /* if there is a mismatch between the number of mails which should
670      * have been expunged and the number of mails actually expunged,
671      * another email client may be deleting mails. Quit here,
672      * otherwise fetchmail gets out-of-sync with the imap server,
673      * reports the wrong size to the SMTP server on MAIL FROM: and
674      * triggers a "message ... was not the expected length" error on
675      * every subsequent mail */
676     if (deletions > 0 && deletions != actual_deletions)
677     {
678         report(stderr,
679                 GT_("mail expunge mismatch (%d actual != %d expected)\n"),
680                 actual_deletions, deletions);
681         deletions = 0;
682         return(PS_ERROR);
683     }
684
685     expunged += deletions;
686     deletions = 0;
687
688 #ifdef IMAP_UID /* not used */
689     expunge_uids(ctl);
690 #endif /* IMAP_UID */
691
692     return(PS_SUCCESS);
693 }
694
695 static int imap_idle(int sock)
696 /* start an RFC2177 IDLE, or fake one if unsupported */
697 {
698     int ok;
699
700     saved_timeout = mytimeout;
701
702     if (has_idle) {
703         /* special timeout to terminate the IDLE and re-issue it
704          * at least every 28 minutes:
705          * (the server may have an inactivity timeout) */
706         mytimeout = idle_timeout = 1680; /* 28 min */
707         time(&idle_start_time);
708         stage = STAGE_IDLE;
709         /* enter IDLE mode */
710         ok = gen_transact(sock, "IDLE");
711
712         if (ok == PS_IDLETIMEOUT) {
713             /* send "DONE" continuation */
714             SockWrite(sock, "DONE\r\n", 6);
715             if (outlevel >= O_MONITOR)
716                 report(stdout, "IMAP> DONE\n");
717             /* reset stage and timeout here: we are not idling any more */
718             mytimeout = saved_timeout;
719             stage = STAGE_GETRANGE;
720             /* get OK IDLE message */
721             ok = imap_ok(sock, NULL);
722         }
723     } else {  /* no idle support, fake it */
724         /* Note: stage and timeout have not been changed here as NOOP
725          * does not idle */
726         ok = gen_transact(sock, "NOOP");
727
728         /* no error, but no new mail either */
729         if (ok == PS_SUCCESS && recentcount == 0)
730         {
731             /* There are some servers who do send new mail
732              * notification out of the blue. This is in compliance
733              * with RFC 2060 section 5.3. Wait for that with a low
734              * timeout */
735             mytimeout = idle_timeout = 28;
736             time(&idle_start_time);
737             stage = STAGE_IDLE;
738             /* We are waiting for notification; no tag needed */
739             tag[0] = '\0';
740             /* wait (briefly) for an unsolicited status update */
741             ok = imap_ok(sock, NULL);
742             if (ok == PS_IDLETIMEOUT) {
743                 /* no notification came; ok */
744                 ok = PS_SUCCESS;
745             }
746         }
747     }
748
749     /* restore normal timeout value */
750     set_timeout(0);
751     mytimeout = saved_timeout;
752     stage = STAGE_GETRANGE;
753
754     return(ok);
755 }
756
757 /* maximum number of numbers we can process in "SEARCH" response */
758 # define IMAP_SEARCH_MAX 1000
759
760 static int imap_search(int sock, struct query *ctl, int count)
761 /* search for unseen messages */
762 {
763     int ok, first, last;
764     char buf[MSGBUFSIZE+1], *cp;
765
766     /* Don't count deleted messages. Enabled only for IMAP4 servers or
767      * higher and only when keeping mails. This flag will have an
768      * effect only when user has marked some unread mails for deletion
769      * using another e-mail client. */
770     flag skipdeleted = (imap_version >= IMAP4) && ctl->keep;
771     const char *undeleted;
772
773     /* Skip range search if there are less than or equal to
774      * IMAP_SEARCH_MAX mails. */
775     flag skiprangesearch = (count <= IMAP_SEARCH_MAX);
776
777     /* startcount is higher than count so that if there are no
778      * unseen messages, imap_getsizes() will not need to do
779      * anything! */
780     startcount = count + 1;
781
782     for (first = 1, last = IMAP_SEARCH_MAX; first <= count; first += IMAP_SEARCH_MAX, last += IMAP_SEARCH_MAX)
783     {
784         if (last > count)
785             last = count;
786
787 restartsearch:
788         undeleted = (skipdeleted ? " UNDELETED" : "");
789         if (skiprangesearch)
790             gen_send(sock, "SEARCH UNSEEN%s", undeleted);
791         else if (last == first)
792             gen_send(sock, "SEARCH %d UNSEEN%s", last, undeleted);
793         else
794             gen_send(sock, "SEARCH %d:%d UNSEEN%s", first, last, undeleted);
795         while ((ok = imap_response(sock, buf)) == PS_UNTAGGED)
796         {
797             if ((cp = strstr(buf, "* SEARCH")))
798             {
799                 char    *ep;
800
801                 cp += 8;        /* skip "* SEARCH" */
802                 while (*cp && unseen < count)
803                 {
804                     /* skip whitespace */
805                     while (*cp && isspace((unsigned char)*cp))
806                         cp++;
807                     if (*cp) 
808                     {
809                         unsigned long um;
810
811                         errno = 0;
812                         um = strtoul(cp,&ep,10);
813                         if (errno == 0 && ep > cp
814                                 && um <= INT_MAX && um <= (unsigned)count)
815                         {
816                             unseen_messages[unseen++] = um;
817                             if (outlevel >= O_DEBUG)
818                                 report(stdout, GT_("%lu is unseen\n"), um);
819                             if (startcount > um)
820                                 startcount = um;
821                         }
822                         cp = ep;
823                     }
824                 }
825             }
826         }
827         /* if there is a protocol error on the first loop, try a
828          * different search command */
829         if (ok == PS_ERROR && first == 1)
830         {
831             if (skipdeleted)
832             {
833                 /* retry with "SEARCH 1:1000 UNSEEN" */
834                 skipdeleted = FALSE;
835                 goto restartsearch;
836             }
837             if (!skiprangesearch)
838             {
839                 /* retry with "SEARCH UNSEEN" */
840                 skiprangesearch = TRUE;
841                 goto restartsearch;
842             }
843             /* try with "FETCH 1:n FLAGS" */
844             goto fetchflags;
845         }
846         if (ok != PS_SUCCESS)
847             return(ok);
848         /* loop back only when searching in range */
849         if (skiprangesearch)
850             break;
851     }
852     return(PS_SUCCESS);
853
854 fetchflags:
855     if (count == 1)
856         gen_send(sock, "FETCH %d FLAGS", count);
857     else
858         gen_send(sock, "FETCH %d:%d FLAGS", 1, count);
859     while ((ok = imap_response(sock, buf)) == PS_UNTAGGED)
860     {
861         unsigned int num;
862         int consumed;
863
864         /* expected response format:
865          * IMAP< * 1 FETCH (FLAGS (\Seen))
866          * IMAP< * 2 FETCH (FLAGS (\Seen \Deleted))
867          * IMAP< * 3 FETCH (FLAGS ())
868          * IMAP< * 4 FETCH (FLAGS (\Recent))
869          * IMAP< * 5 FETCH (UID 10 FLAGS (\Recent))
870          */
871         if (unseen < count
872                 && sscanf(buf, "* %u %n", &num, &consumed) == 1
873                 && 0 == strncasecmp(buf+consumed, "FETCH", 5)
874                 && isspace((unsigned char)buf[consumed+5])
875                 && num >= 1 && num <= (unsigned)count
876                 && strstr(buf, "FLAGS ")
877                 && !strstr(buf, "\\SEEN")
878                 && !strstr(buf, "\\DELETED"))
879         {
880             unseen_messages[unseen++] = num;
881             if (outlevel >= O_DEBUG)
882                 report(stdout, GT_("%u is unseen\n"), num);
883             if (startcount > num)
884                 startcount = num;
885         }
886     }
887     return(ok);
888 }
889
890 static int imap_getrange(int sock, 
891                          struct query *ctl, 
892                          const char *folder, 
893                          int *countp, int *newp, int *bytes)
894 /* get range of messages to be fetched */
895 {
896     int ok;
897
898     /* find out how many messages are waiting */
899     *bytes = -1;
900
901     if (pass > 1)
902     {
903         /* deleted mails have already been expunged by
904          * end_mailbox_poll().
905          *
906          * recentcount is already set here by the last imap command which
907          * returned EXISTS on detecting new mail. if recentcount is 0, wait
908          * for new mail.
909          *
910          * this is a while loop because imap_idle() might return on other
911          * mailbox changes also */
912         while (recentcount == 0 && do_idle) {
913             smtp_close(ctl, 1);
914             ok = imap_idle(sock);
915             if (ok)
916             {
917                 report(stderr, GT_("re-poll failed\n"));
918                 return(ok);
919             }
920         }
921         /* if recentcount is 0, return no mail */
922         if (recentcount == 0)
923                 count = 0;
924         if (outlevel >= O_DEBUG)
925             report(stdout, ngettext("%d message waiting after re-poll\n",
926                                     "%d messages waiting after re-poll\n",
927                                     count), count);
928     }
929     else
930     {
931         oldcount = count = 0;
932         ok = gen_transact(sock, 
933                           check_only ? "EXAMINE \"%s\"" : "SELECT \"%s\"",
934                           folder ? folder : "INBOX");
935         /* imap_ok returns PS_LOCKBUSY for READ-ONLY folders,
936          * which we can safely use in fetchall keep only */
937         if (ok == PS_LOCKBUSY && ctl->fetchall && ctl-> keep)
938             ok = 0;
939
940         if (ok != 0)
941         {
942             report(stderr, GT_("mailbox selection failed\n"));
943             return(ok);
944         }
945         else if (outlevel >= O_DEBUG)
946             report(stdout, ngettext("%d message waiting after first poll\n",
947                                     "%d messages waiting after first poll\n",
948                                     count), count);
949
950         /*
951          * We should have an expunge here to
952          * a) avoid fetching deleted mails during 'fetchall'
953          * b) getting a wrong count of mails during 'no fetchall'
954          */
955         if (!check_only && !ctl->keep && count > 0)
956         {
957             ok = internal_expunge(sock);
958             if (ok)
959             {
960                 report(stderr, GT_("expunge failed\n"));
961                 return(ok);
962             }
963             if (outlevel >= O_DEBUG)
964                 report(stdout, ngettext("%d message waiting after expunge\n",
965                                         "%d messages waiting after expunge\n",
966                                         count), count);
967         }
968
969         if (count == 0 && do_idle)
970         {
971             /* no messages?  then we may need to idle until we get some */
972             while (count == 0) {
973                 ok = imap_idle(sock);
974                 if (ok)
975                 {
976                     report(stderr, GT_("re-poll failed\n"));
977                     return(ok);
978                 }
979             }
980             if (outlevel >= O_DEBUG)
981                 report(stdout, ngettext("%d message waiting after re-poll\n",
982                                         "%d messages waiting after re-poll\n",
983                                         count), count);
984         }
985     }
986
987     *countp = oldcount = count;
988     recentcount = 0;
989     startcount = 1;
990
991     /* OK, now get a count of unseen messages and their indices */
992     if (!ctl->fetchall && count > 0)
993     {
994         if (unseen_messages)
995             free(unseen_messages);
996         unseen_messages = (unsigned int *)xmalloc(count * sizeof(unsigned int));
997         memset(unseen_messages, 0, count * sizeof(unsigned int));
998         unseen = 0;
999
1000         ok = imap_search(sock, ctl, count);
1001         if (ok != 0)
1002         {
1003             report(stderr, GT_("search for unseen messages failed\n"));
1004             return(ok);
1005         }
1006
1007         if (outlevel >= O_DEBUG && unseen > 0)
1008             report(stdout, GT_("%u is first unseen\n"), startcount);
1009     } else
1010         unseen = -1;
1011
1012     *newp = unseen;
1013     expunged = 0;
1014     deletions = 0;
1015
1016     return(PS_SUCCESS);
1017 }
1018
1019 static int imap_getpartialsizes(int sock, int first, int last, int *sizes)
1020 /* capture the sizes of messages #first-#last */
1021 {
1022     char buf [MSGBUFSIZE+1];
1023     int ok;
1024
1025     /*
1026      * Some servers (as in, PMDF5.1-9.1 under OpenVMS 6.1)
1027      * won't accept 1:1 as valid set syntax.  Some implementors
1028      * should be taken out and shot for excessive anality.
1029      *
1030      * Microsoft Exchange (brain-dead piece of crap that it is) 
1031      * sometimes gets its knickers in a knot about bodiless messages.
1032      * You may see responses like this:
1033      *
1034      *  fetchmail: IMAP> A0004 FETCH 1:9 RFC822.SIZE
1035      *  fetchmail: IMAP< * 2 FETCH (RFC822.SIZE 1187)
1036      *  fetchmail: IMAP< * 3 FETCH (RFC822.SIZE 3954)
1037      *  fetchmail: IMAP< * 4 FETCH (RFC822.SIZE 1944)
1038      *  fetchmail: IMAP< * 5 FETCH (RFC822.SIZE 2933)
1039      *  fetchmail: IMAP< * 6 FETCH (RFC822.SIZE 1854)
1040      *  fetchmail: IMAP< * 7 FETCH (RFC822.SIZE 34054)
1041      *  fetchmail: IMAP< * 8 FETCH (RFC822.SIZE 5561)
1042      *  fetchmail: IMAP< * 9 FETCH (RFC822.SIZE 1101)
1043      *  fetchmail: IMAP< A0004 NO The requested item could not be found.
1044      *
1045      * This means message 1 has only headers.  For kicks and grins
1046      * you can telnet in and look:
1047      *  A003 FETCH 1 FULL
1048      *  A003 NO The requested item could not be found.
1049      *  A004 fetch 1 rfc822.header
1050      *  A004 NO The requested item could not be found.
1051      *  A006 FETCH 1 BODY
1052      *  * 1 FETCH (BODY ("TEXT" "PLAIN" ("CHARSET" "US-ASCII") NIL NIL "7BIT" 35 3))
1053      *  A006 OK FETCH completed.
1054      *
1055      * To get around this, we treat the final NO as success and count
1056      * on the fact that the sizes array has been preinitialized with a
1057      * known-bad size value.
1058      */
1059
1060     /* expunges change the fetch numbers */
1061     first -= expunged;
1062     last -= expunged;
1063
1064     if (last == first)
1065         gen_send(sock, "FETCH %d RFC822.SIZE", last);
1066     else if (last > first)
1067         gen_send(sock, "FETCH %d:%d RFC822.SIZE", first, last);
1068     else /* no unseen messages! */
1069         return(PS_SUCCESS);
1070     while ((ok = imap_response(sock, buf)) == PS_UNTAGGED)
1071     {
1072         unsigned int size;
1073         int num;
1074         int consumed;
1075         char *ptr;
1076
1077         /* expected response formats:
1078          * IMAP> A0005 FETCH 1 RFC822.SIZE
1079          * IMAP< * 1 FETCH (RFC822.SIZE 1187)
1080          * IMAP< * 1 FETCH (UID 16 RFC822.SIZE 1447)
1081          */
1082         if (sscanf(buf, "* %d %n", &num, &consumed) == 1
1083             && 0 == strncasecmp(buf + consumed, "FETCH", 5)
1084             && isspace((unsigned char)buf[consumed + 5])
1085                 && (ptr = strstr(buf, "RFC822.SIZE "))
1086                 && sscanf(ptr, "RFC822.SIZE %u", &size) == 1)
1087         {
1088             if (num >= first && num <= last)
1089                 sizes[num - first] = size;
1090             else
1091                 report(stderr,
1092                         GT_("Warning: ignoring bogus data for message sizes returned by the server.\n"));
1093         }
1094     }
1095     return(ok);
1096 }
1097
1098 static int imap_getsizes(int sock, int count, int *sizes)
1099 /* capture the sizes of all messages */
1100 {
1101     return imap_getpartialsizes(sock, 1, count, sizes);
1102 }
1103
1104 static int imap_is_old(int sock, struct query *ctl, int number)
1105 /* is the given message old? */
1106 {
1107     flag seen = TRUE;
1108     int i;
1109
1110     (void)sock;
1111     (void)ctl;
1112     /* 
1113      * Expunges change the fetch numbers, but unseen_messages contains
1114      * indices from before any expungees were done.  So neither the
1115      * argument nor the values in message_sequence need to be decremented.
1116      */
1117
1118     seen = TRUE;
1119     for (i = 0; i < unseen; i++)
1120         if (unseen_messages[i] == (unsigned)number)
1121         {
1122             seen = FALSE;
1123             break;
1124         }
1125
1126     return(seen);
1127 }
1128
1129 #if 0
1130 static char *skip_token(char *ptr)
1131 {
1132     while(isspace((unsigned char)*ptr)) ptr++;
1133     while(!isspace((unsigned char)*ptr) && !iscntrl((unsigned char)*ptr)) ptr++;
1134     while(isspace((unsigned char)*ptr)) ptr++;
1135     return(ptr);
1136 }
1137 #endif
1138
1139 static int imap_fetch_headers(int sock, struct query *ctl,int number,int *lenp)
1140 /* request headers of nth message */
1141 {
1142     char buf [MSGBUFSIZE+1];
1143     int num;
1144     int ok;
1145     char *ptr;
1146
1147     (void)ctl;
1148     /* expunges change the fetch numbers */
1149     number -= expunged;
1150
1151     /*
1152      * This is blessed by RFC1176, RFC1730, RFC2060.
1153      * According to the RFCs, it should *not* set the \Seen flag.
1154      */
1155     gen_send(sock, "FETCH %d RFC822.HEADER", number);
1156
1157     /* looking for FETCH response */
1158     if ((ok = imap_response(sock, buf)) == PS_UNTAGGED)
1159     {
1160                 int consumed;
1161         /* expected response formats:
1162          * IMAP> A0006 FETCH 1 RFC822.HEADER
1163          * IMAP< * 1 FETCH (RFC822.HEADER {1360}
1164          * IMAP< * 1 FETCH (UID 16 RFC822.HEADER {1360}
1165          * IMAP< * 1 FETCH (UID 16 RFC822.SIZE 4029 RFC822.HEADER {1360}
1166          */
1167         if (sscanf(buf, "* %d %n", &num, &consumed) == 1
1168             && 0 == strncasecmp(buf + consumed, "FETCH", 5)
1169             && isspace((unsigned char)buf[5+consumed])
1170                 && num == number
1171                 && (ptr = strstr(buf, "RFC822.HEADER"))
1172                 && sscanf(ptr, "RFC822.HEADER {%d}%n", lenp, &consumed) == 1
1173                 && ptr[consumed-1] == '}')
1174         {
1175             return(PS_SUCCESS);
1176         }
1177
1178         /* wait for a tagged response */
1179         imap_ok (sock, 0);
1180
1181         /* try to recover for some responses */
1182         if (!strncmp(buf, "* NO", 4) ||
1183                 !strncmp(buf, "* BAD", 5))
1184         {
1185             return(PS_TRANSIENT);
1186         }
1187
1188         /* a response which does not match any of the above */
1189         if (outlevel > O_SILENT)
1190             report(stderr, GT_("Incorrect FETCH response: %s.\n"), buf);
1191         return(PS_ERROR);
1192     }
1193     else if (ok == PS_SUCCESS)
1194     {
1195         /* an unexpected tagged response */
1196         if (outlevel > O_SILENT)
1197             report(stderr, GT_("Incorrect FETCH response: %s.\n"), buf);
1198         return(PS_ERROR);
1199     }
1200     return(ok);
1201 }
1202
1203 static int imap_fetch_body(int sock, struct query *ctl, int number, int *lenp)
1204 /* request body of nth message */
1205 {
1206     char buf [MSGBUFSIZE+1], *cp;
1207     int num;
1208
1209     (void)ctl;
1210     /* expunges change the fetch numbers */
1211     number -= expunged;
1212
1213     /*
1214      * If we're using IMAP4, we can fetch the message without setting its
1215      * seen flag.  This is good!  It means that if the protocol exchange
1216      * craps out during the message, it will still be marked `unseen' on
1217      * the server.
1218      *
1219      * According to RFC2060, and Mark Crispin the IMAP maintainer,
1220      * FETCH %d BODY[TEXT] and RFC822.TEXT are "functionally 
1221      * equivalent".  However, we know of at least one server that
1222      * treats them differently in the presence of MIME attachments;
1223      * the latter form downloads the attachment, the former does not.
1224      * The server is InterChange, and the fool who implemented this
1225      * misfeature ought to be strung up by his thumbs.  
1226      *
1227      * When I tried working around this by disabling use of the 4rev1 form,
1228      * I found that doing this breaks operation with M$ Exchange.
1229      * Annoyingly enough, Exchange's refusal to cope is technically legal
1230      * under RFC2062.  Trust Microsoft, the Great Enemy of interoperability
1231      * standards, to find a way to make standards compliance irritating....
1232      */
1233     switch (imap_version)
1234     {
1235     case IMAP4rev1:     /* RFC 2060 */
1236         gen_send(sock, "FETCH %d BODY.PEEK[TEXT]", number);
1237         break;
1238
1239     case IMAP4:         /* RFC 1730 */
1240         gen_send(sock, "FETCH %d RFC822.TEXT.PEEK", number);
1241         break;
1242
1243     default:            /* RFC 1176 */
1244         gen_send(sock, "FETCH %d RFC822.TEXT", number);
1245         break;
1246     }
1247
1248     /* looking for FETCH response */
1249     do {
1250         int     ok;
1251
1252         if ((ok = gen_recv(sock, buf, sizeof(buf))))
1253             return(ok);
1254     } while
1255         (!strstr(buf+4, "FETCH") || sscanf(buf+2, "%d", &num) != 1);
1256
1257     if (num != number)
1258         return(PS_ERROR);
1259
1260     /* Understand "NIL" as length => no body present
1261      * (MS Exchange, BerliOS Bug #11980) */
1262     if (strstr(buf+10, "NIL)")) {
1263             *lenp = 0;
1264             return PS_SUCCESS;
1265     }
1266
1267     /*
1268      * Try to extract a length from the FETCH response.  RFC2060 requires
1269      * it to be present, but at least one IMAP server (Novell GroupWise)
1270      * botches this.  The overflow check is needed because of a broken
1271      * server called dbmail that returns huge garbage lengths.
1272      */
1273     if ((cp = strchr(buf, '{'))) {
1274         long l; char *t;
1275         errno = 0;
1276         ++ cp;
1277         l = strtol(cp, &t, 10);
1278         if (errno || t == cp || (t && !strchr(t, '}')) /* parse error */
1279                     || l < 0 || l > INT_MAX /* range check */) {
1280             *lenp = -1;
1281         } else {
1282             *lenp = l;
1283         }
1284     } else {
1285         *lenp = -1;     /* missing length part in FETCH reponse */
1286     }
1287
1288     return PS_SUCCESS;
1289 }
1290
1291 static int imap_trail(int sock, struct query *ctl, const char *tag)
1292 /* discard tail of FETCH response after reading message text */
1293 {
1294     /* expunges change the fetch numbers */
1295     /* number -= expunged; */
1296
1297     (void)ctl;
1298     (void)tag;
1299
1300     return imap_ok(sock, NULL);
1301 }
1302
1303 static int imap_delete(int sock, struct query *ctl, int number)
1304 /* set delete flag for given message */
1305 {
1306     int ok;
1307
1308     (void)ctl;
1309     /* expunges change the fetch numbers */
1310     number -= expunged;
1311
1312     /*
1313      * Use SILENT if possible as a minor throughput optimization.
1314      * Note: this has been dropped from IMAP4rev1.
1315      *
1316      * We set Seen because there are some IMAP servers (notably HP
1317      * OpenMail) that do message-receipt DSNs, but only when the seen
1318      * bit is set.  This is the appropriate time -- we get here right
1319      * after the local SMTP response that says delivery was
1320      * successful.
1321      */
1322     if ((ok = gen_transact(sock,
1323                         imap_version == IMAP4 
1324                                 ? "STORE %d +FLAGS.SILENT (\\Seen \\Deleted)"
1325                                 : "STORE %d +FLAGS (\\Seen \\Deleted)", 
1326                         number)))
1327         return(ok);
1328     else
1329         deletions++;
1330
1331     /*
1332      * We do an expunge after expunge_period messages, rather than
1333      * just before quit, so that a line hit during a long session
1334      * won't result in lots of messages being fetched again during
1335      * the next session.
1336      */
1337     if (NUM_NONZERO(expunge_period) && (deletions % expunge_period) == 0)
1338     {
1339         if ((ok = internal_expunge(sock)))
1340             return(ok);
1341     }
1342
1343     return(PS_SUCCESS);
1344 }
1345
1346 static int imap_mark_seen(int sock, struct query *ctl, int number)
1347 /* mark the given message as seen */
1348 {
1349     (void)ctl;
1350
1351     /* expunges change the message numbers */
1352     number -= expunged;
1353
1354     return(gen_transact(sock,
1355         imap_version == IMAP4
1356         ? "STORE %d +FLAGS.SILENT (\\Seen)"
1357         : "STORE %d +FLAGS (\\Seen)",
1358         number));
1359 }
1360
1361 static int imap_end_mailbox_poll(int sock, struct query *ctl)
1362 /* cleanup mailbox before we idle or switch to another one */
1363 {
1364     (void)ctl;
1365     if (deletions)
1366         internal_expunge(sock);
1367     return(PS_SUCCESS);
1368 }
1369
1370 static int imap_logout(int sock, struct query *ctl)
1371 /* send logout command */
1372 {
1373     (void)ctl;
1374     /* if any un-expunged deletions remain, ship an expunge now */
1375     if (deletions)
1376         internal_expunge(sock);
1377
1378 #ifdef USE_SEARCH
1379     /* Memory clean-up */
1380     if (unseen_messages)
1381         free(unseen_messages);
1382 #endif /* USE_SEARCH */
1383
1384     return(gen_transact(sock, "LOGOUT"));
1385 }
1386
1387 static const struct method imap =
1388 {
1389     "IMAP",             /* Internet Message Access Protocol */
1390     "imap",             /* service (plain and TLS) */
1391     "imaps",            /* service (SSL) */
1392     TRUE,               /* this is a tagged protocol */
1393     FALSE,              /* no message delimiter */
1394     imap_ok,            /* parse command response */
1395     imap_getauth,       /* get authorization */
1396     imap_getrange,      /* query range of messages */
1397     imap_getsizes,      /* get sizes of messages (used for ESMTP SIZE option) */
1398     imap_getpartialsizes,       /* get sizes of subset of messages (used for ESMTP SIZE option) */
1399     imap_is_old,        /* no UID check */
1400     imap_fetch_headers, /* request given message headers */
1401     imap_fetch_body,    /* request given message body */
1402     imap_trail,         /* eat message trailer */
1403     imap_delete,        /* delete the message */
1404     imap_mark_seen,     /* how to mark a message as seen */
1405     imap_end_mailbox_poll,      /* end-of-mailbox processing */
1406     imap_logout,        /* expunge and exit */
1407     TRUE,               /* yes, we can re-poll */
1408 };
1409
1410 int doIMAP(struct query *ctl)
1411 /* retrieve messages using IMAP Version 2bis or Version 4 */
1412 {
1413     return(do_protocol(ctl, &imap));
1414 }
1415
1416 /* imap.c ends here */