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