]> diplodocus.org Git - nmh/blob - uip/imaptest.c
a13593862d96b3fd01a09dcdff3b05e178e060bc
[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 "sbr/client.h"
10 #include "sbr/getcpy.h"
11 #include "sbr/brkstring.h"
12 #include "sbr/ambigsw.h"
13 #include "sbr/print_version.h"
14 #include "sbr/print_help.h"
15 #include "sbr/error.h"
16 #include "h/utils.h"
17 #include "h/netsec.h"
18 #include <stdarg.h>
19 #include <sys/time.h>
20 #include "h/done.h"
21 #include "sbr/base64.h"
22
23 #define IMAPTEST_SWITCHES \
24 X("host hostname", 0, HOSTSW) \
25 X("user username", 0, USERSW) \
26 X("port name/number", 0, PORTSW) \
27 X("snoop", 0, SNOOPSW) \
28 X("nosnoop", 0, NOSNOOPSW) \
29 X("sasl", 0, SASLSW) \
30 X("nosasl", 0, NOSASLSW) \
31 X("saslmech", 0, SASLMECHSW) \
32 X("authservice", 0, AUTHSERVICESW) \
33 X("tls", 0, TLSSW) \
34 X("notls", 0, NOTLSSW) \
35 X("initialtls", 0, INITIALTLSSW) \
36 X("queue", 0, QUEUESW) \
37 X("noqueue", 0, NOQUEUESW) \
38 X("append filename", 0, APPENDSW) \
39 X("afolder foldername", 0, AFOLDERSW) \
40 X("batch filename", 0, BATCHSW) \
41 X("timestamp", 0, TIMESTAMPSW) \
42 X("notimestamp", 0, NOTIMESTAMPSW) \
43 X("timeout", 0, TIMEOUTSW) \
44 X("version", 0, VERSIONSW) \
45 X("help", 0, HELPSW) \
46
47 #define X(sw, minchars, id) id,
48 DEFINE_SWITCH_ENUM(IMAPTEST);
49 #undef X
50
51 #define X(sw, minchars, id) { sw, minchars, id },
52 DEFINE_SWITCH_ARRAY(IMAPTEST, switches);
53 #undef X
54
55 struct imap_msg;
56
57 struct imap_msg {
58 char *command; /* Command to send */
59 char *folder; /* Folder (for append) */
60 bool queue; /* If true, queue for later delivery */
61 bool append; /* If true, append "command" to mbox */
62 size_t msgsize; /* RFC822 size of message */
63 struct imap_msg *next; /* Next pointer */
64 };
65
66 struct imap_msg *msgqueue_head = NULL;
67 struct imap_msg *msgqueue_tail = NULL;
68
69 struct imap_cmd;
70
71 struct imap_cmd {
72 char tag[16]; /* Command tag */
73 struct timeval start; /* Time command was sent */
74 char prefix[64]; /* Command prefix */
75 struct imap_cmd *next; /* Next pointer */
76 };
77
78 static struct imap_cmd *cmdqueue = NULL;
79
80 static char *saslmechs = NULL;
81 svector_t imap_capabilities = NULL;
82
83 static int imap_sasl_callback(enum sasl_message_type, unsigned const char *,
84 unsigned int, unsigned char **, unsigned int *,
85 void *, char **);
86
87 static void parse_capability(const char *, unsigned int len);
88 static int capability_set(const char *);
89 static void clear_capability(void);
90 static int have_capability(void);
91 static int send_imap_command(netsec_context *, bool noflush, char **errstr,
92 const char *fmt, ...) CHECK_PRINTF(4, 5);
93 static int send_append(netsec_context *, struct imap_msg *, char **errstr);
94 static int get_imap_response(netsec_context *, const char *token,
95 char **tokenresp, char **status, bool contok,
96 bool failerr, char **errstr);
97
98 static void ts_report(struct timeval *tv, const char *fmt, ...)
99 CHECK_PRINTF(2, 3);
100 static void imap_negotiate_tls(netsec_context *);
101
102 static void add_msg(bool queue, struct imap_msg **, const char *fmt, ...)
103 CHECK_PRINTF(3, 4);
104 static void add_append(const char *filename, const char *folder, bool queue);
105
106 static void batchfile(const char *filename, char *afolder, bool queue);
107
108 static size_t rfc822size(const char *filename);
109
110 static bool timestamp = false;
111
112 int
113 main (int argc, char **argv)
114 {
115 bool sasl = false, tls = false, initialtls = false;
116 bool snoop = false, queue = false;
117 int fd, timeout = 0;
118 char *saslmech = NULL, *host = NULL, *port = "143", *user = NULL;
119 char *cp, **argp, buf[BUFSIZ], *oauth_svc = NULL, *errstr, **arguments, *p;
120 char *afolder = NULL;
121 netsec_context *nsc = NULL;
122 struct imap_msg *imsg;
123 size_t len;
124 struct timeval tv_start, tv_connect, tv_auth;
125
126 if (nmh_init(argv[0], true, true)) { return 1; }
127
128 arguments = getarguments (invo_name, argc, argv, 1);
129 argp = arguments;
130
131 while ((cp = *argp++)) {
132 if (*cp == '-') {
133 switch (smatch (++cp, switches)) {
134 case AMBIGSW:
135 ambigsw (cp, switches);
136 done (1);
137 case UNKWNSW:
138 die("-%s unknown", cp);
139
140 case HELPSW:
141 snprintf (buf, sizeof(buf), "%s [switches] +folder command "
142 "[command ...]", invo_name);
143 print_help (buf, switches, 1);
144 done (0);
145 case VERSIONSW:
146 print_version(invo_name);
147 done (0);
148
149 case HOSTSW:
150 if (!(host = *argp++) || *host == '-')
151 die("missing argument to %s", argp[-2]);
152 continue;
153 case PORTSW:
154 if (!(port = *argp++) || *port == '-')
155 die("missing argument to %s", argp[-2]);
156 continue;
157 case USERSW:
158 if (!(user = *argp++) || *user == '-')
159 die("missing argument to %s", argp[-2]);
160 continue;
161
162 case AFOLDERSW:
163 if (!(afolder = *argp++) || *afolder == '-')
164 die("missing argument to %s", argp[-2]);
165 continue;
166 case APPENDSW:
167 if (!*argp || (**argp == '-'))
168 die("missing argument to %s", argp[-1]);
169 if (! afolder)
170 die("Append folder must be set with -afolder first");
171 add_append(*argp++, afolder, queue);
172 continue;
173
174 case BATCHSW:
175 if (! *argp || (**argp == '-'))
176 die("missing argument to %s", argp[-1]);
177 batchfile(*argp++, afolder, queue);
178 continue;
179
180 case TIMEOUTSW:
181 if (! *argp || (**argp == '-'))
182 die("missing argument to %s", argp[-1]);
183 if (! (timeout = atoi(*argp++)))
184 die("Invalid timeout: %s", argp[-1]);
185 continue;
186
187 case SNOOPSW:
188 snoop = true;
189 continue;
190 case NOSNOOPSW:
191 snoop = false;
192 continue;
193 case SASLSW:
194 sasl = true;
195 continue;
196 case NOSASLSW:
197 sasl = false;
198 continue;
199 case SASLMECHSW:
200 if (!(saslmech = *argp++) || *saslmech == '-')
201 die("missing argument to %s", argp[-2]);
202 continue;
203 case AUTHSERVICESW:
204 if (!(oauth_svc = *argp++) || *oauth_svc == '-')
205 die("missing argument to %s", argp[-2]);
206 continue;
207 case TLSSW:
208 tls = true;
209 initialtls = false;
210 continue;
211 case INITIALTLSSW:
212 tls = false;
213 initialtls = true;
214 continue;
215 case NOTLSSW:
216 tls = false;
217 initialtls = false;
218 continue;
219 case QUEUESW:
220 queue = true;
221 continue;
222 case NOQUEUESW:
223 queue = false;
224 continue;
225 case TIMESTAMPSW:
226 timestamp = true;
227 continue;
228 case NOTIMESTAMPSW:
229 timestamp = false;
230 continue;
231 }
232 } else if (*cp == '+') {
233 if (*(cp + 1) == '\0')
234 die("Invalid null folder name");
235 add_msg(false, NULL, "SELECT \"%s\"", cp + 1);
236 } else {
237 add_msg(queue, NULL, "%s", cp);
238 }
239 }
240
241 if (! host)
242 die("A hostname must be given with -host");
243
244 nsc = netsec_init();
245
246 if (user)
247 netsec_set_userid(nsc, user);
248
249 netsec_set_hostname(nsc, host);
250
251 if (timeout)
252 netsec_set_timeout(nsc, timeout);
253
254 if (snoop)
255 netsec_set_snoop(nsc, 1);
256
257 if (oauth_svc) {
258 if (netsec_set_oauth_service(nsc, oauth_svc) != OK) {
259 die("OAuth2 not supported");
260 }
261 }
262
263 if (timestamp)
264 gettimeofday(&tv_start, NULL);
265
266 if ((fd = client(host, port, buf, sizeof(buf), snoop)) == NOTOK)
267 die("Connect failed: %s", buf);
268
269 if (timestamp) {
270 ts_report(&tv_start, "Connect time");
271 gettimeofday(&tv_connect, NULL);
272 }
273
274 netsec_set_fd(nsc, fd, fd);
275 netsec_set_snoop(nsc, snoop);
276
277 if (initialtls || tls) {
278 if (netsec_set_tls(nsc, 1, 0, &errstr) != OK)
279 die("%s", errstr);
280
281 if (initialtls)
282 imap_negotiate_tls(nsc);
283 }
284
285 if (sasl) {
286 if (netsec_set_sasl_params(nsc, "imap", saslmech, imap_sasl_callback,
287 nsc, &errstr) != OK)
288 die("%s", errstr);
289 }
290
291 if ((cp = netsec_readline(nsc, &len, &errstr)) == NULL) {
292 die("%s", errstr);
293 }
294
295 if (has_prefix(cp, "* BYE")) {
296 fprintf(stderr, "Connection rejected: %s\n", cp + 5);
297 goto finish;
298 }
299
300 if (!has_prefix(cp, "* OK") && !has_prefix(cp, "* PREAUTH")) {
301 fprintf(stderr, "Invalid server response: %s\n", cp);
302 goto finish;
303 }
304
305 if ((p = strchr(cp + 2, ' ')) && *(p + 1) != '\0' &&
306 has_prefix(p + 1, "[CAPABILITY ")) {
307 /*
308 * Parse the capability list out to the end
309 */
310 char *q;
311 p += 13; /* 1 + [CAPABILITY + space */
312
313 if (!(q = strchr(p, ']'))) {
314 fprintf(stderr, "Cannot find end of CAPABILITY announcement\n");
315 goto finish;
316 }
317
318 parse_capability(p, q - p);
319 } else {
320 char *capstring;
321
322 if (send_imap_command(nsc, false, &errstr, "CAPABILITY") != OK) {
323 fprintf(stderr, "Unable to send CAPABILITY command: %s\n", errstr);
324 goto finish;
325 }
326
327 if (get_imap_response(nsc, "CAPABILITY ", &capstring, NULL, false, true,
328 &errstr) != OK) {
329 fprintf(stderr, "Cannot get CAPABILITY response: %s\n", errstr);
330 goto finish;
331 }
332
333 if (! capstring) {
334 fprintf(stderr, "No CAPABILITY response seen\n");
335 goto finish;
336 }
337
338 p = capstring + 11; /* "CAPABILITY " */
339
340 parse_capability(p, strlen(p));
341 free(capstring);
342 }
343
344 if (tls) {
345 if (!capability_set("STARTTLS")) {
346 fprintf(stderr, "Requested STARTTLS with -tls, but IMAP server "
347 "has no support for STARTTLS\n");
348 goto finish;
349 }
350 if (send_imap_command(nsc, false, &errstr, "STARTTLS") != OK) {
351 fprintf(stderr, "Unable to issue STARTTLS: %s\n", errstr);
352 goto finish;
353 }
354
355 if (get_imap_response(nsc, NULL, NULL, NULL, false, true,
356 &errstr) != OK) {
357 fprintf(stderr, "STARTTLS failed: %s\n", errstr);
358 goto finish;
359 }
360
361 imap_negotiate_tls(nsc);
362 }
363
364 if (sasl) {
365 if (netsec_negotiate_sasl(nsc, saslmechs, &errstr) != OK) {
366 fprintf(stderr, "SASL negotiation failed: %s\n", errstr);
367 goto finish;
368 }
369 /*
370 * Sigh. If we negotiated a SSF AND we got a capability response
371 * as part of the AUTHENTICATE OK message, we can't actually trust
372 * it because it's not protected at that point. So discard the
373 * capability list and we will generate a fresh CAPABILITY command
374 * later.
375 */
376 if (netsec_get_sasl_ssf(nsc) > 0) {
377 clear_capability();
378 }
379 } else {
380 if (capability_set("LOGINDISABLED")) {
381 fprintf(stderr, "User did not request SASL, but LOGIN "
382 "is disabled\n");
383 goto finish;
384 }
385 }
386
387 if (!have_capability()) {
388 char *capstring;
389
390 if (send_imap_command(nsc, false, &errstr, "CAPABILITY") != OK) {
391 fprintf(stderr, "Unable to send CAPABILITY command: %s\n", errstr);
392 goto finish;
393 }
394
395 if (get_imap_response(nsc, "CAPABILITY ", &capstring, NULL, false,
396 true, &errstr) != OK) {
397 fprintf(stderr, "Cannot get CAPABILITY response: %s\n", errstr);
398 goto finish;
399 }
400
401 if (! capstring) {
402 fprintf(stderr, "No CAPABILITY response seen\n");
403 goto finish;
404 }
405
406 p = capstring + 11; /* "CAPABILITY " */
407
408 parse_capability(p, strlen(p));
409 free(capstring);
410 }
411
412 if (timestamp) {
413 ts_report(&tv_connect, "Authentication time");
414 gettimeofday(&tv_auth, NULL);
415 }
416
417 while (msgqueue_head != NULL) {
418 imsg = msgqueue_head;
419
420 if (imsg->append) {
421 if (send_append(nsc, imsg, &errstr) != OK) {
422 fprintf(stderr, "Cannot send APPEND for %s to mbox %s: %s\n",
423 imsg->command, imsg->folder, errstr);
424 free(errstr);
425 goto finish;
426 }
427 } else if (send_imap_command(nsc, imsg->queue, &errstr, "%s",
428 imsg->command) != OK) {
429 fprintf(stderr, "Cannot send command \"%s\": %s\n",
430 imsg->command, errstr);
431 free(errstr);
432 goto finish;
433 }
434
435 if (! imsg->queue) {
436 if (get_imap_response(nsc, NULL, NULL, NULL, false, false,
437 &errstr) != OK) {
438 fprintf(stderr, "Unable to get response for command "
439 "\"%s\": %s\n", imsg->command, errstr);
440 goto finish;
441 }
442 }
443
444 msgqueue_head = imsg->next;
445
446 free(imsg->command);
447 free(imsg->folder);
448 free(imsg);
449 }
450
451 /*
452 * Flush out any pending network data and get any responses
453 */
454
455 if (netsec_flush(nsc, &errstr) != OK) {
456 fprintf(stderr, "Error performing final network flush: %s\n", errstr);
457 free(errstr);
458 }
459
460 if (get_imap_response(nsc, NULL, NULL, NULL, false, false, &errstr) != OK) {
461 fprintf(stderr, "Error fetching final command responses: %s\n", errstr);
462 free(errstr);
463 }
464
465 if (timestamp)
466 ts_report(&tv_auth, "Total command execution time");
467
468 send_imap_command(nsc, false, NULL, "LOGOUT");
469 get_imap_response(nsc, NULL, NULL, NULL, false, false, NULL);
470
471 finish:
472 netsec_shutdown(nsc);
473
474 if (timestamp)
475 ts_report(&tv_start, "Total elapsed time");
476
477 exit(0);
478 }
479
480 /*
481 * Parse a capability string
482 *
483 * Put these into an svector so we can check for stuff later. But special
484 * things, like AUTH, we parse now
485 */
486
487 static void
488 parse_capability(const char *cap, unsigned int len)
489 {
490 char *str = mh_xmalloc(len + 1);
491 char **caplist;
492 int i;
493
494 trunccpy(str, cap, len + 1);
495 caplist = brkstring(str, " ", NULL);
496
497 if (imap_capabilities) {
498 svector_free(imap_capabilities);
499 }
500
501 imap_capabilities = svector_create(32);
502
503 if (saslmechs) {
504 free(saslmechs);
505 saslmechs = NULL;
506 }
507
508 for (i = 0; caplist[i] != NULL; i++) {
509 if (has_prefix(caplist[i], "AUTH=") && *(caplist[i] + 5) != '\0') {
510 if (saslmechs) {
511 saslmechs = add(" ", saslmechs);
512 }
513 saslmechs = add(caplist[i] + 5, saslmechs);
514 } else {
515 svector_push_back(imap_capabilities, getcpy(caplist[i]));
516 }
517 }
518
519 free(str);
520 }
521
522 /*
523 * Return 1 if a particular capability is set
524 */
525
526 static int
527 capability_set(const char *capability)
528 {
529 if (!imap_capabilities)
530 return 0;
531
532 return svector_find(imap_capabilities, capability) != NULL;
533 }
534
535 /*
536 * Clear the CAPABILITY list (used after we call STARTTLS, for example)
537 */
538
539 static void
540 clear_capability(void)
541 {
542 svector_free(imap_capabilities);
543 imap_capabilities = NULL;
544 }
545
546 static int
547 have_capability(void)
548 {
549 return imap_capabilities != NULL;
550 }
551
552 /*
553 * Our SASL callback, which handles the SASL authentication dialog
554 */
555
556 static int
557 imap_sasl_callback(enum sasl_message_type mtype, unsigned const char *indata,
558 unsigned int indatalen, unsigned char **outdata,
559 unsigned int *outdatalen, void *context, char **errstr)
560 {
561 int rc, snoopoffset;
562 char *mech, *line, *capstring, *p;
563 size_t len;
564 netsec_context *nsc = (netsec_context *) context;
565
566 switch (mtype) {
567 case NETSEC_SASL_START:
568 /*
569 * Generate our AUTHENTICATE message.
570 *
571 * If SASL-IR capability is set, we can include any initial response
572 * in the AUTHENTICATE command. Otherwise we have to wait for
573 * the first server response (which should be blank).
574 */
575
576 mech = netsec_get_sasl_mechanism(nsc);
577
578 if (indatalen) {
579 char *b64data;
580 b64data = mh_xmalloc(BASE64SIZE(indatalen));
581 writeBase64raw(indata, indatalen, (unsigned char *) b64data);
582 if (capability_set("SASL-IR")) {
583 netsec_set_snoop_callback(nsc, netsec_b64_snoop_decoder,
584 &snoopoffset);
585 /*
586 * Sigh. We're assuming a short tag length here. Really,
587 * I guess we should figure out a way to get the length
588 * of the next tag.
589 */
590 snoopoffset = 17 + strlen(mech);
591 rc = send_imap_command(nsc, 0, errstr, "AUTHENTICATE %s %s",
592 mech, b64data);
593 free(b64data);
594 netsec_set_snoop_callback(nsc, NULL, NULL);
595 if (rc)
596 return NOTOK;
597 } else {
598 rc = send_imap_command(nsc, 0, errstr, "AUTHENTICATE %s", mech);
599 line = netsec_readline(nsc, &len, errstr);
600 if (! line)
601 return NOTOK;
602 /*
603 * We should get a "+ ", nothing else.
604 */
605 if (len != 2 || strcmp(line, "+ ") != 0) {
606 netsec_err(errstr, "Did not get expected blank response "
607 "for initial challenge response");
608 return NOTOK;
609 }
610 rc = netsec_printf(nsc, errstr, "%s\r\n", b64data);
611 free(b64data);
612 if (rc != OK)
613 return NOTOK;
614 netsec_set_snoop_callback(nsc, netsec_b64_snoop_decoder, NULL);
615 rc = netsec_flush(nsc, errstr);
616 netsec_set_snoop_callback(nsc, NULL, NULL);
617 if (rc != OK)
618 return NOTOK;
619 }
620 } else {
621 if (send_imap_command(nsc, 0, errstr, "AUTHENTICATE %s",
622 mech) != OK)
623 return NOTOK;
624 }
625
626 break;
627
628 /*
629 * Get a response, decode it and process it.
630 */
631
632 case NETSEC_SASL_READ:
633 netsec_set_snoop_callback(nsc, netsec_b64_snoop_decoder, &snoopoffset);
634 snoopoffset = 2;
635 line = netsec_readline(nsc, &len, errstr);
636 netsec_set_snoop_callback(nsc, NULL, NULL);
637
638 if (line == NULL)
639 return NOTOK;
640
641 if (len < 2 || (len == 2 && strcmp(line, "+ ") != 0)) {
642 netsec_err(errstr, "Invalid format for SASL response");
643 return NOTOK;
644 }
645
646 if (len == 2) {
647 *outdata = NULL;
648 *outdatalen = 0;
649 } else {
650 rc = decodeBase64(line + 2, outdata, &len, 0, NULL);
651 *outdatalen = len;
652 if (rc != OK) {
653 netsec_err(errstr, "Unable to decode base64 response");
654 return NOTOK;
655 }
656 }
657 break;
658
659 /*
660 * Simple request encoding
661 */
662
663 case NETSEC_SASL_WRITE:
664 if (indatalen > 0) {
665 unsigned char *b64data;
666 b64data = mh_xmalloc(BASE64SIZE(indatalen));
667 writeBase64raw(indata, indatalen, b64data);
668 rc = netsec_printf(nsc, errstr, "%s", b64data);
669 free(b64data);
670 if (rc != OK)
671 return NOTOK;
672 }
673
674 if (netsec_printf(nsc, errstr, "\r\n") != OK)
675 return NOTOK;
676
677 netsec_set_snoop_callback(nsc, netsec_b64_snoop_decoder, NULL);
678 rc = netsec_flush(nsc, errstr);
679 netsec_set_snoop_callback(nsc, NULL, NULL);
680 if (rc != OK)
681 return NOTOK;
682 break;
683
684 /*
685 * Finish protocol
686 */
687
688 case NETSEC_SASL_FINISH:
689 line = NULL;
690 if (get_imap_response(nsc, "CAPABILITY ", &capstring, &line,
691 false, true, errstr) != OK)
692 return NOTOK;
693 /*
694 * We MIGHT get a capability response here. If so, be sure we
695 * parse it. We ALSO might get a untagged CAPABILITY response.
696 * Which one should we prefer? I guess we'll go with the untagged
697 * one.
698 */
699
700 if (capstring) {
701 p = capstring + 11; /* "CAPABILITY " */
702 parse_capability(p, strlen(p));
703 free(capstring);
704 } else if (line && has_prefix(line, "OK [CAPABILITY ")) {
705 char *q;
706
707 p = line + 15;
708 q = strchr(p, ']');
709
710 if (q)
711 parse_capability(p, q - p);
712 }
713
714 break;
715
716 /*
717 * Cancel an authentication dialog
718 */
719
720 case NETSEC_SASL_CANCEL:
721 rc = netsec_printf(nsc, errstr, "*\r\n");
722 if (rc == OK)
723 rc = netsec_flush(nsc, errstr);
724 if (rc != OK)
725 return NOTOK;
726 break;
727 }
728 return OK;
729 }
730
731 /*
732 * Send a single command to the IMAP server.
733 */
734
735 static int
736 send_imap_command(netsec_context *nsc, bool noflush, char **errstr,
737 const char *fmt, ...)
738 {
739 static unsigned int seq = 0; /* Tag sequence number */
740 va_list ap;
741 int rc;
742 struct imap_cmd *cmd;
743
744 cmd = mh_xmalloc(sizeof(*cmd));
745
746 snprintf(cmd->tag, sizeof(cmd->tag), "A%u ", seq++);
747
748 if (timestamp) {
749 char *p;
750 va_start(ap, fmt);
751 vsnprintf(cmd->prefix, sizeof(cmd->prefix), fmt, ap);
752 va_end(ap);
753
754 p = strchr(cmd->prefix, ' ');
755
756 if (p)
757 *p = '\0';
758
759 gettimeofday(&cmd->start, NULL);
760 }
761
762 if (netsec_write(nsc, cmd->tag, strlen(cmd->tag), errstr) != OK) {
763 free(cmd);
764 return NOTOK;
765 }
766
767 va_start(ap, fmt);
768 rc = netsec_vprintf(nsc, errstr, fmt, ap);
769 va_end(ap);
770
771 if (rc == OK)
772 rc = netsec_write(nsc, "\r\n", 2, errstr);
773
774 if (rc != OK) {
775 free(cmd);
776 return NOTOK;
777 }
778
779 if (!noflush && netsec_flush(nsc, errstr) != OK) {
780 free(cmd);
781 return NOTOK;
782 }
783
784 cmd->next = cmdqueue;
785 cmdqueue = cmd;
786
787 return OK;
788 }
789
790 /*
791 * Send an APPEND to the server, which requires some extra semantics
792 */
793
794 static int
795 send_append(netsec_context *nsc, struct imap_msg *imsg, char **errstr)
796 {
797 FILE *f;
798 bool nonsynlit = false;
799 char *status = NULL, *line = NULL;
800 size_t linesize = 0;
801 ssize_t rc;
802
803 /*
804 * If we have the LITERAL+ extension, or we have LITERAL- and our
805 * message is 4096 bytes or less, we can do it all in one message.
806 * Otherwise we have to wait for a contination marker (+).
807 */
808
809 if (capability_set("LITERAL+") ||
810 (capability_set("LITERAL-") && imsg->msgsize <= 4096)) {
811 nonsynlit = true;
812 }
813
814 /*
815 * Send our APPEND command
816 */
817
818 if (send_imap_command(nsc, nonsynlit, errstr, "APPEND \"%s\" {%u%s}",
819 imsg->folder, (unsigned int) imsg->msgsize,
820 nonsynlit ? "+" : "") != OK)
821 return NOTOK;
822
823 /*
824 * If we need to wait for a syncing literal, do that now
825 */
826
827 if (! nonsynlit) {
828 if (get_imap_response(nsc, NULL, NULL, &status, true,
829 true, errstr) != OK) {
830 imsg->queue = true; /* XXX Sigh */
831 fprintf(stderr, "APPEND command failed: %s\n", *errstr);
832 free(*errstr);
833 return OK;
834 }
835 if (!(status && has_prefix(status, "+"))) {
836 netsec_err(errstr, "Expected contination (+), but got: %s", status);
837 free(status);
838 return NOTOK;
839 }
840 free(status);
841 }
842
843 /*
844 * Now write the message out, but make sure we end each line with \r\n
845 */
846
847 if ((f = fopen(imsg->command, "r")) == NULL) {
848 netsec_err(errstr, "Unable to open %s: %s", imsg->command,
849 strerror(errno));
850 return NOTOK;
851 }
852
853 while ((rc = getline(&line, &linesize, f)) > 0) {
854 if (rc > 1 && line[rc - 1] == '\n' && line[rc - 2] == '\r') {
855 if (netsec_write(nsc, line, rc, errstr) != OK) {
856 free(line);
857 fclose(f);
858 return NOTOK;
859 }
860 } else {
861 if (line[rc - 1] == '\n')
862 rc--;
863 if (netsec_write(nsc, line, rc, errstr) != OK) {
864 free(line);
865 fclose(f);
866 return NOTOK;
867 }
868 if (netsec_write(nsc, "\r\n", 2, errstr) != OK) {
869 free(line);
870 fclose(f);
871 return NOTOK;
872 }
873 }
874 }
875
876 free(line);
877
878 if (! feof(f)) {
879 netsec_err(errstr, "Error reading %s: %s", imsg->command,
880 strerror(errno));
881 fclose(f);
882 return NOTOK;
883 }
884
885 fclose(f);
886
887 /*
888 * Send a final \r\n for the end of the command
889 */
890
891 if (netsec_write(nsc, "\r\n", 2, errstr) != OK)
892 return NOTOK;
893
894 if (! imsg->queue)
895 return netsec_flush(nsc, errstr);
896
897 return OK;
898 }
899
900 /*
901 * Get all outstanding responses. If we were passed in a token string
902 * to look for, return it.
903 */
904
905 static int
906 get_imap_response(netsec_context *nsc, const char *token, char **tokenresponse,
907 char **status, bool condok, bool failerr, char **errstr)
908 {
909 char *line;
910 struct imap_cmd *cmd;
911 bool numerrs = false;
912
913 if (tokenresponse)
914 *tokenresponse = NULL;
915
916 getline:
917 while (cmdqueue) {
918 if (!(line = netsec_readline(nsc, NULL, errstr)))
919 return NOTOK;
920 if (has_prefix(line, "* ") && *(line + 2) != '\0') {
921 if (token && tokenresponse && has_prefix(line + 2, token)) {
922 if (*tokenresponse)
923 free(*tokenresponse);
924 *tokenresponse = getcpy(line + 2);
925 }
926 } if (condok && has_prefix(line, "+")) {
927 if (status) {
928 *status = getcpy(line);
929 }
930 /*
931 * Special case; return now but don't dequeue the tag,
932 * since we will want to get final result later.
933 */
934 return OK;
935 } else {
936
937 if (has_prefix(line, cmdqueue->tag)) {
938 cmd = cmdqueue;
939 if (timestamp)
940 ts_report(&cmd->start, "Command (%s) execution time",
941 cmd->prefix);
942 cmdqueue = cmd->next;
943 free(cmd);
944 } else {
945 for (cmd = cmdqueue; cmd->next != NULL; cmd = cmd->next) {
946 if (has_prefix(line, cmd->next->tag)) {
947 struct imap_cmd *cmd2 = cmd->next;
948 cmd->next = cmd->next->next;
949 if (failerr && strncmp(line + strlen(cmd2->tag),
950 "OK ", 3) != 0) {
951 numerrs = true;
952 netsec_err(errstr, "%s", line + strlen(cmd2->tag));
953 }
954 if (timestamp)
955 ts_report(&cmd2->start, "Command (%s) execution "
956 "time", cmd2->prefix);
957 free(cmd2);
958 if (status)
959 *status = getcpy(line);
960 goto getline;
961 }
962 }
963 }
964 }
965 }
966
967 return numerrs ? NOTOK : OK;
968 }
969
970 /*
971 * Add an IMAP command to the msg queue
972 */
973
974 static void
975 add_msg(bool queue, struct imap_msg **ret_imsg, const char *fmt, ...)
976 {
977 struct imap_msg *imsg;
978 va_list ap;
979 size_t msgbufsize;
980 char *msg = NULL;
981 int rc = 63;
982
983 do {
984 msgbufsize = rc + 1;
985 msg = mh_xrealloc(msg, msgbufsize);
986 va_start(ap, fmt);
987 rc = vsnprintf(msg, msgbufsize, fmt, ap);
988 va_end(ap);
989 } while (rc >= (int) msgbufsize);
990
991 imsg = mh_xmalloc(sizeof(*imsg));
992
993 imsg->command = msg;
994 imsg->folder = NULL;
995 imsg->append = false;
996 imsg->queue = queue;
997 imsg->next = NULL;
998
999 if (msgqueue_head == NULL) {
1000 msgqueue_head = imsg;
1001 msgqueue_tail = imsg;
1002 } else {
1003 msgqueue_tail->next = imsg;
1004 msgqueue_tail = imsg;
1005 }
1006
1007 if (ret_imsg)
1008 *ret_imsg = imsg;
1009 }
1010
1011 /*
1012 * Add an APPEND command to the queue
1013 */
1014
1015 static void
1016 add_append(const char *filename, const char *folder, bool queue)
1017 {
1018 size_t filesize = rfc822size(filename);
1019 struct imap_msg *imsg;
1020
1021 add_msg(queue, &imsg, "%s", filename);
1022
1023 imsg->folder = getcpy(folder);
1024 imsg->append = true;
1025 imsg->msgsize = filesize;
1026 }
1027
1028 /*
1029 * Process a batch file, which can contain commands (and some arguments)
1030 */
1031
1032 static void
1033 batchfile(const char *filename, char *afolder, bool queue)
1034 {
1035 FILE *f;
1036 char *line = NULL;
1037 size_t linesize = 0;
1038 ssize_t rc;
1039 bool afolder_alloc = false;
1040
1041 if (!(f = fopen(filename, "r"))) {
1042 die("Unable to open batch file %s: %s", filename, strerror(errno));
1043 }
1044
1045 while ((rc = getline(&line, &linesize, f)) > 0) {
1046 line[rc - 1] = '\0';
1047 if (*line == '-') {
1048 switch (smatch (line + 1, switches)) {
1049 case QUEUESW:
1050 queue = true;
1051 continue;
1052 case NOQUEUESW:
1053 queue = false;
1054 continue;
1055 case AFOLDERSW:
1056 if (afolder_alloc)
1057 free(afolder);
1058 rc = getline(&line, &linesize, f);
1059 if (rc <= 0)
1060 die("Unable to read next line for -afolder");
1061 if (rc == 1)
1062 die("Folder name cannot be blank");
1063 line[rc - 1] = '\0';
1064 afolder = getcpy(line);
1065 afolder_alloc = true;
1066 continue;
1067
1068 case APPENDSW:
1069 rc = getline(&line, &linesize, f);
1070 if (rc <= 0)
1071 die("Unable to read filename for -append");
1072 if (rc == 1)
1073 die("Filename for -append cannot be blank");
1074 line[rc - 1] = '\0';
1075 add_append(line, afolder, queue);
1076 continue;
1077
1078 case AMBIGSW:
1079 ambigsw (line, switches);
1080 done (1);
1081 case UNKWNSW:
1082 die("%s unknown", line);
1083 default:
1084 die("Switch %s not supported in batch mode", line);
1085 }
1086 } else if (*line == '+') {
1087 if (*(line + 1) == '\0')
1088 die("Invalid null folder name");
1089 add_msg(false, NULL, "SELECT \"%s\"", line + 1);
1090 } else {
1091 if (*line == '\0')
1092 continue; /* Ignore blank line */
1093 add_msg(queue, NULL, "%s", line);
1094 }
1095 }
1096
1097 if (!feof(f)) {
1098 die("Read of \"%s\" failed: %s", filename, strerror(errno));
1099 }
1100
1101 fclose(f);
1102
1103 if (afolder_alloc)
1104 free(afolder);
1105
1106 free(line);
1107 }
1108
1109 /*
1110 * Negotiate TLS connection, with optional timestamp
1111 */
1112
1113 static void
1114 imap_negotiate_tls(netsec_context *nsc)
1115 {
1116 char *errstr;
1117 struct timeval tv;
1118
1119 if (timestamp)
1120 gettimeofday(&tv, NULL);
1121
1122 if (netsec_negotiate_tls(nsc, &errstr) != OK)
1123 die("%s", errstr);
1124
1125 if (timestamp)
1126 ts_report(&tv, "TLS negotation time");
1127 }
1128
1129 /*
1130 * Give a timestamp report.
1131 */
1132
1133 static void
1134 ts_report(struct timeval *tv, const char *fmt, ...)
1135 {
1136 struct timeval now;
1137 double delta;
1138 va_list ap;
1139
1140 gettimeofday(&now, NULL);
1141
1142 delta = ((double) now.tv_sec) - ((double) tv->tv_sec) +
1143 (now.tv_usec / 1E6 - tv->tv_usec / 1E6);
1144
1145 va_start(ap, fmt);
1146 vfprintf(stdout, fmt, ap);
1147 va_end(ap);
1148
1149 printf(": %f sec\n", delta);
1150 }
1151
1152 /*
1153 * Calculate the RFC 822 size of file.
1154 */
1155
1156 static size_t
1157 rfc822size(const char *filename)
1158 {
1159 FILE *f;
1160 size_t total = 0, linecap = 0;
1161 ssize_t rc;
1162 char *line = NULL;
1163
1164 if (! (f = fopen(filename, "r")))
1165 die("Unable to open %s: %s", filename, strerror(errno));
1166
1167 while ((rc = getline(&line, &linecap, f)) > 0) {
1168 total += rc;
1169 if (line[rc - 1] == '\n' && (rc == 1 || line[rc - 2] != '\r'))
1170 total++;
1171 if (line[rc - 1] != '\n')
1172 total += 2;
1173 }
1174
1175 free(line);
1176
1177 if (! feof(f))
1178 die("Error while reading %s: %s", filename, strerror(errno));
1179
1180 fclose(f);
1181
1182 return total;
1183 }