]> Pileus Git - ~andy/fetchmail/blob - imap.c
First cut at ODMR support.
[~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
34 #ifdef GSSAPI
35 #ifdef HAVE_GSSAPI_H
36 #include <gssapi.h>
37 #endif
38 #ifdef HAVE_GSSAPI_GSSAPI_H
39 #include <gssapi/gssapi.h>
40 #endif
41 #ifdef HAVE_GSSAPI_GSSAPI_GENERIC_H
42 #include <gssapi/gssapi_generic.h>
43 #endif
44 #ifndef HAVE_GSS_C_NT_HOSTBASED_SERVICE
45 #define GSS_C_NT_HOSTBASED_SERVICE gss_nt_service_name
46 #endif
47 #endif
48
49 #include  "i18n.h"
50
51 #if OPIE_ENABLE
52 #include <opie.h>
53 #endif /* OPIE_ENABLE */
54
55 #ifndef strstr          /* glibc-2.1 declares this as a macro */
56 extern char *strstr();  /* needed on sysV68 R3V7.1. */
57 #endif /* strstr */
58
59 /* imap_version values */
60 #define IMAP2           -1      /* IMAP2 or IMAP2BIS, RFC1176 */
61 #define IMAP4           0       /* IMAP4 rev 0, RFC1730 */
62 #define IMAP4rev1       1       /* IMAP4 rev 1, RFC2060 */
63
64 static int count, unseen, deletions, imap_version, preauth; 
65 static int expunged, expunge_period, saved_timeout;
66 static flag do_idle;
67 static char capabilities[MSGBUFSIZE+1];
68 static unsigned int *unseen_messages;
69
70 int imap_ok(int sock, char *argbuf)
71 /* parse command response */
72 {
73     char buf[MSGBUFSIZE+1];
74
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         else if (strstr(buf, "EXISTS"))
91         {
92             count = atoi(buf+2);
93             /*
94              * Nasty kluge to handle RFC2177 IDLE.  If we know we're idling
95              * we can't wait for the tag matching the IDLE; we have to tell the
96              * server the IDLE is finished by shipping back a DONE when we
97              * see an EXISTS.  Only after that will a tagged response be
98              * shipped.  The idling flag also gets cleared on a timeout.
99              */
100             if (stage == STAGE_IDLE)
101             {
102                 /* we do our own write and report here to disable tagging */
103                 SockWrite(sock, "DONE\r\n", 6);
104                 if (outlevel >= O_MONITOR)
105                     report(stdout, "IMAP> DONE\n");
106
107                 mytimeout = saved_timeout;
108                 stage = STAGE_FETCH;
109             }
110         }
111         else if (strstr(buf, "PREAUTH"))
112             preauth = TRUE;
113     } while
114         (tag[0] != '\0' && strncmp(buf, tag, strlen(tag)));
115
116     if (tag[0] == '\0')
117     {
118         if (argbuf)
119             strcpy(argbuf, buf);
120         return(PS_SUCCESS); 
121     }
122     else
123     {
124         char    *cp;
125
126         /* skip the tag */
127         for (cp = buf; !isspace(*cp); cp++)
128             continue;
129         while (isspace(*cp))
130             cp++;
131
132         if (strncmp(cp, "OK", 2) == 0)
133         {
134             if (argbuf)
135                 strcpy(argbuf, cp);
136             return(PS_SUCCESS);
137         }
138         else if (strncmp(cp, "BAD", 3) == 0)
139             return(PS_ERROR);
140         else if (strncmp(cp, "NO", 2) == 0)
141         {
142             if (stage == STAGE_GETAUTH) 
143                 return(PS_AUTHFAIL);    /* RFC2060, 6.2.2 */
144             else
145                 return(PS_ERROR);
146         }
147         else
148             return(PS_PROTOCOL);
149     }
150 }
151
152 #if OPIE_ENABLE
153 static int do_otp(int sock, struct query *ctl)
154 {
155     int i, rval;
156     char buffer[128];
157     char challenge[OPIE_CHALLENGE_MAX+1];
158     char response[OPIE_RESPONSE_MAX+1];
159
160     gen_send(sock, "AUTHENTICATE X-OTP");
161
162     if (rval = gen_recv(sock, buffer, sizeof(buffer)))
163         return rval;
164
165     if ((i = from64tobits(challenge, buffer)) < 0) {
166         report(stderr, _("Could not decode initial BASE64 challenge\n"));
167         return PS_AUTHFAIL;
168     };
169
170
171     to64frombits(buffer, ctl->remotename, strlen(ctl->remotename));
172
173     if (outlevel >= O_MONITOR)
174         report(stdout, "IMAP> %s\n", buffer);
175
176     /* best not to count on the challenge code handling multiple writes */
177     strcat(buffer, "\r\n");
178     SockWrite(sock, buffer, strlen(buffer));
179
180     if (rval = gen_recv(sock, buffer, sizeof(buffer)))
181         return rval;
182
183     if ((i = from64tobits(challenge, buffer)) < 0) {
184         report(stderr, _("Could not decode OTP challenge\n"));
185         return PS_AUTHFAIL;
186     };
187
188     rval = opiegenerator(challenge, !strcmp(ctl->password, "opie") ? "" : ctl->password, response);
189     if ((rval == -2) && !run.poll_interval) {
190         char secret[OPIE_SECRET_MAX+1];
191         fprintf(stderr, _("Secret pass phrase: "));
192         if (opiereadpass(secret, sizeof(secret), 0))
193             rval = opiegenerator(challenge, secret, response);
194         memset(secret, 0, sizeof(secret));
195     };
196
197     if (rval)
198         return(PS_AUTHFAIL);
199
200     to64frombits(buffer, response, strlen(response));
201
202     if (outlevel >= O_MONITOR)
203         report(stdout, "IMAP> %s\n", buffer);
204     strcat(buffer, "\r\n");
205     SockWrite(sock, buffer, strlen(buffer));
206
207     if (rval = gen_recv(sock, buffer, sizeof(buffer)))
208         return rval;
209
210     if (strstr(buffer, "OK"))
211         return PS_SUCCESS;
212     else
213         return PS_AUTHFAIL;
214 };
215 #endif /* OPIE_ENABLE */
216
217 #ifdef KERBEROS_V4
218 #if SIZEOF_INT == 4
219 typedef int     int32;
220 #elif SIZEOF_SHORT == 4
221 typedef short   int32;
222 #elif SIZEOF_LONG == 4
223 typedef long    int32;
224 #else
225 #error Cannot deduce a 32-bit-type
226 #endif
227
228 static int do_rfc1731(int sock, char *truename)
229 /* authenticate as per RFC1731 -- note 32-bit integer requirement here */
230 {
231     int result = 0, len;
232     char buf1[4096], buf2[4096];
233     union {
234       int32 cint;
235       char cstr[4];
236     } challenge1, challenge2;
237     char srvinst[INST_SZ];
238     char *p;
239     char srvrealm[REALM_SZ];
240     KTEXT_ST authenticator;
241     CREDENTIALS credentials;
242     char tktuser[MAX_K_NAME_SZ+1+INST_SZ+1+REALM_SZ+1];
243     char tktinst[INST_SZ];
244     char tktrealm[REALM_SZ];
245     des_cblock session;
246     des_key_schedule schedule;
247
248     gen_send(sock, "AUTHENTICATE KERBEROS_V4");
249
250     /* The data encoded in the first ready response contains a random
251      * 32-bit number in network byte order.  The client should respond
252      * with a Kerberos ticket and an authenticator for the principal
253      * "imap.hostname@realm", where "hostname" is the first component
254      * of the host name of the server with all letters in lower case
255      * and where "realm" is the Kerberos realm of the server.  The
256      * encrypted checksum field included within the Kerberos
257      * authenticator should contain the server provided 32-bit number
258      * in network byte order.
259      */
260
261     if (result = gen_recv(sock, buf1, sizeof buf1)) {
262         return result;
263     }
264
265     len = from64tobits(challenge1.cstr, buf1);
266     if (len < 0) {
267         report(stderr, _("could not decode initial BASE64 challenge\n"));
268         return PS_AUTHFAIL;
269     }
270
271     /* this patch by Dan Root <dar@thekeep.org> solves an endianess
272      * problem. */
273     {
274         char tmp[4];
275
276         *(int *)tmp = ntohl(*(int *) challenge1.cstr);
277         memcpy(challenge1.cstr, tmp, sizeof(tmp));
278     }
279
280     /* Client responds with a Kerberos ticket and an authenticator for
281      * the principal "imap.hostname@realm" where "hostname" is the
282      * first component of the host name of the server with all letters
283      * in lower case and where "realm" is the Kerberos realm of the
284      * server.  The encrypted checksum field included within the
285      * Kerberos authenticator should contain the server-provided
286      * 32-bit number in network byte order.
287      */
288
289     strncpy(srvinst, truename, (sizeof srvinst)-1);
290     srvinst[(sizeof srvinst)-1] = '\0';
291     for (p = srvinst; *p; p++) {
292       if (isupper(*p)) {
293         *p = tolower(*p);
294       }
295     }
296
297     strncpy(srvrealm, (char *)krb_realmofhost(srvinst), (sizeof srvrealm)-1);
298     srvrealm[(sizeof srvrealm)-1] = '\0';
299     if (p = strchr(srvinst, '.')) {
300       *p = '\0';
301     }
302
303     result = krb_mk_req(&authenticator, "imap", srvinst, srvrealm, 0);
304     if (result) {
305         report(stderr, "krb_mq_req: %s\n", krb_get_err_text(result));
306         return PS_AUTHFAIL;
307     }
308
309     result = krb_get_cred("imap", srvinst, srvrealm, &credentials);
310     if (result) {
311         report(stderr, "krb_get_cred: %s\n", krb_get_err_text(result));
312         return PS_AUTHFAIL;
313     }
314
315     memcpy(session, credentials.session, sizeof session);
316     memset(&credentials, 0, sizeof credentials);
317     des_key_sched(session, schedule);
318
319     result = krb_get_tf_fullname(TKT_FILE, tktuser, tktinst, tktrealm);
320     if (result) {
321         report(stderr, "krb_get_tf_fullname: %s\n", krb_get_err_text(result));
322         return PS_AUTHFAIL;
323     }
324
325 #ifdef __UNUSED__
326     /*
327      * Andrew H. Chatham <andrew.chatham@duke.edu> alleges that this check
328      * is not necessary and has consistently been messing him up.
329      */
330     if (strcmp(tktuser, user) != 0) {
331         report(stderr, 
332                _("principal %s in ticket does not match -u %s\n"), tktuser,
333                 user);
334         return PS_AUTHFAIL;
335     }
336 #endif /* __UNUSED__ */
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     do {
611         if (result = gen_recv(sock, buf1, sizeof buf1))
612            return result;
613     } while(strncmp(buf1, tag, strlen(tag)) != 0);
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 #if NTLM_ENABLE
636 #include "ntlm.h"
637
638 static tSmbNtlmAuthRequest   request;              
639 static tSmbNtlmAuthChallenge challenge;
640 static tSmbNtlmAuthResponse  response;
641
642 /*
643  * NTLM support by Grant Edwards.
644  *
645  * Handle MS-Exchange NTLM authentication method.  This is the same
646  * as the NTLM auth used by Samba for SMB related services. We just
647  * encode the packets in base64 instead of sending them out via a
648  * network interface.
649  * 
650  * Much source (ntlm.h, smb*.c smb*.h) was borrowed from Samba.
651  */
652
653 static int do_imap_ntlm(int sock, struct query *ctl)
654 {
655     char msgbuf[2048];
656     int result,len;
657   
658     gen_send(sock, "AUTHENTICATE NTLM");
659
660     if ((result = gen_recv(sock, msgbuf, sizeof msgbuf)))
661         return result;
662   
663     if (msgbuf[0] != '+')
664         return PS_AUTHFAIL;
665   
666     buildSmbNtlmAuthRequest(&request,ctl->remotename,NULL);
667
668     if (outlevel >= O_DEBUG)
669         dumpSmbNtlmAuthRequest(stdout, &request);
670
671     memset(msgbuf,0,sizeof msgbuf);
672     to64frombits (msgbuf, (unsigned char*)&request, SmbLength(&request));
673   
674     if (outlevel >= O_MONITOR)
675         report(stdout, "IMAP> %s\n", msgbuf);
676   
677     strcat(msgbuf,"\r\n");
678     SockWrite (sock, msgbuf, strlen (msgbuf));
679
680     if ((gen_recv(sock, msgbuf, sizeof msgbuf)))
681         return result;
682   
683     len = from64tobits ((unsigned char*)&challenge, msgbuf);
684     
685     if (outlevel >= O_DEBUG)
686         dumpSmbNtlmAuthChallenge(stdout, &challenge);
687     
688     buildSmbNtlmAuthResponse(&challenge, &response,ctl->remotename,ctl->password);
689   
690     if (outlevel >= O_DEBUG)
691         dumpSmbNtlmAuthResponse(stdout, &response);
692   
693     memset(msgbuf,0,sizeof msgbuf);
694     to64frombits (msgbuf, (unsigned char*)&response, SmbLength(&response));
695
696     if (outlevel >= O_MONITOR)
697         report(stdout, "IMAP> %s\n", msgbuf);
698       
699     strcat(msgbuf,"\r\n");
700
701     SockWrite (sock, msgbuf, strlen (msgbuf));
702   
703     if ((result = gen_recv (sock, msgbuf, sizeof msgbuf)))
704         return result;
705   
706     if (strstr (msgbuf, "OK"))
707         return PS_SUCCESS;
708     else
709         return PS_AUTHFAIL;
710 }
711 #endif /* NTLM */
712
713 int imap_canonicalize(char *result, char *raw, int maxlen)
714 /* encode an IMAP password as per RFC1730's quoting conventions */
715 {
716     int i, j;
717
718     j = 0;
719     for (i = 0; i < strlen(raw) && i < maxlen; i++)
720     {
721         if ((raw[i] == '\\') || (raw[i] == '"'))
722             result[j++] = '\\';
723         result[j++] = raw[i];
724     }
725     result[j] = '\0';
726
727     return(i);
728 }
729
730 int imap_getauth(int sock, struct query *ctl, char *greeting)
731 /* apply for connection authorization */
732 {
733     int ok = 0;
734
735     /* probe to see if we're running IMAP4 and can use RFC822.PEEK */
736     capabilities[0] = '\0';
737     if ((ok = gen_transact(sock, "CAPABILITY")) == PS_SUCCESS)
738     {
739         /* UW-IMAP server 10.173 notifies in all caps */
740         if (strstr(capabilities, "IMAP4REV1"))
741         {
742             imap_version = IMAP4rev1;
743             if (outlevel >= O_DEBUG)
744                 report(stdout, _("Protocol identified as IMAP4 rev 1\n"));
745         }
746         else
747         {
748             imap_version = IMAP4;
749             if (outlevel >= O_DEBUG)
750                 report(stdout, _("Protocol identified as IMAP4 rev 0\n"));
751         }
752     }
753     else if (ok == PS_ERROR)
754     {
755         imap_version = IMAP2;
756         if (outlevel >= O_DEBUG)
757             report(stdout, _("Protocol identified as IMAP2 or IMAP2BIS\n"));
758     }
759     else
760         return(ok);
761
762     peek_capable = (imap_version >= IMAP4);
763
764     /* 
765      * Assumption: expunges are cheap, so we want to do them
766      * after every message unless user said otherwise.
767      */
768     if (NUM_SPECIFIED(ctl->expunge))
769         expunge_period = NUM_VALUE_OUT(ctl->expunge);
770     else
771         expunge_period = 1;
772
773     /* 
774      * Handle idling.  We depend on coming through here on startup
775      * and after each timeout (including timeouts during idles).
776      */
777     if (strstr(capabilities, "IDLE") && ctl->idle)
778     {
779         do_idle = TRUE;
780         if (outlevel >= O_VERBOSE)
781             report(stdout, _("will idle after poll\n"));
782     }
783
784     /* 
785      * If either (a) we saw a PREAUTH token in the greeting, or
786      * (b) the user specified ssh preauthentication, then we're done.
787      */
788     if (preauth || ctl->server.preauthenticate == A_SSH)
789     {
790         preauth = FALSE;  /* reset for the next session */
791         return(PS_SUCCESS);
792     }
793
794 #if OPIE_ENABLE
795     if ((ctl->server.protocol == P_IMAP) && strstr(capabilities, "AUTH=X-OTP"))
796     {
797         if (outlevel >= O_DEBUG)
798             report(stdout, _("OTP authentication is supported\n"));
799         if (do_otp(sock, ctl) == PS_SUCCESS)
800             return(PS_SUCCESS);
801     };
802 #endif /* OPIE_ENABLE */
803
804 #ifdef GSSAPI
805     if (strstr(capabilities, "AUTH=GSSAPI"))
806     {
807         if (ctl->server.protocol == P_IMAP_GSS)
808         {
809             if (outlevel >= O_DEBUG)
810                 report(stdout, _("GSS authentication is supported\n"));
811             return do_gssauth(sock, ctl->server.truename, ctl->remotename);
812         }
813     }
814     else if (ctl->server.protocol == P_IMAP_GSS)
815     {
816         report(stderr, 
817                _("Required GSS capability not supported by server\n"));
818         return(PS_AUTHFAIL);
819     }
820 #endif /* GSSAPI */
821
822 #ifdef KERBEROS_V4
823     if (strstr(capabilities, "AUTH=KERBEROS_V4"))
824     {
825         if (outlevel >= O_DEBUG)
826             report(stdout, _("KERBEROS_V4 authentication is supported\n"));
827
828         if (ctl->server.protocol == P_IMAP_K4)
829         {
830             if ((ok = do_rfc1731(sock, ctl->server.truename)))
831             {
832                 if (outlevel >= O_MONITOR)
833                     report(stdout, "IMAP> *\n");
834                 SockWrite(sock, "*\r\n", 3);
835             }
836             
837             return(ok);
838         }
839         /* else fall through to ordinary AUTH=LOGIN case */
840     }
841     else if (ctl->server.protocol == P_IMAP_K4)
842     {
843         report(stderr, 
844                _("Required KERBEROS_V4 capability not supported by server\n"));
845         return(PS_AUTHFAIL);
846     }
847 #endif /* KERBEROS_V4 */
848
849     if (strstr(capabilities, "AUTH=CRAM-MD5"))
850     {
851         if (outlevel >= O_DEBUG)
852             report (stdout, _("CRAM-MD5 authentication is supported\n"));
853         if (ctl->server.protocol != P_IMAP_LOGIN)
854         {
855             if ((ok = do_cram_md5 (sock, ctl)))
856             {
857                 if (outlevel >= O_MONITOR)
858                     report (stdout, "IMAP> *\n");
859                 SockWrite (sock, "*\r\n", 3);
860             }
861             return ok;
862         }
863     }
864     else if (ctl->server.protocol == P_IMAP_CRAM_MD5)
865     {
866         report(stderr,
867                _("Required CRAM-MD5 capability not supported by server\n"));
868         return(PS_AUTHFAIL);
869     }
870
871 #ifdef NTLM_ENABLE
872     if (strstr (capabilities, "AUTH=NTLM"))
873     {
874         if (outlevel >= O_DEBUG)
875             report (stdout, _("NTLM authentication is supported\n"));
876         return do_imap_ntlm (sock, ctl);
877     }
878 #endif /* NTLM_ENABLE */
879
880 #ifdef __UNUSED__       /* The Cyrus IMAP4rev1 server chokes on this */
881     /* this handles either AUTH=LOGIN or AUTH-LOGIN */
882     if ((imap_version >= IMAP4rev1) && (!strstr(capabilities, "LOGIN"))) {
883       report(stderr, 
884              _("Required LOGIN capability not supported by server\n"));
885       return PS_AUTHFAIL;
886     };
887 #endif /* __UNUSED__ */
888
889     {
890         /* these sizes guarantee no buffer overflow */
891         char    remotename[NAMELEN*2+1], password[PASSWORDLEN*2+1];
892
893         imap_canonicalize(remotename, ctl->remotename, NAMELEN);
894         imap_canonicalize(password, ctl->password, PASSWORDLEN);
895         ok = gen_transact(sock, "LOGIN \"%s\" \"%s\"", remotename, password);
896     }
897
898     if (ok)
899         return(ok);
900     
901     return(PS_SUCCESS);
902 }
903
904 static int internal_expunge(int sock)
905 /* ship an expunge, resetting associated counters */
906 {
907     int ok;
908
909     if ((ok = gen_transact(sock, "EXPUNGE")))
910         return(ok);
911
912     expunged += deletions;
913     deletions = 0;
914
915 #ifdef IMAP_UID /* not used */
916     expunge_uids(ctl);
917 #endif /* IMAP_UID */
918
919     return(PS_SUCCESS);
920 }
921
922 static int imap_idle(int sock)
923 /* start an RFC2177 IDLE */
924 {
925     stage = STAGE_IDLE;
926     saved_timeout = mytimeout;
927     mytimeout = 0;
928
929     return (gen_transact(sock, "IDLE"));
930 }
931
932 static int imap_getrange(int sock, 
933                          struct query *ctl, 
934                          const char *folder, 
935                          int *countp, int *newp, int *bytes)
936 /* get range of messages to be fetched */
937 {
938     int ok;
939     char buf[MSGBUFSIZE+1], *cp;
940
941     /* find out how many messages are waiting */
942     *bytes = -1;
943
944     if (pass > 1)
945     {
946         /* 
947          * We have to have an expunge here, otherwise the re-poll will
948          * infinite-loop picking up un-expunged messages -- unless the
949          * expunge period is one and we've been nuking each message 
950          * just after deletion.
951          */
952         ok = 0;
953         if (deletions && expunge_period != 1)
954             ok = internal_expunge(sock);
955         count = -1;
956         if (do_idle)
957             ok = imap_idle(sock);
958         if (ok || gen_transact(sock, "NOOP"))
959         {
960             report(stderr, _("re-poll failed\n"));
961             return(ok);
962         }
963         else if (count == -1)   /* no EXISTS response to NOOP/IDLE */
964         {
965             count = 0;
966         }
967         if (outlevel >= O_DEBUG)
968             report(stdout, _("%d messages waiting after re-poll\n"), count);
969     }
970     else
971     {
972         ok = gen_transact(sock, 
973                           check_only ? "EXAMINE \"%s\"" : "SELECT \"%s\"",
974                           folder ? folder : "INBOX");
975         if (ok != 0)
976         {
977             report(stderr, _("mailbox selection failed\n"));
978             return(ok);
979         }
980         else if (outlevel >= O_DEBUG)
981             report(stdout, _("%d messages waiting after first poll\n"), count);
982
983         /* no messages?  then we may need to idle until we get some */
984         if (count == 0 && do_idle)
985             imap_idle(sock);
986     }
987
988     *countp = count;
989
990     /* OK, now get a count of unseen messages and their indices */
991     if (!ctl->fetchall && count > 0)
992     {
993         if (unseen_messages)
994             free(unseen_messages);
995         unseen_messages = xmalloc(count * sizeof(unsigned int));
996         memset(unseen_messages, 0, count * sizeof(unsigned int));
997         unseen = 0;
998
999         gen_send(sock, "SEARCH UNSEEN");
1000         do {
1001             ok = gen_recv(sock, buf, sizeof(buf));
1002             if (ok != 0)
1003             {
1004                 report(stderr, _("search for unseen messages failed\n"));
1005                 return(PS_PROTOCOL);
1006             }
1007             else if ((cp = strstr(buf, "* SEARCH")))
1008             {
1009                 char    *ep;
1010
1011                 cp += 8;        /* skip "* SEARCH" */
1012
1013                 while (*cp && unseen < count)
1014                 {
1015                     /* skip whitespace */
1016                     while (*cp && isspace(*cp))
1017                         cp++;
1018                     if (*cp) 
1019                     {
1020                         /*
1021                          * Message numbers are between 1 and 2^32 inclusive,
1022                          * so unsigned int is large enough.
1023                          */
1024                         unseen_messages[unseen]=(unsigned int)strtol(cp,&ep,10);
1025
1026                         if (outlevel >= O_DEBUG)
1027                             report(stdout, 
1028                                    _("%u is unseen\n"), 
1029                                    unseen_messages[unseen]);
1030                 
1031                         unseen++;
1032                         cp = ep;
1033                     }
1034                 }
1035             }
1036         } while
1037             (tag[0] != '\0' && strncmp(buf, tag, strlen(tag)));
1038     }
1039
1040     *newp = unseen;
1041     expunged = 0;
1042
1043     return(PS_SUCCESS);
1044 }
1045
1046 static int imap_getsizes(int sock, int count, int *sizes)
1047 /* capture the sizes of all messages */
1048 {
1049     char buf [MSGBUFSIZE+1];
1050
1051     /*
1052      * Some servers (as in, PMDF5.1-9.1 under OpenVMS 6.1)
1053      * won't accept 1:1 as valid set syntax.  Some implementors
1054      * should be taken out and shot for excessive anality.
1055      *
1056      * Microsoft Exchange (brain-dead piece of crap that it is) 
1057      * sometimes gets its knickers in a knot about bodiless messages.
1058      * You may see responses like this:
1059      *
1060      *  fetchmail: IMAP> A0004 FETCH 1:9 RFC822.SIZE
1061      *  fetchmail: IMAP< * 2 FETCH (RFC822.SIZE 1187)
1062      *  fetchmail: IMAP< * 3 FETCH (RFC822.SIZE 3954)
1063      *  fetchmail: IMAP< * 4 FETCH (RFC822.SIZE 1944)
1064      *  fetchmail: IMAP< * 5 FETCH (RFC822.SIZE 2933)
1065      *  fetchmail: IMAP< * 6 FETCH (RFC822.SIZE 1854)
1066      *  fetchmail: IMAP< * 7 FETCH (RFC822.SIZE 34054)
1067      *  fetchmail: IMAP< * 8 FETCH (RFC822.SIZE 5561)
1068      *  fetchmail: IMAP< * 9 FETCH (RFC822.SIZE 1101)
1069      *  fetchmail: IMAP< A0004 NO The requested item could not be found.
1070      *
1071      * This means message 1 has only headers.  For kicks and grins
1072      * you can telnet in and look:
1073      *  A003 FETCH 1 FULL
1074      *  A003 NO The requested item could not be found.
1075      *  A004 fetch 1 rfc822.header
1076      *  A004 NO The requested item could not be found.
1077      *  A006 FETCH 1 BODY
1078      *  * 1 FETCH (BODY ("TEXT" "PLAIN" ("CHARSET" "US-ASCII") NIL NIL "7BIT" 35 3))
1079      *  A006 OK FETCH completed.
1080      *
1081      * To get around this, we terminate the read loop on a NO and count
1082      * on the fact that the sizes array has been preinitialized with a
1083      * known-bad size value.
1084      */
1085     if (count == 1)
1086         gen_send(sock, "FETCH 1 RFC822.SIZE", count);
1087     else
1088         gen_send(sock, "FETCH 1:%d RFC822.SIZE", count);
1089     for (;;)
1090     {
1091         int num, size, ok;
1092
1093         if ((ok = gen_recv(sock, buf, sizeof(buf))))
1094             return(ok);
1095         else if (strstr(buf, "OK") || strstr(buf, "NO"))
1096             break;
1097         else if (sscanf(buf, "* %d FETCH (RFC822.SIZE %d)", &num, &size) == 2)
1098             sizes[num - 1] = size;
1099     }
1100
1101     return(PS_SUCCESS);
1102 }
1103
1104 static int imap_is_old(int sock, struct query *ctl, int number)
1105 /* is the given message old? */
1106 {
1107     flag seen = TRUE;
1108     int i;
1109
1110     /* 
1111      * Expunges change the fetch numbers, but unseen_messages contains
1112      * indices from before any expungees were done.  So neither the
1113      * argument nor the values in message_sequence need to be decremented.
1114      */
1115
1116     seen = TRUE;
1117     for (i = 0; i < unseen; i++)
1118         if (unseen_messages[i] == number)
1119         {
1120             seen = FALSE;
1121             break;
1122         }
1123
1124     return(seen);
1125 }
1126
1127 static int imap_fetch_headers(int sock, struct query *ctl,int number,int *lenp)
1128 /* request headers of nth message */
1129 {
1130     char buf [MSGBUFSIZE+1];
1131     int num;
1132
1133     /* expunges change the fetch numbers */
1134     number -= expunged;
1135
1136     /*
1137      * This is blessed by RFC1176, RFC1730, RFC2060.
1138      * According to the RFCs, it should *not* set the \Seen flag.
1139      */
1140     gen_send(sock, "FETCH %d RFC822.HEADER", number);
1141
1142     /* looking for FETCH response */
1143     do {
1144         int     ok;
1145
1146         if ((ok = gen_recv(sock, buf, sizeof(buf))))
1147             return(ok);
1148     } while
1149         (sscanf(buf+2, "%d FETCH (%*s {%d}", &num, lenp) != 2);
1150
1151     if (num != number)
1152         return(PS_ERROR);
1153     else
1154         return(PS_SUCCESS);
1155 }
1156
1157 static int imap_fetch_body(int sock, struct query *ctl, int number, int *lenp)
1158 /* request body of nth message */
1159 {
1160     char buf [MSGBUFSIZE+1], *cp;
1161     int num;
1162
1163     /* expunges change the fetch numbers */
1164     number -= expunged;
1165
1166     /*
1167      * If we're using IMAP4, we can fetch the message without setting its
1168      * seen flag.  This is good!  It means that if the protocol exchange
1169      * craps out during the message, it will still be marked `unseen' on
1170      * the server.
1171      *
1172      * However...*don't* do this if we're using keep to suppress deletion!
1173      * In that case, marking the seen flag is the only way to prevent the
1174      * message from being re-fetched on subsequent runs (and according
1175      * to RFC2060 p.43 this fetch should set Seen as a side effect).
1176      *
1177      * According to RFC2060, and Mark Crispin the IMAP maintainer,
1178      * FETCH %d BODY[TEXT] and RFC822.TEXT are "functionally 
1179      * equivalent".  However, we know of at least one server that
1180      * treats them differently in the presence of MIME attachments;
1181      * the latter form downloads the attachment, the former does not.
1182      * The server is InterChange, and the fool who implemented this
1183      * misfeature ought to be strung up by his thumbs.  
1184      *
1185      * When I tried working around this by disabling use of the 4rev1 form,
1186      * I found that doing this breaks operation with M$ Exchange.
1187      * Annoyingly enough, Exchange's refusal to cope is technically legal
1188      * under RFC2062.  Trust Microsoft, the Great Enemy of interoperability
1189      * standards, to find a way to make standards compliance irritating....
1190      */
1191     switch (imap_version)
1192     {
1193     case IMAP4rev1:     /* RFC 2060 */
1194         if (!ctl->keep)
1195             gen_send(sock, "FETCH %d BODY.PEEK[TEXT]", number);
1196         else
1197             gen_send(sock, "FETCH %d BODY[TEXT]", number);
1198         break;
1199
1200     case IMAP4:         /* RFC 1730 */
1201         if (!ctl->keep)
1202             gen_send(sock, "FETCH %d RFC822.TEXT.PEEK", number);
1203         else
1204             gen_send(sock, "FETCH %d RFC822.TEXT", number);
1205         break;
1206
1207     default:            /* RFC 1176 */
1208         gen_send(sock, "FETCH %d RFC822.TEXT", number);
1209         break;
1210     }
1211
1212     /* looking for FETCH response */
1213     do {
1214         int     ok;
1215
1216         if ((ok = gen_recv(sock, buf, sizeof(buf))))
1217             return(ok);
1218     } while
1219         (!strstr(buf+4, "FETCH") || sscanf(buf+2, "%d", &num) != 1);
1220
1221     if (num != number)
1222         return(PS_ERROR);
1223
1224     /*
1225      * Try to extract a length from the FETCH response.  RFC2060 requires
1226      * it to be present, but at least one IMAP server (Novell GroupWise)
1227      * botches this.
1228      */
1229     if ((cp = strchr(buf, '{')))
1230         *lenp = atoi(cp + 1);
1231     else
1232         *lenp = -1;     /* missing length part in FETCH reponse */
1233
1234     return(PS_SUCCESS);
1235 }
1236
1237 static int imap_trail(int sock, struct query *ctl, int number)
1238 /* discard tail of FETCH response after reading message text */
1239 {
1240     /* expunges change the fetch numbers */
1241     /* number -= expunged; */
1242
1243     for (;;)
1244     {
1245         char buf[MSGBUFSIZE+1];
1246         int ok;
1247
1248         if ((ok = gen_recv(sock, buf, sizeof(buf))))
1249             return(ok);
1250
1251         /* UW IMAP returns "OK FETCH", Cyrus returns "OK Completed" */
1252         if (strstr(buf, "OK"))
1253             break;
1254
1255 #ifdef __UNUSED__
1256         /*
1257          * Any IMAP server that fails to set Seen on a BODY[TEXT]
1258          * fetch violates RFC2060 p.43 (top).  This becomes an issue
1259          * when keep is on, because seen messages aren't deleted and
1260          * get refetched on each poll.  As a workaround, if keep is on
1261          * we can set the Seen flag explicitly.
1262          *
1263          * This code isn't used yet because we don't know of any IMAP
1264          * servers broken in this way.
1265          */
1266         if (ctl->keep)
1267             if ((ok = gen_transact(sock,
1268                         imap_version == IMAP4 
1269                                 ? "STORE %d +FLAGS.SILENT (\\Seen)"
1270                                 : "STORE %d +FLAGS (\\Seen)", 
1271                         number)))
1272                 return(ok);
1273 #endif /* __UNUSED__ */
1274     }
1275
1276     return(PS_SUCCESS);
1277 }
1278
1279 static int imap_delete(int sock, struct query *ctl, int number)
1280 /* set delete flag for given message */
1281 {
1282     int ok;
1283
1284     /* expunges change the fetch numbers */
1285     number -= expunged;
1286
1287     /*
1288      * Use SILENT if possible as a minor throughput optimization.
1289      * Note: this has been dropped from IMAP4rev1.
1290      *
1291      * We set Seen because there are some IMAP servers (notably HP
1292      * OpenMail) that do message-receipt DSNs, but only when the seen
1293      * bit is set.  This is the appropriate time -- we get here right
1294      * after the local SMTP response that says delivery was
1295      * successful.
1296      */
1297     if ((ok = gen_transact(sock,
1298                         imap_version == IMAP4 
1299                                 ? "STORE %d +FLAGS.SILENT (\\Seen \\Deleted)"
1300                                 : "STORE %d +FLAGS (\\Seen \\Deleted)", 
1301                         number)))
1302         return(ok);
1303     else
1304         deletions++;
1305
1306     /*
1307      * We do an expunge after expunge_period messages, rather than
1308      * just before quit, so that a line hit during a long session
1309      * won't result in lots of messages being fetched again during
1310      * the next session.
1311      */
1312     if (NUM_NONZERO(expunge_period) && (deletions % expunge_period) == 0)
1313         internal_expunge(sock);
1314
1315     return(PS_SUCCESS);
1316 }
1317
1318 static int imap_logout(int sock, struct query *ctl)
1319 /* send logout command */
1320 {
1321     /* if any un-expunged deletions remain, ship an expunge now */
1322     if (deletions)
1323         internal_expunge(sock);
1324
1325 #ifdef USE_SEARCH
1326     /* Memory clean-up */
1327     if (unseen_messages)
1328         free(unseen_messages);
1329 #endif /* USE_SEARCH */
1330
1331     return(gen_transact(sock, "LOGOUT"));
1332 }
1333
1334 const static struct method imap =
1335 {
1336     "IMAP",             /* Internet Message Access Protocol */
1337 #if INET6_ENABLE
1338     "imap",
1339     "imaps",
1340 #else /* INET6_ENABLE */
1341     143,                /* standard IMAP2bis/IMAP4 port */
1342     993,                /* ssl IMAP2bis/IMAP4 port */
1343 #endif /* INET6_ENABLE */
1344     TRUE,               /* this is a tagged protocol */
1345     FALSE,              /* no message delimiter */
1346     imap_ok,            /* parse command response */
1347     imap_canonicalize,  /* deal with embedded slashes and spaces */
1348     imap_getauth,       /* get authorization */
1349     imap_getrange,      /* query range of messages */
1350     imap_getsizes,      /* get sizes of messages (used for ESMTP SIZE option) */
1351     imap_is_old,        /* no UID check */
1352     imap_fetch_headers, /* request given message headers */
1353     imap_fetch_body,    /* request given message body */
1354     imap_trail,         /* eat message trailer */
1355     imap_delete,        /* delete the message */
1356     imap_logout,        /* expunge and exit */
1357     TRUE,               /* yes, we can re-poll */
1358 };
1359
1360 int doIMAP(struct query *ctl)
1361 /* retrieve messages using IMAP Version 2bis or Version 4 */
1362 {
1363     return(do_protocol(ctl, &imap));
1364 }
1365
1366 /* imap.c ends here */