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>
38 const char *path
; /* should this be here? its interpretation is driver-specific */
41 unsigned max_size
; /* off_t is overkill */
42 unsigned trash_remote_new
:1, trash_only_new
:1;
45 /* For message->status */
46 #define M_RECENT (1<<0) /* unsyncable flag; maildir_* depend on this being 1<<0 */
47 #define M_DEAD (1<<1) /* expunged */
48 #define M_FLAGS (1<<2) /* flags fetched */
52 size_t size
; /* zero implies "not fetched" */
54 unsigned char flags
, status
;
58 struct store_conf
*conf
; /* foreign */
60 /* currently open mailbox */
61 const char *name
; /* foreign! maybe preset? */
63 struct message
*msgs
; /* own */
65 unsigned char opts
; /* maybe preset? */
66 /* note that the following do _not_ reflect stats from msgs, but mailbox totals */
67 int count
; /* # of messages */
68 int recent
; /* # of recent messages - don't trust this beyond the initial read */
75 static const char imap_send_usage
[] = "git imap-send < <mbox>";
79 #define DRV_MSG_BAD -1
80 #define DRV_BOX_BAD -2
81 #define DRV_STORE_BAD -3
83 static int Verbose
, Quiet
;
85 __attribute__((format (printf
, 1, 2)))
86 static void imap_info(const char *, ...);
87 __attribute__((format (printf
, 1, 2)))
88 static void imap_warn(const char *, ...);
90 static char *next_arg(char **);
92 static void free_generic_messages(struct message
*);
94 __attribute__((format (printf
, 3, 4)))
95 static int nfsnprintf(char *buf
, int blen
, const char *fmt
, ...);
97 static int nfvasprintf(char **strp
, const char *fmt
, va_list ap
)
102 len
= vsnprintf(tmp
, sizeof(tmp
), fmt
, ap
);
104 die("Fatal: Out of memory");
105 if (len
>= sizeof(tmp
))
106 die("imap command overflow!");
107 *strp
= xmemdupz(tmp
, len
);
111 struct imap_server_conf
{
124 static struct imap_server_conf server
= {
134 NULL
, /* auth_method */
137 struct imap_store_conf
{
138 struct store_conf gen
;
139 struct imap_server_conf
*server
;
142 #define NIL (void *)0x1
143 #define LIST (void *)0x2
146 struct imap_list
*next
, *child
;
157 struct imap_socket sock
;
166 int uidnext
; /* from SELECT responses */
167 struct imap_list
*ns_personal
, *ns_other
, *ns_shared
; /* NAMESPACE info */
168 unsigned caps
, rcaps
; /* CAPABILITY results */
170 int nexttag
, num_in_progress
, literal_pending
;
171 struct imap_cmd
*in_progress
, **in_progress_append
;
172 struct imap_buffer buf
; /* this is BIG, so put it last */
180 unsigned /*currentnc:1,*/ trashnc
:1;
184 int (*cont
)(struct imap_store
*ctx
, struct imap_cmd
*cmd
, const char *prompt
);
185 void (*done
)(struct imap_store
*ctx
, struct imap_cmd
*cmd
, int response
);
190 unsigned create
:1, trycreate
:1;
194 struct imap_cmd
*next
;
195 struct imap_cmd_cb cb
;
200 #define CAP(cap) (imap->caps & (1 << (cap)))
211 static const char *cap_list
[] = {
224 static int get_cmd_result(struct imap_store
*ctx
, struct imap_cmd
*tcmd
);
228 static void ssl_socket_perror(const char *func
)
230 fprintf(stderr
, "%s: %s\n", func
, ERR_error_string(ERR_get_error(), NULL
));
234 static void socket_perror(const char *func
, struct imap_socket
*sock
, int ret
)
238 int sslerr
= SSL_get_error(sock
->ssl
, ret
);
242 case SSL_ERROR_SYSCALL
:
243 perror("SSL_connect");
246 ssl_socket_perror("SSL_connect");
255 fprintf(stderr
, "%s: unexpected EOF\n", func
);
259 static int ssl_socket_connect(struct imap_socket
*sock
, int use_tls_only
, int verify
)
262 fprintf(stderr
, "SSL requested but SSL support not compiled in\n");
265 #if (OPENSSL_VERSION_NUMBER >= 0x10000000L)
266 const SSL_METHOD
*meth
;
274 SSL_load_error_strings();
277 meth
= TLSv1_method();
279 meth
= SSLv23_method();
282 ssl_socket_perror("SSLv23_method");
286 ctx
= SSL_CTX_new(meth
);
289 SSL_CTX_set_verify(ctx
, SSL_VERIFY_PEER
, NULL
);
291 if (!SSL_CTX_set_default_verify_paths(ctx
)) {
292 ssl_socket_perror("SSL_CTX_set_default_verify_paths");
295 sock
->ssl
= SSL_new(ctx
);
297 ssl_socket_perror("SSL_new");
300 if (!SSL_set_rfd(sock
->ssl
, sock
->fd
[0])) {
301 ssl_socket_perror("SSL_set_rfd");
304 if (!SSL_set_wfd(sock
->ssl
, sock
->fd
[1])) {
305 ssl_socket_perror("SSL_set_wfd");
309 ret
= SSL_connect(sock
->ssl
);
311 socket_perror("SSL_connect", sock
, ret
);
319 static int socket_read(struct imap_socket
*sock
, char *buf
, int len
)
324 n
= SSL_read(sock
->ssl
, buf
, len
);
327 n
= xread(sock
->fd
[0], buf
, len
);
329 socket_perror("read", sock
, n
);
332 sock
->fd
[0] = sock
->fd
[1] = -1;
337 static int socket_write(struct imap_socket
*sock
, const char *buf
, int len
)
342 n
= SSL_write(sock
->ssl
, buf
, len
);
345 n
= write_in_full(sock
->fd
[1], buf
, len
);
347 socket_perror("write", sock
, n
);
350 sock
->fd
[0] = sock
->fd
[1] = -1;
355 static void socket_shutdown(struct imap_socket
*sock
)
359 SSL_shutdown(sock
->ssl
);
367 /* simple line buffering */
368 static int buffer_gets(struct imap_buffer
*b
, char **s
)
371 int start
= b
->offset
;
376 /* make sure we have enough data to read the \r\n sequence */
377 if (b
->offset
+ 1 >= b
->bytes
) {
379 /* shift down used bytes */
382 assert(start
<= b
->bytes
);
383 n
= b
->bytes
- start
;
386 memmove(b
->buf
, b
->buf
+ start
, n
);
392 n
= socket_read(&b
->sock
, b
->buf
+ b
->bytes
,
393 sizeof(b
->buf
) - b
->bytes
);
401 if (b
->buf
[b
->offset
] == '\r') {
402 assert(b
->offset
+ 1 < b
->bytes
);
403 if (b
->buf
[b
->offset
+ 1] == '\n') {
404 b
->buf
[b
->offset
] = 0; /* terminate the string */
405 b
->offset
+= 2; /* next line */
417 static void imap_info(const char *msg
, ...)
429 static void imap_warn(const char *msg
, ...)
435 vfprintf(stderr
, msg
, va
);
440 static char *next_arg(char **s
)
446 while (isspace((unsigned char) **s
))
455 *s
= strchr(*s
, '"');
458 while (**s
&& !isspace((unsigned char) **s
))
470 static void free_generic_messages(struct message
*msgs
)
472 struct message
*tmsg
;
474 for (; msgs
; msgs
= tmsg
) {
480 static int nfsnprintf(char *buf
, int blen
, const char *fmt
, ...)
486 if (blen
<= 0 || (unsigned)(ret
= vsnprintf(buf
, blen
, fmt
, va
)) >= (unsigned)blen
)
487 die("Fatal: buffer too small. Please report a bug.");
492 static struct imap_cmd
*v_issue_imap_cmd(struct imap_store
*ctx
,
493 struct imap_cmd_cb
*cb
,
494 const char *fmt
, va_list ap
)
496 struct imap
*imap
= ctx
->imap
;
497 struct imap_cmd
*cmd
;
501 cmd
= xmalloc(sizeof(struct imap_cmd
));
502 nfvasprintf(&cmd
->cmd
, fmt
, ap
);
503 cmd
->tag
= ++imap
->nexttag
;
508 memset(&cmd
->cb
, 0, sizeof(cmd
->cb
));
510 while (imap
->literal_pending
)
511 get_cmd_result(ctx
, NULL
);
514 bufl
= nfsnprintf(buf
, sizeof(buf
), "%d %s\r\n", cmd
->tag
, cmd
->cmd
);
516 bufl
= nfsnprintf(buf
, sizeof(buf
), "%d %s{%d%s}\r\n",
517 cmd
->tag
, cmd
->cmd
, cmd
->cb
.dlen
,
518 CAP(LITERALPLUS
) ? "+" : "");
521 if (imap
->num_in_progress
)
522 printf("(%d in progress) ", imap
->num_in_progress
);
523 if (memcmp(cmd
->cmd
, "LOGIN", 5))
524 printf(">>> %s", buf
);
526 printf(">>> %d LOGIN <user> <pass>\n", cmd
->tag
);
528 if (socket_write(&imap
->buf
.sock
, buf
, bufl
) != bufl
) {
536 if (CAP(LITERALPLUS
)) {
537 n
= socket_write(&imap
->buf
.sock
, cmd
->cb
.data
, cmd
->cb
.dlen
);
539 if (n
!= cmd
->cb
.dlen
||
540 socket_write(&imap
->buf
.sock
, "\r\n", 2) != 2) {
547 imap
->literal_pending
= 1;
548 } else if (cmd
->cb
.cont
)
549 imap
->literal_pending
= 1;
551 *imap
->in_progress_append
= cmd
;
552 imap
->in_progress_append
= &cmd
->next
;
553 imap
->num_in_progress
++;
557 __attribute__((format (printf
, 3, 4)))
558 static struct imap_cmd
*issue_imap_cmd(struct imap_store
*ctx
,
559 struct imap_cmd_cb
*cb
,
560 const char *fmt
, ...)
562 struct imap_cmd
*ret
;
566 ret
= v_issue_imap_cmd(ctx
, cb
, fmt
, ap
);
571 __attribute__((format (printf
, 3, 4)))
572 static int imap_exec(struct imap_store
*ctx
, struct imap_cmd_cb
*cb
,
573 const char *fmt
, ...)
576 struct imap_cmd
*cmdp
;
579 cmdp
= v_issue_imap_cmd(ctx
, cb
, fmt
, ap
);
584 return get_cmd_result(ctx
, cmdp
);
587 __attribute__((format (printf
, 3, 4)))
588 static int imap_exec_m(struct imap_store
*ctx
, struct imap_cmd_cb
*cb
,
589 const char *fmt
, ...)
592 struct imap_cmd
*cmdp
;
595 cmdp
= v_issue_imap_cmd(ctx
, cb
, fmt
, ap
);
598 return DRV_STORE_BAD
;
600 switch (get_cmd_result(ctx
, cmdp
)) {
601 case RESP_BAD
: return DRV_STORE_BAD
;
602 case RESP_NO
: return DRV_MSG_BAD
;
603 default: return DRV_OK
;
607 static int is_atom(struct imap_list
*list
)
609 return list
&& list
->val
&& list
->val
!= NIL
&& list
->val
!= LIST
;
612 static int is_list(struct imap_list
*list
)
614 return list
&& list
->val
== LIST
;
617 static void free_list(struct imap_list
*list
)
619 struct imap_list
*tmp
;
621 for (; list
; list
= tmp
) {
624 free_list(list
->child
);
625 else if (is_atom(list
))
631 static int parse_imap_list_l(struct imap
*imap
, char **sp
, struct imap_list
**curp
, int level
)
633 struct imap_list
*cur
;
638 while (isspace((unsigned char)*s
))
640 if (level
&& *s
== ')') {
644 *curp
= cur
= xmalloc(sizeof(*cur
));
646 cur
->val
= NULL
; /* for clean bail */
651 if (parse_imap_list_l(imap
, &s
, &cur
->child
, level
+ 1))
653 } else if (imap
&& *s
== '{') {
655 bytes
= cur
->len
= strtol(s
+ 1, &s
, 10);
659 s
= cur
->val
= xmalloc(cur
->len
);
661 /* dump whats left over in the input buffer */
662 n
= imap
->buf
.bytes
- imap
->buf
.offset
;
665 /* the entire message fit in the buffer */
668 memcpy(s
, imap
->buf
.buf
+ imap
->buf
.offset
, n
);
672 /* mark that we used part of the buffer */
673 imap
->buf
.offset
+= n
;
675 /* now read the rest of the message */
677 if ((n
= socket_read(&imap
->buf
.sock
, s
, bytes
)) <= 0)
683 if (buffer_gets(&imap
->buf
, &s
))
685 } else if (*s
== '"') {
689 for (; *s
!= '"'; s
++)
694 cur
->val
= xmemdupz(p
, cur
->len
);
698 for (; *s
&& !isspace((unsigned char)*s
); s
++)
699 if (level
&& *s
== ')')
702 if (cur
->len
== 3 && !memcmp("NIL", p
, 3))
705 cur
->val
= xmemdupz(p
, cur
->len
);
722 static struct imap_list
*parse_imap_list(struct imap
*imap
, char **sp
)
724 struct imap_list
*head
;
726 if (!parse_imap_list_l(imap
, sp
, &head
, 0))
732 static struct imap_list
*parse_list(char **sp
)
734 return parse_imap_list(NULL
, sp
);
737 static void parse_capability(struct imap
*imap
, char *cmd
)
742 imap
->caps
= 0x80000000;
743 while ((arg
= next_arg(&cmd
)))
744 for (i
= 0; i
< ARRAY_SIZE(cap_list
); i
++)
745 if (!strcmp(cap_list
[i
], arg
))
746 imap
->caps
|= 1 << i
;
747 imap
->rcaps
= imap
->caps
;
750 static int parse_response_code(struct imap_store
*ctx
, struct imap_cmd_cb
*cb
,
753 struct imap
*imap
= ctx
->imap
;
757 return RESP_OK
; /* no response code */
759 if (!(p
= strchr(s
, ']'))) {
760 fprintf(stderr
, "IMAP error: malformed response code\n");
765 if (!strcmp("UIDVALIDITY", arg
)) {
766 if (!(arg
= next_arg(&s
)) || !(ctx
->gen
.uidvalidity
= atoi(arg
))) {
767 fprintf(stderr
, "IMAP error: malformed UIDVALIDITY status\n");
770 } else if (!strcmp("UIDNEXT", arg
)) {
771 if (!(arg
= next_arg(&s
)) || !(imap
->uidnext
= atoi(arg
))) {
772 fprintf(stderr
, "IMAP error: malformed NEXTUID status\n");
775 } else if (!strcmp("CAPABILITY", arg
)) {
776 parse_capability(imap
, s
);
777 } else if (!strcmp("ALERT", arg
)) {
778 /* RFC2060 says that these messages MUST be displayed
781 for (; isspace((unsigned char)*p
); p
++);
782 fprintf(stderr
, "*** IMAP ALERT *** %s\n", p
);
783 } else if (cb
&& cb
->ctx
&& !strcmp("APPENDUID", arg
)) {
784 if (!(arg
= next_arg(&s
)) || !(ctx
->gen
.uidvalidity
= atoi(arg
)) ||
785 !(arg
= next_arg(&s
)) || !(*(int *)cb
->ctx
= atoi(arg
))) {
786 fprintf(stderr
, "IMAP error: malformed APPENDUID status\n");
793 static int get_cmd_result(struct imap_store
*ctx
, struct imap_cmd
*tcmd
)
795 struct imap
*imap
= ctx
->imap
;
796 struct imap_cmd
*cmdp
, **pcmdp
, *ncmdp
;
797 char *cmd
, *arg
, *arg1
, *p
;
798 int n
, resp
, resp2
, tag
;
801 if (buffer_gets(&imap
->buf
, &cmd
))
804 arg
= next_arg(&cmd
);
806 arg
= next_arg(&cmd
);
808 fprintf(stderr
, "IMAP error: unable to parse untagged response\n");
812 if (!strcmp("NAMESPACE", arg
)) {
813 imap
->ns_personal
= parse_list(&cmd
);
814 imap
->ns_other
= parse_list(&cmd
);
815 imap
->ns_shared
= parse_list(&cmd
);
816 } else if (!strcmp("OK", arg
) || !strcmp("BAD", arg
) ||
817 !strcmp("NO", arg
) || !strcmp("BYE", arg
)) {
818 if ((resp
= parse_response_code(ctx
, NULL
, cmd
)) != RESP_OK
)
820 } else if (!strcmp("CAPABILITY", arg
))
821 parse_capability(imap
, cmd
);
822 else if ((arg1
= next_arg(&cmd
))) {
823 if (!strcmp("EXISTS", arg1
))
824 ctx
->gen
.count
= atoi(arg
);
825 else if (!strcmp("RECENT", arg1
))
826 ctx
->gen
.recent
= atoi(arg
);
828 fprintf(stderr
, "IMAP error: unable to parse untagged response\n");
831 } else if (!imap
->in_progress
) {
832 fprintf(stderr
, "IMAP error: unexpected reply: %s %s\n", arg
, cmd
? cmd
: "");
834 } else if (*arg
== '+') {
835 /* This can happen only with the last command underway, as
836 it enforces a round-trip. */
837 cmdp
= (struct imap_cmd
*)((char *)imap
->in_progress_append
-
838 offsetof(struct imap_cmd
, next
));
840 n
= socket_write(&imap
->buf
.sock
, cmdp
->cb
.data
, cmdp
->cb
.dlen
);
842 cmdp
->cb
.data
= NULL
;
843 if (n
!= (int)cmdp
->cb
.dlen
)
845 } else if (cmdp
->cb
.cont
) {
846 if (cmdp
->cb
.cont(ctx
, cmdp
, cmd
))
849 fprintf(stderr
, "IMAP error: unexpected command continuation request\n");
852 if (socket_write(&imap
->buf
.sock
, "\r\n", 2) != 2)
855 imap
->literal_pending
= 0;
860 for (pcmdp
= &imap
->in_progress
; (cmdp
= *pcmdp
); pcmdp
= &cmdp
->next
)
861 if (cmdp
->tag
== tag
)
863 fprintf(stderr
, "IMAP error: unexpected tag %s\n", arg
);
866 if (!(*pcmdp
= cmdp
->next
))
867 imap
->in_progress_append
= pcmdp
;
868 imap
->num_in_progress
--;
869 if (cmdp
->cb
.cont
|| cmdp
->cb
.data
)
870 imap
->literal_pending
= 0;
871 arg
= next_arg(&cmd
);
872 if (!strcmp("OK", arg
))
875 if (!strcmp("NO", arg
)) {
876 if (cmdp
->cb
.create
&& cmd
&& (cmdp
->cb
.trycreate
|| !memcmp(cmd
, "[TRYCREATE]", 11))) { /* SELECT, APPEND or UID COPY */
877 p
= strchr(cmdp
->cmd
, '"');
878 if (!issue_imap_cmd(ctx
, NULL
, "CREATE \"%.*s\"", (int)(strchr(p
+ 1, '"') - p
+ 1), p
)) {
882 /* not waiting here violates the spec, but a server that does not
883 grok this nonetheless violates it too. */
885 if (!(ncmdp
= issue_imap_cmd(ctx
, &cmdp
->cb
, "%s", cmdp
->cmd
))) {
892 return 0; /* ignored */
898 } else /*if (!strcmp("BAD", arg))*/
900 fprintf(stderr
, "IMAP command '%s' returned response (%s) - %s\n",
901 memcmp(cmdp
->cmd
, "LOGIN", 5) ?
902 cmdp
->cmd
: "LOGIN <user> <pass>",
903 arg
, cmd
? cmd
: "");
905 if ((resp2
= parse_response_code(ctx
, &cmdp
->cb
, cmd
)) > resp
)
909 cmdp
->cb
.done(ctx
, cmdp
, resp
);
913 if (!tcmd
|| tcmd
== cmdp
)
920 static void imap_close_server(struct imap_store
*ictx
)
922 struct imap
*imap
= ictx
->imap
;
924 if (imap
->buf
.sock
.fd
[0] != -1) {
925 imap_exec(ictx
, NULL
, "LOGOUT");
926 socket_shutdown(&imap
->buf
.sock
);
928 free_list(imap
->ns_personal
);
929 free_list(imap
->ns_other
);
930 free_list(imap
->ns_shared
);
934 static void imap_close_store(struct store
*ctx
)
936 imap_close_server((struct imap_store
*)ctx
);
937 free_generic_messages(ctx
->msgs
);
944 * hexchar() and cram() functions are based on the code from the isync
945 * project (http://isync.sf.net/).
947 static char hexchar(unsigned int b
)
949 return b
< 10 ? '0' + b
: 'a' + (b
- 10);
952 #define ENCODED_SIZE(n) (4*((n+2)/3))
953 static char *cram(const char *challenge_64
, const char *user
, const char *pass
)
955 int i
, resp_len
, encoded_len
, decoded_len
;
957 unsigned char hash
[16];
959 char *response
, *response_64
, *challenge
;
962 * length of challenge_64 (i.e. base-64 encoded string) is a good
963 * enough upper bound for challenge (decoded result).
965 encoded_len
= strlen(challenge_64
);
966 challenge
= xmalloc(encoded_len
);
967 decoded_len
= EVP_DecodeBlock((unsigned char *)challenge
,
968 (unsigned char *)challenge_64
, encoded_len
);
970 die("invalid challenge %s", challenge_64
);
971 HMAC_Init(&hmac
, (unsigned char *)pass
, strlen(pass
), EVP_md5());
972 HMAC_Update(&hmac
, (unsigned char *)challenge
, decoded_len
);
973 HMAC_Final(&hmac
, hash
, NULL
);
974 HMAC_CTX_cleanup(&hmac
);
977 for (i
= 0; i
< 16; i
++) {
978 hex
[2 * i
] = hexchar((hash
[i
] >> 4) & 0xf);
979 hex
[2 * i
+ 1] = hexchar(hash
[i
] & 0xf);
982 /* response: "<user> <digest in hex>" */
983 resp_len
= strlen(user
) + 1 + strlen(hex
) + 1;
984 response
= xmalloc(resp_len
);
985 sprintf(response
, "%s %s", user
, hex
);
987 response_64
= xmalloc(ENCODED_SIZE(resp_len
) + 1);
988 encoded_len
= EVP_EncodeBlock((unsigned char *)response_64
,
989 (unsigned char *)response
, resp_len
);
991 die("EVP_EncodeBlock error");
992 response_64
[encoded_len
] = '\0';
993 return (char *)response_64
;
998 static char *cram(const char *challenge_64
, const char *user
, const char *pass
)
1000 die("If you want to use CRAM-MD5 authenticate method, "
1001 "you have to build git-imap-send with OpenSSL library.");
1006 static int auth_cram_md5(struct imap_store
*ctx
, struct imap_cmd
*cmd
, const char *prompt
)
1011 response
= cram(prompt
, server
.user
, server
.pass
);
1013 ret
= socket_write(&ctx
->imap
->buf
.sock
, response
, strlen(response
));
1014 if (ret
!= strlen(response
))
1015 return error("IMAP error: sending response failed");
1022 static struct store
*imap_open_store(struct imap_server_conf
*srvc
)
1024 struct imap_store
*ctx
;
1027 int s
= -1, preauth
;
1029 ctx
= xcalloc(sizeof(*ctx
), 1);
1031 ctx
->imap
= imap
= xcalloc(sizeof(*imap
), 1);
1032 imap
->buf
.sock
.fd
[0] = imap
->buf
.sock
.fd
[1] = -1;
1033 imap
->in_progress_append
= &imap
->in_progress
;
1035 /* open connection to IMAP server */
1038 const char *argv
[] = { srvc
->tunnel
, NULL
};
1039 struct child_process tunnel
= {NULL
};
1041 imap_info("Starting tunnel '%s'... ", srvc
->tunnel
);
1044 tunnel
.use_shell
= 1;
1047 if (start_command(&tunnel
))
1048 die("cannot start proxy %s", argv
[0]);
1050 imap
->buf
.sock
.fd
[0] = tunnel
.out
;
1051 imap
->buf
.sock
.fd
[1] = tunnel
.in
;
1056 struct addrinfo hints
, *ai0
, *ai
;
1060 snprintf(portstr
, sizeof(portstr
), "%d", srvc
->port
);
1062 memset(&hints
, 0, sizeof(hints
));
1063 hints
.ai_socktype
= SOCK_STREAM
;
1064 hints
.ai_protocol
= IPPROTO_TCP
;
1066 imap_info("Resolving %s... ", srvc
->host
);
1067 gai
= getaddrinfo(srvc
->host
, portstr
, &hints
, &ai
);
1069 fprintf(stderr
, "getaddrinfo: %s\n", gai_strerror(gai
));
1074 for (ai0
= ai
; ai
; ai
= ai
->ai_next
) {
1075 char addr
[NI_MAXHOST
];
1077 s
= socket(ai
->ai_family
, ai
->ai_socktype
,
1082 getnameinfo(ai
->ai_addr
, ai
->ai_addrlen
, addr
,
1083 sizeof(addr
), NULL
, 0, NI_NUMERICHOST
);
1084 imap_info("Connecting to [%s]:%s... ", addr
, portstr
);
1086 if (connect(s
, ai
->ai_addr
, ai
->ai_addrlen
) < 0) {
1098 struct sockaddr_in addr
;
1100 memset(&addr
, 0, sizeof(addr
));
1101 addr
.sin_port
= htons(srvc
->port
);
1102 addr
.sin_family
= AF_INET
;
1104 imap_info("Resolving %s... ", srvc
->host
);
1105 he
= gethostbyname(srvc
->host
);
1107 perror("gethostbyname");
1112 addr
.sin_addr
.s_addr
= *((int *) he
->h_addr_list
[0]);
1114 s
= socket(PF_INET
, SOCK_STREAM
, 0);
1116 imap_info("Connecting to %s:%hu... ", inet_ntoa(addr
.sin_addr
), ntohs(addr
.sin_port
));
1117 if (connect(s
, (struct sockaddr
*)&addr
, sizeof(addr
))) {
1124 fputs("Error: unable to connect to server.\n", stderr
);
1128 imap
->buf
.sock
.fd
[0] = s
;
1129 imap
->buf
.sock
.fd
[1] = dup(s
);
1131 if (srvc
->use_ssl
&&
1132 ssl_socket_connect(&imap
->buf
.sock
, 0, srvc
->ssl_verify
)) {
1139 /* read the greeting string */
1140 if (buffer_gets(&imap
->buf
, &rsp
)) {
1141 fprintf(stderr
, "IMAP error: no greeting response\n");
1144 arg
= next_arg(&rsp
);
1145 if (!arg
|| *arg
!= '*' || (arg
= next_arg(&rsp
)) == NULL
) {
1146 fprintf(stderr
, "IMAP error: invalid greeting response\n");
1150 if (!strcmp("PREAUTH", arg
))
1152 else if (strcmp("OK", arg
) != 0) {
1153 fprintf(stderr
, "IMAP error: unknown greeting response\n");
1156 parse_response_code(ctx
, NULL
, rsp
);
1157 if (!imap
->caps
&& imap_exec(ctx
, NULL
, "CAPABILITY") != RESP_OK
)
1162 if (!srvc
->use_ssl
&& CAP(STARTTLS
)) {
1163 if (imap_exec(ctx
, NULL
, "STARTTLS") != RESP_OK
)
1165 if (ssl_socket_connect(&imap
->buf
.sock
, 1,
1168 /* capabilities may have changed, so get the new capabilities */
1169 if (imap_exec(ctx
, NULL
, "CAPABILITY") != RESP_OK
)
1173 imap_info("Logging in...\n");
1175 fprintf(stderr
, "Skipping server %s, no user\n", srvc
->host
);
1179 struct strbuf prompt
= STRBUF_INIT
;
1180 strbuf_addf(&prompt
, "Password (%s@%s): ", srvc
->user
, srvc
->host
);
1181 arg
= git_getpass(prompt
.buf
);
1182 strbuf_release(&prompt
);
1184 fprintf(stderr
, "Skipping account %s@%s, no password\n", srvc
->user
, srvc
->host
);
1188 * getpass() returns a pointer to a static buffer. make a copy
1189 * for long term storage.
1191 srvc
->pass
= xstrdup(arg
);
1194 fprintf(stderr
, "Skipping account %s@%s, server forbids LOGIN\n", srvc
->user
, srvc
->host
);
1198 if (srvc
->auth_method
) {
1199 struct imap_cmd_cb cb
;
1201 if (!strcmp(srvc
->auth_method
, "CRAM-MD5")) {
1202 if (!CAP(AUTH_CRAM_MD5
)) {
1203 fprintf(stderr
, "You specified"
1204 "CRAM-MD5 as authentication method, "
1205 "but %s doesn't support it.\n", srvc
->host
);
1210 memset(&cb
, 0, sizeof(cb
));
1211 cb
.cont
= auth_cram_md5
;
1212 if (imap_exec(ctx
, &cb
, "AUTHENTICATE CRAM-MD5") != RESP_OK
) {
1213 fprintf(stderr
, "IMAP error: AUTHENTICATE CRAM-MD5 failed\n");
1217 fprintf(stderr
, "Unknown authentication method:%s\n", srvc
->host
);
1221 if (!imap
->buf
.sock
.ssl
)
1222 imap_warn("*** IMAP Warning *** Password is being "
1223 "sent in the clear\n");
1224 if (imap_exec(ctx
, NULL
, "LOGIN \"%s\" \"%s\"", srvc
->user
, srvc
->pass
) != RESP_OK
) {
1225 fprintf(stderr
, "IMAP error: LOGIN failed\n");
1233 return (struct store
*)ctx
;
1236 imap_close_store(&ctx
->gen
);
1240 static void lf_to_crlf(struct strbuf
*msg
)
1244 int i
, j
, lfnum
= 0;
1246 if (msg
->buf
[0] == '\n')
1248 for (i
= 1; i
< msg
->len
; i
++) {
1249 if (msg
->buf
[i
- 1] != '\r' && msg
->buf
[i
] == '\n')
1253 new_len
= msg
->len
+ lfnum
;
1254 new = xmalloc(new_len
+ 1);
1255 if (msg
->buf
[0] == '\n') {
1261 new[0] = msg
->buf
[0];
1265 for ( ; i
< msg
->len
; i
++) {
1266 if (msg
->buf
[i
] != '\n') {
1267 new[j
++] = msg
->buf
[i
];
1270 if (msg
->buf
[i
- 1] != '\r')
1272 /* otherwise it already had CR before */
1275 strbuf_attach(msg
, new, new_len
, new_len
+ 1);
1279 * Store msg to IMAP. Also detach and free the data from msg->data,
1280 * leaving msg->data empty.
1282 static int imap_store_msg(struct store
*gctx
, struct msg_data
*msg
)
1284 struct imap_store
*ctx
= (struct imap_store
*)gctx
;
1285 struct imap
*imap
= ctx
->imap
;
1286 struct imap_cmd_cb cb
;
1287 const char *prefix
, *box
;
1290 lf_to_crlf(&msg
->data
);
1291 memset(&cb
, 0, sizeof(cb
));
1293 cb
.dlen
= msg
->data
.len
;
1294 cb
.data
= strbuf_detach(&msg
->data
, NULL
);
1297 prefix
= !strcmp(box
, "INBOX") ? "" : ctx
->prefix
;
1299 ret
= imap_exec_m(ctx
, &cb
, "APPEND \"%s%s\" ", prefix
, box
);
1300 imap
->caps
= imap
->rcaps
;
1308 static void wrap_in_html(struct strbuf
*msg
)
1310 struct strbuf buf
= STRBUF_INIT
;
1311 static char *content_type
= "Content-Type: text/html;\n";
1312 static char *pre_open
= "<pre>\n";
1313 static char *pre_close
= "</pre>\n";
1314 const char *body
= strstr(msg
->buf
, "\n\n");
1317 return; /* Headers but no body; no wrapping needed */
1321 strbuf_add(&buf
, msg
->buf
, body
- msg
->buf
- 1);
1322 strbuf_addstr(&buf
, content_type
);
1323 strbuf_addch(&buf
, '\n');
1324 strbuf_addstr(&buf
, pre_open
);
1325 strbuf_addstr_xml_quoted(&buf
, body
);
1326 strbuf_addstr(&buf
, pre_close
);
1328 strbuf_release(msg
);
1332 #define CHUNKSIZE 0x1000
1334 static int read_message(FILE *f
, struct strbuf
*all_msgs
)
1337 if (strbuf_fread(all_msgs
, CHUNKSIZE
, f
) <= 0)
1341 return ferror(f
) ? -1 : 0;
1344 static int count_messages(struct strbuf
*all_msgs
)
1347 char *p
= all_msgs
->buf
;
1350 if (!prefixcmp(p
, "From ")) {
1351 p
= strstr(p
+5, "\nFrom: ");
1353 p
= strstr(p
+7, "\nDate: ");
1355 p
= strstr(p
+7, "\nSubject: ");
1360 p
= strstr(p
+5, "\nFrom ");
1369 * Copy the next message from all_msgs, starting at offset *ofs, to
1370 * msg. Update *ofs to the start of the following message. Return
1371 * true iff a message was successfully copied.
1373 static int split_msg(struct strbuf
*all_msgs
, struct strbuf
*msg
, int *ofs
)
1378 if (*ofs
>= all_msgs
->len
)
1381 data
= &all_msgs
->buf
[*ofs
];
1382 len
= all_msgs
->len
- *ofs
;
1384 if (len
< 5 || prefixcmp(data
, "From "))
1387 p
= strchr(data
, '\n');
1395 p
= strstr(data
, "\nFrom ");
1399 strbuf_add(msg
, data
, len
);
1404 static char *imap_folder
;
1406 static int git_imap_config(const char *key
, const char *val
, void *cb
)
1408 char imap_key
[] = "imap.";
1410 if (strncmp(key
, imap_key
, sizeof imap_key
- 1))
1413 key
+= sizeof imap_key
- 1;
1415 /* check booleans first, and barf on others */
1416 if (!strcmp("sslverify", key
))
1417 server
.ssl_verify
= git_config_bool(key
, val
);
1418 else if (!strcmp("preformattedhtml", key
))
1419 server
.use_html
= git_config_bool(key
, val
);
1421 return config_error_nonbool(key
);
1423 if (!strcmp("folder", key
)) {
1424 imap_folder
= xstrdup(val
);
1425 } else if (!strcmp("host", key
)) {
1426 if (!prefixcmp(val
, "imap:"))
1428 else if (!prefixcmp(val
, "imaps:")) {
1432 if (!prefixcmp(val
, "//"))
1434 server
.host
= xstrdup(val
);
1435 } else if (!strcmp("user", key
))
1436 server
.user
= xstrdup(val
);
1437 else if (!strcmp("pass", key
))
1438 server
.pass
= xstrdup(val
);
1439 else if (!strcmp("port", key
))
1440 server
.port
= git_config_int(key
, val
);
1441 else if (!strcmp("tunnel", key
))
1442 server
.tunnel
= xstrdup(val
);
1443 else if (!strcmp("authmethod", key
))
1444 server
.auth_method
= xstrdup(val
);
1449 int main(int argc
, char **argv
)
1451 struct strbuf all_msgs
= STRBUF_INIT
;
1452 struct msg_data msg
= {STRBUF_INIT
};
1453 struct store
*ctx
= NULL
;
1459 git_extract_argv0_path(argv
[0]);
1461 git_setup_gettext();
1464 usage(imap_send_usage
);
1466 setup_git_directory_gently(&nongit_ok
);
1467 git_config(git_imap_config
, NULL
);
1470 server
.port
= server
.use_ssl
? 993 : 143;
1473 fprintf(stderr
, "no imap store specified\n");
1477 if (!server
.tunnel
) {
1478 fprintf(stderr
, "no imap host specified\n");
1481 server
.host
= "tunnel";
1484 /* read the messages */
1485 if (read_message(stdin
, &all_msgs
)) {
1486 fprintf(stderr
, "error reading input\n");
1490 if (all_msgs
.len
== 0) {
1491 fprintf(stderr
, "nothing to send\n");
1495 total
= count_messages(&all_msgs
);
1497 fprintf(stderr
, "no messages to send\n");
1501 /* write it to the imap server */
1502 ctx
= imap_open_store(&server
);
1504 fprintf(stderr
, "failed to open store\n");
1508 fprintf(stderr
, "sending %d message%s\n", total
, (total
!= 1) ? "s" : "");
1509 ctx
->name
= imap_folder
;
1511 unsigned percent
= n
* 100 / total
;
1513 fprintf(stderr
, "%4u%% (%d/%d) done\r", percent
, n
, total
);
1514 if (!split_msg(&all_msgs
, &msg
.data
, &ofs
))
1516 if (server
.use_html
)
1517 wrap_in_html(&msg
.data
);
1518 r
= imap_store_msg(ctx
, &msg
);
1523 fprintf(stderr
, "\n");
1525 imap_close_store(ctx
);