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