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