]> Pileus Git - ~andy/fetchmail/blob - imap.c
Clarify IMAP BYE response logging.
[~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 static int imap_getrange(int sock, 
802                          struct query *ctl, 
803                          const char *folder, 
804                          int *countp, int *newp, int *bytes)
805 /* get range of messages to be fetched */
806 {
807     int ok;
808     char buf[MSGBUFSIZE+1], *cp;
809
810     /* find out how many messages are waiting */
811     *bytes = -1;
812
813     if (pass > 1)
814     {
815         /* deleted mails have already been expunged by
816          * end_mailbox_poll().
817          *
818          * recentcount is already set here by the last imap command which
819          * returned EXISTS on detecting new mail. if recentcount is 0, wait
820          * for new mail.
821          *
822          * this is a while loop because imap_idle() might return on other
823          * mailbox changes also */
824         while (recentcount == 0 && do_idle) {
825             smtp_close(ctl, 1);
826             ok = imap_idle(sock);
827             if (ok)
828             {
829                 report(stderr, GT_("re-poll failed\n"));
830                 return(ok);
831             }
832         }
833         /* if recentcount is 0, return no mail */
834         if (recentcount == 0)
835                 count = 0;
836         if (outlevel >= O_DEBUG)
837             report(stdout, ngettext("%d message waiting after re-poll\n",
838                                     "%d messages waiting after re-poll\n",
839                                     count), count);
840     }
841     else
842     {
843         oldcount = count = 0;
844         ok = gen_transact(sock, 
845                           check_only ? "EXAMINE \"%s\"" : "SELECT \"%s\"",
846                           folder ? folder : "INBOX");
847         /* imap_ok returns PS_LOCKBUSY for READ-ONLY folders,
848          * which we can safely use in fetchall keep only */
849         if (ok == PS_LOCKBUSY && ctl->fetchall && ctl-> keep)
850             ok = 0;
851
852         if (ok != 0)
853         {
854             report(stderr, GT_("mailbox selection failed\n"));
855             return(ok);
856         }
857         else if (outlevel >= O_DEBUG)
858             report(stdout, ngettext("%d message waiting after first poll\n",
859                                     "%d messages waiting after first poll\n",
860                                     count), count);
861
862         /*
863          * We should have an expunge here to
864          * a) avoid fetching deleted mails during 'fetchall'
865          * b) getting a wrong count of mails during 'no fetchall'
866          */
867         if (!check_only && !ctl->keep && count > 0)
868         {
869             ok = internal_expunge(sock);
870             if (ok)
871             {
872                 report(stderr, GT_("expunge failed\n"));
873                 return(ok);
874             }
875             if (outlevel >= O_DEBUG)
876                 report(stdout, ngettext("%d message waiting after expunge\n",
877                                         "%d messages waiting after expunge\n",
878                                         count), count);
879         }
880
881         if (count == 0 && do_idle)
882         {
883             /* no messages?  then we may need to idle until we get some */
884             while (count == 0) {
885                 ok = imap_idle(sock);
886                 if (ok)
887                 {
888                     report(stderr, GT_("re-poll failed\n"));
889                     return(ok);
890                 }
891             }
892             if (outlevel >= O_DEBUG)
893                 report(stdout, ngettext("%d message waiting after re-poll\n",
894                                         "%d messages waiting after re-poll\n",
895                                         count), count);
896         }
897     }
898
899     *countp = oldcount = count;
900     recentcount = 0;
901     startcount = 1;
902
903     /* OK, now get a count of unseen messages and their indices */
904     if (!ctl->fetchall && count > 0)
905     {
906         if (unseen_messages)
907             free(unseen_messages);
908         unseen_messages = (unsigned int *)xmalloc(count * sizeof(unsigned int));
909         memset(unseen_messages, 0, count * sizeof(unsigned int));
910         unseen = 0;
911
912         /* don't count deleted messages, in case user enabled keep last time */
913         gen_send(sock, "SEARCH UNSEEN NOT DELETED");
914         while ((ok = imap_response(sock, buf)) == PS_UNTAGGED)
915         {
916             if ((cp = strstr(buf, "* SEARCH")))
917             {
918                 char    *ep;
919
920                 cp += 8;        /* skip "* SEARCH" */
921                 /* startcount is higher than count so that if there are no
922                  * unseen messages, imap_getsizes() will not need to do
923                  * anything! */
924                 startcount = count + 1;
925
926                 while (*cp && unseen < count)
927                 {
928                     /* skip whitespace */
929                     while (*cp && isspace((unsigned char)*cp))
930                         cp++;
931                     if (*cp) 
932                     {
933                         unsigned long um;
934
935                         errno = 0;
936                         um = strtoul(cp,&ep,10);
937                         if (errno == 0 && um <= UINT_MAX && um <= (unsigned)count)
938                         {
939                             unseen_messages[unseen++] = um;
940                             if (outlevel >= O_DEBUG)
941                                 report(stdout, GT_("%lu is unseen\n"), um);
942                             if (startcount > um)
943                                 startcount = um;
944                         }
945                         cp = ep;
946                     }
947                 }
948             }
949         }
950         if (ok != 0)
951         {
952             report(stderr, GT_("search for unseen messages failed\n"));
953             return(ok);
954         }
955
956         if (outlevel >= O_DEBUG && unseen > 0)
957             report(stdout, GT_("%u is first unseen\n"), startcount);
958     } else
959         unseen = -1;
960
961     *newp = unseen;
962     expunged = 0;
963     deletions = 0;
964
965     return(PS_SUCCESS);
966 }
967
968 static int imap_getpartialsizes(int sock, int first, int last, int *sizes)
969 /* capture the sizes of messages #first-#last */
970 {
971     char buf [MSGBUFSIZE+1];
972     int ok;
973
974     /*
975      * Some servers (as in, PMDF5.1-9.1 under OpenVMS 6.1)
976      * won't accept 1:1 as valid set syntax.  Some implementors
977      * should be taken out and shot for excessive anality.
978      *
979      * Microsoft Exchange (brain-dead piece of crap that it is) 
980      * sometimes gets its knickers in a knot about bodiless messages.
981      * You may see responses like this:
982      *
983      *  fetchmail: IMAP> A0004 FETCH 1:9 RFC822.SIZE
984      *  fetchmail: IMAP< * 2 FETCH (RFC822.SIZE 1187)
985      *  fetchmail: IMAP< * 3 FETCH (RFC822.SIZE 3954)
986      *  fetchmail: IMAP< * 4 FETCH (RFC822.SIZE 1944)
987      *  fetchmail: IMAP< * 5 FETCH (RFC822.SIZE 2933)
988      *  fetchmail: IMAP< * 6 FETCH (RFC822.SIZE 1854)
989      *  fetchmail: IMAP< * 7 FETCH (RFC822.SIZE 34054)
990      *  fetchmail: IMAP< * 8 FETCH (RFC822.SIZE 5561)
991      *  fetchmail: IMAP< * 9 FETCH (RFC822.SIZE 1101)
992      *  fetchmail: IMAP< A0004 NO The requested item could not be found.
993      *
994      * This means message 1 has only headers.  For kicks and grins
995      * you can telnet in and look:
996      *  A003 FETCH 1 FULL
997      *  A003 NO The requested item could not be found.
998      *  A004 fetch 1 rfc822.header
999      *  A004 NO The requested item could not be found.
1000      *  A006 FETCH 1 BODY
1001      *  * 1 FETCH (BODY ("TEXT" "PLAIN" ("CHARSET" "US-ASCII") NIL NIL "7BIT" 35 3))
1002      *  A006 OK FETCH completed.
1003      *
1004      * To get around this, we treat the final NO as success and count
1005      * on the fact that the sizes array has been preinitialized with a
1006      * known-bad size value.
1007      */
1008
1009     /* expunges change the fetch numbers */
1010     first -= expunged;
1011     last -= expunged;
1012
1013     if (last == first)
1014         gen_send(sock, "FETCH %d RFC822.SIZE", last);
1015     else if (last > first)
1016         gen_send(sock, "FETCH %d:%d RFC822.SIZE", first, last);
1017     else /* no unseen messages! */
1018         return(PS_SUCCESS);
1019     while ((ok = imap_response(sock, buf)) == PS_UNTAGGED)
1020     {
1021         unsigned int size;
1022         int num;
1023
1024         if (sscanf(buf, "* %d FETCH (RFC822.SIZE %u)", &num, &size) == 2
1025         /* some servers (like mail.internode.on.net bld-mail04) return UID information here
1026          *
1027          * IMAP> A0005 FETCH 1 RFC822.SIZE
1028          * IMAP< * 1 FETCH (UID 16 RFC822.SIZE 1447)
1029          * IMAP< A0005 OK FETCH completed
1030          *
1031          */
1032                 || sscanf(buf, "* %d FETCH (UID %*s RFC822.SIZE %u)", &num, &size) == 2)
1033         {
1034             if (num >= first && num <= last)
1035                 sizes[num - first] = size;
1036             else
1037                 report(stderr,
1038                         GT_("Warning: ignoring bogus data for message sizes returned by the server.\n"));
1039         }
1040     }
1041     return(ok);
1042 }
1043
1044 static int imap_getsizes(int sock, int count, int *sizes)
1045 /* capture the sizes of all messages */
1046 {
1047     return imap_getpartialsizes(sock, 1, count, sizes);
1048 }
1049
1050 static int imap_is_old(int sock, struct query *ctl, int number)
1051 /* is the given message old? */
1052 {
1053     flag seen = TRUE;
1054     int i;
1055
1056     (void)sock;
1057     (void)ctl;
1058     /* 
1059      * Expunges change the fetch numbers, but unseen_messages contains
1060      * indices from before any expungees were done.  So neither the
1061      * argument nor the values in message_sequence need to be decremented.
1062      */
1063
1064     seen = TRUE;
1065     for (i = 0; i < unseen; i++)
1066         if (unseen_messages[i] == (unsigned)number)
1067         {
1068             seen = FALSE;
1069             break;
1070         }
1071
1072     return(seen);
1073 }
1074
1075 static char *skip_token(char *ptr)
1076 {
1077     while(isspace((unsigned char)*ptr)) ptr++;
1078     while(!isspace((unsigned char)*ptr) && !iscntrl((unsigned char)*ptr)) ptr++;
1079     while(isspace((unsigned char)*ptr)) ptr++;
1080     return(ptr);
1081 }
1082
1083 static int imap_fetch_headers(int sock, struct query *ctl,int number,int *lenp)
1084 /* request headers of nth message */
1085 {
1086     char buf [MSGBUFSIZE+1];
1087     int num;
1088
1089     (void)ctl;
1090     /* expunges change the fetch numbers */
1091     number -= expunged;
1092
1093     /*
1094      * This is blessed by RFC1176, RFC1730, RFC2060.
1095      * According to the RFCs, it should *not* set the \Seen flag.
1096      */
1097     gen_send(sock, "FETCH %d RFC822.HEADER", number);
1098
1099     /* looking for FETCH response */
1100     for (;;) 
1101     {
1102         int     ok;
1103         char    *ptr;
1104
1105         if ((ok = gen_recv(sock, buf, sizeof(buf))))
1106             return(ok);
1107         ptr = skip_token(buf);  /* either "* " or "AXXXX " */
1108         if (sscanf(ptr, "%d FETCH (RFC822.HEADER {%d}", &num, lenp) == 2
1109         /* some servers (like mail.internode.on.net bld-mail04) return UID information here
1110          *
1111          * IMAP> A0006 FETCH 1 RFC822.HEADER
1112          * IMAP< * 1 FETCH (UID 16 RFC822.HEADER {1360}
1113          * ...
1114          * IMAP< )
1115          * IMAP< A0006 OK FETCH completed
1116          *
1117          */
1118                 || sscanf(ptr, "%d FETCH (UID %*s RFC822.HEADER {%d}", &num, lenp) == 2)
1119             break;
1120         /* try to recover from chronically fucked-up M$ Exchange servers */
1121         else if (!strncmp(ptr, "NO", 2))
1122         {
1123             /* wait for a tagged response */
1124             if (strstr (buf, "* NO"))
1125                 imap_ok (sock, 0);
1126             return(PS_TRANSIENT);
1127         }
1128         else if (!strncmp(ptr, "BAD", 3))
1129         {
1130             /* wait for a tagged response */
1131             if (strstr (buf, "* BAD"))
1132                 imap_ok (sock, 0);
1133             return(PS_TRANSIENT);
1134         }
1135     }
1136
1137     if (num != number)
1138         return(PS_ERROR);
1139     else
1140         return(PS_SUCCESS);
1141 }
1142
1143 static int imap_fetch_body(int sock, struct query *ctl, int number, int *lenp)
1144 /* request body of nth message */
1145 {
1146     char buf [MSGBUFSIZE+1], *cp;
1147     int num;
1148
1149     (void)ctl;
1150     /* expunges change the fetch numbers */
1151     number -= expunged;
1152
1153     /*
1154      * If we're using IMAP4, we can fetch the message without setting its
1155      * seen flag.  This is good!  It means that if the protocol exchange
1156      * craps out during the message, it will still be marked `unseen' on
1157      * the server.
1158      *
1159      * According to RFC2060, and Mark Crispin the IMAP maintainer,
1160      * FETCH %d BODY[TEXT] and RFC822.TEXT are "functionally 
1161      * equivalent".  However, we know of at least one server that
1162      * treats them differently in the presence of MIME attachments;
1163      * the latter form downloads the attachment, the former does not.
1164      * The server is InterChange, and the fool who implemented this
1165      * misfeature ought to be strung up by his thumbs.  
1166      *
1167      * When I tried working around this by disabling use of the 4rev1 form,
1168      * I found that doing this breaks operation with M$ Exchange.
1169      * Annoyingly enough, Exchange's refusal to cope is technically legal
1170      * under RFC2062.  Trust Microsoft, the Great Enemy of interoperability
1171      * standards, to find a way to make standards compliance irritating....
1172      */
1173     switch (imap_version)
1174     {
1175     case IMAP4rev1:     /* RFC 2060 */
1176         gen_send(sock, "FETCH %d BODY.PEEK[TEXT]", number);
1177         break;
1178
1179     case IMAP4:         /* RFC 1730 */
1180         gen_send(sock, "FETCH %d RFC822.TEXT.PEEK", number);
1181         break;
1182
1183     default:            /* RFC 1176 */
1184         gen_send(sock, "FETCH %d RFC822.TEXT", number);
1185         break;
1186     }
1187
1188     /* looking for FETCH response */
1189     do {
1190         int     ok;
1191
1192         if ((ok = gen_recv(sock, buf, sizeof(buf))))
1193             return(ok);
1194     } while
1195         (!strstr(buf+4, "FETCH") || sscanf(buf+2, "%d", &num) != 1);
1196
1197     if (num != number)
1198         return(PS_ERROR);
1199
1200     /* Understand "NIL" as length => no body present
1201      * (MS Exchange, BerliOS Bug #11980) */
1202     if (strstr(buf+10, "NIL)")) {
1203             *lenp = 0;
1204             return PS_SUCCESS;
1205     }
1206
1207     /*
1208      * Try to extract a length from the FETCH response.  RFC2060 requires
1209      * it to be present, but at least one IMAP server (Novell GroupWise)
1210      * botches this.  The overflow check is needed because of a broken
1211      * server called dbmail that returns huge garbage lengths.
1212      */
1213     if ((cp = strchr(buf, '{'))) {
1214         errno = 0;
1215         *lenp = (int)strtol(cp + 1, (char **)NULL, 10);
1216         if (errno == ERANGE || *lenp < 0)
1217             *lenp = -1;    /* length is too big/small for us to handle */
1218     }
1219     else
1220         *lenp = -1;     /* missing length part in FETCH reponse */
1221
1222     return(PS_SUCCESS);
1223 }
1224
1225 static int imap_trail(int sock, struct query *ctl, const char *tag)
1226 /* discard tail of FETCH response after reading message text */
1227 {
1228     /* expunges change the fetch numbers */
1229     /* number -= expunged; */
1230
1231     (void)ctl;
1232     (void)tag;
1233
1234     return imap_ok(sock, NULL);
1235 }
1236
1237 static int imap_delete(int sock, struct query *ctl, int number)
1238 /* set delete flag for given message */
1239 {
1240     int ok;
1241
1242     (void)ctl;
1243     /* expunges change the fetch numbers */
1244     number -= expunged;
1245
1246     /*
1247      * Use SILENT if possible as a minor throughput optimization.
1248      * Note: this has been dropped from IMAP4rev1.
1249      *
1250      * We set Seen because there are some IMAP servers (notably HP
1251      * OpenMail) that do message-receipt DSNs, but only when the seen
1252      * bit is set.  This is the appropriate time -- we get here right
1253      * after the local SMTP response that says delivery was
1254      * successful.
1255      */
1256     if ((ok = gen_transact(sock,
1257                         imap_version == IMAP4 
1258                                 ? "STORE %d +FLAGS.SILENT (\\Seen \\Deleted)"
1259                                 : "STORE %d +FLAGS (\\Seen \\Deleted)", 
1260                         number)))
1261         return(ok);
1262     else
1263         deletions++;
1264
1265     /*
1266      * We do an expunge after expunge_period messages, rather than
1267      * just before quit, so that a line hit during a long session
1268      * won't result in lots of messages being fetched again during
1269      * the next session.
1270      */
1271     if (NUM_NONZERO(expunge_period) && (deletions % expunge_period) == 0)
1272     {
1273         if ((ok = internal_expunge(sock)))
1274             return(ok);
1275     }
1276
1277     return(PS_SUCCESS);
1278 }
1279
1280 static int imap_mark_seen(int sock, struct query *ctl, int number)
1281 /* mark the given message as seen */
1282 {
1283     (void)ctl;
1284
1285     /* expunges change the message numbers */
1286     number -= expunged;
1287
1288     return(gen_transact(sock,
1289         imap_version == IMAP4
1290         ? "STORE %d +FLAGS.SILENT (\\Seen)"
1291         : "STORE %d +FLAGS (\\Seen)",
1292         number));
1293 }
1294
1295 static int imap_end_mailbox_poll(int sock, struct query *ctl)
1296 /* cleanup mailbox before we idle or switch to another one */
1297 {
1298     (void)ctl;
1299     if (deletions)
1300         internal_expunge(sock);
1301     return(PS_SUCCESS);
1302 }
1303
1304 static int imap_logout(int sock, struct query *ctl)
1305 /* send logout command */
1306 {
1307     (void)ctl;
1308     /* if any un-expunged deletions remain, ship an expunge now */
1309     if (deletions)
1310         internal_expunge(sock);
1311
1312 #ifdef USE_SEARCH
1313     /* Memory clean-up */
1314     if (unseen_messages)
1315         free(unseen_messages);
1316 #endif /* USE_SEARCH */
1317
1318     return(gen_transact(sock, "LOGOUT"));
1319 }
1320
1321 static const struct method imap =
1322 {
1323     "IMAP",             /* Internet Message Access Protocol */
1324     "imap",             /* service (plain and TLS) */
1325     "imaps",            /* service (SSL) */
1326     TRUE,               /* this is a tagged protocol */
1327     FALSE,              /* no message delimiter */
1328     imap_ok,            /* parse command response */
1329     imap_getauth,       /* get authorization */
1330     imap_getrange,      /* query range of messages */
1331     imap_getsizes,      /* get sizes of messages (used for ESMTP SIZE option) */
1332     imap_getpartialsizes,       /* get sizes of subset of messages (used for ESMTP SIZE option) */
1333     imap_is_old,        /* no UID check */
1334     imap_fetch_headers, /* request given message headers */
1335     imap_fetch_body,    /* request given message body */
1336     imap_trail,         /* eat message trailer */
1337     imap_delete,        /* delete the message */
1338     imap_mark_seen,     /* how to mark a message as seen */
1339     imap_end_mailbox_poll,      /* end-of-mailbox processing */
1340     imap_logout,        /* expunge and exit */
1341     TRUE,               /* yes, we can re-poll */
1342 };
1343
1344 int doIMAP(struct query *ctl)
1345 /* retrieve messages using IMAP Version 2bis or Version 4 */
1346 {
1347     return(do_protocol(ctl, &imap));
1348 }
1349
1350 /* imap.c ends here */