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