]> diplodocus.org Git - nmh/blob - uip/imaptest.c
c4919f7b00a8e3f98f5cee1e44d13c8a09a4fbe3
[nmh] / uip / imaptest.c
1 /* imaptest.c -- A program to send commands to an IMAP server
2 *
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.
6 */
7
8 #include <h/mh.h>
9 #include <h/utils.h>
10 #include <h/netsec.h>
11 #include <stdarg.h>
12 #include "h/done.h"
13 #include "sbr/base64.h"
14
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) \
25 X("tls", 0, TLSSW) \
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) \
33
34 #define X(sw, minchars, id) id,
35 DEFINE_SWITCH_ENUM(IMAPTEST);
36 #undef X
37
38 #define X(sw, minchars, id) { sw, minchars, id },
39 DEFINE_SWITCH_ARRAY(IMAPTEST, switches);
40 #undef X
41
42 struct imap_cmd;
43
44 struct imap_cmd {
45 char tag[16]; /* Command tag */
46 struct imap_cmd *next; /* Next pointer */
47 };
48
49 static struct imap_cmd *cmdqueue = NULL;
50 static char *saslmechs = NULL;
51 svector_t imap_capabilities = NULL;
52
53 static int imap_sasl_callback(enum sasl_message_type, unsigned const char *,
54 unsigned int, unsigned char **, unsigned int *,
55 void *, char **);
56
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,
65 char **errstr);
66
67 int
68 main (int argc, char **argv)
69 {
70 bool timestamp = false, sasl = false, tls = false, initialtls = false;
71 bool snoop = false;
72 int fd;
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;
76 size_t len;
77
78 if (nmh_init(argv[0], 1)) { return 1; }
79
80 arguments = getarguments (invo_name, argc, argv, 1);
81 argp = arguments;
82
83 while ((cp = *argp++)) {
84 if (*cp == '-') {
85 switch (smatch (++cp, switches)) {
86 case AMBIGSW:
87 ambigsw (cp, switches);
88 done (1);
89 case UNKWNSW:
90 adios (NULL, "-%s unknown", cp);
91
92 case HELPSW:
93 snprintf (buf, sizeof(buf), "%s [switches] +folder command "
94 "[command ...]", invo_name);
95 print_help (buf, switches, 1);
96 done (0);
97 case VERSIONSW:
98 print_version(invo_name);
99 done (0);
100
101 case HOSTSW:
102 if (!(host = *argp++) || *host == '-')
103 adios(NULL, "missing argument to %s", argp[-2]);
104 continue;
105 case PORTSW:
106 if (!(port = *argp++) || *port == '-')
107 adios(NULL, "missing argument to %s", argp[-2]);
108 continue;
109 case USERSW:
110 if (!(user = *argp++) || *user == '-')
111 adios(NULL, "missing argument to %s", argp[-2]);
112 continue;
113
114 case SNOOPSW:
115 snoop = true;
116 continue;
117 case NOSNOOPSW:
118 snoop = false;
119 continue;
120 case SASLSW:
121 sasl = true;
122 continue;
123 case NOSASLSW:
124 sasl = false;
125 continue;
126 case SASLMECHSW:
127 if (!(saslmech = *argp++) || *saslmech == '-')
128 adios(NULL, "missing argument to %s", argp[-2]);
129 continue;
130 case AUTHSERVICESW:
131 if (!(oauth_svc = *argp++) || *oauth_svc == '-')
132 adios(NULL, "missing argument to %s", argp[-2]);
133 continue;
134 case TLSSW:
135 tls = true;
136 initialtls = false;
137 continue;
138 case INITIALTLSSW:
139 tls = false;
140 initialtls = true;
141 continue;
142 case NOTLSSW:
143 tls = false;
144 initialtls = false;
145 continue;
146 case TIMESTAMPSW:
147 timestamp = true;
148 continue;
149 case NOTIMESTAMPSW:
150 timestamp = false;
151 continue;
152 }
153 }
154 }
155
156 if (! host)
157 adios(NULL, "A hostname must be given with -host");
158
159 nsc = netsec_init();
160
161 if (user)
162 netsec_set_userid(nsc, user);
163
164 netsec_set_hostname(nsc, host);
165
166 if (snoop)
167 netsec_set_snoop(nsc, 1);
168
169 if (oauth_svc) {
170 if (netsec_set_oauth_service(nsc, oauth_svc) != OK) {
171 adios(NULL, "OAuth2 not supported");
172 }
173 }
174
175 if ((fd = client(host, port, buf, sizeof(buf), snoop)) == NOTOK)
176 adios(NULL, "Connect failed: %s", buf);
177
178 netsec_set_fd(nsc, fd, fd);
179 netsec_set_snoop(nsc, snoop);
180
181 if (initialtls || tls) {
182 if (netsec_set_tls(nsc, 1, 0, &errstr) != OK)
183 adios(NULL, errstr);
184
185 if (initialtls && netsec_negotiate_tls(nsc, &errstr) != OK)
186 adios(NULL, errstr);
187 }
188
189 if (sasl) {
190 if (netsec_set_sasl_params(nsc, "imap", saslmech, imap_sasl_callback,
191 nsc, &errstr) != OK)
192 adios(NULL, errstr);
193 }
194
195 if ((cp = netsec_readline(nsc, &len, &errstr)) == NULL) {
196 adios(NULL, errstr);
197 }
198
199 if (has_prefix(cp, "* BYE")) {
200 fprintf(stderr, "Connection rejected: %s\n", cp + 5);
201 goto finish;
202 }
203
204 if (!has_prefix(cp, "* OK") && !has_prefix(cp, "* PREAUTH")) {
205 fprintf(stderr, "Invalid server response: %s\n", cp);
206 goto finish;
207 }
208
209 if ((p = strchr(cp + 2, ' ')) && *(p + 1) != '\0' &&
210 has_prefix(p + 1, "[CAPABILITY ")) {
211 /*
212 * Parse the capability list out to the end
213 */
214 char *q;
215 p += 13; /* 1 + [CAPABILITY + space */
216
217 if (!(q = strchr(p, ']'))) {
218 fprintf(stderr, "Cannot find end of CAPABILITY announcement\n");
219 goto finish;
220 }
221
222 parse_capability(p, q - p);
223 } else {
224 char *capstring;
225
226 if (send_imap_command(nsc, 0, &errstr, "CAPABILITY") != OK) {
227 fprintf(stderr, "Unable to send CAPABILITY command: %s\n", errstr);
228 goto finish;
229 }
230
231 if (get_imap_response(nsc, "CAPABILITY", &capstring, NULL, 1,
232 &errstr) != OK) {
233 fprintf(stderr, "Cannot get CAPABILITY response: %s\n", errstr);
234 goto finish;
235 }
236
237 if (! capstring) {
238 fprintf(stderr, "No CAPABILITY response seen\n");
239 goto finish;
240 }
241
242 parse_capability(capstring, strlen(capstring));
243 free(capstring);
244 }
245
246 if (tls) {
247 if (!capability_set("STARTTLS")) {
248 fprintf(stderr, "Requested STARTTLS with -tls, but IMAP server "
249 "has no support for STARTTLS\n");
250 goto finish;
251 }
252 if (send_imap_command(nsc, 0, &errstr, "STARTTLS") != OK) {
253 fprintf(stderr, "Unable to issue STARTTLS: %s\n", errstr);
254 goto finish;
255 }
256
257 if (get_imap_response(nsc, NULL, NULL, NULL, 1, &errstr) != OK) {
258 fprintf(stderr, "STARTTLS failed: %s\n", errstr);
259 goto finish;
260 }
261 if (netsec_negotiate_tls(nsc, &errstr) != OK) {
262 adios(NULL, errstr);
263 }
264 }
265
266 if (sasl) {
267 if (netsec_negotiate_sasl(nsc, saslmechs, &errstr) != OK) {
268 fprintf(stderr, "SASL negotiation failed: %s\n", errstr);
269 goto finish;
270 }
271 /*
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
276 * later.
277 */
278 if (netsec_get_sasl_ssf(nsc) > 0) {
279 clear_capability();
280 }
281 } else {
282 if (capability_set("LOGINDISABLED")) {
283 fprintf(stderr, "User did not request SASL, but LOGIN "
284 "is disabled\n");
285 goto finish;
286 }
287 }
288
289 send_imap_command(nsc, 0, NULL, "LOGOUT");
290 get_imap_response(nsc, NULL, NULL, NULL, 0, NULL);
291
292 finish:
293 netsec_shutdown(nsc);
294
295 exit(0);
296 }
297
298 /*
299 * Parse a capability string
300 *
301 * Put these into an svector so we can check for stuff later. But special
302 * things, like AUTH, we parse now
303 */
304
305 static void
306 parse_capability(const char *cap, unsigned int len)
307 {
308 char *str = mh_xmalloc(len + 1);
309 char **caplist;
310 int i;
311
312 trunccpy(str, cap, len + 1);
313 caplist = brkstring(str, " ", NULL);
314
315 if (imap_capabilities) {
316 svector_free(imap_capabilities);
317 }
318
319 imap_capabilities = svector_create(32);
320
321 if (saslmechs) {
322 free(saslmechs);
323 saslmechs = NULL;
324 }
325
326 for (i = 0; caplist[i] != NULL; i++) {
327 if (has_prefix(caplist[i], "AUTH=") && caplist[i] + 5 != '\0') {
328 if (saslmechs) {
329 saslmechs = add(" ", saslmechs);
330 }
331 saslmechs = add(caplist[i] + 5, saslmechs);
332 } else {
333 svector_push_back(imap_capabilities, getcpy(caplist[i]));
334 }
335 }
336
337 free(caplist);
338 free(str);
339 }
340
341 /*
342 * Return 1 if a particular capability is set
343 */
344
345 static int
346 capability_set(const char *capability)
347 {
348 if (!imap_capabilities)
349 return 0;
350
351 return svector_find(imap_capabilities, capability) != NULL;
352 }
353
354 /*
355 * Clear the CAPABILITY list (used after we call STARTTLS, for example)
356 */
357
358 static void
359 clear_capability(void)
360 {
361 svector_free(imap_capabilities);
362 imap_capabilities = NULL;
363 }
364
365 static int
366 have_capability(void)
367 {
368 return imap_capabilities != NULL;
369 }
370
371 /*
372 * Our SASL callback, which handles the SASL authentication dialog
373 */
374
375 static int
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)
379 {
380 int rc, snoopoffset;
381 char *mech, *line;
382 size_t len;
383 netsec_context *nsc = (netsec_context *) context;
384
385 switch (mtype) {
386 case NETSEC_SASL_START:
387 /*
388 * Generate our AUTHENTICATE message.
389 *
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).
393 */
394
395 mech = netsec_get_sasl_mechanism(nsc);
396
397 if (indatalen) {
398 char *b64data;
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,
403 &snoopoffset);
404 /*
405 * Sigh. We're assuming a short tag length here. Really,
406 * I guess we should figure out a way to get the length
407 * of the next tag.
408 */
409 snoopoffset = 17 + strlen(mech);
410 rc = send_imap_command(nsc, 0, errstr, "AUTHENTICATE %s %s",
411 mech, b64data);
412 free(b64data);
413 netsec_set_snoop_callback(nsc, NULL, NULL);
414 if (rc)
415 return NOTOK;
416 } else {
417 rc = send_imap_command(nsc, 0, errstr, "AUTHENTICATE %s", mech);
418 line = netsec_readline(nsc, &len, errstr);
419 if (! line)
420 return NOTOK;
421 /*
422 * We should get a "+ ", nothing else.
423 */
424 if (len != 2 || strcmp(line, "+ ") != 0) {
425 netsec_err(errstr, "Did not get expected blank response "
426 "for initial challenge response");
427 return NOTOK;
428 }
429 rc = netsec_printf(nsc, errstr, "%s\r\n", b64data);
430 free(b64data);
431 if (rc != OK)
432 return NOTOK;
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);
436 if (rc != OK)
437 return NOTOK;
438 }
439 } else {
440 if (send_imap_command(nsc, 0, errstr, "AUTHENTICATE %s",
441 mech) != OK)
442 return NOTOK;
443 }
444
445 break;
446
447 /*
448 * Get a response, decode it and process it.
449 */
450
451 case NETSEC_SASL_READ:
452 netsec_set_snoop_callback(nsc, netsec_b64_snoop_decoder, &snoopoffset);
453 snoopoffset = 2;
454 line = netsec_readline(nsc, &len, errstr);
455 netsec_set_snoop_callback(nsc, NULL, NULL);
456
457 if (line == NULL)
458 return NOTOK;
459
460 if (len < 2 || (len == 2 && strcmp(line, "+ ") != 0)) {
461 netsec_err(errstr, "Invalid format for SASL response");
462 return NOTOK;
463 }
464
465 if (len == 2) {
466 *outdata = NULL;
467 *outdatalen = 0;
468 } else {
469 rc = decodeBase64(line + 2, outdata, &len, 0, NULL);
470 *outdatalen = len;
471 if (rc != OK) {
472 netsec_err(errstr, "Unable to decode base64 response");
473 return NOTOK;
474 }
475 }
476 break;
477
478 /*
479 * Simple request encoding
480 */
481
482 case NETSEC_SASL_WRITE:
483 if (indatalen > 0) {
484 unsigned char *b64data;
485 b64data = mh_xmalloc(BASE64SIZE(indatalen));
486 writeBase64raw(indata, indatalen, b64data);
487 rc = netsec_printf(nsc, errstr, "%s", b64data);
488 free(b64data);
489 if (rc != OK)
490 return NOTOK;
491 }
492
493 if (netsec_printf(nsc, errstr, "\r\n") != OK)
494 return NOTOK;
495
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);
499 if (rc != OK)
500 return NOTOK;
501 break;
502
503 /*
504 * Finish protocol
505 */
506
507 case NETSEC_SASL_FINISH:
508 if (get_imap_response(nsc, NULL, NULL, &line, 1, errstr) != OK)
509 return NOTOK;
510 /*
511 * We MIGHT get a capability response here. If so, be sure we
512 * parse it.
513 */
514
515 if (has_prefix(line, "OK [CAPABILITY ")) {
516 char *p = line + 15, *q;
517 q = strchr(p, ']');
518
519 if (q)
520 parse_capability(p, q - p);
521 }
522
523 break;
524
525 /*
526 * Cancel an authentication dialog
527 */
528
529 case NETSEC_SASL_CANCEL:
530 rc = netsec_printf(nsc, errstr, "*\r\n");
531 if (rc == OK)
532 rc = netsec_flush(nsc, errstr);
533 if (rc != OK)
534 return NOTOK;
535 break;
536 }
537 return OK;
538 }
539
540 /*
541 * Send a single command to the IMAP server.
542 */
543
544 static int
545 send_imap_command(netsec_context *nsc, int noflush, char **errstr,
546 const char *fmt, ...)
547 {
548 static unsigned int seq = 0; /* Tag sequence number */
549 va_list ap;
550 int rc;
551 struct imap_cmd *cmd;
552
553 cmd = mh_xmalloc(sizeof(*cmd));
554
555 snprintf(cmd->tag, sizeof(cmd->tag), "A%u ", seq++);
556
557 if (netsec_write(nsc, cmd->tag, strlen(cmd->tag), errstr) != OK) {
558 free(cmd);
559 return NOTOK;
560 }
561
562 va_start(ap, fmt);
563 rc = netsec_vprintf(nsc, errstr, fmt, ap);
564 va_end(ap);
565
566 if (rc == OK)
567 rc = netsec_write(nsc, "\r\n", 2, errstr);
568
569 if (rc != OK) {
570 free(cmd);
571 return NOTOK;
572 }
573
574 if (!noflush && netsec_flush(nsc, errstr) != OK) {
575 free(cmd);
576 return NOTOK;
577 }
578
579 cmd->next = cmdqueue;
580 cmdqueue = cmd;
581
582 return OK;
583 }
584
585 /*
586 * Get all outstanding responses. If we were passed in a token string
587 * to look for, return it.
588 */
589
590 static int
591 get_imap_response(netsec_context *nsc, const char *token, char **tokenresponse,
592 char **status, int failerr, char **errstr)
593 {
594 char *line;
595 struct imap_cmd *cmd;
596 int numerrs = 0;
597
598 if (tokenresponse)
599 *tokenresponse = NULL;
600
601 getline:
602 while (cmdqueue) {
603 if (!(line = netsec_readline(nsc, NULL, errstr)))
604 return NOTOK;
605 if (has_prefix(line, "* ") && *(line + 2) != '\0') {
606 if (token && tokenresponse && has_prefix(line + 2, token)) {
607 if (*tokenresponse)
608 free(*tokenresponse);
609 *tokenresponse = getcpy(line + 2);
610 }
611 } else {
612
613 if (has_prefix(line, cmdqueue->tag)) {
614 cmd = cmdqueue;
615 cmdqueue = cmd->next;
616 free(cmd);
617 } else {
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),
623 "OK ", 3) != 0) {
624 numerrs++;
625 netsec_err(errstr, "%s", line + strlen(cmd2->tag));
626 }
627 free(cmd2);
628 if (status)
629 *status = getcpy(line);
630 goto getline;
631 }
632 netsec_err(errstr, "Non-matching response line: %s\n",
633 line);
634 return NOTOK;
635 }
636 }
637 }
638 }
639
640 return numerrs == 0 ? OK : NOTOK;
641 }