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