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>
37 /* currently open mailbox */
38 const char *name
; /* foreign! maybe preset? */
41 unsigned char opts
; /* maybe preset? */
42 /* note that the following do _not_ reflect stats from msgs, but mailbox totals */
43 int count
; /* # of messages */
44 int recent
; /* # of recent messages - don't trust this beyond the initial read */
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 */
107 #define NIL (void *)0x1
108 #define LIST (void *)0x2
111 struct imap_list
*next
, *child
;
122 struct imap_socket sock
;
131 int uidnext
; /* from SELECT responses */
132 struct imap_list
*ns_personal
, *ns_other
, *ns_shared
; /* NAMESPACE info */
133 unsigned caps
, rcaps
; /* CAPABILITY results */
135 int nexttag
, num_in_progress
, literal_pending
;
136 struct imap_cmd
*in_progress
, **in_progress_append
;
137 struct imap_buffer buf
; /* this is BIG, so put it last */
145 unsigned /*currentnc:1,*/ trashnc
:1;
149 int (*cont
)(struct imap_store
*ctx
, struct imap_cmd
*cmd
, const char *prompt
);
150 void (*done
)(struct imap_store
*ctx
, struct imap_cmd
*cmd
, int response
);
155 unsigned create
:1, trycreate
:1;
159 struct imap_cmd
*next
;
160 struct imap_cmd_cb cb
;
165 #define CAP(cap) (imap->caps & (1 << (cap)))
176 static const char *cap_list
[] = {
189 static int get_cmd_result(struct imap_store
*ctx
, struct imap_cmd
*tcmd
);
193 static void ssl_socket_perror(const char *func
)
195 fprintf(stderr
, "%s: %s\n", func
, ERR_error_string(ERR_get_error(), NULL
));
199 static void socket_perror(const char *func
, struct imap_socket
*sock
, int ret
)
203 int sslerr
= SSL_get_error(sock
->ssl
, ret
);
207 case SSL_ERROR_SYSCALL
:
208 perror("SSL_connect");
211 ssl_socket_perror("SSL_connect");
220 fprintf(stderr
, "%s: unexpected EOF\n", func
);
224 static int ssl_socket_connect(struct imap_socket
*sock
, int use_tls_only
, int verify
)
227 fprintf(stderr
, "SSL requested but SSL support not compiled in\n");
230 #if (OPENSSL_VERSION_NUMBER >= 0x10000000L)
231 const SSL_METHOD
*meth
;
239 SSL_load_error_strings();
242 meth
= TLSv1_method();
244 meth
= SSLv23_method();
247 ssl_socket_perror("SSLv23_method");
251 ctx
= SSL_CTX_new(meth
);
254 SSL_CTX_set_verify(ctx
, SSL_VERIFY_PEER
, NULL
);
256 if (!SSL_CTX_set_default_verify_paths(ctx
)) {
257 ssl_socket_perror("SSL_CTX_set_default_verify_paths");
260 sock
->ssl
= SSL_new(ctx
);
262 ssl_socket_perror("SSL_new");
265 if (!SSL_set_rfd(sock
->ssl
, sock
->fd
[0])) {
266 ssl_socket_perror("SSL_set_rfd");
269 if (!SSL_set_wfd(sock
->ssl
, sock
->fd
[1])) {
270 ssl_socket_perror("SSL_set_wfd");
274 ret
= SSL_connect(sock
->ssl
);
276 socket_perror("SSL_connect", sock
, ret
);
284 static int socket_read(struct imap_socket
*sock
, char *buf
, int len
)
289 n
= SSL_read(sock
->ssl
, buf
, len
);
292 n
= xread(sock
->fd
[0], buf
, len
);
294 socket_perror("read", sock
, n
);
297 sock
->fd
[0] = sock
->fd
[1] = -1;
302 static int socket_write(struct imap_socket
*sock
, const char *buf
, int len
)
307 n
= SSL_write(sock
->ssl
, buf
, len
);
310 n
= write_in_full(sock
->fd
[1], buf
, len
);
312 socket_perror("write", sock
, n
);
315 sock
->fd
[0] = sock
->fd
[1] = -1;
320 static void socket_shutdown(struct imap_socket
*sock
)
324 SSL_shutdown(sock
->ssl
);
332 /* simple line buffering */
333 static int buffer_gets(struct imap_buffer
*b
, char **s
)
336 int start
= b
->offset
;
341 /* make sure we have enough data to read the \r\n sequence */
342 if (b
->offset
+ 1 >= b
->bytes
) {
344 /* shift down used bytes */
347 assert(start
<= b
->bytes
);
348 n
= b
->bytes
- start
;
351 memmove(b
->buf
, b
->buf
+ start
, n
);
357 n
= socket_read(&b
->sock
, b
->buf
+ b
->bytes
,
358 sizeof(b
->buf
) - b
->bytes
);
366 if (b
->buf
[b
->offset
] == '\r') {
367 assert(b
->offset
+ 1 < b
->bytes
);
368 if (b
->buf
[b
->offset
+ 1] == '\n') {
369 b
->buf
[b
->offset
] = 0; /* terminate the string */
370 b
->offset
+= 2; /* next line */
382 static void imap_info(const char *msg
, ...)
394 static void imap_warn(const char *msg
, ...)
400 vfprintf(stderr
, msg
, va
);
405 static char *next_arg(char **s
)
411 while (isspace((unsigned char) **s
))
420 *s
= strchr(*s
, '"');
423 while (**s
&& !isspace((unsigned char) **s
))
435 static int nfsnprintf(char *buf
, int blen
, const char *fmt
, ...)
441 if (blen
<= 0 || (unsigned)(ret
= vsnprintf(buf
, blen
, fmt
, va
)) >= (unsigned)blen
)
442 die("Fatal: buffer too small. Please report a bug.");
447 static struct imap_cmd
*v_issue_imap_cmd(struct imap_store
*ctx
,
448 struct imap_cmd_cb
*cb
,
449 const char *fmt
, va_list ap
)
451 struct imap
*imap
= ctx
->imap
;
452 struct imap_cmd
*cmd
;
456 cmd
= xmalloc(sizeof(struct imap_cmd
));
457 nfvasprintf(&cmd
->cmd
, fmt
, ap
);
458 cmd
->tag
= ++imap
->nexttag
;
463 memset(&cmd
->cb
, 0, sizeof(cmd
->cb
));
465 while (imap
->literal_pending
)
466 get_cmd_result(ctx
, NULL
);
469 bufl
= nfsnprintf(buf
, sizeof(buf
), "%d %s\r\n", cmd
->tag
, cmd
->cmd
);
471 bufl
= nfsnprintf(buf
, sizeof(buf
), "%d %s{%d%s}\r\n",
472 cmd
->tag
, cmd
->cmd
, cmd
->cb
.dlen
,
473 CAP(LITERALPLUS
) ? "+" : "");
476 if (imap
->num_in_progress
)
477 printf("(%d in progress) ", imap
->num_in_progress
);
478 if (memcmp(cmd
->cmd
, "LOGIN", 5))
479 printf(">>> %s", buf
);
481 printf(">>> %d LOGIN <user> <pass>\n", cmd
->tag
);
483 if (socket_write(&imap
->buf
.sock
, buf
, bufl
) != bufl
) {
491 if (CAP(LITERALPLUS
)) {
492 n
= socket_write(&imap
->buf
.sock
, cmd
->cb
.data
, cmd
->cb
.dlen
);
494 if (n
!= cmd
->cb
.dlen
||
495 socket_write(&imap
->buf
.sock
, "\r\n", 2) != 2) {
502 imap
->literal_pending
= 1;
503 } else if (cmd
->cb
.cont
)
504 imap
->literal_pending
= 1;
506 *imap
->in_progress_append
= cmd
;
507 imap
->in_progress_append
= &cmd
->next
;
508 imap
->num_in_progress
++;
512 __attribute__((format (printf
, 3, 4)))
513 static struct imap_cmd
*issue_imap_cmd(struct imap_store
*ctx
,
514 struct imap_cmd_cb
*cb
,
515 const char *fmt
, ...)
517 struct imap_cmd
*ret
;
521 ret
= v_issue_imap_cmd(ctx
, cb
, fmt
, ap
);
526 __attribute__((format (printf
, 3, 4)))
527 static int imap_exec(struct imap_store
*ctx
, struct imap_cmd_cb
*cb
,
528 const char *fmt
, ...)
531 struct imap_cmd
*cmdp
;
534 cmdp
= v_issue_imap_cmd(ctx
, cb
, fmt
, ap
);
539 return get_cmd_result(ctx
, cmdp
);
542 __attribute__((format (printf
, 3, 4)))
543 static int imap_exec_m(struct imap_store
*ctx
, struct imap_cmd_cb
*cb
,
544 const char *fmt
, ...)
547 struct imap_cmd
*cmdp
;
550 cmdp
= v_issue_imap_cmd(ctx
, cb
, fmt
, ap
);
553 return DRV_STORE_BAD
;
555 switch (get_cmd_result(ctx
, cmdp
)) {
556 case RESP_BAD
: return DRV_STORE_BAD
;
557 case RESP_NO
: return DRV_MSG_BAD
;
558 default: return DRV_OK
;
562 static int is_atom(struct imap_list
*list
)
564 return list
&& list
->val
&& list
->val
!= NIL
&& list
->val
!= LIST
;
567 static int is_list(struct imap_list
*list
)
569 return list
&& list
->val
== LIST
;
572 static void free_list(struct imap_list
*list
)
574 struct imap_list
*tmp
;
576 for (; list
; list
= tmp
) {
579 free_list(list
->child
);
580 else if (is_atom(list
))
586 static int parse_imap_list_l(struct imap
*imap
, char **sp
, struct imap_list
**curp
, int level
)
588 struct imap_list
*cur
;
593 while (isspace((unsigned char)*s
))
595 if (level
&& *s
== ')') {
599 *curp
= cur
= xmalloc(sizeof(*cur
));
601 cur
->val
= NULL
; /* for clean bail */
606 if (parse_imap_list_l(imap
, &s
, &cur
->child
, level
+ 1))
608 } else if (imap
&& *s
== '{') {
610 bytes
= cur
->len
= strtol(s
+ 1, &s
, 10);
614 s
= cur
->val
= xmalloc(cur
->len
);
616 /* dump whats left over in the input buffer */
617 n
= imap
->buf
.bytes
- imap
->buf
.offset
;
620 /* the entire message fit in the buffer */
623 memcpy(s
, imap
->buf
.buf
+ imap
->buf
.offset
, n
);
627 /* mark that we used part of the buffer */
628 imap
->buf
.offset
+= n
;
630 /* now read the rest of the message */
632 if ((n
= socket_read(&imap
->buf
.sock
, s
, bytes
)) <= 0)
638 if (buffer_gets(&imap
->buf
, &s
))
640 } else if (*s
== '"') {
644 for (; *s
!= '"'; s
++)
649 cur
->val
= xmemdupz(p
, cur
->len
);
653 for (; *s
&& !isspace((unsigned char)*s
); s
++)
654 if (level
&& *s
== ')')
657 if (cur
->len
== 3 && !memcmp("NIL", p
, 3))
660 cur
->val
= xmemdupz(p
, cur
->len
);
677 static struct imap_list
*parse_imap_list(struct imap
*imap
, char **sp
)
679 struct imap_list
*head
;
681 if (!parse_imap_list_l(imap
, sp
, &head
, 0))
687 static struct imap_list
*parse_list(char **sp
)
689 return parse_imap_list(NULL
, sp
);
692 static void parse_capability(struct imap
*imap
, char *cmd
)
697 imap
->caps
= 0x80000000;
698 while ((arg
= next_arg(&cmd
)))
699 for (i
= 0; i
< ARRAY_SIZE(cap_list
); i
++)
700 if (!strcmp(cap_list
[i
], arg
))
701 imap
->caps
|= 1 << i
;
702 imap
->rcaps
= imap
->caps
;
705 static int parse_response_code(struct imap_store
*ctx
, struct imap_cmd_cb
*cb
,
708 struct imap
*imap
= ctx
->imap
;
712 return RESP_OK
; /* no response code */
714 if (!(p
= strchr(s
, ']'))) {
715 fprintf(stderr
, "IMAP error: malformed response code\n");
720 if (!strcmp("UIDVALIDITY", arg
)) {
721 if (!(arg
= next_arg(&s
)) || !(ctx
->gen
.uidvalidity
= atoi(arg
))) {
722 fprintf(stderr
, "IMAP error: malformed UIDVALIDITY status\n");
725 } else if (!strcmp("UIDNEXT", arg
)) {
726 if (!(arg
= next_arg(&s
)) || !(imap
->uidnext
= atoi(arg
))) {
727 fprintf(stderr
, "IMAP error: malformed NEXTUID status\n");
730 } else if (!strcmp("CAPABILITY", arg
)) {
731 parse_capability(imap
, s
);
732 } else if (!strcmp("ALERT", arg
)) {
733 /* RFC2060 says that these messages MUST be displayed
736 for (; isspace((unsigned char)*p
); p
++);
737 fprintf(stderr
, "*** IMAP ALERT *** %s\n", p
);
738 } else if (cb
&& cb
->ctx
&& !strcmp("APPENDUID", arg
)) {
739 if (!(arg
= next_arg(&s
)) || !(ctx
->gen
.uidvalidity
= atoi(arg
)) ||
740 !(arg
= next_arg(&s
)) || !(*(int *)cb
->ctx
= atoi(arg
))) {
741 fprintf(stderr
, "IMAP error: malformed APPENDUID status\n");
748 static int get_cmd_result(struct imap_store
*ctx
, struct imap_cmd
*tcmd
)
750 struct imap
*imap
= ctx
->imap
;
751 struct imap_cmd
*cmdp
, **pcmdp
, *ncmdp
;
752 char *cmd
, *arg
, *arg1
, *p
;
753 int n
, resp
, resp2
, tag
;
756 if (buffer_gets(&imap
->buf
, &cmd
))
759 arg
= next_arg(&cmd
);
761 arg
= next_arg(&cmd
);
763 fprintf(stderr
, "IMAP error: unable to parse untagged response\n");
767 if (!strcmp("NAMESPACE", arg
)) {
768 imap
->ns_personal
= parse_list(&cmd
);
769 imap
->ns_other
= parse_list(&cmd
);
770 imap
->ns_shared
= parse_list(&cmd
);
771 } else if (!strcmp("OK", arg
) || !strcmp("BAD", arg
) ||
772 !strcmp("NO", arg
) || !strcmp("BYE", arg
)) {
773 if ((resp
= parse_response_code(ctx
, NULL
, cmd
)) != RESP_OK
)
775 } else if (!strcmp("CAPABILITY", arg
))
776 parse_capability(imap
, cmd
);
777 else if ((arg1
= next_arg(&cmd
))) {
778 if (!strcmp("EXISTS", arg1
))
779 ctx
->gen
.count
= atoi(arg
);
780 else if (!strcmp("RECENT", arg1
))
781 ctx
->gen
.recent
= atoi(arg
);
783 fprintf(stderr
, "IMAP error: unable to parse untagged response\n");
786 } else if (!imap
->in_progress
) {
787 fprintf(stderr
, "IMAP error: unexpected reply: %s %s\n", arg
, cmd
? cmd
: "");
789 } else if (*arg
== '+') {
790 /* This can happen only with the last command underway, as
791 it enforces a round-trip. */
792 cmdp
= (struct imap_cmd
*)((char *)imap
->in_progress_append
-
793 offsetof(struct imap_cmd
, next
));
795 n
= socket_write(&imap
->buf
.sock
, cmdp
->cb
.data
, cmdp
->cb
.dlen
);
797 cmdp
->cb
.data
= NULL
;
798 if (n
!= (int)cmdp
->cb
.dlen
)
800 } else if (cmdp
->cb
.cont
) {
801 if (cmdp
->cb
.cont(ctx
, cmdp
, cmd
))
804 fprintf(stderr
, "IMAP error: unexpected command continuation request\n");
807 if (socket_write(&imap
->buf
.sock
, "\r\n", 2) != 2)
810 imap
->literal_pending
= 0;
815 for (pcmdp
= &imap
->in_progress
; (cmdp
= *pcmdp
); pcmdp
= &cmdp
->next
)
816 if (cmdp
->tag
== tag
)
818 fprintf(stderr
, "IMAP error: unexpected tag %s\n", arg
);
821 if (!(*pcmdp
= cmdp
->next
))
822 imap
->in_progress_append
= pcmdp
;
823 imap
->num_in_progress
--;
824 if (cmdp
->cb
.cont
|| cmdp
->cb
.data
)
825 imap
->literal_pending
= 0;
826 arg
= next_arg(&cmd
);
827 if (!strcmp("OK", arg
))
830 if (!strcmp("NO", arg
)) {
831 if (cmdp
->cb
.create
&& cmd
&& (cmdp
->cb
.trycreate
|| !memcmp(cmd
, "[TRYCREATE]", 11))) { /* SELECT, APPEND or UID COPY */
832 p
= strchr(cmdp
->cmd
, '"');
833 if (!issue_imap_cmd(ctx
, NULL
, "CREATE \"%.*s\"", (int)(strchr(p
+ 1, '"') - p
+ 1), p
)) {
837 /* not waiting here violates the spec, but a server that does not
838 grok this nonetheless violates it too. */
840 if (!(ncmdp
= issue_imap_cmd(ctx
, &cmdp
->cb
, "%s", cmdp
->cmd
))) {
847 return 0; /* ignored */
853 } else /*if (!strcmp("BAD", arg))*/
855 fprintf(stderr
, "IMAP command '%s' returned response (%s) - %s\n",
856 memcmp(cmdp
->cmd
, "LOGIN", 5) ?
857 cmdp
->cmd
: "LOGIN <user> <pass>",
858 arg
, cmd
? cmd
: "");
860 if ((resp2
= parse_response_code(ctx
, &cmdp
->cb
, cmd
)) > resp
)
864 cmdp
->cb
.done(ctx
, cmdp
, resp
);
868 if (!tcmd
|| tcmd
== cmdp
)
875 static void imap_close_server(struct imap_store
*ictx
)
877 struct imap
*imap
= ictx
->imap
;
879 if (imap
->buf
.sock
.fd
[0] != -1) {
880 imap_exec(ictx
, NULL
, "LOGOUT");
881 socket_shutdown(&imap
->buf
.sock
);
883 free_list(imap
->ns_personal
);
884 free_list(imap
->ns_other
);
885 free_list(imap
->ns_shared
);
889 static void imap_close_store(struct store
*ctx
)
891 imap_close_server((struct imap_store
*)ctx
);
898 * hexchar() and cram() functions are based on the code from the isync
899 * project (http://isync.sf.net/).
901 static char hexchar(unsigned int b
)
903 return b
< 10 ? '0' + b
: 'a' + (b
- 10);
906 #define ENCODED_SIZE(n) (4*((n+2)/3))
907 static char *cram(const char *challenge_64
, const char *user
, const char *pass
)
909 int i
, resp_len
, encoded_len
, decoded_len
;
911 unsigned char hash
[16];
913 char *response
, *response_64
, *challenge
;
916 * length of challenge_64 (i.e. base-64 encoded string) is a good
917 * enough upper bound for challenge (decoded result).
919 encoded_len
= strlen(challenge_64
);
920 challenge
= xmalloc(encoded_len
);
921 decoded_len
= EVP_DecodeBlock((unsigned char *)challenge
,
922 (unsigned char *)challenge_64
, encoded_len
);
924 die("invalid challenge %s", challenge_64
);
925 HMAC_Init(&hmac
, (unsigned char *)pass
, strlen(pass
), EVP_md5());
926 HMAC_Update(&hmac
, (unsigned char *)challenge
, decoded_len
);
927 HMAC_Final(&hmac
, hash
, NULL
);
928 HMAC_CTX_cleanup(&hmac
);
931 for (i
= 0; i
< 16; i
++) {
932 hex
[2 * i
] = hexchar((hash
[i
] >> 4) & 0xf);
933 hex
[2 * i
+ 1] = hexchar(hash
[i
] & 0xf);
936 /* response: "<user> <digest in hex>" */
937 resp_len
= strlen(user
) + 1 + strlen(hex
) + 1;
938 response
= xmalloc(resp_len
);
939 sprintf(response
, "%s %s", user
, hex
);
941 response_64
= xmalloc(ENCODED_SIZE(resp_len
) + 1);
942 encoded_len
= EVP_EncodeBlock((unsigned char *)response_64
,
943 (unsigned char *)response
, resp_len
);
945 die("EVP_EncodeBlock error");
946 response_64
[encoded_len
] = '\0';
947 return (char *)response_64
;
952 static char *cram(const char *challenge_64
, const char *user
, const char *pass
)
954 die("If you want to use CRAM-MD5 authenticate method, "
955 "you have to build git-imap-send with OpenSSL library.");
960 static int auth_cram_md5(struct imap_store
*ctx
, struct imap_cmd
*cmd
, const char *prompt
)
965 response
= cram(prompt
, server
.user
, server
.pass
);
967 ret
= socket_write(&ctx
->imap
->buf
.sock
, response
, strlen(response
));
968 if (ret
!= strlen(response
))
969 return error("IMAP error: sending response failed");
976 static struct store
*imap_open_store(struct imap_server_conf
*srvc
)
978 struct imap_store
*ctx
;
983 ctx
= xcalloc(sizeof(*ctx
), 1);
985 ctx
->imap
= imap
= xcalloc(sizeof(*imap
), 1);
986 imap
->buf
.sock
.fd
[0] = imap
->buf
.sock
.fd
[1] = -1;
987 imap
->in_progress_append
= &imap
->in_progress
;
989 /* open connection to IMAP server */
992 const char *argv
[] = { srvc
->tunnel
, NULL
};
993 struct child_process tunnel
= {NULL
};
995 imap_info("Starting tunnel '%s'... ", srvc
->tunnel
);
998 tunnel
.use_shell
= 1;
1001 if (start_command(&tunnel
))
1002 die("cannot start proxy %s", argv
[0]);
1004 imap
->buf
.sock
.fd
[0] = tunnel
.out
;
1005 imap
->buf
.sock
.fd
[1] = tunnel
.in
;
1010 struct addrinfo hints
, *ai0
, *ai
;
1014 snprintf(portstr
, sizeof(portstr
), "%d", srvc
->port
);
1016 memset(&hints
, 0, sizeof(hints
));
1017 hints
.ai_socktype
= SOCK_STREAM
;
1018 hints
.ai_protocol
= IPPROTO_TCP
;
1020 imap_info("Resolving %s... ", srvc
->host
);
1021 gai
= getaddrinfo(srvc
->host
, portstr
, &hints
, &ai
);
1023 fprintf(stderr
, "getaddrinfo: %s\n", gai_strerror(gai
));
1028 for (ai0
= ai
; ai
; ai
= ai
->ai_next
) {
1029 char addr
[NI_MAXHOST
];
1031 s
= socket(ai
->ai_family
, ai
->ai_socktype
,
1036 getnameinfo(ai
->ai_addr
, ai
->ai_addrlen
, addr
,
1037 sizeof(addr
), NULL
, 0, NI_NUMERICHOST
);
1038 imap_info("Connecting to [%s]:%s... ", addr
, portstr
);
1040 if (connect(s
, ai
->ai_addr
, ai
->ai_addrlen
) < 0) {
1052 struct sockaddr_in addr
;
1054 memset(&addr
, 0, sizeof(addr
));
1055 addr
.sin_port
= htons(srvc
->port
);
1056 addr
.sin_family
= AF_INET
;
1058 imap_info("Resolving %s... ", srvc
->host
);
1059 he
= gethostbyname(srvc
->host
);
1061 perror("gethostbyname");
1066 addr
.sin_addr
.s_addr
= *((int *) he
->h_addr_list
[0]);
1068 s
= socket(PF_INET
, SOCK_STREAM
, 0);
1070 imap_info("Connecting to %s:%hu... ", inet_ntoa(addr
.sin_addr
), ntohs(addr
.sin_port
));
1071 if (connect(s
, (struct sockaddr
*)&addr
, sizeof(addr
))) {
1078 fputs("Error: unable to connect to server.\n", stderr
);
1082 imap
->buf
.sock
.fd
[0] = s
;
1083 imap
->buf
.sock
.fd
[1] = dup(s
);
1085 if (srvc
->use_ssl
&&
1086 ssl_socket_connect(&imap
->buf
.sock
, 0, srvc
->ssl_verify
)) {
1093 /* read the greeting string */
1094 if (buffer_gets(&imap
->buf
, &rsp
)) {
1095 fprintf(stderr
, "IMAP error: no greeting response\n");
1098 arg
= next_arg(&rsp
);
1099 if (!arg
|| *arg
!= '*' || (arg
= next_arg(&rsp
)) == NULL
) {
1100 fprintf(stderr
, "IMAP error: invalid greeting response\n");
1104 if (!strcmp("PREAUTH", arg
))
1106 else if (strcmp("OK", arg
) != 0) {
1107 fprintf(stderr
, "IMAP error: unknown greeting response\n");
1110 parse_response_code(ctx
, NULL
, rsp
);
1111 if (!imap
->caps
&& imap_exec(ctx
, NULL
, "CAPABILITY") != RESP_OK
)
1116 if (!srvc
->use_ssl
&& CAP(STARTTLS
)) {
1117 if (imap_exec(ctx
, NULL
, "STARTTLS") != RESP_OK
)
1119 if (ssl_socket_connect(&imap
->buf
.sock
, 1,
1122 /* capabilities may have changed, so get the new capabilities */
1123 if (imap_exec(ctx
, NULL
, "CAPABILITY") != RESP_OK
)
1127 imap_info("Logging in...\n");
1129 fprintf(stderr
, "Skipping server %s, no user\n", srvc
->host
);
1133 struct strbuf prompt
= STRBUF_INIT
;
1134 strbuf_addf(&prompt
, "Password (%s@%s): ", srvc
->user
, srvc
->host
);
1135 arg
= git_getpass(prompt
.buf
);
1136 strbuf_release(&prompt
);
1138 fprintf(stderr
, "Skipping account %s@%s, no password\n", srvc
->user
, srvc
->host
);
1142 * getpass() returns a pointer to a static buffer. make a copy
1143 * for long term storage.
1145 srvc
->pass
= xstrdup(arg
);
1148 fprintf(stderr
, "Skipping account %s@%s, server forbids LOGIN\n", srvc
->user
, srvc
->host
);
1152 if (srvc
->auth_method
) {
1153 struct imap_cmd_cb cb
;
1155 if (!strcmp(srvc
->auth_method
, "CRAM-MD5")) {
1156 if (!CAP(AUTH_CRAM_MD5
)) {
1157 fprintf(stderr
, "You specified"
1158 "CRAM-MD5 as authentication method, "
1159 "but %s doesn't support it.\n", srvc
->host
);
1164 memset(&cb
, 0, sizeof(cb
));
1165 cb
.cont
= auth_cram_md5
;
1166 if (imap_exec(ctx
, &cb
, "AUTHENTICATE CRAM-MD5") != RESP_OK
) {
1167 fprintf(stderr
, "IMAP error: AUTHENTICATE CRAM-MD5 failed\n");
1171 fprintf(stderr
, "Unknown authentication method:%s\n", srvc
->host
);
1175 if (!imap
->buf
.sock
.ssl
)
1176 imap_warn("*** IMAP Warning *** Password is being "
1177 "sent in the clear\n");
1178 if (imap_exec(ctx
, NULL
, "LOGIN \"%s\" \"%s\"", srvc
->user
, srvc
->pass
) != RESP_OK
) {
1179 fprintf(stderr
, "IMAP error: LOGIN failed\n");
1187 return (struct store
*)ctx
;
1190 imap_close_store(&ctx
->gen
);
1194 static void lf_to_crlf(struct strbuf
*msg
)
1198 int i
, j
, lfnum
= 0;
1200 if (msg
->buf
[0] == '\n')
1202 for (i
= 1; i
< msg
->len
; i
++) {
1203 if (msg
->buf
[i
- 1] != '\r' && msg
->buf
[i
] == '\n')
1207 new_len
= msg
->len
+ lfnum
;
1208 new = xmalloc(new_len
+ 1);
1209 if (msg
->buf
[0] == '\n') {
1215 new[0] = msg
->buf
[0];
1219 for ( ; i
< msg
->len
; i
++) {
1220 if (msg
->buf
[i
] != '\n') {
1221 new[j
++] = msg
->buf
[i
];
1224 if (msg
->buf
[i
- 1] != '\r')
1226 /* otherwise it already had CR before */
1229 strbuf_attach(msg
, new, new_len
, new_len
+ 1);
1233 * Store msg to IMAP. Also detach and free the data from msg->data,
1234 * leaving msg->data empty.
1236 static int imap_store_msg(struct store
*gctx
, struct strbuf
*msg
)
1238 struct imap_store
*ctx
= (struct imap_store
*)gctx
;
1239 struct imap
*imap
= ctx
->imap
;
1240 struct imap_cmd_cb cb
;
1241 const char *prefix
, *box
;
1245 memset(&cb
, 0, sizeof(cb
));
1248 cb
.data
= strbuf_detach(msg
, NULL
);
1251 prefix
= !strcmp(box
, "INBOX") ? "" : ctx
->prefix
;
1253 ret
= imap_exec_m(ctx
, &cb
, "APPEND \"%s%s\" ", prefix
, box
);
1254 imap
->caps
= imap
->rcaps
;
1262 static void wrap_in_html(struct strbuf
*msg
)
1264 struct strbuf buf
= STRBUF_INIT
;
1265 static char *content_type
= "Content-Type: text/html;\n";
1266 static char *pre_open
= "<pre>\n";
1267 static char *pre_close
= "</pre>\n";
1268 const char *body
= strstr(msg
->buf
, "\n\n");
1271 return; /* Headers but no body; no wrapping needed */
1275 strbuf_add(&buf
, msg
->buf
, body
- msg
->buf
- 1);
1276 strbuf_addstr(&buf
, content_type
);
1277 strbuf_addch(&buf
, '\n');
1278 strbuf_addstr(&buf
, pre_open
);
1279 strbuf_addstr_xml_quoted(&buf
, body
);
1280 strbuf_addstr(&buf
, pre_close
);
1282 strbuf_release(msg
);
1286 #define CHUNKSIZE 0x1000
1288 static int read_message(FILE *f
, struct strbuf
*all_msgs
)
1291 if (strbuf_fread(all_msgs
, CHUNKSIZE
, f
) <= 0)
1295 return ferror(f
) ? -1 : 0;
1298 static int count_messages(struct strbuf
*all_msgs
)
1301 char *p
= all_msgs
->buf
;
1304 if (!prefixcmp(p
, "From ")) {
1305 p
= strstr(p
+5, "\nFrom: ");
1307 p
= strstr(p
+7, "\nDate: ");
1309 p
= strstr(p
+7, "\nSubject: ");
1314 p
= strstr(p
+5, "\nFrom ");
1323 * Copy the next message from all_msgs, starting at offset *ofs, to
1324 * msg. Update *ofs to the start of the following message. Return
1325 * true iff a message was successfully copied.
1327 static int split_msg(struct strbuf
*all_msgs
, struct strbuf
*msg
, int *ofs
)
1332 if (*ofs
>= all_msgs
->len
)
1335 data
= &all_msgs
->buf
[*ofs
];
1336 len
= all_msgs
->len
- *ofs
;
1338 if (len
< 5 || prefixcmp(data
, "From "))
1341 p
= strchr(data
, '\n');
1349 p
= strstr(data
, "\nFrom ");
1353 strbuf_add(msg
, data
, len
);
1358 static char *imap_folder
;
1360 static int git_imap_config(const char *key
, const char *val
, void *cb
)
1362 char imap_key
[] = "imap.";
1364 if (strncmp(key
, imap_key
, sizeof imap_key
- 1))
1367 key
+= sizeof imap_key
- 1;
1369 /* check booleans first, and barf on others */
1370 if (!strcmp("sslverify", key
))
1371 server
.ssl_verify
= git_config_bool(key
, val
);
1372 else if (!strcmp("preformattedhtml", key
))
1373 server
.use_html
= git_config_bool(key
, val
);
1375 return config_error_nonbool(key
);
1377 if (!strcmp("folder", key
)) {
1378 imap_folder
= xstrdup(val
);
1379 } else if (!strcmp("host", key
)) {
1380 if (!prefixcmp(val
, "imap:"))
1382 else if (!prefixcmp(val
, "imaps:")) {
1386 if (!prefixcmp(val
, "//"))
1388 server
.host
= xstrdup(val
);
1389 } else if (!strcmp("user", key
))
1390 server
.user
= xstrdup(val
);
1391 else if (!strcmp("pass", key
))
1392 server
.pass
= xstrdup(val
);
1393 else if (!strcmp("port", key
))
1394 server
.port
= git_config_int(key
, val
);
1395 else if (!strcmp("tunnel", key
))
1396 server
.tunnel
= xstrdup(val
);
1397 else if (!strcmp("authmethod", key
))
1398 server
.auth_method
= xstrdup(val
);
1403 int main(int argc
, char **argv
)
1405 struct strbuf all_msgs
= STRBUF_INIT
;
1406 struct strbuf msg
= STRBUF_INIT
;
1407 struct store
*ctx
= NULL
;
1413 git_extract_argv0_path(argv
[0]);
1415 git_setup_gettext();
1418 usage(imap_send_usage
);
1420 setup_git_directory_gently(&nongit_ok
);
1421 git_config(git_imap_config
, NULL
);
1424 server
.port
= server
.use_ssl
? 993 : 143;
1427 fprintf(stderr
, "no imap store specified\n");
1431 if (!server
.tunnel
) {
1432 fprintf(stderr
, "no imap host specified\n");
1435 server
.host
= "tunnel";
1438 /* read the messages */
1439 if (read_message(stdin
, &all_msgs
)) {
1440 fprintf(stderr
, "error reading input\n");
1444 if (all_msgs
.len
== 0) {
1445 fprintf(stderr
, "nothing to send\n");
1449 total
= count_messages(&all_msgs
);
1451 fprintf(stderr
, "no messages to send\n");
1455 /* write it to the imap server */
1456 ctx
= imap_open_store(&server
);
1458 fprintf(stderr
, "failed to open store\n");
1462 fprintf(stderr
, "sending %d message%s\n", total
, (total
!= 1) ? "s" : "");
1463 ctx
->name
= imap_folder
;
1465 unsigned percent
= n
* 100 / total
;
1467 fprintf(stderr
, "%4u%% (%d/%d) done\r", percent
, n
, total
);
1468 if (!split_msg(&all_msgs
, &msg
, &ofs
))
1470 if (server
.use_html
)
1472 r
= imap_store_msg(ctx
, &msg
);
1477 fprintf(stderr
, "\n");
1479 imap_close_store(ctx
);