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