]> Pileus Git - ~andy/fetchmail/blob - imap.c
Cosmetic cleanup.
[~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 KERBEROS_V4
19 #ifdef KERBEROS_V5
20 #include <kerberosIV/des.h>
21 #include <kerberosIV/krb.h>
22 #else
23 #if defined (__bsdi__)
24 #include <des.h>
25 #define krb_get_err_text(e) (krb_err_txt[e])
26 #endif
27 #if defined(__NetBSD__) || (__FreeBSD__) || defined(__linux__)
28 #define krb_get_err_text(e) (krb_err_txt[e])
29 #endif
30 #include <krb.h>
31 #endif
32 #endif /* KERBEROS_V4 */
33 #include  "i18n.h"
34
35 #ifdef GSSAPI
36 #ifdef HAVE_GSSAPI_H
37 #include <gssapi.h>
38 #endif
39 #ifdef HAVE_GSSAPI_GSSAPI_H
40 #include <gssapi/gssapi.h>
41 #endif
42 #ifdef HAVE_GSSAPI_GSSAPI_GENERIC_H
43 #include <gssapi/gssapi_generic.h>
44 #endif
45 #ifndef HAVE_GSS_C_NT_HOSTBASED_SERVICE
46 #define GSS_C_NT_HOSTBASED_SERVICE gss_nt_service_name
47 #endif
48 #endif
49
50 #include "md5.h"
51
52 #if OPIE_ENABLE
53 #include <opie.h>
54 #endif /* OPIE_ENABLE */
55
56 #ifndef strstr          /* glibc-2.1 declares this as a macro */
57 extern char *strstr();  /* needed on sysV68 R3V7.1. */
58 #endif /* strstr */
59
60 /* imap_version values */
61 #define IMAP2           -1      /* IMAP2 or IMAP2BIS, RFC1176 */
62 #define IMAP4           0       /* IMAP4 rev 0, RFC1730 */
63 #define IMAP4rev1       1       /* IMAP4 rev 1, RFC2060 */
64
65 static int count, seen, recent, unseen, deletions, imap_version, preauth; 
66 #ifdef USE_SEARCH
67 static int unseen_count;
68 #endif /* USE_SEARCH */
69 static int expunged, expunge_period, saved_timeout;
70 static flag do_idle;
71 static char capabilities[MSGBUFSIZE+1];
72
73 #ifdef USE_SEARCH
74 /*
75  * unseen_count is a dynamic array that holds the sequence number
76  * of unseen_messages. It is created whenever a SEARCH UNSEEN response
77  * is returned and deleted at logout time.
78  * Data are terminated by 0 in unseen_sequence since sequence numbers
79  * are between 1 and 2^32.
80  */
81 static unsigned int* unseen_sequence;
82 #endif /* USE_SEARCH */
83
84 int imap_ok(int sock, char *argbuf)
85 /* parse command response */
86 {
87     char buf [MSGBUFSIZE+1];
88
89     seen = 0;
90     do {
91         int     ok;
92         char    *cp;
93
94         if ((ok = gen_recv(sock, buf, sizeof(buf))))
95             return(ok);
96
97         /* all tokens in responses are caseblind */
98         for (cp = buf; *cp; cp++)
99             if (islower(*cp))
100                 *cp = toupper(*cp);
101
102         /* interpret untagged status responses */
103         if (strstr(buf, "* CAPABILITY"))
104             strncpy(capabilities, buf + 12, sizeof(capabilities));
105         if (strstr(buf, "EXISTS"))
106         {
107             count = atoi(buf+2);
108             /*
109              * Nasty kluge to handle RFC2177 IDLE.  If we know we're idling
110              * we can't wait for the tag matching the IDLE; we have to tell the
111              * server the IDLE is finished by shipping back a DONE when we
112              * see an EXISTS.  Only after that will a tagged response be
113              * shipped.  The idling flag also gets cleared on a timeout.
114              */
115             if (stage == STAGE_IDLE)
116             {
117                 /* we do our own write and report here to disable tagging */
118                 SockWrite(sock, "DONE\r\n", 6);
119                 if (outlevel >= O_MONITOR)
120                     report(stdout, "IMAP> DONE\n");
121
122                 mytimeout = saved_timeout;
123                 stage = STAGE_FETCH;
124             }
125         }
126         if (strstr(buf, "RECENT"))
127             recent = atoi(buf+2);
128         if (strstr(buf, "UNSEEN"))
129         {
130             char        *cp;
131
132             /*
133              * Handle both "* 42 UNSEEN" (if that ever happens) and 
134              * "* OK [UNSEEN 42] 42". Note that what this gets us is
135              * a minimum index, not a count.
136              */
137             unseen = 0;
138             for (cp = buf; *cp && !isdigit(*cp); cp++)
139                 continue;
140             unseen = atoi(cp);
141         }
142         if (strstr(buf, "FLAGS"))
143             seen = (strstr(buf, "SEEN") != (char *)NULL);
144         if (strstr(buf, "PREAUTH"))
145             preauth = TRUE;
146 #ifdef USE_SEARCH
147         /*
148          * The response to SEARCH UNSEEN looks like:
149          * * SEARCH list of sequence numbers
150          * It means stuffing unseen_sequence and eating white space in between.
151          */
152         if (strstr(buf, "* SEARCH")) {
153             char        *cp = strstr(buf, "SEARCH") + 6; /* Start after SEARCH */
154             char        *endofnumber = NULL;
155
156             /* unseen_sequence already exists. Discard it for a new use */
157             if (unseen_sequence)
158                 free(unseen_sequence);
159
160             /* 
161              * unseen_sequence memory allocation
162              * Chances are it is grossly oversized, but there is no
163              * way to size it correctly in one pass without
164              * relying on the RECENT response. Which is exactly why
165              * we're using SEARCH UNSEEN.
166              * Fill unseen_sequence with zero because 0 means end of data
167              */
168             unseen_sequence = xmalloc(count * sizeof(unsigned int));
169             memset(unseen_sequence, 0, count * sizeof(unsigned int));
170             unseen_count = 0;
171
172             while (*cp) {
173                 /* White space */
174                 while (*cp && isspace(*cp)) cp++;
175                 /* Number is between 1 and 2^32 included so unsigned int is enough. */
176                 if (*cp) {
177                 /*
178                  * To avoid a buffer overflow.
179                  * That count would be less than unseen_count is not supposed to
180                  * happen, but you never know.
181                  */
182                 if (unseen_count >= count) break; /* Flush the rest of the command? */
183                 unseen_sequence[unseen_count++] = (unsigned int)strtol(cp, &endofnumber, 10);
184
185                 if (outlevel >= O_DEBUG)
186                     report(stdout, _("%u is unseen\n"), unseen_sequence[unseen_count - 1]);
187                 
188                     cp = endofnumber;
189                 }
190             }
191
192             if (unseen_sequence[0] > 0 && unseen_count > 0)
193                 unseen = unseen_sequence[0];
194             }
195 #endif /* USE_SEARCH */
196     } while
197         (tag[0] != '\0' && strncmp(buf, tag, strlen(tag)));
198
199     if (tag[0] == '\0')
200     {
201         if (argbuf)
202             strcpy(argbuf, buf);
203         return(PS_SUCCESS); 
204     }
205     else
206     {
207         char    *cp;
208
209         /* skip the tag */
210         for (cp = buf; !isspace(*cp); cp++)
211             continue;
212         while (isspace(*cp))
213             cp++;
214
215         if (strncmp(cp, "PREAUTH", 2) == 0)
216         {
217             if (argbuf)
218                 strcpy(argbuf, cp);
219             preauth = TRUE;
220             return(PS_SUCCESS);
221         }
222         else if (strncmp(cp, "OK", 2) == 0)
223         {
224             if (argbuf)
225                 strcpy(argbuf, cp);
226             return(PS_SUCCESS);
227         }
228         else if (strncmp(cp, "BAD", 3) == 0)
229             return(PS_ERROR);
230         else if (strncmp(cp, "NO", 2) == 0)
231         {
232             if (stage == STAGE_GETAUTH) 
233                 return(PS_AUTHFAIL);    /* RFC2060, 6.2.2 */
234             else
235                 return(PS_ERROR);
236         }
237         else
238             return(PS_PROTOCOL);
239     }
240 }
241
242 #if OPIE_ENABLE
243 static int do_otp(int sock, struct query *ctl)
244 {
245     int i, rval;
246     char buffer[128];
247     char challenge[OPIE_CHALLENGE_MAX+1];
248     char response[OPIE_RESPONSE_MAX+1];
249
250     gen_send(sock, "AUTHENTICATE X-OTP");
251
252     if (rval = gen_recv(sock, buffer, sizeof(buffer)))
253         return rval;
254
255     if ((i = from64tobits(challenge, buffer)) < 0) {
256         report(stderr, _("Could not decode initial BASE64 challenge\n"));
257         return PS_AUTHFAIL;
258     };
259
260
261     to64frombits(buffer, ctl->remotename, strlen(ctl->remotename));
262
263     if (outlevel >= O_MONITOR)
264         report(stdout, "IMAP> %s\n", buffer);
265
266     /* best not to count on the challenge code handling multiple writes */
267     strcat(buffer, "\r\n");
268     SockWrite(sock, buffer, strlen(buffer));
269
270     if (rval = gen_recv(sock, buffer, sizeof(buffer)))
271         return rval;
272
273     if ((i = from64tobits(challenge, buffer)) < 0) {
274         report(stderr, _("Could not decode OTP challenge\n"));
275         return PS_AUTHFAIL;
276     };
277
278     rval = opiegenerator(challenge, !strcmp(ctl->password, "opie") ? "" : ctl->password, response);
279     if ((rval == -2) && !run.poll_interval) {
280         char secret[OPIE_SECRET_MAX+1];
281         fprintf(stderr, _("Secret pass phrase: "));
282         if (opiereadpass(secret, sizeof(secret), 0))
283             rval = opiegenerator(challenge, secret, response);
284         memset(secret, 0, sizeof(secret));
285     };
286
287     if (rval)
288         return(PS_AUTHFAIL);
289
290     to64frombits(buffer, response, strlen(response));
291
292     if (outlevel >= O_MONITOR)
293         report(stdout, "IMAP> %s\n", buffer);
294     strcat(buffer, "\r\n");
295     SockWrite(sock, buffer, strlen(buffer));
296
297     if (rval = gen_recv(sock, buffer, sizeof(buffer)))
298         return rval;
299
300     if (strstr(buffer, "OK"))
301         return PS_SUCCESS;
302     else
303         return PS_AUTHFAIL;
304 };
305 #endif /* OPIE_ENABLE */
306
307 #ifdef KERBEROS_V4
308 #if SIZEOF_INT == 4
309 typedef int     int32;
310 #elif SIZEOF_SHORT == 4
311 typedef short   int32;
312 #elif SIZEOF_LONG == 4
313 typedef long    int32;
314 #else
315 #error Cannot deduce a 32-bit-type
316 #endif
317
318 static int do_rfc1731(int sock, char *truename)
319 /* authenticate as per RFC1731 -- note 32-bit integer requirement here */
320 {
321     int result = 0, len;
322     char buf1[4096], buf2[4096];
323     union {
324       int32 cint;
325       char cstr[4];
326     } challenge1, challenge2;
327     char srvinst[INST_SZ];
328     char *p;
329     char srvrealm[REALM_SZ];
330     KTEXT_ST authenticator;
331     CREDENTIALS credentials;
332     char tktuser[MAX_K_NAME_SZ+1+INST_SZ+1+REALM_SZ+1];
333     char tktinst[INST_SZ];
334     char tktrealm[REALM_SZ];
335     des_cblock session;
336     des_key_schedule schedule;
337
338     gen_send(sock, "AUTHENTICATE KERBEROS_V4");
339
340     /* The data encoded in the first ready response contains a random
341      * 32-bit number in network byte order.  The client should respond
342      * with a Kerberos ticket and an authenticator for the principal
343      * "imap.hostname@realm", where "hostname" is the first component
344      * of the host name of the server with all letters in lower case
345      * and where "realm" is the Kerberos realm of the server.  The
346      * encrypted checksum field included within the Kerberos
347      * authenticator should contain the server provided 32-bit number
348      * in network byte order.
349      */
350
351     if (result = gen_recv(sock, buf1, sizeof buf1)) {
352         return result;
353     }
354
355     len = from64tobits(challenge1.cstr, buf1);
356     if (len < 0) {
357         report(stderr, _("could not decode initial BASE64 challenge\n"));
358         return PS_AUTHFAIL;
359     }
360
361     /* this patch by Dan Root <dar@thekeep.org> solves an endianess
362      * problem. */
363     {
364         char tmp[4];
365
366         *(int *)tmp = ntohl(*(int *) challenge1.cstr);
367         memcpy(challenge1.cstr, tmp, sizeof(tmp));
368     }
369
370     /* Client responds with a Kerberos ticket and an authenticator for
371      * the principal "imap.hostname@realm" where "hostname" is the
372      * first component of the host name of the server with all letters
373      * in lower case and where "realm" is the Kerberos realm of the
374      * server.  The encrypted checksum field included within the
375      * Kerberos authenticator should contain the server-provided
376      * 32-bit number in network byte order.
377      */
378
379     strncpy(srvinst, truename, (sizeof srvinst)-1);
380     srvinst[(sizeof srvinst)-1] = '\0';
381     for (p = srvinst; *p; p++) {
382       if (isupper(*p)) {
383         *p = tolower(*p);
384       }
385     }
386
387     strncpy(srvrealm, (char *)krb_realmofhost(srvinst), (sizeof srvrealm)-1);
388     srvrealm[(sizeof srvrealm)-1] = '\0';
389     if (p = strchr(srvinst, '.')) {
390       *p = '\0';
391     }
392
393     result = krb_mk_req(&authenticator, "imap", srvinst, srvrealm, 0);
394     if (result) {
395         report(stderr, "krb_mq_req: %s\n", krb_get_err_text(result));
396         return PS_AUTHFAIL;
397     }
398
399     result = krb_get_cred("imap", srvinst, srvrealm, &credentials);
400     if (result) {
401         report(stderr, "krb_get_cred: %s\n", krb_get_err_text(result));
402         return PS_AUTHFAIL;
403     }
404
405     memcpy(session, credentials.session, sizeof session);
406     memset(&credentials, 0, sizeof credentials);
407     des_key_sched(&session, schedule);
408
409     result = krb_get_tf_fullname(TKT_FILE, tktuser, tktinst, tktrealm);
410     if (result) {
411         report(stderr, "krb_get_tf_fullname: %s\n", krb_get_err_text(result));
412         return PS_AUTHFAIL;
413     }
414
415     if (strcmp(tktuser, user) != 0) {
416         report(stderr, 
417                _("principal %s in ticket does not match -u %s\n"), tktuser,
418                 user);
419         return PS_AUTHFAIL;
420     }
421
422     if (tktinst[0]) {
423         report(stderr, 
424                _("non-null instance (%s) might cause strange behavior\n"),
425                 tktinst);
426         strcat(tktuser, ".");
427         strcat(tktuser, tktinst);
428     }
429
430     if (strcmp(tktrealm, srvrealm) != 0) {
431         strcat(tktuser, "@");
432         strcat(tktuser, tktrealm);
433     }
434
435     result = krb_mk_req(&authenticator, "imap", srvinst, srvrealm,
436             challenge1.cint);
437     if (result) {
438         report(stderr, "krb_mq_req: %s\n", krb_get_err_text(result));
439         return PS_AUTHFAIL;
440     }
441
442     to64frombits(buf1, authenticator.dat, authenticator.length);
443     if (outlevel >= O_MONITOR) {
444         report(stdout, "IMAP> %s\n", buf1);
445     }
446     strcat(buf1, "\r\n");
447     SockWrite(sock, buf1, strlen(buf1));
448
449     /* Upon decrypting and verifying the ticket and authenticator, the
450      * server should verify that the contained checksum field equals
451      * the original server provided random 32-bit number.  Should the
452      * verification be successful, the server must add one to the
453      * checksum and construct 8 octets of data, with the first four
454      * octets containing the incremented checksum in network byte
455      * order, the fifth octet containing a bit-mask specifying the
456      * protection mechanisms supported by the server, and the sixth
457      * through eighth octets containing, in network byte order, the
458      * maximum cipher-text buffer size the server is able to receive.
459      * The server must encrypt the 8 octets of data in the session key
460      * and issue that encrypted data in a second ready response.  The
461      * client should consider the server authenticated if the first
462      * four octets the un-encrypted data is equal to one plus the
463      * checksum it previously sent.
464      */
465     
466     if (result = gen_recv(sock, buf1, sizeof buf1))
467         return result;
468
469     /* The client must construct data with the first four octets
470      * containing the original server-issued checksum in network byte
471      * order, the fifth octet containing the bit-mask specifying the
472      * selected protection mechanism, the sixth through eighth octets
473      * containing in network byte order the maximum cipher-text buffer
474      * size the client is able to receive, and the following octets
475      * containing a user name string.  The client must then append
476      * from one to eight octets so that the length of the data is a
477      * multiple of eight octets. The client must then PCBC encrypt the
478      * data with the session key and respond to the second ready
479      * response with the encrypted data.  The server decrypts the data
480      * and verifies the contained checksum.  The username field
481      * identifies the user for whom subsequent IMAP operations are to
482      * be performed; the server must verify that the principal
483      * identified in the Kerberos ticket is authorized to connect as
484      * that user.  After these verifications, the authentication
485      * process is complete.
486      */
487
488     len = from64tobits(buf2, buf1);
489     if (len < 0) {
490         report(stderr, _("could not decode BASE64 ready response\n"));
491         return PS_AUTHFAIL;
492     }
493
494     des_ecb_encrypt((des_cblock *)buf2, (des_cblock *)buf2, schedule, 0);
495     memcpy(challenge2.cstr, buf2, 4);
496     if (ntohl(challenge2.cint) != challenge1.cint + 1) {
497         report(stderr, _("challenge mismatch\n"));
498         return PS_AUTHFAIL;
499     }       
500
501     memset(authenticator.dat, 0, sizeof authenticator.dat);
502
503     result = htonl(challenge1.cint);
504     memcpy(authenticator.dat, &result, sizeof result);
505
506     /* The protection mechanisms and their corresponding bit-masks are as
507      * follows:
508      *
509      * 1 No protection mechanism
510      * 2 Integrity (krb_mk_safe) protection
511      * 4 Privacy (krb_mk_priv) protection
512      */
513     authenticator.dat[4] = 1;
514
515     len = strlen(tktuser);
516     strncpy(authenticator.dat+8, tktuser, len);
517     authenticator.length = len + 8 + 1;
518     while (authenticator.length & 7) {
519         authenticator.length++;
520     }
521     des_pcbc_encrypt((des_cblock *)authenticator.dat,
522             (des_cblock *)authenticator.dat, authenticator.length, schedule,
523             &session, 1);
524
525     to64frombits(buf1, authenticator.dat, authenticator.length);
526     if (outlevel >= O_MONITOR) {
527         report(stdout, "IMAP> %s\n", buf1);
528     }
529
530     strcat(buf1, "\r\n");
531     SockWrite(sock, buf1, strlen(buf1));
532
533     if (result = gen_recv(sock, buf1, sizeof buf1))
534         return result;
535
536     if (strstr(buf1, "OK")) {
537         return PS_SUCCESS;
538     }
539     else {
540         return PS_AUTHFAIL;
541     }
542 }
543 #endif /* KERBEROS_V4 */
544
545 #ifdef GSSAPI
546 #define GSSAUTH_P_NONE      1
547 #define GSSAUTH_P_INTEGRITY 2
548 #define GSSAUTH_P_PRIVACY   4
549
550 static int do_gssauth(int sock, char *hostname, char *username)
551 {
552     gss_buffer_desc request_buf, send_token;
553     gss_buffer_t sec_token;
554     gss_name_t target_name;
555     gss_ctx_id_t context;
556     gss_OID mech_name;
557     gss_qop_t quality;
558     int cflags;
559     OM_uint32 maj_stat, min_stat;
560     char buf1[8192], buf2[8192], server_conf_flags;
561     unsigned long buf_size;
562     int result;
563
564     /* first things first: get an imap ticket for host */
565     sprintf(buf1, "imap@%s", hostname);
566     request_buf.value = buf1;
567     request_buf.length = strlen(buf1) + 1;
568     maj_stat = gss_import_name(&min_stat, &request_buf, GSS_C_NT_HOSTBASED_SERVICE,
569         &target_name);
570     if (maj_stat != GSS_S_COMPLETE) {
571         report(stderr, _("Couldn't get service name for [%s]\n"), buf1);
572         return PS_AUTHFAIL;
573     }
574     else if (outlevel >= O_DEBUG) {
575         maj_stat = gss_display_name(&min_stat, target_name, &request_buf,
576             &mech_name);
577         report(stderr, _("Using service name [%s]\n"),request_buf.value);
578         maj_stat = gss_release_buffer(&min_stat, &request_buf);
579     }
580
581     gen_send(sock, "AUTHENTICATE GSSAPI");
582
583     /* upon receipt of the GSSAPI authentication request, server returns
584      * null data ready response. */
585     if (result = gen_recv(sock, buf1, sizeof buf1)) {
586         return result;
587     }
588
589     /* now start the security context initialisation loop... */
590     sec_token = GSS_C_NO_BUFFER;
591     context = GSS_C_NO_CONTEXT;
592     if (outlevel >= O_VERBOSE)
593         report(stdout, _("Sending credentials\n"));
594     do {
595         send_token.length = 0;
596         send_token.value = NULL;
597         maj_stat = gss_init_sec_context(&min_stat, 
598                                         GSS_C_NO_CREDENTIAL,
599                                         &context, 
600                                         target_name, 
601                                         GSS_C_NO_OID, 
602                                         GSS_C_MUTUAL_FLAG | GSS_C_SEQUENCE_FLAG, 
603                                         0, 
604                                         GSS_C_NO_CHANNEL_BINDINGS, 
605                                         sec_token, 
606                                         NULL, 
607                                         &send_token, 
608                                         NULL, 
609                                         NULL);
610         if (maj_stat!=GSS_S_COMPLETE && maj_stat!=GSS_S_CONTINUE_NEEDED) {
611             report(stderr, _("Error exchanging credentials\n"));
612             gss_release_name(&min_stat, &target_name);
613             /* wake up server and await NO response */
614             SockWrite(sock, "\r\n", 2);
615             if (result = gen_recv(sock, buf1, sizeof buf1))
616                 return result;
617             return PS_AUTHFAIL;
618         }
619         to64frombits(buf1, send_token.value, send_token.length);
620         gss_release_buffer(&min_stat, &send_token);
621         strcat(buf1, "\r\n");
622         SockWrite(sock, buf1, strlen(buf1));
623         if (outlevel >= O_MONITOR)
624             report(stdout, "IMAP> %s\n", buf1);
625         if (maj_stat == GSS_S_CONTINUE_NEEDED) {
626             if (result = gen_recv(sock, buf1, sizeof buf1)) {
627                 gss_release_name(&min_stat, &target_name);
628                 return result;
629             }
630             request_buf.length = from64tobits(buf2, buf1 + 2);
631             request_buf.value = buf2;
632             sec_token = &request_buf;
633         }
634     } while (maj_stat == GSS_S_CONTINUE_NEEDED);
635     gss_release_name(&min_stat, &target_name);
636
637     /* get security flags and buffer size */
638     if (result = gen_recv(sock, buf1, sizeof buf1)) {
639         return result;
640     }
641     request_buf.length = from64tobits(buf2, buf1 + 2);
642     request_buf.value = buf2;
643
644     maj_stat = gss_unwrap(&min_stat, context, &request_buf, &send_token,
645         &cflags, &quality);
646     if (maj_stat != GSS_S_COMPLETE) {
647         report(stderr, _("Couldn't unwrap security level data\n"));
648         gss_release_buffer(&min_stat, &send_token);
649         return PS_AUTHFAIL;
650     }
651     if (outlevel >= O_DEBUG)
652         report(stdout, _("Credential exchange complete\n"));
653     /* first octet is security levels supported. We want none, for now */
654     server_conf_flags = ((char *)send_token.value)[0];
655     if ( !(((char *)send_token.value)[0] & GSSAUTH_P_NONE) ) {
656         report(stderr, _("Server requires integrity and/or privacy\n"));
657         gss_release_buffer(&min_stat, &send_token);
658         return PS_AUTHFAIL;
659     }
660     ((char *)send_token.value)[0] = 0;
661     buf_size = ntohl(*((long *)send_token.value));
662     /* we don't care about buffer size if we don't wrap data */
663     gss_release_buffer(&min_stat, &send_token);
664     if (outlevel >= O_DEBUG) {
665         report(stdout, _("Unwrapped security level flags: %s%s%s\n"),
666             server_conf_flags & GSSAUTH_P_NONE ? "N" : "-",
667             server_conf_flags & GSSAUTH_P_INTEGRITY ? "I" : "-",
668             server_conf_flags & GSSAUTH_P_PRIVACY ? "C" : "-");
669         report(stdout, _("Maximum GSS token size is %ld\n"),buf_size);
670     }
671
672     /* now respond in kind (hack!!!) */
673     buf_size = htonl(buf_size); /* do as they do... only matters if we do enc */
674     memcpy(buf1, &buf_size, 4);
675     buf1[0] = GSSAUTH_P_NONE;
676     strcpy(buf1+4, username); /* server decides if princ is user */
677     request_buf.length = 4 + strlen(username) + 1;
678     request_buf.value = buf1;
679     maj_stat = gss_wrap(&min_stat, context, 0, GSS_C_QOP_DEFAULT, &request_buf,
680         &cflags, &send_token);
681     if (maj_stat != GSS_S_COMPLETE) {
682         report(stderr, _("Error creating security level request\n"));
683         return PS_AUTHFAIL;
684     }
685     to64frombits(buf1, send_token.value, send_token.length);
686     if (outlevel >= O_DEBUG) {
687         report(stdout, _("Requesting authorization as %s\n"), username);
688         report(stdout, "IMAP> %s\n",buf1);
689     }
690     strcat(buf1, "\r\n");
691     SockWrite(sock, buf1, strlen(buf1));
692
693     /* we should be done. Get status and finish up */
694     if (result = gen_recv(sock, buf1, sizeof buf1))
695         return result;
696     if (strstr(buf1, "OK")) {
697         /* flush security context */
698         if (outlevel >= O_DEBUG)
699             report(stdout, _("Releasing GSS credentials\n"));
700         maj_stat = gss_delete_sec_context(&min_stat, &context, &send_token);
701         if (maj_stat != GSS_S_COMPLETE) {
702             report(stderr, _("Error releasing credentials\n"));
703             return PS_AUTHFAIL;
704         }
705         /* send_token may contain a notification to the server to flush
706          * credentials. RFC 1731 doesn't specify what to do, and since this
707          * support is only for authentication, we'll assume the server
708          * knows enough to flush its own credentials */
709         gss_release_buffer(&min_stat, &send_token);
710         return PS_SUCCESS;
711     }
712
713     return PS_AUTHFAIL;
714 }       
715 #endif /* GSSAPI */
716
717 static void hmac_md5 (unsigned char *password,  size_t pass_len,
718                       unsigned char *challenge, size_t chal_len,
719                       unsigned char *response,  size_t resp_len)
720 {
721     int i;
722     unsigned char ipad[64];
723     unsigned char opad[64];
724     unsigned char hash_passwd[16];
725
726     MD5_CTX ctx;
727     
728     if (resp_len != 16)
729         return;
730
731     if (pass_len > sizeof (ipad))
732     {
733         MD5Init (&ctx);
734         MD5Update (&ctx, password, pass_len);
735         MD5Final (hash_passwd, &ctx);
736         password = hash_passwd; pass_len = sizeof (hash_passwd);
737     }
738
739     memset (ipad, 0, sizeof (ipad));
740     memset (opad, 0, sizeof (opad));
741     memcpy (ipad, password, pass_len);
742     memcpy (opad, password, pass_len);
743
744     for (i=0; i<64; i++) {
745         ipad[i] ^= 0x36;
746         opad[i] ^= 0x5c;
747     }
748
749     MD5Init (&ctx);
750     MD5Update (&ctx, ipad, sizeof (ipad));
751     MD5Update (&ctx, challenge, chal_len);
752     MD5Final (response, &ctx);
753
754     MD5Init (&ctx);
755     MD5Update (&ctx, opad, sizeof (opad));
756     MD5Update (&ctx, response, resp_len);
757     MD5Final (response, &ctx);
758 }
759
760 #if NTLM_ENABLE
761 #include "ntlm.h"
762
763 static tSmbNtlmAuthRequest   request;              
764 static tSmbNtlmAuthChallenge challenge;
765 static tSmbNtlmAuthResponse  response;
766
767 /*
768  * NTLM support by Grant Edwards.
769  *
770  * Handle MS-Exchange NTLM authentication method.  This is the same
771  * as the NTLM auth used by Samba for SMB related services. We just
772  * encode the packets in base64 instead of sending them out via a
773  * network interface.
774  * 
775  * Much source (ntlm.h, smb*.c smb*.h) was borrowed from Samba.
776  */
777
778 static int do_imap_ntlm(int sock, struct query *ctl)
779 {
780     char msgbuf[2048];
781     int result,len;
782   
783     gen_send(sock, "AUTHENTICATE NTLM");
784
785     if ((result = gen_recv(sock, msgbuf, sizeof msgbuf)))
786         return result;
787   
788     if (msgbuf[0] != '+')
789         return PS_AUTHFAIL;
790   
791     buildSmbNtlmAuthRequest(&request,ctl->remotename,NULL);
792
793     if (outlevel >= O_DEBUG)
794         dumpSmbNtlmAuthRequest(stdout, &request);
795
796     memset(msgbuf,0,sizeof msgbuf);
797     to64frombits (msgbuf, (unsigned char*)&request, SmbLength(&request));
798   
799     if (outlevel >= O_MONITOR)
800         report(stdout, "IMAP> %s\n", msgbuf);
801   
802     strcat(msgbuf,"\r\n");
803     SockWrite (sock, msgbuf, strlen (msgbuf));
804
805     if ((gen_recv(sock, msgbuf, sizeof msgbuf)))
806         return result;
807   
808     len = from64tobits ((unsigned char*)&challenge, msgbuf);
809     
810     if (outlevel >= O_DEBUG)
811         dumpSmbNtlmAuthChallenge(stdout, &challenge);
812     
813     buildSmbNtlmAuthResponse(&challenge, &response,ctl->remotename,ctl->password);
814   
815     if (outlevel >= O_DEBUG)
816         dumpSmbNtlmAuthResponse(stdout, &response);
817   
818     memset(msgbuf,0,sizeof msgbuf);
819     to64frombits (msgbuf, (unsigned char*)&response, SmbLength(&response));
820
821     if (outlevel >= O_MONITOR)
822         report(stdout, "IMAP> %s\n", msgbuf);
823       
824     strcat(msgbuf,"\r\n");
825
826     SockWrite (sock, msgbuf, strlen (msgbuf));
827   
828     if ((result = gen_recv (sock, msgbuf, sizeof msgbuf)))
829         return result;
830   
831     if (strstr (msgbuf, "OK"))
832         return PS_SUCCESS;
833     else
834         return PS_AUTHFAIL;
835 }
836 #endif /* NTLM */
837
838 static int do_cram_md5 (int sock, struct query *ctl)
839 /* authenticate as per RFC2195 */
840 {
841     int result;
842     int len;
843     unsigned char buf1[1024];
844     unsigned char msg_id[768];
845     unsigned char response[16];
846     unsigned char reply[1024];
847
848     gen_send (sock, "AUTHENTICATE CRAM-MD5");
849
850     /* From RFC2195:
851      * The data encoded in the first ready response contains an
852      * presumptively arbitrary string of random digits, a timestamp, and the
853      * fully-qualified primary host name of the server.  The syntax of the
854      * unencoded form must correspond to that of an RFC 822 'msg-id'
855      * [RFC822] as described in [POP3].
856      */
857
858     if ((result = gen_recv (sock, buf1, sizeof (buf1)))) {
859         return result;
860     }
861
862     len = from64tobits (msg_id, buf1);
863     if (len < 0) {
864         report (stderr, _("could not decode BASE64 challenge\n"));
865         return PS_AUTHFAIL;
866     } else if (len < sizeof (msg_id)) {
867         msg_id[len] = 0;
868     } else {
869         msg_id[sizeof (msg_id)-1] = 0;
870     }
871     if (outlevel >= O_DEBUG) {
872         report (stdout, "decoded as %s\n", msg_id);
873     }
874
875     /* The client makes note of the data and then responds with a string
876      * consisting of the user name, a space, and a 'digest'.  The latter is
877      * computed by applying the keyed MD5 algorithm from [KEYED-MD5] where
878      * the key is a shared secret and the digested text is the timestamp
879      * (including angle-brackets).
880      */
881
882     hmac_md5 (ctl->password, strlen (ctl->password),
883               msg_id, strlen (msg_id),
884               response, sizeof (response));
885
886 #ifdef HAVE_SNPRINTF
887     snprintf (reply, sizeof (reply),
888 #else
889     sprintf(reply,
890 #endif
891               "%s %02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x", 
892               ctl->remotename,
893               response[0], response[1], response[2], response[3],
894               response[4], response[5], response[6], response[7],
895               response[8], response[9], response[10], response[11],
896               response[12], response[13], response[14], response[15]);
897
898     if (outlevel >= O_DEBUG) {
899         report (stdout, "replying with %s\n", reply);
900     }
901
902     to64frombits (buf1, reply, strlen (reply));
903     if (outlevel >= O_MONITOR) {
904         report (stdout, "IMAP> %s\n", buf1);
905     }
906
907     /* PMDF5.2 IMAP has a bug that requires this to be a single write */
908     strcat (buf1, "\r\n");
909     SockWrite (sock, buf1, strlen (buf1));
910
911     if ((result = gen_recv (sock, buf1, sizeof (buf1))))
912         return result;
913
914     if (strstr (buf1, "OK")) {
915         return PS_SUCCESS;
916     } else {
917         return PS_AUTHFAIL;
918     }
919 }
920
921 int imap_canonicalize(char *result, char *raw, int maxlen)
922 /* encode an IMAP password as per RFC1730's quoting conventions */
923 {
924     int i, j;
925
926     j = 0;
927     for (i = 0; i < strlen(raw) && i < maxlen; i++)
928     {
929         if ((raw[i] == '\\') || (raw[i] == '"'))
930             result[j++] = '\\';
931         result[j++] = raw[i];
932     }
933     result[j] = '\0';
934
935     return(i);
936 }
937
938 int imap_getauth(int sock, struct query *ctl, char *greeting)
939 /* apply for connection authorization */
940 {
941     int ok = 0;
942
943     /* probe to see if we're running IMAP4 and can use RFC822.PEEK */
944     capabilities[0] = '\0';
945     preauth = FALSE;
946     if ((ok = gen_transact(sock, "CAPABILITY")) == PS_SUCCESS)
947     {
948         /* UW-IMAP server 10.173 notifies in all caps */
949         if (strstr(capabilities, "IMAP4REV1"))
950         {
951             imap_version = IMAP4rev1;
952             if (outlevel >= O_DEBUG)
953                 report(stdout, _("Protocol identified as IMAP4 rev 1\n"));
954         }
955         else
956         {
957             imap_version = IMAP4;
958             if (outlevel >= O_DEBUG)
959                 report(stdout, _("Protocol identified as IMAP4 rev 0\n"));
960         }
961     }
962     else if (ok == PS_ERROR)
963     {
964         imap_version = IMAP2;
965         if (outlevel >= O_DEBUG)
966             report(stdout, _("Protocol identified as IMAP2 or IMAP2BIS\n"));
967     }
968     else
969         return(ok);
970
971     peek_capable = (imap_version >= IMAP4);
972
973     /* 
974      * Assumption: expunges are cheap, so we want to do them
975      * after every message unless user said otherwise.
976      */
977     if (NUM_SPECIFIED(ctl->expunge))
978         expunge_period = NUM_VALUE_OUT(ctl->expunge);
979     else
980         expunge_period = 1;
981
982     /* 
983      * If either (a) we saw a PREAUTH token in the capability response, or
984      * (b) the user specified ssh preauthentication, then we're done.
985      */
986     if (preauth || ctl->server.preauthenticate == A_SSH)
987         return(PS_SUCCESS);
988
989     /* 
990      * Handle idling.  We depend on coming through here on startup
991      * and after each timeout (including timeouts during idles).
992      */
993     if (strstr(capabilities, "IDLE") && ctl->idle)
994     {
995         do_idle = TRUE;
996         if (outlevel >= O_VERBOSE)
997             report(stdout, "will idle after poll\n");
998     }
999
1000 #if OPIE_ENABLE
1001     if ((ctl->server.protocol == P_IMAP) && strstr(capabilities, "AUTH=X-OTP"))
1002     {
1003         if (outlevel >= O_DEBUG)
1004             report(stdout, _("OTP authentication is supported\n"));
1005         if (do_otp(sock, ctl) == PS_SUCCESS)
1006             return(PS_SUCCESS);
1007     };
1008 #endif /* OPIE_ENABLE */
1009
1010 #ifdef GSSAPI
1011     if (strstr(capabilities, "AUTH=GSSAPI"))
1012     {
1013         if (ctl->server.protocol == P_IMAP_GSS)
1014         {
1015             if (outlevel >= O_DEBUG)
1016                 report(stdout, _("GSS authentication is supported\n"));
1017             return do_gssauth(sock, ctl->server.truename, ctl->remotename);
1018         }
1019     }
1020     else if (ctl->server.protocol == P_IMAP_GSS)
1021     {
1022         report(stderr, 
1023                _("Required GSS capability not supported by server\n"));
1024         return(PS_AUTHFAIL);
1025     }
1026 #endif /* GSSAPI */
1027
1028 #ifdef KERBEROS_V4
1029     if (strstr(capabilities, "AUTH=KERBEROS_V4"))
1030     {
1031         if (outlevel >= O_DEBUG)
1032             report(stdout, _("KERBEROS_V4 authentication is supported\n"));
1033
1034         if (ctl->server.protocol == P_IMAP_K4)
1035         {
1036             if ((ok = do_rfc1731(sock, ctl->server.truename)))
1037             {
1038                 if (outlevel >= O_MONITOR)
1039                     report(stdout, "IMAP> *\n");
1040                 SockWrite(sock, "*\r\n", 3);
1041             }
1042             
1043             return(ok);
1044         }
1045         /* else fall through to ordinary AUTH=LOGIN case */
1046     }
1047     else if (ctl->server.protocol == P_IMAP_K4)
1048     {
1049         report(stderr, 
1050                _("Required KERBEROS_V4 capability not supported by server\n"));
1051         return(PS_AUTHFAIL);
1052     }
1053 #endif /* KERBEROS_V4 */
1054
1055     if (strstr(capabilities, "AUTH=CRAM-MD5"))
1056     {
1057         if (outlevel >= O_DEBUG)
1058             report (stdout, _("CRAM-MD5 authentication is supported\n"));
1059         if (ctl->server.protocol != P_IMAP_LOGIN)
1060         {
1061             if ((ok = do_cram_md5 (sock, ctl)))
1062             {
1063                 if (outlevel >= O_MONITOR)
1064                     report (stdout, "IMAP> *\n");
1065                 SockWrite (sock, "*\r\n", 3);
1066             }
1067             return ok;
1068         }
1069     }
1070     else if (ctl->server.protocol == P_IMAP_CRAM_MD5)
1071     {
1072         report(stderr,
1073                _("Required CRAM-MD5 capability not supported by server\n"));
1074         return(PS_AUTHFAIL);
1075     }
1076
1077 #ifdef NTLM_ENABLE
1078     if (strstr (capabilities, "AUTH=NTLM"))
1079     {
1080         if (outlevel >= O_DEBUG)
1081             report (stdout, _("NTLM authentication is supported\n"));
1082         return do_imap_ntlm (sock, ctl);
1083     }
1084 #endif /* NTLM_ENABLE */
1085
1086 #ifdef __UNUSED__       /* The Cyrus IMAP4rev1 server chokes on this */
1087     /* this handles either AUTH=LOGIN or AUTH-LOGIN */
1088     if ((imap_version >= IMAP4rev1) && (!strstr(capabilities, "LOGIN"))) {
1089       report(stderr, 
1090              _("Required LOGIN capability not supported by server\n"));
1091       return PS_AUTHFAIL;
1092     };
1093 #endif /* __UNUSED__ */
1094
1095     {
1096         /* these sizes guarantee no buffer overflow */
1097         char    remotename[NAMELEN*2+1], password[PASSWORDLEN*2+1];
1098
1099         imap_canonicalize(remotename, ctl->remotename, NAMELEN);
1100         imap_canonicalize(password, ctl->password, PASSWORDLEN);
1101         ok = gen_transact(sock, "LOGIN \"%s\" \"%s\"", remotename, password);
1102     }
1103
1104     if (ok)
1105         return(ok);
1106     
1107     return(PS_SUCCESS);
1108 }
1109
1110 static int internal_expunge(int sock)
1111 /* ship an expunge, resetting associated counters */
1112 {
1113     int ok;
1114
1115     if ((ok = gen_transact(sock, "EXPUNGE")))
1116         return(ok);
1117
1118     expunged += deletions;
1119     deletions = 0;
1120
1121 #ifdef IMAP_UID /* not used */
1122     expunge_uids(ctl);
1123 #endif /* IMAP_UID */
1124
1125     return(PS_SUCCESS);
1126 }
1127
1128 static int imap_getrange(int sock, 
1129                          struct query *ctl, 
1130                          const char *folder, 
1131                          int *countp, int *newp, int *bytes)
1132 /* get range of messages to be fetched */
1133 {
1134     int ok;
1135
1136     /* find out how many messages are waiting */
1137     *bytes = recent = unseen = -1;
1138
1139     if (pass > 1)
1140     {
1141         /* 
1142          * We have to have an expunge here, otherwise the re-poll will
1143          * infinite-loop picking up un-expunged messages -- unless the
1144          * expunge period is one and we've been nuking each message 
1145          * just after deletion.
1146          */
1147         ok = 0;
1148         if (deletions && expunge_period != 1)
1149             ok = internal_expunge(sock);
1150         count = -1;
1151         if (do_idle)
1152         {
1153             stage = STAGE_IDLE;
1154             saved_timeout = mytimeout;
1155             mytimeout = 0;
1156         }
1157         if (ok || gen_transact(sock, do_idle ? "IDLE" : "NOOP"))
1158         {
1159             report(stderr, _("re-poll failed\n"));
1160             return(ok);
1161         }
1162         else if (count == -1)   /* no EXISTS response to NOOP/IDLE */
1163         {
1164             count = recent = 0;
1165             unseen = -1;
1166         }
1167     }
1168     else
1169     {
1170 #ifdef USE_SEARCH
1171         ok = gen_transact(sock, 
1172                           check_only ? "EXAMINE \"%s\"" : "SELECT \"%s\"",
1173                           folder ? folder : "INBOX");
1174 #else
1175         if (check_only) {
1176             ok = gen_transact(sock, "EXAMINE \"%s\"", folder? folder: "INBOX");
1177         } else {
1178             ok = gen_transact(sock, "SELECT \"%s\"", folder? folder: "INBOX");
1179             /*
1180              * SEARCH UNSEEN will modify the static unseen variable.
1181              * It is a much better way than RECENT to determine UNSEEN
1182              * messages.
1183              */
1184             ok = gen_transact(sock, "SEARCH UNSEEN");
1185         }
1186 #endif /* USE_SEARCH */
1187         if (ok != 0)
1188         {
1189             report(stderr, _("mailbox selection failed\n"));
1190             return(ok);
1191         }
1192     }
1193
1194     *countp = count;
1195
1196     /*
1197      * Note: because IMAP has an is_old method, this number is used
1198      * only for the "X messages (Y unseen)" notification.  Accordingly
1199      * it doesn't matter much that it can be wrong (e.g. if we see an
1200      * UNSEEN response but not all messages above the first UNSEEN one
1201      * are likewise).
1202      *
1203      * RECENT is not really a good indication of recent messages,
1204      * because it is ill-defined, e.g. if several connections are made
1205      * to the folder, messages might appear as recent to some and not
1206      * to others.  Using SEARCH UNSEEN provides us with the exact
1207      * number of unseen messages.
1208      */
1209 #ifndef USE_SEARCH
1210     if (unseen >= 0)            /* optional, but better if we see it */
1211         *newp = count - unseen + 1;
1212 #else
1213     if (unseen >= 0 && unseen_count > 0)        /* optional, but better if we see it */
1214         *newp = unseen_count;
1215 #endif /* USE_SEARCH */
1216     else if (recent >= 0)
1217         *newp = recent;
1218     else
1219         *newp = -1;             /* should never happen */ 
1220
1221     expunged = 0;
1222
1223     return(PS_SUCCESS);
1224 }
1225
1226 static int imap_getsizes(int sock, int count, int *sizes)
1227 /* capture the sizes of all messages */
1228 {
1229     char buf [MSGBUFSIZE+1];
1230
1231     /*
1232      * Some servers (as in, PMDF5.1-9.1 under OpenVMS 6.1)
1233      * won't accept 1:1 as valid set syntax.  Some implementors
1234      * should be taken out and shot for excessive anality.
1235      *
1236      * Microsoft Exchange (brain-dead piece of crap that it is) 
1237      * sometimes gets its knickers in a knot about bodiless messages.
1238      * You may see responses like this:
1239      *
1240      *  fetchmail: IMAP> A0004 FETCH 1:9 RFC822.SIZE
1241      *  fetchmail: IMAP< * 2 FETCH (RFC822.SIZE 1187)
1242      *  fetchmail: IMAP< * 3 FETCH (RFC822.SIZE 3954)
1243      *  fetchmail: IMAP< * 4 FETCH (RFC822.SIZE 1944)
1244      *  fetchmail: IMAP< * 5 FETCH (RFC822.SIZE 2933)
1245      *  fetchmail: IMAP< * 6 FETCH (RFC822.SIZE 1854)
1246      *  fetchmail: IMAP< * 7 FETCH (RFC822.SIZE 34054)
1247      *  fetchmail: IMAP< * 8 FETCH (RFC822.SIZE 5561)
1248      *  fetchmail: IMAP< * 9 FETCH (RFC822.SIZE 1101)
1249      *  fetchmail: IMAP< A0004 NO The requested item could not be found.
1250      *
1251      * This means message 1 has only headers.  For kicks and grins
1252      * you can telnet in and look:
1253      *  A003 FETCH 1 FULL
1254      *  A003 NO The requested item could not be found.
1255      *  A004 fetch 1 rfc822.header
1256      *  A004 NO The requested item could not be found.
1257      *  A006 FETCH 1 BODY
1258      *  * 1 FETCH (BODY ("TEXT" "PLAIN" ("CHARSET" "US-ASCII") NIL NIL "7BIT" 35 3))
1259      *  A006 OK FETCH completed.
1260      *
1261      * To get around this, we terminate the read loop on a NO and count
1262      * on the fact that the sizes array has been preinitialized with a
1263      * known-bad size value.
1264      */
1265     if (count == 1)
1266         gen_send(sock, "FETCH 1 RFC822.SIZE", count);
1267     else
1268         gen_send(sock, "FETCH 1:%d RFC822.SIZE", count);
1269     for (;;)
1270     {
1271         int num, size, ok;
1272
1273         if ((ok = gen_recv(sock, buf, sizeof(buf))))
1274             return(ok);
1275         else if (strstr(buf, "OK") || strstr(buf, "NO"))
1276             break;
1277         else if (sscanf(buf, "* %d FETCH (RFC822.SIZE %d)", &num, &size) == 2)
1278             sizes[num - 1] = size;
1279     }
1280
1281     return(PS_SUCCESS);
1282 }
1283
1284 static int imap_is_old(int sock, struct query *ctl, int number)
1285 /* is the given message old? */
1286 {
1287 #ifdef USE_SEARCH
1288     int ok;
1289 #else
1290     int ok, i;
1291 #endif /* USE_SEARCH */
1292
1293     /* expunges change the fetch numbers */
1294     number -= expunged;
1295
1296 #ifdef USE_SEARCH
1297     if (unseen_count > 0) 
1298     {
1299         /* !unseen_count[i] means end of data - redundant with unseen_count */
1300         for (i = 0; i < unseen_count && 0 < unseen_sequence[i]; i++)
1301         {
1302             unseen_sequence[i] -= expunged;     /* expunge adjustment */
1303             if (unseen_sequence[i] == number) {
1304                 seen = FALSE;                   /* message in unseen_sequence */
1305                 break;
1306             } 
1307             else
1308                 seen = TRUE;
1309         }
1310     }
1311     else
1312         /* Fall back to FETCH FLAGS */
1313 #endif /* USE_SEARCH */
1314         if ((ok = gen_transact(sock, "FETCH %d FLAGS", number)) != 0)
1315             return(PS_ERROR);
1316
1317     return(seen);
1318 }
1319
1320 static int imap_fetch_headers(int sock, struct query *ctl,int number,int *lenp)
1321 /* request headers of nth message */
1322 {
1323     char buf [MSGBUFSIZE+1];
1324     int num;
1325
1326     /* expunges change the fetch numbers */
1327     number -= expunged;
1328
1329     /*
1330      * This is blessed by RFC1176, RFC1730, RFC2060.
1331      * According to the RFCs, it should *not* set the \Seen flag.
1332      */
1333     gen_send(sock, "FETCH %d RFC822.HEADER", number);
1334
1335     /* looking for FETCH response */
1336     do {
1337         int     ok;
1338
1339         if ((ok = gen_recv(sock, buf, sizeof(buf))))
1340             return(ok);
1341     } while
1342         (sscanf(buf+2, "%d FETCH (%*s {%d}", &num, lenp) != 2);
1343
1344     if (num != number)
1345         return(PS_ERROR);
1346     else
1347         return(PS_SUCCESS);
1348 }
1349
1350 static int imap_fetch_body(int sock, struct query *ctl, int number, int *lenp)
1351 /* request body of nth message */
1352 {
1353     char buf [MSGBUFSIZE+1], *cp;
1354     int num;
1355
1356     /* expunges change the fetch numbers */
1357     number -= expunged;
1358
1359     /*
1360      * If we're using IMAP4, we can fetch the message without setting its
1361      * seen flag.  This is good!  It means that if the protocol exchange
1362      * craps out during the message, it will still be marked `unseen' on
1363      * the server.
1364      *
1365      * However...*don't* do this if we're using keep to suppress deletion!
1366      * In that case, marking the seen flag is the only way to prevent the
1367      * message from being re-fetched on subsequent runs (and according
1368      * to RFC2060 p.43 this fetch should set Seen as a side effect).
1369      *
1370      * According to RFC2060, and Mark Crispin the IMAP maintainer,
1371      * FETCH %d BODY[TEXT] and RFC822.TEXT are "functionally 
1372      * equivalent".  However, we know of at least one server that
1373      * treats them differently in the presence of MIME attachments;
1374      * the latter form downloads the attachment, the former does not.
1375      * The server is InterChange, and the fool who implemented this
1376      * misfeature ought to be strung up by his thumbs.  
1377      *
1378      * When I tried working around this by disable use of the 4rev1 form,
1379      * I found that doing this breaks operation with M$ Exchange.
1380      * Annoyingly enough, Exchange's refusal to cope is technically legal
1381      * under RFC2062.  Trust Microsoft, the Great Enemy of interoperability
1382      * standards, to find a way to make standards compliance irritating....
1383      */
1384     switch (imap_version)
1385     {
1386     case IMAP4rev1:     /* RFC 2060 */
1387         if (!ctl->keep)
1388             gen_send(sock, "FETCH %d BODY.PEEK[TEXT]", number);
1389         else
1390             gen_send(sock, "FETCH %d BODY[TEXT]", number);
1391         break;
1392
1393     case IMAP4:         /* RFC 1730 */
1394         if (!ctl->keep)
1395             gen_send(sock, "FETCH %d RFC822.TEXT.PEEK", number);
1396         else
1397             gen_send(sock, "FETCH %d RFC822.TEXT", number);
1398         break;
1399
1400     default:            /* RFC 1176 */
1401         gen_send(sock, "FETCH %d RFC822.TEXT", number);
1402         break;
1403     }
1404
1405     /* looking for FETCH response */
1406     do {
1407         int     ok;
1408
1409         if ((ok = gen_recv(sock, buf, sizeof(buf))))
1410             return(ok);
1411     } while
1412         (!strstr(buf+4, "FETCH") || sscanf(buf+2, "%d", &num) != 1);
1413
1414     if (num != number)
1415         return(PS_ERROR);
1416
1417     /*
1418      * Try to extract a length from the FETCH response.  RFC2060 requires
1419      * it to be present, but at least one IMAP server (Novell GroupWise)
1420      * botches this.
1421      */
1422     if ((cp = strchr(buf, '{')))
1423         *lenp = atoi(cp + 1);
1424     else
1425         *lenp = -1;     /* missing length part in FETCH reponse */
1426
1427 #ifdef USE_SEARCH
1428     /* Memory clean-up */
1429     if (unseen_sequence)
1430         free(unseen_sequence);
1431 #endif /* USE_SEARCH */
1432
1433     return(PS_SUCCESS);
1434 }
1435
1436 static int imap_trail(int sock, struct query *ctl, int number)
1437 /* discard tail of FETCH response after reading message text */
1438 {
1439     /* expunges change the fetch numbers */
1440     /* number -= expunged; */
1441
1442     for (;;)
1443     {
1444         char buf[MSGBUFSIZE+1];
1445         int ok;
1446
1447         if ((ok = gen_recv(sock, buf, sizeof(buf))))
1448             return(ok);
1449
1450         /* UW IMAP returns "OK FETCH", Cyrus returns "OK Completed" */
1451         if (strstr(buf, "OK"))
1452             break;
1453
1454 #ifdef __UNUSED__
1455         /*
1456          * Any IMAP server that fails to set Seen on a BODY[TEXT]
1457          * fetch violates RFC2060 p.43 (top).  This becomes an issue
1458          * when keep is on, because seen messages aren't deleted and
1459          * get refetched on each poll.  As a workaround, if keep is on
1460          * we can set the Seen flag explicitly.
1461          *
1462          * This code isn't used yet because we don't know of any IMAP
1463          * servers broken in this way.
1464          */
1465         if (ctl->keep)
1466             if ((ok = gen_transact(sock,
1467                         imap_version == IMAP4 
1468                                 ? "STORE %d +FLAGS.SILENT (\\Seen)"
1469                                 : "STORE %d +FLAGS (\\Seen)", 
1470                         number)))
1471                 return(ok);
1472 #endif /* __UNUSED__ */
1473     }
1474
1475     return(PS_SUCCESS);
1476 }
1477
1478 static int imap_delete(int sock, struct query *ctl, int number)
1479 /* set delete flag for given message */
1480 {
1481     int ok;
1482
1483     /* expunges change the fetch numbers */
1484     number -= expunged;
1485
1486     /*
1487      * Use SILENT if possible as a minor throughput optimization.
1488      * Note: this has been dropped from IMAP4rev1.
1489      *
1490      * We set Seen because there are some IMAP servers (notably HP
1491      * OpenMail) that do message-receipt DSNs, but only when the seen
1492      * bit is set.  This is the appropriate time -- we get here right
1493      * after the local SMTP response that says delivery was
1494      * successful.
1495      */
1496     if ((ok = gen_transact(sock,
1497                         imap_version == IMAP4 
1498                                 ? "STORE %d +FLAGS.SILENT (\\Seen \\Deleted)"
1499                                 : "STORE %d +FLAGS (\\Seen \\Deleted)", 
1500                         number)))
1501         return(ok);
1502     else
1503         deletions++;
1504
1505     /*
1506      * We do an expunge after expunge_period messages, rather than
1507      * just before quit, so that a line hit during a long session
1508      * won't result in lots of messages being fetched again during
1509      * the next session.
1510      */
1511     if (NUM_NONZERO(expunge_period) && (deletions % expunge_period) == 0)
1512         internal_expunge(sock);
1513
1514 #ifdef USE_SEARCH
1515     /* Memory clean-up */
1516     if (unseen_sequence)
1517         free(unseen_sequence);
1518 #endif /* USE_SEARCH */
1519
1520     return(PS_SUCCESS);
1521 }
1522
1523 static int imap_logout(int sock, struct query *ctl)
1524 /* send logout command */
1525 {
1526     /* if any un-expunged deletions remain, ship an expunge now */
1527     if (deletions)
1528         internal_expunge(sock);
1529
1530 #ifdef USE_SEARCH
1531     /* Memory clean-up */
1532     if (unseen_sequence)
1533         free(unseen_sequence);
1534 #endif /* USE_SEARCH */
1535
1536     return(gen_transact(sock, "LOGOUT"));
1537 }
1538
1539 const static struct method imap =
1540 {
1541     "IMAP",             /* Internet Message Access Protocol */
1542 #if INET6_ENABLE
1543     "imap",
1544     "imaps",
1545 #else /* INET6_ENABLE */
1546     143,                /* standard IMAP2bis/IMAP4 port */
1547     993,                /* ssl IMAP2bis/IMAP4 port */
1548 #endif /* INET6_ENABLE */
1549     TRUE,               /* this is a tagged protocol */
1550     FALSE,              /* no message delimiter */
1551     imap_ok,            /* parse command response */
1552     imap_canonicalize,  /* deal with embedded slashes and spaces */
1553     imap_getauth,       /* get authorization */
1554     imap_getrange,      /* query range of messages */
1555     imap_getsizes,      /* get sizes of messages (used for ESMTP SIZE option) */
1556     imap_is_old,        /* no UID check */
1557     imap_fetch_headers, /* request given message headers */
1558     imap_fetch_body,    /* request given message body */
1559     imap_trail,         /* eat message trailer */
1560     imap_delete,        /* delete the message */
1561     imap_logout,        /* expunge and exit */
1562     TRUE,               /* yes, we can re-poll */
1563 };
1564
1565 int doIMAP(struct query *ctl)
1566 /* retrieve messages using IMAP Version 2bis or Version 4 */
1567 {
1568     return(do_protocol(ctl, &imap));
1569 }
1570
1571 /* imap.c ends here */