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 */
76 static const char imap_send_usage
[] = "git imap-send < <mbox>";
80 #define DRV_MSG_BAD -1
81 #define DRV_BOX_BAD -2
82 #define DRV_STORE_BAD -3
84 static int Verbose
, Quiet
;
86 __attribute__((format (printf
, 1, 2)))
87 static void imap_info(const char *, ...);
88 __attribute__((format (printf
, 1, 2)))
89 static void imap_warn(const char *, ...);
91 static char *next_arg(char **);
93 static void free_generic_messages(struct message
*);
95 __attribute__((format (printf
, 3, 4)))
96 static int nfsnprintf(char *buf
, int blen
, const char *fmt
, ...);
98 static int nfvasprintf(char **strp
, const char *fmt
, va_list ap
)
103 len
= vsnprintf(tmp
, sizeof(tmp
), fmt
, ap
);
105 die("Fatal: Out of memory");
106 if (len
>= sizeof(tmp
))
107 die("imap command overflow!");
108 *strp
= xmemdupz(tmp
, len
);
112 struct imap_server_conf
{
125 static struct imap_server_conf server
= {
135 NULL
, /* auth_method */
138 struct imap_store_conf
{
139 struct store_conf gen
;
140 struct imap_server_conf
*server
;
143 #define NIL (void *)0x1
144 #define LIST (void *)0x2
147 struct imap_list
*next
, *child
;
158 struct imap_socket sock
;
167 int uidnext
; /* from SELECT responses */
168 struct imap_list
*ns_personal
, *ns_other
, *ns_shared
; /* NAMESPACE info */
169 unsigned caps
, rcaps
; /* CAPABILITY results */
171 int nexttag
, num_in_progress
, literal_pending
;
172 struct imap_cmd
*in_progress
, **in_progress_append
;
173 struct imap_buffer buf
; /* this is BIG, so put it last */
181 unsigned /*currentnc:1,*/ trashnc
:1;
185 int (*cont
)(struct imap_store
*ctx
, struct imap_cmd
*cmd
, const char *prompt
);
186 void (*done
)(struct imap_store
*ctx
, struct imap_cmd
*cmd
, int response
);
191 unsigned create
:1, trycreate
:1;
195 struct imap_cmd
*next
;
196 struct imap_cmd_cb cb
;
201 #define CAP(cap) (imap->caps & (1 << (cap)))
212 static const char *cap_list
[] = {
225 static int get_cmd_result(struct imap_store
*ctx
, struct imap_cmd
*tcmd
);
228 static const char *Flags
[] = {
237 static void ssl_socket_perror(const char *func
)
239 fprintf(stderr
, "%s: %s\n", func
, ERR_error_string(ERR_get_error(), NULL
));
243 static void socket_perror(const char *func
, struct imap_socket
*sock
, int ret
)
247 int sslerr
= SSL_get_error(sock
->ssl
, ret
);
251 case SSL_ERROR_SYSCALL
:
252 perror("SSL_connect");
255 ssl_socket_perror("SSL_connect");
264 fprintf(stderr
, "%s: unexpected EOF\n", func
);
268 static int ssl_socket_connect(struct imap_socket
*sock
, int use_tls_only
, int verify
)
271 fprintf(stderr
, "SSL requested but SSL support not compiled in\n");
274 #if (OPENSSL_VERSION_NUMBER >= 0x10000000L)
275 const SSL_METHOD
*meth
;
283 SSL_load_error_strings();
286 meth
= TLSv1_method();
288 meth
= SSLv23_method();
291 ssl_socket_perror("SSLv23_method");
295 ctx
= SSL_CTX_new(meth
);
298 SSL_CTX_set_verify(ctx
, SSL_VERIFY_PEER
, NULL
);
300 if (!SSL_CTX_set_default_verify_paths(ctx
)) {
301 ssl_socket_perror("SSL_CTX_set_default_verify_paths");
304 sock
->ssl
= SSL_new(ctx
);
306 ssl_socket_perror("SSL_new");
309 if (!SSL_set_rfd(sock
->ssl
, sock
->fd
[0])) {
310 ssl_socket_perror("SSL_set_rfd");
313 if (!SSL_set_wfd(sock
->ssl
, sock
->fd
[1])) {
314 ssl_socket_perror("SSL_set_wfd");
318 ret
= SSL_connect(sock
->ssl
);
320 socket_perror("SSL_connect", sock
, ret
);
328 static int socket_read(struct imap_socket
*sock
, char *buf
, int len
)
333 n
= SSL_read(sock
->ssl
, buf
, len
);
336 n
= xread(sock
->fd
[0], buf
, len
);
338 socket_perror("read", sock
, n
);
341 sock
->fd
[0] = sock
->fd
[1] = -1;
346 static int socket_write(struct imap_socket
*sock
, const char *buf
, int len
)
351 n
= SSL_write(sock
->ssl
, buf
, len
);
354 n
= write_in_full(sock
->fd
[1], buf
, len
);
356 socket_perror("write", sock
, n
);
359 sock
->fd
[0] = sock
->fd
[1] = -1;
364 static void socket_shutdown(struct imap_socket
*sock
)
368 SSL_shutdown(sock
->ssl
);
376 /* simple line buffering */
377 static int buffer_gets(struct imap_buffer
*b
, char **s
)
380 int start
= b
->offset
;
385 /* make sure we have enough data to read the \r\n sequence */
386 if (b
->offset
+ 1 >= b
->bytes
) {
388 /* shift down used bytes */
391 assert(start
<= b
->bytes
);
392 n
= b
->bytes
- start
;
395 memmove(b
->buf
, b
->buf
+ start
, n
);
401 n
= socket_read(&b
->sock
, b
->buf
+ b
->bytes
,
402 sizeof(b
->buf
) - b
->bytes
);
410 if (b
->buf
[b
->offset
] == '\r') {
411 assert(b
->offset
+ 1 < b
->bytes
);
412 if (b
->buf
[b
->offset
+ 1] == '\n') {
413 b
->buf
[b
->offset
] = 0; /* terminate the string */
414 b
->offset
+= 2; /* next line */
426 static void imap_info(const char *msg
, ...)
438 static void imap_warn(const char *msg
, ...)
444 vfprintf(stderr
, msg
, va
);
449 static char *next_arg(char **s
)
455 while (isspace((unsigned char) **s
))
464 *s
= strchr(*s
, '"');
467 while (**s
&& !isspace((unsigned char) **s
))
479 static void free_generic_messages(struct message
*msgs
)
481 struct message
*tmsg
;
483 for (; msgs
; msgs
= tmsg
) {
489 static int nfsnprintf(char *buf
, int blen
, const char *fmt
, ...)
495 if (blen
<= 0 || (unsigned)(ret
= vsnprintf(buf
, blen
, fmt
, va
)) >= (unsigned)blen
)
496 die("Fatal: buffer too small. Please report a bug.");
501 static struct imap_cmd
*v_issue_imap_cmd(struct imap_store
*ctx
,
502 struct imap_cmd_cb
*cb
,
503 const char *fmt
, va_list ap
)
505 struct imap
*imap
= ctx
->imap
;
506 struct imap_cmd
*cmd
;
510 cmd
= xmalloc(sizeof(struct imap_cmd
));
511 nfvasprintf(&cmd
->cmd
, fmt
, ap
);
512 cmd
->tag
= ++imap
->nexttag
;
517 memset(&cmd
->cb
, 0, sizeof(cmd
->cb
));
519 while (imap
->literal_pending
)
520 get_cmd_result(ctx
, NULL
);
523 bufl
= nfsnprintf(buf
, sizeof(buf
), "%d %s\r\n", cmd
->tag
, cmd
->cmd
);
525 bufl
= nfsnprintf(buf
, sizeof(buf
), "%d %s{%d%s}\r\n",
526 cmd
->tag
, cmd
->cmd
, cmd
->cb
.dlen
,
527 CAP(LITERALPLUS
) ? "+" : "");
530 if (imap
->num_in_progress
)
531 printf("(%d in progress) ", imap
->num_in_progress
);
532 if (memcmp(cmd
->cmd
, "LOGIN", 5))
533 printf(">>> %s", buf
);
535 printf(">>> %d LOGIN <user> <pass>\n", cmd
->tag
);
537 if (socket_write(&imap
->buf
.sock
, buf
, bufl
) != bufl
) {
545 if (CAP(LITERALPLUS
)) {
546 n
= socket_write(&imap
->buf
.sock
, cmd
->cb
.data
, cmd
->cb
.dlen
);
548 if (n
!= cmd
->cb
.dlen
||
549 socket_write(&imap
->buf
.sock
, "\r\n", 2) != 2) {
556 imap
->literal_pending
= 1;
557 } else if (cmd
->cb
.cont
)
558 imap
->literal_pending
= 1;
560 *imap
->in_progress_append
= cmd
;
561 imap
->in_progress_append
= &cmd
->next
;
562 imap
->num_in_progress
++;
566 __attribute__((format (printf
, 3, 4)))
567 static struct imap_cmd
*issue_imap_cmd(struct imap_store
*ctx
,
568 struct imap_cmd_cb
*cb
,
569 const char *fmt
, ...)
571 struct imap_cmd
*ret
;
575 ret
= v_issue_imap_cmd(ctx
, cb
, fmt
, ap
);
580 __attribute__((format (printf
, 3, 4)))
581 static int imap_exec(struct imap_store
*ctx
, struct imap_cmd_cb
*cb
,
582 const char *fmt
, ...)
585 struct imap_cmd
*cmdp
;
588 cmdp
= v_issue_imap_cmd(ctx
, cb
, fmt
, ap
);
593 return get_cmd_result(ctx
, cmdp
);
596 __attribute__((format (printf
, 3, 4)))
597 static int imap_exec_m(struct imap_store
*ctx
, struct imap_cmd_cb
*cb
,
598 const char *fmt
, ...)
601 struct imap_cmd
*cmdp
;
604 cmdp
= v_issue_imap_cmd(ctx
, cb
, fmt
, ap
);
607 return DRV_STORE_BAD
;
609 switch (get_cmd_result(ctx
, cmdp
)) {
610 case RESP_BAD
: return DRV_STORE_BAD
;
611 case RESP_NO
: return DRV_MSG_BAD
;
612 default: return DRV_OK
;
616 static int is_atom(struct imap_list
*list
)
618 return list
&& list
->val
&& list
->val
!= NIL
&& list
->val
!= LIST
;
621 static int is_list(struct imap_list
*list
)
623 return list
&& list
->val
== LIST
;
626 static void free_list(struct imap_list
*list
)
628 struct imap_list
*tmp
;
630 for (; list
; list
= tmp
) {
633 free_list(list
->child
);
634 else if (is_atom(list
))
640 static int parse_imap_list_l(struct imap
*imap
, char **sp
, struct imap_list
**curp
, int level
)
642 struct imap_list
*cur
;
647 while (isspace((unsigned char)*s
))
649 if (level
&& *s
== ')') {
653 *curp
= cur
= xmalloc(sizeof(*cur
));
655 cur
->val
= NULL
; /* for clean bail */
660 if (parse_imap_list_l(imap
, &s
, &cur
->child
, level
+ 1))
662 } else if (imap
&& *s
== '{') {
664 bytes
= cur
->len
= strtol(s
+ 1, &s
, 10);
668 s
= cur
->val
= xmalloc(cur
->len
);
670 /* dump whats left over in the input buffer */
671 n
= imap
->buf
.bytes
- imap
->buf
.offset
;
674 /* the entire message fit in the buffer */
677 memcpy(s
, imap
->buf
.buf
+ imap
->buf
.offset
, n
);
681 /* mark that we used part of the buffer */
682 imap
->buf
.offset
+= n
;
684 /* now read the rest of the message */
686 if ((n
= socket_read(&imap
->buf
.sock
, s
, bytes
)) <= 0)
692 if (buffer_gets(&imap
->buf
, &s
))
694 } else if (*s
== '"') {
698 for (; *s
!= '"'; s
++)
703 cur
->val
= xmemdupz(p
, cur
->len
);
707 for (; *s
&& !isspace((unsigned char)*s
); s
++)
708 if (level
&& *s
== ')')
711 if (cur
->len
== 3 && !memcmp("NIL", p
, 3))
714 cur
->val
= xmemdupz(p
, cur
->len
);
731 static struct imap_list
*parse_imap_list(struct imap
*imap
, char **sp
)
733 struct imap_list
*head
;
735 if (!parse_imap_list_l(imap
, sp
, &head
, 0))
741 static struct imap_list
*parse_list(char **sp
)
743 return parse_imap_list(NULL
, sp
);
746 static void parse_capability(struct imap
*imap
, char *cmd
)
751 imap
->caps
= 0x80000000;
752 while ((arg
= next_arg(&cmd
)))
753 for (i
= 0; i
< ARRAY_SIZE(cap_list
); i
++)
754 if (!strcmp(cap_list
[i
], arg
))
755 imap
->caps
|= 1 << i
;
756 imap
->rcaps
= imap
->caps
;
759 static int parse_response_code(struct imap_store
*ctx
, struct imap_cmd_cb
*cb
,
762 struct imap
*imap
= ctx
->imap
;
766 return RESP_OK
; /* no response code */
768 if (!(p
= strchr(s
, ']'))) {
769 fprintf(stderr
, "IMAP error: malformed response code\n");
774 if (!strcmp("UIDVALIDITY", arg
)) {
775 if (!(arg
= next_arg(&s
)) || !(ctx
->gen
.uidvalidity
= atoi(arg
))) {
776 fprintf(stderr
, "IMAP error: malformed UIDVALIDITY status\n");
779 } else if (!strcmp("UIDNEXT", arg
)) {
780 if (!(arg
= next_arg(&s
)) || !(imap
->uidnext
= atoi(arg
))) {
781 fprintf(stderr
, "IMAP error: malformed NEXTUID status\n");
784 } else if (!strcmp("CAPABILITY", arg
)) {
785 parse_capability(imap
, s
);
786 } else if (!strcmp("ALERT", arg
)) {
787 /* RFC2060 says that these messages MUST be displayed
790 for (; isspace((unsigned char)*p
); p
++);
791 fprintf(stderr
, "*** IMAP ALERT *** %s\n", p
);
792 } else if (cb
&& cb
->ctx
&& !strcmp("APPENDUID", arg
)) {
793 if (!(arg
= next_arg(&s
)) || !(ctx
->gen
.uidvalidity
= atoi(arg
)) ||
794 !(arg
= next_arg(&s
)) || !(*(int *)cb
->ctx
= atoi(arg
))) {
795 fprintf(stderr
, "IMAP error: malformed APPENDUID status\n");
802 static int get_cmd_result(struct imap_store
*ctx
, struct imap_cmd
*tcmd
)
804 struct imap
*imap
= ctx
->imap
;
805 struct imap_cmd
*cmdp
, **pcmdp
, *ncmdp
;
806 char *cmd
, *arg
, *arg1
, *p
;
807 int n
, resp
, resp2
, tag
;
810 if (buffer_gets(&imap
->buf
, &cmd
))
813 arg
= next_arg(&cmd
);
815 arg
= next_arg(&cmd
);
817 fprintf(stderr
, "IMAP error: unable to parse untagged response\n");
821 if (!strcmp("NAMESPACE", arg
)) {
822 imap
->ns_personal
= parse_list(&cmd
);
823 imap
->ns_other
= parse_list(&cmd
);
824 imap
->ns_shared
= parse_list(&cmd
);
825 } else if (!strcmp("OK", arg
) || !strcmp("BAD", arg
) ||
826 !strcmp("NO", arg
) || !strcmp("BYE", arg
)) {
827 if ((resp
= parse_response_code(ctx
, NULL
, cmd
)) != RESP_OK
)
829 } else if (!strcmp("CAPABILITY", arg
))
830 parse_capability(imap
, cmd
);
831 else if ((arg1
= next_arg(&cmd
))) {
832 if (!strcmp("EXISTS", arg1
))
833 ctx
->gen
.count
= atoi(arg
);
834 else if (!strcmp("RECENT", arg1
))
835 ctx
->gen
.recent
= atoi(arg
);
837 fprintf(stderr
, "IMAP error: unable to parse untagged response\n");
840 } else if (!imap
->in_progress
) {
841 fprintf(stderr
, "IMAP error: unexpected reply: %s %s\n", arg
, cmd
? cmd
: "");
843 } else if (*arg
== '+') {
844 /* This can happen only with the last command underway, as
845 it enforces a round-trip. */
846 cmdp
= (struct imap_cmd
*)((char *)imap
->in_progress_append
-
847 offsetof(struct imap_cmd
, next
));
849 n
= socket_write(&imap
->buf
.sock
, cmdp
->cb
.data
, cmdp
->cb
.dlen
);
851 cmdp
->cb
.data
= NULL
;
852 if (n
!= (int)cmdp
->cb
.dlen
)
854 } else if (cmdp
->cb
.cont
) {
855 if (cmdp
->cb
.cont(ctx
, cmdp
, cmd
))
858 fprintf(stderr
, "IMAP error: unexpected command continuation request\n");
861 if (socket_write(&imap
->buf
.sock
, "\r\n", 2) != 2)
864 imap
->literal_pending
= 0;
869 for (pcmdp
= &imap
->in_progress
; (cmdp
= *pcmdp
); pcmdp
= &cmdp
->next
)
870 if (cmdp
->tag
== tag
)
872 fprintf(stderr
, "IMAP error: unexpected tag %s\n", arg
);
875 if (!(*pcmdp
= cmdp
->next
))
876 imap
->in_progress_append
= pcmdp
;
877 imap
->num_in_progress
--;
878 if (cmdp
->cb
.cont
|| cmdp
->cb
.data
)
879 imap
->literal_pending
= 0;
880 arg
= next_arg(&cmd
);
881 if (!strcmp("OK", arg
))
884 if (!strcmp("NO", arg
)) {
885 if (cmdp
->cb
.create
&& cmd
&& (cmdp
->cb
.trycreate
|| !memcmp(cmd
, "[TRYCREATE]", 11))) { /* SELECT, APPEND or UID COPY */
886 p
= strchr(cmdp
->cmd
, '"');
887 if (!issue_imap_cmd(ctx
, NULL
, "CREATE \"%.*s\"", (int)(strchr(p
+ 1, '"') - p
+ 1), p
)) {
891 /* not waiting here violates the spec, but a server that does not
892 grok this nonetheless violates it too. */
894 if (!(ncmdp
= issue_imap_cmd(ctx
, &cmdp
->cb
, "%s", cmdp
->cmd
))) {
901 return 0; /* ignored */
907 } else /*if (!strcmp("BAD", arg))*/
909 fprintf(stderr
, "IMAP command '%s' returned response (%s) - %s\n",
910 memcmp(cmdp
->cmd
, "LOGIN", 5) ?
911 cmdp
->cmd
: "LOGIN <user> <pass>",
912 arg
, cmd
? cmd
: "");
914 if ((resp2
= parse_response_code(ctx
, &cmdp
->cb
, cmd
)) > resp
)
918 cmdp
->cb
.done(ctx
, cmdp
, resp
);
922 if (!tcmd
|| tcmd
== cmdp
)
929 static void imap_close_server(struct imap_store
*ictx
)
931 struct imap
*imap
= ictx
->imap
;
933 if (imap
->buf
.sock
.fd
[0] != -1) {
934 imap_exec(ictx
, NULL
, "LOGOUT");
935 socket_shutdown(&imap
->buf
.sock
);
937 free_list(imap
->ns_personal
);
938 free_list(imap
->ns_other
);
939 free_list(imap
->ns_shared
);
943 static void imap_close_store(struct store
*ctx
)
945 imap_close_server((struct imap_store
*)ctx
);
946 free_generic_messages(ctx
->msgs
);
953 * hexchar() and cram() functions are based on the code from the isync
954 * project (http://isync.sf.net/).
956 static char hexchar(unsigned int b
)
958 return b
< 10 ? '0' + b
: 'a' + (b
- 10);
961 #define ENCODED_SIZE(n) (4*((n+2)/3))
962 static char *cram(const char *challenge_64
, const char *user
, const char *pass
)
964 int i
, resp_len
, encoded_len
, decoded_len
;
966 unsigned char hash
[16];
968 char *response
, *response_64
, *challenge
;
971 * length of challenge_64 (i.e. base-64 encoded string) is a good
972 * enough upper bound for challenge (decoded result).
974 encoded_len
= strlen(challenge_64
);
975 challenge
= xmalloc(encoded_len
);
976 decoded_len
= EVP_DecodeBlock((unsigned char *)challenge
,
977 (unsigned char *)challenge_64
, encoded_len
);
979 die("invalid challenge %s", challenge_64
);
980 HMAC_Init(&hmac
, (unsigned char *)pass
, strlen(pass
), EVP_md5());
981 HMAC_Update(&hmac
, (unsigned char *)challenge
, decoded_len
);
982 HMAC_Final(&hmac
, hash
, NULL
);
983 HMAC_CTX_cleanup(&hmac
);
986 for (i
= 0; i
< 16; i
++) {
987 hex
[2 * i
] = hexchar((hash
[i
] >> 4) & 0xf);
988 hex
[2 * i
+ 1] = hexchar(hash
[i
] & 0xf);
991 /* response: "<user> <digest in hex>" */
992 resp_len
= strlen(user
) + 1 + strlen(hex
) + 1;
993 response
= xmalloc(resp_len
);
994 sprintf(response
, "%s %s", user
, hex
);
996 response_64
= xmalloc(ENCODED_SIZE(resp_len
) + 1);
997 encoded_len
= EVP_EncodeBlock((unsigned char *)response_64
,
998 (unsigned char *)response
, resp_len
);
1000 die("EVP_EncodeBlock error");
1001 response_64
[encoded_len
] = '\0';
1002 return (char *)response_64
;
1007 static char *cram(const char *challenge_64
, const char *user
, const char *pass
)
1009 die("If you want to use CRAM-MD5 authenticate method, "
1010 "you have to build git-imap-send with OpenSSL library.");
1015 static int auth_cram_md5(struct imap_store
*ctx
, struct imap_cmd
*cmd
, const char *prompt
)
1020 response
= cram(prompt
, server
.user
, server
.pass
);
1022 ret
= socket_write(&ctx
->imap
->buf
.sock
, response
, strlen(response
));
1023 if (ret
!= strlen(response
))
1024 return error("IMAP error: sending response failed");
1031 static struct store
*imap_open_store(struct imap_server_conf
*srvc
)
1033 struct imap_store
*ctx
;
1036 int s
= -1, preauth
;
1038 ctx
= xcalloc(sizeof(*ctx
), 1);
1040 ctx
->imap
= imap
= xcalloc(sizeof(*imap
), 1);
1041 imap
->buf
.sock
.fd
[0] = imap
->buf
.sock
.fd
[1] = -1;
1042 imap
->in_progress_append
= &imap
->in_progress
;
1044 /* open connection to IMAP server */
1047 const char *argv
[] = { srvc
->tunnel
, NULL
};
1048 struct child_process tunnel
= {NULL
};
1050 imap_info("Starting tunnel '%s'... ", srvc
->tunnel
);
1053 tunnel
.use_shell
= 1;
1056 if (start_command(&tunnel
))
1057 die("cannot start proxy %s", argv
[0]);
1059 imap
->buf
.sock
.fd
[0] = tunnel
.out
;
1060 imap
->buf
.sock
.fd
[1] = tunnel
.in
;
1065 struct addrinfo hints
, *ai0
, *ai
;
1069 snprintf(portstr
, sizeof(portstr
), "%d", srvc
->port
);
1071 memset(&hints
, 0, sizeof(hints
));
1072 hints
.ai_socktype
= SOCK_STREAM
;
1073 hints
.ai_protocol
= IPPROTO_TCP
;
1075 imap_info("Resolving %s... ", srvc
->host
);
1076 gai
= getaddrinfo(srvc
->host
, portstr
, &hints
, &ai
);
1078 fprintf(stderr
, "getaddrinfo: %s\n", gai_strerror(gai
));
1083 for (ai0
= ai
; ai
; ai
= ai
->ai_next
) {
1084 char addr
[NI_MAXHOST
];
1086 s
= socket(ai
->ai_family
, ai
->ai_socktype
,
1091 getnameinfo(ai
->ai_addr
, ai
->ai_addrlen
, addr
,
1092 sizeof(addr
), NULL
, 0, NI_NUMERICHOST
);
1093 imap_info("Connecting to [%s]:%s... ", addr
, portstr
);
1095 if (connect(s
, ai
->ai_addr
, ai
->ai_addrlen
) < 0) {
1107 struct sockaddr_in addr
;
1109 memset(&addr
, 0, sizeof(addr
));
1110 addr
.sin_port
= htons(srvc
->port
);
1111 addr
.sin_family
= AF_INET
;
1113 imap_info("Resolving %s... ", srvc
->host
);
1114 he
= gethostbyname(srvc
->host
);
1116 perror("gethostbyname");
1121 addr
.sin_addr
.s_addr
= *((int *) he
->h_addr_list
[0]);
1123 s
= socket(PF_INET
, SOCK_STREAM
, 0);
1125 imap_info("Connecting to %s:%hu... ", inet_ntoa(addr
.sin_addr
), ntohs(addr
.sin_port
));
1126 if (connect(s
, (struct sockaddr
*)&addr
, sizeof(addr
))) {
1133 fputs("Error: unable to connect to server.\n", stderr
);
1137 imap
->buf
.sock
.fd
[0] = s
;
1138 imap
->buf
.sock
.fd
[1] = dup(s
);
1140 if (srvc
->use_ssl
&&
1141 ssl_socket_connect(&imap
->buf
.sock
, 0, srvc
->ssl_verify
)) {
1148 /* read the greeting string */
1149 if (buffer_gets(&imap
->buf
, &rsp
)) {
1150 fprintf(stderr
, "IMAP error: no greeting response\n");
1153 arg
= next_arg(&rsp
);
1154 if (!arg
|| *arg
!= '*' || (arg
= next_arg(&rsp
)) == NULL
) {
1155 fprintf(stderr
, "IMAP error: invalid greeting response\n");
1159 if (!strcmp("PREAUTH", arg
))
1161 else if (strcmp("OK", arg
) != 0) {
1162 fprintf(stderr
, "IMAP error: unknown greeting response\n");
1165 parse_response_code(ctx
, NULL
, rsp
);
1166 if (!imap
->caps
&& imap_exec(ctx
, NULL
, "CAPABILITY") != RESP_OK
)
1171 if (!srvc
->use_ssl
&& CAP(STARTTLS
)) {
1172 if (imap_exec(ctx
, NULL
, "STARTTLS") != RESP_OK
)
1174 if (ssl_socket_connect(&imap
->buf
.sock
, 1,
1177 /* capabilities may have changed, so get the new capabilities */
1178 if (imap_exec(ctx
, NULL
, "CAPABILITY") != RESP_OK
)
1182 imap_info("Logging in...\n");
1184 fprintf(stderr
, "Skipping server %s, no user\n", srvc
->host
);
1188 struct strbuf prompt
= STRBUF_INIT
;
1189 strbuf_addf(&prompt
, "Password (%s@%s): ", srvc
->user
, srvc
->host
);
1190 arg
= git_getpass(prompt
.buf
);
1191 strbuf_release(&prompt
);
1193 fprintf(stderr
, "Skipping account %s@%s, no password\n", srvc
->user
, srvc
->host
);
1197 * getpass() returns a pointer to a static buffer. make a copy
1198 * for long term storage.
1200 srvc
->pass
= xstrdup(arg
);
1203 fprintf(stderr
, "Skipping account %s@%s, server forbids LOGIN\n", srvc
->user
, srvc
->host
);
1207 if (srvc
->auth_method
) {
1208 struct imap_cmd_cb cb
;
1210 if (!strcmp(srvc
->auth_method
, "CRAM-MD5")) {
1211 if (!CAP(AUTH_CRAM_MD5
)) {
1212 fprintf(stderr
, "You specified"
1213 "CRAM-MD5 as authentication method, "
1214 "but %s doesn't support it.\n", srvc
->host
);
1219 memset(&cb
, 0, sizeof(cb
));
1220 cb
.cont
= auth_cram_md5
;
1221 if (imap_exec(ctx
, &cb
, "AUTHENTICATE CRAM-MD5") != RESP_OK
) {
1222 fprintf(stderr
, "IMAP error: AUTHENTICATE CRAM-MD5 failed\n");
1226 fprintf(stderr
, "Unknown authentication method:%s\n", srvc
->host
);
1230 if (!imap
->buf
.sock
.ssl
)
1231 imap_warn("*** IMAP Warning *** Password is being "
1232 "sent in the clear\n");
1233 if (imap_exec(ctx
, NULL
, "LOGIN \"%s\" \"%s\"", srvc
->user
, srvc
->pass
) != RESP_OK
) {
1234 fprintf(stderr
, "IMAP error: LOGIN failed\n");
1242 return (struct store
*)ctx
;
1245 imap_close_store(&ctx
->gen
);
1249 static int imap_make_flags(int flags
, char *buf
)
1254 for (i
= d
= 0; i
< ARRAY_SIZE(Flags
); i
++)
1255 if (flags
& (1 << i
)) {
1258 for (s
= Flags
[i
]; *s
; s
++)
1266 static void lf_to_crlf(struct strbuf
*msg
)
1270 int i
, j
, lfnum
= 0;
1272 if (msg
->buf
[0] == '\n')
1274 for (i
= 1; i
< msg
->len
; i
++) {
1275 if (msg
->buf
[i
- 1] != '\r' && msg
->buf
[i
] == '\n')
1279 new_len
= msg
->len
+ lfnum
;
1280 new = xmalloc(new_len
+ 1);
1281 if (msg
->buf
[0] == '\n') {
1287 new[0] = msg
->buf
[0];
1291 for ( ; i
< msg
->len
; i
++) {
1292 if (msg
->buf
[i
] != '\n') {
1293 new[j
++] = msg
->buf
[i
];
1296 if (msg
->buf
[i
- 1] != '\r')
1298 /* otherwise it already had CR before */
1301 strbuf_attach(msg
, new, new_len
, new_len
+ 1);
1305 * Store msg to IMAP. Also detach and free the data from msg->data,
1306 * leaving msg->data empty.
1308 static int imap_store_msg(struct store
*gctx
, struct msg_data
*msg
)
1310 struct imap_store
*ctx
= (struct imap_store
*)gctx
;
1311 struct imap
*imap
= ctx
->imap
;
1312 struct imap_cmd_cb cb
;
1313 const char *prefix
, *box
;
1317 lf_to_crlf(&msg
->data
);
1318 memset(&cb
, 0, sizeof(cb
));
1320 cb
.dlen
= msg
->data
.len
;
1321 cb
.data
= strbuf_detach(&msg
->data
, NULL
);
1325 d
= imap_make_flags(msg
->flags
, flagstr
);
1331 prefix
= !strcmp(box
, "INBOX") ? "" : ctx
->prefix
;
1333 ret
= imap_exec_m(ctx
, &cb
, "APPEND \"%s%s\" %s", prefix
, box
, flagstr
);
1334 imap
->caps
= imap
->rcaps
;
1342 static void wrap_in_html(struct strbuf
*msg
)
1344 struct strbuf buf
= STRBUF_INIT
;
1345 static char *content_type
= "Content-Type: text/html;\n";
1346 static char *pre_open
= "<pre>\n";
1347 static char *pre_close
= "</pre>\n";
1348 const char *body
= strstr(msg
->buf
, "\n\n");
1351 return; /* Headers but no body; no wrapping needed */
1355 strbuf_add(&buf
, msg
->buf
, body
- msg
->buf
- 1);
1356 strbuf_addstr(&buf
, content_type
);
1357 strbuf_addch(&buf
, '\n');
1358 strbuf_addstr(&buf
, pre_open
);
1359 strbuf_addstr_xml_quoted(&buf
, body
);
1360 strbuf_addstr(&buf
, pre_close
);
1362 strbuf_release(msg
);
1366 #define CHUNKSIZE 0x1000
1368 static int read_message(FILE *f
, struct strbuf
*all_msgs
)
1371 if (strbuf_fread(all_msgs
, CHUNKSIZE
, f
) <= 0)
1375 return ferror(f
) ? -1 : 0;
1378 static int count_messages(struct strbuf
*all_msgs
)
1381 char *p
= all_msgs
->buf
;
1384 if (!prefixcmp(p
, "From ")) {
1385 p
= strstr(p
+5, "\nFrom: ");
1387 p
= strstr(p
+7, "\nDate: ");
1389 p
= strstr(p
+7, "\nSubject: ");
1394 p
= strstr(p
+5, "\nFrom ");
1403 * Copy the next message from all_msgs, starting at offset *ofs, to
1404 * msg. Update *ofs to the start of the following message. Return
1405 * true iff a message was successfully copied.
1407 static int split_msg(struct strbuf
*all_msgs
, struct strbuf
*msg
, int *ofs
)
1412 if (*ofs
>= all_msgs
->len
)
1415 data
= &all_msgs
->buf
[*ofs
];
1416 len
= all_msgs
->len
- *ofs
;
1418 if (len
< 5 || prefixcmp(data
, "From "))
1421 p
= strchr(data
, '\n');
1429 p
= strstr(data
, "\nFrom ");
1433 strbuf_add(msg
, data
, len
);
1438 static char *imap_folder
;
1440 static int git_imap_config(const char *key
, const char *val
, void *cb
)
1442 char imap_key
[] = "imap.";
1444 if (strncmp(key
, imap_key
, sizeof imap_key
- 1))
1447 key
+= sizeof imap_key
- 1;
1449 /* check booleans first, and barf on others */
1450 if (!strcmp("sslverify", key
))
1451 server
.ssl_verify
= git_config_bool(key
, val
);
1452 else if (!strcmp("preformattedhtml", key
))
1453 server
.use_html
= git_config_bool(key
, val
);
1455 return config_error_nonbool(key
);
1457 if (!strcmp("folder", key
)) {
1458 imap_folder
= xstrdup(val
);
1459 } else if (!strcmp("host", key
)) {
1460 if (!prefixcmp(val
, "imap:"))
1462 else if (!prefixcmp(val
, "imaps:")) {
1466 if (!prefixcmp(val
, "//"))
1468 server
.host
= xstrdup(val
);
1469 } else if (!strcmp("user", key
))
1470 server
.user
= xstrdup(val
);
1471 else if (!strcmp("pass", key
))
1472 server
.pass
= xstrdup(val
);
1473 else if (!strcmp("port", key
))
1474 server
.port
= git_config_int(key
, val
);
1475 else if (!strcmp("tunnel", key
))
1476 server
.tunnel
= xstrdup(val
);
1477 else if (!strcmp("authmethod", key
))
1478 server
.auth_method
= xstrdup(val
);
1483 int main(int argc
, char **argv
)
1485 struct strbuf all_msgs
= STRBUF_INIT
;
1486 struct msg_data msg
= {STRBUF_INIT
, 0};
1487 struct store
*ctx
= NULL
;
1493 git_extract_argv0_path(argv
[0]);
1495 git_setup_gettext();
1498 usage(imap_send_usage
);
1500 setup_git_directory_gently(&nongit_ok
);
1501 git_config(git_imap_config
, NULL
);
1504 server
.port
= server
.use_ssl
? 993 : 143;
1507 fprintf(stderr
, "no imap store specified\n");
1511 if (!server
.tunnel
) {
1512 fprintf(stderr
, "no imap host specified\n");
1515 server
.host
= "tunnel";
1518 /* read the messages */
1519 if (read_message(stdin
, &all_msgs
)) {
1520 fprintf(stderr
, "error reading input\n");
1524 if (all_msgs
.len
== 0) {
1525 fprintf(stderr
, "nothing to send\n");
1529 total
= count_messages(&all_msgs
);
1531 fprintf(stderr
, "no messages to send\n");
1535 /* write it to the imap server */
1536 ctx
= imap_open_store(&server
);
1538 fprintf(stderr
, "failed to open store\n");
1542 fprintf(stderr
, "sending %d message%s\n", total
, (total
!= 1) ? "s" : "");
1543 ctx
->name
= imap_folder
;
1545 unsigned percent
= n
* 100 / total
;
1547 fprintf(stderr
, "%4u%% (%d/%d) done\r", percent
, n
, total
);
1548 if (!split_msg(&all_msgs
, &msg
.data
, &ofs
))
1550 if (server
.use_html
)
1551 wrap_in_html(&msg
.data
);
1552 r
= imap_store_msg(ctx
, &msg
);
1557 fprintf(stderr
, "\n");
1559 imap_close_store(ctx
);