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.
14 #include "sbr/base64.h"
16 #define IMAPTEST_SWITCHES \
17 X("host hostname", 0, HOSTSW) \
18 X("user username", 0, USERSW) \
19 X("port name/number", 0, PORTSW) \
20 X("snoop", 0, SNOOPSW) \
21 X("nosnoop", 0, NOSNOOPSW) \
22 X("sasl", 0, SASLSW) \
23 X("nosasl", 0, NOSASLSW) \
24 X("saslmech", 0, SASLMECHSW) \
25 X("authservice", 0, AUTHSERVICESW) \
27 X("notls", 0, NOTLSSW) \
28 X("initialtls", 0, INITIALTLSSW) \
29 X("append filename", 0, APPENDSW) \
30 X("timestamp", 0, TIMESTAMPSW) \
31 X("notimestamp", 0, NOTIMESTAMPSW) \
32 X("version", 0, VERSIONSW) \
33 X("help", 0, HELPSW) \
35 #define X(sw, minchars, id) id,
36 DEFINE_SWITCH_ENUM(IMAPTEST
);
39 #define X(sw, minchars, id) { sw, minchars, id },
40 DEFINE_SWITCH_ARRAY(IMAPTEST
, switches
);
46 char *command
; /* Command to send */
47 bool queue
; /* If true, queue for later delivery */
48 struct imap_msg
*next
; /* Next pointer */
51 struct imap_msg
*msgqueue_head
= NULL
;
52 struct imap_msg
*msgqueue_tail
= NULL
;
57 char tag
[16]; /* Command tag */
58 struct timeval start
; /* Time command was sent */
59 char prefix
[64]; /* Command prefix */
60 struct imap_cmd
*next
; /* Next pointer */
63 static struct imap_cmd
*cmdqueue
= NULL
;
65 static char *saslmechs
= NULL
;
66 svector_t imap_capabilities
= NULL
;
68 static int imap_sasl_callback(enum sasl_message_type
, unsigned const char *,
69 unsigned int, unsigned char **, unsigned int *,
72 static void parse_capability(const char *, unsigned int len
);
73 static int capability_set(const char *);
74 static void clear_capability(void);
75 static int have_capability(void);
76 static int send_imap_command(netsec_context
*, bool noflush
, char **errstr
,
77 const char *fmt
, ...) CHECK_PRINTF(4, 5);
78 static int get_imap_response(netsec_context
*, const char *token
,
79 char **tokenresp
, char **status
, int failerr
,
82 static void ts_report(struct timeval
*tv
, const char *fmt
, ...)
84 static void imap_negotiate_tls(netsec_context
*);
86 static void add_msg(bool queue
, const char *fmt
, ...) CHECK_PRINTF(2, 3);
88 static bool timestamp
= false;
91 main (int argc
, char **argv
)
93 bool sasl
= false, tls
= false, initialtls
= false;
96 char *saslmech
= NULL
, *host
= NULL
, *port
= "143", *user
= NULL
;
97 char *cp
, **argp
, buf
[BUFSIZ
], *oauth_svc
= NULL
, *errstr
, **arguments
, *p
;
98 netsec_context
*nsc
= NULL
;
99 struct imap_msg
*imsg
;
101 struct timeval tv_start
, tv_connect
, tv_auth
;
103 if (nmh_init(argv
[0], true, true)) { return 1; }
105 arguments
= getarguments (invo_name
, argc
, argv
, 1);
108 while ((cp
= *argp
++)) {
110 switch (smatch (++cp
, switches
)) {
112 ambigsw (cp
, switches
);
115 die("-%s unknown", cp
);
118 snprintf (buf
, sizeof(buf
), "%s [switches] +folder command "
119 "[command ...]", invo_name
);
120 print_help (buf
, switches
, 1);
123 print_version(invo_name
);
127 if (!(host
= *argp
++) || *host
== '-')
128 die("missing argument to %s", argp
[-2]);
131 if (!(port
= *argp
++) || *port
== '-')
132 die("missing argument to %s", argp
[-2]);
135 if (!(user
= *argp
++) || *user
== '-')
136 die("missing argument to %s", argp
[-2]);
152 if (!(saslmech
= *argp
++) || *saslmech
== '-')
153 die("missing argument to %s", argp
[-2]);
156 if (!(oauth_svc
= *argp
++) || *oauth_svc
== '-')
157 die("missing argument to %s", argp
[-2]);
178 } else if (*cp
== '+') {
179 if (*(cp
+ 1) == '\0')
180 die("Invalid null folder name");
181 add_msg(0, "SELECT \"%s\"", cp
+ 1);
183 add_msg(0, "%s", cp
);
188 die("A hostname must be given with -host");
193 netsec_set_userid(nsc
, user
);
195 netsec_set_hostname(nsc
, host
);
198 netsec_set_snoop(nsc
, 1);
201 if (netsec_set_oauth_service(nsc
, oauth_svc
) != OK
) {
202 die("OAuth2 not supported");
207 gettimeofday(&tv_start
, NULL
);
209 if ((fd
= client(host
, port
, buf
, sizeof(buf
), snoop
)) == NOTOK
)
210 die("Connect failed: %s", buf
);
213 ts_report(&tv_start
, "Connect time");
214 gettimeofday(&tv_connect
, NULL
);
217 netsec_set_fd(nsc
, fd
, fd
);
218 netsec_set_snoop(nsc
, snoop
);
220 if (initialtls
|| tls
) {
221 if (netsec_set_tls(nsc
, 1, 0, &errstr
) != OK
)
225 imap_negotiate_tls(nsc
);
229 if (netsec_set_sasl_params(nsc
, "imap", saslmech
, imap_sasl_callback
,
234 if ((cp
= netsec_readline(nsc
, &len
, &errstr
)) == NULL
) {
238 if (has_prefix(cp
, "* BYE")) {
239 fprintf(stderr
, "Connection rejected: %s\n", cp
+ 5);
243 if (!has_prefix(cp
, "* OK") && !has_prefix(cp
, "* PREAUTH")) {
244 fprintf(stderr
, "Invalid server response: %s\n", cp
);
248 if ((p
= strchr(cp
+ 2, ' ')) && *(p
+ 1) != '\0' &&
249 has_prefix(p
+ 1, "[CAPABILITY ")) {
251 * Parse the capability list out to the end
254 p
+= 13; /* 1 + [CAPABILITY + space */
256 if (!(q
= strchr(p
, ']'))) {
257 fprintf(stderr
, "Cannot find end of CAPABILITY announcement\n");
261 parse_capability(p
, q
- p
);
265 if (send_imap_command(nsc
, false, &errstr
, "CAPABILITY") != OK
) {
266 fprintf(stderr
, "Unable to send CAPABILITY command: %s\n", errstr
);
270 if (get_imap_response(nsc
, "CAPABILITY", &capstring
, NULL
, 1,
272 fprintf(stderr
, "Cannot get CAPABILITY response: %s\n", errstr
);
277 fprintf(stderr
, "No CAPABILITY response seen\n");
281 parse_capability(capstring
, strlen(capstring
));
286 if (!capability_set("STARTTLS")) {
287 fprintf(stderr
, "Requested STARTTLS with -tls, but IMAP server "
288 "has no support for STARTTLS\n");
291 if (send_imap_command(nsc
, false, &errstr
, "STARTTLS") != OK
) {
292 fprintf(stderr
, "Unable to issue STARTTLS: %s\n", errstr
);
296 if (get_imap_response(nsc
, NULL
, NULL
, NULL
, 1, &errstr
) != OK
) {
297 fprintf(stderr
, "STARTTLS failed: %s\n", errstr
);
301 imap_negotiate_tls(nsc
);
305 if (netsec_negotiate_sasl(nsc
, saslmechs
, &errstr
) != OK
) {
306 fprintf(stderr
, "SASL negotiation failed: %s\n", errstr
);
310 * Sigh. If we negotiated a SSF AND we got a capability response
311 * as part of the AUTHENTICATE OK message, we can't actually trust
312 * it because it's not protected at that point. So discard the
313 * capability list and we will generate a fresh CAPABILITY command
316 if (netsec_get_sasl_ssf(nsc
) > 0) {
320 if (capability_set("LOGINDISABLED")) {
321 fprintf(stderr
, "User did not request SASL, but LOGIN "
327 if (!have_capability()) {
330 if (send_imap_command(nsc
, false, &errstr
, "CAPABILITY") != OK
) {
331 fprintf(stderr
, "Unable to send CAPABILITY command: %s\n", errstr
);
335 if (get_imap_response(nsc
, "CAPABILITY", &capstring
, NULL
, 1,
337 fprintf(stderr
, "Cannot get CAPABILITY response: %s\n", errstr
);
342 fprintf(stderr
, "No CAPABILITY response seen\n");
346 parse_capability(capstring
, strlen(capstring
));
351 ts_report(&tv_connect
, "Authentication time");
352 gettimeofday(&tv_auth
, NULL
);
355 while (msgqueue_head
!= NULL
) {
356 imsg
= msgqueue_head
;
358 if (send_imap_command(nsc
, imsg
->queue
, &errstr
, "%s",
359 imsg
->command
) != OK
) {
360 fprintf(stderr
, "Cannot send command \"%s\": %s\n", imsg
->command
,
367 if (get_imap_response(nsc
, NULL
, NULL
, NULL
, 0, &errstr
) != OK
) {
368 fprintf(stderr
, "Unable to get response for command "
369 "\"%s\": %s\n", imsg
->command
, errstr
);
374 msgqueue_head
= imsg
->next
;
381 ts_report(&tv_auth
, "Total command execution time");
383 send_imap_command(nsc
, 0, NULL
, "LOGOUT");
384 get_imap_response(nsc
, NULL
, NULL
, NULL
, 0, NULL
);
387 netsec_shutdown(nsc
);
390 ts_report(&tv_start
, "Total elapsed time");
396 * Parse a capability string
398 * Put these into an svector so we can check for stuff later. But special
399 * things, like AUTH, we parse now
403 parse_capability(const char *cap
, unsigned int len
)
405 char *str
= mh_xmalloc(len
+ 1);
409 trunccpy(str
, cap
, len
+ 1);
410 caplist
= brkstring(str
, " ", NULL
);
412 if (imap_capabilities
) {
413 svector_free(imap_capabilities
);
416 imap_capabilities
= svector_create(32);
423 for (i
= 0; caplist
[i
] != NULL
; i
++) {
424 if (has_prefix(caplist
[i
], "AUTH=") && *(caplist
[i
] + 5) != '\0') {
426 saslmechs
= add(" ", saslmechs
);
428 saslmechs
= add(caplist
[i
] + 5, saslmechs
);
430 svector_push_back(imap_capabilities
, getcpy(caplist
[i
]));
438 * Return 1 if a particular capability is set
442 capability_set(const char *capability
)
444 if (!imap_capabilities
)
447 return svector_find(imap_capabilities
, capability
) != NULL
;
451 * Clear the CAPABILITY list (used after we call STARTTLS, for example)
455 clear_capability(void)
457 svector_free(imap_capabilities
);
458 imap_capabilities
= NULL
;
462 have_capability(void)
464 return imap_capabilities
!= NULL
;
468 * Our SASL callback, which handles the SASL authentication dialog
472 imap_sasl_callback(enum sasl_message_type mtype
, unsigned const char *indata
,
473 unsigned int indatalen
, unsigned char **outdata
,
474 unsigned int *outdatalen
, void *context
, char **errstr
)
479 netsec_context
*nsc
= (netsec_context
*) context
;
482 case NETSEC_SASL_START
:
484 * Generate our AUTHENTICATE message.
486 * If SASL-IR capability is set, we can include any initial response
487 * in the AUTHENTICATE command. Otherwise we have to wait for
488 * the first server response (which should be blank).
491 mech
= netsec_get_sasl_mechanism(nsc
);
495 b64data
= mh_xmalloc(BASE64SIZE(indatalen
));
496 writeBase64raw(indata
, indatalen
, (unsigned char *) b64data
);
497 if (capability_set("SASL-IR")) {
498 netsec_set_snoop_callback(nsc
, netsec_b64_snoop_decoder
,
501 * Sigh. We're assuming a short tag length here. Really,
502 * I guess we should figure out a way to get the length
505 snoopoffset
= 17 + strlen(mech
);
506 rc
= send_imap_command(nsc
, 0, errstr
, "AUTHENTICATE %s %s",
509 netsec_set_snoop_callback(nsc
, NULL
, NULL
);
513 rc
= send_imap_command(nsc
, 0, errstr
, "AUTHENTICATE %s", mech
);
514 line
= netsec_readline(nsc
, &len
, errstr
);
518 * We should get a "+ ", nothing else.
520 if (len
!= 2 || strcmp(line
, "+ ") != 0) {
521 netsec_err(errstr
, "Did not get expected blank response "
522 "for initial challenge response");
525 rc
= netsec_printf(nsc
, errstr
, "%s\r\n", b64data
);
529 netsec_set_snoop_callback(nsc
, netsec_b64_snoop_decoder
, NULL
);
530 rc
= netsec_flush(nsc
, errstr
);
531 netsec_set_snoop_callback(nsc
, NULL
, NULL
);
536 if (send_imap_command(nsc
, 0, errstr
, "AUTHENTICATE %s",
544 * Get a response, decode it and process it.
547 case NETSEC_SASL_READ
:
548 netsec_set_snoop_callback(nsc
, netsec_b64_snoop_decoder
, &snoopoffset
);
550 line
= netsec_readline(nsc
, &len
, errstr
);
551 netsec_set_snoop_callback(nsc
, NULL
, NULL
);
556 if (len
< 2 || (len
== 2 && strcmp(line
, "+ ") != 0)) {
557 netsec_err(errstr
, "Invalid format for SASL response");
565 rc
= decodeBase64(line
+ 2, outdata
, &len
, 0, NULL
);
568 netsec_err(errstr
, "Unable to decode base64 response");
575 * Simple request encoding
578 case NETSEC_SASL_WRITE
:
580 unsigned char *b64data
;
581 b64data
= mh_xmalloc(BASE64SIZE(indatalen
));
582 writeBase64raw(indata
, indatalen
, b64data
);
583 rc
= netsec_printf(nsc
, errstr
, "%s", b64data
);
589 if (netsec_printf(nsc
, errstr
, "\r\n") != OK
)
592 netsec_set_snoop_callback(nsc
, netsec_b64_snoop_decoder
, NULL
);
593 rc
= netsec_flush(nsc
, errstr
);
594 netsec_set_snoop_callback(nsc
, NULL
, NULL
);
603 case NETSEC_SASL_FINISH
:
605 if (get_imap_response(nsc
, NULL
, NULL
, &line
, 1, errstr
) != OK
)
608 * We MIGHT get a capability response here. If so, be sure we
612 if (line
&& has_prefix(line
, "OK [CAPABILITY ")) {
613 char *p
= line
+ 15, *q
;
617 parse_capability(p
, q
- p
);
623 * Cancel an authentication dialog
626 case NETSEC_SASL_CANCEL
:
627 rc
= netsec_printf(nsc
, errstr
, "*\r\n");
629 rc
= netsec_flush(nsc
, errstr
);
638 * Send a single command to the IMAP server.
642 send_imap_command(netsec_context
*nsc
, bool noflush
, char **errstr
,
643 const char *fmt
, ...)
645 static unsigned int seq
= 0; /* Tag sequence number */
648 struct imap_cmd
*cmd
;
650 cmd
= mh_xmalloc(sizeof(*cmd
));
652 snprintf(cmd
->tag
, sizeof(cmd
->tag
), "A%u ", seq
++);
657 vsnprintf(cmd
->prefix
, sizeof(cmd
->prefix
), fmt
, ap
);
660 p
= strchr(cmd
->prefix
, ' ');
665 gettimeofday(&cmd
->start
, NULL
);
668 if (netsec_write(nsc
, cmd
->tag
, strlen(cmd
->tag
), errstr
) != OK
) {
674 rc
= netsec_vprintf(nsc
, errstr
, fmt
, ap
);
678 rc
= netsec_write(nsc
, "\r\n", 2, errstr
);
685 if (!noflush
&& netsec_flush(nsc
, errstr
) != OK
) {
690 cmd
->next
= cmdqueue
;
697 * Get all outstanding responses. If we were passed in a token string
698 * to look for, return it.
702 get_imap_response(netsec_context
*nsc
, const char *token
, char **tokenresponse
,
703 char **status
, int failerr
, char **errstr
)
706 struct imap_cmd
*cmd
;
707 bool numerrs
= false;
710 *tokenresponse
= NULL
;
714 if (!(line
= netsec_readline(nsc
, NULL
, errstr
)))
716 if (has_prefix(line
, "* ") && *(line
+ 2) != '\0') {
717 if (token
&& tokenresponse
&& has_prefix(line
+ 2, token
)) {
719 free(*tokenresponse
);
720 *tokenresponse
= getcpy(line
+ 2);
724 if (has_prefix(line
, cmdqueue
->tag
)) {
727 ts_report(&cmd
->start
, "Command (%s) execution time",
729 cmdqueue
= cmd
->next
;
732 for (cmd
= cmdqueue
; cmd
->next
!= NULL
; cmd
= cmd
->next
) {
733 if (has_prefix(line
, cmd
->next
->tag
)) {
734 struct imap_cmd
*cmd2
= cmd
->next
;
735 cmd
->next
= cmd
->next
->next
;
736 if (failerr
&& strncmp(line
+ strlen(cmd2
->tag
),
739 netsec_err(errstr
, "%s", line
+ strlen(cmd2
->tag
));
743 *status
= getcpy(line
);
746 netsec_err(errstr
, "Non-matching response line: %s\n",
754 return numerrs
? NOTOK
: OK
;
758 * Add an IMAP command to the msg queue
762 add_msg(bool queue
, const char *fmt
, ...)
764 struct imap_msg
*imsg
;
772 msg
= mh_xrealloc(msg
, msgbufsize
);
774 rc
= vsnprintf(msg
, msgbufsize
, fmt
, ap
);
776 } while (rc
>= (int) msgbufsize
);
778 imsg
= mh_xmalloc(sizeof(*imsg
));
784 if (msgqueue_head
== NULL
) {
785 msgqueue_head
= imsg
;
786 msgqueue_tail
= imsg
;
788 msgqueue_tail
->next
= imsg
;
789 msgqueue_tail
= imsg
;
794 * Negotiate TLS connection, with optional timestamp
798 imap_negotiate_tls(netsec_context
*nsc
)
804 gettimeofday(&tv
, NULL
);
806 if (netsec_negotiate_tls(nsc
, &errstr
) != OK
)
810 ts_report(&tv
, "TLS negotation time");
814 * Give a timestamp report.
818 ts_report(struct timeval
*tv
, const char *fmt
, ...)
824 gettimeofday(&now
, NULL
);
826 delta
= ((double) now
.tv_sec
) - ((double) tv
->tv_sec
) +
827 (now
.tv_usec
/ 1E6
- tv
->tv_usec
/ 1E6
);
830 vfprintf(stdout
, fmt
, ap
);
833 printf(": %f sec\n", delta
);