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