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 int 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 struct imap_cmd
*next
; /* Next pointer */
62 static struct imap_cmd
*cmdqueue
= NULL
;
64 static char *saslmechs
= NULL
;
65 svector_t imap_capabilities
= NULL
;
67 static int imap_sasl_callback(enum sasl_message_type
, unsigned const char *,
68 unsigned int, unsigned char **, unsigned int *,
71 static void parse_capability(const char *, unsigned int len
);
72 static int capability_set(const char *);
73 static void clear_capability(void);
74 static int have_capability(void);
75 static int send_imap_command(netsec_context
*, int noflush
, char **errstr
,
76 const char *fmt
, ...) CHECK_PRINTF(4, 5);
77 static int get_imap_response(netsec_context
*, const char *token
,
78 char **tokenresp
, char **status
, int failerr
,
81 static void ts_report(const char *str
, struct timeval
*tv
);
83 static void add_msg(int queue
, const char *fmt
, ...) CHECK_PRINTF(2, 3);
85 static bool timestamp
= false;
88 main (int argc
, char **argv
)
90 bool sasl
= false, tls
= false, initialtls
= false;
93 char *saslmech
= NULL
, *host
= NULL
, *port
= "143", *user
= NULL
;
94 char *cp
, **argp
, buf
[BUFSIZ
], *oauth_svc
= NULL
, *errstr
, **arguments
, *p
;
95 netsec_context
*nsc
= NULL
;
96 struct imap_msg
*imsg
;
98 struct timeval tv_start
, tv_connect
, tv_auth
;
100 if (nmh_init(argv
[0], 1)) { return 1; }
102 arguments
= getarguments (invo_name
, argc
, argv
, 1);
105 while ((cp
= *argp
++)) {
107 switch (smatch (++cp
, switches
)) {
109 ambigsw (cp
, switches
);
112 adios (NULL
, "-%s unknown", cp
);
115 snprintf (buf
, sizeof(buf
), "%s [switches] +folder command "
116 "[command ...]", invo_name
);
117 print_help (buf
, switches
, 1);
120 print_version(invo_name
);
124 if (!(host
= *argp
++) || *host
== '-')
125 adios(NULL
, "missing argument to %s", argp
[-2]);
128 if (!(port
= *argp
++) || *port
== '-')
129 adios(NULL
, "missing argument to %s", argp
[-2]);
132 if (!(user
= *argp
++) || *user
== '-')
133 adios(NULL
, "missing argument to %s", argp
[-2]);
149 if (!(saslmech
= *argp
++) || *saslmech
== '-')
150 adios(NULL
, "missing argument to %s", argp
[-2]);
153 if (!(oauth_svc
= *argp
++) || *oauth_svc
== '-')
154 adios(NULL
, "missing argument to %s", argp
[-2]);
175 } else if (*cp
== '+') {
176 if (*(cp
+ 1) == '\0')
177 adios(NULL
, "Invalid null folder name");
178 add_msg(0, "SELECT \"%s\"", cp
+ 1);
180 add_msg(0, "%s", cp
);
185 adios(NULL
, "A hostname must be given with -host");
190 netsec_set_userid(nsc
, user
);
192 netsec_set_hostname(nsc
, host
);
195 netsec_set_snoop(nsc
, 1);
198 if (netsec_set_oauth_service(nsc
, oauth_svc
) != OK
) {
199 adios(NULL
, "OAuth2 not supported");
204 gettimeofday(&tv_start
, NULL
);
206 if ((fd
= client(host
, port
, buf
, sizeof(buf
), snoop
)) == NOTOK
)
207 adios(NULL
, "Connect failed: %s", buf
);
210 ts_report("Connect time", &tv_start
);
211 gettimeofday(&tv_connect
, NULL
);
214 netsec_set_fd(nsc
, fd
, fd
);
215 netsec_set_snoop(nsc
, snoop
);
217 if (initialtls
|| tls
) {
218 if (netsec_set_tls(nsc
, 1, 0, &errstr
) != OK
)
219 adios(NULL
, "%s", errstr
);
221 if (initialtls
&& netsec_negotiate_tls(nsc
, &errstr
) != OK
)
222 adios(NULL
, "%s", errstr
);
226 if (netsec_set_sasl_params(nsc
, "imap", saslmech
, imap_sasl_callback
,
228 adios(NULL
, "%s", errstr
);
231 if ((cp
= netsec_readline(nsc
, &len
, &errstr
)) == NULL
) {
232 adios(NULL
, "%s", errstr
);
235 if (has_prefix(cp
, "* BYE")) {
236 fprintf(stderr
, "Connection rejected: %s\n", cp
+ 5);
240 if (!has_prefix(cp
, "* OK") && !has_prefix(cp
, "* PREAUTH")) {
241 fprintf(stderr
, "Invalid server response: %s\n", cp
);
245 if ((p
= strchr(cp
+ 2, ' ')) && *(p
+ 1) != '\0' &&
246 has_prefix(p
+ 1, "[CAPABILITY ")) {
248 * Parse the capability list out to the end
251 p
+= 13; /* 1 + [CAPABILITY + space */
253 if (!(q
= strchr(p
, ']'))) {
254 fprintf(stderr
, "Cannot find end of CAPABILITY announcement\n");
258 parse_capability(p
, q
- p
);
262 if (send_imap_command(nsc
, 0, &errstr
, "CAPABILITY") != OK
) {
263 fprintf(stderr
, "Unable to send CAPABILITY command: %s\n", errstr
);
267 if (get_imap_response(nsc
, "CAPABILITY", &capstring
, NULL
, 1,
269 fprintf(stderr
, "Cannot get CAPABILITY response: %s\n", errstr
);
274 fprintf(stderr
, "No CAPABILITY response seen\n");
278 parse_capability(capstring
, strlen(capstring
));
283 if (!capability_set("STARTTLS")) {
284 fprintf(stderr
, "Requested STARTTLS with -tls, but IMAP server "
285 "has no support for STARTTLS\n");
288 if (send_imap_command(nsc
, 0, &errstr
, "STARTTLS") != OK
) {
289 fprintf(stderr
, "Unable to issue STARTTLS: %s\n", errstr
);
293 if (get_imap_response(nsc
, NULL
, NULL
, NULL
, 1, &errstr
) != OK
) {
294 fprintf(stderr
, "STARTTLS failed: %s\n", errstr
);
297 if (netsec_negotiate_tls(nsc
, &errstr
) != OK
) {
298 adios(NULL
, "%s", errstr
);
303 if (netsec_negotiate_sasl(nsc
, saslmechs
, &errstr
) != OK
) {
304 fprintf(stderr
, "SASL negotiation failed: %s\n", errstr
);
308 * Sigh. If we negotiated a SSF AND we got a capability response
309 * as part of the AUTHENTICATE OK message, we can't actually trust
310 * it because it's not protected at that point. So discard the
311 * capability list and we will generate a fresh CAPABILITY command
314 if (netsec_get_sasl_ssf(nsc
) > 0) {
318 if (capability_set("LOGINDISABLED")) {
319 fprintf(stderr
, "User did not request SASL, but LOGIN "
325 if (!have_capability()) {
328 if (send_imap_command(nsc
, 0, &errstr
, "CAPABILITY") != OK
) {
329 fprintf(stderr
, "Unable to send CAPABILITY command: %s\n", errstr
);
333 if (get_imap_response(nsc
, "CAPABILITY", &capstring
, NULL
, 1,
335 fprintf(stderr
, "Cannot get CAPABILITY response: %s\n", errstr
);
340 fprintf(stderr
, "No CAPABILITY response seen\n");
344 parse_capability(capstring
, strlen(capstring
));
349 ts_report("Authentication time", &tv_connect
);
350 gettimeofday(&tv_auth
, NULL
);
353 while (msgqueue_head
!= NULL
) {
354 imsg
= msgqueue_head
;
356 if (send_imap_command(nsc
, imsg
->queue
, &errstr
, "%s",
357 imsg
->command
) != OK
) {
358 fprintf(stderr
, "Cannot send command \"%s\": %s\n", imsg
->command
,
365 if (get_imap_response(nsc
, NULL
, NULL
, NULL
, 0, &errstr
) != OK
) {
366 fprintf(stderr
, "Unable to get response for command "
367 "\"%s\": %s\n", imsg
->command
, errstr
);
372 msgqueue_head
= imsg
->next
;
378 ts_report("Total command execution time", &tv_auth
);
380 send_imap_command(nsc
, 0, NULL
, "LOGOUT");
381 get_imap_response(nsc
, NULL
, NULL
, NULL
, 0, NULL
);
384 netsec_shutdown(nsc
);
386 ts_report("Total elapsed time", &tv_start
);
392 * Parse a capability string
394 * Put these into an svector so we can check for stuff later. But special
395 * things, like AUTH, we parse now
399 parse_capability(const char *cap
, unsigned int len
)
401 char *str
= mh_xmalloc(len
+ 1);
405 trunccpy(str
, cap
, len
+ 1);
406 caplist
= brkstring(str
, " ", NULL
);
408 if (imap_capabilities
) {
409 svector_free(imap_capabilities
);
412 imap_capabilities
= svector_create(32);
419 for (i
= 0; caplist
[i
] != NULL
; i
++) {
420 if (has_prefix(caplist
[i
], "AUTH=") && *(caplist
[i
] + 5) != '\0') {
422 saslmechs
= add(" ", saslmechs
);
424 saslmechs
= add(caplist
[i
] + 5, saslmechs
);
426 svector_push_back(imap_capabilities
, getcpy(caplist
[i
]));
434 * Return 1 if a particular capability is set
438 capability_set(const char *capability
)
440 if (!imap_capabilities
)
443 return svector_find(imap_capabilities
, capability
) != NULL
;
447 * Clear the CAPABILITY list (used after we call STARTTLS, for example)
451 clear_capability(void)
453 svector_free(imap_capabilities
);
454 imap_capabilities
= NULL
;
458 have_capability(void)
460 return imap_capabilities
!= NULL
;
464 * Our SASL callback, which handles the SASL authentication dialog
468 imap_sasl_callback(enum sasl_message_type mtype
, unsigned const char *indata
,
469 unsigned int indatalen
, unsigned char **outdata
,
470 unsigned int *outdatalen
, void *context
, char **errstr
)
475 netsec_context
*nsc
= (netsec_context
*) context
;
478 case NETSEC_SASL_START
:
480 * Generate our AUTHENTICATE message.
482 * If SASL-IR capability is set, we can include any initial response
483 * in the AUTHENTICATE command. Otherwise we have to wait for
484 * the first server response (which should be blank).
487 mech
= netsec_get_sasl_mechanism(nsc
);
491 b64data
= mh_xmalloc(BASE64SIZE(indatalen
));
492 writeBase64raw(indata
, indatalen
, (unsigned char *) b64data
);
493 if (capability_set("SASL-IR")) {
494 netsec_set_snoop_callback(nsc
, netsec_b64_snoop_decoder
,
497 * Sigh. We're assuming a short tag length here. Really,
498 * I guess we should figure out a way to get the length
501 snoopoffset
= 17 + strlen(mech
);
502 rc
= send_imap_command(nsc
, 0, errstr
, "AUTHENTICATE %s %s",
505 netsec_set_snoop_callback(nsc
, NULL
, NULL
);
509 rc
= send_imap_command(nsc
, 0, errstr
, "AUTHENTICATE %s", mech
);
510 line
= netsec_readline(nsc
, &len
, errstr
);
514 * We should get a "+ ", nothing else.
516 if (len
!= 2 || strcmp(line
, "+ ") != 0) {
517 netsec_err(errstr
, "Did not get expected blank response "
518 "for initial challenge response");
521 rc
= netsec_printf(nsc
, errstr
, "%s\r\n", b64data
);
525 netsec_set_snoop_callback(nsc
, netsec_b64_snoop_decoder
, NULL
);
526 rc
= netsec_flush(nsc
, errstr
);
527 netsec_set_snoop_callback(nsc
, NULL
, NULL
);
532 if (send_imap_command(nsc
, 0, errstr
, "AUTHENTICATE %s",
540 * Get a response, decode it and process it.
543 case NETSEC_SASL_READ
:
544 netsec_set_snoop_callback(nsc
, netsec_b64_snoop_decoder
, &snoopoffset
);
546 line
= netsec_readline(nsc
, &len
, errstr
);
547 netsec_set_snoop_callback(nsc
, NULL
, NULL
);
552 if (len
< 2 || (len
== 2 && strcmp(line
, "+ ") != 0)) {
553 netsec_err(errstr
, "Invalid format for SASL response");
561 rc
= decodeBase64(line
+ 2, outdata
, &len
, 0, NULL
);
564 netsec_err(errstr
, "Unable to decode base64 response");
571 * Simple request encoding
574 case NETSEC_SASL_WRITE
:
576 unsigned char *b64data
;
577 b64data
= mh_xmalloc(BASE64SIZE(indatalen
));
578 writeBase64raw(indata
, indatalen
, b64data
);
579 rc
= netsec_printf(nsc
, errstr
, "%s", b64data
);
585 if (netsec_printf(nsc
, errstr
, "\r\n") != OK
)
588 netsec_set_snoop_callback(nsc
, netsec_b64_snoop_decoder
, NULL
);
589 rc
= netsec_flush(nsc
, errstr
);
590 netsec_set_snoop_callback(nsc
, NULL
, NULL
);
599 case NETSEC_SASL_FINISH
:
601 if (get_imap_response(nsc
, NULL
, NULL
, &line
, 1, errstr
) != OK
)
604 * We MIGHT get a capability response here. If so, be sure we
608 if (line
&& has_prefix(line
, "OK [CAPABILITY ")) {
609 char *p
= line
+ 15, *q
;
613 parse_capability(p
, q
- p
);
619 * Cancel an authentication dialog
622 case NETSEC_SASL_CANCEL
:
623 rc
= netsec_printf(nsc
, errstr
, "*\r\n");
625 rc
= netsec_flush(nsc
, errstr
);
634 * Send a single command to the IMAP server.
638 send_imap_command(netsec_context
*nsc
, int noflush
, char **errstr
,
639 const char *fmt
, ...)
641 static unsigned int seq
= 0; /* Tag sequence number */
644 struct imap_cmd
*cmd
;
646 cmd
= mh_xmalloc(sizeof(*cmd
));
648 snprintf(cmd
->tag
, sizeof(cmd
->tag
), "A%u ", seq
++);
651 gettimeofday(&cmd
->start
, NULL
);
653 if (netsec_write(nsc
, cmd
->tag
, strlen(cmd
->tag
), errstr
) != OK
) {
659 rc
= netsec_vprintf(nsc
, errstr
, fmt
, ap
);
663 rc
= netsec_write(nsc
, "\r\n", 2, errstr
);
670 if (!noflush
&& netsec_flush(nsc
, errstr
) != OK
) {
675 cmd
->next
= cmdqueue
;
682 * Get all outstanding responses. If we were passed in a token string
683 * to look for, return it.
687 get_imap_response(netsec_context
*nsc
, const char *token
, char **tokenresponse
,
688 char **status
, int failerr
, char **errstr
)
691 struct imap_cmd
*cmd
;
695 *tokenresponse
= NULL
;
699 if (!(line
= netsec_readline(nsc
, NULL
, errstr
)))
701 if (has_prefix(line
, "* ") && *(line
+ 2) != '\0') {
702 if (token
&& tokenresponse
&& has_prefix(line
+ 2, token
)) {
704 free(*tokenresponse
);
705 *tokenresponse
= getcpy(line
+ 2);
709 if (has_prefix(line
, cmdqueue
->tag
)) {
712 ts_report("Command execution time", &cmd
->start
);
713 cmdqueue
= cmd
->next
;
716 for (cmd
= cmdqueue
; cmd
->next
!= NULL
; cmd
= cmd
->next
) {
717 if (has_prefix(line
, cmd
->next
->tag
)) {
718 struct imap_cmd
*cmd2
= cmd
->next
;
719 cmd
->next
= cmd
->next
->next
;
720 if (failerr
&& strncmp(line
+ strlen(cmd2
->tag
),
723 netsec_err(errstr
, "%s", line
+ strlen(cmd2
->tag
));
727 *status
= getcpy(line
);
730 netsec_err(errstr
, "Non-matching response line: %s\n",
738 return numerrs
== 0 ? OK
: NOTOK
;
742 * Add an IMAP command to the msg queue
746 add_msg(int queue
, const char *fmt
, ...)
748 struct imap_msg
*imsg
;
756 msg
= mh_xrealloc(msg
, msgbufsize
);
758 rc
= vsnprintf(msg
, msgbufsize
, fmt
, ap
);
760 } while (rc
>= (int) msgbufsize
);
762 imsg
= mh_xmalloc(sizeof(*imsg
));
768 if (msgqueue_head
== NULL
) {
769 msgqueue_head
= imsg
;
770 msgqueue_tail
= imsg
;
772 msgqueue_tail
->next
= imsg
;
773 msgqueue_tail
= imsg
;
778 * Give a timestamp report.
782 ts_report(const char *str
, struct timeval
*tv
)
787 gettimeofday(&now
, NULL
);
789 delta
= ((double) now
.tv_sec
) - ((double) tv
->tv_sec
) +
790 (now
.tv_usec
/ 1E6
- tv
->tv_usec
/ 1E6
);
792 printf("%s: %f sec\n", str
, delta
);