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