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
27 #include "run-command.h"
32 #ifdef APPLE_COMMON_CRYPTO
33 #include <CommonCrypto/CommonHMAC.h>
34 #define HMAC_CTX CCHmacContext
35 #define HMAC_Init(hmac, key, len, algo) CCHmacInit(hmac, algo, key, len)
36 #define HMAC_Update CCHmacUpdate
37 #define HMAC_Final(hmac, hash, ptr) CCHmacFinal(hmac, hash)
38 #define HMAC_CTX_cleanup(ignore)
39 #define EVP_md5() kCCHmacAlgMD5
41 #include <openssl/evp.h>
42 #include <openssl/hmac.h>
44 #include <openssl/x509v3.h>
47 static const char imap_send_usage
[] = "git imap-send < <mbox>";
51 #define DRV_MSG_BAD -1
52 #define DRV_BOX_BAD -2
53 #define DRV_STORE_BAD -3
55 static int Verbose
, Quiet
;
57 __attribute__((format (printf
, 1, 2)))
58 static void imap_info(const char *, ...);
59 __attribute__((format (printf
, 1, 2)))
60 static void imap_warn(const char *, ...);
62 static char *next_arg(char **);
64 __attribute__((format (printf
, 3, 4)))
65 static int nfsnprintf(char *buf
, int blen
, const char *fmt
, ...);
67 static int nfvasprintf(char **strp
, const char *fmt
, va_list ap
)
72 len
= vsnprintf(tmp
, sizeof(tmp
), fmt
, ap
);
74 die("Fatal: Out of memory");
75 if (len
>= sizeof(tmp
))
76 die("imap command overflow!");
77 *strp
= xmemdupz(tmp
, len
);
81 struct imap_server_conf
{
94 static struct imap_server_conf server
= {
104 NULL
, /* auth_method */
113 struct imap_socket sock
;
122 int uidnext
; /* from SELECT responses */
123 unsigned caps
, rcaps
; /* CAPABILITY results */
125 int nexttag
, num_in_progress
, literal_pending
;
126 struct imap_cmd
*in_progress
, **in_progress_append
;
127 struct imap_buffer buf
; /* this is BIG, so put it last */
131 /* currently open mailbox */
132 const char *name
; /* foreign! maybe preset? */
139 int (*cont
)(struct imap_store
*ctx
, struct imap_cmd
*cmd
, const char *prompt
);
140 void (*done
)(struct imap_store
*ctx
, struct imap_cmd
*cmd
, int response
);
145 unsigned create
:1, trycreate
:1;
149 struct imap_cmd
*next
;
150 struct imap_cmd_cb cb
;
155 #define CAP(cap) (imap->caps & (1 << (cap)))
166 static const char *cap_list
[] = {
179 static int get_cmd_result(struct imap_store
*ctx
, struct imap_cmd
*tcmd
);
183 static void ssl_socket_perror(const char *func
)
185 fprintf(stderr
, "%s: %s\n", func
, ERR_error_string(ERR_get_error(), NULL
));
189 static void socket_perror(const char *func
, struct imap_socket
*sock
, int ret
)
193 int sslerr
= SSL_get_error(sock
->ssl
, ret
);
197 case SSL_ERROR_SYSCALL
:
198 perror("SSL_connect");
201 ssl_socket_perror("SSL_connect");
210 fprintf(stderr
, "%s: unexpected EOF\n", func
);
215 static int ssl_socket_connect(struct imap_socket
*sock
, int use_tls_only
, int verify
)
217 fprintf(stderr
, "SSL requested but SSL support not compiled in\n");
223 static int host_matches(const char *host
, const char *pattern
)
225 if (pattern
[0] == '*' && pattern
[1] == '.') {
227 if (!(host
= strchr(host
, '.')))
232 return *host
&& *pattern
&& !strcasecmp(host
, pattern
);
235 static int verify_hostname(X509
*cert
, const char *hostname
)
241 STACK_OF(GENERAL_NAME
) *subj_alt_names
;
243 /* try the DNS subjectAltNames */
245 if ((subj_alt_names
= X509_get_ext_d2i(cert
, NID_subject_alt_name
, NULL
, NULL
))) {
246 int num_subj_alt_names
= sk_GENERAL_NAME_num(subj_alt_names
);
247 for (i
= 0; !found
&& i
< num_subj_alt_names
; i
++) {
248 GENERAL_NAME
*subj_alt_name
= sk_GENERAL_NAME_value(subj_alt_names
, i
);
249 if (subj_alt_name
->type
== GEN_DNS
&&
250 strlen((const char *)subj_alt_name
->d
.ia5
->data
) == (size_t)subj_alt_name
->d
.ia5
->length
&&
251 host_matches(hostname
, (const char *)(subj_alt_name
->d
.ia5
->data
)))
254 sk_GENERAL_NAME_pop_free(subj_alt_names
, GENERAL_NAME_free
);
259 /* try the common name */
260 if (!(subj
= X509_get_subject_name(cert
)))
261 return error("cannot get certificate subject");
262 if ((len
= X509_NAME_get_text_by_NID(subj
, NID_commonName
, cname
, sizeof(cname
))) < 0)
263 return error("cannot get certificate common name");
264 if (strlen(cname
) == (size_t)len
&& host_matches(hostname
, cname
))
266 return error("certificate owner '%s' does not match hostname '%s'",
270 static int ssl_socket_connect(struct imap_socket
*sock
, int use_tls_only
, int verify
)
272 #if (OPENSSL_VERSION_NUMBER >= 0x10000000L)
273 const SSL_METHOD
*meth
;
282 SSL_load_error_strings();
285 meth
= TLSv1_method();
287 meth
= SSLv23_method();
290 ssl_socket_perror("SSLv23_method");
294 ctx
= SSL_CTX_new(meth
);
297 SSL_CTX_set_verify(ctx
, SSL_VERIFY_PEER
, NULL
);
299 if (!SSL_CTX_set_default_verify_paths(ctx
)) {
300 ssl_socket_perror("SSL_CTX_set_default_verify_paths");
303 sock
->ssl
= SSL_new(ctx
);
305 ssl_socket_perror("SSL_new");
308 if (!SSL_set_rfd(sock
->ssl
, sock
->fd
[0])) {
309 ssl_socket_perror("SSL_set_rfd");
312 if (!SSL_set_wfd(sock
->ssl
, sock
->fd
[1])) {
313 ssl_socket_perror("SSL_set_wfd");
317 #ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
320 * OpenSSL does not document this function, but the implementation
321 * returns 1 on success, 0 on failure after calling SSLerr().
323 ret
= SSL_set_tlsext_host_name(sock
->ssl
, server
.host
);
325 warning("SSL_set_tlsext_host_name(%s) failed.", server
.host
);
328 ret
= SSL_connect(sock
->ssl
);
330 socket_perror("SSL_connect", sock
, ret
);
335 /* make sure the hostname matches that of the certificate */
336 cert
= SSL_get_peer_certificate(sock
->ssl
);
338 return error("unable to get peer certificate.");
339 if (verify_hostname(cert
, server
.host
) < 0)
347 static int socket_read(struct imap_socket
*sock
, char *buf
, int len
)
352 n
= SSL_read(sock
->ssl
, buf
, len
);
355 n
= xread(sock
->fd
[0], buf
, len
);
357 socket_perror("read", sock
, n
);
360 sock
->fd
[0] = sock
->fd
[1] = -1;
365 static int socket_write(struct imap_socket
*sock
, const char *buf
, int len
)
370 n
= SSL_write(sock
->ssl
, buf
, len
);
373 n
= write_in_full(sock
->fd
[1], buf
, len
);
375 socket_perror("write", sock
, n
);
378 sock
->fd
[0] = sock
->fd
[1] = -1;
383 static void socket_shutdown(struct imap_socket
*sock
)
387 SSL_shutdown(sock
->ssl
);
395 /* simple line buffering */
396 static int buffer_gets(struct imap_buffer
*b
, char **s
)
399 int start
= b
->offset
;
404 /* make sure we have enough data to read the \r\n sequence */
405 if (b
->offset
+ 1 >= b
->bytes
) {
407 /* shift down used bytes */
410 assert(start
<= b
->bytes
);
411 n
= b
->bytes
- start
;
414 memmove(b
->buf
, b
->buf
+ start
, n
);
420 n
= socket_read(&b
->sock
, b
->buf
+ b
->bytes
,
421 sizeof(b
->buf
) - b
->bytes
);
429 if (b
->buf
[b
->offset
] == '\r') {
430 assert(b
->offset
+ 1 < b
->bytes
);
431 if (b
->buf
[b
->offset
+ 1] == '\n') {
432 b
->buf
[b
->offset
] = 0; /* terminate the string */
433 b
->offset
+= 2; /* next line */
445 static void imap_info(const char *msg
, ...)
457 static void imap_warn(const char *msg
, ...)
463 vfprintf(stderr
, msg
, va
);
468 static char *next_arg(char **s
)
474 while (isspace((unsigned char) **s
))
483 *s
= strchr(*s
, '"');
486 while (**s
&& !isspace((unsigned char) **s
))
498 static int nfsnprintf(char *buf
, int blen
, const char *fmt
, ...)
504 if (blen
<= 0 || (unsigned)(ret
= vsnprintf(buf
, blen
, fmt
, va
)) >= (unsigned)blen
)
505 die("Fatal: buffer too small. Please report a bug.");
510 static struct imap_cmd
*v_issue_imap_cmd(struct imap_store
*ctx
,
511 struct imap_cmd_cb
*cb
,
512 const char *fmt
, va_list ap
)
514 struct imap
*imap
= ctx
->imap
;
515 struct imap_cmd
*cmd
;
519 cmd
= xmalloc(sizeof(struct imap_cmd
));
520 nfvasprintf(&cmd
->cmd
, fmt
, ap
);
521 cmd
->tag
= ++imap
->nexttag
;
526 memset(&cmd
->cb
, 0, sizeof(cmd
->cb
));
528 while (imap
->literal_pending
)
529 get_cmd_result(ctx
, NULL
);
532 bufl
= nfsnprintf(buf
, sizeof(buf
), "%d %s\r\n", cmd
->tag
, cmd
->cmd
);
534 bufl
= nfsnprintf(buf
, sizeof(buf
), "%d %s{%d%s}\r\n",
535 cmd
->tag
, cmd
->cmd
, cmd
->cb
.dlen
,
536 CAP(LITERALPLUS
) ? "+" : "");
539 if (imap
->num_in_progress
)
540 printf("(%d in progress) ", imap
->num_in_progress
);
541 if (memcmp(cmd
->cmd
, "LOGIN", 5))
542 printf(">>> %s", buf
);
544 printf(">>> %d LOGIN <user> <pass>\n", cmd
->tag
);
546 if (socket_write(&imap
->buf
.sock
, buf
, bufl
) != bufl
) {
554 if (CAP(LITERALPLUS
)) {
555 n
= socket_write(&imap
->buf
.sock
, cmd
->cb
.data
, cmd
->cb
.dlen
);
557 if (n
!= cmd
->cb
.dlen
||
558 socket_write(&imap
->buf
.sock
, "\r\n", 2) != 2) {
565 imap
->literal_pending
= 1;
566 } else if (cmd
->cb
.cont
)
567 imap
->literal_pending
= 1;
569 *imap
->in_progress_append
= cmd
;
570 imap
->in_progress_append
= &cmd
->next
;
571 imap
->num_in_progress
++;
575 __attribute__((format (printf
, 3, 4)))
576 static struct imap_cmd
*issue_imap_cmd(struct imap_store
*ctx
,
577 struct imap_cmd_cb
*cb
,
578 const char *fmt
, ...)
580 struct imap_cmd
*ret
;
584 ret
= v_issue_imap_cmd(ctx
, cb
, fmt
, ap
);
589 __attribute__((format (printf
, 3, 4)))
590 static int imap_exec(struct imap_store
*ctx
, struct imap_cmd_cb
*cb
,
591 const char *fmt
, ...)
594 struct imap_cmd
*cmdp
;
597 cmdp
= v_issue_imap_cmd(ctx
, cb
, fmt
, ap
);
602 return get_cmd_result(ctx
, cmdp
);
605 __attribute__((format (printf
, 3, 4)))
606 static int imap_exec_m(struct imap_store
*ctx
, struct imap_cmd_cb
*cb
,
607 const char *fmt
, ...)
610 struct imap_cmd
*cmdp
;
613 cmdp
= v_issue_imap_cmd(ctx
, cb
, fmt
, ap
);
616 return DRV_STORE_BAD
;
618 switch (get_cmd_result(ctx
, cmdp
)) {
619 case RESP_BAD
: return DRV_STORE_BAD
;
620 case RESP_NO
: return DRV_MSG_BAD
;
621 default: return DRV_OK
;
625 static int skip_imap_list_l(char **sp
, int level
)
630 while (isspace((unsigned char)*s
))
632 if (level
&& *s
== ')') {
639 if (skip_imap_list_l(&s
, level
+ 1))
641 } else if (*s
== '"') {
644 for (; *s
!= '"'; s
++)
650 for (; *s
&& !isspace((unsigned char)*s
); s
++)
651 if (level
&& *s
== ')')
667 static void skip_list(char **sp
)
669 skip_imap_list_l(sp
, 0);
672 static void parse_capability(struct imap
*imap
, char *cmd
)
677 imap
->caps
= 0x80000000;
678 while ((arg
= next_arg(&cmd
)))
679 for (i
= 0; i
< ARRAY_SIZE(cap_list
); i
++)
680 if (!strcmp(cap_list
[i
], arg
))
681 imap
->caps
|= 1 << i
;
682 imap
->rcaps
= imap
->caps
;
685 static int parse_response_code(struct imap_store
*ctx
, struct imap_cmd_cb
*cb
,
688 struct imap
*imap
= ctx
->imap
;
692 return RESP_OK
; /* no response code */
694 if (!(p
= strchr(s
, ']'))) {
695 fprintf(stderr
, "IMAP error: malformed response code\n");
700 if (!strcmp("UIDVALIDITY", arg
)) {
701 if (!(arg
= next_arg(&s
)) || !(ctx
->uidvalidity
= atoi(arg
))) {
702 fprintf(stderr
, "IMAP error: malformed UIDVALIDITY status\n");
705 } else if (!strcmp("UIDNEXT", arg
)) {
706 if (!(arg
= next_arg(&s
)) || !(imap
->uidnext
= atoi(arg
))) {
707 fprintf(stderr
, "IMAP error: malformed NEXTUID status\n");
710 } else if (!strcmp("CAPABILITY", arg
)) {
711 parse_capability(imap
, s
);
712 } else if (!strcmp("ALERT", arg
)) {
713 /* RFC2060 says that these messages MUST be displayed
716 for (; isspace((unsigned char)*p
); p
++);
717 fprintf(stderr
, "*** IMAP ALERT *** %s\n", p
);
718 } else if (cb
&& cb
->ctx
&& !strcmp("APPENDUID", arg
)) {
719 if (!(arg
= next_arg(&s
)) || !(ctx
->uidvalidity
= atoi(arg
)) ||
720 !(arg
= next_arg(&s
)) || !(*(int *)cb
->ctx
= atoi(arg
))) {
721 fprintf(stderr
, "IMAP error: malformed APPENDUID status\n");
728 static int get_cmd_result(struct imap_store
*ctx
, struct imap_cmd
*tcmd
)
730 struct imap
*imap
= ctx
->imap
;
731 struct imap_cmd
*cmdp
, **pcmdp
, *ncmdp
;
732 char *cmd
, *arg
, *arg1
, *p
;
733 int n
, resp
, resp2
, tag
;
736 if (buffer_gets(&imap
->buf
, &cmd
))
739 arg
= next_arg(&cmd
);
741 arg
= next_arg(&cmd
);
743 fprintf(stderr
, "IMAP error: unable to parse untagged response\n");
747 if (!strcmp("NAMESPACE", arg
)) {
748 /* rfc2342 NAMESPACE response. */
749 skip_list(&cmd
); /* Personal mailboxes */
750 skip_list(&cmd
); /* Others' mailboxes */
751 skip_list(&cmd
); /* Shared mailboxes */
752 } else if (!strcmp("OK", arg
) || !strcmp("BAD", arg
) ||
753 !strcmp("NO", arg
) || !strcmp("BYE", arg
)) {
754 if ((resp
= parse_response_code(ctx
, NULL
, cmd
)) != RESP_OK
)
756 } else if (!strcmp("CAPABILITY", arg
)) {
757 parse_capability(imap
, cmd
);
758 } else if ((arg1
= next_arg(&cmd
))) {
760 * Unhandled response-data with at least two words.
763 * NEEDSWORK: Previously this case handled '<num> EXISTS'
764 * and '<num> RECENT' but as a probably-unintended side
765 * effect it ignores other unrecognized two-word
766 * responses. imap-send doesn't ever try to read
767 * messages or mailboxes these days, so consider
768 * eliminating this case.
771 fprintf(stderr
, "IMAP error: unable to parse untagged response\n");
774 } else if (!imap
->in_progress
) {
775 fprintf(stderr
, "IMAP error: unexpected reply: %s %s\n", arg
, cmd
? cmd
: "");
777 } else if (*arg
== '+') {
778 /* This can happen only with the last command underway, as
779 it enforces a round-trip. */
780 cmdp
= (struct imap_cmd
*)((char *)imap
->in_progress_append
-
781 offsetof(struct imap_cmd
, next
));
783 n
= socket_write(&imap
->buf
.sock
, cmdp
->cb
.data
, cmdp
->cb
.dlen
);
785 cmdp
->cb
.data
= NULL
;
786 if (n
!= (int)cmdp
->cb
.dlen
)
788 } else if (cmdp
->cb
.cont
) {
789 if (cmdp
->cb
.cont(ctx
, cmdp
, cmd
))
792 fprintf(stderr
, "IMAP error: unexpected command continuation request\n");
795 if (socket_write(&imap
->buf
.sock
, "\r\n", 2) != 2)
798 imap
->literal_pending
= 0;
803 for (pcmdp
= &imap
->in_progress
; (cmdp
= *pcmdp
); pcmdp
= &cmdp
->next
)
804 if (cmdp
->tag
== tag
)
806 fprintf(stderr
, "IMAP error: unexpected tag %s\n", arg
);
809 if (!(*pcmdp
= cmdp
->next
))
810 imap
->in_progress_append
= pcmdp
;
811 imap
->num_in_progress
--;
812 if (cmdp
->cb
.cont
|| cmdp
->cb
.data
)
813 imap
->literal_pending
= 0;
814 arg
= next_arg(&cmd
);
815 if (!strcmp("OK", arg
))
818 if (!strcmp("NO", arg
)) {
819 if (cmdp
->cb
.create
&& cmd
&& (cmdp
->cb
.trycreate
|| !memcmp(cmd
, "[TRYCREATE]", 11))) { /* SELECT, APPEND or UID COPY */
820 p
= strchr(cmdp
->cmd
, '"');
821 if (!issue_imap_cmd(ctx
, NULL
, "CREATE \"%.*s\"", (int)(strchr(p
+ 1, '"') - p
+ 1), p
)) {
825 /* not waiting here violates the spec, but a server that does not
826 grok this nonetheless violates it too. */
828 if (!(ncmdp
= issue_imap_cmd(ctx
, &cmdp
->cb
, "%s", cmdp
->cmd
))) {
835 return 0; /* ignored */
841 } else /*if (!strcmp("BAD", arg))*/
843 fprintf(stderr
, "IMAP command '%s' returned response (%s) - %s\n",
844 memcmp(cmdp
->cmd
, "LOGIN", 5) ?
845 cmdp
->cmd
: "LOGIN <user> <pass>",
846 arg
, cmd
? cmd
: "");
848 if ((resp2
= parse_response_code(ctx
, &cmdp
->cb
, cmd
)) > resp
)
852 cmdp
->cb
.done(ctx
, cmdp
, resp
);
856 if (!tcmd
|| tcmd
== cmdp
)
863 static void imap_close_server(struct imap_store
*ictx
)
865 struct imap
*imap
= ictx
->imap
;
867 if (imap
->buf
.sock
.fd
[0] != -1) {
868 imap_exec(ictx
, NULL
, "LOGOUT");
869 socket_shutdown(&imap
->buf
.sock
);
874 static void imap_close_store(struct imap_store
*ctx
)
876 imap_close_server(ctx
);
883 * hexchar() and cram() functions are based on the code from the isync
884 * project (http://isync.sf.net/).
886 static char hexchar(unsigned int b
)
888 return b
< 10 ? '0' + b
: 'a' + (b
- 10);
891 #define ENCODED_SIZE(n) (4*((n+2)/3))
892 static char *cram(const char *challenge_64
, const char *user
, const char *pass
)
894 int i
, resp_len
, encoded_len
, decoded_len
;
896 unsigned char hash
[16];
898 char *response
, *response_64
, *challenge
;
901 * length of challenge_64 (i.e. base-64 encoded string) is a good
902 * enough upper bound for challenge (decoded result).
904 encoded_len
= strlen(challenge_64
);
905 challenge
= xmalloc(encoded_len
);
906 decoded_len
= EVP_DecodeBlock((unsigned char *)challenge
,
907 (unsigned char *)challenge_64
, encoded_len
);
909 die("invalid challenge %s", challenge_64
);
910 HMAC_Init(&hmac
, (unsigned char *)pass
, strlen(pass
), EVP_md5());
911 HMAC_Update(&hmac
, (unsigned char *)challenge
, decoded_len
);
912 HMAC_Final(&hmac
, hash
, NULL
);
913 HMAC_CTX_cleanup(&hmac
);
916 for (i
= 0; i
< 16; i
++) {
917 hex
[2 * i
] = hexchar((hash
[i
] >> 4) & 0xf);
918 hex
[2 * i
+ 1] = hexchar(hash
[i
] & 0xf);
921 /* response: "<user> <digest in hex>" */
922 resp_len
= strlen(user
) + 1 + strlen(hex
) + 1;
923 response
= xmalloc(resp_len
);
924 sprintf(response
, "%s %s", user
, hex
);
926 response_64
= xmalloc(ENCODED_SIZE(resp_len
) + 1);
927 encoded_len
= EVP_EncodeBlock((unsigned char *)response_64
,
928 (unsigned char *)response
, resp_len
);
930 die("EVP_EncodeBlock error");
931 response_64
[encoded_len
] = '\0';
932 return (char *)response_64
;
937 static char *cram(const char *challenge_64
, const char *user
, const char *pass
)
939 die("If you want to use CRAM-MD5 authenticate method, "
940 "you have to build git-imap-send with OpenSSL library.");
945 static int auth_cram_md5(struct imap_store
*ctx
, struct imap_cmd
*cmd
, const char *prompt
)
950 response
= cram(prompt
, server
.user
, server
.pass
);
952 ret
= socket_write(&ctx
->imap
->buf
.sock
, response
, strlen(response
));
953 if (ret
!= strlen(response
))
954 return error("IMAP error: sending response failed");
961 static struct imap_store
*imap_open_store(struct imap_server_conf
*srvc
)
963 struct imap_store
*ctx
;
968 ctx
= xcalloc(sizeof(*ctx
), 1);
970 ctx
->imap
= imap
= xcalloc(sizeof(*imap
), 1);
971 imap
->buf
.sock
.fd
[0] = imap
->buf
.sock
.fd
[1] = -1;
972 imap
->in_progress_append
= &imap
->in_progress
;
974 /* open connection to IMAP server */
977 const char *argv
[] = { srvc
->tunnel
, NULL
};
978 struct child_process tunnel
= {NULL
};
980 imap_info("Starting tunnel '%s'... ", srvc
->tunnel
);
983 tunnel
.use_shell
= 1;
986 if (start_command(&tunnel
))
987 die("cannot start proxy %s", argv
[0]);
989 imap
->buf
.sock
.fd
[0] = tunnel
.out
;
990 imap
->buf
.sock
.fd
[1] = tunnel
.in
;
995 struct addrinfo hints
, *ai0
, *ai
;
999 snprintf(portstr
, sizeof(portstr
), "%d", srvc
->port
);
1001 memset(&hints
, 0, sizeof(hints
));
1002 hints
.ai_socktype
= SOCK_STREAM
;
1003 hints
.ai_protocol
= IPPROTO_TCP
;
1005 imap_info("Resolving %s... ", srvc
->host
);
1006 gai
= getaddrinfo(srvc
->host
, portstr
, &hints
, &ai
);
1008 fprintf(stderr
, "getaddrinfo: %s\n", gai_strerror(gai
));
1013 for (ai0
= ai
; ai
; ai
= ai
->ai_next
) {
1014 char addr
[NI_MAXHOST
];
1016 s
= socket(ai
->ai_family
, ai
->ai_socktype
,
1021 getnameinfo(ai
->ai_addr
, ai
->ai_addrlen
, addr
,
1022 sizeof(addr
), NULL
, 0, NI_NUMERICHOST
);
1023 imap_info("Connecting to [%s]:%s... ", addr
, portstr
);
1025 if (connect(s
, ai
->ai_addr
, ai
->ai_addrlen
) < 0) {
1037 struct sockaddr_in addr
;
1039 memset(&addr
, 0, sizeof(addr
));
1040 addr
.sin_port
= htons(srvc
->port
);
1041 addr
.sin_family
= AF_INET
;
1043 imap_info("Resolving %s... ", srvc
->host
);
1044 he
= gethostbyname(srvc
->host
);
1046 perror("gethostbyname");
1051 addr
.sin_addr
.s_addr
= *((int *) he
->h_addr_list
[0]);
1053 s
= socket(PF_INET
, SOCK_STREAM
, 0);
1055 imap_info("Connecting to %s:%hu... ", inet_ntoa(addr
.sin_addr
), ntohs(addr
.sin_port
));
1056 if (connect(s
, (struct sockaddr
*)&addr
, sizeof(addr
))) {
1063 fputs("Error: unable to connect to server.\n", stderr
);
1067 imap
->buf
.sock
.fd
[0] = s
;
1068 imap
->buf
.sock
.fd
[1] = dup(s
);
1070 if (srvc
->use_ssl
&&
1071 ssl_socket_connect(&imap
->buf
.sock
, 0, srvc
->ssl_verify
)) {
1078 /* read the greeting string */
1079 if (buffer_gets(&imap
->buf
, &rsp
)) {
1080 fprintf(stderr
, "IMAP error: no greeting response\n");
1083 arg
= next_arg(&rsp
);
1084 if (!arg
|| *arg
!= '*' || (arg
= next_arg(&rsp
)) == NULL
) {
1085 fprintf(stderr
, "IMAP error: invalid greeting response\n");
1089 if (!strcmp("PREAUTH", arg
))
1091 else if (strcmp("OK", arg
) != 0) {
1092 fprintf(stderr
, "IMAP error: unknown greeting response\n");
1095 parse_response_code(ctx
, NULL
, rsp
);
1096 if (!imap
->caps
&& imap_exec(ctx
, NULL
, "CAPABILITY") != RESP_OK
)
1101 if (!srvc
->use_ssl
&& CAP(STARTTLS
)) {
1102 if (imap_exec(ctx
, NULL
, "STARTTLS") != RESP_OK
)
1104 if (ssl_socket_connect(&imap
->buf
.sock
, 1,
1107 /* capabilities may have changed, so get the new capabilities */
1108 if (imap_exec(ctx
, NULL
, "CAPABILITY") != RESP_OK
)
1112 imap_info("Logging in...\n");
1114 fprintf(stderr
, "Skipping server %s, no user\n", srvc
->host
);
1118 struct strbuf prompt
= STRBUF_INIT
;
1119 strbuf_addf(&prompt
, "Password (%s@%s): ", srvc
->user
, srvc
->host
);
1120 arg
= git_getpass(prompt
.buf
);
1121 strbuf_release(&prompt
);
1123 fprintf(stderr
, "Skipping account %s@%s, no password\n", srvc
->user
, srvc
->host
);
1127 * getpass() returns a pointer to a static buffer. make a copy
1128 * for long term storage.
1130 srvc
->pass
= xstrdup(arg
);
1133 fprintf(stderr
, "Skipping account %s@%s, server forbids LOGIN\n", srvc
->user
, srvc
->host
);
1137 if (srvc
->auth_method
) {
1138 struct imap_cmd_cb cb
;
1140 if (!strcmp(srvc
->auth_method
, "CRAM-MD5")) {
1141 if (!CAP(AUTH_CRAM_MD5
)) {
1142 fprintf(stderr
, "You specified"
1143 "CRAM-MD5 as authentication method, "
1144 "but %s doesn't support it.\n", srvc
->host
);
1149 memset(&cb
, 0, sizeof(cb
));
1150 cb
.cont
= auth_cram_md5
;
1151 if (imap_exec(ctx
, &cb
, "AUTHENTICATE CRAM-MD5") != RESP_OK
) {
1152 fprintf(stderr
, "IMAP error: AUTHENTICATE CRAM-MD5 failed\n");
1156 fprintf(stderr
, "Unknown authentication method:%s\n", srvc
->host
);
1160 if (!imap
->buf
.sock
.ssl
)
1161 imap_warn("*** IMAP Warning *** Password is being "
1162 "sent in the clear\n");
1163 if (imap_exec(ctx
, NULL
, "LOGIN \"%s\" \"%s\"", srvc
->user
, srvc
->pass
) != RESP_OK
) {
1164 fprintf(stderr
, "IMAP error: LOGIN failed\n");
1174 imap_close_store(ctx
);
1179 * Insert CR characters as necessary in *msg to ensure that every LF
1180 * character in *msg is preceded by a CR.
1182 static void lf_to_crlf(struct strbuf
*msg
)
1188 /* First pass: tally, in j, the size of the new string: */
1189 for (i
= j
= 0, lastc
= '\0'; i
< msg
->len
; i
++) {
1190 if (msg
->buf
[i
] == '\n' && lastc
!= '\r')
1191 j
++; /* a CR will need to be added here */
1192 lastc
= msg
->buf
[i
];
1196 new = xmalloc(j
+ 1);
1199 * Second pass: write the new string. Note that this loop is
1200 * otherwise identical to the first pass.
1202 for (i
= j
= 0, lastc
= '\0'; i
< msg
->len
; i
++) {
1203 if (msg
->buf
[i
] == '\n' && lastc
!= '\r')
1205 lastc
= new[j
++] = msg
->buf
[i
];
1207 strbuf_attach(msg
, new, j
, j
+ 1);
1211 * Store msg to IMAP. Also detach and free the data from msg->data,
1212 * leaving msg->data empty.
1214 static int imap_store_msg(struct imap_store
*ctx
, struct strbuf
*msg
)
1216 struct imap
*imap
= ctx
->imap
;
1217 struct imap_cmd_cb cb
;
1218 const char *prefix
, *box
;
1222 memset(&cb
, 0, sizeof(cb
));
1225 cb
.data
= strbuf_detach(msg
, NULL
);
1228 prefix
= !strcmp(box
, "INBOX") ? "" : ctx
->prefix
;
1230 ret
= imap_exec_m(ctx
, &cb
, "APPEND \"%s%s\" ", prefix
, box
);
1231 imap
->caps
= imap
->rcaps
;
1238 static void wrap_in_html(struct strbuf
*msg
)
1240 struct strbuf buf
= STRBUF_INIT
;
1241 static char *content_type
= "Content-Type: text/html;\n";
1242 static char *pre_open
= "<pre>\n";
1243 static char *pre_close
= "</pre>\n";
1244 const char *body
= strstr(msg
->buf
, "\n\n");
1247 return; /* Headers but no body; no wrapping needed */
1251 strbuf_add(&buf
, msg
->buf
, body
- msg
->buf
- 1);
1252 strbuf_addstr(&buf
, content_type
);
1253 strbuf_addch(&buf
, '\n');
1254 strbuf_addstr(&buf
, pre_open
);
1255 strbuf_addstr_xml_quoted(&buf
, body
);
1256 strbuf_addstr(&buf
, pre_close
);
1258 strbuf_release(msg
);
1262 #define CHUNKSIZE 0x1000
1264 static int read_message(FILE *f
, struct strbuf
*all_msgs
)
1267 if (strbuf_fread(all_msgs
, CHUNKSIZE
, f
) <= 0)
1271 return ferror(f
) ? -1 : 0;
1274 static int count_messages(struct strbuf
*all_msgs
)
1277 char *p
= all_msgs
->buf
;
1280 if (!prefixcmp(p
, "From ")) {
1281 p
= strstr(p
+5, "\nFrom: ");
1283 p
= strstr(p
+7, "\nDate: ");
1285 p
= strstr(p
+7, "\nSubject: ");
1290 p
= strstr(p
+5, "\nFrom ");
1299 * Copy the next message from all_msgs, starting at offset *ofs, to
1300 * msg. Update *ofs to the start of the following message. Return
1301 * true iff a message was successfully copied.
1303 static int split_msg(struct strbuf
*all_msgs
, struct strbuf
*msg
, int *ofs
)
1308 if (*ofs
>= all_msgs
->len
)
1311 data
= &all_msgs
->buf
[*ofs
];
1312 len
= all_msgs
->len
- *ofs
;
1314 if (len
< 5 || prefixcmp(data
, "From "))
1317 p
= strchr(data
, '\n');
1325 p
= strstr(data
, "\nFrom ");
1329 strbuf_add(msg
, data
, len
);
1334 static char *imap_folder
;
1336 static int git_imap_config(const char *key
, const char *val
, void *cb
)
1338 char imap_key
[] = "imap.";
1340 if (strncmp(key
, imap_key
, sizeof imap_key
- 1))
1343 key
+= sizeof imap_key
- 1;
1345 /* check booleans first, and barf on others */
1346 if (!strcmp("sslverify", key
))
1347 server
.ssl_verify
= git_config_bool(key
, val
);
1348 else if (!strcmp("preformattedhtml", key
))
1349 server
.use_html
= git_config_bool(key
, val
);
1351 return config_error_nonbool(key
);
1353 if (!strcmp("folder", key
)) {
1354 imap_folder
= xstrdup(val
);
1355 } else if (!strcmp("host", key
)) {
1356 if (!prefixcmp(val
, "imap:"))
1358 else if (!prefixcmp(val
, "imaps:")) {
1362 if (!prefixcmp(val
, "//"))
1364 server
.host
= xstrdup(val
);
1365 } else if (!strcmp("user", key
))
1366 server
.user
= xstrdup(val
);
1367 else if (!strcmp("pass", key
))
1368 server
.pass
= xstrdup(val
);
1369 else if (!strcmp("port", key
))
1370 server
.port
= git_config_int(key
, val
);
1371 else if (!strcmp("tunnel", key
))
1372 server
.tunnel
= xstrdup(val
);
1373 else if (!strcmp("authmethod", key
))
1374 server
.auth_method
= xstrdup(val
);
1379 int main(int argc
, char **argv
)
1381 struct strbuf all_msgs
= STRBUF_INIT
;
1382 struct strbuf msg
= STRBUF_INIT
;
1383 struct imap_store
*ctx
= NULL
;
1389 git_extract_argv0_path(argv
[0]);
1391 git_setup_gettext();
1394 usage(imap_send_usage
);
1396 setup_git_directory_gently(&nongit_ok
);
1397 git_config(git_imap_config
, NULL
);
1400 server
.port
= server
.use_ssl
? 993 : 143;
1403 fprintf(stderr
, "no imap store specified\n");
1407 if (!server
.tunnel
) {
1408 fprintf(stderr
, "no imap host specified\n");
1411 server
.host
= "tunnel";
1414 /* read the messages */
1415 if (read_message(stdin
, &all_msgs
)) {
1416 fprintf(stderr
, "error reading input\n");
1420 if (all_msgs
.len
== 0) {
1421 fprintf(stderr
, "nothing to send\n");
1425 total
= count_messages(&all_msgs
);
1427 fprintf(stderr
, "no messages to send\n");
1431 /* write it to the imap server */
1432 ctx
= imap_open_store(&server
);
1434 fprintf(stderr
, "failed to open store\n");
1438 fprintf(stderr
, "sending %d message%s\n", total
, (total
!= 1) ? "s" : "");
1439 ctx
->name
= imap_folder
;
1441 unsigned percent
= n
* 100 / total
;
1443 fprintf(stderr
, "%4u%% (%d/%d) done\r", percent
, n
, total
);
1444 if (!split_msg(&all_msgs
, &msg
, &ofs
))
1446 if (server
.use_html
)
1448 r
= imap_store_msg(ctx
, &msg
);
1453 fprintf(stderr
, "\n");
1455 imap_close_store(ctx
);