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>
39 const char *path
; /* should this be here? its interpretation is driver-specific */
42 unsigned max_size
; /* off_t is overkill */
43 unsigned trash_remote_new
:1, trash_only_new
:1;
46 /* For message->status */
47 #define M_RECENT (1<<0) /* unsyncable flag; maildir_* depend on this being 1<<0 */
48 #define M_DEAD (1<<1) /* expunged */
49 #define M_FLAGS (1<<2) /* flags fetched */
53 size_t size
; /* zero implies "not fetched" */
55 unsigned char flags
, status
;
59 struct store_conf
*conf
; /* foreign */
61 /* currently open mailbox */
62 const char *name
; /* foreign! maybe preset? */
64 struct message
*msgs
; /* own */
66 unsigned char opts
; /* maybe preset? */
67 /* note that the following do _not_ reflect stats from msgs, but mailbox totals */
68 int count
; /* # of messages */
69 int recent
; /* # of recent messages - don't trust this beyond the initial read */
78 static const char imap_send_usage
[] = "git imap-send < <mbox>";
82 #define DRV_MSG_BAD -1
83 #define DRV_BOX_BAD -2
84 #define DRV_STORE_BAD -3
86 static int Verbose
, Quiet
;
88 __attribute__((format (printf
, 1, 2)))
89 static void imap_info(const char *, ...);
90 __attribute__((format (printf
, 1, 2)))
91 static void imap_warn(const char *, ...);
93 static char *next_arg(char **);
95 static void free_generic_messages(struct message
*);
97 __attribute__((format (printf
, 3, 4)))
98 static int nfsnprintf(char *buf
, int blen
, const char *fmt
, ...);
100 static int nfvasprintf(char **strp
, const char *fmt
, va_list ap
)
105 len
= vsnprintf(tmp
, sizeof(tmp
), fmt
, ap
);
107 die("Fatal: Out of memory");
108 if (len
>= sizeof(tmp
))
109 die("imap command overflow!");
110 *strp
= xmemdupz(tmp
, len
);
114 struct imap_server_conf
{
127 static struct imap_server_conf server
= {
137 NULL
, /* auth_method */
140 struct imap_store_conf
{
141 struct store_conf gen
;
142 struct imap_server_conf
*server
;
145 #define NIL (void *)0x1
146 #define LIST (void *)0x2
149 struct imap_list
*next
, *child
;
160 struct imap_socket sock
;
169 int uidnext
; /* from SELECT responses */
170 struct imap_list
*ns_personal
, *ns_other
, *ns_shared
; /* NAMESPACE info */
171 unsigned caps
, rcaps
; /* CAPABILITY results */
173 int nexttag
, num_in_progress
, literal_pending
;
174 struct imap_cmd
*in_progress
, **in_progress_append
;
175 struct imap_buffer buf
; /* this is BIG, so put it last */
183 unsigned /*currentnc:1,*/ trashnc
:1;
187 int (*cont
)(struct imap_store
*ctx
, struct imap_cmd
*cmd
, const char *prompt
);
188 void (*done
)(struct imap_store
*ctx
, struct imap_cmd
*cmd
, int response
);
193 unsigned create
:1, trycreate
:1;
197 struct imap_cmd
*next
;
198 struct imap_cmd_cb cb
;
203 #define CAP(cap) (imap->caps & (1 << (cap)))
214 static const char *cap_list
[] = {
227 static int get_cmd_result(struct imap_store
*ctx
, struct imap_cmd
*tcmd
);
230 static const char *Flags
[] = {
239 static void ssl_socket_perror(const char *func
)
241 fprintf(stderr
, "%s: %s\n", func
, ERR_error_string(ERR_get_error(), NULL
));
245 static void socket_perror(const char *func
, struct imap_socket
*sock
, int ret
)
249 int sslerr
= SSL_get_error(sock
->ssl
, ret
);
253 case SSL_ERROR_SYSCALL
:
254 perror("SSL_connect");
257 ssl_socket_perror("SSL_connect");
266 fprintf(stderr
, "%s: unexpected EOF\n", func
);
271 static int ssl_socket_connect(struct imap_socket
*sock
, int use_tls_only
, int verify
)
273 fprintf(stderr
, "SSL requested but SSL support not compiled in\n");
279 static int host_matches(const char *host
, const char *pattern
)
281 if (pattern
[0] == '*' && pattern
[1] == '.') {
283 if (!(host
= strchr(host
, '.')))
288 return *host
&& *pattern
&& !strcasecmp(host
, pattern
);
291 static int verify_hostname(X509
*cert
, const char *hostname
)
297 STACK_OF(GENERAL_NAME
) *subj_alt_names
;
299 /* try the DNS subjectAltNames */
301 if ((subj_alt_names
= X509_get_ext_d2i(cert
, NID_subject_alt_name
, NULL
, NULL
))) {
302 int num_subj_alt_names
= sk_GENERAL_NAME_num(subj_alt_names
);
303 for (i
= 0; !found
&& i
< num_subj_alt_names
; i
++) {
304 GENERAL_NAME
*subj_alt_name
= sk_GENERAL_NAME_value(subj_alt_names
, i
);
305 if (subj_alt_name
->type
== GEN_DNS
&&
306 strlen((const char *)subj_alt_name
->d
.ia5
->data
) == (size_t)subj_alt_name
->d
.ia5
->length
&&
307 host_matches(hostname
, (const char *)(subj_alt_name
->d
.ia5
->data
)))
310 sk_GENERAL_NAME_pop_free(subj_alt_names
, GENERAL_NAME_free
);
315 /* try the common name */
316 if (!(subj
= X509_get_subject_name(cert
)))
317 return error("cannot get certificate subject");
318 if ((len
= X509_NAME_get_text_by_NID(subj
, NID_commonName
, cname
, sizeof(cname
))) < 0)
319 return error("cannot get certificate common name");
320 if (strlen(cname
) == (size_t)len
&& host_matches(hostname
, cname
))
322 return error("certificate owner '%s' does not match hostname '%s'",
326 static int ssl_socket_connect(struct imap_socket
*sock
, int use_tls_only
, int verify
)
328 #if (OPENSSL_VERSION_NUMBER >= 0x10000000L)
329 const SSL_METHOD
*meth
;
338 SSL_load_error_strings();
341 meth
= TLSv1_method();
343 meth
= SSLv23_method();
346 ssl_socket_perror("SSLv23_method");
350 ctx
= SSL_CTX_new(meth
);
353 SSL_CTX_set_verify(ctx
, SSL_VERIFY_PEER
, NULL
);
355 if (!SSL_CTX_set_default_verify_paths(ctx
)) {
356 ssl_socket_perror("SSL_CTX_set_default_verify_paths");
359 sock
->ssl
= SSL_new(ctx
);
361 ssl_socket_perror("SSL_new");
364 if (!SSL_set_rfd(sock
->ssl
, sock
->fd
[0])) {
365 ssl_socket_perror("SSL_set_rfd");
368 if (!SSL_set_wfd(sock
->ssl
, sock
->fd
[1])) {
369 ssl_socket_perror("SSL_set_wfd");
373 ret
= SSL_connect(sock
->ssl
);
375 socket_perror("SSL_connect", sock
, ret
);
380 /* make sure the hostname matches that of the certificate */
381 cert
= SSL_get_peer_certificate(sock
->ssl
);
383 return error("unable to get peer certificate.");
384 if (verify_hostname(cert
, server
.host
) < 0)
392 static int socket_read(struct imap_socket
*sock
, char *buf
, int len
)
397 n
= SSL_read(sock
->ssl
, buf
, len
);
400 n
= xread(sock
->fd
[0], buf
, len
);
402 socket_perror("read", sock
, n
);
405 sock
->fd
[0] = sock
->fd
[1] = -1;
410 static int socket_write(struct imap_socket
*sock
, const char *buf
, int len
)
415 n
= SSL_write(sock
->ssl
, buf
, len
);
418 n
= write_in_full(sock
->fd
[1], buf
, len
);
420 socket_perror("write", sock
, n
);
423 sock
->fd
[0] = sock
->fd
[1] = -1;
428 static void socket_shutdown(struct imap_socket
*sock
)
432 SSL_shutdown(sock
->ssl
);
440 /* simple line buffering */
441 static int buffer_gets(struct imap_buffer
*b
, char **s
)
444 int start
= b
->offset
;
449 /* make sure we have enough data to read the \r\n sequence */
450 if (b
->offset
+ 1 >= b
->bytes
) {
452 /* shift down used bytes */
455 assert(start
<= b
->bytes
);
456 n
= b
->bytes
- start
;
459 memmove(b
->buf
, b
->buf
+ start
, n
);
465 n
= socket_read(&b
->sock
, b
->buf
+ b
->bytes
,
466 sizeof(b
->buf
) - b
->bytes
);
474 if (b
->buf
[b
->offset
] == '\r') {
475 assert(b
->offset
+ 1 < b
->bytes
);
476 if (b
->buf
[b
->offset
+ 1] == '\n') {
477 b
->buf
[b
->offset
] = 0; /* terminate the string */
478 b
->offset
+= 2; /* next line */
490 static void imap_info(const char *msg
, ...)
502 static void imap_warn(const char *msg
, ...)
508 vfprintf(stderr
, msg
, va
);
513 static char *next_arg(char **s
)
519 while (isspace((unsigned char) **s
))
528 *s
= strchr(*s
, '"');
531 while (**s
&& !isspace((unsigned char) **s
))
543 static void free_generic_messages(struct message
*msgs
)
545 struct message
*tmsg
;
547 for (; msgs
; msgs
= tmsg
) {
553 static int nfsnprintf(char *buf
, int blen
, const char *fmt
, ...)
559 if (blen
<= 0 || (unsigned)(ret
= vsnprintf(buf
, blen
, fmt
, va
)) >= (unsigned)blen
)
560 die("Fatal: buffer too small. Please report a bug.");
565 static struct imap_cmd
*v_issue_imap_cmd(struct imap_store
*ctx
,
566 struct imap_cmd_cb
*cb
,
567 const char *fmt
, va_list ap
)
569 struct imap
*imap
= ctx
->imap
;
570 struct imap_cmd
*cmd
;
574 cmd
= xmalloc(sizeof(struct imap_cmd
));
575 nfvasprintf(&cmd
->cmd
, fmt
, ap
);
576 cmd
->tag
= ++imap
->nexttag
;
581 memset(&cmd
->cb
, 0, sizeof(cmd
->cb
));
583 while (imap
->literal_pending
)
584 get_cmd_result(ctx
, NULL
);
587 bufl
= nfsnprintf(buf
, sizeof(buf
), "%d %s\r\n", cmd
->tag
, cmd
->cmd
);
589 bufl
= nfsnprintf(buf
, sizeof(buf
), "%d %s{%d%s}\r\n",
590 cmd
->tag
, cmd
->cmd
, cmd
->cb
.dlen
,
591 CAP(LITERALPLUS
) ? "+" : "");
594 if (imap
->num_in_progress
)
595 printf("(%d in progress) ", imap
->num_in_progress
);
596 if (memcmp(cmd
->cmd
, "LOGIN", 5))
597 printf(">>> %s", buf
);
599 printf(">>> %d LOGIN <user> <pass>\n", cmd
->tag
);
601 if (socket_write(&imap
->buf
.sock
, buf
, bufl
) != bufl
) {
609 if (CAP(LITERALPLUS
)) {
610 n
= socket_write(&imap
->buf
.sock
, cmd
->cb
.data
, cmd
->cb
.dlen
);
612 if (n
!= cmd
->cb
.dlen
||
613 socket_write(&imap
->buf
.sock
, "\r\n", 2) != 2) {
620 imap
->literal_pending
= 1;
621 } else if (cmd
->cb
.cont
)
622 imap
->literal_pending
= 1;
624 *imap
->in_progress_append
= cmd
;
625 imap
->in_progress_append
= &cmd
->next
;
626 imap
->num_in_progress
++;
630 __attribute__((format (printf
, 3, 4)))
631 static struct imap_cmd
*issue_imap_cmd(struct imap_store
*ctx
,
632 struct imap_cmd_cb
*cb
,
633 const char *fmt
, ...)
635 struct imap_cmd
*ret
;
639 ret
= v_issue_imap_cmd(ctx
, cb
, fmt
, ap
);
644 __attribute__((format (printf
, 3, 4)))
645 static int imap_exec(struct imap_store
*ctx
, struct imap_cmd_cb
*cb
,
646 const char *fmt
, ...)
649 struct imap_cmd
*cmdp
;
652 cmdp
= v_issue_imap_cmd(ctx
, cb
, fmt
, ap
);
657 return get_cmd_result(ctx
, cmdp
);
660 __attribute__((format (printf
, 3, 4)))
661 static int imap_exec_m(struct imap_store
*ctx
, struct imap_cmd_cb
*cb
,
662 const char *fmt
, ...)
665 struct imap_cmd
*cmdp
;
668 cmdp
= v_issue_imap_cmd(ctx
, cb
, fmt
, ap
);
671 return DRV_STORE_BAD
;
673 switch (get_cmd_result(ctx
, cmdp
)) {
674 case RESP_BAD
: return DRV_STORE_BAD
;
675 case RESP_NO
: return DRV_MSG_BAD
;
676 default: return DRV_OK
;
680 static int is_atom(struct imap_list
*list
)
682 return list
&& list
->val
&& list
->val
!= NIL
&& list
->val
!= LIST
;
685 static int is_list(struct imap_list
*list
)
687 return list
&& list
->val
== LIST
;
690 static void free_list(struct imap_list
*list
)
692 struct imap_list
*tmp
;
694 for (; list
; list
= tmp
) {
697 free_list(list
->child
);
698 else if (is_atom(list
))
704 static int parse_imap_list_l(struct imap
*imap
, char **sp
, struct imap_list
**curp
, int level
)
706 struct imap_list
*cur
;
711 while (isspace((unsigned char)*s
))
713 if (level
&& *s
== ')') {
717 *curp
= cur
= xmalloc(sizeof(*cur
));
719 cur
->val
= NULL
; /* for clean bail */
724 if (parse_imap_list_l(imap
, &s
, &cur
->child
, level
+ 1))
726 } else if (imap
&& *s
== '{') {
728 bytes
= cur
->len
= strtol(s
+ 1, &s
, 10);
732 s
= cur
->val
= xmalloc(cur
->len
);
734 /* dump whats left over in the input buffer */
735 n
= imap
->buf
.bytes
- imap
->buf
.offset
;
738 /* the entire message fit in the buffer */
741 memcpy(s
, imap
->buf
.buf
+ imap
->buf
.offset
, n
);
745 /* mark that we used part of the buffer */
746 imap
->buf
.offset
+= n
;
748 /* now read the rest of the message */
750 if ((n
= socket_read(&imap
->buf
.sock
, s
, bytes
)) <= 0)
756 if (buffer_gets(&imap
->buf
, &s
))
758 } else if (*s
== '"') {
762 for (; *s
!= '"'; s
++)
767 cur
->val
= xmemdupz(p
, cur
->len
);
771 for (; *s
&& !isspace((unsigned char)*s
); s
++)
772 if (level
&& *s
== ')')
775 if (cur
->len
== 3 && !memcmp("NIL", p
, 3))
778 cur
->val
= xmemdupz(p
, cur
->len
);
795 static struct imap_list
*parse_imap_list(struct imap
*imap
, char **sp
)
797 struct imap_list
*head
;
799 if (!parse_imap_list_l(imap
, sp
, &head
, 0))
805 static struct imap_list
*parse_list(char **sp
)
807 return parse_imap_list(NULL
, sp
);
810 static void parse_capability(struct imap
*imap
, char *cmd
)
815 imap
->caps
= 0x80000000;
816 while ((arg
= next_arg(&cmd
)))
817 for (i
= 0; i
< ARRAY_SIZE(cap_list
); i
++)
818 if (!strcmp(cap_list
[i
], arg
))
819 imap
->caps
|= 1 << i
;
820 imap
->rcaps
= imap
->caps
;
823 static int parse_response_code(struct imap_store
*ctx
, struct imap_cmd_cb
*cb
,
826 struct imap
*imap
= ctx
->imap
;
830 return RESP_OK
; /* no response code */
832 if (!(p
= strchr(s
, ']'))) {
833 fprintf(stderr
, "IMAP error: malformed response code\n");
838 if (!strcmp("UIDVALIDITY", arg
)) {
839 if (!(arg
= next_arg(&s
)) || !(ctx
->gen
.uidvalidity
= atoi(arg
))) {
840 fprintf(stderr
, "IMAP error: malformed UIDVALIDITY status\n");
843 } else if (!strcmp("UIDNEXT", arg
)) {
844 if (!(arg
= next_arg(&s
)) || !(imap
->uidnext
= atoi(arg
))) {
845 fprintf(stderr
, "IMAP error: malformed NEXTUID status\n");
848 } else if (!strcmp("CAPABILITY", arg
)) {
849 parse_capability(imap
, s
);
850 } else if (!strcmp("ALERT", arg
)) {
851 /* RFC2060 says that these messages MUST be displayed
854 for (; isspace((unsigned char)*p
); p
++);
855 fprintf(stderr
, "*** IMAP ALERT *** %s\n", p
);
856 } else if (cb
&& cb
->ctx
&& !strcmp("APPENDUID", arg
)) {
857 if (!(arg
= next_arg(&s
)) || !(ctx
->gen
.uidvalidity
= atoi(arg
)) ||
858 !(arg
= next_arg(&s
)) || !(*(int *)cb
->ctx
= atoi(arg
))) {
859 fprintf(stderr
, "IMAP error: malformed APPENDUID status\n");
866 static int get_cmd_result(struct imap_store
*ctx
, struct imap_cmd
*tcmd
)
868 struct imap
*imap
= ctx
->imap
;
869 struct imap_cmd
*cmdp
, **pcmdp
, *ncmdp
;
870 char *cmd
, *arg
, *arg1
, *p
;
871 int n
, resp
, resp2
, tag
;
874 if (buffer_gets(&imap
->buf
, &cmd
))
877 arg
= next_arg(&cmd
);
879 arg
= next_arg(&cmd
);
881 fprintf(stderr
, "IMAP error: unable to parse untagged response\n");
885 if (!strcmp("NAMESPACE", arg
)) {
886 imap
->ns_personal
= parse_list(&cmd
);
887 imap
->ns_other
= parse_list(&cmd
);
888 imap
->ns_shared
= parse_list(&cmd
);
889 } else if (!strcmp("OK", arg
) || !strcmp("BAD", arg
) ||
890 !strcmp("NO", arg
) || !strcmp("BYE", arg
)) {
891 if ((resp
= parse_response_code(ctx
, NULL
, cmd
)) != RESP_OK
)
893 } else if (!strcmp("CAPABILITY", arg
))
894 parse_capability(imap
, cmd
);
895 else if ((arg1
= next_arg(&cmd
))) {
896 if (!strcmp("EXISTS", arg1
))
897 ctx
->gen
.count
= atoi(arg
);
898 else if (!strcmp("RECENT", arg1
))
899 ctx
->gen
.recent
= atoi(arg
);
901 fprintf(stderr
, "IMAP error: unable to parse untagged response\n");
904 } else if (!imap
->in_progress
) {
905 fprintf(stderr
, "IMAP error: unexpected reply: %s %s\n", arg
, cmd
? cmd
: "");
907 } else if (*arg
== '+') {
908 /* This can happen only with the last command underway, as
909 it enforces a round-trip. */
910 cmdp
= (struct imap_cmd
*)((char *)imap
->in_progress_append
-
911 offsetof(struct imap_cmd
, next
));
913 n
= socket_write(&imap
->buf
.sock
, cmdp
->cb
.data
, cmdp
->cb
.dlen
);
915 cmdp
->cb
.data
= NULL
;
916 if (n
!= (int)cmdp
->cb
.dlen
)
918 } else if (cmdp
->cb
.cont
) {
919 if (cmdp
->cb
.cont(ctx
, cmdp
, cmd
))
922 fprintf(stderr
, "IMAP error: unexpected command continuation request\n");
925 if (socket_write(&imap
->buf
.sock
, "\r\n", 2) != 2)
928 imap
->literal_pending
= 0;
933 for (pcmdp
= &imap
->in_progress
; (cmdp
= *pcmdp
); pcmdp
= &cmdp
->next
)
934 if (cmdp
->tag
== tag
)
936 fprintf(stderr
, "IMAP error: unexpected tag %s\n", arg
);
939 if (!(*pcmdp
= cmdp
->next
))
940 imap
->in_progress_append
= pcmdp
;
941 imap
->num_in_progress
--;
942 if (cmdp
->cb
.cont
|| cmdp
->cb
.data
)
943 imap
->literal_pending
= 0;
944 arg
= next_arg(&cmd
);
945 if (!strcmp("OK", arg
))
948 if (!strcmp("NO", arg
)) {
949 if (cmdp
->cb
.create
&& cmd
&& (cmdp
->cb
.trycreate
|| !memcmp(cmd
, "[TRYCREATE]", 11))) { /* SELECT, APPEND or UID COPY */
950 p
= strchr(cmdp
->cmd
, '"');
951 if (!issue_imap_cmd(ctx
, NULL
, "CREATE \"%.*s\"", (int)(strchr(p
+ 1, '"') - p
+ 1), p
)) {
955 /* not waiting here violates the spec, but a server that does not
956 grok this nonetheless violates it too. */
958 if (!(ncmdp
= issue_imap_cmd(ctx
, &cmdp
->cb
, "%s", cmdp
->cmd
))) {
965 return 0; /* ignored */
971 } else /*if (!strcmp("BAD", arg))*/
973 fprintf(stderr
, "IMAP command '%s' returned response (%s) - %s\n",
974 memcmp(cmdp
->cmd
, "LOGIN", 5) ?
975 cmdp
->cmd
: "LOGIN <user> <pass>",
976 arg
, cmd
? cmd
: "");
978 if ((resp2
= parse_response_code(ctx
, &cmdp
->cb
, cmd
)) > resp
)
982 cmdp
->cb
.done(ctx
, cmdp
, resp
);
986 if (!tcmd
|| tcmd
== cmdp
)
993 static void imap_close_server(struct imap_store
*ictx
)
995 struct imap
*imap
= ictx
->imap
;
997 if (imap
->buf
.sock
.fd
[0] != -1) {
998 imap_exec(ictx
, NULL
, "LOGOUT");
999 socket_shutdown(&imap
->buf
.sock
);
1001 free_list(imap
->ns_personal
);
1002 free_list(imap
->ns_other
);
1003 free_list(imap
->ns_shared
);
1007 static void imap_close_store(struct store
*ctx
)
1009 imap_close_server((struct imap_store
*)ctx
);
1010 free_generic_messages(ctx
->msgs
);
1017 * hexchar() and cram() functions are based on the code from the isync
1018 * project (http://isync.sf.net/).
1020 static char hexchar(unsigned int b
)
1022 return b
< 10 ? '0' + b
: 'a' + (b
- 10);
1025 #define ENCODED_SIZE(n) (4*((n+2)/3))
1026 static char *cram(const char *challenge_64
, const char *user
, const char *pass
)
1028 int i
, resp_len
, encoded_len
, decoded_len
;
1030 unsigned char hash
[16];
1032 char *response
, *response_64
, *challenge
;
1035 * length of challenge_64 (i.e. base-64 encoded string) is a good
1036 * enough upper bound for challenge (decoded result).
1038 encoded_len
= strlen(challenge_64
);
1039 challenge
= xmalloc(encoded_len
);
1040 decoded_len
= EVP_DecodeBlock((unsigned char *)challenge
,
1041 (unsigned char *)challenge_64
, encoded_len
);
1042 if (decoded_len
< 0)
1043 die("invalid challenge %s", challenge_64
);
1044 HMAC_Init(&hmac
, (unsigned char *)pass
, strlen(pass
), EVP_md5());
1045 HMAC_Update(&hmac
, (unsigned char *)challenge
, decoded_len
);
1046 HMAC_Final(&hmac
, hash
, NULL
);
1047 HMAC_CTX_cleanup(&hmac
);
1050 for (i
= 0; i
< 16; i
++) {
1051 hex
[2 * i
] = hexchar((hash
[i
] >> 4) & 0xf);
1052 hex
[2 * i
+ 1] = hexchar(hash
[i
] & 0xf);
1055 /* response: "<user> <digest in hex>" */
1056 resp_len
= strlen(user
) + 1 + strlen(hex
) + 1;
1057 response
= xmalloc(resp_len
);
1058 sprintf(response
, "%s %s", user
, hex
);
1060 response_64
= xmalloc(ENCODED_SIZE(resp_len
) + 1);
1061 encoded_len
= EVP_EncodeBlock((unsigned char *)response_64
,
1062 (unsigned char *)response
, resp_len
);
1063 if (encoded_len
< 0)
1064 die("EVP_EncodeBlock error");
1065 response_64
[encoded_len
] = '\0';
1066 return (char *)response_64
;
1071 static char *cram(const char *challenge_64
, const char *user
, const char *pass
)
1073 die("If you want to use CRAM-MD5 authenticate method, "
1074 "you have to build git-imap-send with OpenSSL library.");
1079 static int auth_cram_md5(struct imap_store
*ctx
, struct imap_cmd
*cmd
, const char *prompt
)
1084 response
= cram(prompt
, server
.user
, server
.pass
);
1086 ret
= socket_write(&ctx
->imap
->buf
.sock
, response
, strlen(response
));
1087 if (ret
!= strlen(response
))
1088 return error("IMAP error: sending response failed");
1095 static struct store
*imap_open_store(struct imap_server_conf
*srvc
)
1097 struct imap_store
*ctx
;
1100 int s
= -1, preauth
;
1102 ctx
= xcalloc(sizeof(*ctx
), 1);
1104 ctx
->imap
= imap
= xcalloc(sizeof(*imap
), 1);
1105 imap
->buf
.sock
.fd
[0] = imap
->buf
.sock
.fd
[1] = -1;
1106 imap
->in_progress_append
= &imap
->in_progress
;
1108 /* open connection to IMAP server */
1111 const char *argv
[] = { srvc
->tunnel
, NULL
};
1112 struct child_process tunnel
= {NULL
};
1114 imap_info("Starting tunnel '%s'... ", srvc
->tunnel
);
1117 tunnel
.use_shell
= 1;
1120 if (start_command(&tunnel
))
1121 die("cannot start proxy %s", argv
[0]);
1123 imap
->buf
.sock
.fd
[0] = tunnel
.out
;
1124 imap
->buf
.sock
.fd
[1] = tunnel
.in
;
1129 struct addrinfo hints
, *ai0
, *ai
;
1133 snprintf(portstr
, sizeof(portstr
), "%d", srvc
->port
);
1135 memset(&hints
, 0, sizeof(hints
));
1136 hints
.ai_socktype
= SOCK_STREAM
;
1137 hints
.ai_protocol
= IPPROTO_TCP
;
1139 imap_info("Resolving %s... ", srvc
->host
);
1140 gai
= getaddrinfo(srvc
->host
, portstr
, &hints
, &ai
);
1142 fprintf(stderr
, "getaddrinfo: %s\n", gai_strerror(gai
));
1147 for (ai0
= ai
; ai
; ai
= ai
->ai_next
) {
1148 char addr
[NI_MAXHOST
];
1150 s
= socket(ai
->ai_family
, ai
->ai_socktype
,
1155 getnameinfo(ai
->ai_addr
, ai
->ai_addrlen
, addr
,
1156 sizeof(addr
), NULL
, 0, NI_NUMERICHOST
);
1157 imap_info("Connecting to [%s]:%s... ", addr
, portstr
);
1159 if (connect(s
, ai
->ai_addr
, ai
->ai_addrlen
) < 0) {
1171 struct sockaddr_in addr
;
1173 memset(&addr
, 0, sizeof(addr
));
1174 addr
.sin_port
= htons(srvc
->port
);
1175 addr
.sin_family
= AF_INET
;
1177 imap_info("Resolving %s... ", srvc
->host
);
1178 he
= gethostbyname(srvc
->host
);
1180 perror("gethostbyname");
1185 addr
.sin_addr
.s_addr
= *((int *) he
->h_addr_list
[0]);
1187 s
= socket(PF_INET
, SOCK_STREAM
, 0);
1189 imap_info("Connecting to %s:%hu... ", inet_ntoa(addr
.sin_addr
), ntohs(addr
.sin_port
));
1190 if (connect(s
, (struct sockaddr
*)&addr
, sizeof(addr
))) {
1197 fputs("Error: unable to connect to server.\n", stderr
);
1201 imap
->buf
.sock
.fd
[0] = s
;
1202 imap
->buf
.sock
.fd
[1] = dup(s
);
1204 if (srvc
->use_ssl
&&
1205 ssl_socket_connect(&imap
->buf
.sock
, 0, srvc
->ssl_verify
)) {
1212 /* read the greeting string */
1213 if (buffer_gets(&imap
->buf
, &rsp
)) {
1214 fprintf(stderr
, "IMAP error: no greeting response\n");
1217 arg
= next_arg(&rsp
);
1218 if (!arg
|| *arg
!= '*' || (arg
= next_arg(&rsp
)) == NULL
) {
1219 fprintf(stderr
, "IMAP error: invalid greeting response\n");
1223 if (!strcmp("PREAUTH", arg
))
1225 else if (strcmp("OK", arg
) != 0) {
1226 fprintf(stderr
, "IMAP error: unknown greeting response\n");
1229 parse_response_code(ctx
, NULL
, rsp
);
1230 if (!imap
->caps
&& imap_exec(ctx
, NULL
, "CAPABILITY") != RESP_OK
)
1235 if (!srvc
->use_ssl
&& CAP(STARTTLS
)) {
1236 if (imap_exec(ctx
, NULL
, "STARTTLS") != RESP_OK
)
1238 if (ssl_socket_connect(&imap
->buf
.sock
, 1,
1241 /* capabilities may have changed, so get the new capabilities */
1242 if (imap_exec(ctx
, NULL
, "CAPABILITY") != RESP_OK
)
1246 imap_info("Logging in...\n");
1248 fprintf(stderr
, "Skipping server %s, no user\n", srvc
->host
);
1252 struct strbuf prompt
= STRBUF_INIT
;
1253 strbuf_addf(&prompt
, "Password (%s@%s): ", srvc
->user
, srvc
->host
);
1254 arg
= git_getpass(prompt
.buf
);
1255 strbuf_release(&prompt
);
1257 fprintf(stderr
, "Skipping account %s@%s, no password\n", srvc
->user
, srvc
->host
);
1261 * getpass() returns a pointer to a static buffer. make a copy
1262 * for long term storage.
1264 srvc
->pass
= xstrdup(arg
);
1267 fprintf(stderr
, "Skipping account %s@%s, server forbids LOGIN\n", srvc
->user
, srvc
->host
);
1271 if (srvc
->auth_method
) {
1272 struct imap_cmd_cb cb
;
1274 if (!strcmp(srvc
->auth_method
, "CRAM-MD5")) {
1275 if (!CAP(AUTH_CRAM_MD5
)) {
1276 fprintf(stderr
, "You specified"
1277 "CRAM-MD5 as authentication method, "
1278 "but %s doesn't support it.\n", srvc
->host
);
1283 memset(&cb
, 0, sizeof(cb
));
1284 cb
.cont
= auth_cram_md5
;
1285 if (imap_exec(ctx
, &cb
, "AUTHENTICATE CRAM-MD5") != RESP_OK
) {
1286 fprintf(stderr
, "IMAP error: AUTHENTICATE CRAM-MD5 failed\n");
1290 fprintf(stderr
, "Unknown authentication method:%s\n", srvc
->host
);
1294 if (!imap
->buf
.sock
.ssl
)
1295 imap_warn("*** IMAP Warning *** Password is being "
1296 "sent in the clear\n");
1297 if (imap_exec(ctx
, NULL
, "LOGIN \"%s\" \"%s\"", srvc
->user
, srvc
->pass
) != RESP_OK
) {
1298 fprintf(stderr
, "IMAP error: LOGIN failed\n");
1306 return (struct store
*)ctx
;
1309 imap_close_store(&ctx
->gen
);
1313 static int imap_make_flags(int flags
, char *buf
)
1318 for (i
= d
= 0; i
< ARRAY_SIZE(Flags
); i
++)
1319 if (flags
& (1 << i
)) {
1322 for (s
= Flags
[i
]; *s
; s
++)
1330 static void lf_to_crlf(struct msg_data
*msg
)
1333 int i
, j
, lfnum
= 0;
1335 if (msg
->data
[0] == '\n')
1337 for (i
= 1; i
< msg
->len
; i
++) {
1338 if (msg
->data
[i
- 1] != '\r' && msg
->data
[i
] == '\n')
1342 new = xmalloc(msg
->len
+ lfnum
);
1343 if (msg
->data
[0] == '\n') {
1349 new[0] = msg
->data
[0];
1353 for ( ; i
< msg
->len
; i
++) {
1354 if (msg
->data
[i
] != '\n') {
1355 new[j
++] = msg
->data
[i
];
1358 if (msg
->data
[i
- 1] != '\r')
1360 /* otherwise it already had CR before */
1368 static int imap_store_msg(struct store
*gctx
, struct msg_data
*data
)
1370 struct imap_store
*ctx
= (struct imap_store
*)gctx
;
1371 struct imap
*imap
= ctx
->imap
;
1372 struct imap_cmd_cb cb
;
1373 const char *prefix
, *box
;
1378 memset(&cb
, 0, sizeof(cb
));
1380 cb
.dlen
= data
->len
;
1381 cb
.data
= xmalloc(cb
.dlen
);
1382 memcpy(cb
.data
, data
->data
, data
->len
);
1386 d
= imap_make_flags(data
->flags
, flagstr
);
1392 prefix
= !strcmp(box
, "INBOX") ? "" : ctx
->prefix
;
1394 ret
= imap_exec_m(ctx
, &cb
, "APPEND \"%s%s\" %s", prefix
, box
, flagstr
);
1395 imap
->caps
= imap
->rcaps
;
1403 static void encode_html_chars(struct strbuf
*p
)
1406 for (i
= 0; i
< p
->len
; i
++) {
1407 if (p
->buf
[i
] == '&')
1408 strbuf_splice(p
, i
, 1, "&", 5);
1409 if (p
->buf
[i
] == '<')
1410 strbuf_splice(p
, i
, 1, "<", 4);
1411 if (p
->buf
[i
] == '>')
1412 strbuf_splice(p
, i
, 1, ">", 4);
1413 if (p
->buf
[i
] == '"')
1414 strbuf_splice(p
, i
, 1, """, 6);
1417 static void wrap_in_html(struct msg_data
*msg
)
1419 struct strbuf buf
= STRBUF_INIT
;
1420 struct strbuf
**lines
;
1422 static char *content_type
= "Content-Type: text/html;\n";
1423 static char *pre_open
= "<pre>\n";
1424 static char *pre_close
= "</pre>\n";
1425 int added_header
= 0;
1427 strbuf_attach(&buf
, msg
->data
, msg
->len
, msg
->len
);
1428 lines
= strbuf_split(&buf
, '\n');
1429 strbuf_release(&buf
);
1430 for (p
= lines
; *p
; p
++) {
1431 if (! added_header
) {
1432 if ((*p
)->len
== 1 && *((*p
)->buf
) == '\n') {
1433 strbuf_addstr(&buf
, content_type
);
1434 strbuf_addbuf(&buf
, *p
);
1435 strbuf_addstr(&buf
, pre_open
);
1441 encode_html_chars(*p
);
1442 strbuf_addbuf(&buf
, *p
);
1444 strbuf_addstr(&buf
, pre_close
);
1445 strbuf_list_free(lines
);
1447 msg
->data
= strbuf_detach(&buf
, NULL
);
1450 #define CHUNKSIZE 0x1000
1452 static int read_message(FILE *f
, struct msg_data
*msg
)
1454 struct strbuf buf
= STRBUF_INIT
;
1456 memset(msg
, 0, sizeof(*msg
));
1459 if (strbuf_fread(&buf
, CHUNKSIZE
, f
) <= 0)
1464 msg
->data
= strbuf_detach(&buf
, NULL
);
1468 static int count_messages(struct msg_data
*msg
)
1471 char *p
= msg
->data
;
1474 if (!prefixcmp(p
, "From ")) {
1475 p
= strstr(p
+5, "\nFrom: ");
1477 p
= strstr(p
+7, "\nDate: ");
1479 p
= strstr(p
+7, "\nSubject: ");
1484 p
= strstr(p
+5, "\nFrom ");
1492 static int split_msg(struct msg_data
*all_msgs
, struct msg_data
*msg
, int *ofs
)
1496 memset(msg
, 0, sizeof *msg
);
1497 if (*ofs
>= all_msgs
->len
)
1500 data
= &all_msgs
->data
[*ofs
];
1501 msg
->len
= all_msgs
->len
- *ofs
;
1503 if (msg
->len
< 5 || prefixcmp(data
, "From "))
1506 p
= strchr(data
, '\n');
1514 p
= strstr(data
, "\nFrom ");
1516 msg
->len
= &p
[1] - data
;
1518 msg
->data
= xmemdupz(data
, msg
->len
);
1523 static char *imap_folder
;
1525 static int git_imap_config(const char *key
, const char *val
, void *cb
)
1527 char imap_key
[] = "imap.";
1529 if (strncmp(key
, imap_key
, sizeof imap_key
- 1))
1532 key
+= sizeof imap_key
- 1;
1534 /* check booleans first, and barf on others */
1535 if (!strcmp("sslverify", key
))
1536 server
.ssl_verify
= git_config_bool(key
, val
);
1537 else if (!strcmp("preformattedhtml", key
))
1538 server
.use_html
= git_config_bool(key
, val
);
1540 return config_error_nonbool(key
);
1542 if (!strcmp("folder", key
)) {
1543 imap_folder
= xstrdup(val
);
1544 } else if (!strcmp("host", key
)) {
1545 if (!prefixcmp(val
, "imap:"))
1547 else if (!prefixcmp(val
, "imaps:")) {
1551 if (!prefixcmp(val
, "//"))
1553 server
.host
= xstrdup(val
);
1554 } else if (!strcmp("user", key
))
1555 server
.user
= xstrdup(val
);
1556 else if (!strcmp("pass", key
))
1557 server
.pass
= xstrdup(val
);
1558 else if (!strcmp("port", key
))
1559 server
.port
= git_config_int(key
, val
);
1560 else if (!strcmp("tunnel", key
))
1561 server
.tunnel
= xstrdup(val
);
1562 else if (!strcmp("authmethod", key
))
1563 server
.auth_method
= xstrdup(val
);
1568 int main(int argc
, char **argv
)
1570 struct msg_data all_msgs
, msg
;
1571 struct store
*ctx
= NULL
;
1577 git_extract_argv0_path(argv
[0]);
1579 git_setup_gettext();
1582 usage(imap_send_usage
);
1584 setup_git_directory_gently(&nongit_ok
);
1585 git_config(git_imap_config
, NULL
);
1588 server
.port
= server
.use_ssl
? 993 : 143;
1591 fprintf(stderr
, "no imap store specified\n");
1595 if (!server
.tunnel
) {
1596 fprintf(stderr
, "no imap host specified\n");
1599 server
.host
= "tunnel";
1602 /* read the messages */
1603 if (!read_message(stdin
, &all_msgs
)) {
1604 fprintf(stderr
, "nothing to send\n");
1608 total
= count_messages(&all_msgs
);
1610 fprintf(stderr
, "no messages to send\n");
1614 /* write it to the imap server */
1615 ctx
= imap_open_store(&server
);
1617 fprintf(stderr
, "failed to open store\n");
1621 fprintf(stderr
, "sending %d message%s\n", total
, (total
!= 1) ? "s" : "");
1622 ctx
->name
= imap_folder
;
1624 unsigned percent
= n
* 100 / total
;
1625 fprintf(stderr
, "%4u%% (%d/%d) done\r", percent
, n
, total
);
1626 if (!split_msg(&all_msgs
, &msg
, &ofs
))
1628 if (server
.use_html
)
1630 r
= imap_store_msg(ctx
, &msg
);
1635 fprintf(stderr
, "\n");
1637 imap_close_store(ctx
);