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