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