1 /* imaptest.c -- A program to send commands to an IMAP server
3 * This code is Copyright (c) 2017, by the authors of nmh. See the
4 * COPYRIGHT file in the root directory of the nmh distribution for
5 * complete copyright information.
13 #include "sbr/base64.h"
15 #define IMAPTEST_SWITCHES \
16 X("host hostname", 0, HOSTSW) \
17 X("user username", 0, USERSW) \
18 X("port name/number", 0, PORTSW) \
19 X("snoop", 0, SNOOPSW) \
20 X("nosnoop", 0, NOSNOOPSW) \
21 X("sasl", 0, SASLSW) \
22 X("nosasl", 0, NOSASLSW) \
23 X("saslmech", 0, SASLMECHSW) \
24 X("authservice", 0, AUTHSERVICESW) \
26 X("notls", 0, NOTLSSW) \
27 X("initialtls", 0, INITIALTLSSW) \
28 X("append filename", 0, APPENDSW) \
29 X("timestamp", 0, TIMESTAMPSW) \
30 X("notimestamp", 0, NOTIMESTAMPSW) \
31 X("version", 0, VERSIONSW) \
32 X("help", 0, HELPSW) \
34 #define X(sw, minchars, id) id,
35 DEFINE_SWITCH_ENUM(IMAPTEST
);
38 #define X(sw, minchars, id) { sw, minchars, id },
39 DEFINE_SWITCH_ARRAY(IMAPTEST
, switches
);
45 char tag
[16]; /* Command tag */
46 struct imap_cmd
*next
; /* Next pointer */
49 static struct imap_cmd
*cmdqueue
= NULL
;
50 static char *saslmechs
= NULL
;
51 svector_t imap_capabilities
= NULL
;
53 static int imap_sasl_callback(enum sasl_message_type
, unsigned const char *,
54 unsigned int, unsigned char **, unsigned int *,
57 static void parse_capability(const char *, unsigned int len
);
58 static int capability_set(const char *);
59 static void clear_capability(void);
60 static int have_capability(void);
61 static int send_imap_command(netsec_context
*, int noflush
, char **errstr
,
62 const char *fmt
, ...);
63 static int get_imap_response(netsec_context
*, const char *token
,
64 char **tokenresp
, char **status
, int failerr
,
68 main (int argc
, char **argv
)
70 bool timestamp
= false, sasl
= false, tls
= false, initialtls
= false;
73 char *saslmech
= NULL
, *host
= NULL
, *port
= "143", *user
= NULL
;
74 char *cp
, **argp
, buf
[BUFSIZ
], *oauth_svc
= NULL
, *errstr
, **arguments
, *p
;
75 netsec_context
*nsc
= NULL
;
78 if (nmh_init(argv
[0], 1)) { return 1; }
80 arguments
= getarguments (invo_name
, argc
, argv
, 1);
83 while ((cp
= *argp
++)) {
85 switch (smatch (++cp
, switches
)) {
87 ambigsw (cp
, switches
);
90 adios (NULL
, "-%s unknown", cp
);
93 snprintf (buf
, sizeof(buf
), "%s [switches] +folder command "
94 "[command ...]", invo_name
);
95 print_help (buf
, switches
, 1);
98 print_version(invo_name
);
102 if (!(host
= *argp
++) || *host
== '-')
103 adios(NULL
, "missing argument to %s", argp
[-2]);
106 if (!(port
= *argp
++) || *port
== '-')
107 adios(NULL
, "missing argument to %s", argp
[-2]);
110 if (!(user
= *argp
++) || *user
== '-')
111 adios(NULL
, "missing argument to %s", argp
[-2]);
127 if (!(saslmech
= *argp
++) || *saslmech
== '-')
128 adios(NULL
, "missing argument to %s", argp
[-2]);
131 if (!(oauth_svc
= *argp
++) || *oauth_svc
== '-')
132 adios(NULL
, "missing argument to %s", argp
[-2]);
157 adios(NULL
, "A hostname must be given with -host");
162 netsec_set_userid(nsc
, user
);
164 netsec_set_hostname(nsc
, host
);
167 netsec_set_snoop(nsc
, 1);
170 if (netsec_set_oauth_service(nsc
, oauth_svc
) != OK
) {
171 adios(NULL
, "OAuth2 not supported");
175 if ((fd
= client(host
, port
, buf
, sizeof(buf
), snoop
)) == NOTOK
)
176 adios(NULL
, "Connect failed: %s", buf
);
178 netsec_set_fd(nsc
, fd
, fd
);
179 netsec_set_snoop(nsc
, snoop
);
181 if (initialtls
|| tls
) {
182 if (netsec_set_tls(nsc
, 1, 0, &errstr
) != OK
)
185 if (initialtls
&& netsec_negotiate_tls(nsc
, &errstr
) != OK
)
190 if (netsec_set_sasl_params(nsc
, "imap", saslmech
, imap_sasl_callback
,
195 if ((cp
= netsec_readline(nsc
, &len
, &errstr
)) == NULL
) {
199 if (has_prefix(cp
, "* BYE")) {
200 fprintf(stderr
, "Connection rejected: %s\n", cp
+ 5);
204 if (!has_prefix(cp
, "* OK") && !has_prefix(cp
, "* PREAUTH")) {
205 fprintf(stderr
, "Invalid server response: %s\n", cp
);
209 if ((p
= strchr(cp
+ 2, ' ')) && *(p
+ 1) != '\0' &&
210 has_prefix(p
+ 1, "[CAPABILITY ")) {
212 * Parse the capability list out to the end
215 p
+= 13; /* 1 + [CAPABILITY + space */
217 if (!(q
= strchr(p
, ']'))) {
218 fprintf(stderr
, "Cannot find end of CAPABILITY announcement\n");
222 parse_capability(p
, q
- p
);
226 if (send_imap_command(nsc
, 0, &errstr
, "CAPABILITY") != OK
) {
227 fprintf(stderr
, "Unable to send CAPABILITY command: %s\n", errstr
);
231 if (get_imap_response(nsc
, "CAPABILITY", &capstring
, NULL
, 1,
233 fprintf(stderr
, "Cannot get CAPABILITY response: %s\n", errstr
);
238 fprintf(stderr
, "No CAPABILITY response seen\n");
242 parse_capability(capstring
, strlen(capstring
));
247 if (!capability_set("STARTTLS")) {
248 fprintf(stderr
, "Requested STARTTLS with -tls, but IMAP server "
249 "has no support for STARTTLS\n");
252 if (send_imap_command(nsc
, 0, &errstr
, "STARTTLS") != OK
) {
253 fprintf(stderr
, "Unable to issue STARTTLS: %s\n", errstr
);
257 if (get_imap_response(nsc
, NULL
, NULL
, NULL
, 1, &errstr
) != OK
) {
258 fprintf(stderr
, "STARTTLS failed: %s\n", errstr
);
261 if (netsec_negotiate_tls(nsc
, &errstr
) != OK
) {
267 if (netsec_negotiate_sasl(nsc
, saslmechs
, &errstr
) != OK
) {
268 fprintf(stderr
, "SASL negotiation failed: %s\n", errstr
);
272 * Sigh. If we negotiated a SSF AND we got a capability response
273 * as part of the AUTHENTICATE OK message, we can't actually trust
274 * it because it's not protected at that point. So discard the
275 * capability list and we will generate a fresh CAPABILITY command
278 if (netsec_get_sasl_ssf(nsc
) > 0) {
282 if (capability_set("LOGINDISABLED")) {
283 fprintf(stderr
, "User did not request SASL, but LOGIN "
289 send_imap_command(nsc
, 0, NULL
, "LOGOUT");
290 get_imap_response(nsc
, NULL
, NULL
, NULL
, 0, NULL
);
293 netsec_shutdown(nsc
);
299 * Parse a capability string
301 * Put these into an svector so we can check for stuff later. But special
302 * things, like AUTH, we parse now
306 parse_capability(const char *cap
, unsigned int len
)
308 char *str
= mh_xmalloc(len
+ 1);
312 trunccpy(str
, cap
, len
+ 1);
313 caplist
= brkstring(str
, " ", NULL
);
315 if (imap_capabilities
) {
316 svector_free(imap_capabilities
);
319 imap_capabilities
= svector_create(32);
326 for (i
= 0; caplist
[i
] != NULL
; i
++) {
327 if (has_prefix(caplist
[i
], "AUTH=") && caplist
[i
] + 5 != '\0') {
329 saslmechs
= add(" ", saslmechs
);
331 saslmechs
= add(caplist
[i
] + 5, saslmechs
);
333 svector_push_back(imap_capabilities
, getcpy(caplist
[i
]));
342 * Return 1 if a particular capability is set
346 capability_set(const char *capability
)
348 if (!imap_capabilities
)
351 return svector_find(imap_capabilities
, capability
) != NULL
;
355 * Clear the CAPABILITY list (used after we call STARTTLS, for example)
359 clear_capability(void)
361 svector_free(imap_capabilities
);
362 imap_capabilities
= NULL
;
366 have_capability(void)
368 return imap_capabilities
!= NULL
;
372 * Our SASL callback, which handles the SASL authentication dialog
376 imap_sasl_callback(enum sasl_message_type mtype
, unsigned const char *indata
,
377 unsigned int indatalen
, unsigned char **outdata
,
378 unsigned int *outdatalen
, void *context
, char **errstr
)
383 netsec_context
*nsc
= (netsec_context
*) context
;
386 case NETSEC_SASL_START
:
388 * Generate our AUTHENTICATE message.
390 * If SASL-IR capability is set, we can include any initial response
391 * in the AUTHENTICATE command. Otherwise we have to wait for
392 * the first server response (which should be blank).
395 mech
= netsec_get_sasl_mechanism(nsc
);
399 b64data
= mh_xmalloc(BASE64SIZE(indatalen
));
400 writeBase64raw(indata
, indatalen
, (unsigned char *) b64data
);
401 if (capability_set("SASL-IR")) {
402 netsec_set_snoop_callback(nsc
, netsec_b64_snoop_decoder
,
405 * Sigh. We're assuming a short tag length here. Really,
406 * I guess we should figure out a way to get the length
409 snoopoffset
= 17 + strlen(mech
);
410 rc
= send_imap_command(nsc
, 0, errstr
, "AUTHENTICATE %s %s",
413 netsec_set_snoop_callback(nsc
, NULL
, NULL
);
417 rc
= send_imap_command(nsc
, 0, errstr
, "AUTHENTICATE %s", mech
);
418 line
= netsec_readline(nsc
, &len
, errstr
);
422 * We should get a "+ ", nothing else.
424 if (len
!= 2 || strcmp(line
, "+ ") != 0) {
425 netsec_err(errstr
, "Did not get expected blank response "
426 "for initial challenge response");
429 rc
= netsec_printf(nsc
, errstr
, "%s\r\n", b64data
);
433 netsec_set_snoop_callback(nsc
, netsec_b64_snoop_decoder
, NULL
);
434 rc
= netsec_flush(nsc
, errstr
);
435 netsec_set_snoop_callback(nsc
, NULL
, NULL
);
440 if (send_imap_command(nsc
, 0, errstr
, "AUTHENTICATE %s",
448 * Get a response, decode it and process it.
451 case NETSEC_SASL_READ
:
452 netsec_set_snoop_callback(nsc
, netsec_b64_snoop_decoder
, &snoopoffset
);
454 line
= netsec_readline(nsc
, &len
, errstr
);
455 netsec_set_snoop_callback(nsc
, NULL
, NULL
);
460 if (len
< 2 || (len
== 2 && strcmp(line
, "+ ") != 0)) {
461 netsec_err(errstr
, "Invalid format for SASL response");
469 rc
= decodeBase64(line
+ 2, outdata
, &len
, 0, NULL
);
472 netsec_err(errstr
, "Unable to decode base64 response");
479 * Simple request encoding
482 case NETSEC_SASL_WRITE
:
484 unsigned char *b64data
;
485 b64data
= mh_xmalloc(BASE64SIZE(indatalen
));
486 writeBase64raw(indata
, indatalen
, b64data
);
487 rc
= netsec_printf(nsc
, errstr
, "%s", b64data
);
493 if (netsec_printf(nsc
, errstr
, "\r\n") != OK
)
496 netsec_set_snoop_callback(nsc
, netsec_b64_snoop_decoder
, NULL
);
497 rc
= netsec_flush(nsc
, errstr
);
498 netsec_set_snoop_callback(nsc
, NULL
, NULL
);
507 case NETSEC_SASL_FINISH
:
508 if (get_imap_response(nsc
, NULL
, NULL
, &line
, 1, errstr
) != OK
)
511 * We MIGHT get a capability response here. If so, be sure we
515 if (has_prefix(line
, "OK [CAPABILITY ")) {
516 char *p
= line
+ 15, *q
;
520 parse_capability(p
, q
- p
);
526 * Cancel an authentication dialog
529 case NETSEC_SASL_CANCEL
:
530 rc
= netsec_printf(nsc
, errstr
, "*\r\n");
532 rc
= netsec_flush(nsc
, errstr
);
541 * Send a single command to the IMAP server.
545 send_imap_command(netsec_context
*nsc
, int noflush
, char **errstr
,
546 const char *fmt
, ...)
548 static unsigned int seq
= 0; /* Tag sequence number */
551 struct imap_cmd
*cmd
;
553 cmd
= mh_xmalloc(sizeof(*cmd
));
555 snprintf(cmd
->tag
, sizeof(cmd
->tag
), "A%u ", seq
++);
557 if (netsec_write(nsc
, cmd
->tag
, strlen(cmd
->tag
), errstr
) != OK
) {
563 rc
= netsec_vprintf(nsc
, errstr
, fmt
, ap
);
567 rc
= netsec_write(nsc
, "\r\n", 2, errstr
);
574 if (!noflush
&& netsec_flush(nsc
, errstr
) != OK
) {
579 cmd
->next
= cmdqueue
;
586 * Get all outstanding responses. If we were passed in a token string
587 * to look for, return it.
591 get_imap_response(netsec_context
*nsc
, const char *token
, char **tokenresponse
,
592 char **status
, int failerr
, char **errstr
)
595 struct imap_cmd
*cmd
;
599 *tokenresponse
= NULL
;
603 if (!(line
= netsec_readline(nsc
, NULL
, errstr
)))
605 if (has_prefix(line
, "* ") && *(line
+ 2) != '\0') {
606 if (token
&& tokenresponse
&& has_prefix(line
+ 2, token
)) {
608 free(*tokenresponse
);
609 *tokenresponse
= getcpy(line
+ 2);
613 if (has_prefix(line
, cmdqueue
->tag
)) {
615 cmdqueue
= cmd
->next
;
618 for (cmd
= cmdqueue
; cmd
->next
!= NULL
; cmd
= cmd
->next
) {
619 if (has_prefix(line
, cmd
->next
->tag
)) {
620 struct imap_cmd
*cmd2
= cmd
->next
;
621 cmd
->next
= cmd
->next
->next
;
622 if (failerr
&& strncmp(line
+ strlen(cmd2
->tag
),
625 netsec_err(errstr
, "%s", line
+ strlen(cmd2
->tag
));
629 *status
= getcpy(line
);
632 netsec_err(errstr
, "Non-matching response line: %s\n",
640 return numerrs
== 0 ? OK
: NOTOK
;