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