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