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