2 * imap.c -- IMAP2bis/IMAP4 protocol methods
4 * Copyright 1997 by Eric S. Raymond
5 * For license terms, see the file COPYING in this directory.
12 #if defined(STDC_HEADERS)
15 #include "fetchmail.h"
21 #endif /* OPIE_ENABLE */
23 #ifndef strstr /* glibc-2.1 declares this as a macro */
24 extern char *strstr(); /* needed on sysV68 R3V7.1. */
27 /* imap_version values */
28 #define IMAP2 -1 /* IMAP2 or IMAP2BIS, RFC1176 */
29 #define IMAP4 0 /* IMAP4 rev 0, RFC1730 */
30 #define IMAP4rev1 1 /* IMAP4 rev 1, RFC2060 */
32 static int count, unseen, deletions, imap_version, preauth;
33 static int expunged, expunge_period, saved_timeout;
35 static char capabilities[MSGBUFSIZE+1];
36 static unsigned int *unseen_messages;
38 static int imap_ok(int sock, char *argbuf)
39 /* parse command response */
41 char buf[MSGBUFSIZE+1];
47 if ((ok = gen_recv(sock, buf, sizeof(buf))))
50 /* all tokens in responses are caseblind */
51 for (cp = buf; *cp; cp++)
55 /* interpret untagged status responses */
56 if (strstr(buf, "* CAPABILITY"))
57 strncpy(capabilities, buf + 12, sizeof(capabilities));
58 else if (strstr(buf, "EXISTS"))
62 * Nasty kluge to handle RFC2177 IDLE. If we know we're idling
63 * we can't wait for the tag matching the IDLE; we have to tell the
64 * server the IDLE is finished by shipping back a DONE when we
65 * see an EXISTS. Only after that will a tagged response be
66 * shipped. The idling flag also gets cleared on a timeout.
68 if (stage == STAGE_IDLE)
70 /* we do our own write and report here to disable tagging */
71 SockWrite(sock, "DONE\r\n", 6);
72 if (outlevel >= O_MONITOR)
73 report(stdout, "IMAP> DONE\n");
75 mytimeout = saved_timeout;
79 else if (strstr(buf, "PREAUTH"))
82 * The server may decide to make the mailbox read-only,
83 * which causes fetchmail to go into a endless loop
84 * fetching the same message over and over again.
86 * However, for check_only, we use EXAMINE which will
87 * mark the mailbox read-only as per the RFC.
89 * This checks for the condition and aborts if
90 * the mailbox is read-only.
92 * See RFC 2060 section 6.3.1 (SELECT).
93 * See RFC 2060 section 6.3.2 (EXAMINE).
95 else if (!check_only && strstr(buf, "[READ-ONLY]"))
98 (tag[0] != '\0' && strncmp(buf, tag, strlen(tag)));
111 for (cp = buf; !isspace(*cp); cp++)
116 if (strncmp(cp, "OK", 2) == 0)
122 else if (strncmp(cp, "BAD", 3) == 0)
124 else if (strncmp(cp, "NO", 2) == 0)
126 if (stage == STAGE_GETAUTH)
127 return(PS_AUTHFAIL); /* RFC2060, 6.2.2 */
139 static tSmbNtlmAuthRequest request;
140 static tSmbNtlmAuthChallenge challenge;
141 static tSmbNtlmAuthResponse response;
144 * NTLM support by Grant Edwards.
146 * Handle MS-Exchange NTLM authentication method. This is the same
147 * as the NTLM auth used by Samba for SMB related services. We just
148 * encode the packets in base64 instead of sending them out via a
151 * Much source (ntlm.h, smb*.c smb*.h) was borrowed from Samba.
154 static int do_imap_ntlm(int sock, struct query *ctl)
159 gen_send(sock, "AUTHENTICATE NTLM");
161 if ((result = gen_recv(sock, msgbuf, sizeof msgbuf)))
164 if (msgbuf[0] != '+')
167 buildSmbNtlmAuthRequest(&request,ctl->remotename,NULL);
169 if (outlevel >= O_DEBUG)
170 dumpSmbNtlmAuthRequest(stdout, &request);
172 memset(msgbuf,0,sizeof msgbuf);
173 to64frombits (msgbuf, (unsigned char*)&request, SmbLength(&request));
175 if (outlevel >= O_MONITOR)
176 report(stdout, "IMAP> %s\n", msgbuf);
178 strcat(msgbuf,"\r\n");
179 SockWrite (sock, msgbuf, strlen (msgbuf));
181 if ((gen_recv(sock, msgbuf, sizeof msgbuf)))
184 len = from64tobits ((unsigned char*)&challenge, msgbuf);
186 if (outlevel >= O_DEBUG)
187 dumpSmbNtlmAuthChallenge(stdout, &challenge);
189 buildSmbNtlmAuthResponse(&challenge, &response,ctl->remotename,ctl->password);
191 if (outlevel >= O_DEBUG)
192 dumpSmbNtlmAuthResponse(stdout, &response);
194 memset(msgbuf,0,sizeof msgbuf);
195 to64frombits (msgbuf, (unsigned char*)&response, SmbLength(&response));
197 if (outlevel >= O_MONITOR)
198 report(stdout, "IMAP> %s\n", msgbuf);
200 strcat(msgbuf,"\r\n");
201 SockWrite (sock, msgbuf, strlen (msgbuf));
203 if ((result = gen_recv (sock, msgbuf, sizeof msgbuf)))
206 if (strstr (msgbuf, "OK"))
213 static int imap_canonicalize(char *result, char *raw, int maxlen)
214 /* encode an IMAP password as per RFC1730's quoting conventions */
219 for (i = 0; i < strlen(raw) && i < maxlen; i++)
221 if ((raw[i] == '\\') || (raw[i] == '"'))
223 result[j++] = raw[i];
230 static int imap_getauth(int sock, struct query *ctl, char *greeting)
231 /* apply for connection authorization */
235 /* probe to see if we're running IMAP4 and can use RFC822.PEEK */
236 capabilities[0] = '\0';
237 if ((ok = gen_transact(sock, "CAPABILITY")) == PS_SUCCESS)
239 /* UW-IMAP server 10.173 notifies in all caps, but RFC2060 says we
240 should expect a response in mixed-case */
241 if (strstr(capabilities, "IMAP4REV1") ||
242 strstr(capabilities, "IMAP4rev1"))
244 imap_version = IMAP4rev1;
245 if (outlevel >= O_DEBUG)
246 report(stdout, _("Protocol identified as IMAP4 rev 1\n"));
250 imap_version = IMAP4;
251 if (outlevel >= O_DEBUG)
252 report(stdout, _("Protocol identified as IMAP4 rev 0\n"));
255 else if (ok == PS_ERROR)
257 imap_version = IMAP2;
258 if (outlevel >= O_DEBUG)
259 report(stdout, _("Protocol identified as IMAP2 or IMAP2BIS\n"));
264 peek_capable = (imap_version >= IMAP4);
267 * Assumption: expunges are cheap, so we want to do them
268 * after every message unless user said otherwise.
270 if (NUM_SPECIFIED(ctl->expunge))
271 expunge_period = NUM_VALUE_OUT(ctl->expunge);
276 * Handle idling. We depend on coming through here on startup
277 * and after each timeout (including timeouts during idles).
279 if (strstr(capabilities, "IDLE") && ctl->idle)
282 if (outlevel >= O_VERBOSE)
283 report(stdout, _("will idle after poll\n"));
287 * If either (a) we saw a PREAUTH token in the greeting, or
288 * (b) the user specified ssh preauthentication, then we're done.
290 if (preauth || ctl->server.authenticate == A_SSH)
292 preauth = FALSE; /* reset for the next session */
297 * Time to authenticate the user.
298 * Try the protocol variants that don't require passwords first.
303 if ((ctl->server.authenticate == A_ANY
304 || ctl->server.authenticate == A_GSSAPI)
305 && strstr(capabilities, "AUTH=GSSAPI"))
306 if(ok = do_gssauth(sock, "AUTHENTICATE", ctl->server.truename, ctl->remotename))
308 /* SASL cancellation of authentication */
310 if(ctl->server.authenticate != A_ANY)
318 if ((ctl->server.authenticate == A_ANY
319 || ctl->server.authenticate == A_KERBEROS_V4
320 || ctl->server.authenticate == A_KERBEROS_V5)
321 && strstr(capabilities, "AUTH=KERBEROS_V4"))
323 if ((ok = do_rfc1731(sock, "AUTHENTICATE", ctl->server.truename)))
325 /* SASL cancellation of authentication */
327 if(ctl->server.authenticate != A_ANY)
333 #endif /* KERBEROS_V4 */
336 * No such luck. OK, now try the variants that mask your password
337 * in a challenge-response.
340 if ((ctl->server.authenticate == A_ANY
341 || ctl->server.authenticate == A_CRAM_MD5)
342 && strstr(capabilities, "AUTH=CRAM-MD5"))
344 if ((ok = do_cram_md5 (sock, "AUTHENTICATE", ctl)))
346 /* SASL cancellation of authentication */
348 if(ctl->server.authenticate != A_ANY)
356 if ((ctl->server.authenticate == A_ANY
357 || ctl->server.authenticate == A_OTP)
358 && strstr(capabilities, "AUTH=X-OTP"))
359 if ((ok = do_otp(sock, "AUTHENTICATE", ctl)))
361 /* SASL cancellation of authentication */
363 if(ctl->server.authenticate != A_ANY)
369 if (ctl->server.authenticate == A_NTLM)
372 _("Required OTP capability not compiled into fetchmail\n"));
374 #endif /* OPIE_ENABLE */
377 if ((ctl->server.authenticate == A_ANY
378 || ctl->server.authenticate == A_NTLM)
379 && strstr (capabilities, "AUTH=NTLM")) {
380 if ((ok = do_imap_ntlm(sock, ctl)))
382 /* SASL cancellation of authentication */
384 if(ctl->server.authenticate != A_ANY)
391 if (ctl->server.authenticate == A_NTLM)
394 _("Required NTLM capability not compiled into fetchmail\n"));
396 #endif /* NTLM_ENABLE */
398 #ifdef __UNUSED__ /* The Cyrus IMAP4rev1 server chokes on this */
399 /* this handles either AUTH=LOGIN or AUTH-LOGIN */
400 if ((imap_version >= IMAP4rev1) && (!strstr(capabilities, "LOGIN")))
403 _("Required LOGIN capability not supported by server\n"));
405 #endif /* __UNUSED__ */
407 /* we're stuck with sending the password en clair */
408 if ((ctl->server.authenticate == A_ANY
409 || ctl->server.authenticate == A_PASSWORD)
410 && !strstr (capabilities, "LOGINDISABLED"))
412 /* these sizes guarantee no buffer overflow */
413 char remotename[NAMELEN*2+1], password[PASSWORDLEN*2+1];
415 imap_canonicalize(remotename, ctl->remotename, NAMELEN);
416 imap_canonicalize(password, ctl->password, PASSWORDLEN);
418 strcpy(shroud, ctl->password);
419 ok = gen_transact(sock, "LOGIN \"%s\" \"%s\"", remotename, password);
423 /* SASL cancellation of authentication */
425 if(ctl->server.authenticate != A_ANY)
435 static int internal_expunge(int sock)
436 /* ship an expunge, resetting associated counters */
440 if ((ok = gen_transact(sock, "EXPUNGE")))
443 expunged += deletions;
446 #ifdef IMAP_UID /* not used */
448 #endif /* IMAP_UID */
453 static int imap_idle(int sock)
454 /* start an RFC2177 IDLE */
457 saved_timeout = mytimeout;
460 return (gen_transact(sock, "IDLE"));
463 static int imap_getrange(int sock,
466 int *countp, int *newp, int *bytes)
467 /* get range of messages to be fetched */
470 char buf[MSGBUFSIZE+1], *cp;
472 /* find out how many messages are waiting */
478 * We have to have an expunge here, otherwise the re-poll will
479 * infinite-loop picking up un-expunged messages -- unless the
480 * expunge period is one and we've been nuking each message
481 * just after deletion.
484 if (deletions && expunge_period != 1)
485 ok = internal_expunge(sock);
488 ok = imap_idle(sock);
489 if (ok || gen_transact(sock, "NOOP"))
491 report(stderr, _("re-poll failed\n"));
494 else if (count == -1) /* no EXISTS response to NOOP/IDLE */
498 if (outlevel >= O_DEBUG)
499 report(stdout, _("%d messages waiting after re-poll\n"), count);
503 ok = gen_transact(sock,
504 check_only ? "EXAMINE \"%s\"" : "SELECT \"%s\"",
505 folder ? folder : "INBOX");
508 report(stderr, _("mailbox selection failed\n"));
511 else if (outlevel >= O_DEBUG)
512 report(stdout, _("%d messages waiting after first poll\n"), count);
514 /* no messages? then we may need to idle until we get some */
515 if (count == 0 && do_idle)
521 /* OK, now get a count of unseen messages and their indices */
522 if (!ctl->fetchall && count > 0)
525 free(unseen_messages);
526 unseen_messages = xmalloc(count * sizeof(unsigned int));
527 memset(unseen_messages, 0, count * sizeof(unsigned int));
530 gen_send(sock, "SEARCH UNSEEN");
532 ok = gen_recv(sock, buf, sizeof(buf));
535 report(stderr, _("search for unseen messages failed\n"));
538 else if ((cp = strstr(buf, "* SEARCH")))
542 cp += 8; /* skip "* SEARCH" */
544 while (*cp && unseen < count)
546 /* skip whitespace */
547 while (*cp && isspace(*cp))
552 * Message numbers are between 1 and 2^32 inclusive,
553 * so unsigned int is large enough.
555 unseen_messages[unseen]=(unsigned int)strtol(cp,&ep,10);
557 if (outlevel >= O_DEBUG)
560 unseen_messages[unseen]);
568 (tag[0] != '\0' && strncmp(buf, tag, strlen(tag)));
578 static int imap_getsizes(int sock, int count, int *sizes)
579 /* capture the sizes of all messages */
581 char buf [MSGBUFSIZE+1];
584 * Some servers (as in, PMDF5.1-9.1 under OpenVMS 6.1)
585 * won't accept 1:1 as valid set syntax. Some implementors
586 * should be taken out and shot for excessive anality.
588 * Microsoft Exchange (brain-dead piece of crap that it is)
589 * sometimes gets its knickers in a knot about bodiless messages.
590 * You may see responses like this:
592 * fetchmail: IMAP> A0004 FETCH 1:9 RFC822.SIZE
593 * fetchmail: IMAP< * 2 FETCH (RFC822.SIZE 1187)
594 * fetchmail: IMAP< * 3 FETCH (RFC822.SIZE 3954)
595 * fetchmail: IMAP< * 4 FETCH (RFC822.SIZE 1944)
596 * fetchmail: IMAP< * 5 FETCH (RFC822.SIZE 2933)
597 * fetchmail: IMAP< * 6 FETCH (RFC822.SIZE 1854)
598 * fetchmail: IMAP< * 7 FETCH (RFC822.SIZE 34054)
599 * fetchmail: IMAP< * 8 FETCH (RFC822.SIZE 5561)
600 * fetchmail: IMAP< * 9 FETCH (RFC822.SIZE 1101)
601 * fetchmail: IMAP< A0004 NO The requested item could not be found.
603 * This means message 1 has only headers. For kicks and grins
604 * you can telnet in and look:
606 * A003 NO The requested item could not be found.
607 * A004 fetch 1 rfc822.header
608 * A004 NO The requested item could not be found.
610 * * 1 FETCH (BODY ("TEXT" "PLAIN" ("CHARSET" "US-ASCII") NIL NIL "7BIT" 35 3))
611 * A006 OK FETCH completed.
613 * To get around this, we terminate the read loop on a NO and count
614 * on the fact that the sizes array has been preinitialized with a
615 * known-bad size value.
618 gen_send(sock, "FETCH 1 RFC822.SIZE", count);
620 gen_send(sock, "FETCH 1:%d RFC822.SIZE", count);
625 if ((ok = gen_recv(sock, buf, sizeof(buf))))
627 else if (strstr(buf, "OK") || strstr(buf, "NO"))
629 else if (sscanf(buf, "* %d FETCH (RFC822.SIZE %d)", &num, &size) == 2)
630 sizes[num - 1] = size;
636 static int imap_is_old(int sock, struct query *ctl, int number)
637 /* is the given message old? */
643 * Expunges change the fetch numbers, but unseen_messages contains
644 * indices from before any expungees were done. So neither the
645 * argument nor the values in message_sequence need to be decremented.
649 for (i = 0; i < unseen; i++)
650 if (unseen_messages[i] == number)
659 static int imap_fetch_headers(int sock, struct query *ctl,int number,int *lenp)
660 /* request headers of nth message */
662 char buf [MSGBUFSIZE+1];
665 /* expunges change the fetch numbers */
669 * This is blessed by RFC1176, RFC1730, RFC2060.
670 * According to the RFCs, it should *not* set the \Seen flag.
672 gen_send(sock, "FETCH %d RFC822.HEADER", number);
674 /* looking for FETCH response */
678 if ((ok = gen_recv(sock, buf, sizeof(buf))))
681 (sscanf(buf+2, "%d FETCH (%*s {%d}", &num, lenp) != 2);
689 static int imap_fetch_body(int sock, struct query *ctl, int number, int *lenp)
690 /* request body of nth message */
692 char buf [MSGBUFSIZE+1], *cp;
695 /* expunges change the fetch numbers */
699 * If we're using IMAP4, we can fetch the message without setting its
700 * seen flag. This is good! It means that if the protocol exchange
701 * craps out during the message, it will still be marked `unseen' on
704 * However...*don't* do this if we're using keep to suppress deletion!
705 * In that case, marking the seen flag is the only way to prevent the
706 * message from being re-fetched on subsequent runs (and according
707 * to RFC2060 p.43 this fetch should set Seen as a side effect).
709 * According to RFC2060, and Mark Crispin the IMAP maintainer,
710 * FETCH %d BODY[TEXT] and RFC822.TEXT are "functionally
711 * equivalent". However, we know of at least one server that
712 * treats them differently in the presence of MIME attachments;
713 * the latter form downloads the attachment, the former does not.
714 * The server is InterChange, and the fool who implemented this
715 * misfeature ought to be strung up by his thumbs.
717 * When I tried working around this by disabling use of the 4rev1 form,
718 * I found that doing this breaks operation with M$ Exchange.
719 * Annoyingly enough, Exchange's refusal to cope is technically legal
720 * under RFC2062. Trust Microsoft, the Great Enemy of interoperability
721 * standards, to find a way to make standards compliance irritating....
723 switch (imap_version)
725 case IMAP4rev1: /* RFC 2060 */
727 gen_send(sock, "FETCH %d BODY.PEEK[TEXT]", number);
729 gen_send(sock, "FETCH %d BODY[TEXT]", number);
732 case IMAP4: /* RFC 1730 */
734 gen_send(sock, "FETCH %d RFC822.TEXT.PEEK", number);
736 gen_send(sock, "FETCH %d RFC822.TEXT", number);
739 default: /* RFC 1176 */
740 gen_send(sock, "FETCH %d RFC822.TEXT", number);
744 /* looking for FETCH response */
748 if ((ok = gen_recv(sock, buf, sizeof(buf))))
751 (!strstr(buf+4, "FETCH") || sscanf(buf+2, "%d", &num) != 1);
757 * Try to extract a length from the FETCH response. RFC2060 requires
758 * it to be present, but at least one IMAP server (Novell GroupWise)
761 if ((cp = strchr(buf, '{')))
762 *lenp = atoi(cp + 1);
764 *lenp = -1; /* missing length part in FETCH reponse */
769 static int imap_trail(int sock, struct query *ctl, int number)
770 /* discard tail of FETCH response after reading message text */
772 /* expunges change the fetch numbers */
773 /* number -= expunged; */
777 char buf[MSGBUFSIZE+1];
780 if ((ok = gen_recv(sock, buf, sizeof(buf))))
783 /* UW IMAP returns "OK FETCH", Cyrus returns "OK Completed" */
784 if (strstr(buf, "OK"))
789 * Any IMAP server that fails to set Seen on a BODY[TEXT]
790 * fetch violates RFC2060 p.43 (top). This becomes an issue
791 * when keep is on, because seen messages aren't deleted and
792 * get refetched on each poll. As a workaround, if keep is on
793 * we can set the Seen flag explicitly.
795 * This code isn't used yet because we don't know of any IMAP
796 * servers broken in this way.
799 if ((ok = gen_transact(sock,
800 imap_version == IMAP4
801 ? "STORE %d +FLAGS.SILENT (\\Seen)"
802 : "STORE %d +FLAGS (\\Seen)",
805 #endif /* __UNUSED__ */
811 static int imap_delete(int sock, struct query *ctl, int number)
812 /* set delete flag for given message */
816 /* expunges change the fetch numbers */
820 * Use SILENT if possible as a minor throughput optimization.
821 * Note: this has been dropped from IMAP4rev1.
823 * We set Seen because there are some IMAP servers (notably HP
824 * OpenMail) that do message-receipt DSNs, but only when the seen
825 * bit is set. This is the appropriate time -- we get here right
826 * after the local SMTP response that says delivery was
829 if ((ok = gen_transact(sock,
830 imap_version == IMAP4
831 ? "STORE %d +FLAGS.SILENT (\\Seen \\Deleted)"
832 : "STORE %d +FLAGS (\\Seen \\Deleted)",
839 * We do an expunge after expunge_period messages, rather than
840 * just before quit, so that a line hit during a long session
841 * won't result in lots of messages being fetched again during
844 if (NUM_NONZERO(expunge_period) && (deletions % expunge_period) == 0)
845 internal_expunge(sock);
850 static int imap_logout(int sock, struct query *ctl)
851 /* send logout command */
853 /* if any un-expunged deletions remain, ship an expunge now */
855 internal_expunge(sock);
858 /* Memory clean-up */
860 free(unseen_messages);
861 #endif /* USE_SEARCH */
863 return(gen_transact(sock, "LOGOUT"));
866 const static struct method imap =
868 "IMAP", /* Internet Message Access Protocol */
872 #else /* INET6_ENABLE */
873 143, /* standard IMAP2bis/IMAP4 port */
874 993, /* ssl IMAP2bis/IMAP4 port */
875 #endif /* INET6_ENABLE */
876 TRUE, /* this is a tagged protocol */
877 FALSE, /* no message delimiter */
878 imap_ok, /* parse command response */
879 imap_getauth, /* get authorization */
880 imap_getrange, /* query range of messages */
881 imap_getsizes, /* get sizes of messages (used for ESMTP SIZE option) */
882 imap_is_old, /* no UID check */
883 imap_fetch_headers, /* request given message headers */
884 imap_fetch_body, /* request given message body */
885 imap_trail, /* eat message trailer */
886 imap_delete, /* delete the message */
887 imap_logout, /* expunge and exit */
888 TRUE, /* yes, we can re-poll */
891 int doIMAP(struct query *ctl)
892 /* retrieve messages using IMAP Version 2bis or Version 4 */
894 return(do_protocol(ctl, &imap));
897 /* imap.c ends here */