2 * git-imap-send - drops patches into an imap Drafts folder
3 * derived from isync/mbsync - mailbox synchronizer
5 * Copyright (C) 2000-2002 Michael R. Elkins <me@mutt.org>
6 * Copyright (C) 2002-2004 Oswald Buddenhagen <ossi@users.sf.net>
7 * Copyright (C) 2004 Theodore Y. Ts'o <tytso@mit.edu>
8 * Copyright (C) 2006 Mike McCormack
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation; either version 2 of the License, or
13 * (at your option) any later version.
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
20 * You should have received a copy of the GNU General Public License
21 * along with this program; if not, write to the Free Software
22 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
26 #include "credential.h"
28 #include "run-command.h"
33 static const char imap_send_usage
[] = "git imap-send < <mbox>";
37 #define DRV_MSG_BAD -1
38 #define DRV_BOX_BAD -2
39 #define DRV_STORE_BAD -3
41 static int Verbose
, Quiet
;
43 __attribute__((format (printf
, 1, 2)))
44 static void imap_info(const char *, ...);
45 __attribute__((format (printf
, 1, 2)))
46 static void imap_warn(const char *, ...);
48 static char *next_arg(char **);
50 __attribute__((format (printf
, 3, 4)))
51 static int nfsnprintf(char *buf
, int blen
, const char *fmt
, ...);
53 static int nfvasprintf(char **strp
, const char *fmt
, va_list ap
)
58 len
= vsnprintf(tmp
, sizeof(tmp
), fmt
, ap
);
60 die("Fatal: Out of memory");
61 if (len
>= sizeof(tmp
))
62 die("imap command overflow!");
63 *strp
= xmemdupz(tmp
, len
);
67 struct imap_server_conf
{
80 static struct imap_server_conf server
= {
90 NULL
, /* auth_method */
99 struct imap_socket sock
;
108 int uidnext
; /* from SELECT responses */
109 unsigned caps
, rcaps
; /* CAPABILITY results */
111 int nexttag
, num_in_progress
, literal_pending
;
112 struct imap_cmd
*in_progress
, **in_progress_append
;
113 struct imap_buffer buf
; /* this is BIG, so put it last */
117 /* currently open mailbox */
118 const char *name
; /* foreign! maybe preset? */
125 int (*cont
)(struct imap_store
*ctx
, struct imap_cmd
*cmd
, const char *prompt
);
126 void (*done
)(struct imap_store
*ctx
, struct imap_cmd
*cmd
, int response
);
131 unsigned create
:1, trycreate
:1;
135 struct imap_cmd
*next
;
136 struct imap_cmd_cb cb
;
141 #define CAP(cap) (imap->caps & (1 << (cap)))
152 static const char *cap_list
[] = {
165 static int get_cmd_result(struct imap_store
*ctx
, struct imap_cmd
*tcmd
);
169 static void ssl_socket_perror(const char *func
)
171 fprintf(stderr
, "%s: %s\n", func
, ERR_error_string(ERR_get_error(), NULL
));
175 static void socket_perror(const char *func
, struct imap_socket
*sock
, int ret
)
179 int sslerr
= SSL_get_error(sock
->ssl
, ret
);
183 case SSL_ERROR_SYSCALL
:
184 perror("SSL_connect");
187 ssl_socket_perror("SSL_connect");
196 fprintf(stderr
, "%s: unexpected EOF\n", func
);
201 static int ssl_socket_connect(struct imap_socket
*sock
, int use_tls_only
, int verify
)
203 fprintf(stderr
, "SSL requested but SSL support not compiled in\n");
209 static int host_matches(const char *host
, const char *pattern
)
211 if (pattern
[0] == '*' && pattern
[1] == '.') {
213 if (!(host
= strchr(host
, '.')))
218 return *host
&& *pattern
&& !strcasecmp(host
, pattern
);
221 static int verify_hostname(X509
*cert
, const char *hostname
)
227 STACK_OF(GENERAL_NAME
) *subj_alt_names
;
229 /* try the DNS subjectAltNames */
231 if ((subj_alt_names
= X509_get_ext_d2i(cert
, NID_subject_alt_name
, NULL
, NULL
))) {
232 int num_subj_alt_names
= sk_GENERAL_NAME_num(subj_alt_names
);
233 for (i
= 0; !found
&& i
< num_subj_alt_names
; i
++) {
234 GENERAL_NAME
*subj_alt_name
= sk_GENERAL_NAME_value(subj_alt_names
, i
);
235 if (subj_alt_name
->type
== GEN_DNS
&&
236 strlen((const char *)subj_alt_name
->d
.ia5
->data
) == (size_t)subj_alt_name
->d
.ia5
->length
&&
237 host_matches(hostname
, (const char *)(subj_alt_name
->d
.ia5
->data
)))
240 sk_GENERAL_NAME_pop_free(subj_alt_names
, GENERAL_NAME_free
);
245 /* try the common name */
246 if (!(subj
= X509_get_subject_name(cert
)))
247 return error("cannot get certificate subject");
248 if ((len
= X509_NAME_get_text_by_NID(subj
, NID_commonName
, cname
, sizeof(cname
))) < 0)
249 return error("cannot get certificate common name");
250 if (strlen(cname
) == (size_t)len
&& host_matches(hostname
, cname
))
252 return error("certificate owner '%s' does not match hostname '%s'",
256 static int ssl_socket_connect(struct imap_socket
*sock
, int use_tls_only
, int verify
)
258 #if (OPENSSL_VERSION_NUMBER >= 0x10000000L)
259 const SSL_METHOD
*meth
;
268 SSL_load_error_strings();
271 meth
= TLSv1_method();
273 meth
= SSLv23_method();
276 ssl_socket_perror("SSLv23_method");
280 ctx
= SSL_CTX_new(meth
);
283 SSL_CTX_set_verify(ctx
, SSL_VERIFY_PEER
, NULL
);
285 if (!SSL_CTX_set_default_verify_paths(ctx
)) {
286 ssl_socket_perror("SSL_CTX_set_default_verify_paths");
289 sock
->ssl
= SSL_new(ctx
);
291 ssl_socket_perror("SSL_new");
294 if (!SSL_set_rfd(sock
->ssl
, sock
->fd
[0])) {
295 ssl_socket_perror("SSL_set_rfd");
298 if (!SSL_set_wfd(sock
->ssl
, sock
->fd
[1])) {
299 ssl_socket_perror("SSL_set_wfd");
303 #ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
306 * OpenSSL does not document this function, but the implementation
307 * returns 1 on success, 0 on failure after calling SSLerr().
309 ret
= SSL_set_tlsext_host_name(sock
->ssl
, server
.host
);
311 warning("SSL_set_tlsext_host_name(%s) failed.", server
.host
);
314 ret
= SSL_connect(sock
->ssl
);
316 socket_perror("SSL_connect", sock
, ret
);
321 /* make sure the hostname matches that of the certificate */
322 cert
= SSL_get_peer_certificate(sock
->ssl
);
324 return error("unable to get peer certificate.");
325 if (verify_hostname(cert
, server
.host
) < 0)
333 static int socket_read(struct imap_socket
*sock
, char *buf
, int len
)
338 n
= SSL_read(sock
->ssl
, buf
, len
);
341 n
= xread(sock
->fd
[0], buf
, len
);
343 socket_perror("read", sock
, n
);
346 sock
->fd
[0] = sock
->fd
[1] = -1;
351 static int socket_write(struct imap_socket
*sock
, const char *buf
, int len
)
356 n
= SSL_write(sock
->ssl
, buf
, len
);
359 n
= write_in_full(sock
->fd
[1], buf
, len
);
361 socket_perror("write", sock
, n
);
364 sock
->fd
[0] = sock
->fd
[1] = -1;
369 static void socket_shutdown(struct imap_socket
*sock
)
373 SSL_shutdown(sock
->ssl
);
381 /* simple line buffering */
382 static int buffer_gets(struct imap_buffer
*b
, char **s
)
385 int start
= b
->offset
;
390 /* make sure we have enough data to read the \r\n sequence */
391 if (b
->offset
+ 1 >= b
->bytes
) {
393 /* shift down used bytes */
396 assert(start
<= b
->bytes
);
397 n
= b
->bytes
- start
;
400 memmove(b
->buf
, b
->buf
+ start
, n
);
406 n
= socket_read(&b
->sock
, b
->buf
+ b
->bytes
,
407 sizeof(b
->buf
) - b
->bytes
);
415 if (b
->buf
[b
->offset
] == '\r') {
416 assert(b
->offset
+ 1 < b
->bytes
);
417 if (b
->buf
[b
->offset
+ 1] == '\n') {
418 b
->buf
[b
->offset
] = 0; /* terminate the string */
419 b
->offset
+= 2; /* next line */
431 static void imap_info(const char *msg
, ...)
443 static void imap_warn(const char *msg
, ...)
449 vfprintf(stderr
, msg
, va
);
454 static char *next_arg(char **s
)
460 while (isspace((unsigned char) **s
))
469 *s
= strchr(*s
, '"');
472 while (**s
&& !isspace((unsigned char) **s
))
484 static int nfsnprintf(char *buf
, int blen
, const char *fmt
, ...)
490 if (blen
<= 0 || (unsigned)(ret
= vsnprintf(buf
, blen
, fmt
, va
)) >= (unsigned)blen
)
491 die("Fatal: buffer too small. Please report a bug.");
496 static struct imap_cmd
*v_issue_imap_cmd(struct imap_store
*ctx
,
497 struct imap_cmd_cb
*cb
,
498 const char *fmt
, va_list ap
)
500 struct imap
*imap
= ctx
->imap
;
501 struct imap_cmd
*cmd
;
505 cmd
= xmalloc(sizeof(struct imap_cmd
));
506 nfvasprintf(&cmd
->cmd
, fmt
, ap
);
507 cmd
->tag
= ++imap
->nexttag
;
512 memset(&cmd
->cb
, 0, sizeof(cmd
->cb
));
514 while (imap
->literal_pending
)
515 get_cmd_result(ctx
, NULL
);
518 bufl
= nfsnprintf(buf
, sizeof(buf
), "%d %s\r\n", cmd
->tag
, cmd
->cmd
);
520 bufl
= nfsnprintf(buf
, sizeof(buf
), "%d %s{%d%s}\r\n",
521 cmd
->tag
, cmd
->cmd
, cmd
->cb
.dlen
,
522 CAP(LITERALPLUS
) ? "+" : "");
525 if (imap
->num_in_progress
)
526 printf("(%d in progress) ", imap
->num_in_progress
);
527 if (memcmp(cmd
->cmd
, "LOGIN", 5))
528 printf(">>> %s", buf
);
530 printf(">>> %d LOGIN <user> <pass>\n", cmd
->tag
);
532 if (socket_write(&imap
->buf
.sock
, buf
, bufl
) != bufl
) {
540 if (CAP(LITERALPLUS
)) {
541 n
= socket_write(&imap
->buf
.sock
, cmd
->cb
.data
, cmd
->cb
.dlen
);
543 if (n
!= cmd
->cb
.dlen
||
544 socket_write(&imap
->buf
.sock
, "\r\n", 2) != 2) {
551 imap
->literal_pending
= 1;
552 } else if (cmd
->cb
.cont
)
553 imap
->literal_pending
= 1;
555 *imap
->in_progress_append
= cmd
;
556 imap
->in_progress_append
= &cmd
->next
;
557 imap
->num_in_progress
++;
561 __attribute__((format (printf
, 3, 4)))
562 static struct imap_cmd
*issue_imap_cmd(struct imap_store
*ctx
,
563 struct imap_cmd_cb
*cb
,
564 const char *fmt
, ...)
566 struct imap_cmd
*ret
;
570 ret
= v_issue_imap_cmd(ctx
, cb
, fmt
, ap
);
575 __attribute__((format (printf
, 3, 4)))
576 static int imap_exec(struct imap_store
*ctx
, struct imap_cmd_cb
*cb
,
577 const char *fmt
, ...)
580 struct imap_cmd
*cmdp
;
583 cmdp
= v_issue_imap_cmd(ctx
, cb
, fmt
, ap
);
588 return get_cmd_result(ctx
, cmdp
);
591 __attribute__((format (printf
, 3, 4)))
592 static int imap_exec_m(struct imap_store
*ctx
, struct imap_cmd_cb
*cb
,
593 const char *fmt
, ...)
596 struct imap_cmd
*cmdp
;
599 cmdp
= v_issue_imap_cmd(ctx
, cb
, fmt
, ap
);
602 return DRV_STORE_BAD
;
604 switch (get_cmd_result(ctx
, cmdp
)) {
605 case RESP_BAD
: return DRV_STORE_BAD
;
606 case RESP_NO
: return DRV_MSG_BAD
;
607 default: return DRV_OK
;
611 static int skip_imap_list_l(char **sp
, int level
)
616 while (isspace((unsigned char)*s
))
618 if (level
&& *s
== ')') {
625 if (skip_imap_list_l(&s
, level
+ 1))
627 } else if (*s
== '"') {
630 for (; *s
!= '"'; s
++)
636 for (; *s
&& !isspace((unsigned char)*s
); s
++)
637 if (level
&& *s
== ')')
653 static void skip_list(char **sp
)
655 skip_imap_list_l(sp
, 0);
658 static void parse_capability(struct imap
*imap
, char *cmd
)
663 imap
->caps
= 0x80000000;
664 while ((arg
= next_arg(&cmd
)))
665 for (i
= 0; i
< ARRAY_SIZE(cap_list
); i
++)
666 if (!strcmp(cap_list
[i
], arg
))
667 imap
->caps
|= 1 << i
;
668 imap
->rcaps
= imap
->caps
;
671 static int parse_response_code(struct imap_store
*ctx
, struct imap_cmd_cb
*cb
,
674 struct imap
*imap
= ctx
->imap
;
678 return RESP_OK
; /* no response code */
680 if (!(p
= strchr(s
, ']'))) {
681 fprintf(stderr
, "IMAP error: malformed response code\n");
686 if (!strcmp("UIDVALIDITY", arg
)) {
687 if (!(arg
= next_arg(&s
)) || !(ctx
->uidvalidity
= atoi(arg
))) {
688 fprintf(stderr
, "IMAP error: malformed UIDVALIDITY status\n");
691 } else if (!strcmp("UIDNEXT", arg
)) {
692 if (!(arg
= next_arg(&s
)) || !(imap
->uidnext
= atoi(arg
))) {
693 fprintf(stderr
, "IMAP error: malformed NEXTUID status\n");
696 } else if (!strcmp("CAPABILITY", arg
)) {
697 parse_capability(imap
, s
);
698 } else if (!strcmp("ALERT", arg
)) {
699 /* RFC2060 says that these messages MUST be displayed
702 for (; isspace((unsigned char)*p
); p
++);
703 fprintf(stderr
, "*** IMAP ALERT *** %s\n", p
);
704 } else if (cb
&& cb
->ctx
&& !strcmp("APPENDUID", arg
)) {
705 if (!(arg
= next_arg(&s
)) || !(ctx
->uidvalidity
= atoi(arg
)) ||
706 !(arg
= next_arg(&s
)) || !(*(int *)cb
->ctx
= atoi(arg
))) {
707 fprintf(stderr
, "IMAP error: malformed APPENDUID status\n");
714 static int get_cmd_result(struct imap_store
*ctx
, struct imap_cmd
*tcmd
)
716 struct imap
*imap
= ctx
->imap
;
717 struct imap_cmd
*cmdp
, **pcmdp
, *ncmdp
;
718 char *cmd
, *arg
, *arg1
, *p
;
719 int n
, resp
, resp2
, tag
;
722 if (buffer_gets(&imap
->buf
, &cmd
))
725 arg
= next_arg(&cmd
);
727 arg
= next_arg(&cmd
);
729 fprintf(stderr
, "IMAP error: unable to parse untagged response\n");
733 if (!strcmp("NAMESPACE", arg
)) {
734 /* rfc2342 NAMESPACE response. */
735 skip_list(&cmd
); /* Personal mailboxes */
736 skip_list(&cmd
); /* Others' mailboxes */
737 skip_list(&cmd
); /* Shared mailboxes */
738 } else if (!strcmp("OK", arg
) || !strcmp("BAD", arg
) ||
739 !strcmp("NO", arg
) || !strcmp("BYE", arg
)) {
740 if ((resp
= parse_response_code(ctx
, NULL
, cmd
)) != RESP_OK
)
742 } else if (!strcmp("CAPABILITY", arg
)) {
743 parse_capability(imap
, cmd
);
744 } else if ((arg1
= next_arg(&cmd
))) {
746 * Unhandled response-data with at least two words.
749 * NEEDSWORK: Previously this case handled '<num> EXISTS'
750 * and '<num> RECENT' but as a probably-unintended side
751 * effect it ignores other unrecognized two-word
752 * responses. imap-send doesn't ever try to read
753 * messages or mailboxes these days, so consider
754 * eliminating this case.
757 fprintf(stderr
, "IMAP error: unable to parse untagged response\n");
760 } else if (!imap
->in_progress
) {
761 fprintf(stderr
, "IMAP error: unexpected reply: %s %s\n", arg
, cmd
? cmd
: "");
763 } else if (*arg
== '+') {
764 /* This can happen only with the last command underway, as
765 it enforces a round-trip. */
766 cmdp
= (struct imap_cmd
*)((char *)imap
->in_progress_append
-
767 offsetof(struct imap_cmd
, next
));
769 n
= socket_write(&imap
->buf
.sock
, cmdp
->cb
.data
, cmdp
->cb
.dlen
);
771 cmdp
->cb
.data
= NULL
;
772 if (n
!= (int)cmdp
->cb
.dlen
)
774 } else if (cmdp
->cb
.cont
) {
775 if (cmdp
->cb
.cont(ctx
, cmdp
, cmd
))
778 fprintf(stderr
, "IMAP error: unexpected command continuation request\n");
781 if (socket_write(&imap
->buf
.sock
, "\r\n", 2) != 2)
784 imap
->literal_pending
= 0;
789 for (pcmdp
= &imap
->in_progress
; (cmdp
= *pcmdp
); pcmdp
= &cmdp
->next
)
790 if (cmdp
->tag
== tag
)
792 fprintf(stderr
, "IMAP error: unexpected tag %s\n", arg
);
795 if (!(*pcmdp
= cmdp
->next
))
796 imap
->in_progress_append
= pcmdp
;
797 imap
->num_in_progress
--;
798 if (cmdp
->cb
.cont
|| cmdp
->cb
.data
)
799 imap
->literal_pending
= 0;
800 arg
= next_arg(&cmd
);
801 if (!strcmp("OK", arg
))
804 if (!strcmp("NO", arg
)) {
805 if (cmdp
->cb
.create
&& cmd
&& (cmdp
->cb
.trycreate
|| !memcmp(cmd
, "[TRYCREATE]", 11))) { /* SELECT, APPEND or UID COPY */
806 p
= strchr(cmdp
->cmd
, '"');
807 if (!issue_imap_cmd(ctx
, NULL
, "CREATE \"%.*s\"", (int)(strchr(p
+ 1, '"') - p
+ 1), p
)) {
811 /* not waiting here violates the spec, but a server that does not
812 grok this nonetheless violates it too. */
814 if (!(ncmdp
= issue_imap_cmd(ctx
, &cmdp
->cb
, "%s", cmdp
->cmd
))) {
821 return 0; /* ignored */
827 } else /*if (!strcmp("BAD", arg))*/
829 fprintf(stderr
, "IMAP command '%s' returned response (%s) - %s\n",
830 memcmp(cmdp
->cmd
, "LOGIN", 5) ?
831 cmdp
->cmd
: "LOGIN <user> <pass>",
832 arg
, cmd
? cmd
: "");
834 if ((resp2
= parse_response_code(ctx
, &cmdp
->cb
, cmd
)) > resp
)
838 cmdp
->cb
.done(ctx
, cmdp
, resp
);
842 if (!tcmd
|| tcmd
== cmdp
)
849 static void imap_close_server(struct imap_store
*ictx
)
851 struct imap
*imap
= ictx
->imap
;
853 if (imap
->buf
.sock
.fd
[0] != -1) {
854 imap_exec(ictx
, NULL
, "LOGOUT");
855 socket_shutdown(&imap
->buf
.sock
);
860 static void imap_close_store(struct imap_store
*ctx
)
862 imap_close_server(ctx
);
869 * hexchar() and cram() functions are based on the code from the isync
870 * project (http://isync.sf.net/).
872 static char hexchar(unsigned int b
)
874 return b
< 10 ? '0' + b
: 'a' + (b
- 10);
877 #define ENCODED_SIZE(n) (4*((n+2)/3))
878 static char *cram(const char *challenge_64
, const char *user
, const char *pass
)
880 int i
, resp_len
, encoded_len
, decoded_len
;
882 unsigned char hash
[16];
884 char *response
, *response_64
, *challenge
;
887 * length of challenge_64 (i.e. base-64 encoded string) is a good
888 * enough upper bound for challenge (decoded result).
890 encoded_len
= strlen(challenge_64
);
891 challenge
= xmalloc(encoded_len
);
892 decoded_len
= EVP_DecodeBlock((unsigned char *)challenge
,
893 (unsigned char *)challenge_64
, encoded_len
);
895 die("invalid challenge %s", challenge_64
);
896 HMAC_Init(&hmac
, (unsigned char *)pass
, strlen(pass
), EVP_md5());
897 HMAC_Update(&hmac
, (unsigned char *)challenge
, decoded_len
);
898 HMAC_Final(&hmac
, hash
, NULL
);
899 HMAC_CTX_cleanup(&hmac
);
902 for (i
= 0; i
< 16; i
++) {
903 hex
[2 * i
] = hexchar((hash
[i
] >> 4) & 0xf);
904 hex
[2 * i
+ 1] = hexchar(hash
[i
] & 0xf);
907 /* response: "<user> <digest in hex>" */
908 resp_len
= strlen(user
) + 1 + strlen(hex
) + 1;
909 response
= xmalloc(resp_len
);
910 sprintf(response
, "%s %s", user
, hex
);
912 response_64
= xmalloc(ENCODED_SIZE(resp_len
) + 1);
913 encoded_len
= EVP_EncodeBlock((unsigned char *)response_64
,
914 (unsigned char *)response
, resp_len
);
916 die("EVP_EncodeBlock error");
917 response_64
[encoded_len
] = '\0';
918 return (char *)response_64
;
923 static char *cram(const char *challenge_64
, const char *user
, const char *pass
)
925 die("If you want to use CRAM-MD5 authenticate method, "
926 "you have to build git-imap-send with OpenSSL library.");
931 static int auth_cram_md5(struct imap_store
*ctx
, struct imap_cmd
*cmd
, const char *prompt
)
936 response
= cram(prompt
, server
.user
, server
.pass
);
938 ret
= socket_write(&ctx
->imap
->buf
.sock
, response
, strlen(response
));
939 if (ret
!= strlen(response
))
940 return error("IMAP error: sending response failed");
947 static struct imap_store
*imap_open_store(struct imap_server_conf
*srvc
)
949 struct credential cred
= CREDENTIAL_INIT
;
950 struct imap_store
*ctx
;
955 ctx
= xcalloc(1, sizeof(*ctx
));
957 ctx
->imap
= imap
= xcalloc(sizeof(*imap
), 1);
958 imap
->buf
.sock
.fd
[0] = imap
->buf
.sock
.fd
[1] = -1;
959 imap
->in_progress_append
= &imap
->in_progress
;
961 /* open connection to IMAP server */
964 const char *argv
[] = { srvc
->tunnel
, NULL
};
965 struct child_process tunnel
= CHILD_PROCESS_INIT
;
967 imap_info("Starting tunnel '%s'... ", srvc
->tunnel
);
970 tunnel
.use_shell
= 1;
973 if (start_command(&tunnel
))
974 die("cannot start proxy %s", argv
[0]);
976 imap
->buf
.sock
.fd
[0] = tunnel
.out
;
977 imap
->buf
.sock
.fd
[1] = tunnel
.in
;
982 struct addrinfo hints
, *ai0
, *ai
;
986 snprintf(portstr
, sizeof(portstr
), "%d", srvc
->port
);
988 memset(&hints
, 0, sizeof(hints
));
989 hints
.ai_socktype
= SOCK_STREAM
;
990 hints
.ai_protocol
= IPPROTO_TCP
;
992 imap_info("Resolving %s... ", srvc
->host
);
993 gai
= getaddrinfo(srvc
->host
, portstr
, &hints
, &ai
);
995 fprintf(stderr
, "getaddrinfo: %s\n", gai_strerror(gai
));
1000 for (ai0
= ai
; ai
; ai
= ai
->ai_next
) {
1001 char addr
[NI_MAXHOST
];
1003 s
= socket(ai
->ai_family
, ai
->ai_socktype
,
1008 getnameinfo(ai
->ai_addr
, ai
->ai_addrlen
, addr
,
1009 sizeof(addr
), NULL
, 0, NI_NUMERICHOST
);
1010 imap_info("Connecting to [%s]:%s... ", addr
, portstr
);
1012 if (connect(s
, ai
->ai_addr
, ai
->ai_addrlen
) < 0) {
1024 struct sockaddr_in addr
;
1026 memset(&addr
, 0, sizeof(addr
));
1027 addr
.sin_port
= htons(srvc
->port
);
1028 addr
.sin_family
= AF_INET
;
1030 imap_info("Resolving %s... ", srvc
->host
);
1031 he
= gethostbyname(srvc
->host
);
1033 perror("gethostbyname");
1038 addr
.sin_addr
.s_addr
= *((int *) he
->h_addr_list
[0]);
1040 s
= socket(PF_INET
, SOCK_STREAM
, 0);
1042 imap_info("Connecting to %s:%hu... ", inet_ntoa(addr
.sin_addr
), ntohs(addr
.sin_port
));
1043 if (connect(s
, (struct sockaddr
*)&addr
, sizeof(addr
))) {
1050 fputs("Error: unable to connect to server.\n", stderr
);
1054 imap
->buf
.sock
.fd
[0] = s
;
1055 imap
->buf
.sock
.fd
[1] = dup(s
);
1057 if (srvc
->use_ssl
&&
1058 ssl_socket_connect(&imap
->buf
.sock
, 0, srvc
->ssl_verify
)) {
1065 /* read the greeting string */
1066 if (buffer_gets(&imap
->buf
, &rsp
)) {
1067 fprintf(stderr
, "IMAP error: no greeting response\n");
1070 arg
= next_arg(&rsp
);
1071 if (!arg
|| *arg
!= '*' || (arg
= next_arg(&rsp
)) == NULL
) {
1072 fprintf(stderr
, "IMAP error: invalid greeting response\n");
1076 if (!strcmp("PREAUTH", arg
))
1078 else if (strcmp("OK", arg
) != 0) {
1079 fprintf(stderr
, "IMAP error: unknown greeting response\n");
1082 parse_response_code(ctx
, NULL
, rsp
);
1083 if (!imap
->caps
&& imap_exec(ctx
, NULL
, "CAPABILITY") != RESP_OK
)
1088 if (!srvc
->use_ssl
&& CAP(STARTTLS
)) {
1089 if (imap_exec(ctx
, NULL
, "STARTTLS") != RESP_OK
)
1091 if (ssl_socket_connect(&imap
->buf
.sock
, 1,
1094 /* capabilities may have changed, so get the new capabilities */
1095 if (imap_exec(ctx
, NULL
, "CAPABILITY") != RESP_OK
)
1099 imap_info("Logging in...\n");
1100 if (!srvc
->user
|| !srvc
->pass
) {
1101 cred
.protocol
= xstrdup(srvc
->use_ssl
? "imaps" : "imap");
1102 cred
.host
= xstrdup(srvc
->host
);
1105 cred
.username
= xstrdup(srvc
->user
);
1107 cred
.password
= xstrdup(srvc
->pass
);
1109 credential_fill(&cred
);
1112 srvc
->user
= xstrdup(cred
.username
);
1114 srvc
->pass
= xstrdup(cred
.password
);
1118 fprintf(stderr
, "Skipping account %s@%s, server forbids LOGIN\n", srvc
->user
, srvc
->host
);
1122 if (srvc
->auth_method
) {
1123 struct imap_cmd_cb cb
;
1125 if (!strcmp(srvc
->auth_method
, "CRAM-MD5")) {
1126 if (!CAP(AUTH_CRAM_MD5
)) {
1127 fprintf(stderr
, "You specified"
1128 "CRAM-MD5 as authentication method, "
1129 "but %s doesn't support it.\n", srvc
->host
);
1134 memset(&cb
, 0, sizeof(cb
));
1135 cb
.cont
= auth_cram_md5
;
1136 if (imap_exec(ctx
, &cb
, "AUTHENTICATE CRAM-MD5") != RESP_OK
) {
1137 fprintf(stderr
, "IMAP error: AUTHENTICATE CRAM-MD5 failed\n");
1141 fprintf(stderr
, "Unknown authentication method:%s\n", srvc
->host
);
1145 if (!imap
->buf
.sock
.ssl
)
1146 imap_warn("*** IMAP Warning *** Password is being "
1147 "sent in the clear\n");
1148 if (imap_exec(ctx
, NULL
, "LOGIN \"%s\" \"%s\"", srvc
->user
, srvc
->pass
) != RESP_OK
) {
1149 fprintf(stderr
, "IMAP error: LOGIN failed\n");
1156 credential_approve(&cred
);
1157 credential_clear(&cred
);
1164 credential_reject(&cred
);
1165 credential_clear(&cred
);
1167 imap_close_store(ctx
);
1172 * Insert CR characters as necessary in *msg to ensure that every LF
1173 * character in *msg is preceded by a CR.
1175 static void lf_to_crlf(struct strbuf
*msg
)
1181 /* First pass: tally, in j, the size of the new string: */
1182 for (i
= j
= 0, lastc
= '\0'; i
< msg
->len
; i
++) {
1183 if (msg
->buf
[i
] == '\n' && lastc
!= '\r')
1184 j
++; /* a CR will need to be added here */
1185 lastc
= msg
->buf
[i
];
1189 new = xmalloc(j
+ 1);
1192 * Second pass: write the new string. Note that this loop is
1193 * otherwise identical to the first pass.
1195 for (i
= j
= 0, lastc
= '\0'; i
< msg
->len
; i
++) {
1196 if (msg
->buf
[i
] == '\n' && lastc
!= '\r')
1198 lastc
= new[j
++] = msg
->buf
[i
];
1200 strbuf_attach(msg
, new, j
, j
+ 1);
1204 * Store msg to IMAP. Also detach and free the data from msg->data,
1205 * leaving msg->data empty.
1207 static int imap_store_msg(struct imap_store
*ctx
, struct strbuf
*msg
)
1209 struct imap
*imap
= ctx
->imap
;
1210 struct imap_cmd_cb cb
;
1211 const char *prefix
, *box
;
1215 memset(&cb
, 0, sizeof(cb
));
1218 cb
.data
= strbuf_detach(msg
, NULL
);
1221 prefix
= !strcmp(box
, "INBOX") ? "" : ctx
->prefix
;
1223 ret
= imap_exec_m(ctx
, &cb
, "APPEND \"%s%s\" ", prefix
, box
);
1224 imap
->caps
= imap
->rcaps
;
1231 static void wrap_in_html(struct strbuf
*msg
)
1233 struct strbuf buf
= STRBUF_INIT
;
1234 static char *content_type
= "Content-Type: text/html;\n";
1235 static char *pre_open
= "<pre>\n";
1236 static char *pre_close
= "</pre>\n";
1237 const char *body
= strstr(msg
->buf
, "\n\n");
1240 return; /* Headers but no body; no wrapping needed */
1244 strbuf_add(&buf
, msg
->buf
, body
- msg
->buf
- 1);
1245 strbuf_addstr(&buf
, content_type
);
1246 strbuf_addch(&buf
, '\n');
1247 strbuf_addstr(&buf
, pre_open
);
1248 strbuf_addstr_xml_quoted(&buf
, body
);
1249 strbuf_addstr(&buf
, pre_close
);
1251 strbuf_release(msg
);
1255 #define CHUNKSIZE 0x1000
1257 static int read_message(FILE *f
, struct strbuf
*all_msgs
)
1260 if (strbuf_fread(all_msgs
, CHUNKSIZE
, f
) <= 0)
1264 return ferror(f
) ? -1 : 0;
1267 static int count_messages(struct strbuf
*all_msgs
)
1270 char *p
= all_msgs
->buf
;
1273 if (starts_with(p
, "From ")) {
1274 p
= strstr(p
+5, "\nFrom: ");
1276 p
= strstr(p
+7, "\nDate: ");
1278 p
= strstr(p
+7, "\nSubject: ");
1283 p
= strstr(p
+5, "\nFrom ");
1292 * Copy the next message from all_msgs, starting at offset *ofs, to
1293 * msg. Update *ofs to the start of the following message. Return
1294 * true iff a message was successfully copied.
1296 static int split_msg(struct strbuf
*all_msgs
, struct strbuf
*msg
, int *ofs
)
1301 if (*ofs
>= all_msgs
->len
)
1304 data
= &all_msgs
->buf
[*ofs
];
1305 len
= all_msgs
->len
- *ofs
;
1307 if (len
< 5 || !starts_with(data
, "From "))
1310 p
= strchr(data
, '\n');
1318 p
= strstr(data
, "\nFrom ");
1322 strbuf_add(msg
, data
, len
);
1327 static char *imap_folder
;
1329 static int git_imap_config(const char *key
, const char *val
, void *cb
)
1331 if (!skip_prefix(key
, "imap.", &key
))
1334 /* check booleans first, and barf on others */
1335 if (!strcmp("sslverify", key
))
1336 server
.ssl_verify
= git_config_bool(key
, val
);
1337 else if (!strcmp("preformattedhtml", key
))
1338 server
.use_html
= git_config_bool(key
, val
);
1340 return config_error_nonbool(key
);
1342 if (!strcmp("folder", key
)) {
1343 imap_folder
= xstrdup(val
);
1344 } else if (!strcmp("host", key
)) {
1345 if (starts_with(val
, "imap:"))
1347 else if (starts_with(val
, "imaps:")) {
1351 if (starts_with(val
, "//"))
1353 server
.host
= xstrdup(val
);
1354 } else if (!strcmp("user", key
))
1355 server
.user
= xstrdup(val
);
1356 else if (!strcmp("pass", key
))
1357 server
.pass
= xstrdup(val
);
1358 else if (!strcmp("port", key
))
1359 server
.port
= git_config_int(key
, val
);
1360 else if (!strcmp("tunnel", key
))
1361 server
.tunnel
= xstrdup(val
);
1362 else if (!strcmp("authmethod", key
))
1363 server
.auth_method
= xstrdup(val
);
1368 int main(int argc
, char **argv
)
1370 struct strbuf all_msgs
= STRBUF_INIT
;
1371 struct strbuf msg
= STRBUF_INIT
;
1372 struct imap_store
*ctx
= NULL
;
1378 git_extract_argv0_path(argv
[0]);
1380 git_setup_gettext();
1383 usage(imap_send_usage
);
1385 setup_git_directory_gently(&nongit_ok
);
1386 git_config(git_imap_config
, NULL
);
1389 server
.port
= server
.use_ssl
? 993 : 143;
1392 fprintf(stderr
, "no imap store specified\n");
1396 if (!server
.tunnel
) {
1397 fprintf(stderr
, "no imap host specified\n");
1400 server
.host
= "tunnel";
1403 /* read the messages */
1404 if (read_message(stdin
, &all_msgs
)) {
1405 fprintf(stderr
, "error reading input\n");
1409 if (all_msgs
.len
== 0) {
1410 fprintf(stderr
, "nothing to send\n");
1414 total
= count_messages(&all_msgs
);
1416 fprintf(stderr
, "no messages to send\n");
1420 /* write it to the imap server */
1421 ctx
= imap_open_store(&server
);
1423 fprintf(stderr
, "failed to open store\n");
1427 fprintf(stderr
, "sending %d message%s\n", total
, (total
!= 1) ? "s" : "");
1428 ctx
->name
= imap_folder
;
1430 unsigned percent
= n
* 100 / total
;
1432 fprintf(stderr
, "%4u%% (%d/%d) done\r", percent
, n
, total
);
1433 if (!split_msg(&all_msgs
, &msg
, &ofs
))
1435 if (server
.use_html
)
1437 r
= imap_store_msg(ctx
, &msg
);
1442 fprintf(stderr
, "\n");
1444 imap_close_store(ctx
);