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"
31 #include <openssl/evp.h>
32 #include <openssl/hmac.h>
37 const char *path
; /* should this be here? its interpretation is driver-specific */
40 unsigned max_size
; /* off_t is overkill */
41 unsigned trash_remote_new
:1, trash_only_new
:1;
44 /* For message->status */
45 #define M_RECENT (1<<0) /* unsyncable flag; maildir_* depend on this being 1<<0 */
46 #define M_DEAD (1<<1) /* expunged */
47 #define M_FLAGS (1<<2) /* flags fetched */
51 size_t size
; /* zero implies "not fetched" */
53 unsigned char flags
, status
;
57 struct store_conf
*conf
; /* foreign */
59 /* currently open mailbox */
60 const char *name
; /* foreign! maybe preset? */
62 struct message
*msgs
; /* own */
64 unsigned char opts
; /* maybe preset? */
65 /* note that the following do _not_ reflect stats from msgs, but mailbox totals */
66 int count
; /* # of messages */
67 int recent
; /* # of recent messages - don't trust this beyond the initial read */
76 static const char imap_send_usage
[] = "git imap-send < <mbox>";
80 #define DRV_MSG_BAD -1
81 #define DRV_BOX_BAD -2
82 #define DRV_STORE_BAD -3
84 static int Verbose
, Quiet
;
86 __attribute__((format (printf
, 1, 2)))
87 static void imap_info(const char *, ...);
88 __attribute__((format (printf
, 1, 2)))
89 static void imap_warn(const char *, ...);
91 static char *next_arg(char **);
93 static void free_generic_messages(struct message
*);
95 __attribute__((format (printf
, 3, 4)))
96 static int nfsnprintf(char *buf
, int blen
, const char *fmt
, ...);
98 static int nfvasprintf(char **strp
, const char *fmt
, va_list ap
)
103 len
= vsnprintf(tmp
, sizeof(tmp
), fmt
, ap
);
105 die("Fatal: Out of memory");
106 if (len
>= sizeof(tmp
))
107 die("imap command overflow!");
108 *strp
= xmemdupz(tmp
, len
);
112 struct imap_server_conf
{
125 static struct imap_server_conf server
= {
135 NULL
, /* auth_method */
138 struct imap_store_conf
{
139 struct store_conf gen
;
140 struct imap_server_conf
*server
;
141 unsigned use_namespace
:1;
144 #define NIL (void *)0x1
145 #define LIST (void *)0x2
148 struct imap_list
*next
, *child
;
159 struct imap_socket sock
;
168 int uidnext
; /* from SELECT responses */
169 struct imap_list
*ns_personal
, *ns_other
, *ns_shared
; /* NAMESPACE info */
170 unsigned caps
, rcaps
; /* CAPABILITY results */
172 int nexttag
, num_in_progress
, literal_pending
;
173 struct imap_cmd
*in_progress
, **in_progress_append
;
174 struct imap_buffer buf
; /* this is BIG, so put it last */
182 unsigned /*currentnc:1,*/ trashnc
:1;
186 int (*cont
)(struct imap_store
*ctx
, struct imap_cmd
*cmd
, const char *prompt
);
187 void (*done
)(struct imap_store
*ctx
, struct imap_cmd
*cmd
, int response
);
192 unsigned create
:1, trycreate
:1;
196 struct imap_cmd
*next
;
197 struct imap_cmd_cb cb
;
202 #define CAP(cap) (imap->caps & (1 << (cap)))
213 static const char *cap_list
[] = {
226 static int get_cmd_result(struct imap_store
*ctx
, struct imap_cmd
*tcmd
);
229 static const char *Flags
[] = {
238 static void ssl_socket_perror(const char *func
)
240 fprintf(stderr
, "%s: %s\n", func
, ERR_error_string(ERR_get_error(), NULL
));
244 static void socket_perror(const char *func
, struct imap_socket
*sock
, int ret
)
248 int sslerr
= SSL_get_error(sock
->ssl
, ret
);
252 case SSL_ERROR_SYSCALL
:
253 perror("SSL_connect");
256 ssl_socket_perror("SSL_connect");
265 fprintf(stderr
, "%s: unexpected EOF\n", func
);
270 static int ssl_socket_connect(struct imap_socket
*sock
, int use_tls_only
, int verify
)
272 fprintf(stderr
, "SSL requested but SSL support not compiled in\n");
278 static int host_matches(const char *host
, const char *pattern
)
280 if (pattern
[0] == '*' && pattern
[1] == '.') {
282 if (!(host
= strchr(host
, '.')))
287 return *host
&& *pattern
&& !strcasecmp(host
, pattern
);
290 static int verify_hostname(X509
*cert
, const char *hostname
)
296 /* try the common name */
297 if (!(subj
= X509_get_subject_name(cert
)))
298 return error("cannot get certificate subject");
299 if ((len
= X509_NAME_get_text_by_NID(subj
, NID_commonName
, cname
, sizeof(cname
))) < 0)
300 return error("cannot get certificate common name");
301 if (strlen(cname
) == (size_t)len
&& host_matches(hostname
, cname
))
303 return error("certificate owner '%s' does not match hostname '%s'",
307 static int ssl_socket_connect(struct imap_socket
*sock
, int use_tls_only
, int verify
)
309 #if (OPENSSL_VERSION_NUMBER >= 0x10000000L)
310 const SSL_METHOD
*meth
;
319 SSL_load_error_strings();
322 meth
= TLSv1_method();
324 meth
= SSLv23_method();
327 ssl_socket_perror("SSLv23_method");
331 ctx
= SSL_CTX_new(meth
);
334 SSL_CTX_set_verify(ctx
, SSL_VERIFY_PEER
, NULL
);
336 if (!SSL_CTX_set_default_verify_paths(ctx
)) {
337 ssl_socket_perror("SSL_CTX_set_default_verify_paths");
340 sock
->ssl
= SSL_new(ctx
);
342 ssl_socket_perror("SSL_new");
345 if (!SSL_set_rfd(sock
->ssl
, sock
->fd
[0])) {
346 ssl_socket_perror("SSL_set_rfd");
349 if (!SSL_set_wfd(sock
->ssl
, sock
->fd
[1])) {
350 ssl_socket_perror("SSL_set_wfd");
354 ret
= SSL_connect(sock
->ssl
);
356 socket_perror("SSL_connect", sock
, ret
);
361 /* make sure the hostname matches that of the certificate */
362 cert
= SSL_get_peer_certificate(sock
->ssl
);
364 return error("unable to get peer certificate.");
365 if (verify_hostname(cert
, server
.host
) < 0)
373 static int socket_read(struct imap_socket
*sock
, char *buf
, int len
)
378 n
= SSL_read(sock
->ssl
, buf
, len
);
381 n
= xread(sock
->fd
[0], buf
, len
);
383 socket_perror("read", sock
, n
);
386 sock
->fd
[0] = sock
->fd
[1] = -1;
391 static int socket_write(struct imap_socket
*sock
, const char *buf
, int len
)
396 n
= SSL_write(sock
->ssl
, buf
, len
);
399 n
= write_in_full(sock
->fd
[1], buf
, len
);
401 socket_perror("write", sock
, n
);
404 sock
->fd
[0] = sock
->fd
[1] = -1;
409 static void socket_shutdown(struct imap_socket
*sock
)
413 SSL_shutdown(sock
->ssl
);
421 /* simple line buffering */
422 static int buffer_gets(struct imap_buffer
*b
, char **s
)
425 int start
= b
->offset
;
430 /* make sure we have enough data to read the \r\n sequence */
431 if (b
->offset
+ 1 >= b
->bytes
) {
433 /* shift down used bytes */
436 assert(start
<= b
->bytes
);
437 n
= b
->bytes
- start
;
440 memmove(b
->buf
, b
->buf
+ start
, n
);
446 n
= socket_read(&b
->sock
, b
->buf
+ b
->bytes
,
447 sizeof(b
->buf
) - b
->bytes
);
455 if (b
->buf
[b
->offset
] == '\r') {
456 assert(b
->offset
+ 1 < b
->bytes
);
457 if (b
->buf
[b
->offset
+ 1] == '\n') {
458 b
->buf
[b
->offset
] = 0; /* terminate the string */
459 b
->offset
+= 2; /* next line */
471 static void imap_info(const char *msg
, ...)
483 static void imap_warn(const char *msg
, ...)
489 vfprintf(stderr
, msg
, va
);
494 static char *next_arg(char **s
)
500 while (isspace((unsigned char) **s
))
509 *s
= strchr(*s
, '"');
512 while (**s
&& !isspace((unsigned char) **s
))
524 static void free_generic_messages(struct message
*msgs
)
526 struct message
*tmsg
;
528 for (; msgs
; msgs
= tmsg
) {
534 static int nfsnprintf(char *buf
, int blen
, const char *fmt
, ...)
540 if (blen
<= 0 || (unsigned)(ret
= vsnprintf(buf
, blen
, fmt
, va
)) >= (unsigned)blen
)
541 die("Fatal: buffer too small. Please report a bug.");
546 static struct imap_cmd
*v_issue_imap_cmd(struct imap_store
*ctx
,
547 struct imap_cmd_cb
*cb
,
548 const char *fmt
, va_list ap
)
550 struct imap
*imap
= ctx
->imap
;
551 struct imap_cmd
*cmd
;
555 cmd
= xmalloc(sizeof(struct imap_cmd
));
556 nfvasprintf(&cmd
->cmd
, fmt
, ap
);
557 cmd
->tag
= ++imap
->nexttag
;
562 memset(&cmd
->cb
, 0, sizeof(cmd
->cb
));
564 while (imap
->literal_pending
)
565 get_cmd_result(ctx
, NULL
);
568 bufl
= nfsnprintf(buf
, sizeof(buf
), "%d %s\r\n", cmd
->tag
, cmd
->cmd
);
570 bufl
= nfsnprintf(buf
, sizeof(buf
), "%d %s{%d%s}\r\n",
571 cmd
->tag
, cmd
->cmd
, cmd
->cb
.dlen
,
572 CAP(LITERALPLUS
) ? "+" : "");
575 if (imap
->num_in_progress
)
576 printf("(%d in progress) ", imap
->num_in_progress
);
577 if (memcmp(cmd
->cmd
, "LOGIN", 5))
578 printf(">>> %s", buf
);
580 printf(">>> %d LOGIN <user> <pass>\n", cmd
->tag
);
582 if (socket_write(&imap
->buf
.sock
, buf
, bufl
) != bufl
) {
590 if (CAP(LITERALPLUS
)) {
591 n
= socket_write(&imap
->buf
.sock
, cmd
->cb
.data
, cmd
->cb
.dlen
);
593 if (n
!= cmd
->cb
.dlen
||
594 socket_write(&imap
->buf
.sock
, "\r\n", 2) != 2) {
601 imap
->literal_pending
= 1;
602 } else if (cmd
->cb
.cont
)
603 imap
->literal_pending
= 1;
605 *imap
->in_progress_append
= cmd
;
606 imap
->in_progress_append
= &cmd
->next
;
607 imap
->num_in_progress
++;
611 __attribute__((format (printf
, 3, 4)))
612 static struct imap_cmd
*issue_imap_cmd(struct imap_store
*ctx
,
613 struct imap_cmd_cb
*cb
,
614 const char *fmt
, ...)
616 struct imap_cmd
*ret
;
620 ret
= v_issue_imap_cmd(ctx
, cb
, fmt
, ap
);
625 __attribute__((format (printf
, 3, 4)))
626 static int imap_exec(struct imap_store
*ctx
, struct imap_cmd_cb
*cb
,
627 const char *fmt
, ...)
630 struct imap_cmd
*cmdp
;
633 cmdp
= v_issue_imap_cmd(ctx
, cb
, fmt
, ap
);
638 return get_cmd_result(ctx
, cmdp
);
641 __attribute__((format (printf
, 3, 4)))
642 static int imap_exec_m(struct imap_store
*ctx
, struct imap_cmd_cb
*cb
,
643 const char *fmt
, ...)
646 struct imap_cmd
*cmdp
;
649 cmdp
= v_issue_imap_cmd(ctx
, cb
, fmt
, ap
);
652 return DRV_STORE_BAD
;
654 switch (get_cmd_result(ctx
, cmdp
)) {
655 case RESP_BAD
: return DRV_STORE_BAD
;
656 case RESP_NO
: return DRV_MSG_BAD
;
657 default: return DRV_OK
;
661 static int is_atom(struct imap_list
*list
)
663 return list
&& list
->val
&& list
->val
!= NIL
&& list
->val
!= LIST
;
666 static int is_list(struct imap_list
*list
)
668 return list
&& list
->val
== LIST
;
671 static void free_list(struct imap_list
*list
)
673 struct imap_list
*tmp
;
675 for (; list
; list
= tmp
) {
678 free_list(list
->child
);
679 else if (is_atom(list
))
685 static int parse_imap_list_l(struct imap
*imap
, char **sp
, struct imap_list
**curp
, int level
)
687 struct imap_list
*cur
;
692 while (isspace((unsigned char)*s
))
694 if (level
&& *s
== ')') {
698 *curp
= cur
= xmalloc(sizeof(*cur
));
700 cur
->val
= NULL
; /* for clean bail */
705 if (parse_imap_list_l(imap
, &s
, &cur
->child
, level
+ 1))
707 } else if (imap
&& *s
== '{') {
709 bytes
= cur
->len
= strtol(s
+ 1, &s
, 10);
713 s
= cur
->val
= xmalloc(cur
->len
);
715 /* dump whats left over in the input buffer */
716 n
= imap
->buf
.bytes
- imap
->buf
.offset
;
719 /* the entire message fit in the buffer */
722 memcpy(s
, imap
->buf
.buf
+ imap
->buf
.offset
, n
);
726 /* mark that we used part of the buffer */
727 imap
->buf
.offset
+= n
;
729 /* now read the rest of the message */
731 if ((n
= socket_read(&imap
->buf
.sock
, s
, bytes
)) <= 0)
737 if (buffer_gets(&imap
->buf
, &s
))
739 } else if (*s
== '"') {
743 for (; *s
!= '"'; s
++)
748 cur
->val
= xmemdupz(p
, cur
->len
);
752 for (; *s
&& !isspace((unsigned char)*s
); s
++)
753 if (level
&& *s
== ')')
756 if (cur
->len
== 3 && !memcmp("NIL", p
, 3))
759 cur
->val
= xmemdupz(p
, cur
->len
);
776 static struct imap_list
*parse_imap_list(struct imap
*imap
, char **sp
)
778 struct imap_list
*head
;
780 if (!parse_imap_list_l(imap
, sp
, &head
, 0))
786 static struct imap_list
*parse_list(char **sp
)
788 return parse_imap_list(NULL
, sp
);
791 static void parse_capability(struct imap
*imap
, char *cmd
)
796 imap
->caps
= 0x80000000;
797 while ((arg
= next_arg(&cmd
)))
798 for (i
= 0; i
< ARRAY_SIZE(cap_list
); i
++)
799 if (!strcmp(cap_list
[i
], arg
))
800 imap
->caps
|= 1 << i
;
801 imap
->rcaps
= imap
->caps
;
804 static int parse_response_code(struct imap_store
*ctx
, struct imap_cmd_cb
*cb
,
807 struct imap
*imap
= ctx
->imap
;
811 return RESP_OK
; /* no response code */
813 if (!(p
= strchr(s
, ']'))) {
814 fprintf(stderr
, "IMAP error: malformed response code\n");
819 if (!strcmp("UIDVALIDITY", arg
)) {
820 if (!(arg
= next_arg(&s
)) || !(ctx
->gen
.uidvalidity
= atoi(arg
))) {
821 fprintf(stderr
, "IMAP error: malformed UIDVALIDITY status\n");
824 } else if (!strcmp("UIDNEXT", arg
)) {
825 if (!(arg
= next_arg(&s
)) || !(imap
->uidnext
= atoi(arg
))) {
826 fprintf(stderr
, "IMAP error: malformed NEXTUID status\n");
829 } else if (!strcmp("CAPABILITY", arg
)) {
830 parse_capability(imap
, s
);
831 } else if (!strcmp("ALERT", arg
)) {
832 /* RFC2060 says that these messages MUST be displayed
835 for (; isspace((unsigned char)*p
); p
++);
836 fprintf(stderr
, "*** IMAP ALERT *** %s\n", p
);
837 } else if (cb
&& cb
->ctx
&& !strcmp("APPENDUID", arg
)) {
838 if (!(arg
= next_arg(&s
)) || !(ctx
->gen
.uidvalidity
= atoi(arg
)) ||
839 !(arg
= next_arg(&s
)) || !(*(int *)cb
->ctx
= atoi(arg
))) {
840 fprintf(stderr
, "IMAP error: malformed APPENDUID status\n");
847 static int get_cmd_result(struct imap_store
*ctx
, struct imap_cmd
*tcmd
)
849 struct imap
*imap
= ctx
->imap
;
850 struct imap_cmd
*cmdp
, **pcmdp
, *ncmdp
;
851 char *cmd
, *arg
, *arg1
, *p
;
852 int n
, resp
, resp2
, tag
;
855 if (buffer_gets(&imap
->buf
, &cmd
))
858 arg
= next_arg(&cmd
);
860 arg
= next_arg(&cmd
);
862 fprintf(stderr
, "IMAP error: unable to parse untagged response\n");
866 if (!strcmp("NAMESPACE", arg
)) {
867 imap
->ns_personal
= parse_list(&cmd
);
868 imap
->ns_other
= parse_list(&cmd
);
869 imap
->ns_shared
= parse_list(&cmd
);
870 } else if (!strcmp("OK", arg
) || !strcmp("BAD", arg
) ||
871 !strcmp("NO", arg
) || !strcmp("BYE", arg
)) {
872 if ((resp
= parse_response_code(ctx
, NULL
, cmd
)) != RESP_OK
)
874 } else if (!strcmp("CAPABILITY", arg
))
875 parse_capability(imap
, cmd
);
876 else if ((arg1
= next_arg(&cmd
))) {
877 if (!strcmp("EXISTS", arg1
))
878 ctx
->gen
.count
= atoi(arg
);
879 else if (!strcmp("RECENT", arg1
))
880 ctx
->gen
.recent
= atoi(arg
);
882 fprintf(stderr
, "IMAP error: unable to parse untagged response\n");
885 } else if (!imap
->in_progress
) {
886 fprintf(stderr
, "IMAP error: unexpected reply: %s %s\n", arg
, cmd
? cmd
: "");
888 } else if (*arg
== '+') {
889 /* This can happen only with the last command underway, as
890 it enforces a round-trip. */
891 cmdp
= (struct imap_cmd
*)((char *)imap
->in_progress_append
-
892 offsetof(struct imap_cmd
, next
));
894 n
= socket_write(&imap
->buf
.sock
, cmdp
->cb
.data
, cmdp
->cb
.dlen
);
896 cmdp
->cb
.data
= NULL
;
897 if (n
!= (int)cmdp
->cb
.dlen
)
899 } else if (cmdp
->cb
.cont
) {
900 if (cmdp
->cb
.cont(ctx
, cmdp
, cmd
))
903 fprintf(stderr
, "IMAP error: unexpected command continuation request\n");
906 if (socket_write(&imap
->buf
.sock
, "\r\n", 2) != 2)
909 imap
->literal_pending
= 0;
914 for (pcmdp
= &imap
->in_progress
; (cmdp
= *pcmdp
); pcmdp
= &cmdp
->next
)
915 if (cmdp
->tag
== tag
)
917 fprintf(stderr
, "IMAP error: unexpected tag %s\n", arg
);
920 if (!(*pcmdp
= cmdp
->next
))
921 imap
->in_progress_append
= pcmdp
;
922 imap
->num_in_progress
--;
923 if (cmdp
->cb
.cont
|| cmdp
->cb
.data
)
924 imap
->literal_pending
= 0;
925 arg
= next_arg(&cmd
);
926 if (!strcmp("OK", arg
))
929 if (!strcmp("NO", arg
)) {
930 if (cmdp
->cb
.create
&& cmd
&& (cmdp
->cb
.trycreate
|| !memcmp(cmd
, "[TRYCREATE]", 11))) { /* SELECT, APPEND or UID COPY */
931 p
= strchr(cmdp
->cmd
, '"');
932 if (!issue_imap_cmd(ctx
, NULL
, "CREATE \"%.*s\"", (int)(strchr(p
+ 1, '"') - p
+ 1), p
)) {
936 /* not waiting here violates the spec, but a server that does not
937 grok this nonetheless violates it too. */
939 if (!(ncmdp
= issue_imap_cmd(ctx
, &cmdp
->cb
, "%s", cmdp
->cmd
))) {
946 return 0; /* ignored */
952 } else /*if (!strcmp("BAD", arg))*/
954 fprintf(stderr
, "IMAP command '%s' returned response (%s) - %s\n",
955 memcmp(cmdp
->cmd
, "LOGIN", 5) ?
956 cmdp
->cmd
: "LOGIN <user> <pass>",
957 arg
, cmd
? cmd
: "");
959 if ((resp2
= parse_response_code(ctx
, &cmdp
->cb
, cmd
)) > resp
)
963 cmdp
->cb
.done(ctx
, cmdp
, resp
);
967 if (!tcmd
|| tcmd
== cmdp
)
974 static void imap_close_server(struct imap_store
*ictx
)
976 struct imap
*imap
= ictx
->imap
;
978 if (imap
->buf
.sock
.fd
[0] != -1) {
979 imap_exec(ictx
, NULL
, "LOGOUT");
980 socket_shutdown(&imap
->buf
.sock
);
982 free_list(imap
->ns_personal
);
983 free_list(imap
->ns_other
);
984 free_list(imap
->ns_shared
);
988 static void imap_close_store(struct store
*ctx
)
990 imap_close_server((struct imap_store
*)ctx
);
991 free_generic_messages(ctx
->msgs
);
998 * hexchar() and cram() functions are based on the code from the isync
999 * project (http://isync.sf.net/).
1001 static char hexchar(unsigned int b
)
1003 return b
< 10 ? '0' + b
: 'a' + (b
- 10);
1006 #define ENCODED_SIZE(n) (4*((n+2)/3))
1007 static char *cram(const char *challenge_64
, const char *user
, const char *pass
)
1009 int i
, resp_len
, encoded_len
, decoded_len
;
1011 unsigned char hash
[16];
1013 char *response
, *response_64
, *challenge
;
1016 * length of challenge_64 (i.e. base-64 encoded string) is a good
1017 * enough upper bound for challenge (decoded result).
1019 encoded_len
= strlen(challenge_64
);
1020 challenge
= xmalloc(encoded_len
);
1021 decoded_len
= EVP_DecodeBlock((unsigned char *)challenge
,
1022 (unsigned char *)challenge_64
, encoded_len
);
1023 if (decoded_len
< 0)
1024 die("invalid challenge %s", challenge_64
);
1025 HMAC_Init(&hmac
, (unsigned char *)pass
, strlen(pass
), EVP_md5());
1026 HMAC_Update(&hmac
, (unsigned char *)challenge
, decoded_len
);
1027 HMAC_Final(&hmac
, hash
, NULL
);
1028 HMAC_CTX_cleanup(&hmac
);
1031 for (i
= 0; i
< 16; i
++) {
1032 hex
[2 * i
] = hexchar((hash
[i
] >> 4) & 0xf);
1033 hex
[2 * i
+ 1] = hexchar(hash
[i
] & 0xf);
1036 /* response: "<user> <digest in hex>" */
1037 resp_len
= strlen(user
) + 1 + strlen(hex
) + 1;
1038 response
= xmalloc(resp_len
);
1039 sprintf(response
, "%s %s", user
, hex
);
1041 response_64
= xmalloc(ENCODED_SIZE(resp_len
) + 1);
1042 encoded_len
= EVP_EncodeBlock((unsigned char *)response_64
,
1043 (unsigned char *)response
, resp_len
);
1044 if (encoded_len
< 0)
1045 die("EVP_EncodeBlock error");
1046 response_64
[encoded_len
] = '\0';
1047 return (char *)response_64
;
1052 static char *cram(const char *challenge_64
, const char *user
, const char *pass
)
1054 die("If you want to use CRAM-MD5 authenticate method, "
1055 "you have to build git-imap-send with OpenSSL library.");
1060 static int auth_cram_md5(struct imap_store
*ctx
, struct imap_cmd
*cmd
, const char *prompt
)
1065 response
= cram(prompt
, server
.user
, server
.pass
);
1067 ret
= socket_write(&ctx
->imap
->buf
.sock
, response
, strlen(response
));
1068 if (ret
!= strlen(response
))
1069 return error("IMAP error: sending response failed\n");
1076 static struct store
*imap_open_store(struct imap_server_conf
*srvc
)
1078 struct imap_store
*ctx
;
1081 int s
= -1, preauth
;
1083 ctx
= xcalloc(sizeof(*ctx
), 1);
1085 ctx
->imap
= imap
= xcalloc(sizeof(*imap
), 1);
1086 imap
->buf
.sock
.fd
[0] = imap
->buf
.sock
.fd
[1] = -1;
1087 imap
->in_progress_append
= &imap
->in_progress
;
1089 /* open connection to IMAP server */
1092 const char *argv
[] = { srvc
->tunnel
, NULL
};
1093 struct child_process tunnel
= {NULL
};
1095 imap_info("Starting tunnel '%s'... ", srvc
->tunnel
);
1098 tunnel
.use_shell
= 1;
1101 if (start_command(&tunnel
))
1102 die("cannot start proxy %s", argv
[0]);
1104 imap
->buf
.sock
.fd
[0] = tunnel
.out
;
1105 imap
->buf
.sock
.fd
[1] = tunnel
.in
;
1110 struct addrinfo hints
, *ai0
, *ai
;
1114 snprintf(portstr
, sizeof(portstr
), "%d", srvc
->port
);
1116 memset(&hints
, 0, sizeof(hints
));
1117 hints
.ai_socktype
= SOCK_STREAM
;
1118 hints
.ai_protocol
= IPPROTO_TCP
;
1120 imap_info("Resolving %s... ", srvc
->host
);
1121 gai
= getaddrinfo(srvc
->host
, portstr
, &hints
, &ai
);
1123 fprintf(stderr
, "getaddrinfo: %s\n", gai_strerror(gai
));
1128 for (ai0
= ai
; ai
; ai
= ai
->ai_next
) {
1129 char addr
[NI_MAXHOST
];
1131 s
= socket(ai
->ai_family
, ai
->ai_socktype
,
1136 getnameinfo(ai
->ai_addr
, ai
->ai_addrlen
, addr
,
1137 sizeof(addr
), NULL
, 0, NI_NUMERICHOST
);
1138 imap_info("Connecting to [%s]:%s... ", addr
, portstr
);
1140 if (connect(s
, ai
->ai_addr
, ai
->ai_addrlen
) < 0) {
1152 struct sockaddr_in addr
;
1154 memset(&addr
, 0, sizeof(addr
));
1155 addr
.sin_port
= htons(srvc
->port
);
1156 addr
.sin_family
= AF_INET
;
1158 imap_info("Resolving %s... ", srvc
->host
);
1159 he
= gethostbyname(srvc
->host
);
1161 perror("gethostbyname");
1166 addr
.sin_addr
.s_addr
= *((int *) he
->h_addr_list
[0]);
1168 s
= socket(PF_INET
, SOCK_STREAM
, 0);
1170 imap_info("Connecting to %s:%hu... ", inet_ntoa(addr
.sin_addr
), ntohs(addr
.sin_port
));
1171 if (connect(s
, (struct sockaddr
*)&addr
, sizeof(addr
))) {
1178 fputs("Error: unable to connect to server.\n", stderr
);
1182 imap
->buf
.sock
.fd
[0] = s
;
1183 imap
->buf
.sock
.fd
[1] = dup(s
);
1185 if (srvc
->use_ssl
&&
1186 ssl_socket_connect(&imap
->buf
.sock
, 0, srvc
->ssl_verify
)) {
1193 /* read the greeting string */
1194 if (buffer_gets(&imap
->buf
, &rsp
)) {
1195 fprintf(stderr
, "IMAP error: no greeting response\n");
1198 arg
= next_arg(&rsp
);
1199 if (!arg
|| *arg
!= '*' || (arg
= next_arg(&rsp
)) == NULL
) {
1200 fprintf(stderr
, "IMAP error: invalid greeting response\n");
1204 if (!strcmp("PREAUTH", arg
))
1206 else if (strcmp("OK", arg
) != 0) {
1207 fprintf(stderr
, "IMAP error: unknown greeting response\n");
1210 parse_response_code(ctx
, NULL
, rsp
);
1211 if (!imap
->caps
&& imap_exec(ctx
, NULL
, "CAPABILITY") != RESP_OK
)
1216 if (!srvc
->use_ssl
&& CAP(STARTTLS
)) {
1217 if (imap_exec(ctx
, NULL
, "STARTTLS") != RESP_OK
)
1219 if (ssl_socket_connect(&imap
->buf
.sock
, 1,
1222 /* capabilities may have changed, so get the new capabilities */
1223 if (imap_exec(ctx
, NULL
, "CAPABILITY") != RESP_OK
)
1227 imap_info("Logging in...\n");
1229 fprintf(stderr
, "Skipping server %s, no user\n", srvc
->host
);
1234 sprintf(prompt
, "Password (%s@%s): ", srvc
->user
, srvc
->host
);
1235 arg
= git_getpass(prompt
);
1241 fprintf(stderr
, "Skipping account %s@%s, no password\n", srvc
->user
, srvc
->host
);
1245 * getpass() returns a pointer to a static buffer. make a copy
1246 * for long term storage.
1248 srvc
->pass
= xstrdup(arg
);
1251 fprintf(stderr
, "Skipping account %s@%s, server forbids LOGIN\n", srvc
->user
, srvc
->host
);
1255 if (srvc
->auth_method
) {
1256 struct imap_cmd_cb cb
;
1258 if (!strcmp(srvc
->auth_method
, "CRAM-MD5")) {
1259 if (!CAP(AUTH_CRAM_MD5
)) {
1260 fprintf(stderr
, "You specified"
1261 "CRAM-MD5 as authentication method, "
1262 "but %s doesn't support it.\n", srvc
->host
);
1267 memset(&cb
, 0, sizeof(cb
));
1268 cb
.cont
= auth_cram_md5
;
1269 if (imap_exec(ctx
, &cb
, "AUTHENTICATE CRAM-MD5") != RESP_OK
) {
1270 fprintf(stderr
, "IMAP error: AUTHENTICATE CRAM-MD5 failed\n");
1274 fprintf(stderr
, "Unknown authentication method:%s\n", srvc
->host
);
1278 if (!imap
->buf
.sock
.ssl
)
1279 imap_warn("*** IMAP Warning *** Password is being "
1280 "sent in the clear\n");
1281 if (imap_exec(ctx
, NULL
, "LOGIN \"%s\" \"%s\"", srvc
->user
, srvc
->pass
) != RESP_OK
) {
1282 fprintf(stderr
, "IMAP error: LOGIN failed\n");
1290 return (struct store
*)ctx
;
1293 imap_close_store(&ctx
->gen
);
1297 static int imap_make_flags(int flags
, char *buf
)
1302 for (i
= d
= 0; i
< ARRAY_SIZE(Flags
); i
++)
1303 if (flags
& (1 << i
)) {
1306 for (s
= Flags
[i
]; *s
; s
++)
1314 static void lf_to_crlf(struct msg_data
*msg
)
1317 int i
, j
, lfnum
= 0;
1319 if (msg
->data
[0] == '\n')
1321 for (i
= 1; i
< msg
->len
; i
++) {
1322 if (msg
->data
[i
- 1] != '\r' && msg
->data
[i
] == '\n')
1326 new = xmalloc(msg
->len
+ lfnum
);
1327 if (msg
->data
[0] == '\n') {
1333 new[0] = msg
->data
[0];
1337 for ( ; i
< msg
->len
; i
++) {
1338 if (msg
->data
[i
] != '\n') {
1339 new[j
++] = msg
->data
[i
];
1342 if (msg
->data
[i
- 1] != '\r')
1344 /* otherwise it already had CR before */
1352 static int imap_store_msg(struct store
*gctx
, struct msg_data
*data
)
1354 struct imap_store
*ctx
= (struct imap_store
*)gctx
;
1355 struct imap
*imap
= ctx
->imap
;
1356 struct imap_cmd_cb cb
;
1357 const char *prefix
, *box
;
1362 memset(&cb
, 0, sizeof(cb
));
1364 cb
.dlen
= data
->len
;
1365 cb
.data
= xmalloc(cb
.dlen
);
1366 memcpy(cb
.data
, data
->data
, data
->len
);
1370 d
= imap_make_flags(data
->flags
, flagstr
);
1376 prefix
= !strcmp(box
, "INBOX") ? "" : ctx
->prefix
;
1378 ret
= imap_exec_m(ctx
, &cb
, "APPEND \"%s%s\" %s", prefix
, box
, flagstr
);
1379 imap
->caps
= imap
->rcaps
;
1387 static void encode_html_chars(struct strbuf
*p
)
1390 for (i
= 0; i
< p
->len
; i
++) {
1391 if (p
->buf
[i
] == '&')
1392 strbuf_splice(p
, i
, 1, "&", 5);
1393 if (p
->buf
[i
] == '<')
1394 strbuf_splice(p
, i
, 1, "<", 4);
1395 if (p
->buf
[i
] == '>')
1396 strbuf_splice(p
, i
, 1, ">", 4);
1397 if (p
->buf
[i
] == '"')
1398 strbuf_splice(p
, i
, 1, """, 6);
1401 static void wrap_in_html(struct msg_data
*msg
)
1403 struct strbuf buf
= STRBUF_INIT
;
1404 struct strbuf
**lines
;
1406 static char *content_type
= "Content-Type: text/html;\n";
1407 static char *pre_open
= "<pre>\n";
1408 static char *pre_close
= "</pre>\n";
1409 int added_header
= 0;
1411 strbuf_attach(&buf
, msg
->data
, msg
->len
, msg
->len
);
1412 lines
= strbuf_split(&buf
, '\n');
1413 strbuf_release(&buf
);
1414 for (p
= lines
; *p
; p
++) {
1415 if (! added_header
) {
1416 if ((*p
)->len
== 1 && *((*p
)->buf
) == '\n') {
1417 strbuf_addstr(&buf
, content_type
);
1418 strbuf_addbuf(&buf
, *p
);
1419 strbuf_addstr(&buf
, pre_open
);
1425 encode_html_chars(*p
);
1426 strbuf_addbuf(&buf
, *p
);
1428 strbuf_addstr(&buf
, pre_close
);
1429 strbuf_list_free(lines
);
1431 msg
->data
= strbuf_detach(&buf
, NULL
);
1434 #define CHUNKSIZE 0x1000
1436 static int read_message(FILE *f
, struct msg_data
*msg
)
1438 struct strbuf buf
= STRBUF_INIT
;
1440 memset(msg
, 0, sizeof(*msg
));
1443 if (strbuf_fread(&buf
, CHUNKSIZE
, f
) <= 0)
1448 msg
->data
= strbuf_detach(&buf
, NULL
);
1452 static int count_messages(struct msg_data
*msg
)
1455 char *p
= msg
->data
;
1458 if (!prefixcmp(p
, "From ")) {
1459 p
= strstr(p
+5, "\nFrom: ");
1461 p
= strstr(p
+7, "\nDate: ");
1463 p
= strstr(p
+7, "\nSubject: ");
1468 p
= strstr(p
+5, "\nFrom ");
1476 static int split_msg(struct msg_data
*all_msgs
, struct msg_data
*msg
, int *ofs
)
1480 memset(msg
, 0, sizeof *msg
);
1481 if (*ofs
>= all_msgs
->len
)
1484 data
= &all_msgs
->data
[*ofs
];
1485 msg
->len
= all_msgs
->len
- *ofs
;
1487 if (msg
->len
< 5 || prefixcmp(data
, "From "))
1490 p
= strchr(data
, '\n');
1498 p
= strstr(data
, "\nFrom ");
1500 msg
->len
= &p
[1] - data
;
1502 msg
->data
= xmemdupz(data
, msg
->len
);
1507 static char *imap_folder
;
1509 static int git_imap_config(const char *key
, const char *val
, void *cb
)
1511 char imap_key
[] = "imap.";
1513 if (strncmp(key
, imap_key
, sizeof imap_key
- 1))
1516 key
+= sizeof imap_key
- 1;
1518 /* check booleans first, and barf on others */
1519 if (!strcmp("sslverify", key
))
1520 server
.ssl_verify
= git_config_bool(key
, val
);
1521 else if (!strcmp("preformattedhtml", key
))
1522 server
.use_html
= git_config_bool(key
, val
);
1524 return config_error_nonbool(key
);
1526 if (!strcmp("folder", key
)) {
1527 imap_folder
= xstrdup(val
);
1528 } else if (!strcmp("host", key
)) {
1529 if (!prefixcmp(val
, "imap:"))
1531 else if (!prefixcmp(val
, "imaps:")) {
1535 if (!prefixcmp(val
, "//"))
1537 server
.host
= xstrdup(val
);
1538 } else if (!strcmp("user", key
))
1539 server
.user
= xstrdup(val
);
1540 else if (!strcmp("pass", key
))
1541 server
.pass
= xstrdup(val
);
1542 else if (!strcmp("port", key
))
1543 server
.port
= git_config_int(key
, val
);
1544 else if (!strcmp("tunnel", key
))
1545 server
.tunnel
= xstrdup(val
);
1546 else if (!strcmp("authmethod", key
))
1547 server
.auth_method
= xstrdup(val
);
1552 int main(int argc
, char **argv
)
1554 struct msg_data all_msgs
, msg
;
1555 struct store
*ctx
= NULL
;
1561 git_extract_argv0_path(argv
[0]);
1564 usage(imap_send_usage
);
1566 setup_git_directory_gently(&nongit_ok
);
1567 git_config(git_imap_config
, NULL
);
1570 server
.port
= server
.use_ssl
? 993 : 143;
1573 fprintf(stderr
, "no imap store specified\n");
1577 if (!server
.tunnel
) {
1578 fprintf(stderr
, "no imap host specified\n");
1581 server
.host
= "tunnel";
1584 /* read the messages */
1585 if (!read_message(stdin
, &all_msgs
)) {
1586 fprintf(stderr
, "nothing to send\n");
1590 total
= count_messages(&all_msgs
);
1592 fprintf(stderr
, "no messages to send\n");
1596 /* write it to the imap server */
1597 ctx
= imap_open_store(&server
);
1599 fprintf(stderr
, "failed to open store\n");
1603 fprintf(stderr
, "sending %d message%s\n", total
, (total
!= 1) ? "s" : "");
1604 ctx
->name
= imap_folder
;
1606 unsigned percent
= n
* 100 / total
;
1607 fprintf(stderr
, "%4u%% (%d/%d) done\r", percent
, n
, total
);
1608 if (!split_msg(&all_msgs
, &msg
, &ofs
))
1610 if (server
.use_html
)
1612 r
= imap_store_msg(ctx
, &msg
);
1617 fprintf(stderr
, "\n");
1619 imap_close_store(ctx
);