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