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 */
71 static const char imap_send_usage
[] = "git imap-send < <mbox>";
75 #define DRV_MSG_BAD -1
76 #define DRV_BOX_BAD -2
77 #define DRV_STORE_BAD -3
79 static int Verbose
, Quiet
;
81 __attribute__((format (printf
, 1, 2)))
82 static void imap_info(const char *, ...);
83 __attribute__((format (printf
, 1, 2)))
84 static void imap_warn(const char *, ...);
86 static char *next_arg(char **);
88 static void free_generic_messages(struct message
*);
90 __attribute__((format (printf
, 3, 4)))
91 static int nfsnprintf(char *buf
, int blen
, const char *fmt
, ...);
93 static int nfvasprintf(char **strp
, const char *fmt
, va_list ap
)
98 len
= vsnprintf(tmp
, sizeof(tmp
), fmt
, ap
);
100 die("Fatal: Out of memory");
101 if (len
>= sizeof(tmp
))
102 die("imap command overflow!");
103 *strp
= xmemdupz(tmp
, len
);
107 struct imap_server_conf
{
120 static struct imap_server_conf server
= {
130 NULL
, /* auth_method */
133 #define NIL (void *)0x1
134 #define LIST (void *)0x2
137 struct imap_list
*next
, *child
;
148 struct imap_socket sock
;
157 int uidnext
; /* from SELECT responses */
158 struct imap_list
*ns_personal
, *ns_other
, *ns_shared
; /* NAMESPACE info */
159 unsigned caps
, rcaps
; /* CAPABILITY results */
161 int nexttag
, num_in_progress
, literal_pending
;
162 struct imap_cmd
*in_progress
, **in_progress_append
;
163 struct imap_buffer buf
; /* this is BIG, so put it last */
171 unsigned /*currentnc:1,*/ trashnc
:1;
175 int (*cont
)(struct imap_store
*ctx
, struct imap_cmd
*cmd
, const char *prompt
);
176 void (*done
)(struct imap_store
*ctx
, struct imap_cmd
*cmd
, int response
);
181 unsigned create
:1, trycreate
:1;
185 struct imap_cmd
*next
;
186 struct imap_cmd_cb cb
;
191 #define CAP(cap) (imap->caps & (1 << (cap)))
202 static const char *cap_list
[] = {
215 static int get_cmd_result(struct imap_store
*ctx
, struct imap_cmd
*tcmd
);
219 static void ssl_socket_perror(const char *func
)
221 fprintf(stderr
, "%s: %s\n", func
, ERR_error_string(ERR_get_error(), NULL
));
225 static void socket_perror(const char *func
, struct imap_socket
*sock
, int ret
)
229 int sslerr
= SSL_get_error(sock
->ssl
, ret
);
233 case SSL_ERROR_SYSCALL
:
234 perror("SSL_connect");
237 ssl_socket_perror("SSL_connect");
246 fprintf(stderr
, "%s: unexpected EOF\n", func
);
250 static int ssl_socket_connect(struct imap_socket
*sock
, int use_tls_only
, int verify
)
253 fprintf(stderr
, "SSL requested but SSL support not compiled in\n");
256 #if (OPENSSL_VERSION_NUMBER >= 0x10000000L)
257 const SSL_METHOD
*meth
;
265 SSL_load_error_strings();
268 meth
= TLSv1_method();
270 meth
= SSLv23_method();
273 ssl_socket_perror("SSLv23_method");
277 ctx
= SSL_CTX_new(meth
);
280 SSL_CTX_set_verify(ctx
, SSL_VERIFY_PEER
, NULL
);
282 if (!SSL_CTX_set_default_verify_paths(ctx
)) {
283 ssl_socket_perror("SSL_CTX_set_default_verify_paths");
286 sock
->ssl
= SSL_new(ctx
);
288 ssl_socket_perror("SSL_new");
291 if (!SSL_set_rfd(sock
->ssl
, sock
->fd
[0])) {
292 ssl_socket_perror("SSL_set_rfd");
295 if (!SSL_set_wfd(sock
->ssl
, sock
->fd
[1])) {
296 ssl_socket_perror("SSL_set_wfd");
300 ret
= SSL_connect(sock
->ssl
);
302 socket_perror("SSL_connect", sock
, ret
);
310 static int socket_read(struct imap_socket
*sock
, char *buf
, int len
)
315 n
= SSL_read(sock
->ssl
, buf
, len
);
318 n
= xread(sock
->fd
[0], buf
, len
);
320 socket_perror("read", sock
, n
);
323 sock
->fd
[0] = sock
->fd
[1] = -1;
328 static int socket_write(struct imap_socket
*sock
, const char *buf
, int len
)
333 n
= SSL_write(sock
->ssl
, buf
, len
);
336 n
= write_in_full(sock
->fd
[1], buf
, len
);
338 socket_perror("write", sock
, n
);
341 sock
->fd
[0] = sock
->fd
[1] = -1;
346 static void socket_shutdown(struct imap_socket
*sock
)
350 SSL_shutdown(sock
->ssl
);
358 /* simple line buffering */
359 static int buffer_gets(struct imap_buffer
*b
, char **s
)
362 int start
= b
->offset
;
367 /* make sure we have enough data to read the \r\n sequence */
368 if (b
->offset
+ 1 >= b
->bytes
) {
370 /* shift down used bytes */
373 assert(start
<= b
->bytes
);
374 n
= b
->bytes
- start
;
377 memmove(b
->buf
, b
->buf
+ start
, n
);
383 n
= socket_read(&b
->sock
, b
->buf
+ b
->bytes
,
384 sizeof(b
->buf
) - b
->bytes
);
392 if (b
->buf
[b
->offset
] == '\r') {
393 assert(b
->offset
+ 1 < b
->bytes
);
394 if (b
->buf
[b
->offset
+ 1] == '\n') {
395 b
->buf
[b
->offset
] = 0; /* terminate the string */
396 b
->offset
+= 2; /* next line */
408 static void imap_info(const char *msg
, ...)
420 static void imap_warn(const char *msg
, ...)
426 vfprintf(stderr
, msg
, va
);
431 static char *next_arg(char **s
)
437 while (isspace((unsigned char) **s
))
446 *s
= strchr(*s
, '"');
449 while (**s
&& !isspace((unsigned char) **s
))
461 static void free_generic_messages(struct message
*msgs
)
463 struct message
*tmsg
;
465 for (; msgs
; msgs
= tmsg
) {
471 static int nfsnprintf(char *buf
, int blen
, const char *fmt
, ...)
477 if (blen
<= 0 || (unsigned)(ret
= vsnprintf(buf
, blen
, fmt
, va
)) >= (unsigned)blen
)
478 die("Fatal: buffer too small. Please report a bug.");
483 static struct imap_cmd
*v_issue_imap_cmd(struct imap_store
*ctx
,
484 struct imap_cmd_cb
*cb
,
485 const char *fmt
, va_list ap
)
487 struct imap
*imap
= ctx
->imap
;
488 struct imap_cmd
*cmd
;
492 cmd
= xmalloc(sizeof(struct imap_cmd
));
493 nfvasprintf(&cmd
->cmd
, fmt
, ap
);
494 cmd
->tag
= ++imap
->nexttag
;
499 memset(&cmd
->cb
, 0, sizeof(cmd
->cb
));
501 while (imap
->literal_pending
)
502 get_cmd_result(ctx
, NULL
);
505 bufl
= nfsnprintf(buf
, sizeof(buf
), "%d %s\r\n", cmd
->tag
, cmd
->cmd
);
507 bufl
= nfsnprintf(buf
, sizeof(buf
), "%d %s{%d%s}\r\n",
508 cmd
->tag
, cmd
->cmd
, cmd
->cb
.dlen
,
509 CAP(LITERALPLUS
) ? "+" : "");
512 if (imap
->num_in_progress
)
513 printf("(%d in progress) ", imap
->num_in_progress
);
514 if (memcmp(cmd
->cmd
, "LOGIN", 5))
515 printf(">>> %s", buf
);
517 printf(">>> %d LOGIN <user> <pass>\n", cmd
->tag
);
519 if (socket_write(&imap
->buf
.sock
, buf
, bufl
) != bufl
) {
527 if (CAP(LITERALPLUS
)) {
528 n
= socket_write(&imap
->buf
.sock
, cmd
->cb
.data
, cmd
->cb
.dlen
);
530 if (n
!= cmd
->cb
.dlen
||
531 socket_write(&imap
->buf
.sock
, "\r\n", 2) != 2) {
538 imap
->literal_pending
= 1;
539 } else if (cmd
->cb
.cont
)
540 imap
->literal_pending
= 1;
542 *imap
->in_progress_append
= cmd
;
543 imap
->in_progress_append
= &cmd
->next
;
544 imap
->num_in_progress
++;
548 __attribute__((format (printf
, 3, 4)))
549 static struct imap_cmd
*issue_imap_cmd(struct imap_store
*ctx
,
550 struct imap_cmd_cb
*cb
,
551 const char *fmt
, ...)
553 struct imap_cmd
*ret
;
557 ret
= v_issue_imap_cmd(ctx
, cb
, fmt
, ap
);
562 __attribute__((format (printf
, 3, 4)))
563 static int imap_exec(struct imap_store
*ctx
, struct imap_cmd_cb
*cb
,
564 const char *fmt
, ...)
567 struct imap_cmd
*cmdp
;
570 cmdp
= v_issue_imap_cmd(ctx
, cb
, fmt
, ap
);
575 return get_cmd_result(ctx
, cmdp
);
578 __attribute__((format (printf
, 3, 4)))
579 static int imap_exec_m(struct imap_store
*ctx
, struct imap_cmd_cb
*cb
,
580 const char *fmt
, ...)
583 struct imap_cmd
*cmdp
;
586 cmdp
= v_issue_imap_cmd(ctx
, cb
, fmt
, ap
);
589 return DRV_STORE_BAD
;
591 switch (get_cmd_result(ctx
, cmdp
)) {
592 case RESP_BAD
: return DRV_STORE_BAD
;
593 case RESP_NO
: return DRV_MSG_BAD
;
594 default: return DRV_OK
;
598 static int is_atom(struct imap_list
*list
)
600 return list
&& list
->val
&& list
->val
!= NIL
&& list
->val
!= LIST
;
603 static int is_list(struct imap_list
*list
)
605 return list
&& list
->val
== LIST
;
608 static void free_list(struct imap_list
*list
)
610 struct imap_list
*tmp
;
612 for (; list
; list
= tmp
) {
615 free_list(list
->child
);
616 else if (is_atom(list
))
622 static int parse_imap_list_l(struct imap
*imap
, char **sp
, struct imap_list
**curp
, int level
)
624 struct imap_list
*cur
;
629 while (isspace((unsigned char)*s
))
631 if (level
&& *s
== ')') {
635 *curp
= cur
= xmalloc(sizeof(*cur
));
637 cur
->val
= NULL
; /* for clean bail */
642 if (parse_imap_list_l(imap
, &s
, &cur
->child
, level
+ 1))
644 } else if (imap
&& *s
== '{') {
646 bytes
= cur
->len
= strtol(s
+ 1, &s
, 10);
650 s
= cur
->val
= xmalloc(cur
->len
);
652 /* dump whats left over in the input buffer */
653 n
= imap
->buf
.bytes
- imap
->buf
.offset
;
656 /* the entire message fit in the buffer */
659 memcpy(s
, imap
->buf
.buf
+ imap
->buf
.offset
, n
);
663 /* mark that we used part of the buffer */
664 imap
->buf
.offset
+= n
;
666 /* now read the rest of the message */
668 if ((n
= socket_read(&imap
->buf
.sock
, s
, bytes
)) <= 0)
674 if (buffer_gets(&imap
->buf
, &s
))
676 } else if (*s
== '"') {
680 for (; *s
!= '"'; s
++)
685 cur
->val
= xmemdupz(p
, cur
->len
);
689 for (; *s
&& !isspace((unsigned char)*s
); s
++)
690 if (level
&& *s
== ')')
693 if (cur
->len
== 3 && !memcmp("NIL", p
, 3))
696 cur
->val
= xmemdupz(p
, cur
->len
);
713 static struct imap_list
*parse_imap_list(struct imap
*imap
, char **sp
)
715 struct imap_list
*head
;
717 if (!parse_imap_list_l(imap
, sp
, &head
, 0))
723 static struct imap_list
*parse_list(char **sp
)
725 return parse_imap_list(NULL
, sp
);
728 static void parse_capability(struct imap
*imap
, char *cmd
)
733 imap
->caps
= 0x80000000;
734 while ((arg
= next_arg(&cmd
)))
735 for (i
= 0; i
< ARRAY_SIZE(cap_list
); i
++)
736 if (!strcmp(cap_list
[i
], arg
))
737 imap
->caps
|= 1 << i
;
738 imap
->rcaps
= imap
->caps
;
741 static int parse_response_code(struct imap_store
*ctx
, struct imap_cmd_cb
*cb
,
744 struct imap
*imap
= ctx
->imap
;
748 return RESP_OK
; /* no response code */
750 if (!(p
= strchr(s
, ']'))) {
751 fprintf(stderr
, "IMAP error: malformed response code\n");
756 if (!strcmp("UIDVALIDITY", arg
)) {
757 if (!(arg
= next_arg(&s
)) || !(ctx
->gen
.uidvalidity
= atoi(arg
))) {
758 fprintf(stderr
, "IMAP error: malformed UIDVALIDITY status\n");
761 } else if (!strcmp("UIDNEXT", arg
)) {
762 if (!(arg
= next_arg(&s
)) || !(imap
->uidnext
= atoi(arg
))) {
763 fprintf(stderr
, "IMAP error: malformed NEXTUID status\n");
766 } else if (!strcmp("CAPABILITY", arg
)) {
767 parse_capability(imap
, s
);
768 } else if (!strcmp("ALERT", arg
)) {
769 /* RFC2060 says that these messages MUST be displayed
772 for (; isspace((unsigned char)*p
); p
++);
773 fprintf(stderr
, "*** IMAP ALERT *** %s\n", p
);
774 } else if (cb
&& cb
->ctx
&& !strcmp("APPENDUID", arg
)) {
775 if (!(arg
= next_arg(&s
)) || !(ctx
->gen
.uidvalidity
= atoi(arg
)) ||
776 !(arg
= next_arg(&s
)) || !(*(int *)cb
->ctx
= atoi(arg
))) {
777 fprintf(stderr
, "IMAP error: malformed APPENDUID status\n");
784 static int get_cmd_result(struct imap_store
*ctx
, struct imap_cmd
*tcmd
)
786 struct imap
*imap
= ctx
->imap
;
787 struct imap_cmd
*cmdp
, **pcmdp
, *ncmdp
;
788 char *cmd
, *arg
, *arg1
, *p
;
789 int n
, resp
, resp2
, tag
;
792 if (buffer_gets(&imap
->buf
, &cmd
))
795 arg
= next_arg(&cmd
);
797 arg
= next_arg(&cmd
);
799 fprintf(stderr
, "IMAP error: unable to parse untagged response\n");
803 if (!strcmp("NAMESPACE", arg
)) {
804 imap
->ns_personal
= parse_list(&cmd
);
805 imap
->ns_other
= parse_list(&cmd
);
806 imap
->ns_shared
= parse_list(&cmd
);
807 } else if (!strcmp("OK", arg
) || !strcmp("BAD", arg
) ||
808 !strcmp("NO", arg
) || !strcmp("BYE", arg
)) {
809 if ((resp
= parse_response_code(ctx
, NULL
, cmd
)) != RESP_OK
)
811 } else if (!strcmp("CAPABILITY", arg
))
812 parse_capability(imap
, cmd
);
813 else if ((arg1
= next_arg(&cmd
))) {
814 if (!strcmp("EXISTS", arg1
))
815 ctx
->gen
.count
= atoi(arg
);
816 else if (!strcmp("RECENT", arg1
))
817 ctx
->gen
.recent
= atoi(arg
);
819 fprintf(stderr
, "IMAP error: unable to parse untagged response\n");
822 } else if (!imap
->in_progress
) {
823 fprintf(stderr
, "IMAP error: unexpected reply: %s %s\n", arg
, cmd
? cmd
: "");
825 } else if (*arg
== '+') {
826 /* This can happen only with the last command underway, as
827 it enforces a round-trip. */
828 cmdp
= (struct imap_cmd
*)((char *)imap
->in_progress_append
-
829 offsetof(struct imap_cmd
, next
));
831 n
= socket_write(&imap
->buf
.sock
, cmdp
->cb
.data
, cmdp
->cb
.dlen
);
833 cmdp
->cb
.data
= NULL
;
834 if (n
!= (int)cmdp
->cb
.dlen
)
836 } else if (cmdp
->cb
.cont
) {
837 if (cmdp
->cb
.cont(ctx
, cmdp
, cmd
))
840 fprintf(stderr
, "IMAP error: unexpected command continuation request\n");
843 if (socket_write(&imap
->buf
.sock
, "\r\n", 2) != 2)
846 imap
->literal_pending
= 0;
851 for (pcmdp
= &imap
->in_progress
; (cmdp
= *pcmdp
); pcmdp
= &cmdp
->next
)
852 if (cmdp
->tag
== tag
)
854 fprintf(stderr
, "IMAP error: unexpected tag %s\n", arg
);
857 if (!(*pcmdp
= cmdp
->next
))
858 imap
->in_progress_append
= pcmdp
;
859 imap
->num_in_progress
--;
860 if (cmdp
->cb
.cont
|| cmdp
->cb
.data
)
861 imap
->literal_pending
= 0;
862 arg
= next_arg(&cmd
);
863 if (!strcmp("OK", arg
))
866 if (!strcmp("NO", arg
)) {
867 if (cmdp
->cb
.create
&& cmd
&& (cmdp
->cb
.trycreate
|| !memcmp(cmd
, "[TRYCREATE]", 11))) { /* SELECT, APPEND or UID COPY */
868 p
= strchr(cmdp
->cmd
, '"');
869 if (!issue_imap_cmd(ctx
, NULL
, "CREATE \"%.*s\"", (int)(strchr(p
+ 1, '"') - p
+ 1), p
)) {
873 /* not waiting here violates the spec, but a server that does not
874 grok this nonetheless violates it too. */
876 if (!(ncmdp
= issue_imap_cmd(ctx
, &cmdp
->cb
, "%s", cmdp
->cmd
))) {
883 return 0; /* ignored */
889 } else /*if (!strcmp("BAD", arg))*/
891 fprintf(stderr
, "IMAP command '%s' returned response (%s) - %s\n",
892 memcmp(cmdp
->cmd
, "LOGIN", 5) ?
893 cmdp
->cmd
: "LOGIN <user> <pass>",
894 arg
, cmd
? cmd
: "");
896 if ((resp2
= parse_response_code(ctx
, &cmdp
->cb
, cmd
)) > resp
)
900 cmdp
->cb
.done(ctx
, cmdp
, resp
);
904 if (!tcmd
|| tcmd
== cmdp
)
911 static void imap_close_server(struct imap_store
*ictx
)
913 struct imap
*imap
= ictx
->imap
;
915 if (imap
->buf
.sock
.fd
[0] != -1) {
916 imap_exec(ictx
, NULL
, "LOGOUT");
917 socket_shutdown(&imap
->buf
.sock
);
919 free_list(imap
->ns_personal
);
920 free_list(imap
->ns_other
);
921 free_list(imap
->ns_shared
);
925 static void imap_close_store(struct store
*ctx
)
927 imap_close_server((struct imap_store
*)ctx
);
928 free_generic_messages(ctx
->msgs
);
935 * hexchar() and cram() functions are based on the code from the isync
936 * project (http://isync.sf.net/).
938 static char hexchar(unsigned int b
)
940 return b
< 10 ? '0' + b
: 'a' + (b
- 10);
943 #define ENCODED_SIZE(n) (4*((n+2)/3))
944 static char *cram(const char *challenge_64
, const char *user
, const char *pass
)
946 int i
, resp_len
, encoded_len
, decoded_len
;
948 unsigned char hash
[16];
950 char *response
, *response_64
, *challenge
;
953 * length of challenge_64 (i.e. base-64 encoded string) is a good
954 * enough upper bound for challenge (decoded result).
956 encoded_len
= strlen(challenge_64
);
957 challenge
= xmalloc(encoded_len
);
958 decoded_len
= EVP_DecodeBlock((unsigned char *)challenge
,
959 (unsigned char *)challenge_64
, encoded_len
);
961 die("invalid challenge %s", challenge_64
);
962 HMAC_Init(&hmac
, (unsigned char *)pass
, strlen(pass
), EVP_md5());
963 HMAC_Update(&hmac
, (unsigned char *)challenge
, decoded_len
);
964 HMAC_Final(&hmac
, hash
, NULL
);
965 HMAC_CTX_cleanup(&hmac
);
968 for (i
= 0; i
< 16; i
++) {
969 hex
[2 * i
] = hexchar((hash
[i
] >> 4) & 0xf);
970 hex
[2 * i
+ 1] = hexchar(hash
[i
] & 0xf);
973 /* response: "<user> <digest in hex>" */
974 resp_len
= strlen(user
) + 1 + strlen(hex
) + 1;
975 response
= xmalloc(resp_len
);
976 sprintf(response
, "%s %s", user
, hex
);
978 response_64
= xmalloc(ENCODED_SIZE(resp_len
) + 1);
979 encoded_len
= EVP_EncodeBlock((unsigned char *)response_64
,
980 (unsigned char *)response
, resp_len
);
982 die("EVP_EncodeBlock error");
983 response_64
[encoded_len
] = '\0';
984 return (char *)response_64
;
989 static char *cram(const char *challenge_64
, const char *user
, const char *pass
)
991 die("If you want to use CRAM-MD5 authenticate method, "
992 "you have to build git-imap-send with OpenSSL library.");
997 static int auth_cram_md5(struct imap_store
*ctx
, struct imap_cmd
*cmd
, const char *prompt
)
1002 response
= cram(prompt
, server
.user
, server
.pass
);
1004 ret
= socket_write(&ctx
->imap
->buf
.sock
, response
, strlen(response
));
1005 if (ret
!= strlen(response
))
1006 return error("IMAP error: sending response failed");
1013 static struct store
*imap_open_store(struct imap_server_conf
*srvc
)
1015 struct imap_store
*ctx
;
1018 int s
= -1, preauth
;
1020 ctx
= xcalloc(sizeof(*ctx
), 1);
1022 ctx
->imap
= imap
= xcalloc(sizeof(*imap
), 1);
1023 imap
->buf
.sock
.fd
[0] = imap
->buf
.sock
.fd
[1] = -1;
1024 imap
->in_progress_append
= &imap
->in_progress
;
1026 /* open connection to IMAP server */
1029 const char *argv
[] = { srvc
->tunnel
, NULL
};
1030 struct child_process tunnel
= {NULL
};
1032 imap_info("Starting tunnel '%s'... ", srvc
->tunnel
);
1035 tunnel
.use_shell
= 1;
1038 if (start_command(&tunnel
))
1039 die("cannot start proxy %s", argv
[0]);
1041 imap
->buf
.sock
.fd
[0] = tunnel
.out
;
1042 imap
->buf
.sock
.fd
[1] = tunnel
.in
;
1047 struct addrinfo hints
, *ai0
, *ai
;
1051 snprintf(portstr
, sizeof(portstr
), "%d", srvc
->port
);
1053 memset(&hints
, 0, sizeof(hints
));
1054 hints
.ai_socktype
= SOCK_STREAM
;
1055 hints
.ai_protocol
= IPPROTO_TCP
;
1057 imap_info("Resolving %s... ", srvc
->host
);
1058 gai
= getaddrinfo(srvc
->host
, portstr
, &hints
, &ai
);
1060 fprintf(stderr
, "getaddrinfo: %s\n", gai_strerror(gai
));
1065 for (ai0
= ai
; ai
; ai
= ai
->ai_next
) {
1066 char addr
[NI_MAXHOST
];
1068 s
= socket(ai
->ai_family
, ai
->ai_socktype
,
1073 getnameinfo(ai
->ai_addr
, ai
->ai_addrlen
, addr
,
1074 sizeof(addr
), NULL
, 0, NI_NUMERICHOST
);
1075 imap_info("Connecting to [%s]:%s... ", addr
, portstr
);
1077 if (connect(s
, ai
->ai_addr
, ai
->ai_addrlen
) < 0) {
1089 struct sockaddr_in addr
;
1091 memset(&addr
, 0, sizeof(addr
));
1092 addr
.sin_port
= htons(srvc
->port
);
1093 addr
.sin_family
= AF_INET
;
1095 imap_info("Resolving %s... ", srvc
->host
);
1096 he
= gethostbyname(srvc
->host
);
1098 perror("gethostbyname");
1103 addr
.sin_addr
.s_addr
= *((int *) he
->h_addr_list
[0]);
1105 s
= socket(PF_INET
, SOCK_STREAM
, 0);
1107 imap_info("Connecting to %s:%hu... ", inet_ntoa(addr
.sin_addr
), ntohs(addr
.sin_port
));
1108 if (connect(s
, (struct sockaddr
*)&addr
, sizeof(addr
))) {
1115 fputs("Error: unable to connect to server.\n", stderr
);
1119 imap
->buf
.sock
.fd
[0] = s
;
1120 imap
->buf
.sock
.fd
[1] = dup(s
);
1122 if (srvc
->use_ssl
&&
1123 ssl_socket_connect(&imap
->buf
.sock
, 0, srvc
->ssl_verify
)) {
1130 /* read the greeting string */
1131 if (buffer_gets(&imap
->buf
, &rsp
)) {
1132 fprintf(stderr
, "IMAP error: no greeting response\n");
1135 arg
= next_arg(&rsp
);
1136 if (!arg
|| *arg
!= '*' || (arg
= next_arg(&rsp
)) == NULL
) {
1137 fprintf(stderr
, "IMAP error: invalid greeting response\n");
1141 if (!strcmp("PREAUTH", arg
))
1143 else if (strcmp("OK", arg
) != 0) {
1144 fprintf(stderr
, "IMAP error: unknown greeting response\n");
1147 parse_response_code(ctx
, NULL
, rsp
);
1148 if (!imap
->caps
&& imap_exec(ctx
, NULL
, "CAPABILITY") != RESP_OK
)
1153 if (!srvc
->use_ssl
&& CAP(STARTTLS
)) {
1154 if (imap_exec(ctx
, NULL
, "STARTTLS") != RESP_OK
)
1156 if (ssl_socket_connect(&imap
->buf
.sock
, 1,
1159 /* capabilities may have changed, so get the new capabilities */
1160 if (imap_exec(ctx
, NULL
, "CAPABILITY") != RESP_OK
)
1164 imap_info("Logging in...\n");
1166 fprintf(stderr
, "Skipping server %s, no user\n", srvc
->host
);
1170 struct strbuf prompt
= STRBUF_INIT
;
1171 strbuf_addf(&prompt
, "Password (%s@%s): ", srvc
->user
, srvc
->host
);
1172 arg
= git_getpass(prompt
.buf
);
1173 strbuf_release(&prompt
);
1175 fprintf(stderr
, "Skipping account %s@%s, no password\n", srvc
->user
, srvc
->host
);
1179 * getpass() returns a pointer to a static buffer. make a copy
1180 * for long term storage.
1182 srvc
->pass
= xstrdup(arg
);
1185 fprintf(stderr
, "Skipping account %s@%s, server forbids LOGIN\n", srvc
->user
, srvc
->host
);
1189 if (srvc
->auth_method
) {
1190 struct imap_cmd_cb cb
;
1192 if (!strcmp(srvc
->auth_method
, "CRAM-MD5")) {
1193 if (!CAP(AUTH_CRAM_MD5
)) {
1194 fprintf(stderr
, "You specified"
1195 "CRAM-MD5 as authentication method, "
1196 "but %s doesn't support it.\n", srvc
->host
);
1201 memset(&cb
, 0, sizeof(cb
));
1202 cb
.cont
= auth_cram_md5
;
1203 if (imap_exec(ctx
, &cb
, "AUTHENTICATE CRAM-MD5") != RESP_OK
) {
1204 fprintf(stderr
, "IMAP error: AUTHENTICATE CRAM-MD5 failed\n");
1208 fprintf(stderr
, "Unknown authentication method:%s\n", srvc
->host
);
1212 if (!imap
->buf
.sock
.ssl
)
1213 imap_warn("*** IMAP Warning *** Password is being "
1214 "sent in the clear\n");
1215 if (imap_exec(ctx
, NULL
, "LOGIN \"%s\" \"%s\"", srvc
->user
, srvc
->pass
) != RESP_OK
) {
1216 fprintf(stderr
, "IMAP error: LOGIN failed\n");
1224 return (struct store
*)ctx
;
1227 imap_close_store(&ctx
->gen
);
1231 static void lf_to_crlf(struct strbuf
*msg
)
1235 int i
, j
, lfnum
= 0;
1237 if (msg
->buf
[0] == '\n')
1239 for (i
= 1; i
< msg
->len
; i
++) {
1240 if (msg
->buf
[i
- 1] != '\r' && msg
->buf
[i
] == '\n')
1244 new_len
= msg
->len
+ lfnum
;
1245 new = xmalloc(new_len
+ 1);
1246 if (msg
->buf
[0] == '\n') {
1252 new[0] = msg
->buf
[0];
1256 for ( ; i
< msg
->len
; i
++) {
1257 if (msg
->buf
[i
] != '\n') {
1258 new[j
++] = msg
->buf
[i
];
1261 if (msg
->buf
[i
- 1] != '\r')
1263 /* otherwise it already had CR before */
1266 strbuf_attach(msg
, new, new_len
, new_len
+ 1);
1270 * Store msg to IMAP. Also detach and free the data from msg->data,
1271 * leaving msg->data empty.
1273 static int imap_store_msg(struct store
*gctx
, struct strbuf
*msg
)
1275 struct imap_store
*ctx
= (struct imap_store
*)gctx
;
1276 struct imap
*imap
= ctx
->imap
;
1277 struct imap_cmd_cb cb
;
1278 const char *prefix
, *box
;
1282 memset(&cb
, 0, sizeof(cb
));
1285 cb
.data
= strbuf_detach(msg
, NULL
);
1288 prefix
= !strcmp(box
, "INBOX") ? "" : ctx
->prefix
;
1290 ret
= imap_exec_m(ctx
, &cb
, "APPEND \"%s%s\" ", prefix
, box
);
1291 imap
->caps
= imap
->rcaps
;
1299 static void wrap_in_html(struct strbuf
*msg
)
1301 struct strbuf buf
= STRBUF_INIT
;
1302 static char *content_type
= "Content-Type: text/html;\n";
1303 static char *pre_open
= "<pre>\n";
1304 static char *pre_close
= "</pre>\n";
1305 const char *body
= strstr(msg
->buf
, "\n\n");
1308 return; /* Headers but no body; no wrapping needed */
1312 strbuf_add(&buf
, msg
->buf
, body
- msg
->buf
- 1);
1313 strbuf_addstr(&buf
, content_type
);
1314 strbuf_addch(&buf
, '\n');
1315 strbuf_addstr(&buf
, pre_open
);
1316 strbuf_addstr_xml_quoted(&buf
, body
);
1317 strbuf_addstr(&buf
, pre_close
);
1319 strbuf_release(msg
);
1323 #define CHUNKSIZE 0x1000
1325 static int read_message(FILE *f
, struct strbuf
*all_msgs
)
1328 if (strbuf_fread(all_msgs
, CHUNKSIZE
, f
) <= 0)
1332 return ferror(f
) ? -1 : 0;
1335 static int count_messages(struct strbuf
*all_msgs
)
1338 char *p
= all_msgs
->buf
;
1341 if (!prefixcmp(p
, "From ")) {
1342 p
= strstr(p
+5, "\nFrom: ");
1344 p
= strstr(p
+7, "\nDate: ");
1346 p
= strstr(p
+7, "\nSubject: ");
1351 p
= strstr(p
+5, "\nFrom ");
1360 * Copy the next message from all_msgs, starting at offset *ofs, to
1361 * msg. Update *ofs to the start of the following message. Return
1362 * true iff a message was successfully copied.
1364 static int split_msg(struct strbuf
*all_msgs
, struct strbuf
*msg
, int *ofs
)
1369 if (*ofs
>= all_msgs
->len
)
1372 data
= &all_msgs
->buf
[*ofs
];
1373 len
= all_msgs
->len
- *ofs
;
1375 if (len
< 5 || prefixcmp(data
, "From "))
1378 p
= strchr(data
, '\n');
1386 p
= strstr(data
, "\nFrom ");
1390 strbuf_add(msg
, data
, len
);
1395 static char *imap_folder
;
1397 static int git_imap_config(const char *key
, const char *val
, void *cb
)
1399 char imap_key
[] = "imap.";
1401 if (strncmp(key
, imap_key
, sizeof imap_key
- 1))
1404 key
+= sizeof imap_key
- 1;
1406 /* check booleans first, and barf on others */
1407 if (!strcmp("sslverify", key
))
1408 server
.ssl_verify
= git_config_bool(key
, val
);
1409 else if (!strcmp("preformattedhtml", key
))
1410 server
.use_html
= git_config_bool(key
, val
);
1412 return config_error_nonbool(key
);
1414 if (!strcmp("folder", key
)) {
1415 imap_folder
= xstrdup(val
);
1416 } else if (!strcmp("host", key
)) {
1417 if (!prefixcmp(val
, "imap:"))
1419 else if (!prefixcmp(val
, "imaps:")) {
1423 if (!prefixcmp(val
, "//"))
1425 server
.host
= xstrdup(val
);
1426 } else if (!strcmp("user", key
))
1427 server
.user
= xstrdup(val
);
1428 else if (!strcmp("pass", key
))
1429 server
.pass
= xstrdup(val
);
1430 else if (!strcmp("port", key
))
1431 server
.port
= git_config_int(key
, val
);
1432 else if (!strcmp("tunnel", key
))
1433 server
.tunnel
= xstrdup(val
);
1434 else if (!strcmp("authmethod", key
))
1435 server
.auth_method
= xstrdup(val
);
1440 int main(int argc
, char **argv
)
1442 struct strbuf all_msgs
= STRBUF_INIT
;
1443 struct strbuf msg
= STRBUF_INIT
;
1444 struct store
*ctx
= NULL
;
1450 git_extract_argv0_path(argv
[0]);
1452 git_setup_gettext();
1455 usage(imap_send_usage
);
1457 setup_git_directory_gently(&nongit_ok
);
1458 git_config(git_imap_config
, NULL
);
1461 server
.port
= server
.use_ssl
? 993 : 143;
1464 fprintf(stderr
, "no imap store specified\n");
1468 if (!server
.tunnel
) {
1469 fprintf(stderr
, "no imap host specified\n");
1472 server
.host
= "tunnel";
1475 /* read the messages */
1476 if (read_message(stdin
, &all_msgs
)) {
1477 fprintf(stderr
, "error reading input\n");
1481 if (all_msgs
.len
== 0) {
1482 fprintf(stderr
, "nothing to send\n");
1486 total
= count_messages(&all_msgs
);
1488 fprintf(stderr
, "no messages to send\n");
1492 /* write it to the imap server */
1493 ctx
= imap_open_store(&server
);
1495 fprintf(stderr
, "failed to open store\n");
1499 fprintf(stderr
, "sending %d message%s\n", total
, (total
!= 1) ? "s" : "");
1500 ctx
->name
= imap_folder
;
1502 unsigned percent
= n
* 100 / total
;
1504 fprintf(stderr
, "%4u%% (%d/%d) done\r", percent
, n
, total
);
1505 if (!split_msg(&all_msgs
, &msg
, &ofs
))
1507 if (server
.use_html
)
1509 r
= imap_store_msg(ctx
, &msg
);
1514 fprintf(stderr
, "\n");
1516 imap_close_store(ctx
);