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, see <https://www.gnu.org/licenses/>.
24 #include "git-compat-util.h"
26 #include "credential.h"
28 #include "run-command.h"
29 #include "parse-options.h"
32 #if defined(NO_OPENSSL) && !defined(HAVE_OPENSSL_CSPRNG)
35 #ifdef USE_CURL_FOR_IMAP_SEND
39 #if defined(USE_CURL_FOR_IMAP_SEND)
40 /* Always default to curl if it's available. */
41 #define USE_CURL_DEFAULT 1
43 /* We don't have curl, so continue to use the historical implementation */
44 #define USE_CURL_DEFAULT 0
48 static int use_curl
= USE_CURL_DEFAULT
;
50 static const char * const imap_send_usage
[] = { "git imap-send [-v] [-q] [--[no-]curl] < <mbox>", NULL
};
52 static struct option imap_send_options
[] = {
53 OPT__VERBOSITY(&verbosity
),
54 OPT_BOOL(0, "curl", &use_curl
, "use libcurl to communicate with the IMAP server"),
60 #define DRV_MSG_BAD -1
61 #define DRV_BOX_BAD -2
62 #define DRV_STORE_BAD -3
64 __attribute__((format (printf
, 1, 2)))
65 static void imap_info(const char *, ...);
66 __attribute__((format (printf
, 1, 2)))
67 static void imap_warn(const char *, ...);
69 static char *next_arg(char **);
71 struct imap_server_conf
{
90 struct imap_socket sock
;
99 int uidnext
; /* from SELECT responses */
100 unsigned caps
, rcaps
; /* CAPABILITY results */
102 int nexttag
, num_in_progress
, literal_pending
;
103 struct imap_cmd
*in_progress
, **in_progress_append
;
104 struct imap_buffer buf
; /* this is BIG, so put it last */
108 const struct imap_server_conf
*cfg
;
109 /* currently open mailbox */
110 const char *name
; /* foreign! maybe preset? */
117 int (*cont
)(struct imap_store
*ctx
, const char *prompt
);
124 struct imap_cmd
*next
;
125 struct imap_cmd_cb cb
;
130 #define CAP(cap) (imap->caps & (1 << (cap)))
141 static const char *cap_list
[] = {
154 static int get_cmd_result(struct imap_store
*ctx
, struct imap_cmd
*tcmd
);
158 static void ssl_socket_perror(const char *func
)
160 fprintf(stderr
, "%s: %s\n", func
, ERR_error_string(ERR_get_error(), NULL
));
164 static void socket_perror(const char *func
, struct imap_socket
*sock
, int ret
)
168 int sslerr
= SSL_get_error(sock
->ssl
, ret
);
172 case SSL_ERROR_SYSCALL
:
173 perror("SSL_connect");
176 ssl_socket_perror("SSL_connect");
185 fprintf(stderr
, "%s: unexpected EOF\n", func
);
187 /* mark as used to appease -Wunused-parameter with NO_OPENSSL */
192 static int ssl_socket_connect(struct imap_socket
*sock UNUSED
,
193 const struct imap_server_conf
*cfg
,
194 int use_tls_only UNUSED
)
196 fprintf(stderr
, "SSL requested but SSL support not compiled in\n");
202 static int host_matches(const char *host
, const char *pattern
)
204 if (pattern
[0] == '*' && pattern
[1] == '.') {
206 if (!(host
= strchr(host
, '.')))
211 return *host
&& *pattern
&& !strcasecmp(host
, pattern
);
214 static int verify_hostname(X509
*cert
, const char *hostname
)
220 STACK_OF(GENERAL_NAME
) *subj_alt_names
;
222 /* try the DNS subjectAltNames */
224 if ((subj_alt_names
= X509_get_ext_d2i(cert
, NID_subject_alt_name
, NULL
, NULL
))) {
225 int num_subj_alt_names
= sk_GENERAL_NAME_num(subj_alt_names
);
226 for (i
= 0; !found
&& i
< num_subj_alt_names
; i
++) {
227 GENERAL_NAME
*subj_alt_name
= sk_GENERAL_NAME_value(subj_alt_names
, i
);
228 if (subj_alt_name
->type
== GEN_DNS
&&
229 strlen((const char *)subj_alt_name
->d
.ia5
->data
) == (size_t)subj_alt_name
->d
.ia5
->length
&&
230 host_matches(hostname
, (const char *)(subj_alt_name
->d
.ia5
->data
)))
233 sk_GENERAL_NAME_pop_free(subj_alt_names
, GENERAL_NAME_free
);
238 /* try the common name */
239 if (!(subj
= X509_get_subject_name(cert
)))
240 return error("cannot get certificate subject");
241 if ((len
= X509_NAME_get_text_by_NID(subj
, NID_commonName
, cname
, sizeof(cname
))) < 0)
242 return error("cannot get certificate common name");
243 if (strlen(cname
) == (size_t)len
&& host_matches(hostname
, cname
))
245 return error("certificate owner '%s' does not match hostname '%s'",
249 static int ssl_socket_connect(struct imap_socket
*sock
,
250 const struct imap_server_conf
*cfg
,
253 #if (OPENSSL_VERSION_NUMBER >= 0x10000000L)
254 const SSL_METHOD
*meth
;
263 SSL_load_error_strings();
265 meth
= SSLv23_method();
267 ssl_socket_perror("SSLv23_method");
271 ctx
= SSL_CTX_new(meth
);
273 ssl_socket_perror("SSL_CTX_new");
278 SSL_CTX_set_options(ctx
, SSL_OP_NO_SSLv2
| SSL_OP_NO_SSLv3
);
281 SSL_CTX_set_verify(ctx
, SSL_VERIFY_PEER
, NULL
);
283 if (!SSL_CTX_set_default_verify_paths(ctx
)) {
284 ssl_socket_perror("SSL_CTX_set_default_verify_paths");
287 sock
->ssl
= SSL_new(ctx
);
289 ssl_socket_perror("SSL_new");
292 if (!SSL_set_rfd(sock
->ssl
, sock
->fd
[0])) {
293 ssl_socket_perror("SSL_set_rfd");
296 if (!SSL_set_wfd(sock
->ssl
, sock
->fd
[1])) {
297 ssl_socket_perror("SSL_set_wfd");
301 #ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
304 * OpenSSL does not document this function, but the implementation
305 * returns 1 on success, 0 on failure after calling SSLerr().
307 ret
= SSL_set_tlsext_host_name(sock
->ssl
, cfg
->host
);
309 warning("SSL_set_tlsext_host_name(%s) failed.", cfg
->host
);
312 ret
= SSL_connect(sock
->ssl
);
314 socket_perror("SSL_connect", sock
, ret
);
318 if (cfg
->ssl_verify
) {
319 /* make sure the hostname matches that of the certificate */
320 cert
= SSL_get_peer_certificate(sock
->ssl
);
322 return error("unable to get peer certificate.");
323 if (verify_hostname(cert
, cfg
->host
) < 0)
331 static int socket_read(struct imap_socket
*sock
, char *buf
, int len
)
336 n
= SSL_read(sock
->ssl
, buf
, len
);
339 n
= xread(sock
->fd
[0], buf
, len
);
341 socket_perror("read", sock
, n
);
344 sock
->fd
[0] = sock
->fd
[1] = -1;
349 static int socket_write(struct imap_socket
*sock
, const char *buf
, int len
)
354 n
= SSL_write(sock
->ssl
, buf
, len
);
357 n
= write_in_full(sock
->fd
[1], buf
, len
);
359 socket_perror("write", sock
, n
);
362 sock
->fd
[0] = sock
->fd
[1] = -1;
367 static void socket_shutdown(struct imap_socket
*sock
)
371 SSL_shutdown(sock
->ssl
);
379 /* simple line buffering */
380 static int buffer_gets(struct imap_buffer
*b
, char **s
)
383 int start
= b
->offset
;
388 /* make sure we have enough data to read the \r\n sequence */
389 if (b
->offset
+ 1 >= b
->bytes
) {
391 /* shift down used bytes */
394 assert(start
<= b
->bytes
);
395 n
= b
->bytes
- start
;
398 memmove(b
->buf
, b
->buf
+ start
, n
);
404 n
= socket_read(&b
->sock
, b
->buf
+ b
->bytes
,
405 sizeof(b
->buf
) - b
->bytes
);
413 if (b
->buf
[b
->offset
] == '\r') {
414 assert(b
->offset
+ 1 < b
->bytes
);
415 if (b
->buf
[b
->offset
+ 1] == '\n') {
416 b
->buf
[b
->offset
] = 0; /* terminate the string */
417 b
->offset
+= 2; /* next line */
429 __attribute__((format (printf
, 1, 2)))
430 static void imap_info(const char *msg
, ...)
434 if (0 <= verbosity
) {
442 __attribute__((format (printf
, 1, 2)))
443 static void imap_warn(const char *msg
, ...)
447 if (-2 < verbosity
) {
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 struct imap_cmd
*issue_imap_cmd(struct imap_store
*ctx
,
485 struct imap_cmd_cb
*cb
,
486 const char *fmt
, va_list ap
)
488 struct imap
*imap
= ctx
->imap
;
489 struct imap_cmd
*cmd
;
491 struct strbuf buf
= STRBUF_INIT
;
493 cmd
= xmalloc(sizeof(struct imap_cmd
));
494 cmd
->cmd
= xstrvfmt(fmt
, ap
);
495 cmd
->tag
= ++imap
->nexttag
;
500 memset(&cmd
->cb
, 0, sizeof(cmd
->cb
));
502 while (imap
->literal_pending
)
503 get_cmd_result(ctx
, NULL
);
506 strbuf_addf(&buf
, "%d %s\r\n", cmd
->tag
, cmd
->cmd
);
508 strbuf_addf(&buf
, "%d %s{%d%s}\r\n", cmd
->tag
, cmd
->cmd
,
509 cmd
->cb
.dlen
, CAP(LITERALPLUS
) ? "+" : "");
510 if (buf
.len
> INT_MAX
)
511 die("imap command overflow!");
514 if (imap
->num_in_progress
)
515 printf("(%d in progress) ", imap
->num_in_progress
);
516 if (!starts_with(cmd
->cmd
, "LOGIN"))
517 printf(">>> %s", buf
.buf
);
519 printf(">>> %d LOGIN <user> <pass>\n", cmd
->tag
);
521 if (socket_write(&imap
->buf
.sock
, buf
.buf
, buf
.len
) != buf
.len
) {
526 strbuf_release(&buf
);
529 strbuf_release(&buf
);
531 if (CAP(LITERALPLUS
)) {
532 n
= socket_write(&imap
->buf
.sock
, cmd
->cb
.data
, cmd
->cb
.dlen
);
534 if (n
!= cmd
->cb
.dlen
||
535 socket_write(&imap
->buf
.sock
, "\r\n", 2) != 2) {
542 imap
->literal_pending
= 1;
543 } else if (cmd
->cb
.cont
)
544 imap
->literal_pending
= 1;
546 *imap
->in_progress_append
= cmd
;
547 imap
->in_progress_append
= &cmd
->next
;
548 imap
->num_in_progress
++;
552 __attribute__((format (printf
, 3, 4)))
553 static int imap_exec(struct imap_store
*ctx
, struct imap_cmd_cb
*cb
,
554 const char *fmt
, ...)
557 struct imap_cmd
*cmdp
;
560 cmdp
= issue_imap_cmd(ctx
, cb
, fmt
, ap
);
565 return get_cmd_result(ctx
, cmdp
);
568 __attribute__((format (printf
, 3, 4)))
569 static int imap_exec_m(struct imap_store
*ctx
, struct imap_cmd_cb
*cb
,
570 const char *fmt
, ...)
573 struct imap_cmd
*cmdp
;
576 cmdp
= issue_imap_cmd(ctx
, cb
, fmt
, ap
);
579 return DRV_STORE_BAD
;
581 switch (get_cmd_result(ctx
, cmdp
)) {
582 case RESP_BAD
: return DRV_STORE_BAD
;
583 case RESP_NO
: return DRV_MSG_BAD
;
584 default: return DRV_OK
;
588 static int skip_imap_list_l(char **sp
, int level
)
593 while (isspace((unsigned char)*s
))
595 if (level
&& *s
== ')') {
602 if (skip_imap_list_l(&s
, level
+ 1))
604 } else if (*s
== '"') {
607 for (; *s
!= '"'; s
++)
613 for (; *s
&& !isspace((unsigned char)*s
); s
++)
614 if (level
&& *s
== ')')
630 static void skip_list(char **sp
)
632 skip_imap_list_l(sp
, 0);
635 static void parse_capability(struct imap
*imap
, char *cmd
)
640 imap
->caps
= 0x80000000;
641 while ((arg
= next_arg(&cmd
)))
642 for (i
= 0; i
< ARRAY_SIZE(cap_list
); i
++)
643 if (!strcmp(cap_list
[i
], arg
))
644 imap
->caps
|= 1 << i
;
645 imap
->rcaps
= imap
->caps
;
648 static int parse_response_code(struct imap_store
*ctx
, struct imap_cmd_cb
*cb
,
651 struct imap
*imap
= ctx
->imap
;
655 return RESP_OK
; /* no response code */
657 if (!(p
= strchr(s
, ']'))) {
658 fprintf(stderr
, "IMAP error: malformed response code\n");
664 fprintf(stderr
, "IMAP error: empty response code\n");
667 if (!strcmp("UIDVALIDITY", arg
)) {
668 if (!(arg
= next_arg(&s
)) || !(ctx
->uidvalidity
= atoi(arg
))) {
669 fprintf(stderr
, "IMAP error: malformed UIDVALIDITY status\n");
672 } else if (!strcmp("UIDNEXT", arg
)) {
673 if (!(arg
= next_arg(&s
)) || !(imap
->uidnext
= atoi(arg
))) {
674 fprintf(stderr
, "IMAP error: malformed NEXTUID status\n");
677 } else if (!strcmp("CAPABILITY", arg
)) {
678 parse_capability(imap
, s
);
679 } else if (!strcmp("ALERT", arg
)) {
680 /* RFC2060 says that these messages MUST be displayed
683 for (; isspace((unsigned char)*p
); p
++);
684 fprintf(stderr
, "*** IMAP ALERT *** %s\n", p
);
685 } else if (cb
&& cb
->ctx
&& !strcmp("APPENDUID", arg
)) {
686 if (!(arg
= next_arg(&s
)) || !(ctx
->uidvalidity
= atoi(arg
)) ||
687 !(arg
= next_arg(&s
)) || !(*(int *)cb
->ctx
= atoi(arg
))) {
688 fprintf(stderr
, "IMAP error: malformed APPENDUID status\n");
695 static int get_cmd_result(struct imap_store
*ctx
, struct imap_cmd
*tcmd
)
697 struct imap
*imap
= ctx
->imap
;
698 struct imap_cmd
*cmdp
, **pcmdp
;
700 const char *arg
, *arg1
;
701 int n
, resp
, resp2
, tag
;
704 if (buffer_gets(&imap
->buf
, &cmd
))
707 arg
= next_arg(&cmd
);
709 fprintf(stderr
, "IMAP error: empty response\n");
713 arg
= next_arg(&cmd
);
715 fprintf(stderr
, "IMAP error: unable to parse untagged response\n");
719 if (!strcmp("NAMESPACE", arg
)) {
720 /* rfc2342 NAMESPACE response. */
721 skip_list(&cmd
); /* Personal mailboxes */
722 skip_list(&cmd
); /* Others' mailboxes */
723 skip_list(&cmd
); /* Shared mailboxes */
724 } else if (!strcmp("OK", arg
) || !strcmp("BAD", arg
) ||
725 !strcmp("NO", arg
) || !strcmp("BYE", arg
)) {
726 if ((resp
= parse_response_code(ctx
, NULL
, cmd
)) != RESP_OK
)
728 } else if (!strcmp("CAPABILITY", arg
)) {
729 parse_capability(imap
, cmd
);
730 } else if ((arg1
= next_arg(&cmd
))) {
732 * Unhandled response-data with at least two words.
735 * NEEDSWORK: Previously this case handled '<num> EXISTS'
736 * and '<num> RECENT' but as a probably-unintended side
737 * effect it ignores other unrecognized two-word
738 * responses. imap-send doesn't ever try to read
739 * messages or mailboxes these days, so consider
740 * eliminating this case.
743 fprintf(stderr
, "IMAP error: unable to parse untagged response\n");
746 } else if (!imap
->in_progress
) {
747 fprintf(stderr
, "IMAP error: unexpected reply: %s %s\n", arg
, cmd
? cmd
: "");
749 } else if (*arg
== '+') {
750 /* This can happen only with the last command underway, as
751 it enforces a round-trip. */
752 cmdp
= (struct imap_cmd
*)((char *)imap
->in_progress_append
-
753 offsetof(struct imap_cmd
, next
));
755 n
= socket_write(&imap
->buf
.sock
, cmdp
->cb
.data
, cmdp
->cb
.dlen
);
756 FREE_AND_NULL(cmdp
->cb
.data
);
757 if (n
!= (int)cmdp
->cb
.dlen
)
759 } else if (cmdp
->cb
.cont
) {
760 if (cmdp
->cb
.cont(ctx
, cmd
))
763 fprintf(stderr
, "IMAP error: unexpected command continuation request\n");
766 if (socket_write(&imap
->buf
.sock
, "\r\n", 2) != 2)
769 imap
->literal_pending
= 0;
774 for (pcmdp
= &imap
->in_progress
; (cmdp
= *pcmdp
); pcmdp
= &cmdp
->next
)
775 if (cmdp
->tag
== tag
)
777 fprintf(stderr
, "IMAP error: unexpected tag %s\n", arg
);
780 if (!(*pcmdp
= cmdp
->next
))
781 imap
->in_progress_append
= pcmdp
;
782 imap
->num_in_progress
--;
783 if (cmdp
->cb
.cont
|| cmdp
->cb
.data
)
784 imap
->literal_pending
= 0;
785 arg
= next_arg(&cmd
);
788 if (!strcmp("OK", arg
))
791 if (!strcmp("NO", arg
))
793 else /*if (!strcmp("BAD", arg))*/
795 fprintf(stderr
, "IMAP command '%s' returned response (%s) - %s\n",
796 !starts_with(cmdp
->cmd
, "LOGIN") ?
797 cmdp
->cmd
: "LOGIN <user> <pass>",
798 arg
, cmd
? cmd
: "");
800 if ((resp2
= parse_response_code(ctx
, &cmdp
->cb
, cmd
)) > resp
)
805 if (!tcmd
|| tcmd
== cmdp
)
812 static void imap_close_server(struct imap_store
*ictx
)
814 struct imap
*imap
= ictx
->imap
;
816 if (imap
->buf
.sock
.fd
[0] != -1) {
817 imap_exec(ictx
, NULL
, "LOGOUT");
818 socket_shutdown(&imap
->buf
.sock
);
823 static void imap_close_store(struct imap_store
*ctx
)
825 imap_close_server(ctx
);
832 * hexchar() and cram() functions are based on the code from the isync
833 * project (https://isync.sourceforge.io/).
835 static char hexchar(unsigned int b
)
837 return b
< 10 ? '0' + b
: 'a' + (b
- 10);
840 #define ENCODED_SIZE(n) (4 * DIV_ROUND_UP((n), 3))
841 static char *cram(const char *challenge_64
, const char *user
, const char *pass
)
843 int i
, resp_len
, encoded_len
, decoded_len
;
844 unsigned char hash
[16];
846 char *response
, *response_64
, *challenge
;
849 * length of challenge_64 (i.e. base-64 encoded string) is a good
850 * enough upper bound for challenge (decoded result).
852 encoded_len
= strlen(challenge_64
);
853 challenge
= xmalloc(encoded_len
);
854 decoded_len
= EVP_DecodeBlock((unsigned char *)challenge
,
855 (unsigned char *)challenge_64
, encoded_len
);
857 die("invalid challenge %s", challenge_64
);
858 if (!HMAC(EVP_md5(), pass
, strlen(pass
), (unsigned char *)challenge
, decoded_len
, hash
, NULL
))
862 for (i
= 0; i
< 16; i
++) {
863 hex
[2 * i
] = hexchar((hash
[i
] >> 4) & 0xf);
864 hex
[2 * i
+ 1] = hexchar(hash
[i
] & 0xf);
867 /* response: "<user> <digest in hex>" */
868 response
= xstrfmt("%s %s", user
, hex
);
869 resp_len
= strlen(response
);
871 response_64
= xmallocz(ENCODED_SIZE(resp_len
));
872 encoded_len
= EVP_EncodeBlock((unsigned char *)response_64
,
873 (unsigned char *)response
, resp_len
);
875 die("EVP_EncodeBlock error");
876 return (char *)response_64
;
881 static char *cram(const char *challenge_64 UNUSED
,
882 const char *user UNUSED
,
883 const char *pass UNUSED
)
885 die("If you want to use CRAM-MD5 authenticate method, "
886 "you have to build git-imap-send with OpenSSL library.");
891 static int auth_cram_md5(struct imap_store
*ctx
, const char *prompt
)
896 response
= cram(prompt
, ctx
->cfg
->user
, ctx
->cfg
->pass
);
898 ret
= socket_write(&ctx
->imap
->buf
.sock
, response
, strlen(response
));
899 if (ret
!= strlen(response
))
900 return error("IMAP error: sending response failed");
907 static void server_fill_credential(struct imap_server_conf
*srvc
, struct credential
*cred
)
909 if (srvc
->user
&& srvc
->pass
)
912 cred
->protocol
= xstrdup(srvc
->use_ssl
? "imaps" : "imap");
913 cred
->host
= xstrdup(srvc
->host
);
915 cred
->username
= xstrdup_or_null(srvc
->user
);
916 cred
->password
= xstrdup_or_null(srvc
->pass
);
918 credential_fill(cred
, 1);
921 srvc
->user
= xstrdup(cred
->username
);
923 srvc
->pass
= xstrdup(cred
->password
);
926 static struct imap_store
*imap_open_store(struct imap_server_conf
*srvc
, const char *folder
)
928 struct credential cred
= CREDENTIAL_INIT
;
929 struct imap_store
*ctx
;
934 CALLOC_ARRAY(ctx
, 1);
937 ctx
->imap
= CALLOC_ARRAY(imap
, 1);
938 imap
->buf
.sock
.fd
[0] = imap
->buf
.sock
.fd
[1] = -1;
939 imap
->in_progress_append
= &imap
->in_progress
;
941 /* open connection to IMAP server */
944 struct child_process tunnel
= CHILD_PROCESS_INIT
;
946 imap_info("Starting tunnel '%s'... ", srvc
->tunnel
);
948 strvec_push(&tunnel
.args
, srvc
->tunnel
);
949 tunnel
.use_shell
= 1;
952 if (start_command(&tunnel
))
953 die("cannot start proxy %s", srvc
->tunnel
);
955 imap
->buf
.sock
.fd
[0] = tunnel
.out
;
956 imap
->buf
.sock
.fd
[1] = tunnel
.in
;
961 struct addrinfo hints
, *ai0
, *ai
;
965 xsnprintf(portstr
, sizeof(portstr
), "%d", srvc
->port
);
967 memset(&hints
, 0, sizeof(hints
));
968 hints
.ai_socktype
= SOCK_STREAM
;
969 hints
.ai_protocol
= IPPROTO_TCP
;
971 imap_info("Resolving %s... ", srvc
->host
);
972 gai
= getaddrinfo(srvc
->host
, portstr
, &hints
, &ai
);
974 fprintf(stderr
, "getaddrinfo: %s\n", gai_strerror(gai
));
979 for (ai0
= ai
; ai
; ai
= ai
->ai_next
) {
980 char addr
[NI_MAXHOST
];
982 s
= socket(ai
->ai_family
, ai
->ai_socktype
,
987 getnameinfo(ai
->ai_addr
, ai
->ai_addrlen
, addr
,
988 sizeof(addr
), NULL
, 0, NI_NUMERICHOST
);
989 imap_info("Connecting to [%s]:%s... ", addr
, portstr
);
991 if (connect(s
, ai
->ai_addr
, ai
->ai_addrlen
) < 0) {
1003 struct sockaddr_in addr
;
1005 memset(&addr
, 0, sizeof(addr
));
1006 addr
.sin_port
= htons(srvc
->port
);
1007 addr
.sin_family
= AF_INET
;
1009 imap_info("Resolving %s... ", srvc
->host
);
1010 he
= gethostbyname(srvc
->host
);
1012 perror("gethostbyname");
1017 addr
.sin_addr
.s_addr
= *((int *) he
->h_addr_list
[0]);
1019 s
= socket(PF_INET
, SOCK_STREAM
, 0);
1021 imap_info("Connecting to %s:%hu... ", inet_ntoa(addr
.sin_addr
), ntohs(addr
.sin_port
));
1022 if (connect(s
, (struct sockaddr
*)&addr
, sizeof(addr
))) {
1029 fputs("Error: unable to connect to server.\n", stderr
);
1033 imap
->buf
.sock
.fd
[0] = s
;
1034 imap
->buf
.sock
.fd
[1] = dup(s
);
1036 if (srvc
->use_ssl
&&
1037 ssl_socket_connect(&imap
->buf
.sock
, srvc
, 0)) {
1044 /* read the greeting string */
1045 if (buffer_gets(&imap
->buf
, &rsp
)) {
1046 fprintf(stderr
, "IMAP error: no greeting response\n");
1049 arg
= next_arg(&rsp
);
1050 if (!arg
|| *arg
!= '*' || (arg
= next_arg(&rsp
)) == NULL
) {
1051 fprintf(stderr
, "IMAP error: invalid greeting response\n");
1055 if (!strcmp("PREAUTH", arg
))
1057 else if (strcmp("OK", arg
) != 0) {
1058 fprintf(stderr
, "IMAP error: unknown greeting response\n");
1061 parse_response_code(ctx
, NULL
, rsp
);
1062 if (!imap
->caps
&& imap_exec(ctx
, NULL
, "CAPABILITY") != RESP_OK
)
1067 if (!srvc
->use_ssl
&& CAP(STARTTLS
)) {
1068 if (imap_exec(ctx
, NULL
, "STARTTLS") != RESP_OK
)
1070 if (ssl_socket_connect(&imap
->buf
.sock
, srvc
, 1))
1072 /* capabilities may have changed, so get the new capabilities */
1073 if (imap_exec(ctx
, NULL
, "CAPABILITY") != RESP_OK
)
1077 imap_info("Logging in...\n");
1078 server_fill_credential(srvc
, &cred
);
1080 if (srvc
->auth_method
) {
1081 struct imap_cmd_cb cb
;
1083 if (!strcmp(srvc
->auth_method
, "CRAM-MD5")) {
1084 if (!CAP(AUTH_CRAM_MD5
)) {
1085 fprintf(stderr
, "You specified "
1086 "CRAM-MD5 as authentication method, "
1087 "but %s doesn't support it.\n", srvc
->host
);
1092 memset(&cb
, 0, sizeof(cb
));
1093 cb
.cont
= auth_cram_md5
;
1094 if (imap_exec(ctx
, &cb
, "AUTHENTICATE CRAM-MD5") != RESP_OK
) {
1095 fprintf(stderr
, "IMAP error: AUTHENTICATE CRAM-MD5 failed\n");
1099 fprintf(stderr
, "Unknown authentication method:%s\n", srvc
->host
);
1104 fprintf(stderr
, "Skipping account %s@%s, server forbids LOGIN\n",
1105 srvc
->user
, srvc
->host
);
1108 if (!imap
->buf
.sock
.ssl
)
1109 imap_warn("*** IMAP Warning *** Password is being "
1110 "sent in the clear\n");
1111 if (imap_exec(ctx
, NULL
, "LOGIN \"%s\" \"%s\"", srvc
->user
, srvc
->pass
) != RESP_OK
) {
1112 fprintf(stderr
, "IMAP error: LOGIN failed\n");
1119 credential_approve(&cred
);
1120 credential_clear(&cred
);
1122 /* check the target mailbox exists */
1124 switch (imap_exec(ctx
, NULL
, "EXAMINE \"%s\"", ctx
->name
)) {
1129 fprintf(stderr
, "IMAP error: could not check mailbox\n");
1132 if (imap_exec(ctx
, NULL
, "CREATE \"%s\"", ctx
->name
) == RESP_OK
) {
1133 imap_info("Created missing mailbox\n");
1135 fprintf(stderr
, "IMAP error: could not create missing mailbox\n");
1146 credential_reject(&cred
);
1147 credential_clear(&cred
);
1150 imap_close_store(ctx
);
1155 * Insert CR characters as necessary in *msg to ensure that every LF
1156 * character in *msg is preceded by a CR.
1158 static void lf_to_crlf(struct strbuf
*msg
)
1164 /* First pass: tally, in j, the size of the new_msg string: */
1165 for (i
= j
= 0, lastc
= '\0'; i
< msg
->len
; i
++) {
1166 if (msg
->buf
[i
] == '\n' && lastc
!= '\r')
1167 j
++; /* a CR will need to be added here */
1168 lastc
= msg
->buf
[i
];
1172 new_msg
= xmallocz(j
);
1175 * Second pass: write the new_msg string. Note that this loop is
1176 * otherwise identical to the first pass.
1178 for (i
= j
= 0, lastc
= '\0'; i
< msg
->len
; i
++) {
1179 if (msg
->buf
[i
] == '\n' && lastc
!= '\r')
1180 new_msg
[j
++] = '\r';
1181 lastc
= new_msg
[j
++] = msg
->buf
[i
];
1183 strbuf_attach(msg
, new_msg
, j
, j
+ 1);
1187 * Store msg to IMAP. Also detach and free the data from msg->data,
1188 * leaving msg->data empty.
1190 static int imap_store_msg(struct imap_store
*ctx
, struct strbuf
*msg
)
1192 struct imap
*imap
= ctx
->imap
;
1193 struct imap_cmd_cb cb
;
1194 const char *prefix
, *box
;
1198 memset(&cb
, 0, sizeof(cb
));
1201 cb
.data
= strbuf_detach(msg
, NULL
);
1204 prefix
= !strcmp(box
, "INBOX") ? "" : ctx
->prefix
;
1205 ret
= imap_exec_m(ctx
, &cb
, "APPEND \"%s%s\" ", prefix
, box
);
1206 imap
->caps
= imap
->rcaps
;
1213 static void wrap_in_html(struct strbuf
*msg
)
1215 struct strbuf buf
= STRBUF_INIT
;
1216 static const char *content_type
= "Content-Type: text/html;\n";
1217 static const char *pre_open
= "<pre>\n";
1218 static const char *pre_close
= "</pre>\n";
1219 const char *body
= strstr(msg
->buf
, "\n\n");
1222 return; /* Headers but no body; no wrapping needed */
1226 strbuf_add(&buf
, msg
->buf
, body
- msg
->buf
- 1);
1227 strbuf_addstr(&buf
, content_type
);
1228 strbuf_addch(&buf
, '\n');
1229 strbuf_addstr(&buf
, pre_open
);
1230 strbuf_addstr_xml_quoted(&buf
, body
);
1231 strbuf_addstr(&buf
, pre_close
);
1233 strbuf_release(msg
);
1237 static int count_messages(struct strbuf
*all_msgs
)
1240 char *p
= all_msgs
->buf
;
1243 if (starts_with(p
, "From ")) {
1244 p
= strstr(p
+5, "\nFrom: ");
1246 p
= strstr(p
+7, "\nDate: ");
1248 p
= strstr(p
+7, "\nSubject: ");
1253 p
= strstr(p
+5, "\nFrom ");
1262 * Copy the next message from all_msgs, starting at offset *ofs, to
1263 * msg. Update *ofs to the start of the following message. Return
1264 * true iff a message was successfully copied.
1266 static int split_msg(struct strbuf
*all_msgs
, struct strbuf
*msg
, int *ofs
)
1271 if (*ofs
>= all_msgs
->len
)
1274 data
= &all_msgs
->buf
[*ofs
];
1275 len
= all_msgs
->len
- *ofs
;
1277 if (len
< 5 || !starts_with(data
, "From "))
1280 p
= strchr(data
, '\n');
1288 p
= strstr(data
, "\nFrom ");
1292 strbuf_add(msg
, data
, len
);
1297 static int git_imap_config(const char *var
, const char *val
,
1298 const struct config_context
*ctx
, void *cb
)
1300 struct imap_server_conf
*cfg
= cb
;
1302 if (!strcmp("imap.sslverify", var
)) {
1303 cfg
->ssl_verify
= git_config_bool(var
, val
);
1304 } else if (!strcmp("imap.preformattedhtml", var
)) {
1305 cfg
->use_html
= git_config_bool(var
, val
);
1306 } else if (!strcmp("imap.folder", var
)) {
1307 FREE_AND_NULL(cfg
->folder
);
1308 return git_config_string(&cfg
->folder
, var
, val
);
1309 } else if (!strcmp("imap.user", var
)) {
1310 FREE_AND_NULL(cfg
->folder
);
1311 return git_config_string(&cfg
->user
, var
, val
);
1312 } else if (!strcmp("imap.pass", var
)) {
1313 FREE_AND_NULL(cfg
->folder
);
1314 return git_config_string(&cfg
->pass
, var
, val
);
1315 } else if (!strcmp("imap.tunnel", var
)) {
1316 FREE_AND_NULL(cfg
->folder
);
1317 return git_config_string(&cfg
->tunnel
, var
, val
);
1318 } else if (!strcmp("imap.authmethod", var
)) {
1319 FREE_AND_NULL(cfg
->folder
);
1320 return git_config_string(&cfg
->auth_method
, var
, val
);
1321 } else if (!strcmp("imap.port", var
)) {
1322 cfg
->port
= git_config_int(var
, val
, ctx
->kvi
);
1323 } else if (!strcmp("imap.host", var
)) {
1325 return config_error_nonbool(var
);
1327 if (starts_with(val
, "imap:"))
1329 else if (starts_with(val
, "imaps:")) {
1333 if (starts_with(val
, "//"))
1335 cfg
->host
= xstrdup(val
);
1338 return git_default_config(var
, val
, ctx
, cb
);
1344 static int append_msgs_to_imap(struct imap_server_conf
*server
,
1345 struct strbuf
* all_msgs
, int total
)
1347 struct strbuf msg
= STRBUF_INIT
;
1348 struct imap_store
*ctx
= NULL
;
1353 ctx
= imap_open_store(server
, server
->folder
);
1355 fprintf(stderr
, "failed to open store\n");
1358 ctx
->name
= server
->folder
;
1360 fprintf(stderr
, "sending %d message%s\n", total
, (total
!= 1) ? "s" : "");
1362 unsigned percent
= n
* 100 / total
;
1364 fprintf(stderr
, "%4u%% (%d/%d) done\r", percent
, n
, total
);
1366 if (!split_msg(all_msgs
, &msg
, &ofs
))
1368 if (server
->use_html
)
1370 r
= imap_store_msg(ctx
, &msg
);
1375 fprintf(stderr
, "\n");
1377 imap_close_store(ctx
);
1382 #ifdef USE_CURL_FOR_IMAP_SEND
1383 static CURL
*setup_curl(struct imap_server_conf
*srvc
, struct credential
*cred
)
1386 struct strbuf path
= STRBUF_INIT
;
1387 char *uri_encoded_folder
;
1389 if (curl_global_init(CURL_GLOBAL_ALL
) != CURLE_OK
)
1390 die("curl_global_init failed");
1392 curl
= curl_easy_init();
1395 die("curl_easy_init failed");
1397 server_fill_credential(srvc
, cred
);
1398 curl_easy_setopt(curl
, CURLOPT_USERNAME
, srvc
->user
);
1399 curl_easy_setopt(curl
, CURLOPT_PASSWORD
, srvc
->pass
);
1401 strbuf_addstr(&path
, srvc
->use_ssl
? "imaps://" : "imap://");
1402 strbuf_addstr(&path
, srvc
->host
);
1403 if (!path
.len
|| path
.buf
[path
.len
- 1] != '/')
1404 strbuf_addch(&path
, '/');
1406 uri_encoded_folder
= curl_easy_escape(curl
, srvc
->folder
, 0);
1407 if (!uri_encoded_folder
)
1408 die("failed to encode server folder");
1409 strbuf_addstr(&path
, uri_encoded_folder
);
1410 curl_free(uri_encoded_folder
);
1412 curl_easy_setopt(curl
, CURLOPT_URL
, path
.buf
);
1413 strbuf_release(&path
);
1414 curl_easy_setopt(curl
, CURLOPT_PORT
, srvc
->port
);
1416 if (srvc
->auth_method
) {
1417 #ifndef GIT_CURL_HAVE_CURLOPT_LOGIN_OPTIONS
1418 warning("No LOGIN_OPTIONS support in this cURL version");
1420 struct strbuf auth
= STRBUF_INIT
;
1421 strbuf_addstr(&auth
, "AUTH=");
1422 strbuf_addstr(&auth
, srvc
->auth_method
);
1423 curl_easy_setopt(curl
, CURLOPT_LOGIN_OPTIONS
, auth
.buf
);
1424 strbuf_release(&auth
);
1429 curl_easy_setopt(curl
, CURLOPT_USE_SSL
, (long)CURLUSESSL_TRY
);
1431 curl_easy_setopt(curl
, CURLOPT_SSL_VERIFYPEER
, srvc
->ssl_verify
);
1432 curl_easy_setopt(curl
, CURLOPT_SSL_VERIFYHOST
, srvc
->ssl_verify
);
1434 curl_easy_setopt(curl
, CURLOPT_READFUNCTION
, fread_buffer
);
1436 curl_easy_setopt(curl
, CURLOPT_UPLOAD
, 1L);
1438 if (0 < verbosity
|| getenv("GIT_CURL_VERBOSE"))
1439 http_trace_curl_no_data();
1440 setup_curl_trace(curl
);
1445 static int curl_append_msgs_to_imap(struct imap_server_conf
*server
,
1446 struct strbuf
* all_msgs
, int total
)
1450 struct buffer msgbuf
= { STRBUF_INIT
, 0 };
1452 CURLcode res
= CURLE_OK
;
1453 struct credential cred
= CREDENTIAL_INIT
;
1455 curl
= setup_curl(server
, &cred
);
1456 curl_easy_setopt(curl
, CURLOPT_READDATA
, &msgbuf
);
1458 fprintf(stderr
, "sending %d message%s\n", total
, (total
!= 1) ? "s" : "");
1460 unsigned percent
= n
* 100 / total
;
1463 fprintf(stderr
, "%4u%% (%d/%d) done\r", percent
, n
, total
);
1465 prev_len
= msgbuf
.buf
.len
;
1466 if (!split_msg(all_msgs
, &msgbuf
.buf
, &ofs
))
1468 if (server
->use_html
)
1469 wrap_in_html(&msgbuf
.buf
);
1470 lf_to_crlf(&msgbuf
.buf
);
1472 curl_easy_setopt(curl
, CURLOPT_INFILESIZE_LARGE
,
1473 (curl_off_t
)(msgbuf
.buf
.len
-prev_len
));
1475 res
= curl_easy_perform(curl
);
1477 if(res
!= CURLE_OK
) {
1478 fprintf(stderr
, "curl_easy_perform() failed: %s\n",
1479 curl_easy_strerror(res
));
1485 fprintf(stderr
, "\n");
1487 curl_easy_cleanup(curl
);
1488 curl_global_cleanup();
1490 if (cred
.username
) {
1491 if (res
== CURLE_OK
)
1492 credential_approve(&cred
);
1493 else if (res
== CURLE_LOGIN_DENIED
)
1494 credential_reject(&cred
);
1497 credential_clear(&cred
);
1499 return res
!= CURLE_OK
;
1503 int cmd_main(int argc
, const char **argv
)
1505 struct imap_server_conf server
= {
1508 struct strbuf all_msgs
= STRBUF_INIT
;
1513 setup_git_directory_gently(&nongit_ok
);
1514 git_config(git_imap_config
, &server
);
1516 argc
= parse_options(argc
, (const char **)argv
, "", imap_send_options
, imap_send_usage
, 0);
1519 usage_with_options(imap_send_usage
, imap_send_options
);
1521 #ifndef USE_CURL_FOR_IMAP_SEND
1523 warning("--curl not supported in this build");
1526 #elif defined(NO_OPENSSL)
1528 warning("--no-curl not supported in this build");
1534 server
.port
= server
.use_ssl
? 993 : 143;
1536 if (!server
.folder
) {
1537 fprintf(stderr
, "no imap store specified\n");
1542 if (!server
.tunnel
) {
1543 fprintf(stderr
, "no imap host specified\n");
1547 server
.host
= xstrdup("tunnel");
1550 /* read the messages */
1551 if (strbuf_read(&all_msgs
, 0, 0) < 0) {
1552 error_errno(_("could not read from stdin"));
1557 if (all_msgs
.len
== 0) {
1558 fprintf(stderr
, "nothing to send\n");
1563 total
= count_messages(&all_msgs
);
1565 fprintf(stderr
, "no messages to send\n");
1570 /* write it to the imap server */
1573 ret
= append_msgs_to_imap(&server
, &all_msgs
, total
);
1574 #ifdef USE_CURL_FOR_IMAP_SEND
1576 ret
= curl_append_msgs_to_imap(&server
, &all_msgs
, total
);
1579 ret
= append_msgs_to_imap(&server
, &all_msgs
, total
);
1582 free(server
.tunnel
);
1584 free(server
.folder
);
1587 free(server
.auth_method
);
1588 strbuf_release(&all_msgs
);