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 #include <openssl/evp.h>
33 #include <openssl/hmac.h>
34 #include <openssl/x509v3.h>
37 static const char imap_send_usage
[] = "git imap-send < <mbox>";
41 #define DRV_MSG_BAD -1
42 #define DRV_BOX_BAD -2
43 #define DRV_STORE_BAD -3
45 static int Verbose
, Quiet
;
47 __attribute__((format (printf
, 1, 2)))
48 static void imap_info(const char *, ...);
49 __attribute__((format (printf
, 1, 2)))
50 static void imap_warn(const char *, ...);
52 static char *next_arg(char **);
54 __attribute__((format (printf
, 3, 4)))
55 static int nfsnprintf(char *buf
, int blen
, const char *fmt
, ...);
57 static int nfvasprintf(char **strp
, const char *fmt
, va_list ap
)
62 len
= vsnprintf(tmp
, sizeof(tmp
), fmt
, ap
);
64 die("Fatal: Out of memory");
65 if (len
>= sizeof(tmp
))
66 die("imap command overflow!");
67 *strp
= xmemdupz(tmp
, len
);
71 struct imap_server_conf
{
84 static struct imap_server_conf server
= {
94 NULL
, /* auth_method */
103 struct imap_socket sock
;
112 int uidnext
; /* from SELECT responses */
113 unsigned caps
, rcaps
; /* CAPABILITY results */
115 int nexttag
, num_in_progress
, literal_pending
;
116 struct imap_cmd
*in_progress
, **in_progress_append
;
117 struct imap_buffer buf
; /* this is BIG, so put it last */
121 /* currently open mailbox */
122 const char *name
; /* foreign! maybe preset? */
129 int (*cont
)(struct imap_store
*ctx
, struct imap_cmd
*cmd
, const char *prompt
);
130 void (*done
)(struct imap_store
*ctx
, struct imap_cmd
*cmd
, int response
);
135 unsigned create
:1, trycreate
:1;
139 struct imap_cmd
*next
;
140 struct imap_cmd_cb cb
;
145 #define CAP(cap) (imap->caps & (1 << (cap)))
156 static const char *cap_list
[] = {
169 static int get_cmd_result(struct imap_store
*ctx
, struct imap_cmd
*tcmd
);
173 static void ssl_socket_perror(const char *func
)
175 fprintf(stderr
, "%s: %s\n", func
, ERR_error_string(ERR_get_error(), NULL
));
179 static void socket_perror(const char *func
, struct imap_socket
*sock
, int ret
)
183 int sslerr
= SSL_get_error(sock
->ssl
, ret
);
187 case SSL_ERROR_SYSCALL
:
188 perror("SSL_connect");
191 ssl_socket_perror("SSL_connect");
200 fprintf(stderr
, "%s: unexpected EOF\n", func
);
205 static int ssl_socket_connect(struct imap_socket
*sock
, int use_tls_only
, int verify
)
207 fprintf(stderr
, "SSL requested but SSL support not compiled in\n");
213 static int host_matches(const char *host
, const char *pattern
)
215 if (pattern
[0] == '*' && pattern
[1] == '.') {
217 if (!(host
= strchr(host
, '.')))
222 return *host
&& *pattern
&& !strcasecmp(host
, pattern
);
225 static int verify_hostname(X509
*cert
, const char *hostname
)
231 STACK_OF(GENERAL_NAME
) *subj_alt_names
;
233 /* try the DNS subjectAltNames */
235 if ((subj_alt_names
= X509_get_ext_d2i(cert
, NID_subject_alt_name
, NULL
, NULL
))) {
236 int num_subj_alt_names
= sk_GENERAL_NAME_num(subj_alt_names
);
237 for (i
= 0; !found
&& i
< num_subj_alt_names
; i
++) {
238 GENERAL_NAME
*subj_alt_name
= sk_GENERAL_NAME_value(subj_alt_names
, i
);
239 if (subj_alt_name
->type
== GEN_DNS
&&
240 strlen((const char *)subj_alt_name
->d
.ia5
->data
) == (size_t)subj_alt_name
->d
.ia5
->length
&&
241 host_matches(hostname
, (const char *)(subj_alt_name
->d
.ia5
->data
)))
244 sk_GENERAL_NAME_pop_free(subj_alt_names
, GENERAL_NAME_free
);
249 /* try the common name */
250 if (!(subj
= X509_get_subject_name(cert
)))
251 return error("cannot get certificate subject");
252 if ((len
= X509_NAME_get_text_by_NID(subj
, NID_commonName
, cname
, sizeof(cname
))) < 0)
253 return error("cannot get certificate common name");
254 if (strlen(cname
) == (size_t)len
&& host_matches(hostname
, cname
))
256 return error("certificate owner '%s' does not match hostname '%s'",
260 static int ssl_socket_connect(struct imap_socket
*sock
, int use_tls_only
, int verify
)
262 #if (OPENSSL_VERSION_NUMBER >= 0x10000000L)
263 const SSL_METHOD
*meth
;
272 SSL_load_error_strings();
275 meth
= TLSv1_method();
277 meth
= SSLv23_method();
280 ssl_socket_perror("SSLv23_method");
284 ctx
= SSL_CTX_new(meth
);
287 SSL_CTX_set_verify(ctx
, SSL_VERIFY_PEER
, NULL
);
289 if (!SSL_CTX_set_default_verify_paths(ctx
)) {
290 ssl_socket_perror("SSL_CTX_set_default_verify_paths");
293 sock
->ssl
= SSL_new(ctx
);
295 ssl_socket_perror("SSL_new");
298 if (!SSL_set_rfd(sock
->ssl
, sock
->fd
[0])) {
299 ssl_socket_perror("SSL_set_rfd");
302 if (!SSL_set_wfd(sock
->ssl
, sock
->fd
[1])) {
303 ssl_socket_perror("SSL_set_wfd");
307 #ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
310 * OpenSSL does not document this function, but the implementation
311 * returns 1 on success, 0 on failure after calling SSLerr().
313 ret
= SSL_set_tlsext_host_name(sock
->ssl
, server
.host
);
315 warning("SSL_set_tlsext_host_name(%s) failed.", server
.host
);
318 ret
= SSL_connect(sock
->ssl
);
320 socket_perror("SSL_connect", sock
, ret
);
325 /* make sure the hostname matches that of the certificate */
326 cert
= SSL_get_peer_certificate(sock
->ssl
);
328 return error("unable to get peer certificate.");
329 if (verify_hostname(cert
, server
.host
) < 0)
337 static int socket_read(struct imap_socket
*sock
, char *buf
, int len
)
342 n
= SSL_read(sock
->ssl
, buf
, len
);
345 n
= xread(sock
->fd
[0], buf
, len
);
347 socket_perror("read", sock
, n
);
350 sock
->fd
[0] = sock
->fd
[1] = -1;
355 static int socket_write(struct imap_socket
*sock
, const char *buf
, int len
)
360 n
= SSL_write(sock
->ssl
, buf
, len
);
363 n
= write_in_full(sock
->fd
[1], buf
, len
);
365 socket_perror("write", sock
, n
);
368 sock
->fd
[0] = sock
->fd
[1] = -1;
373 static void socket_shutdown(struct imap_socket
*sock
)
377 SSL_shutdown(sock
->ssl
);
385 /* simple line buffering */
386 static int buffer_gets(struct imap_buffer
*b
, char **s
)
389 int start
= b
->offset
;
394 /* make sure we have enough data to read the \r\n sequence */
395 if (b
->offset
+ 1 >= b
->bytes
) {
397 /* shift down used bytes */
400 assert(start
<= b
->bytes
);
401 n
= b
->bytes
- start
;
404 memmove(b
->buf
, b
->buf
+ start
, n
);
410 n
= socket_read(&b
->sock
, b
->buf
+ b
->bytes
,
411 sizeof(b
->buf
) - b
->bytes
);
419 if (b
->buf
[b
->offset
] == '\r') {
420 assert(b
->offset
+ 1 < b
->bytes
);
421 if (b
->buf
[b
->offset
+ 1] == '\n') {
422 b
->buf
[b
->offset
] = 0; /* terminate the string */
423 b
->offset
+= 2; /* next line */
435 static void imap_info(const char *msg
, ...)
447 static void imap_warn(const char *msg
, ...)
453 vfprintf(stderr
, msg
, va
);
458 static char *next_arg(char **s
)
464 while (isspace((unsigned char) **s
))
473 *s
= strchr(*s
, '"');
476 while (**s
&& !isspace((unsigned char) **s
))
488 static int nfsnprintf(char *buf
, int blen
, const char *fmt
, ...)
494 if (blen
<= 0 || (unsigned)(ret
= vsnprintf(buf
, blen
, fmt
, va
)) >= (unsigned)blen
)
495 die("Fatal: buffer too small. Please report a bug.");
500 static struct imap_cmd
*v_issue_imap_cmd(struct imap_store
*ctx
,
501 struct imap_cmd_cb
*cb
,
502 const char *fmt
, va_list ap
)
504 struct imap
*imap
= ctx
->imap
;
505 struct imap_cmd
*cmd
;
509 cmd
= xmalloc(sizeof(struct imap_cmd
));
510 nfvasprintf(&cmd
->cmd
, fmt
, ap
);
511 cmd
->tag
= ++imap
->nexttag
;
516 memset(&cmd
->cb
, 0, sizeof(cmd
->cb
));
518 while (imap
->literal_pending
)
519 get_cmd_result(ctx
, NULL
);
522 bufl
= nfsnprintf(buf
, sizeof(buf
), "%d %s\r\n", cmd
->tag
, cmd
->cmd
);
524 bufl
= nfsnprintf(buf
, sizeof(buf
), "%d %s{%d%s}\r\n",
525 cmd
->tag
, cmd
->cmd
, cmd
->cb
.dlen
,
526 CAP(LITERALPLUS
) ? "+" : "");
529 if (imap
->num_in_progress
)
530 printf("(%d in progress) ", imap
->num_in_progress
);
531 if (memcmp(cmd
->cmd
, "LOGIN", 5))
532 printf(">>> %s", buf
);
534 printf(">>> %d LOGIN <user> <pass>\n", cmd
->tag
);
536 if (socket_write(&imap
->buf
.sock
, buf
, bufl
) != bufl
) {
544 if (CAP(LITERALPLUS
)) {
545 n
= socket_write(&imap
->buf
.sock
, cmd
->cb
.data
, cmd
->cb
.dlen
);
547 if (n
!= cmd
->cb
.dlen
||
548 socket_write(&imap
->buf
.sock
, "\r\n", 2) != 2) {
555 imap
->literal_pending
= 1;
556 } else if (cmd
->cb
.cont
)
557 imap
->literal_pending
= 1;
559 *imap
->in_progress_append
= cmd
;
560 imap
->in_progress_append
= &cmd
->next
;
561 imap
->num_in_progress
++;
565 __attribute__((format (printf
, 3, 4)))
566 static struct imap_cmd
*issue_imap_cmd(struct imap_store
*ctx
,
567 struct imap_cmd_cb
*cb
,
568 const char *fmt
, ...)
570 struct imap_cmd
*ret
;
574 ret
= v_issue_imap_cmd(ctx
, cb
, fmt
, ap
);
579 __attribute__((format (printf
, 3, 4)))
580 static int imap_exec(struct imap_store
*ctx
, struct imap_cmd_cb
*cb
,
581 const char *fmt
, ...)
584 struct imap_cmd
*cmdp
;
587 cmdp
= v_issue_imap_cmd(ctx
, cb
, fmt
, ap
);
592 return get_cmd_result(ctx
, cmdp
);
595 __attribute__((format (printf
, 3, 4)))
596 static int imap_exec_m(struct imap_store
*ctx
, struct imap_cmd_cb
*cb
,
597 const char *fmt
, ...)
600 struct imap_cmd
*cmdp
;
603 cmdp
= v_issue_imap_cmd(ctx
, cb
, fmt
, ap
);
606 return DRV_STORE_BAD
;
608 switch (get_cmd_result(ctx
, cmdp
)) {
609 case RESP_BAD
: return DRV_STORE_BAD
;
610 case RESP_NO
: return DRV_MSG_BAD
;
611 default: return DRV_OK
;
615 static int skip_imap_list_l(char **sp
, int level
)
620 while (isspace((unsigned char)*s
))
622 if (level
&& *s
== ')') {
629 if (skip_imap_list_l(&s
, level
+ 1))
631 } else if (*s
== '"') {
634 for (; *s
!= '"'; s
++)
640 for (; *s
&& !isspace((unsigned char)*s
); s
++)
641 if (level
&& *s
== ')')
657 static void skip_list(char **sp
)
659 skip_imap_list_l(sp
, 0);
662 static void parse_capability(struct imap
*imap
, char *cmd
)
667 imap
->caps
= 0x80000000;
668 while ((arg
= next_arg(&cmd
)))
669 for (i
= 0; i
< ARRAY_SIZE(cap_list
); i
++)
670 if (!strcmp(cap_list
[i
], arg
))
671 imap
->caps
|= 1 << i
;
672 imap
->rcaps
= imap
->caps
;
675 static int parse_response_code(struct imap_store
*ctx
, struct imap_cmd_cb
*cb
,
678 struct imap
*imap
= ctx
->imap
;
682 return RESP_OK
; /* no response code */
684 if (!(p
= strchr(s
, ']'))) {
685 fprintf(stderr
, "IMAP error: malformed response code\n");
690 if (!strcmp("UIDVALIDITY", arg
)) {
691 if (!(arg
= next_arg(&s
)) || !(ctx
->uidvalidity
= atoi(arg
))) {
692 fprintf(stderr
, "IMAP error: malformed UIDVALIDITY status\n");
695 } else if (!strcmp("UIDNEXT", arg
)) {
696 if (!(arg
= next_arg(&s
)) || !(imap
->uidnext
= atoi(arg
))) {
697 fprintf(stderr
, "IMAP error: malformed NEXTUID status\n");
700 } else if (!strcmp("CAPABILITY", arg
)) {
701 parse_capability(imap
, s
);
702 } else if (!strcmp("ALERT", arg
)) {
703 /* RFC2060 says that these messages MUST be displayed
706 for (; isspace((unsigned char)*p
); p
++);
707 fprintf(stderr
, "*** IMAP ALERT *** %s\n", p
);
708 } else if (cb
&& cb
->ctx
&& !strcmp("APPENDUID", arg
)) {
709 if (!(arg
= next_arg(&s
)) || !(ctx
->uidvalidity
= atoi(arg
)) ||
710 !(arg
= next_arg(&s
)) || !(*(int *)cb
->ctx
= atoi(arg
))) {
711 fprintf(stderr
, "IMAP error: malformed APPENDUID status\n");
718 static int get_cmd_result(struct imap_store
*ctx
, struct imap_cmd
*tcmd
)
720 struct imap
*imap
= ctx
->imap
;
721 struct imap_cmd
*cmdp
, **pcmdp
, *ncmdp
;
722 char *cmd
, *arg
, *arg1
, *p
;
723 int n
, resp
, resp2
, tag
;
726 if (buffer_gets(&imap
->buf
, &cmd
))
729 arg
= next_arg(&cmd
);
731 arg
= next_arg(&cmd
);
733 fprintf(stderr
, "IMAP error: unable to parse untagged response\n");
737 if (!strcmp("NAMESPACE", arg
)) {
738 /* rfc2342 NAMESPACE response. */
739 skip_list(&cmd
); /* Personal mailboxes */
740 skip_list(&cmd
); /* Others' mailboxes */
741 skip_list(&cmd
); /* Shared mailboxes */
742 } else if (!strcmp("OK", arg
) || !strcmp("BAD", arg
) ||
743 !strcmp("NO", arg
) || !strcmp("BYE", arg
)) {
744 if ((resp
= parse_response_code(ctx
, NULL
, cmd
)) != RESP_OK
)
746 } else if (!strcmp("CAPABILITY", arg
)) {
747 parse_capability(imap
, cmd
);
748 } else if ((arg1
= next_arg(&cmd
))) {
750 * Unhandled response-data with at least two words.
753 * NEEDSWORK: Previously this case handled '<num> EXISTS'
754 * and '<num> RECENT' but as a probably-unintended side
755 * effect it ignores other unrecognized two-word
756 * responses. imap-send doesn't ever try to read
757 * messages or mailboxes these days, so consider
758 * eliminating this case.
761 fprintf(stderr
, "IMAP error: unable to parse untagged response\n");
764 } else if (!imap
->in_progress
) {
765 fprintf(stderr
, "IMAP error: unexpected reply: %s %s\n", arg
, cmd
? cmd
: "");
767 } else if (*arg
== '+') {
768 /* This can happen only with the last command underway, as
769 it enforces a round-trip. */
770 cmdp
= (struct imap_cmd
*)((char *)imap
->in_progress_append
-
771 offsetof(struct imap_cmd
, next
));
773 n
= socket_write(&imap
->buf
.sock
, cmdp
->cb
.data
, cmdp
->cb
.dlen
);
775 cmdp
->cb
.data
= NULL
;
776 if (n
!= (int)cmdp
->cb
.dlen
)
778 } else if (cmdp
->cb
.cont
) {
779 if (cmdp
->cb
.cont(ctx
, cmdp
, cmd
))
782 fprintf(stderr
, "IMAP error: unexpected command continuation request\n");
785 if (socket_write(&imap
->buf
.sock
, "\r\n", 2) != 2)
788 imap
->literal_pending
= 0;
793 for (pcmdp
= &imap
->in_progress
; (cmdp
= *pcmdp
); pcmdp
= &cmdp
->next
)
794 if (cmdp
->tag
== tag
)
796 fprintf(stderr
, "IMAP error: unexpected tag %s\n", arg
);
799 if (!(*pcmdp
= cmdp
->next
))
800 imap
->in_progress_append
= pcmdp
;
801 imap
->num_in_progress
--;
802 if (cmdp
->cb
.cont
|| cmdp
->cb
.data
)
803 imap
->literal_pending
= 0;
804 arg
= next_arg(&cmd
);
805 if (!strcmp("OK", arg
))
808 if (!strcmp("NO", arg
)) {
809 if (cmdp
->cb
.create
&& cmd
&& (cmdp
->cb
.trycreate
|| !memcmp(cmd
, "[TRYCREATE]", 11))) { /* SELECT, APPEND or UID COPY */
810 p
= strchr(cmdp
->cmd
, '"');
811 if (!issue_imap_cmd(ctx
, NULL
, "CREATE \"%.*s\"", (int)(strchr(p
+ 1, '"') - p
+ 1), p
)) {
815 /* not waiting here violates the spec, but a server that does not
816 grok this nonetheless violates it too. */
818 if (!(ncmdp
= issue_imap_cmd(ctx
, &cmdp
->cb
, "%s", cmdp
->cmd
))) {
825 return 0; /* ignored */
831 } else /*if (!strcmp("BAD", arg))*/
833 fprintf(stderr
, "IMAP command '%s' returned response (%s) - %s\n",
834 memcmp(cmdp
->cmd
, "LOGIN", 5) ?
835 cmdp
->cmd
: "LOGIN <user> <pass>",
836 arg
, cmd
? cmd
: "");
838 if ((resp2
= parse_response_code(ctx
, &cmdp
->cb
, cmd
)) > resp
)
842 cmdp
->cb
.done(ctx
, cmdp
, resp
);
846 if (!tcmd
|| tcmd
== cmdp
)
853 static void imap_close_server(struct imap_store
*ictx
)
855 struct imap
*imap
= ictx
->imap
;
857 if (imap
->buf
.sock
.fd
[0] != -1) {
858 imap_exec(ictx
, NULL
, "LOGOUT");
859 socket_shutdown(&imap
->buf
.sock
);
864 static void imap_close_store(struct imap_store
*ctx
)
866 imap_close_server(ctx
);
873 * hexchar() and cram() functions are based on the code from the isync
874 * project (http://isync.sf.net/).
876 static char hexchar(unsigned int b
)
878 return b
< 10 ? '0' + b
: 'a' + (b
- 10);
881 #define ENCODED_SIZE(n) (4*((n+2)/3))
882 static char *cram(const char *challenge_64
, const char *user
, const char *pass
)
884 int i
, resp_len
, encoded_len
, decoded_len
;
886 unsigned char hash
[16];
888 char *response
, *response_64
, *challenge
;
891 * length of challenge_64 (i.e. base-64 encoded string) is a good
892 * enough upper bound for challenge (decoded result).
894 encoded_len
= strlen(challenge_64
);
895 challenge
= xmalloc(encoded_len
);
896 decoded_len
= EVP_DecodeBlock((unsigned char *)challenge
,
897 (unsigned char *)challenge_64
, encoded_len
);
899 die("invalid challenge %s", challenge_64
);
900 HMAC_Init(&hmac
, (unsigned char *)pass
, strlen(pass
), EVP_md5());
901 HMAC_Update(&hmac
, (unsigned char *)challenge
, decoded_len
);
902 HMAC_Final(&hmac
, hash
, NULL
);
903 HMAC_CTX_cleanup(&hmac
);
906 for (i
= 0; i
< 16; i
++) {
907 hex
[2 * i
] = hexchar((hash
[i
] >> 4) & 0xf);
908 hex
[2 * i
+ 1] = hexchar(hash
[i
] & 0xf);
911 /* response: "<user> <digest in hex>" */
912 resp_len
= strlen(user
) + 1 + strlen(hex
) + 1;
913 response
= xmalloc(resp_len
);
914 sprintf(response
, "%s %s", user
, hex
);
916 response_64
= xmalloc(ENCODED_SIZE(resp_len
) + 1);
917 encoded_len
= EVP_EncodeBlock((unsigned char *)response_64
,
918 (unsigned char *)response
, resp_len
);
920 die("EVP_EncodeBlock error");
921 response_64
[encoded_len
] = '\0';
922 return (char *)response_64
;
927 static char *cram(const char *challenge_64
, const char *user
, const char *pass
)
929 die("If you want to use CRAM-MD5 authenticate method, "
930 "you have to build git-imap-send with OpenSSL library.");
935 static int auth_cram_md5(struct imap_store
*ctx
, struct imap_cmd
*cmd
, const char *prompt
)
940 response
= cram(prompt
, server
.user
, server
.pass
);
942 ret
= socket_write(&ctx
->imap
->buf
.sock
, response
, strlen(response
));
943 if (ret
!= strlen(response
))
944 return error("IMAP error: sending response failed");
951 static struct imap_store
*imap_open_store(struct imap_server_conf
*srvc
)
953 struct imap_store
*ctx
;
958 ctx
= xcalloc(sizeof(*ctx
), 1);
960 ctx
->imap
= imap
= xcalloc(sizeof(*imap
), 1);
961 imap
->buf
.sock
.fd
[0] = imap
->buf
.sock
.fd
[1] = -1;
962 imap
->in_progress_append
= &imap
->in_progress
;
964 /* open connection to IMAP server */
967 const char *argv
[] = { srvc
->tunnel
, NULL
};
968 struct child_process tunnel
= {NULL
};
970 imap_info("Starting tunnel '%s'... ", srvc
->tunnel
);
973 tunnel
.use_shell
= 1;
976 if (start_command(&tunnel
))
977 die("cannot start proxy %s", argv
[0]);
979 imap
->buf
.sock
.fd
[0] = tunnel
.out
;
980 imap
->buf
.sock
.fd
[1] = tunnel
.in
;
985 struct addrinfo hints
, *ai0
, *ai
;
989 snprintf(portstr
, sizeof(portstr
), "%d", srvc
->port
);
991 memset(&hints
, 0, sizeof(hints
));
992 hints
.ai_socktype
= SOCK_STREAM
;
993 hints
.ai_protocol
= IPPROTO_TCP
;
995 imap_info("Resolving %s... ", srvc
->host
);
996 gai
= getaddrinfo(srvc
->host
, portstr
, &hints
, &ai
);
998 fprintf(stderr
, "getaddrinfo: %s\n", gai_strerror(gai
));
1003 for (ai0
= ai
; ai
; ai
= ai
->ai_next
) {
1004 char addr
[NI_MAXHOST
];
1006 s
= socket(ai
->ai_family
, ai
->ai_socktype
,
1011 getnameinfo(ai
->ai_addr
, ai
->ai_addrlen
, addr
,
1012 sizeof(addr
), NULL
, 0, NI_NUMERICHOST
);
1013 imap_info("Connecting to [%s]:%s... ", addr
, portstr
);
1015 if (connect(s
, ai
->ai_addr
, ai
->ai_addrlen
) < 0) {
1027 struct sockaddr_in addr
;
1029 memset(&addr
, 0, sizeof(addr
));
1030 addr
.sin_port
= htons(srvc
->port
);
1031 addr
.sin_family
= AF_INET
;
1033 imap_info("Resolving %s... ", srvc
->host
);
1034 he
= gethostbyname(srvc
->host
);
1036 perror("gethostbyname");
1041 addr
.sin_addr
.s_addr
= *((int *) he
->h_addr_list
[0]);
1043 s
= socket(PF_INET
, SOCK_STREAM
, 0);
1045 imap_info("Connecting to %s:%hu... ", inet_ntoa(addr
.sin_addr
), ntohs(addr
.sin_port
));
1046 if (connect(s
, (struct sockaddr
*)&addr
, sizeof(addr
))) {
1053 fputs("Error: unable to connect to server.\n", stderr
);
1057 imap
->buf
.sock
.fd
[0] = s
;
1058 imap
->buf
.sock
.fd
[1] = dup(s
);
1060 if (srvc
->use_ssl
&&
1061 ssl_socket_connect(&imap
->buf
.sock
, 0, srvc
->ssl_verify
)) {
1068 /* read the greeting string */
1069 if (buffer_gets(&imap
->buf
, &rsp
)) {
1070 fprintf(stderr
, "IMAP error: no greeting response\n");
1073 arg
= next_arg(&rsp
);
1074 if (!arg
|| *arg
!= '*' || (arg
= next_arg(&rsp
)) == NULL
) {
1075 fprintf(stderr
, "IMAP error: invalid greeting response\n");
1079 if (!strcmp("PREAUTH", arg
))
1081 else if (strcmp("OK", arg
) != 0) {
1082 fprintf(stderr
, "IMAP error: unknown greeting response\n");
1085 parse_response_code(ctx
, NULL
, rsp
);
1086 if (!imap
->caps
&& imap_exec(ctx
, NULL
, "CAPABILITY") != RESP_OK
)
1091 if (!srvc
->use_ssl
&& CAP(STARTTLS
)) {
1092 if (imap_exec(ctx
, NULL
, "STARTTLS") != RESP_OK
)
1094 if (ssl_socket_connect(&imap
->buf
.sock
, 1,
1097 /* capabilities may have changed, so get the new capabilities */
1098 if (imap_exec(ctx
, NULL
, "CAPABILITY") != RESP_OK
)
1102 imap_info("Logging in...\n");
1104 fprintf(stderr
, "Skipping server %s, no user\n", srvc
->host
);
1108 struct strbuf prompt
= STRBUF_INIT
;
1109 strbuf_addf(&prompt
, "Password (%s@%s): ", srvc
->user
, srvc
->host
);
1110 arg
= git_getpass(prompt
.buf
);
1111 strbuf_release(&prompt
);
1113 fprintf(stderr
, "Skipping account %s@%s, no password\n", srvc
->user
, srvc
->host
);
1117 * getpass() returns a pointer to a static buffer. make a copy
1118 * for long term storage.
1120 srvc
->pass
= xstrdup(arg
);
1123 fprintf(stderr
, "Skipping account %s@%s, server forbids LOGIN\n", srvc
->user
, srvc
->host
);
1127 if (srvc
->auth_method
) {
1128 struct imap_cmd_cb cb
;
1130 if (!strcmp(srvc
->auth_method
, "CRAM-MD5")) {
1131 if (!CAP(AUTH_CRAM_MD5
)) {
1132 fprintf(stderr
, "You specified"
1133 "CRAM-MD5 as authentication method, "
1134 "but %s doesn't support it.\n", srvc
->host
);
1139 memset(&cb
, 0, sizeof(cb
));
1140 cb
.cont
= auth_cram_md5
;
1141 if (imap_exec(ctx
, &cb
, "AUTHENTICATE CRAM-MD5") != RESP_OK
) {
1142 fprintf(stderr
, "IMAP error: AUTHENTICATE CRAM-MD5 failed\n");
1146 fprintf(stderr
, "Unknown authentication method:%s\n", srvc
->host
);
1150 if (!imap
->buf
.sock
.ssl
)
1151 imap_warn("*** IMAP Warning *** Password is being "
1152 "sent in the clear\n");
1153 if (imap_exec(ctx
, NULL
, "LOGIN \"%s\" \"%s\"", srvc
->user
, srvc
->pass
) != RESP_OK
) {
1154 fprintf(stderr
, "IMAP error: LOGIN failed\n");
1164 imap_close_store(ctx
);
1169 * Insert CR characters as necessary in *msg to ensure that every LF
1170 * character in *msg is preceded by a CR.
1172 static void lf_to_crlf(struct strbuf
*msg
)
1178 /* First pass: tally, in j, the size of the new string: */
1179 for (i
= j
= 0, lastc
= '\0'; i
< msg
->len
; i
++) {
1180 if (msg
->buf
[i
] == '\n' && lastc
!= '\r')
1181 j
++; /* a CR will need to be added here */
1182 lastc
= msg
->buf
[i
];
1186 new = xmalloc(j
+ 1);
1189 * Second pass: write the new string. Note that this loop is
1190 * otherwise identical to the first pass.
1192 for (i
= j
= 0, lastc
= '\0'; i
< msg
->len
; i
++) {
1193 if (msg
->buf
[i
] == '\n' && lastc
!= '\r')
1195 lastc
= new[j
++] = msg
->buf
[i
];
1197 strbuf_attach(msg
, new, j
, j
+ 1);
1201 * Store msg to IMAP. Also detach and free the data from msg->data,
1202 * leaving msg->data empty.
1204 static int imap_store_msg(struct imap_store
*ctx
, struct strbuf
*msg
)
1206 struct imap
*imap
= ctx
->imap
;
1207 struct imap_cmd_cb cb
;
1208 const char *prefix
, *box
;
1212 memset(&cb
, 0, sizeof(cb
));
1215 cb
.data
= strbuf_detach(msg
, NULL
);
1218 prefix
= !strcmp(box
, "INBOX") ? "" : ctx
->prefix
;
1220 ret
= imap_exec_m(ctx
, &cb
, "APPEND \"%s%s\" ", prefix
, box
);
1221 imap
->caps
= imap
->rcaps
;
1228 static void wrap_in_html(struct strbuf
*msg
)
1230 struct strbuf buf
= STRBUF_INIT
;
1231 static char *content_type
= "Content-Type: text/html;\n";
1232 static char *pre_open
= "<pre>\n";
1233 static char *pre_close
= "</pre>\n";
1234 const char *body
= strstr(msg
->buf
, "\n\n");
1237 return; /* Headers but no body; no wrapping needed */
1241 strbuf_add(&buf
, msg
->buf
, body
- msg
->buf
- 1);
1242 strbuf_addstr(&buf
, content_type
);
1243 strbuf_addch(&buf
, '\n');
1244 strbuf_addstr(&buf
, pre_open
);
1245 strbuf_addstr_xml_quoted(&buf
, body
);
1246 strbuf_addstr(&buf
, pre_close
);
1248 strbuf_release(msg
);
1252 #define CHUNKSIZE 0x1000
1254 static int read_message(FILE *f
, struct strbuf
*all_msgs
)
1257 if (strbuf_fread(all_msgs
, CHUNKSIZE
, f
) <= 0)
1261 return ferror(f
) ? -1 : 0;
1264 static int count_messages(struct strbuf
*all_msgs
)
1267 char *p
= all_msgs
->buf
;
1270 if (!prefixcmp(p
, "From ")) {
1271 p
= strstr(p
+5, "\nFrom: ");
1273 p
= strstr(p
+7, "\nDate: ");
1275 p
= strstr(p
+7, "\nSubject: ");
1280 p
= strstr(p
+5, "\nFrom ");
1289 * Copy the next message from all_msgs, starting at offset *ofs, to
1290 * msg. Update *ofs to the start of the following message. Return
1291 * true iff a message was successfully copied.
1293 static int split_msg(struct strbuf
*all_msgs
, struct strbuf
*msg
, int *ofs
)
1298 if (*ofs
>= all_msgs
->len
)
1301 data
= &all_msgs
->buf
[*ofs
];
1302 len
= all_msgs
->len
- *ofs
;
1304 if (len
< 5 || prefixcmp(data
, "From "))
1307 p
= strchr(data
, '\n');
1315 p
= strstr(data
, "\nFrom ");
1319 strbuf_add(msg
, data
, len
);
1324 static char *imap_folder
;
1326 static int git_imap_config(const char *key
, const char *val
, void *cb
)
1328 char imap_key
[] = "imap.";
1330 if (strncmp(key
, imap_key
, sizeof imap_key
- 1))
1333 key
+= sizeof imap_key
- 1;
1335 /* check booleans first, and barf on others */
1336 if (!strcmp("sslverify", key
))
1337 server
.ssl_verify
= git_config_bool(key
, val
);
1338 else if (!strcmp("preformattedhtml", key
))
1339 server
.use_html
= git_config_bool(key
, val
);
1341 return config_error_nonbool(key
);
1343 if (!strcmp("folder", key
)) {
1344 imap_folder
= xstrdup(val
);
1345 } else if (!strcmp("host", key
)) {
1346 if (!prefixcmp(val
, "imap:"))
1348 else if (!prefixcmp(val
, "imaps:")) {
1352 if (!prefixcmp(val
, "//"))
1354 server
.host
= xstrdup(val
);
1355 } else if (!strcmp("user", key
))
1356 server
.user
= xstrdup(val
);
1357 else if (!strcmp("pass", key
))
1358 server
.pass
= xstrdup(val
);
1359 else if (!strcmp("port", key
))
1360 server
.port
= git_config_int(key
, val
);
1361 else if (!strcmp("tunnel", key
))
1362 server
.tunnel
= xstrdup(val
);
1363 else if (!strcmp("authmethod", key
))
1364 server
.auth_method
= xstrdup(val
);
1369 int main(int argc
, char **argv
)
1371 struct strbuf all_msgs
= STRBUF_INIT
;
1372 struct strbuf msg
= STRBUF_INIT
;
1373 struct imap_store
*ctx
= NULL
;
1379 git_extract_argv0_path(argv
[0]);
1381 git_setup_gettext();
1384 usage(imap_send_usage
);
1386 setup_git_directory_gently(&nongit_ok
);
1387 git_config(git_imap_config
, NULL
);
1390 server
.port
= server
.use_ssl
? 993 : 143;
1393 fprintf(stderr
, "no imap store specified\n");
1397 if (!server
.tunnel
) {
1398 fprintf(stderr
, "no imap host specified\n");
1401 server
.host
= "tunnel";
1404 /* read the messages */
1405 if (read_message(stdin
, &all_msgs
)) {
1406 fprintf(stderr
, "error reading input\n");
1410 if (all_msgs
.len
== 0) {
1411 fprintf(stderr
, "nothing to send\n");
1415 total
= count_messages(&all_msgs
);
1417 fprintf(stderr
, "no messages to send\n");
1421 /* write it to the imap server */
1422 ctx
= imap_open_store(&server
);
1424 fprintf(stderr
, "failed to open store\n");
1428 fprintf(stderr
, "sending %d message%s\n", total
, (total
!= 1) ? "s" : "");
1429 ctx
->name
= imap_folder
;
1431 unsigned percent
= n
* 100 / total
;
1433 fprintf(stderr
, "%4u%% (%d/%d) done\r", percent
, n
, total
);
1434 if (!split_msg(&all_msgs
, &msg
, &ofs
))
1436 if (server
.use_html
)
1438 r
= imap_store_msg(ctx
, &msg
);
1443 fprintf(stderr
, "\n");
1445 imap_close_store(ctx
);