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