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