]> Pileus Git - ~andy/fetchmail/blob - imap.c
Refactored the Kerberos stuff.
[~andy/fetchmail] / imap.c
1 /*
2  * imap.c -- IMAP2bis/IMAP4 protocol methods
3  *
4  * Copyright 1997 by Eric S. Raymond
5  * For license terms, see the file COPYING in this directory.
6  */
7
8 #include  "config.h"
9 #include  <stdio.h>
10 #include  <string.h>
11 #include  <ctype.h>
12 #if defined(STDC_HEADERS)
13 #include  <stdlib.h>
14 #endif
15 #include  "fetchmail.h"
16 #include  "socket.h"
17
18 #ifdef GSSAPI
19 #ifdef HAVE_GSSAPI_H
20 #include <gssapi.h>
21 #endif
22 #ifdef HAVE_GSSAPI_GSSAPI_H
23 #include <gssapi/gssapi.h>
24 #endif
25 #ifdef HAVE_GSSAPI_GSSAPI_GENERIC_H
26 #include <gssapi/gssapi_generic.h>
27 #endif
28 #ifndef HAVE_GSS_C_NT_HOSTBASED_SERVICE
29 #define GSS_C_NT_HOSTBASED_SERVICE gss_nt_service_name
30 #endif
31 #endif
32
33 #include  "i18n.h"
34
35 #if OPIE_ENABLE
36 #include <opie.h>
37 #endif /* OPIE_ENABLE */
38
39 #ifndef strstr          /* glibc-2.1 declares this as a macro */
40 extern char *strstr();  /* needed on sysV68 R3V7.1. */
41 #endif /* strstr */
42
43 /* imap_version values */
44 #define IMAP2           -1      /* IMAP2 or IMAP2BIS, RFC1176 */
45 #define IMAP4           0       /* IMAP4 rev 0, RFC1730 */
46 #define IMAP4rev1       1       /* IMAP4 rev 1, RFC2060 */
47
48 static int count, unseen, deletions, imap_version, preauth; 
49 static int expunged, expunge_period, saved_timeout;
50 static flag do_idle;
51 static char capabilities[MSGBUFSIZE+1];
52 static unsigned int *unseen_messages;
53
54 int imap_ok(int sock, char *argbuf)
55 /* parse command response */
56 {
57     char buf[MSGBUFSIZE+1];
58
59     do {
60         int     ok;
61         char    *cp;
62
63         if ((ok = gen_recv(sock, buf, sizeof(buf))))
64             return(ok);
65
66         /* all tokens in responses are caseblind */
67         for (cp = buf; *cp; cp++)
68             if (islower(*cp))
69                 *cp = toupper(*cp);
70
71         /* interpret untagged status responses */
72         if (strstr(buf, "* CAPABILITY"))
73             strncpy(capabilities, buf + 12, sizeof(capabilities));
74         else if (strstr(buf, "EXISTS"))
75         {
76             count = atoi(buf+2);
77             /*
78              * Nasty kluge to handle RFC2177 IDLE.  If we know we're idling
79              * we can't wait for the tag matching the IDLE; we have to tell the
80              * server the IDLE is finished by shipping back a DONE when we
81              * see an EXISTS.  Only after that will a tagged response be
82              * shipped.  The idling flag also gets cleared on a timeout.
83              */
84             if (stage == STAGE_IDLE)
85             {
86                 /* we do our own write and report here to disable tagging */
87                 SockWrite(sock, "DONE\r\n", 6);
88                 if (outlevel >= O_MONITOR)
89                     report(stdout, "IMAP> DONE\n");
90
91                 mytimeout = saved_timeout;
92                 stage = STAGE_FETCH;
93             }
94         }
95         else if (strstr(buf, "PREAUTH"))
96             preauth = TRUE;
97     } while
98         (tag[0] != '\0' && strncmp(buf, tag, strlen(tag)));
99
100     if (tag[0] == '\0')
101     {
102         if (argbuf)
103             strcpy(argbuf, buf);
104         return(PS_SUCCESS); 
105     }
106     else
107     {
108         char    *cp;
109
110         /* skip the tag */
111         for (cp = buf; !isspace(*cp); cp++)
112             continue;
113         while (isspace(*cp))
114             cp++;
115
116         if (strncmp(cp, "OK", 2) == 0)
117         {
118             if (argbuf)
119                 strcpy(argbuf, cp);
120             return(PS_SUCCESS);
121         }
122         else if (strncmp(cp, "BAD", 3) == 0)
123             return(PS_ERROR);
124         else if (strncmp(cp, "NO", 2) == 0)
125         {
126             if (stage == STAGE_GETAUTH) 
127                 return(PS_AUTHFAIL);    /* RFC2060, 6.2.2 */
128             else
129                 return(PS_ERROR);
130         }
131         else
132             return(PS_PROTOCOL);
133     }
134 }
135
136 #if OPIE_ENABLE
137 static int do_otp(int sock, struct query *ctl)
138 {
139     int i, rval;
140     char buffer[128];
141     char challenge[OPIE_CHALLENGE_MAX+1];
142     char response[OPIE_RESPONSE_MAX+1];
143
144     gen_send(sock, "AUTHENTICATE X-OTP");
145
146     if (rval = gen_recv(sock, buffer, sizeof(buffer)))
147         return rval;
148
149     if ((i = from64tobits(challenge, buffer)) < 0) {
150         report(stderr, _("Could not decode initial BASE64 challenge\n"));
151         return PS_AUTHFAIL;
152     };
153
154
155     to64frombits(buffer, ctl->remotename, strlen(ctl->remotename));
156
157     if (outlevel >= O_MONITOR)
158         report(stdout, "IMAP> %s\n", buffer);
159
160     /* best not to count on the challenge code handling multiple writes */
161     strcat(buffer, "\r\n");
162     SockWrite(sock, buffer, strlen(buffer));
163
164     if (rval = gen_recv(sock, buffer, sizeof(buffer)))
165         return rval;
166
167     if ((i = from64tobits(challenge, buffer)) < 0) {
168         report(stderr, _("Could not decode OTP challenge\n"));
169         return PS_AUTHFAIL;
170     };
171
172     rval = opiegenerator(challenge, !strcmp(ctl->password, "opie") ? "" : ctl->password, response);
173     if ((rval == -2) && !run.poll_interval) {
174         char secret[OPIE_SECRET_MAX+1];
175         fprintf(stderr, _("Secret pass phrase: "));
176         if (opiereadpass(secret, sizeof(secret), 0))
177             rval = opiegenerator(challenge, secret, response);
178         memset(secret, 0, sizeof(secret));
179     };
180
181     if (rval)
182         return(PS_AUTHFAIL);
183
184     to64frombits(buffer, response, strlen(response));
185
186     if (outlevel >= O_MONITOR)
187         report(stdout, "IMAP> %s\n", buffer);
188     strcat(buffer, "\r\n");
189     SockWrite(sock, buffer, strlen(buffer));
190
191     if (rval = gen_recv(sock, buffer, sizeof(buffer)))
192         return rval;
193
194     if (strstr(buffer, "OK"))
195         return PS_SUCCESS;
196     else
197         return PS_AUTHFAIL;
198 };
199 #endif /* OPIE_ENABLE */
200
201 #ifdef GSSAPI
202 #define GSSAUTH_P_NONE      1
203 #define GSSAUTH_P_INTEGRITY 2
204 #define GSSAUTH_P_PRIVACY   4
205
206 static int do_gssauth(int sock, char *hostname, char *username)
207 {
208     gss_buffer_desc request_buf, send_token;
209     gss_buffer_t sec_token;
210     gss_name_t target_name;
211     gss_ctx_id_t context;
212     gss_OID mech_name;
213     gss_qop_t quality;
214     int cflags;
215     OM_uint32 maj_stat, min_stat;
216     char buf1[8192], buf2[8192], server_conf_flags;
217     unsigned long buf_size;
218     int result;
219
220     /* first things first: get an imap ticket for host */
221     sprintf(buf1, "imap@%s", hostname);
222     request_buf.value = buf1;
223     request_buf.length = strlen(buf1) + 1;
224     maj_stat = gss_import_name(&min_stat, &request_buf, GSS_C_NT_HOSTBASED_SERVICE,
225         &target_name);
226     if (maj_stat != GSS_S_COMPLETE) {
227         report(stderr, _("Couldn't get service name for [%s]\n"), buf1);
228         return PS_AUTHFAIL;
229     }
230     else if (outlevel >= O_DEBUG) {
231         maj_stat = gss_display_name(&min_stat, target_name, &request_buf,
232             &mech_name);
233         report(stderr, _("Using service name [%s]\n"),request_buf.value);
234         maj_stat = gss_release_buffer(&min_stat, &request_buf);
235     }
236
237     gen_send(sock, "AUTHENTICATE GSSAPI");
238
239     /* upon receipt of the GSSAPI authentication request, server returns
240      * null data ready response. */
241     if (result = gen_recv(sock, buf1, sizeof buf1)) {
242         return result;
243     }
244
245     /* now start the security context initialisation loop... */
246     sec_token = GSS_C_NO_BUFFER;
247     context = GSS_C_NO_CONTEXT;
248     if (outlevel >= O_VERBOSE)
249         report(stdout, _("Sending credentials\n"));
250     do {
251         send_token.length = 0;
252         send_token.value = NULL;
253         maj_stat = gss_init_sec_context(&min_stat, 
254                                         GSS_C_NO_CREDENTIAL,
255                                         &context, 
256                                         target_name, 
257                                         GSS_C_NO_OID, 
258                                         GSS_C_MUTUAL_FLAG | GSS_C_SEQUENCE_FLAG, 
259                                         0, 
260                                         GSS_C_NO_CHANNEL_BINDINGS, 
261                                         sec_token, 
262                                         NULL, 
263                                         &send_token, 
264                                         NULL, 
265                                         NULL);
266         if (maj_stat!=GSS_S_COMPLETE && maj_stat!=GSS_S_CONTINUE_NEEDED) {
267             report(stderr, _("Error exchanging credentials\n"));
268             gss_release_name(&min_stat, &target_name);
269             /* wake up server and await NO response */
270             SockWrite(sock, "\r\n", 2);
271             if (result = gen_recv(sock, buf1, sizeof buf1))
272                 return result;
273             return PS_AUTHFAIL;
274         }
275         to64frombits(buf1, send_token.value, send_token.length);
276         gss_release_buffer(&min_stat, &send_token);
277         strcat(buf1, "\r\n");
278         SockWrite(sock, buf1, strlen(buf1));
279         if (outlevel >= O_MONITOR)
280             report(stdout, "IMAP> %s\n", buf1);
281         if (maj_stat == GSS_S_CONTINUE_NEEDED) {
282             if (result = gen_recv(sock, buf1, sizeof buf1)) {
283                 gss_release_name(&min_stat, &target_name);
284                 return result;
285             }
286             request_buf.length = from64tobits(buf2, buf1 + 2);
287             request_buf.value = buf2;
288             sec_token = &request_buf;
289         }
290     } while (maj_stat == GSS_S_CONTINUE_NEEDED);
291     gss_release_name(&min_stat, &target_name);
292
293     /* get security flags and buffer size */
294     if (result = gen_recv(sock, buf1, sizeof buf1)) {
295         return result;
296     }
297     request_buf.length = from64tobits(buf2, buf1 + 2);
298     request_buf.value = buf2;
299
300     maj_stat = gss_unwrap(&min_stat, context, &request_buf, &send_token,
301         &cflags, &quality);
302     if (maj_stat != GSS_S_COMPLETE) {
303         report(stderr, _("Couldn't unwrap security level data\n"));
304         gss_release_buffer(&min_stat, &send_token);
305         return PS_AUTHFAIL;
306     }
307     if (outlevel >= O_DEBUG)
308         report(stdout, _("Credential exchange complete\n"));
309     /* first octet is security levels supported. We want none, for now */
310     server_conf_flags = ((char *)send_token.value)[0];
311     if ( !(((char *)send_token.value)[0] & GSSAUTH_P_NONE) ) {
312         report(stderr, _("Server requires integrity and/or privacy\n"));
313         gss_release_buffer(&min_stat, &send_token);
314         return PS_AUTHFAIL;
315     }
316     ((char *)send_token.value)[0] = 0;
317     buf_size = ntohl(*((long *)send_token.value));
318     /* we don't care about buffer size if we don't wrap data */
319     gss_release_buffer(&min_stat, &send_token);
320     if (outlevel >= O_DEBUG) {
321         report(stdout, _("Unwrapped security level flags: %s%s%s\n"),
322             server_conf_flags & GSSAUTH_P_NONE ? "N" : "-",
323             server_conf_flags & GSSAUTH_P_INTEGRITY ? "I" : "-",
324             server_conf_flags & GSSAUTH_P_PRIVACY ? "C" : "-");
325         report(stdout, _("Maximum GSS token size is %ld\n"),buf_size);
326     }
327
328     /* now respond in kind (hack!!!) */
329     buf_size = htonl(buf_size); /* do as they do... only matters if we do enc */
330     memcpy(buf1, &buf_size, 4);
331     buf1[0] = GSSAUTH_P_NONE;
332     strcpy(buf1+4, username); /* server decides if princ is user */
333     request_buf.length = 4 + strlen(username) + 1;
334     request_buf.value = buf1;
335     maj_stat = gss_wrap(&min_stat, context, 0, GSS_C_QOP_DEFAULT, &request_buf,
336         &cflags, &send_token);
337     if (maj_stat != GSS_S_COMPLETE) {
338         report(stderr, _("Error creating security level request\n"));
339         return PS_AUTHFAIL;
340     }
341     to64frombits(buf1, send_token.value, send_token.length);
342     if (outlevel >= O_DEBUG) {
343         report(stdout, _("Requesting authorization as %s\n"), username);
344         report(stdout, "IMAP> %s\n",buf1);
345     }
346     strcat(buf1, "\r\n");
347     SockWrite(sock, buf1, strlen(buf1));
348
349     /* we should be done. Get status and finish up */
350     do {
351         if (result = gen_recv(sock, buf1, sizeof buf1))
352            return result;
353     } while(strncmp(buf1, tag, strlen(tag)) != 0);
354     if (strstr(buf1, "OK")) {
355         /* flush security context */
356         if (outlevel >= O_DEBUG)
357             report(stdout, _("Releasing GSS credentials\n"));
358         maj_stat = gss_delete_sec_context(&min_stat, &context, &send_token);
359         if (maj_stat != GSS_S_COMPLETE) {
360             report(stderr, _("Error releasing credentials\n"));
361             return PS_AUTHFAIL;
362         }
363         /* send_token may contain a notification to the server to flush
364          * credentials. RFC 1731 doesn't specify what to do, and since this
365          * support is only for authentication, we'll assume the server
366          * knows enough to flush its own credentials */
367         gss_release_buffer(&min_stat, &send_token);
368         return PS_SUCCESS;
369     }
370
371     return PS_AUTHFAIL;
372 }       
373 #endif /* GSSAPI */
374
375 #if NTLM_ENABLE
376 #include "ntlm.h"
377
378 static tSmbNtlmAuthRequest   request;              
379 static tSmbNtlmAuthChallenge challenge;
380 static tSmbNtlmAuthResponse  response;
381
382 /*
383  * NTLM support by Grant Edwards.
384  *
385  * Handle MS-Exchange NTLM authentication method.  This is the same
386  * as the NTLM auth used by Samba for SMB related services. We just
387  * encode the packets in base64 instead of sending them out via a
388  * network interface.
389  * 
390  * Much source (ntlm.h, smb*.c smb*.h) was borrowed from Samba.
391  */
392
393 static int do_imap_ntlm(int sock, struct query *ctl)
394 {
395     char msgbuf[2048];
396     int result,len;
397   
398     gen_send(sock, "AUTHENTICATE NTLM");
399
400     if ((result = gen_recv(sock, msgbuf, sizeof msgbuf)))
401         return result;
402   
403     if (msgbuf[0] != '+')
404         return PS_AUTHFAIL;
405   
406     buildSmbNtlmAuthRequest(&request,ctl->remotename,NULL);
407
408     if (outlevel >= O_DEBUG)
409         dumpSmbNtlmAuthRequest(stdout, &request);
410
411     memset(msgbuf,0,sizeof msgbuf);
412     to64frombits (msgbuf, (unsigned char*)&request, SmbLength(&request));
413   
414     if (outlevel >= O_MONITOR)
415         report(stdout, "IMAP> %s\n", msgbuf);
416   
417     strcat(msgbuf,"\r\n");
418     SockWrite (sock, msgbuf, strlen (msgbuf));
419
420     if ((gen_recv(sock, msgbuf, sizeof msgbuf)))
421         return result;
422   
423     len = from64tobits ((unsigned char*)&challenge, msgbuf);
424     
425     if (outlevel >= O_DEBUG)
426         dumpSmbNtlmAuthChallenge(stdout, &challenge);
427     
428     buildSmbNtlmAuthResponse(&challenge, &response,ctl->remotename,ctl->password);
429   
430     if (outlevel >= O_DEBUG)
431         dumpSmbNtlmAuthResponse(stdout, &response);
432   
433     memset(msgbuf,0,sizeof msgbuf);
434     to64frombits (msgbuf, (unsigned char*)&response, SmbLength(&response));
435
436     if (outlevel >= O_MONITOR)
437         report(stdout, "IMAP> %s\n", msgbuf);
438       
439     strcat(msgbuf,"\r\n");
440
441     SockWrite (sock, msgbuf, strlen (msgbuf));
442   
443     if ((result = gen_recv (sock, msgbuf, sizeof msgbuf)))
444         return result;
445   
446     if (strstr (msgbuf, "OK"))
447         return PS_SUCCESS;
448     else
449         return PS_AUTHFAIL;
450 }
451 #endif /* NTLM */
452
453 int imap_canonicalize(char *result, char *raw, int maxlen)
454 /* encode an IMAP password as per RFC1730's quoting conventions */
455 {
456     int i, j;
457
458     j = 0;
459     for (i = 0; i < strlen(raw) && i < maxlen; i++)
460     {
461         if ((raw[i] == '\\') || (raw[i] == '"'))
462             result[j++] = '\\';
463         result[j++] = raw[i];
464     }
465     result[j] = '\0';
466
467     return(i);
468 }
469
470 int imap_getauth(int sock, struct query *ctl, char *greeting)
471 /* apply for connection authorization */
472 {
473     int ok = 0;
474
475     /* probe to see if we're running IMAP4 and can use RFC822.PEEK */
476     capabilities[0] = '\0';
477     if ((ok = gen_transact(sock, "CAPABILITY")) == PS_SUCCESS)
478     {
479         /* UW-IMAP server 10.173 notifies in all caps */
480         if (strstr(capabilities, "IMAP4REV1"))
481         {
482             imap_version = IMAP4rev1;
483             if (outlevel >= O_DEBUG)
484                 report(stdout, _("Protocol identified as IMAP4 rev 1\n"));
485         }
486         else
487         {
488             imap_version = IMAP4;
489             if (outlevel >= O_DEBUG)
490                 report(stdout, _("Protocol identified as IMAP4 rev 0\n"));
491         }
492     }
493     else if (ok == PS_ERROR)
494     {
495         imap_version = IMAP2;
496         if (outlevel >= O_DEBUG)
497             report(stdout, _("Protocol identified as IMAP2 or IMAP2BIS\n"));
498     }
499     else
500         return(ok);
501
502     peek_capable = (imap_version >= IMAP4);
503
504     /* 
505      * Assumption: expunges are cheap, so we want to do them
506      * after every message unless user said otherwise.
507      */
508     if (NUM_SPECIFIED(ctl->expunge))
509         expunge_period = NUM_VALUE_OUT(ctl->expunge);
510     else
511         expunge_period = 1;
512
513     /* 
514      * Handle idling.  We depend on coming through here on startup
515      * and after each timeout (including timeouts during idles).
516      */
517     if (strstr(capabilities, "IDLE") && ctl->idle)
518     {
519         do_idle = TRUE;
520         if (outlevel >= O_VERBOSE)
521             report(stdout, _("will idle after poll\n"));
522     }
523
524     /* 
525      * If either (a) we saw a PREAUTH token in the greeting, or
526      * (b) the user specified ssh preauthentication, then we're done.
527      */
528     if (preauth || ctl->server.preauthenticate == A_SSH)
529     {
530         preauth = FALSE;  /* reset for the next session */
531         return(PS_SUCCESS);
532     }
533
534 #if OPIE_ENABLE
535     if ((ctl->server.protocol == P_IMAP) && strstr(capabilities, "AUTH=X-OTP"))
536     {
537         if (outlevel >= O_DEBUG)
538             report(stdout, _("OTP authentication is supported\n"));
539         if (do_otp(sock, ctl) == PS_SUCCESS)
540             return(PS_SUCCESS);
541     };
542 #endif /* OPIE_ENABLE */
543
544 #ifdef GSSAPI
545     if (strstr(capabilities, "AUTH=GSSAPI"))
546     {
547         if (ctl->server.protocol == P_IMAP_GSS)
548         {
549             if (outlevel >= O_DEBUG)
550                 report(stdout, _("GSS authentication is supported\n"));
551             return do_gssauth(sock, ctl->server.truename, ctl->remotename);
552         }
553     }
554     else if (ctl->server.protocol == P_IMAP_GSS)
555     {
556         report(stderr, 
557                _("Required GSS capability not supported by server\n"));
558         return(PS_AUTHFAIL);
559     }
560 #endif /* GSSAPI */
561
562 #ifdef KERBEROS_V4
563     if (strstr(capabilities, "AUTH=KERBEROS_V4"))
564     {
565         if (outlevel >= O_DEBUG)
566             report(stdout, _("KERBEROS_V4 authentication is supported\n"));
567
568         if (ctl->server.protocol == P_IMAP_K4)
569         {
570             if ((ok = do_rfc1731(sock, "AUTHENTICATE", ctl->server.truename)))
571                 /* SASL cancellation of authentication */
572                 gen_send(sock, "*");
573             
574             return(ok);
575         }
576         /* else fall through to ordinary AUTH=LOGIN case */
577     }
578     else if (ctl->server.protocol == P_IMAP_K4)
579     {
580         report(stderr, 
581                _("Required KERBEROS_V4 capability not supported by server\n"));
582         return(PS_AUTHFAIL);
583     }
584 #endif /* KERBEROS_V4 */
585
586     if (strstr(capabilities, "AUTH=CRAM-MD5"))
587     {
588         if (outlevel >= O_DEBUG)
589             report (stdout, _("CRAM-MD5 authentication is supported\n"));
590         if (ctl->server.protocol != P_IMAP_LOGIN)
591         {
592             if ((ok = do_cram_md5 (sock, "AUTHENTICATE", ctl)))
593                 /* SASL cancellation of authentication */
594                 gen_send(sock, "*");
595
596             return(ok);
597         }
598     }
599     else if (ctl->server.protocol == P_IMAP_CRAM_MD5)
600     {
601         report(stderr,
602                _("Required CRAM-MD5 capability not supported by server\n"));
603         return(PS_AUTHFAIL);
604     }
605
606 #ifdef NTLM_ENABLE
607     if (strstr (capabilities, "AUTH=NTLM"))
608     {
609         if (outlevel >= O_DEBUG)
610             report (stdout, _("NTLM authentication is supported\n"));
611         return do_imap_ntlm (sock, ctl);
612     }
613 #endif /* NTLM_ENABLE */
614
615 #ifdef __UNUSED__       /* The Cyrus IMAP4rev1 server chokes on this */
616     /* this handles either AUTH=LOGIN or AUTH-LOGIN */
617     if ((imap_version >= IMAP4rev1) && (!strstr(capabilities, "LOGIN"))) {
618       report(stderr, 
619              _("Required LOGIN capability not supported by server\n"));
620       return PS_AUTHFAIL;
621     };
622 #endif /* __UNUSED__ */
623
624     {
625         /* these sizes guarantee no buffer overflow */
626         char    remotename[NAMELEN*2+1], password[PASSWORDLEN*2+1];
627
628         imap_canonicalize(remotename, ctl->remotename, NAMELEN);
629         imap_canonicalize(password, ctl->password, PASSWORDLEN);
630         ok = gen_transact(sock, "LOGIN \"%s\" \"%s\"", remotename, password);
631     }
632
633     if (ok)
634         return(ok);
635     
636     return(PS_SUCCESS);
637 }
638
639 static int internal_expunge(int sock)
640 /* ship an expunge, resetting associated counters */
641 {
642     int ok;
643
644     if ((ok = gen_transact(sock, "EXPUNGE")))
645         return(ok);
646
647     expunged += deletions;
648     deletions = 0;
649
650 #ifdef IMAP_UID /* not used */
651     expunge_uids(ctl);
652 #endif /* IMAP_UID */
653
654     return(PS_SUCCESS);
655 }
656
657 static int imap_idle(int sock)
658 /* start an RFC2177 IDLE */
659 {
660     stage = STAGE_IDLE;
661     saved_timeout = mytimeout;
662     mytimeout = 0;
663
664     return (gen_transact(sock, "IDLE"));
665 }
666
667 static int imap_getrange(int sock, 
668                          struct query *ctl, 
669                          const char *folder, 
670                          int *countp, int *newp, int *bytes)
671 /* get range of messages to be fetched */
672 {
673     int ok;
674     char buf[MSGBUFSIZE+1], *cp;
675
676     /* find out how many messages are waiting */
677     *bytes = -1;
678
679     if (pass > 1)
680     {
681         /* 
682          * We have to have an expunge here, otherwise the re-poll will
683          * infinite-loop picking up un-expunged messages -- unless the
684          * expunge period is one and we've been nuking each message 
685          * just after deletion.
686          */
687         ok = 0;
688         if (deletions && expunge_period != 1)
689             ok = internal_expunge(sock);
690         count = -1;
691         if (do_idle)
692             ok = imap_idle(sock);
693         if (ok || gen_transact(sock, "NOOP"))
694         {
695             report(stderr, _("re-poll failed\n"));
696             return(ok);
697         }
698         else if (count == -1)   /* no EXISTS response to NOOP/IDLE */
699         {
700             count = 0;
701         }
702         if (outlevel >= O_DEBUG)
703             report(stdout, _("%d messages waiting after re-poll\n"), count);
704     }
705     else
706     {
707         ok = gen_transact(sock, 
708                           check_only ? "EXAMINE \"%s\"" : "SELECT \"%s\"",
709                           folder ? folder : "INBOX");
710         if (ok != 0)
711         {
712             report(stderr, _("mailbox selection failed\n"));
713             return(ok);
714         }
715         else if (outlevel >= O_DEBUG)
716             report(stdout, _("%d messages waiting after first poll\n"), count);
717
718         /* no messages?  then we may need to idle until we get some */
719         if (count == 0 && do_idle)
720             imap_idle(sock);
721     }
722
723     *countp = count;
724
725     /* OK, now get a count of unseen messages and their indices */
726     if (!ctl->fetchall && count > 0)
727     {
728         if (unseen_messages)
729             free(unseen_messages);
730         unseen_messages = xmalloc(count * sizeof(unsigned int));
731         memset(unseen_messages, 0, count * sizeof(unsigned int));
732         unseen = 0;
733
734         gen_send(sock, "SEARCH UNSEEN");
735         do {
736             ok = gen_recv(sock, buf, sizeof(buf));
737             if (ok != 0)
738             {
739                 report(stderr, _("search for unseen messages failed\n"));
740                 return(PS_PROTOCOL);
741             }
742             else if ((cp = strstr(buf, "* SEARCH")))
743             {
744                 char    *ep;
745
746                 cp += 8;        /* skip "* SEARCH" */
747
748                 while (*cp && unseen < count)
749                 {
750                     /* skip whitespace */
751                     while (*cp && isspace(*cp))
752                         cp++;
753                     if (*cp) 
754                     {
755                         /*
756                          * Message numbers are between 1 and 2^32 inclusive,
757                          * so unsigned int is large enough.
758                          */
759                         unseen_messages[unseen]=(unsigned int)strtol(cp,&ep,10);
760
761                         if (outlevel >= O_DEBUG)
762                             report(stdout, 
763                                    _("%u is unseen\n"), 
764                                    unseen_messages[unseen]);
765                 
766                         unseen++;
767                         cp = ep;
768                     }
769                 }
770             }
771         } while
772             (tag[0] != '\0' && strncmp(buf, tag, strlen(tag)));
773     }
774
775     *newp = unseen;
776     expunged = 0;
777
778     return(PS_SUCCESS);
779 }
780
781 static int imap_getsizes(int sock, int count, int *sizes)
782 /* capture the sizes of all messages */
783 {
784     char buf [MSGBUFSIZE+1];
785
786     /*
787      * Some servers (as in, PMDF5.1-9.1 under OpenVMS 6.1)
788      * won't accept 1:1 as valid set syntax.  Some implementors
789      * should be taken out and shot for excessive anality.
790      *
791      * Microsoft Exchange (brain-dead piece of crap that it is) 
792      * sometimes gets its knickers in a knot about bodiless messages.
793      * You may see responses like this:
794      *
795      *  fetchmail: IMAP> A0004 FETCH 1:9 RFC822.SIZE
796      *  fetchmail: IMAP< * 2 FETCH (RFC822.SIZE 1187)
797      *  fetchmail: IMAP< * 3 FETCH (RFC822.SIZE 3954)
798      *  fetchmail: IMAP< * 4 FETCH (RFC822.SIZE 1944)
799      *  fetchmail: IMAP< * 5 FETCH (RFC822.SIZE 2933)
800      *  fetchmail: IMAP< * 6 FETCH (RFC822.SIZE 1854)
801      *  fetchmail: IMAP< * 7 FETCH (RFC822.SIZE 34054)
802      *  fetchmail: IMAP< * 8 FETCH (RFC822.SIZE 5561)
803      *  fetchmail: IMAP< * 9 FETCH (RFC822.SIZE 1101)
804      *  fetchmail: IMAP< A0004 NO The requested item could not be found.
805      *
806      * This means message 1 has only headers.  For kicks and grins
807      * you can telnet in and look:
808      *  A003 FETCH 1 FULL
809      *  A003 NO The requested item could not be found.
810      *  A004 fetch 1 rfc822.header
811      *  A004 NO The requested item could not be found.
812      *  A006 FETCH 1 BODY
813      *  * 1 FETCH (BODY ("TEXT" "PLAIN" ("CHARSET" "US-ASCII") NIL NIL "7BIT" 35 3))
814      *  A006 OK FETCH completed.
815      *
816      * To get around this, we terminate the read loop on a NO and count
817      * on the fact that the sizes array has been preinitialized with a
818      * known-bad size value.
819      */
820     if (count == 1)
821         gen_send(sock, "FETCH 1 RFC822.SIZE", count);
822     else
823         gen_send(sock, "FETCH 1:%d RFC822.SIZE", count);
824     for (;;)
825     {
826         int num, size, ok;
827
828         if ((ok = gen_recv(sock, buf, sizeof(buf))))
829             return(ok);
830         else if (strstr(buf, "OK") || strstr(buf, "NO"))
831             break;
832         else if (sscanf(buf, "* %d FETCH (RFC822.SIZE %d)", &num, &size) == 2)
833             sizes[num - 1] = size;
834     }
835
836     return(PS_SUCCESS);
837 }
838
839 static int imap_is_old(int sock, struct query *ctl, int number)
840 /* is the given message old? */
841 {
842     flag seen = TRUE;
843     int i;
844
845     /* 
846      * Expunges change the fetch numbers, but unseen_messages contains
847      * indices from before any expungees were done.  So neither the
848      * argument nor the values in message_sequence need to be decremented.
849      */
850
851     seen = TRUE;
852     for (i = 0; i < unseen; i++)
853         if (unseen_messages[i] == number)
854         {
855             seen = FALSE;
856             break;
857         }
858
859     return(seen);
860 }
861
862 static int imap_fetch_headers(int sock, struct query *ctl,int number,int *lenp)
863 /* request headers of nth message */
864 {
865     char buf [MSGBUFSIZE+1];
866     int num;
867
868     /* expunges change the fetch numbers */
869     number -= expunged;
870
871     /*
872      * This is blessed by RFC1176, RFC1730, RFC2060.
873      * According to the RFCs, it should *not* set the \Seen flag.
874      */
875     gen_send(sock, "FETCH %d RFC822.HEADER", number);
876
877     /* looking for FETCH response */
878     do {
879         int     ok;
880
881         if ((ok = gen_recv(sock, buf, sizeof(buf))))
882             return(ok);
883     } while
884         (sscanf(buf+2, "%d FETCH (%*s {%d}", &num, lenp) != 2);
885
886     if (num != number)
887         return(PS_ERROR);
888     else
889         return(PS_SUCCESS);
890 }
891
892 static int imap_fetch_body(int sock, struct query *ctl, int number, int *lenp)
893 /* request body of nth message */
894 {
895     char buf [MSGBUFSIZE+1], *cp;
896     int num;
897
898     /* expunges change the fetch numbers */
899     number -= expunged;
900
901     /*
902      * If we're using IMAP4, we can fetch the message without setting its
903      * seen flag.  This is good!  It means that if the protocol exchange
904      * craps out during the message, it will still be marked `unseen' on
905      * the server.
906      *
907      * However...*don't* do this if we're using keep to suppress deletion!
908      * In that case, marking the seen flag is the only way to prevent the
909      * message from being re-fetched on subsequent runs (and according
910      * to RFC2060 p.43 this fetch should set Seen as a side effect).
911      *
912      * According to RFC2060, and Mark Crispin the IMAP maintainer,
913      * FETCH %d BODY[TEXT] and RFC822.TEXT are "functionally 
914      * equivalent".  However, we know of at least one server that
915      * treats them differently in the presence of MIME attachments;
916      * the latter form downloads the attachment, the former does not.
917      * The server is InterChange, and the fool who implemented this
918      * misfeature ought to be strung up by his thumbs.  
919      *
920      * When I tried working around this by disabling use of the 4rev1 form,
921      * I found that doing this breaks operation with M$ Exchange.
922      * Annoyingly enough, Exchange's refusal to cope is technically legal
923      * under RFC2062.  Trust Microsoft, the Great Enemy of interoperability
924      * standards, to find a way to make standards compliance irritating....
925      */
926     switch (imap_version)
927     {
928     case IMAP4rev1:     /* RFC 2060 */
929         if (!ctl->keep)
930             gen_send(sock, "FETCH %d BODY.PEEK[TEXT]", number);
931         else
932             gen_send(sock, "FETCH %d BODY[TEXT]", number);
933         break;
934
935     case IMAP4:         /* RFC 1730 */
936         if (!ctl->keep)
937             gen_send(sock, "FETCH %d RFC822.TEXT.PEEK", number);
938         else
939             gen_send(sock, "FETCH %d RFC822.TEXT", number);
940         break;
941
942     default:            /* RFC 1176 */
943         gen_send(sock, "FETCH %d RFC822.TEXT", number);
944         break;
945     }
946
947     /* looking for FETCH response */
948     do {
949         int     ok;
950
951         if ((ok = gen_recv(sock, buf, sizeof(buf))))
952             return(ok);
953     } while
954         (!strstr(buf+4, "FETCH") || sscanf(buf+2, "%d", &num) != 1);
955
956     if (num != number)
957         return(PS_ERROR);
958
959     /*
960      * Try to extract a length from the FETCH response.  RFC2060 requires
961      * it to be present, but at least one IMAP server (Novell GroupWise)
962      * botches this.
963      */
964     if ((cp = strchr(buf, '{')))
965         *lenp = atoi(cp + 1);
966     else
967         *lenp = -1;     /* missing length part in FETCH reponse */
968
969     return(PS_SUCCESS);
970 }
971
972 static int imap_trail(int sock, struct query *ctl, int number)
973 /* discard tail of FETCH response after reading message text */
974 {
975     /* expunges change the fetch numbers */
976     /* number -= expunged; */
977
978     for (;;)
979     {
980         char buf[MSGBUFSIZE+1];
981         int ok;
982
983         if ((ok = gen_recv(sock, buf, sizeof(buf))))
984             return(ok);
985
986         /* UW IMAP returns "OK FETCH", Cyrus returns "OK Completed" */
987         if (strstr(buf, "OK"))
988             break;
989
990 #ifdef __UNUSED__
991         /*
992          * Any IMAP server that fails to set Seen on a BODY[TEXT]
993          * fetch violates RFC2060 p.43 (top).  This becomes an issue
994          * when keep is on, because seen messages aren't deleted and
995          * get refetched on each poll.  As a workaround, if keep is on
996          * we can set the Seen flag explicitly.
997          *
998          * This code isn't used yet because we don't know of any IMAP
999          * servers broken in this way.
1000          */
1001         if (ctl->keep)
1002             if ((ok = gen_transact(sock,
1003                         imap_version == IMAP4 
1004                                 ? "STORE %d +FLAGS.SILENT (\\Seen)"
1005                                 : "STORE %d +FLAGS (\\Seen)", 
1006                         number)))
1007                 return(ok);
1008 #endif /* __UNUSED__ */
1009     }
1010
1011     return(PS_SUCCESS);
1012 }
1013
1014 static int imap_delete(int sock, struct query *ctl, int number)
1015 /* set delete flag for given message */
1016 {
1017     int ok;
1018
1019     /* expunges change the fetch numbers */
1020     number -= expunged;
1021
1022     /*
1023      * Use SILENT if possible as a minor throughput optimization.
1024      * Note: this has been dropped from IMAP4rev1.
1025      *
1026      * We set Seen because there are some IMAP servers (notably HP
1027      * OpenMail) that do message-receipt DSNs, but only when the seen
1028      * bit is set.  This is the appropriate time -- we get here right
1029      * after the local SMTP response that says delivery was
1030      * successful.
1031      */
1032     if ((ok = gen_transact(sock,
1033                         imap_version == IMAP4 
1034                                 ? "STORE %d +FLAGS.SILENT (\\Seen \\Deleted)"
1035                                 : "STORE %d +FLAGS (\\Seen \\Deleted)", 
1036                         number)))
1037         return(ok);
1038     else
1039         deletions++;
1040
1041     /*
1042      * We do an expunge after expunge_period messages, rather than
1043      * just before quit, so that a line hit during a long session
1044      * won't result in lots of messages being fetched again during
1045      * the next session.
1046      */
1047     if (NUM_NONZERO(expunge_period) && (deletions % expunge_period) == 0)
1048         internal_expunge(sock);
1049
1050     return(PS_SUCCESS);
1051 }
1052
1053 static int imap_logout(int sock, struct query *ctl)
1054 /* send logout command */
1055 {
1056     /* if any un-expunged deletions remain, ship an expunge now */
1057     if (deletions)
1058         internal_expunge(sock);
1059
1060 #ifdef USE_SEARCH
1061     /* Memory clean-up */
1062     if (unseen_messages)
1063         free(unseen_messages);
1064 #endif /* USE_SEARCH */
1065
1066     return(gen_transact(sock, "LOGOUT"));
1067 }
1068
1069 const static struct method imap =
1070 {
1071     "IMAP",             /* Internet Message Access Protocol */
1072 #if INET6_ENABLE
1073     "imap",
1074     "imaps",
1075 #else /* INET6_ENABLE */
1076     143,                /* standard IMAP2bis/IMAP4 port */
1077     993,                /* ssl IMAP2bis/IMAP4 port */
1078 #endif /* INET6_ENABLE */
1079     TRUE,               /* this is a tagged protocol */
1080     FALSE,              /* no message delimiter */
1081     imap_ok,            /* parse command response */
1082     imap_canonicalize,  /* deal with embedded slashes and spaces */
1083     imap_getauth,       /* get authorization */
1084     imap_getrange,      /* query range of messages */
1085     imap_getsizes,      /* get sizes of messages (used for ESMTP SIZE option) */
1086     imap_is_old,        /* no UID check */
1087     imap_fetch_headers, /* request given message headers */
1088     imap_fetch_body,    /* request given message body */
1089     imap_trail,         /* eat message trailer */
1090     imap_delete,        /* delete the message */
1091     imap_logout,        /* expunge and exit */
1092     TRUE,               /* yes, we can re-poll */
1093 };
1094
1095 int doIMAP(struct query *ctl)
1096 /* retrieve messages using IMAP Version 2bis or Version 4 */
1097 {
1098     return(do_protocol(ctl, &imap));
1099 }
1100
1101 /* imap.c ends here */