]> Pileus Git - ~andy/fetchmail/blob - imap.c
Factor out common NTLM code.
[~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 #ifdef SSL_ENABLE
401     int got_tls = 0;
402 #endif
403     (void)greeting;
404
405     /*
406      * Assumption: expunges are cheap, so we want to do them
407      * after every message unless user said otherwise.
408      */
409     if (NUM_SPECIFIED(ctl->expunge))
410         expunge_period = NUM_VALUE_OUT(ctl->expunge);
411     else
412         expunge_period = 1;
413
414     capa_probe(sock, ctl);
415
416     /* 
417      * If either (a) we saw a PREAUTH token in the greeting, or
418      * (b) the user specified ssh preauthentication, then we're done.
419      */
420     if (preauth || ctl->server.authenticate == A_SSH)
421     {
422         preauth = FALSE;  /* reset for the next session */
423         return(PS_SUCCESS);
424     }
425
426 #ifdef SSL_ENABLE
427     if (maybe_tls(ctl)) {
428         char *commonname;
429
430         commonname = ctl->server.pollname;
431         if (ctl->server.via)
432             commonname = ctl->server.via;
433         if (ctl->sslcommonname)
434             commonname = ctl->sslcommonname;
435
436         if (strstr(capabilities, "STARTTLS"))
437         {
438             /* Use "tls1" rather than ctl->sslproto because tls1 is the only
439              * protocol that will work with STARTTLS.  Don't need to worry
440              * whether TLS is mandatory or opportunistic unless SSLOpen() fails
441              * (see below). */
442             if (gen_transact(sock, "STARTTLS") == PS_SUCCESS
443                     && SSLOpen(sock, ctl->sslcert, ctl->sslkey, "tls1", ctl->sslcertck,
444                         ctl->sslcertfile, ctl->sslcertpath, ctl->sslfingerprint, commonname,
445                         ctl->server.pollname, &ctl->remotename) != -1)
446             {
447                 /*
448                  * RFC 2595 says this:
449                  *
450                  * "Once TLS has been started, the client MUST discard cached
451                  * information about server capabilities and SHOULD re-issue the
452                  * CAPABILITY command.  This is necessary to protect against
453                  * man-in-the-middle attacks which alter the capabilities list prior
454                  * to STARTTLS.  The server MAY advertise different capabilities
455                  * after STARTTLS."
456                  *
457                  * Now that we're confident in our TLS connection we can
458                  * guarantee a secure capability re-probe.
459                  */
460                 got_tls = 1;
461                 capa_probe(sock, ctl);
462                 if (outlevel >= O_VERBOSE)
463                 {
464                     report(stdout, GT_("%s: upgrade to TLS succeeded.\n"), commonname);
465                 }
466             }
467         }
468
469         if (!got_tls) {
470             if (must_tls(ctl)) {
471                 /* Config required TLS but we couldn't guarantee it, so we must
472                  * stop. */
473                 report(stderr, GT_("%s: upgrade to TLS failed.\n"), commonname);
474                 return PS_SOCKET;
475             } else {
476                 if (outlevel >= O_VERBOSE) {
477                     report(stdout, GT_("%s: opportunistic upgrade to TLS failed, trying to continue\n"), commonname);
478                 }
479                 /* We don't know whether the connection is in a working state, so
480                  * test by issuing a NOOP. */
481                 if (gen_transact(sock, "NOOP") != PS_SUCCESS) {
482                     /* Not usable.  Empty sslproto to force an unencrypted
483                      * connection on the next attempt, and repoll. */
484                     ctl->sslproto = xstrdup("");
485                     return PS_REPOLL;
486                 }
487                 /* Usable.  Proceed with authenticating insecurely. */
488             }
489         }
490     }
491 #endif /* SSL_ENABLE */
492
493     /*
494      * Time to authenticate the user.
495      * Try the protocol variants that don't require passwords first.
496      */
497     ok = PS_AUTHFAIL;
498
499     /* Yahoo hack - we'll just try ID if it was offered by the server,
500      * and IGNORE errors. */
501     {
502         char *tmp = strstr(capabilities, " ID");
503         if (tmp && !isalnum((unsigned char)tmp[3]) && strstr(ctl->server.via ? ctl->server.via : ctl->server.pollname, "yahoo.com")) {
504                 (void)gen_transact(sock, "ID (\"guid\" \"1\")");
505         }
506     }
507
508     if ((ctl->server.authenticate == A_ANY 
509          || ctl->server.authenticate == A_EXTERNAL)
510         && strstr(capabilities, "AUTH=EXTERNAL"))
511     {
512         ok = do_authcert(sock, "AUTHENTICATE", ctl->remotename);
513         if (ok)
514         {
515             /* SASL cancellation of authentication */
516             gen_send(sock, "*");
517             if (ctl->server.authenticate != A_ANY)
518                 return ok;
519         } else {
520             return ok;
521         }
522     }
523
524 #ifdef GSSAPI
525     if (((ctl->server.authenticate == A_ANY && check_gss_creds("imap", ctl->server.truename) == PS_SUCCESS)
526          || ctl->server.authenticate == A_GSSAPI)
527         && strstr(capabilities, "AUTH=GSSAPI"))
528     {
529         if ((ok = do_gssauth(sock, "AUTHENTICATE", "imap",
530                         ctl->server.truename, ctl->remotename)))
531         {
532             if (ctl->server.authenticate != A_ANY)
533                 return ok;
534         } else  {
535             return ok;
536         }
537     }
538 #endif /* GSSAPI */
539
540 #ifdef KERBEROS_V4
541     if ((ctl->server.authenticate == A_ANY 
542          || ctl->server.authenticate == A_KERBEROS_V4
543          || ctl->server.authenticate == A_KERBEROS_V5) 
544         && strstr(capabilities, "AUTH=KERBEROS_V4"))
545     {
546         if ((ok = do_rfc1731(sock, "AUTHENTICATE", ctl->server.truename)))
547         {
548             /* SASL cancellation of authentication */
549             gen_send(sock, "*");
550             if(ctl->server.authenticate != A_ANY)
551                 return ok;
552         }
553         else
554             return ok;
555     }
556 #endif /* KERBEROS_V4 */
557
558     /*
559      * No such luck.  OK, now try the variants that mask your password
560      * in a challenge-response.
561      */
562
563     if ((ctl->server.authenticate == A_ANY && strstr(capabilities, "AUTH=CRAM-MD5"))
564         || ctl->server.authenticate == A_CRAM_MD5)
565     {
566         if ((ok = do_cram_md5 (sock, "AUTHENTICATE", ctl, NULL)))
567         {
568             if(ctl->server.authenticate != A_ANY)
569                 return ok;
570         }
571         else
572             return ok;
573     }
574
575 #ifdef OPIE_ENABLE
576     if ((ctl->server.authenticate == A_ANY 
577          || ctl->server.authenticate == A_OTP)
578         && strstr(capabilities, "AUTH=X-OTP")) {
579         if ((ok = do_otp(sock, "AUTHENTICATE", ctl)))
580         {
581             /* SASL cancellation of authentication */
582             gen_send(sock, "*");
583             if(ctl->server.authenticate != A_ANY)
584                 return ok;
585         } else {
586             return ok;
587         }
588     }
589 #else
590     if (ctl->server.authenticate == A_OTP)
591     {
592         report(stderr, 
593            GT_("Required OTP capability not compiled into fetchmail\n"));
594     }
595 #endif /* OPIE_ENABLE */
596
597 #ifdef NTLM_ENABLE
598     if ((ctl->server.authenticate == A_ANY 
599          || ctl->server.authenticate == A_NTLM) 
600         && strstr (capabilities, "AUTH=NTLM")) {
601         if ((ok = do_imap_ntlm(sock, ctl)))
602         {
603             if(ctl->server.authenticate != A_ANY)
604                 return ok;
605         }
606         else
607             return(ok);
608     }
609 #else
610     if (ctl->server.authenticate == A_NTLM)
611     {
612         report(stderr, 
613            GT_("Required NTLM capability not compiled into fetchmail\n"));
614     }
615 #endif /* NTLM_ENABLE */
616
617 #ifdef __UNUSED__       /* The Cyrus IMAP4rev1 server chokes on this */
618     /* this handles either AUTH=LOGIN or AUTH-LOGIN */
619     if ((imap_version >= IMAP4rev1) && (!strstr(capabilities, "LOGIN")))
620     {
621         report(stderr, 
622                GT_("Required LOGIN capability not supported by server\n"));
623     }
624 #endif /* __UNUSED__ */
625
626     /* 
627      * We're stuck with sending the password en clair.
628      * The reason for this odd-looking logic is that some
629      * servers return LOGINDISABLED even though login 
630      * actually works.  So arrange things in such a way that
631      * setting auth passwd makes it ignore this capability.
632      */
633     if((ctl->server.authenticate==A_ANY&&!strstr(capabilities,"LOGINDISABLED"))
634         || ctl->server.authenticate == A_PASSWORD)
635     {
636         /* these sizes guarantee no buffer overflow */
637         char *remotename, *password;
638         size_t rnl, pwl;
639         rnl = 2 * strlen(ctl->remotename) + 1;
640         pwl = 2 * strlen(ctl->password) + 1;
641         remotename = (char *)xmalloc(rnl);
642         password = (char *)xmalloc(pwl);
643
644         imap_canonicalize(remotename, ctl->remotename, rnl);
645         imap_canonicalize(password, ctl->password, pwl);
646
647         snprintf(shroud, sizeof (shroud), "\"%s\"", password);
648         ok = gen_transact(sock, "LOGIN \"%s\" \"%s\"", remotename, password);
649         memset(shroud, 0x55, sizeof(shroud));
650         shroud[0] = '\0';
651         memset(password, 0x55, strlen(password));
652         free(password);
653         free(remotename);
654         if (ok)
655         {
656             if(ctl->server.authenticate != A_ANY)
657                 return ok;
658         }
659         else
660             return(ok);
661     }
662
663     return(ok);
664 }
665
666 static int internal_expunge(int sock)
667 /* ship an expunge, resetting associated counters */
668 {
669     int ok;
670
671     actual_deletions = 0;
672
673     if ((ok = gen_transact(sock, "EXPUNGE")))
674         return(ok);
675
676     /* if there is a mismatch between the number of mails which should
677      * have been expunged and the number of mails actually expunged,
678      * another email client may be deleting mails. Quit here,
679      * otherwise fetchmail gets out-of-sync with the imap server,
680      * reports the wrong size to the SMTP server on MAIL FROM: and
681      * triggers a "message ... was not the expected length" error on
682      * every subsequent mail */
683     if (deletions > 0 && deletions != actual_deletions)
684     {
685         report(stderr,
686                 GT_("mail expunge mismatch (%d actual != %d expected)\n"),
687                 actual_deletions, deletions);
688         deletions = 0;
689         return(PS_ERROR);
690     }
691
692     expunged += deletions;
693     deletions = 0;
694
695 #ifdef IMAP_UID /* not used */
696     expunge_uids(ctl);
697 #endif /* IMAP_UID */
698
699     return(PS_SUCCESS);
700 }
701
702 static int imap_idle(int sock)
703 /* start an RFC2177 IDLE, or fake one if unsupported */
704 {
705     int ok;
706
707     saved_timeout = mytimeout;
708
709     if (has_idle) {
710         /* special timeout to terminate the IDLE and re-issue it
711          * at least every 28 minutes:
712          * (the server may have an inactivity timeout) */
713         mytimeout = idle_timeout = 1680; /* 28 min */
714         time(&idle_start_time);
715         stage = STAGE_IDLE;
716         /* enter IDLE mode */
717         ok = gen_transact(sock, "IDLE");
718
719         if (ok == PS_IDLETIMEOUT) {
720             /* send "DONE" continuation */
721             SockWrite(sock, "DONE\r\n", 6);
722             if (outlevel >= O_MONITOR)
723                 report(stdout, "IMAP> DONE\n");
724             /* reset stage and timeout here: we are not idling any more */
725             mytimeout = saved_timeout;
726             stage = STAGE_GETRANGE;
727             /* get OK IDLE message */
728             ok = imap_ok(sock, NULL);
729         }
730     } else {  /* no idle support, fake it */
731         /* Note: stage and timeout have not been changed here as NOOP
732          * does not idle */
733         ok = gen_transact(sock, "NOOP");
734
735         /* no error, but no new mail either */
736         if (ok == PS_SUCCESS && recentcount == 0)
737         {
738             /* There are some servers who do send new mail
739              * notification out of the blue. This is in compliance
740              * with RFC 2060 section 5.3. Wait for that with a low
741              * timeout */
742             mytimeout = idle_timeout = 28;
743             time(&idle_start_time);
744             stage = STAGE_IDLE;
745             /* We are waiting for notification; no tag needed */
746             tag[0] = '\0';
747             /* wait (briefly) for an unsolicited status update */
748             ok = imap_ok(sock, NULL);
749             if (ok == PS_IDLETIMEOUT) {
750                 /* no notification came; ok */
751                 ok = PS_SUCCESS;
752             }
753         }
754     }
755
756     /* restore normal timeout value */
757     set_timeout(0);
758     mytimeout = saved_timeout;
759     stage = STAGE_GETRANGE;
760
761     return(ok);
762 }
763
764 /* maximum number of numbers we can process in "SEARCH" response */
765 # define IMAP_SEARCH_MAX 1000
766
767 static int imap_search(int sock, struct query *ctl, int count)
768 /* search for unseen messages */
769 {
770     int ok, first, last;
771     char buf[MSGBUFSIZE+1], *cp;
772
773     /* Don't count deleted messages. Enabled only for IMAP4 servers or
774      * higher and only when keeping mails. This flag will have an
775      * effect only when user has marked some unread mails for deletion
776      * using another e-mail client. */
777     flag skipdeleted = (imap_version >= IMAP4) && ctl->keep;
778     const char *undeleted;
779
780     /* Skip range search if there are less than or equal to
781      * IMAP_SEARCH_MAX mails. */
782     flag skiprangesearch = (count <= IMAP_SEARCH_MAX);
783
784     /* startcount is higher than count so that if there are no
785      * unseen messages, imap_getsizes() will not need to do
786      * anything! */
787     startcount = count + 1;
788
789     for (first = 1, last = IMAP_SEARCH_MAX; first <= count; first += IMAP_SEARCH_MAX, last += IMAP_SEARCH_MAX)
790     {
791         if (last > count)
792             last = count;
793
794 restartsearch:
795         undeleted = (skipdeleted ? " UNDELETED" : "");
796         if (skiprangesearch)
797             gen_send(sock, "SEARCH UNSEEN%s", undeleted);
798         else if (last == first)
799             gen_send(sock, "SEARCH %d UNSEEN%s", last, undeleted);
800         else
801             gen_send(sock, "SEARCH %d:%d UNSEEN%s", first, last, undeleted);
802         while ((ok = imap_response(sock, buf)) == PS_UNTAGGED)
803         {
804             if ((cp = strstr(buf, "* SEARCH")))
805             {
806                 char    *ep;
807
808                 cp += 8;        /* skip "* SEARCH" */
809                 while (*cp && unseen < count)
810                 {
811                     /* skip whitespace */
812                     while (*cp && isspace((unsigned char)*cp))
813                         cp++;
814                     if (*cp) 
815                     {
816                         unsigned long um;
817
818                         errno = 0;
819                         um = strtoul(cp,&ep,10);
820                         if (errno == 0 && ep > cp
821                                 && um <= INT_MAX && um <= (unsigned)count)
822                         {
823                             unseen_messages[unseen++] = um;
824                             if (outlevel >= O_DEBUG)
825                                 report(stdout, GT_("%lu is unseen\n"), um);
826                             if (startcount > um)
827                                 startcount = um;
828                         }
829                         cp = ep;
830                     }
831                 }
832             }
833         }
834         /* if there is a protocol error on the first loop, try a
835          * different search command */
836         if (ok == PS_ERROR && first == 1)
837         {
838             if (skipdeleted)
839             {
840                 /* retry with "SEARCH 1:1000 UNSEEN" */
841                 skipdeleted = FALSE;
842                 goto restartsearch;
843             }
844             if (!skiprangesearch)
845             {
846                 /* retry with "SEARCH UNSEEN" */
847                 skiprangesearch = TRUE;
848                 goto restartsearch;
849             }
850             /* try with "FETCH 1:n FLAGS" */
851             goto fetchflags;
852         }
853         if (ok != PS_SUCCESS)
854             return(ok);
855         /* loop back only when searching in range */
856         if (skiprangesearch)
857             break;
858     }
859     return(PS_SUCCESS);
860
861 fetchflags:
862     if (count == 1)
863         gen_send(sock, "FETCH %d FLAGS", count);
864     else
865         gen_send(sock, "FETCH %d:%d FLAGS", 1, count);
866     while ((ok = imap_response(sock, buf)) == PS_UNTAGGED)
867     {
868         unsigned int num;
869         int consumed;
870
871         /* expected response format:
872          * IMAP< * 1 FETCH (FLAGS (\Seen))
873          * IMAP< * 2 FETCH (FLAGS (\Seen \Deleted))
874          * IMAP< * 3 FETCH (FLAGS ())
875          * IMAP< * 4 FETCH (FLAGS (\Recent))
876          * IMAP< * 5 FETCH (UID 10 FLAGS (\Recent))
877          */
878         if (unseen < count
879                 && sscanf(buf, "* %u %n", &num, &consumed) == 1
880                 && 0 == strncasecmp(buf+consumed, "FETCH", 5)
881                 && isspace((unsigned char)buf[consumed+5])
882                 && num >= 1 && num <= (unsigned)count
883                 && strstr(buf, "FLAGS ")
884                 && !strstr(buf, "\\SEEN")
885                 && !strstr(buf, "\\DELETED"))
886         {
887             unseen_messages[unseen++] = num;
888             if (outlevel >= O_DEBUG)
889                 report(stdout, GT_("%u is unseen\n"), num);
890             if (startcount > num)
891                 startcount = num;
892         }
893     }
894     return(ok);
895 }
896
897 static int imap_getrange(int sock, 
898                          struct query *ctl, 
899                          const char *folder, 
900                          int *countp, int *newp, int *bytes)
901 /* get range of messages to be fetched */
902 {
903     int ok;
904
905     /* find out how many messages are waiting */
906     *bytes = -1;
907
908     if (pass > 1)
909     {
910         /* deleted mails have already been expunged by
911          * end_mailbox_poll().
912          *
913          * recentcount is already set here by the last imap command which
914          * returned EXISTS on detecting new mail. if recentcount is 0, wait
915          * for new mail.
916          *
917          * this is a while loop because imap_idle() might return on other
918          * mailbox changes also */
919         while (recentcount == 0 && do_idle) {
920             smtp_close(ctl, 1);
921             ok = imap_idle(sock);
922             if (ok)
923             {
924                 report(stderr, GT_("re-poll failed\n"));
925                 return(ok);
926             }
927         }
928         /* if recentcount is 0, return no mail */
929         if (recentcount == 0)
930                 count = 0;
931         if (outlevel >= O_DEBUG)
932             report(stdout, ngettext("%d message waiting after re-poll\n",
933                                     "%d messages waiting after re-poll\n",
934                                     count), count);
935     }
936     else
937     {
938         oldcount = count = 0;
939         ok = gen_transact(sock, 
940                           check_only ? "EXAMINE \"%s\"" : "SELECT \"%s\"",
941                           folder ? folder : "INBOX");
942         /* imap_ok returns PS_LOCKBUSY for READ-ONLY folders,
943          * which we can safely use in fetchall keep only */
944         if (ok == PS_LOCKBUSY && ctl->fetchall && ctl-> keep)
945             ok = 0;
946
947         if (ok != 0)
948         {
949             report(stderr, GT_("mailbox selection failed\n"));
950             return(ok);
951         }
952         else if (outlevel >= O_DEBUG)
953             report(stdout, ngettext("%d message waiting after first poll\n",
954                                     "%d messages waiting after first poll\n",
955                                     count), count);
956
957         /*
958          * We should have an expunge here to
959          * a) avoid fetching deleted mails during 'fetchall'
960          * b) getting a wrong count of mails during 'no fetchall'
961          */
962         if (!check_only && !ctl->keep && count > 0)
963         {
964             ok = internal_expunge(sock);
965             if (ok)
966             {
967                 report(stderr, GT_("expunge failed\n"));
968                 return(ok);
969             }
970             if (outlevel >= O_DEBUG)
971                 report(stdout, ngettext("%d message waiting after expunge\n",
972                                         "%d messages waiting after expunge\n",
973                                         count), count);
974         }
975
976         if (count == 0 && do_idle)
977         {
978             /* no messages?  then we may need to idle until we get some */
979             while (count == 0) {
980                 ok = imap_idle(sock);
981                 if (ok)
982                 {
983                     report(stderr, GT_("re-poll failed\n"));
984                     return(ok);
985                 }
986             }
987             if (outlevel >= O_DEBUG)
988                 report(stdout, ngettext("%d message waiting after re-poll\n",
989                                         "%d messages waiting after re-poll\n",
990                                         count), count);
991         }
992     }
993
994     *countp = oldcount = count;
995     recentcount = 0;
996     startcount = 1;
997
998     /* OK, now get a count of unseen messages and their indices */
999     if (!ctl->fetchall && count > 0)
1000     {
1001         if (unseen_messages)
1002             free(unseen_messages);
1003         unseen_messages = (unsigned int *)xmalloc(count * sizeof(unsigned int));
1004         memset(unseen_messages, 0, count * sizeof(unsigned int));
1005         unseen = 0;
1006
1007         ok = imap_search(sock, ctl, count);
1008         if (ok != 0)
1009         {
1010             report(stderr, GT_("search for unseen messages failed\n"));
1011             return(ok);
1012         }
1013
1014         if (outlevel >= O_DEBUG && unseen > 0)
1015             report(stdout, GT_("%u is first unseen\n"), startcount);
1016     } else
1017         unseen = -1;
1018
1019     *newp = unseen;
1020     expunged = 0;
1021     deletions = 0;
1022
1023     return(PS_SUCCESS);
1024 }
1025
1026 static int imap_getpartialsizes(int sock, int first, int last, int *sizes)
1027 /* capture the sizes of messages #first-#last */
1028 {
1029     char buf [MSGBUFSIZE+1];
1030     int ok;
1031
1032     /*
1033      * Some servers (as in, PMDF5.1-9.1 under OpenVMS 6.1)
1034      * won't accept 1:1 as valid set syntax.  Some implementors
1035      * should be taken out and shot for excessive anality.
1036      *
1037      * Microsoft Exchange (brain-dead piece of crap that it is) 
1038      * sometimes gets its knickers in a knot about bodiless messages.
1039      * You may see responses like this:
1040      *
1041      *  fetchmail: IMAP> A0004 FETCH 1:9 RFC822.SIZE
1042      *  fetchmail: IMAP< * 2 FETCH (RFC822.SIZE 1187)
1043      *  fetchmail: IMAP< * 3 FETCH (RFC822.SIZE 3954)
1044      *  fetchmail: IMAP< * 4 FETCH (RFC822.SIZE 1944)
1045      *  fetchmail: IMAP< * 5 FETCH (RFC822.SIZE 2933)
1046      *  fetchmail: IMAP< * 6 FETCH (RFC822.SIZE 1854)
1047      *  fetchmail: IMAP< * 7 FETCH (RFC822.SIZE 34054)
1048      *  fetchmail: IMAP< * 8 FETCH (RFC822.SIZE 5561)
1049      *  fetchmail: IMAP< * 9 FETCH (RFC822.SIZE 1101)
1050      *  fetchmail: IMAP< A0004 NO The requested item could not be found.
1051      *
1052      * This means message 1 has only headers.  For kicks and grins
1053      * you can telnet in and look:
1054      *  A003 FETCH 1 FULL
1055      *  A003 NO The requested item could not be found.
1056      *  A004 fetch 1 rfc822.header
1057      *  A004 NO The requested item could not be found.
1058      *  A006 FETCH 1 BODY
1059      *  * 1 FETCH (BODY ("TEXT" "PLAIN" ("CHARSET" "US-ASCII") NIL NIL "7BIT" 35 3))
1060      *  A006 OK FETCH completed.
1061      *
1062      * To get around this, we treat the final NO as success and count
1063      * on the fact that the sizes array has been preinitialized with a
1064      * known-bad size value.
1065      */
1066
1067     /* expunges change the fetch numbers */
1068     first -= expunged;
1069     last -= expunged;
1070
1071     if (last == first)
1072         gen_send(sock, "FETCH %d RFC822.SIZE", last);
1073     else if (last > first)
1074         gen_send(sock, "FETCH %d:%d RFC822.SIZE", first, last);
1075     else /* no unseen messages! */
1076         return(PS_SUCCESS);
1077     while ((ok = imap_response(sock, buf)) == PS_UNTAGGED)
1078     {
1079         unsigned int size;
1080         int num;
1081         int consumed;
1082         char *ptr;
1083
1084         /* expected response formats:
1085          * IMAP> A0005 FETCH 1 RFC822.SIZE
1086          * IMAP< * 1 FETCH (RFC822.SIZE 1187)
1087          * IMAP< * 1 FETCH (UID 16 RFC822.SIZE 1447)
1088          */
1089         if (sscanf(buf, "* %d %n", &num, &consumed) == 1
1090             && 0 == strncasecmp(buf + consumed, "FETCH", 5)
1091             && isspace((unsigned char)buf[consumed + 5])
1092                 && (ptr = strstr(buf, "RFC822.SIZE "))
1093                 && sscanf(ptr, "RFC822.SIZE %u", &size) == 1)
1094         {
1095             if (num >= first && num <= last)
1096                 sizes[num - first] = size;
1097             else
1098                 report(stderr,
1099                         GT_("Warning: ignoring bogus data for message sizes returned by the server.\n"));
1100         }
1101     }
1102     return(ok);
1103 }
1104
1105 static int imap_getsizes(int sock, int count, int *sizes)
1106 /* capture the sizes of all messages */
1107 {
1108     return imap_getpartialsizes(sock, 1, count, sizes);
1109 }
1110
1111 static int imap_is_old(int sock, struct query *ctl, int number)
1112 /* is the given message old? */
1113 {
1114     flag seen = TRUE;
1115     int i;
1116
1117     (void)sock;
1118     (void)ctl;
1119     /* 
1120      * Expunges change the fetch numbers, but unseen_messages contains
1121      * indices from before any expungees were done.  So neither the
1122      * argument nor the values in message_sequence need to be decremented.
1123      */
1124
1125     seen = TRUE;
1126     for (i = 0; i < unseen; i++)
1127         if (unseen_messages[i] == (unsigned)number)
1128         {
1129             seen = FALSE;
1130             break;
1131         }
1132
1133     return(seen);
1134 }
1135
1136 #if 0
1137 static char *skip_token(char *ptr)
1138 {
1139     while(isspace((unsigned char)*ptr)) ptr++;
1140     while(!isspace((unsigned char)*ptr) && !iscntrl((unsigned char)*ptr)) ptr++;
1141     while(isspace((unsigned char)*ptr)) ptr++;
1142     return(ptr);
1143 }
1144 #endif
1145
1146 static int imap_fetch_headers(int sock, struct query *ctl,int number,int *lenp)
1147 /* request headers of nth message */
1148 {
1149     char buf [MSGBUFSIZE+1];
1150     int num;
1151     int ok;
1152     char *ptr;
1153
1154     (void)ctl;
1155     /* expunges change the fetch numbers */
1156     number -= expunged;
1157
1158     /*
1159      * This is blessed by RFC1176, RFC1730, RFC2060.
1160      * According to the RFCs, it should *not* set the \Seen flag.
1161      */
1162     gen_send(sock, "FETCH %d RFC822.HEADER", number);
1163
1164     /* looking for FETCH response */
1165     if ((ok = imap_response(sock, buf)) == PS_UNTAGGED)
1166     {
1167                 int consumed;
1168         /* expected response formats:
1169          * IMAP> A0006 FETCH 1 RFC822.HEADER
1170          * IMAP< * 1 FETCH (RFC822.HEADER {1360}
1171          * IMAP< * 1 FETCH (UID 16 RFC822.HEADER {1360}
1172          * IMAP< * 1 FETCH (UID 16 RFC822.SIZE 4029 RFC822.HEADER {1360}
1173          */
1174         if (sscanf(buf, "* %d %n", &num, &consumed) == 1
1175             && 0 == strncasecmp(buf + consumed, "FETCH", 5)
1176             && isspace((unsigned char)buf[5+consumed])
1177                 && num == number
1178                 && (ptr = strstr(buf, "RFC822.HEADER"))
1179                 && sscanf(ptr, "RFC822.HEADER {%d}%n", lenp, &consumed) == 1
1180                 && ptr[consumed-1] == '}')
1181         {
1182             return(PS_SUCCESS);
1183         }
1184
1185         /* wait for a tagged response */
1186         imap_ok (sock, 0);
1187
1188         /* try to recover for some responses */
1189         if (!strncmp(buf, "* NO", 4) ||
1190                 !strncmp(buf, "* BAD", 5))
1191         {
1192             return(PS_TRANSIENT);
1193         }
1194
1195         /* a response which does not match any of the above */
1196         if (outlevel > O_SILENT)
1197             report(stderr, GT_("Incorrect FETCH response: %s.\n"), buf);
1198         return(PS_ERROR);
1199     }
1200     else if (ok == PS_SUCCESS)
1201     {
1202         /* an unexpected tagged response */
1203         if (outlevel > O_SILENT)
1204             report(stderr, GT_("Incorrect FETCH response: %s.\n"), buf);
1205         return(PS_ERROR);
1206     }
1207     return(ok);
1208 }
1209
1210 static int imap_fetch_body(int sock, struct query *ctl, int number, int *lenp)
1211 /* request body of nth message */
1212 {
1213     char buf [MSGBUFSIZE+1], *cp;
1214     int num;
1215
1216     (void)ctl;
1217     /* expunges change the fetch numbers */
1218     number -= expunged;
1219
1220     /*
1221      * If we're using IMAP4, we can fetch the message without setting its
1222      * seen flag.  This is good!  It means that if the protocol exchange
1223      * craps out during the message, it will still be marked `unseen' on
1224      * the server.
1225      *
1226      * According to RFC2060, and Mark Crispin the IMAP maintainer,
1227      * FETCH %d BODY[TEXT] and RFC822.TEXT are "functionally 
1228      * equivalent".  However, we know of at least one server that
1229      * treats them differently in the presence of MIME attachments;
1230      * the latter form downloads the attachment, the former does not.
1231      * The server is InterChange, and the fool who implemented this
1232      * misfeature ought to be strung up by his thumbs.  
1233      *
1234      * When I tried working around this by disabling use of the 4rev1 form,
1235      * I found that doing this breaks operation with M$ Exchange.
1236      * Annoyingly enough, Exchange's refusal to cope is technically legal
1237      * under RFC2062.  Trust Microsoft, the Great Enemy of interoperability
1238      * standards, to find a way to make standards compliance irritating....
1239      */
1240     switch (imap_version)
1241     {
1242     case IMAP4rev1:     /* RFC 2060 */
1243         gen_send(sock, "FETCH %d BODY.PEEK[TEXT]", number);
1244         break;
1245
1246     case IMAP4:         /* RFC 1730 */
1247         gen_send(sock, "FETCH %d RFC822.TEXT.PEEK", number);
1248         break;
1249
1250     default:            /* RFC 1176 */
1251         gen_send(sock, "FETCH %d RFC822.TEXT", number);
1252         break;
1253     }
1254
1255     /* looking for FETCH response */
1256     do {
1257         int     ok;
1258
1259         if ((ok = gen_recv(sock, buf, sizeof(buf))))
1260             return(ok);
1261     } while
1262         (!strstr(buf+4, "FETCH") || sscanf(buf+2, "%d", &num) != 1);
1263
1264     if (num != number)
1265         return(PS_ERROR);
1266
1267     /* Understand "NIL" as length => no body present
1268      * (MS Exchange, BerliOS Bug #11980) */
1269     if (strstr(buf+10, "NIL)")) {
1270             *lenp = 0;
1271             return PS_SUCCESS;
1272     }
1273
1274     /*
1275      * Try to extract a length from the FETCH response.  RFC2060 requires
1276      * it to be present, but at least one IMAP server (Novell GroupWise)
1277      * botches this.  The overflow check is needed because of a broken
1278      * server called dbmail that returns huge garbage lengths.
1279      */
1280     if ((cp = strchr(buf, '{'))) {
1281         long l; char *t;
1282         errno = 0;
1283         ++ cp;
1284         l = strtol(cp, &t, 10);
1285         if (errno || t == cp || (t && !strchr(t, '}')) /* parse error */
1286                     || l < 0 || l > INT_MAX /* range check */) {
1287             *lenp = -1;
1288         } else {
1289             *lenp = l;
1290         }
1291     } else {
1292         *lenp = -1;     /* missing length part in FETCH reponse */
1293     }
1294
1295     return PS_SUCCESS;
1296 }
1297
1298 static int imap_trail(int sock, struct query *ctl, const char *tag)
1299 /* discard tail of FETCH response after reading message text */
1300 {
1301     /* expunges change the fetch numbers */
1302     /* number -= expunged; */
1303
1304     (void)ctl;
1305     (void)tag;
1306
1307     return imap_ok(sock, NULL);
1308 }
1309
1310 static int imap_delete(int sock, struct query *ctl, int number)
1311 /* set delete flag for given message */
1312 {
1313     int ok;
1314
1315     (void)ctl;
1316     /* expunges change the fetch numbers */
1317     number -= expunged;
1318
1319     /*
1320      * Use SILENT if possible as a minor throughput optimization.
1321      * Note: this has been dropped from IMAP4rev1.
1322      *
1323      * We set Seen because there are some IMAP servers (notably HP
1324      * OpenMail) that do message-receipt DSNs, but only when the seen
1325      * bit is set.  This is the appropriate time -- we get here right
1326      * after the local SMTP response that says delivery was
1327      * successful.
1328      */
1329     if ((ok = gen_transact(sock,
1330                         imap_version == IMAP4 
1331                                 ? "STORE %d +FLAGS.SILENT (\\Seen \\Deleted)"
1332                                 : "STORE %d +FLAGS (\\Seen \\Deleted)", 
1333                         number)))
1334         return(ok);
1335     else
1336         deletions++;
1337
1338     /*
1339      * We do an expunge after expunge_period messages, rather than
1340      * just before quit, so that a line hit during a long session
1341      * won't result in lots of messages being fetched again during
1342      * the next session.
1343      */
1344     if (NUM_NONZERO(expunge_period) && (deletions % expunge_period) == 0)
1345     {
1346         if ((ok = internal_expunge(sock)))
1347             return(ok);
1348     }
1349
1350     return(PS_SUCCESS);
1351 }
1352
1353 static int imap_mark_seen(int sock, struct query *ctl, int number)
1354 /* mark the given message as seen */
1355 {
1356     (void)ctl;
1357
1358     /* expunges change the message numbers */
1359     number -= expunged;
1360
1361     return(gen_transact(sock,
1362         imap_version == IMAP4
1363         ? "STORE %d +FLAGS.SILENT (\\Seen)"
1364         : "STORE %d +FLAGS (\\Seen)",
1365         number));
1366 }
1367
1368 static int imap_end_mailbox_poll(int sock, struct query *ctl)
1369 /* cleanup mailbox before we idle or switch to another one */
1370 {
1371     (void)ctl;
1372     if (deletions)
1373         internal_expunge(sock);
1374     return(PS_SUCCESS);
1375 }
1376
1377 static int imap_logout(int sock, struct query *ctl)
1378 /* send logout command */
1379 {
1380     (void)ctl;
1381     /* if any un-expunged deletions remain, ship an expunge now */
1382     if (deletions)
1383         internal_expunge(sock);
1384
1385 #ifdef USE_SEARCH
1386     /* Memory clean-up */
1387     if (unseen_messages)
1388         free(unseen_messages);
1389 #endif /* USE_SEARCH */
1390
1391     return(gen_transact(sock, "LOGOUT"));
1392 }
1393
1394 static const struct method imap =
1395 {
1396     "IMAP",             /* Internet Message Access Protocol */
1397     "imap",             /* service (plain and TLS) */
1398     "imaps",            /* service (SSL) */
1399     TRUE,               /* this is a tagged protocol */
1400     FALSE,              /* no message delimiter */
1401     imap_ok,            /* parse command response */
1402     imap_getauth,       /* get authorization */
1403     imap_getrange,      /* query range of messages */
1404     imap_getsizes,      /* get sizes of messages (used for ESMTP SIZE option) */
1405     imap_getpartialsizes,       /* get sizes of subset of messages (used for ESMTP SIZE option) */
1406     imap_is_old,        /* no UID check */
1407     imap_fetch_headers, /* request given message headers */
1408     imap_fetch_body,    /* request given message body */
1409     imap_trail,         /* eat message trailer */
1410     imap_delete,        /* delete the message */
1411     imap_mark_seen,     /* how to mark a message as seen */
1412     imap_end_mailbox_poll,      /* end-of-mailbox processing */
1413     imap_logout,        /* expunge and exit */
1414     TRUE,               /* yes, we can re-poll */
1415 };
1416
1417 int doIMAP(struct query *ctl)
1418 /* retrieve messages using IMAP Version 2bis or Version 4 */
1419 {
1420     return(do_protocol(ctl, &imap));
1421 }
1422
1423 /* imap.c ends here */