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? */
42 static const char imap_send_usage
[] = "git imap-send < <mbox>";
46 #define DRV_MSG_BAD -1
47 #define DRV_BOX_BAD -2
48 #define DRV_STORE_BAD -3
50 static int Verbose
, Quiet
;
52 __attribute__((format (printf
, 1, 2)))
53 static void imap_info(const char *, ...);
54 __attribute__((format (printf
, 1, 2)))
55 static void imap_warn(const char *, ...);
57 static char *next_arg(char **);
59 __attribute__((format (printf
, 3, 4)))
60 static int nfsnprintf(char *buf
, int blen
, const char *fmt
, ...);
62 static int nfvasprintf(char **strp
, const char *fmt
, va_list ap
)
67 len
= vsnprintf(tmp
, sizeof(tmp
), fmt
, ap
);
69 die("Fatal: Out of memory");
70 if (len
>= sizeof(tmp
))
71 die("imap command overflow!");
72 *strp
= xmemdupz(tmp
, len
);
76 struct imap_server_conf
{
89 static struct imap_server_conf server
= {
99 NULL
, /* auth_method */
102 #define NIL (void *)0x1
103 #define LIST (void *)0x2
106 struct imap_list
*next
, *child
;
117 struct imap_socket sock
;
126 int uidnext
; /* from SELECT responses */
127 struct imap_list
*ns_personal
, *ns_other
, *ns_shared
; /* NAMESPACE info */
128 unsigned caps
, rcaps
; /* CAPABILITY results */
130 int nexttag
, num_in_progress
, literal_pending
;
131 struct imap_cmd
*in_progress
, **in_progress_append
;
132 struct imap_buffer buf
; /* this is BIG, so put it last */
140 unsigned /*currentnc:1,*/ trashnc
:1;
144 int (*cont
)(struct imap_store
*ctx
, struct imap_cmd
*cmd
, const char *prompt
);
145 void (*done
)(struct imap_store
*ctx
, struct imap_cmd
*cmd
, int response
);
150 unsigned create
:1, trycreate
:1;
154 struct imap_cmd
*next
;
155 struct imap_cmd_cb cb
;
160 #define CAP(cap) (imap->caps & (1 << (cap)))
171 static const char *cap_list
[] = {
184 static int get_cmd_result(struct imap_store
*ctx
, struct imap_cmd
*tcmd
);
188 static void ssl_socket_perror(const char *func
)
190 fprintf(stderr
, "%s: %s\n", func
, ERR_error_string(ERR_get_error(), NULL
));
194 static void socket_perror(const char *func
, struct imap_socket
*sock
, int ret
)
198 int sslerr
= SSL_get_error(sock
->ssl
, ret
);
202 case SSL_ERROR_SYSCALL
:
203 perror("SSL_connect");
206 ssl_socket_perror("SSL_connect");
215 fprintf(stderr
, "%s: unexpected EOF\n", func
);
219 static int ssl_socket_connect(struct imap_socket
*sock
, int use_tls_only
, int verify
)
222 fprintf(stderr
, "SSL requested but SSL support not compiled in\n");
225 #if (OPENSSL_VERSION_NUMBER >= 0x10000000L)
226 const SSL_METHOD
*meth
;
234 SSL_load_error_strings();
237 meth
= TLSv1_method();
239 meth
= SSLv23_method();
242 ssl_socket_perror("SSLv23_method");
246 ctx
= SSL_CTX_new(meth
);
249 SSL_CTX_set_verify(ctx
, SSL_VERIFY_PEER
, NULL
);
251 if (!SSL_CTX_set_default_verify_paths(ctx
)) {
252 ssl_socket_perror("SSL_CTX_set_default_verify_paths");
255 sock
->ssl
= SSL_new(ctx
);
257 ssl_socket_perror("SSL_new");
260 if (!SSL_set_rfd(sock
->ssl
, sock
->fd
[0])) {
261 ssl_socket_perror("SSL_set_rfd");
264 if (!SSL_set_wfd(sock
->ssl
, sock
->fd
[1])) {
265 ssl_socket_perror("SSL_set_wfd");
269 ret
= SSL_connect(sock
->ssl
);
271 socket_perror("SSL_connect", sock
, ret
);
279 static int socket_read(struct imap_socket
*sock
, char *buf
, int len
)
284 n
= SSL_read(sock
->ssl
, buf
, len
);
287 n
= xread(sock
->fd
[0], buf
, len
);
289 socket_perror("read", sock
, n
);
292 sock
->fd
[0] = sock
->fd
[1] = -1;
297 static int socket_write(struct imap_socket
*sock
, const char *buf
, int len
)
302 n
= SSL_write(sock
->ssl
, buf
, len
);
305 n
= write_in_full(sock
->fd
[1], buf
, len
);
307 socket_perror("write", sock
, n
);
310 sock
->fd
[0] = sock
->fd
[1] = -1;
315 static void socket_shutdown(struct imap_socket
*sock
)
319 SSL_shutdown(sock
->ssl
);
327 /* simple line buffering */
328 static int buffer_gets(struct imap_buffer
*b
, char **s
)
331 int start
= b
->offset
;
336 /* make sure we have enough data to read the \r\n sequence */
337 if (b
->offset
+ 1 >= b
->bytes
) {
339 /* shift down used bytes */
342 assert(start
<= b
->bytes
);
343 n
= b
->bytes
- start
;
346 memmove(b
->buf
, b
->buf
+ start
, n
);
352 n
= socket_read(&b
->sock
, b
->buf
+ b
->bytes
,
353 sizeof(b
->buf
) - b
->bytes
);
361 if (b
->buf
[b
->offset
] == '\r') {
362 assert(b
->offset
+ 1 < b
->bytes
);
363 if (b
->buf
[b
->offset
+ 1] == '\n') {
364 b
->buf
[b
->offset
] = 0; /* terminate the string */
365 b
->offset
+= 2; /* next line */
377 static void imap_info(const char *msg
, ...)
389 static void imap_warn(const char *msg
, ...)
395 vfprintf(stderr
, msg
, va
);
400 static char *next_arg(char **s
)
406 while (isspace((unsigned char) **s
))
415 *s
= strchr(*s
, '"');
418 while (**s
&& !isspace((unsigned char) **s
))
430 static int nfsnprintf(char *buf
, int blen
, const char *fmt
, ...)
436 if (blen
<= 0 || (unsigned)(ret
= vsnprintf(buf
, blen
, fmt
, va
)) >= (unsigned)blen
)
437 die("Fatal: buffer too small. Please report a bug.");
442 static struct imap_cmd
*v_issue_imap_cmd(struct imap_store
*ctx
,
443 struct imap_cmd_cb
*cb
,
444 const char *fmt
, va_list ap
)
446 struct imap
*imap
= ctx
->imap
;
447 struct imap_cmd
*cmd
;
451 cmd
= xmalloc(sizeof(struct imap_cmd
));
452 nfvasprintf(&cmd
->cmd
, fmt
, ap
);
453 cmd
->tag
= ++imap
->nexttag
;
458 memset(&cmd
->cb
, 0, sizeof(cmd
->cb
));
460 while (imap
->literal_pending
)
461 get_cmd_result(ctx
, NULL
);
464 bufl
= nfsnprintf(buf
, sizeof(buf
), "%d %s\r\n", cmd
->tag
, cmd
->cmd
);
466 bufl
= nfsnprintf(buf
, sizeof(buf
), "%d %s{%d%s}\r\n",
467 cmd
->tag
, cmd
->cmd
, cmd
->cb
.dlen
,
468 CAP(LITERALPLUS
) ? "+" : "");
471 if (imap
->num_in_progress
)
472 printf("(%d in progress) ", imap
->num_in_progress
);
473 if (memcmp(cmd
->cmd
, "LOGIN", 5))
474 printf(">>> %s", buf
);
476 printf(">>> %d LOGIN <user> <pass>\n", cmd
->tag
);
478 if (socket_write(&imap
->buf
.sock
, buf
, bufl
) != bufl
) {
486 if (CAP(LITERALPLUS
)) {
487 n
= socket_write(&imap
->buf
.sock
, cmd
->cb
.data
, cmd
->cb
.dlen
);
489 if (n
!= cmd
->cb
.dlen
||
490 socket_write(&imap
->buf
.sock
, "\r\n", 2) != 2) {
497 imap
->literal_pending
= 1;
498 } else if (cmd
->cb
.cont
)
499 imap
->literal_pending
= 1;
501 *imap
->in_progress_append
= cmd
;
502 imap
->in_progress_append
= &cmd
->next
;
503 imap
->num_in_progress
++;
507 __attribute__((format (printf
, 3, 4)))
508 static struct imap_cmd
*issue_imap_cmd(struct imap_store
*ctx
,
509 struct imap_cmd_cb
*cb
,
510 const char *fmt
, ...)
512 struct imap_cmd
*ret
;
516 ret
= v_issue_imap_cmd(ctx
, cb
, fmt
, ap
);
521 __attribute__((format (printf
, 3, 4)))
522 static int imap_exec(struct imap_store
*ctx
, struct imap_cmd_cb
*cb
,
523 const char *fmt
, ...)
526 struct imap_cmd
*cmdp
;
529 cmdp
= v_issue_imap_cmd(ctx
, cb
, fmt
, ap
);
534 return get_cmd_result(ctx
, cmdp
);
537 __attribute__((format (printf
, 3, 4)))
538 static int imap_exec_m(struct imap_store
*ctx
, struct imap_cmd_cb
*cb
,
539 const char *fmt
, ...)
542 struct imap_cmd
*cmdp
;
545 cmdp
= v_issue_imap_cmd(ctx
, cb
, fmt
, ap
);
548 return DRV_STORE_BAD
;
550 switch (get_cmd_result(ctx
, cmdp
)) {
551 case RESP_BAD
: return DRV_STORE_BAD
;
552 case RESP_NO
: return DRV_MSG_BAD
;
553 default: return DRV_OK
;
557 static int is_atom(struct imap_list
*list
)
559 return list
&& list
->val
&& list
->val
!= NIL
&& list
->val
!= LIST
;
562 static int is_list(struct imap_list
*list
)
564 return list
&& list
->val
== LIST
;
567 static void free_list(struct imap_list
*list
)
569 struct imap_list
*tmp
;
571 for (; list
; list
= tmp
) {
574 free_list(list
->child
);
575 else if (is_atom(list
))
581 static int parse_imap_list_l(struct imap
*imap
, char **sp
, struct imap_list
**curp
, int level
)
583 struct imap_list
*cur
;
588 while (isspace((unsigned char)*s
))
590 if (level
&& *s
== ')') {
594 *curp
= cur
= xmalloc(sizeof(*cur
));
596 cur
->val
= NULL
; /* for clean bail */
601 if (parse_imap_list_l(imap
, &s
, &cur
->child
, level
+ 1))
603 } else if (imap
&& *s
== '{') {
605 bytes
= cur
->len
= strtol(s
+ 1, &s
, 10);
609 s
= cur
->val
= xmalloc(cur
->len
);
611 /* dump whats left over in the input buffer */
612 n
= imap
->buf
.bytes
- imap
->buf
.offset
;
615 /* the entire message fit in the buffer */
618 memcpy(s
, imap
->buf
.buf
+ imap
->buf
.offset
, n
);
622 /* mark that we used part of the buffer */
623 imap
->buf
.offset
+= n
;
625 /* now read the rest of the message */
627 if ((n
= socket_read(&imap
->buf
.sock
, s
, bytes
)) <= 0)
633 if (buffer_gets(&imap
->buf
, &s
))
635 } else if (*s
== '"') {
639 for (; *s
!= '"'; s
++)
644 cur
->val
= xmemdupz(p
, cur
->len
);
648 for (; *s
&& !isspace((unsigned char)*s
); s
++)
649 if (level
&& *s
== ')')
652 if (cur
->len
== 3 && !memcmp("NIL", p
, 3))
655 cur
->val
= xmemdupz(p
, cur
->len
);
672 static struct imap_list
*parse_list(char **sp
)
674 struct imap_list
*head
;
676 if (!parse_imap_list_l(NULL
, sp
, &head
, 0))
682 static void parse_capability(struct imap
*imap
, char *cmd
)
687 imap
->caps
= 0x80000000;
688 while ((arg
= next_arg(&cmd
)))
689 for (i
= 0; i
< ARRAY_SIZE(cap_list
); i
++)
690 if (!strcmp(cap_list
[i
], arg
))
691 imap
->caps
|= 1 << i
;
692 imap
->rcaps
= imap
->caps
;
695 static int parse_response_code(struct imap_store
*ctx
, struct imap_cmd_cb
*cb
,
698 struct imap
*imap
= ctx
->imap
;
702 return RESP_OK
; /* no response code */
704 if (!(p
= strchr(s
, ']'))) {
705 fprintf(stderr
, "IMAP error: malformed response code\n");
710 if (!strcmp("UIDVALIDITY", arg
)) {
711 if (!(arg
= next_arg(&s
)) || !(ctx
->gen
.uidvalidity
= atoi(arg
))) {
712 fprintf(stderr
, "IMAP error: malformed UIDVALIDITY status\n");
715 } else if (!strcmp("UIDNEXT", arg
)) {
716 if (!(arg
= next_arg(&s
)) || !(imap
->uidnext
= atoi(arg
))) {
717 fprintf(stderr
, "IMAP error: malformed NEXTUID status\n");
720 } else if (!strcmp("CAPABILITY", arg
)) {
721 parse_capability(imap
, s
);
722 } else if (!strcmp("ALERT", arg
)) {
723 /* RFC2060 says that these messages MUST be displayed
726 for (; isspace((unsigned char)*p
); p
++);
727 fprintf(stderr
, "*** IMAP ALERT *** %s\n", p
);
728 } else if (cb
&& cb
->ctx
&& !strcmp("APPENDUID", arg
)) {
729 if (!(arg
= next_arg(&s
)) || !(ctx
->gen
.uidvalidity
= atoi(arg
)) ||
730 !(arg
= next_arg(&s
)) || !(*(int *)cb
->ctx
= atoi(arg
))) {
731 fprintf(stderr
, "IMAP error: malformed APPENDUID status\n");
738 static int get_cmd_result(struct imap_store
*ctx
, struct imap_cmd
*tcmd
)
740 struct imap
*imap
= ctx
->imap
;
741 struct imap_cmd
*cmdp
, **pcmdp
, *ncmdp
;
742 char *cmd
, *arg
, *arg1
, *p
;
743 int n
, resp
, resp2
, tag
;
746 if (buffer_gets(&imap
->buf
, &cmd
))
749 arg
= next_arg(&cmd
);
751 arg
= next_arg(&cmd
);
753 fprintf(stderr
, "IMAP error: unable to parse untagged response\n");
757 if (!strcmp("NAMESPACE", arg
)) {
758 imap
->ns_personal
= parse_list(&cmd
);
759 imap
->ns_other
= parse_list(&cmd
);
760 imap
->ns_shared
= parse_list(&cmd
);
761 } else if (!strcmp("OK", arg
) || !strcmp("BAD", arg
) ||
762 !strcmp("NO", arg
) || !strcmp("BYE", arg
)) {
763 if ((resp
= parse_response_code(ctx
, NULL
, cmd
)) != RESP_OK
)
765 } else if (!strcmp("CAPABILITY", arg
)) {
766 parse_capability(imap
, cmd
);
767 } else if ((arg1
= next_arg(&cmd
))) {
769 * Unhandled response-data with at least two words.
772 * NEEDSWORK: Previously this case handled '<num> EXISTS'
773 * and '<num> RECENT' but as a probably-unintended side
774 * effect it ignores other unrecognized two-word
775 * responses. imap-send doesn't ever try to read
776 * messages or mailboxes these days, so consider
777 * eliminating this case.
780 fprintf(stderr
, "IMAP error: unable to parse untagged response\n");
783 } else if (!imap
->in_progress
) {
784 fprintf(stderr
, "IMAP error: unexpected reply: %s %s\n", arg
, cmd
? cmd
: "");
786 } else if (*arg
== '+') {
787 /* This can happen only with the last command underway, as
788 it enforces a round-trip. */
789 cmdp
= (struct imap_cmd
*)((char *)imap
->in_progress_append
-
790 offsetof(struct imap_cmd
, next
));
792 n
= socket_write(&imap
->buf
.sock
, cmdp
->cb
.data
, cmdp
->cb
.dlen
);
794 cmdp
->cb
.data
= NULL
;
795 if (n
!= (int)cmdp
->cb
.dlen
)
797 } else if (cmdp
->cb
.cont
) {
798 if (cmdp
->cb
.cont(ctx
, cmdp
, cmd
))
801 fprintf(stderr
, "IMAP error: unexpected command continuation request\n");
804 if (socket_write(&imap
->buf
.sock
, "\r\n", 2) != 2)
807 imap
->literal_pending
= 0;
812 for (pcmdp
= &imap
->in_progress
; (cmdp
= *pcmdp
); pcmdp
= &cmdp
->next
)
813 if (cmdp
->tag
== tag
)
815 fprintf(stderr
, "IMAP error: unexpected tag %s\n", arg
);
818 if (!(*pcmdp
= cmdp
->next
))
819 imap
->in_progress_append
= pcmdp
;
820 imap
->num_in_progress
--;
821 if (cmdp
->cb
.cont
|| cmdp
->cb
.data
)
822 imap
->literal_pending
= 0;
823 arg
= next_arg(&cmd
);
824 if (!strcmp("OK", arg
))
827 if (!strcmp("NO", arg
)) {
828 if (cmdp
->cb
.create
&& cmd
&& (cmdp
->cb
.trycreate
|| !memcmp(cmd
, "[TRYCREATE]", 11))) { /* SELECT, APPEND or UID COPY */
829 p
= strchr(cmdp
->cmd
, '"');
830 if (!issue_imap_cmd(ctx
, NULL
, "CREATE \"%.*s\"", (int)(strchr(p
+ 1, '"') - p
+ 1), p
)) {
834 /* not waiting here violates the spec, but a server that does not
835 grok this nonetheless violates it too. */
837 if (!(ncmdp
= issue_imap_cmd(ctx
, &cmdp
->cb
, "%s", cmdp
->cmd
))) {
844 return 0; /* ignored */
850 } else /*if (!strcmp("BAD", arg))*/
852 fprintf(stderr
, "IMAP command '%s' returned response (%s) - %s\n",
853 memcmp(cmdp
->cmd
, "LOGIN", 5) ?
854 cmdp
->cmd
: "LOGIN <user> <pass>",
855 arg
, cmd
? cmd
: "");
857 if ((resp2
= parse_response_code(ctx
, &cmdp
->cb
, cmd
)) > resp
)
861 cmdp
->cb
.done(ctx
, cmdp
, resp
);
865 if (!tcmd
|| tcmd
== cmdp
)
872 static void imap_close_server(struct imap_store
*ictx
)
874 struct imap
*imap
= ictx
->imap
;
876 if (imap
->buf
.sock
.fd
[0] != -1) {
877 imap_exec(ictx
, NULL
, "LOGOUT");
878 socket_shutdown(&imap
->buf
.sock
);
880 free_list(imap
->ns_personal
);
881 free_list(imap
->ns_other
);
882 free_list(imap
->ns_shared
);
886 static void imap_close_store(struct store
*ctx
)
888 imap_close_server((struct imap_store
*)ctx
);
895 * hexchar() and cram() functions are based on the code from the isync
896 * project (http://isync.sf.net/).
898 static char hexchar(unsigned int b
)
900 return b
< 10 ? '0' + b
: 'a' + (b
- 10);
903 #define ENCODED_SIZE(n) (4*((n+2)/3))
904 static char *cram(const char *challenge_64
, const char *user
, const char *pass
)
906 int i
, resp_len
, encoded_len
, decoded_len
;
908 unsigned char hash
[16];
910 char *response
, *response_64
, *challenge
;
913 * length of challenge_64 (i.e. base-64 encoded string) is a good
914 * enough upper bound for challenge (decoded result).
916 encoded_len
= strlen(challenge_64
);
917 challenge
= xmalloc(encoded_len
);
918 decoded_len
= EVP_DecodeBlock((unsigned char *)challenge
,
919 (unsigned char *)challenge_64
, encoded_len
);
921 die("invalid challenge %s", challenge_64
);
922 HMAC_Init(&hmac
, (unsigned char *)pass
, strlen(pass
), EVP_md5());
923 HMAC_Update(&hmac
, (unsigned char *)challenge
, decoded_len
);
924 HMAC_Final(&hmac
, hash
, NULL
);
925 HMAC_CTX_cleanup(&hmac
);
928 for (i
= 0; i
< 16; i
++) {
929 hex
[2 * i
] = hexchar((hash
[i
] >> 4) & 0xf);
930 hex
[2 * i
+ 1] = hexchar(hash
[i
] & 0xf);
933 /* response: "<user> <digest in hex>" */
934 resp_len
= strlen(user
) + 1 + strlen(hex
) + 1;
935 response
= xmalloc(resp_len
);
936 sprintf(response
, "%s %s", user
, hex
);
938 response_64
= xmalloc(ENCODED_SIZE(resp_len
) + 1);
939 encoded_len
= EVP_EncodeBlock((unsigned char *)response_64
,
940 (unsigned char *)response
, resp_len
);
942 die("EVP_EncodeBlock error");
943 response_64
[encoded_len
] = '\0';
944 return (char *)response_64
;
949 static char *cram(const char *challenge_64
, const char *user
, const char *pass
)
951 die("If you want to use CRAM-MD5 authenticate method, "
952 "you have to build git-imap-send with OpenSSL library.");
957 static int auth_cram_md5(struct imap_store
*ctx
, struct imap_cmd
*cmd
, const char *prompt
)
962 response
= cram(prompt
, server
.user
, server
.pass
);
964 ret
= socket_write(&ctx
->imap
->buf
.sock
, response
, strlen(response
));
965 if (ret
!= strlen(response
))
966 return error("IMAP error: sending response failed");
973 static struct store
*imap_open_store(struct imap_server_conf
*srvc
)
975 struct imap_store
*ctx
;
980 ctx
= xcalloc(sizeof(*ctx
), 1);
982 ctx
->imap
= imap
= xcalloc(sizeof(*imap
), 1);
983 imap
->buf
.sock
.fd
[0] = imap
->buf
.sock
.fd
[1] = -1;
984 imap
->in_progress_append
= &imap
->in_progress
;
986 /* open connection to IMAP server */
989 const char *argv
[] = { srvc
->tunnel
, NULL
};
990 struct child_process tunnel
= {NULL
};
992 imap_info("Starting tunnel '%s'... ", srvc
->tunnel
);
995 tunnel
.use_shell
= 1;
998 if (start_command(&tunnel
))
999 die("cannot start proxy %s", argv
[0]);
1001 imap
->buf
.sock
.fd
[0] = tunnel
.out
;
1002 imap
->buf
.sock
.fd
[1] = tunnel
.in
;
1007 struct addrinfo hints
, *ai0
, *ai
;
1011 snprintf(portstr
, sizeof(portstr
), "%d", srvc
->port
);
1013 memset(&hints
, 0, sizeof(hints
));
1014 hints
.ai_socktype
= SOCK_STREAM
;
1015 hints
.ai_protocol
= IPPROTO_TCP
;
1017 imap_info("Resolving %s... ", srvc
->host
);
1018 gai
= getaddrinfo(srvc
->host
, portstr
, &hints
, &ai
);
1020 fprintf(stderr
, "getaddrinfo: %s\n", gai_strerror(gai
));
1025 for (ai0
= ai
; ai
; ai
= ai
->ai_next
) {
1026 char addr
[NI_MAXHOST
];
1028 s
= socket(ai
->ai_family
, ai
->ai_socktype
,
1033 getnameinfo(ai
->ai_addr
, ai
->ai_addrlen
, addr
,
1034 sizeof(addr
), NULL
, 0, NI_NUMERICHOST
);
1035 imap_info("Connecting to [%s]:%s... ", addr
, portstr
);
1037 if (connect(s
, ai
->ai_addr
, ai
->ai_addrlen
) < 0) {
1049 struct sockaddr_in addr
;
1051 memset(&addr
, 0, sizeof(addr
));
1052 addr
.sin_port
= htons(srvc
->port
);
1053 addr
.sin_family
= AF_INET
;
1055 imap_info("Resolving %s... ", srvc
->host
);
1056 he
= gethostbyname(srvc
->host
);
1058 perror("gethostbyname");
1063 addr
.sin_addr
.s_addr
= *((int *) he
->h_addr_list
[0]);
1065 s
= socket(PF_INET
, SOCK_STREAM
, 0);
1067 imap_info("Connecting to %s:%hu... ", inet_ntoa(addr
.sin_addr
), ntohs(addr
.sin_port
));
1068 if (connect(s
, (struct sockaddr
*)&addr
, sizeof(addr
))) {
1075 fputs("Error: unable to connect to server.\n", stderr
);
1079 imap
->buf
.sock
.fd
[0] = s
;
1080 imap
->buf
.sock
.fd
[1] = dup(s
);
1082 if (srvc
->use_ssl
&&
1083 ssl_socket_connect(&imap
->buf
.sock
, 0, srvc
->ssl_verify
)) {
1090 /* read the greeting string */
1091 if (buffer_gets(&imap
->buf
, &rsp
)) {
1092 fprintf(stderr
, "IMAP error: no greeting response\n");
1095 arg
= next_arg(&rsp
);
1096 if (!arg
|| *arg
!= '*' || (arg
= next_arg(&rsp
)) == NULL
) {
1097 fprintf(stderr
, "IMAP error: invalid greeting response\n");
1101 if (!strcmp("PREAUTH", arg
))
1103 else if (strcmp("OK", arg
) != 0) {
1104 fprintf(stderr
, "IMAP error: unknown greeting response\n");
1107 parse_response_code(ctx
, NULL
, rsp
);
1108 if (!imap
->caps
&& imap_exec(ctx
, NULL
, "CAPABILITY") != RESP_OK
)
1113 if (!srvc
->use_ssl
&& CAP(STARTTLS
)) {
1114 if (imap_exec(ctx
, NULL
, "STARTTLS") != RESP_OK
)
1116 if (ssl_socket_connect(&imap
->buf
.sock
, 1,
1119 /* capabilities may have changed, so get the new capabilities */
1120 if (imap_exec(ctx
, NULL
, "CAPABILITY") != RESP_OK
)
1124 imap_info("Logging in...\n");
1126 fprintf(stderr
, "Skipping server %s, no user\n", srvc
->host
);
1130 struct strbuf prompt
= STRBUF_INIT
;
1131 strbuf_addf(&prompt
, "Password (%s@%s): ", srvc
->user
, srvc
->host
);
1132 arg
= git_getpass(prompt
.buf
);
1133 strbuf_release(&prompt
);
1135 fprintf(stderr
, "Skipping account %s@%s, no password\n", srvc
->user
, srvc
->host
);
1139 * getpass() returns a pointer to a static buffer. make a copy
1140 * for long term storage.
1142 srvc
->pass
= xstrdup(arg
);
1145 fprintf(stderr
, "Skipping account %s@%s, server forbids LOGIN\n", srvc
->user
, srvc
->host
);
1149 if (srvc
->auth_method
) {
1150 struct imap_cmd_cb cb
;
1152 if (!strcmp(srvc
->auth_method
, "CRAM-MD5")) {
1153 if (!CAP(AUTH_CRAM_MD5
)) {
1154 fprintf(stderr
, "You specified"
1155 "CRAM-MD5 as authentication method, "
1156 "but %s doesn't support it.\n", srvc
->host
);
1161 memset(&cb
, 0, sizeof(cb
));
1162 cb
.cont
= auth_cram_md5
;
1163 if (imap_exec(ctx
, &cb
, "AUTHENTICATE CRAM-MD5") != RESP_OK
) {
1164 fprintf(stderr
, "IMAP error: AUTHENTICATE CRAM-MD5 failed\n");
1168 fprintf(stderr
, "Unknown authentication method:%s\n", srvc
->host
);
1172 if (!imap
->buf
.sock
.ssl
)
1173 imap_warn("*** IMAP Warning *** Password is being "
1174 "sent in the clear\n");
1175 if (imap_exec(ctx
, NULL
, "LOGIN \"%s\" \"%s\"", srvc
->user
, srvc
->pass
) != RESP_OK
) {
1176 fprintf(stderr
, "IMAP error: LOGIN failed\n");
1184 return (struct store
*)ctx
;
1187 imap_close_store(&ctx
->gen
);
1191 static void lf_to_crlf(struct strbuf
*msg
)
1195 int i
, j
, lfnum
= 0;
1197 if (msg
->buf
[0] == '\n')
1199 for (i
= 1; i
< msg
->len
; i
++) {
1200 if (msg
->buf
[i
- 1] != '\r' && msg
->buf
[i
] == '\n')
1204 new_len
= msg
->len
+ lfnum
;
1205 new = xmalloc(new_len
+ 1);
1206 if (msg
->buf
[0] == '\n') {
1212 new[0] = msg
->buf
[0];
1216 for ( ; i
< msg
->len
; i
++) {
1217 if (msg
->buf
[i
] != '\n') {
1218 new[j
++] = msg
->buf
[i
];
1221 if (msg
->buf
[i
- 1] != '\r')
1223 /* otherwise it already had CR before */
1226 strbuf_attach(msg
, new, new_len
, new_len
+ 1);
1230 * Store msg to IMAP. Also detach and free the data from msg->data,
1231 * leaving msg->data empty.
1233 static int imap_store_msg(struct store
*gctx
, struct strbuf
*msg
)
1235 struct imap_store
*ctx
= (struct imap_store
*)gctx
;
1236 struct imap
*imap
= ctx
->imap
;
1237 struct imap_cmd_cb cb
;
1238 const char *prefix
, *box
;
1242 memset(&cb
, 0, sizeof(cb
));
1245 cb
.data
= strbuf_detach(msg
, NULL
);
1248 prefix
= !strcmp(box
, "INBOX") ? "" : ctx
->prefix
;
1250 ret
= imap_exec_m(ctx
, &cb
, "APPEND \"%s%s\" ", prefix
, box
);
1251 imap
->caps
= imap
->rcaps
;
1258 static void wrap_in_html(struct strbuf
*msg
)
1260 struct strbuf buf
= STRBUF_INIT
;
1261 static char *content_type
= "Content-Type: text/html;\n";
1262 static char *pre_open
= "<pre>\n";
1263 static char *pre_close
= "</pre>\n";
1264 const char *body
= strstr(msg
->buf
, "\n\n");
1267 return; /* Headers but no body; no wrapping needed */
1271 strbuf_add(&buf
, msg
->buf
, body
- msg
->buf
- 1);
1272 strbuf_addstr(&buf
, content_type
);
1273 strbuf_addch(&buf
, '\n');
1274 strbuf_addstr(&buf
, pre_open
);
1275 strbuf_addstr_xml_quoted(&buf
, body
);
1276 strbuf_addstr(&buf
, pre_close
);
1278 strbuf_release(msg
);
1282 #define CHUNKSIZE 0x1000
1284 static int read_message(FILE *f
, struct strbuf
*all_msgs
)
1287 if (strbuf_fread(all_msgs
, CHUNKSIZE
, f
) <= 0)
1291 return ferror(f
) ? -1 : 0;
1294 static int count_messages(struct strbuf
*all_msgs
)
1297 char *p
= all_msgs
->buf
;
1300 if (!prefixcmp(p
, "From ")) {
1301 p
= strstr(p
+5, "\nFrom: ");
1303 p
= strstr(p
+7, "\nDate: ");
1305 p
= strstr(p
+7, "\nSubject: ");
1310 p
= strstr(p
+5, "\nFrom ");
1319 * Copy the next message from all_msgs, starting at offset *ofs, to
1320 * msg. Update *ofs to the start of the following message. Return
1321 * true iff a message was successfully copied.
1323 static int split_msg(struct strbuf
*all_msgs
, struct strbuf
*msg
, int *ofs
)
1328 if (*ofs
>= all_msgs
->len
)
1331 data
= &all_msgs
->buf
[*ofs
];
1332 len
= all_msgs
->len
- *ofs
;
1334 if (len
< 5 || prefixcmp(data
, "From "))
1337 p
= strchr(data
, '\n');
1345 p
= strstr(data
, "\nFrom ");
1349 strbuf_add(msg
, data
, len
);
1354 static char *imap_folder
;
1356 static int git_imap_config(const char *key
, const char *val
, void *cb
)
1358 char imap_key
[] = "imap.";
1360 if (strncmp(key
, imap_key
, sizeof imap_key
- 1))
1363 key
+= sizeof imap_key
- 1;
1365 /* check booleans first, and barf on others */
1366 if (!strcmp("sslverify", key
))
1367 server
.ssl_verify
= git_config_bool(key
, val
);
1368 else if (!strcmp("preformattedhtml", key
))
1369 server
.use_html
= git_config_bool(key
, val
);
1371 return config_error_nonbool(key
);
1373 if (!strcmp("folder", key
)) {
1374 imap_folder
= xstrdup(val
);
1375 } else if (!strcmp("host", key
)) {
1376 if (!prefixcmp(val
, "imap:"))
1378 else if (!prefixcmp(val
, "imaps:")) {
1382 if (!prefixcmp(val
, "//"))
1384 server
.host
= xstrdup(val
);
1385 } else if (!strcmp("user", key
))
1386 server
.user
= xstrdup(val
);
1387 else if (!strcmp("pass", key
))
1388 server
.pass
= xstrdup(val
);
1389 else if (!strcmp("port", key
))
1390 server
.port
= git_config_int(key
, val
);
1391 else if (!strcmp("tunnel", key
))
1392 server
.tunnel
= xstrdup(val
);
1393 else if (!strcmp("authmethod", key
))
1394 server
.auth_method
= xstrdup(val
);
1399 int main(int argc
, char **argv
)
1401 struct strbuf all_msgs
= STRBUF_INIT
;
1402 struct strbuf msg
= STRBUF_INIT
;
1403 struct store
*ctx
= NULL
;
1409 git_extract_argv0_path(argv
[0]);
1411 git_setup_gettext();
1414 usage(imap_send_usage
);
1416 setup_git_directory_gently(&nongit_ok
);
1417 git_config(git_imap_config
, NULL
);
1420 server
.port
= server
.use_ssl
? 993 : 143;
1423 fprintf(stderr
, "no imap store specified\n");
1427 if (!server
.tunnel
) {
1428 fprintf(stderr
, "no imap host specified\n");
1431 server
.host
= "tunnel";
1434 /* read the messages */
1435 if (read_message(stdin
, &all_msgs
)) {
1436 fprintf(stderr
, "error reading input\n");
1440 if (all_msgs
.len
== 0) {
1441 fprintf(stderr
, "nothing to send\n");
1445 total
= count_messages(&all_msgs
);
1447 fprintf(stderr
, "no messages to send\n");
1451 /* write it to the imap server */
1452 ctx
= imap_open_store(&server
);
1454 fprintf(stderr
, "failed to open store\n");
1458 fprintf(stderr
, "sending %d message%s\n", total
, (total
!= 1) ? "s" : "");
1459 ctx
->name
= imap_folder
;
1461 unsigned percent
= n
* 100 / total
;
1463 fprintf(stderr
, "%4u%% (%d/%d) done\r", percent
, n
, total
);
1464 if (!split_msg(&all_msgs
, &msg
, &ofs
))
1466 if (server
.use_html
)
1468 r
= imap_store_msg(ctx
, &msg
);
1473 fprintf(stderr
, "\n");
1475 imap_close_store(ctx
);