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