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>
36 /* For message->status */
37 #define M_RECENT (1<<0) /* unsyncable flag; maildir_* depend on this being 1<<0 */
38 #define M_DEAD (1<<1) /* expunged */
39 #define M_FLAGS (1<<2) /* flags fetched */
43 size_t size
; /* zero implies "not fetched" */
45 unsigned char flags
, status
;
49 /* currently open mailbox */
50 const char *name
; /* foreign! maybe preset? */
52 struct message
*msgs
; /* own */
54 unsigned char opts
; /* maybe preset? */
55 /* note that the following do _not_ reflect stats from msgs, but mailbox totals */
56 int count
; /* # of messages */
57 int recent
; /* # of recent messages - don't trust this beyond the initial read */
60 static const char imap_send_usage
[] = "git imap-send < <mbox>";
64 #define DRV_MSG_BAD -1
65 #define DRV_BOX_BAD -2
66 #define DRV_STORE_BAD -3
68 static int Verbose
, Quiet
;
70 __attribute__((format (printf
, 1, 2)))
71 static void imap_info(const char *, ...);
72 __attribute__((format (printf
, 1, 2)))
73 static void imap_warn(const char *, ...);
75 static char *next_arg(char **);
77 static void free_generic_messages(struct message
*);
79 __attribute__((format (printf
, 3, 4)))
80 static int nfsnprintf(char *buf
, int blen
, const char *fmt
, ...);
82 static int nfvasprintf(char **strp
, const char *fmt
, va_list ap
)
87 len
= vsnprintf(tmp
, sizeof(tmp
), fmt
, ap
);
89 die("Fatal: Out of memory");
90 if (len
>= sizeof(tmp
))
91 die("imap command overflow!");
92 *strp
= xmemdupz(tmp
, len
);
96 struct imap_server_conf
{
109 static struct imap_server_conf server
= {
119 NULL
, /* auth_method */
122 #define NIL (void *)0x1
123 #define LIST (void *)0x2
126 struct imap_list
*next
, *child
;
137 struct imap_socket sock
;
146 int uidnext
; /* from SELECT responses */
147 struct imap_list
*ns_personal
, *ns_other
, *ns_shared
; /* NAMESPACE info */
148 unsigned caps
, rcaps
; /* CAPABILITY results */
150 int nexttag
, num_in_progress
, literal_pending
;
151 struct imap_cmd
*in_progress
, **in_progress_append
;
152 struct imap_buffer buf
; /* this is BIG, so put it last */
160 unsigned /*currentnc:1,*/ trashnc
:1;
164 int (*cont
)(struct imap_store
*ctx
, struct imap_cmd
*cmd
, const char *prompt
);
165 void (*done
)(struct imap_store
*ctx
, struct imap_cmd
*cmd
, int response
);
170 unsigned create
:1, trycreate
:1;
174 struct imap_cmd
*next
;
175 struct imap_cmd_cb cb
;
180 #define CAP(cap) (imap->caps & (1 << (cap)))
191 static const char *cap_list
[] = {
204 static int get_cmd_result(struct imap_store
*ctx
, struct imap_cmd
*tcmd
);
208 static void ssl_socket_perror(const char *func
)
210 fprintf(stderr
, "%s: %s\n", func
, ERR_error_string(ERR_get_error(), NULL
));
214 static void socket_perror(const char *func
, struct imap_socket
*sock
, int ret
)
218 int sslerr
= SSL_get_error(sock
->ssl
, ret
);
222 case SSL_ERROR_SYSCALL
:
223 perror("SSL_connect");
226 ssl_socket_perror("SSL_connect");
235 fprintf(stderr
, "%s: unexpected EOF\n", func
);
239 static int ssl_socket_connect(struct imap_socket
*sock
, int use_tls_only
, int verify
)
242 fprintf(stderr
, "SSL requested but SSL support not compiled in\n");
245 #if (OPENSSL_VERSION_NUMBER >= 0x10000000L)
246 const SSL_METHOD
*meth
;
254 SSL_load_error_strings();
257 meth
= TLSv1_method();
259 meth
= SSLv23_method();
262 ssl_socket_perror("SSLv23_method");
266 ctx
= SSL_CTX_new(meth
);
269 SSL_CTX_set_verify(ctx
, SSL_VERIFY_PEER
, NULL
);
271 if (!SSL_CTX_set_default_verify_paths(ctx
)) {
272 ssl_socket_perror("SSL_CTX_set_default_verify_paths");
275 sock
->ssl
= SSL_new(ctx
);
277 ssl_socket_perror("SSL_new");
280 if (!SSL_set_rfd(sock
->ssl
, sock
->fd
[0])) {
281 ssl_socket_perror("SSL_set_rfd");
284 if (!SSL_set_wfd(sock
->ssl
, sock
->fd
[1])) {
285 ssl_socket_perror("SSL_set_wfd");
289 ret
= SSL_connect(sock
->ssl
);
291 socket_perror("SSL_connect", sock
, ret
);
299 static int socket_read(struct imap_socket
*sock
, char *buf
, int len
)
304 n
= SSL_read(sock
->ssl
, buf
, len
);
307 n
= xread(sock
->fd
[0], buf
, len
);
309 socket_perror("read", sock
, n
);
312 sock
->fd
[0] = sock
->fd
[1] = -1;
317 static int socket_write(struct imap_socket
*sock
, const char *buf
, int len
)
322 n
= SSL_write(sock
->ssl
, buf
, len
);
325 n
= write_in_full(sock
->fd
[1], buf
, len
);
327 socket_perror("write", sock
, n
);
330 sock
->fd
[0] = sock
->fd
[1] = -1;
335 static void socket_shutdown(struct imap_socket
*sock
)
339 SSL_shutdown(sock
->ssl
);
347 /* simple line buffering */
348 static int buffer_gets(struct imap_buffer
*b
, char **s
)
351 int start
= b
->offset
;
356 /* make sure we have enough data to read the \r\n sequence */
357 if (b
->offset
+ 1 >= b
->bytes
) {
359 /* shift down used bytes */
362 assert(start
<= b
->bytes
);
363 n
= b
->bytes
- start
;
366 memmove(b
->buf
, b
->buf
+ start
, n
);
372 n
= socket_read(&b
->sock
, b
->buf
+ b
->bytes
,
373 sizeof(b
->buf
) - b
->bytes
);
381 if (b
->buf
[b
->offset
] == '\r') {
382 assert(b
->offset
+ 1 < b
->bytes
);
383 if (b
->buf
[b
->offset
+ 1] == '\n') {
384 b
->buf
[b
->offset
] = 0; /* terminate the string */
385 b
->offset
+= 2; /* next line */
397 static void imap_info(const char *msg
, ...)
409 static void imap_warn(const char *msg
, ...)
415 vfprintf(stderr
, msg
, va
);
420 static char *next_arg(char **s
)
426 while (isspace((unsigned char) **s
))
435 *s
= strchr(*s
, '"');
438 while (**s
&& !isspace((unsigned char) **s
))
450 static void free_generic_messages(struct message
*msgs
)
452 struct message
*tmsg
;
454 for (; msgs
; msgs
= tmsg
) {
460 static int nfsnprintf(char *buf
, int blen
, const char *fmt
, ...)
466 if (blen
<= 0 || (unsigned)(ret
= vsnprintf(buf
, blen
, fmt
, va
)) >= (unsigned)blen
)
467 die("Fatal: buffer too small. Please report a bug.");
472 static struct imap_cmd
*v_issue_imap_cmd(struct imap_store
*ctx
,
473 struct imap_cmd_cb
*cb
,
474 const char *fmt
, va_list ap
)
476 struct imap
*imap
= ctx
->imap
;
477 struct imap_cmd
*cmd
;
481 cmd
= xmalloc(sizeof(struct imap_cmd
));
482 nfvasprintf(&cmd
->cmd
, fmt
, ap
);
483 cmd
->tag
= ++imap
->nexttag
;
488 memset(&cmd
->cb
, 0, sizeof(cmd
->cb
));
490 while (imap
->literal_pending
)
491 get_cmd_result(ctx
, NULL
);
494 bufl
= nfsnprintf(buf
, sizeof(buf
), "%d %s\r\n", cmd
->tag
, cmd
->cmd
);
496 bufl
= nfsnprintf(buf
, sizeof(buf
), "%d %s{%d%s}\r\n",
497 cmd
->tag
, cmd
->cmd
, cmd
->cb
.dlen
,
498 CAP(LITERALPLUS
) ? "+" : "");
501 if (imap
->num_in_progress
)
502 printf("(%d in progress) ", imap
->num_in_progress
);
503 if (memcmp(cmd
->cmd
, "LOGIN", 5))
504 printf(">>> %s", buf
);
506 printf(">>> %d LOGIN <user> <pass>\n", cmd
->tag
);
508 if (socket_write(&imap
->buf
.sock
, buf
, bufl
) != bufl
) {
516 if (CAP(LITERALPLUS
)) {
517 n
= socket_write(&imap
->buf
.sock
, cmd
->cb
.data
, cmd
->cb
.dlen
);
519 if (n
!= cmd
->cb
.dlen
||
520 socket_write(&imap
->buf
.sock
, "\r\n", 2) != 2) {
527 imap
->literal_pending
= 1;
528 } else if (cmd
->cb
.cont
)
529 imap
->literal_pending
= 1;
531 *imap
->in_progress_append
= cmd
;
532 imap
->in_progress_append
= &cmd
->next
;
533 imap
->num_in_progress
++;
537 __attribute__((format (printf
, 3, 4)))
538 static struct imap_cmd
*issue_imap_cmd(struct imap_store
*ctx
,
539 struct imap_cmd_cb
*cb
,
540 const char *fmt
, ...)
542 struct imap_cmd
*ret
;
546 ret
= v_issue_imap_cmd(ctx
, cb
, fmt
, ap
);
551 __attribute__((format (printf
, 3, 4)))
552 static int imap_exec(struct imap_store
*ctx
, struct imap_cmd_cb
*cb
,
553 const char *fmt
, ...)
556 struct imap_cmd
*cmdp
;
559 cmdp
= v_issue_imap_cmd(ctx
, cb
, fmt
, ap
);
564 return get_cmd_result(ctx
, cmdp
);
567 __attribute__((format (printf
, 3, 4)))
568 static int imap_exec_m(struct imap_store
*ctx
, struct imap_cmd_cb
*cb
,
569 const char *fmt
, ...)
572 struct imap_cmd
*cmdp
;
575 cmdp
= v_issue_imap_cmd(ctx
, cb
, fmt
, ap
);
578 return DRV_STORE_BAD
;
580 switch (get_cmd_result(ctx
, cmdp
)) {
581 case RESP_BAD
: return DRV_STORE_BAD
;
582 case RESP_NO
: return DRV_MSG_BAD
;
583 default: return DRV_OK
;
587 static int is_atom(struct imap_list
*list
)
589 return list
&& list
->val
&& list
->val
!= NIL
&& list
->val
!= LIST
;
592 static int is_list(struct imap_list
*list
)
594 return list
&& list
->val
== LIST
;
597 static void free_list(struct imap_list
*list
)
599 struct imap_list
*tmp
;
601 for (; list
; list
= tmp
) {
604 free_list(list
->child
);
605 else if (is_atom(list
))
611 static int parse_imap_list_l(struct imap
*imap
, char **sp
, struct imap_list
**curp
, int level
)
613 struct imap_list
*cur
;
618 while (isspace((unsigned char)*s
))
620 if (level
&& *s
== ')') {
624 *curp
= cur
= xmalloc(sizeof(*cur
));
626 cur
->val
= NULL
; /* for clean bail */
631 if (parse_imap_list_l(imap
, &s
, &cur
->child
, level
+ 1))
633 } else if (imap
&& *s
== '{') {
635 bytes
= cur
->len
= strtol(s
+ 1, &s
, 10);
639 s
= cur
->val
= xmalloc(cur
->len
);
641 /* dump whats left over in the input buffer */
642 n
= imap
->buf
.bytes
- imap
->buf
.offset
;
645 /* the entire message fit in the buffer */
648 memcpy(s
, imap
->buf
.buf
+ imap
->buf
.offset
, n
);
652 /* mark that we used part of the buffer */
653 imap
->buf
.offset
+= n
;
655 /* now read the rest of the message */
657 if ((n
= socket_read(&imap
->buf
.sock
, s
, bytes
)) <= 0)
663 if (buffer_gets(&imap
->buf
, &s
))
665 } else if (*s
== '"') {
669 for (; *s
!= '"'; s
++)
674 cur
->val
= xmemdupz(p
, cur
->len
);
678 for (; *s
&& !isspace((unsigned char)*s
); s
++)
679 if (level
&& *s
== ')')
682 if (cur
->len
== 3 && !memcmp("NIL", p
, 3))
685 cur
->val
= xmemdupz(p
, cur
->len
);
702 static struct imap_list
*parse_imap_list(struct imap
*imap
, char **sp
)
704 struct imap_list
*head
;
706 if (!parse_imap_list_l(imap
, sp
, &head
, 0))
712 static struct imap_list
*parse_list(char **sp
)
714 return parse_imap_list(NULL
, sp
);
717 static void parse_capability(struct imap
*imap
, char *cmd
)
722 imap
->caps
= 0x80000000;
723 while ((arg
= next_arg(&cmd
)))
724 for (i
= 0; i
< ARRAY_SIZE(cap_list
); i
++)
725 if (!strcmp(cap_list
[i
], arg
))
726 imap
->caps
|= 1 << i
;
727 imap
->rcaps
= imap
->caps
;
730 static int parse_response_code(struct imap_store
*ctx
, struct imap_cmd_cb
*cb
,
733 struct imap
*imap
= ctx
->imap
;
737 return RESP_OK
; /* no response code */
739 if (!(p
= strchr(s
, ']'))) {
740 fprintf(stderr
, "IMAP error: malformed response code\n");
745 if (!strcmp("UIDVALIDITY", arg
)) {
746 if (!(arg
= next_arg(&s
)) || !(ctx
->gen
.uidvalidity
= atoi(arg
))) {
747 fprintf(stderr
, "IMAP error: malformed UIDVALIDITY status\n");
750 } else if (!strcmp("UIDNEXT", arg
)) {
751 if (!(arg
= next_arg(&s
)) || !(imap
->uidnext
= atoi(arg
))) {
752 fprintf(stderr
, "IMAP error: malformed NEXTUID status\n");
755 } else if (!strcmp("CAPABILITY", arg
)) {
756 parse_capability(imap
, s
);
757 } else if (!strcmp("ALERT", arg
)) {
758 /* RFC2060 says that these messages MUST be displayed
761 for (; isspace((unsigned char)*p
); p
++);
762 fprintf(stderr
, "*** IMAP ALERT *** %s\n", p
);
763 } else if (cb
&& cb
->ctx
&& !strcmp("APPENDUID", arg
)) {
764 if (!(arg
= next_arg(&s
)) || !(ctx
->gen
.uidvalidity
= atoi(arg
)) ||
765 !(arg
= next_arg(&s
)) || !(*(int *)cb
->ctx
= atoi(arg
))) {
766 fprintf(stderr
, "IMAP error: malformed APPENDUID status\n");
773 static int get_cmd_result(struct imap_store
*ctx
, struct imap_cmd
*tcmd
)
775 struct imap
*imap
= ctx
->imap
;
776 struct imap_cmd
*cmdp
, **pcmdp
, *ncmdp
;
777 char *cmd
, *arg
, *arg1
, *p
;
778 int n
, resp
, resp2
, tag
;
781 if (buffer_gets(&imap
->buf
, &cmd
))
784 arg
= next_arg(&cmd
);
786 arg
= next_arg(&cmd
);
788 fprintf(stderr
, "IMAP error: unable to parse untagged response\n");
792 if (!strcmp("NAMESPACE", arg
)) {
793 imap
->ns_personal
= parse_list(&cmd
);
794 imap
->ns_other
= parse_list(&cmd
);
795 imap
->ns_shared
= parse_list(&cmd
);
796 } else if (!strcmp("OK", arg
) || !strcmp("BAD", arg
) ||
797 !strcmp("NO", arg
) || !strcmp("BYE", arg
)) {
798 if ((resp
= parse_response_code(ctx
, NULL
, cmd
)) != RESP_OK
)
800 } else if (!strcmp("CAPABILITY", arg
))
801 parse_capability(imap
, cmd
);
802 else if ((arg1
= next_arg(&cmd
))) {
803 if (!strcmp("EXISTS", arg1
))
804 ctx
->gen
.count
= atoi(arg
);
805 else if (!strcmp("RECENT", arg1
))
806 ctx
->gen
.recent
= atoi(arg
);
808 fprintf(stderr
, "IMAP error: unable to parse untagged response\n");
811 } else if (!imap
->in_progress
) {
812 fprintf(stderr
, "IMAP error: unexpected reply: %s %s\n", arg
, cmd
? cmd
: "");
814 } else if (*arg
== '+') {
815 /* This can happen only with the last command underway, as
816 it enforces a round-trip. */
817 cmdp
= (struct imap_cmd
*)((char *)imap
->in_progress_append
-
818 offsetof(struct imap_cmd
, next
));
820 n
= socket_write(&imap
->buf
.sock
, cmdp
->cb
.data
, cmdp
->cb
.dlen
);
822 cmdp
->cb
.data
= NULL
;
823 if (n
!= (int)cmdp
->cb
.dlen
)
825 } else if (cmdp
->cb
.cont
) {
826 if (cmdp
->cb
.cont(ctx
, cmdp
, cmd
))
829 fprintf(stderr
, "IMAP error: unexpected command continuation request\n");
832 if (socket_write(&imap
->buf
.sock
, "\r\n", 2) != 2)
835 imap
->literal_pending
= 0;
840 for (pcmdp
= &imap
->in_progress
; (cmdp
= *pcmdp
); pcmdp
= &cmdp
->next
)
841 if (cmdp
->tag
== tag
)
843 fprintf(stderr
, "IMAP error: unexpected tag %s\n", arg
);
846 if (!(*pcmdp
= cmdp
->next
))
847 imap
->in_progress_append
= pcmdp
;
848 imap
->num_in_progress
--;
849 if (cmdp
->cb
.cont
|| cmdp
->cb
.data
)
850 imap
->literal_pending
= 0;
851 arg
= next_arg(&cmd
);
852 if (!strcmp("OK", arg
))
855 if (!strcmp("NO", arg
)) {
856 if (cmdp
->cb
.create
&& cmd
&& (cmdp
->cb
.trycreate
|| !memcmp(cmd
, "[TRYCREATE]", 11))) { /* SELECT, APPEND or UID COPY */
857 p
= strchr(cmdp
->cmd
, '"');
858 if (!issue_imap_cmd(ctx
, NULL
, "CREATE \"%.*s\"", (int)(strchr(p
+ 1, '"') - p
+ 1), p
)) {
862 /* not waiting here violates the spec, but a server that does not
863 grok this nonetheless violates it too. */
865 if (!(ncmdp
= issue_imap_cmd(ctx
, &cmdp
->cb
, "%s", cmdp
->cmd
))) {
872 return 0; /* ignored */
878 } else /*if (!strcmp("BAD", arg))*/
880 fprintf(stderr
, "IMAP command '%s' returned response (%s) - %s\n",
881 memcmp(cmdp
->cmd
, "LOGIN", 5) ?
882 cmdp
->cmd
: "LOGIN <user> <pass>",
883 arg
, cmd
? cmd
: "");
885 if ((resp2
= parse_response_code(ctx
, &cmdp
->cb
, cmd
)) > resp
)
889 cmdp
->cb
.done(ctx
, cmdp
, resp
);
893 if (!tcmd
|| tcmd
== cmdp
)
900 static void imap_close_server(struct imap_store
*ictx
)
902 struct imap
*imap
= ictx
->imap
;
904 if (imap
->buf
.sock
.fd
[0] != -1) {
905 imap_exec(ictx
, NULL
, "LOGOUT");
906 socket_shutdown(&imap
->buf
.sock
);
908 free_list(imap
->ns_personal
);
909 free_list(imap
->ns_other
);
910 free_list(imap
->ns_shared
);
914 static void imap_close_store(struct store
*ctx
)
916 imap_close_server((struct imap_store
*)ctx
);
917 free_generic_messages(ctx
->msgs
);
924 * hexchar() and cram() functions are based on the code from the isync
925 * project (http://isync.sf.net/).
927 static char hexchar(unsigned int b
)
929 return b
< 10 ? '0' + b
: 'a' + (b
- 10);
932 #define ENCODED_SIZE(n) (4*((n+2)/3))
933 static char *cram(const char *challenge_64
, const char *user
, const char *pass
)
935 int i
, resp_len
, encoded_len
, decoded_len
;
937 unsigned char hash
[16];
939 char *response
, *response_64
, *challenge
;
942 * length of challenge_64 (i.e. base-64 encoded string) is a good
943 * enough upper bound for challenge (decoded result).
945 encoded_len
= strlen(challenge_64
);
946 challenge
= xmalloc(encoded_len
);
947 decoded_len
= EVP_DecodeBlock((unsigned char *)challenge
,
948 (unsigned char *)challenge_64
, encoded_len
);
950 die("invalid challenge %s", challenge_64
);
951 HMAC_Init(&hmac
, (unsigned char *)pass
, strlen(pass
), EVP_md5());
952 HMAC_Update(&hmac
, (unsigned char *)challenge
, decoded_len
);
953 HMAC_Final(&hmac
, hash
, NULL
);
954 HMAC_CTX_cleanup(&hmac
);
957 for (i
= 0; i
< 16; i
++) {
958 hex
[2 * i
] = hexchar((hash
[i
] >> 4) & 0xf);
959 hex
[2 * i
+ 1] = hexchar(hash
[i
] & 0xf);
962 /* response: "<user> <digest in hex>" */
963 resp_len
= strlen(user
) + 1 + strlen(hex
) + 1;
964 response
= xmalloc(resp_len
);
965 sprintf(response
, "%s %s", user
, hex
);
967 response_64
= xmalloc(ENCODED_SIZE(resp_len
) + 1);
968 encoded_len
= EVP_EncodeBlock((unsigned char *)response_64
,
969 (unsigned char *)response
, resp_len
);
971 die("EVP_EncodeBlock error");
972 response_64
[encoded_len
] = '\0';
973 return (char *)response_64
;
978 static char *cram(const char *challenge_64
, const char *user
, const char *pass
)
980 die("If you want to use CRAM-MD5 authenticate method, "
981 "you have to build git-imap-send with OpenSSL library.");
986 static int auth_cram_md5(struct imap_store
*ctx
, struct imap_cmd
*cmd
, const char *prompt
)
991 response
= cram(prompt
, server
.user
, server
.pass
);
993 ret
= socket_write(&ctx
->imap
->buf
.sock
, response
, strlen(response
));
994 if (ret
!= strlen(response
))
995 return error("IMAP error: sending response failed");
1002 static struct store
*imap_open_store(struct imap_server_conf
*srvc
)
1004 struct imap_store
*ctx
;
1007 int s
= -1, preauth
;
1009 ctx
= xcalloc(sizeof(*ctx
), 1);
1011 ctx
->imap
= imap
= xcalloc(sizeof(*imap
), 1);
1012 imap
->buf
.sock
.fd
[0] = imap
->buf
.sock
.fd
[1] = -1;
1013 imap
->in_progress_append
= &imap
->in_progress
;
1015 /* open connection to IMAP server */
1018 const char *argv
[] = { srvc
->tunnel
, NULL
};
1019 struct child_process tunnel
= {NULL
};
1021 imap_info("Starting tunnel '%s'... ", srvc
->tunnel
);
1024 tunnel
.use_shell
= 1;
1027 if (start_command(&tunnel
))
1028 die("cannot start proxy %s", argv
[0]);
1030 imap
->buf
.sock
.fd
[0] = tunnel
.out
;
1031 imap
->buf
.sock
.fd
[1] = tunnel
.in
;
1036 struct addrinfo hints
, *ai0
, *ai
;
1040 snprintf(portstr
, sizeof(portstr
), "%d", srvc
->port
);
1042 memset(&hints
, 0, sizeof(hints
));
1043 hints
.ai_socktype
= SOCK_STREAM
;
1044 hints
.ai_protocol
= IPPROTO_TCP
;
1046 imap_info("Resolving %s... ", srvc
->host
);
1047 gai
= getaddrinfo(srvc
->host
, portstr
, &hints
, &ai
);
1049 fprintf(stderr
, "getaddrinfo: %s\n", gai_strerror(gai
));
1054 for (ai0
= ai
; ai
; ai
= ai
->ai_next
) {
1055 char addr
[NI_MAXHOST
];
1057 s
= socket(ai
->ai_family
, ai
->ai_socktype
,
1062 getnameinfo(ai
->ai_addr
, ai
->ai_addrlen
, addr
,
1063 sizeof(addr
), NULL
, 0, NI_NUMERICHOST
);
1064 imap_info("Connecting to [%s]:%s... ", addr
, portstr
);
1066 if (connect(s
, ai
->ai_addr
, ai
->ai_addrlen
) < 0) {
1078 struct sockaddr_in addr
;
1080 memset(&addr
, 0, sizeof(addr
));
1081 addr
.sin_port
= htons(srvc
->port
);
1082 addr
.sin_family
= AF_INET
;
1084 imap_info("Resolving %s... ", srvc
->host
);
1085 he
= gethostbyname(srvc
->host
);
1087 perror("gethostbyname");
1092 addr
.sin_addr
.s_addr
= *((int *) he
->h_addr_list
[0]);
1094 s
= socket(PF_INET
, SOCK_STREAM
, 0);
1096 imap_info("Connecting to %s:%hu... ", inet_ntoa(addr
.sin_addr
), ntohs(addr
.sin_port
));
1097 if (connect(s
, (struct sockaddr
*)&addr
, sizeof(addr
))) {
1104 fputs("Error: unable to connect to server.\n", stderr
);
1108 imap
->buf
.sock
.fd
[0] = s
;
1109 imap
->buf
.sock
.fd
[1] = dup(s
);
1111 if (srvc
->use_ssl
&&
1112 ssl_socket_connect(&imap
->buf
.sock
, 0, srvc
->ssl_verify
)) {
1119 /* read the greeting string */
1120 if (buffer_gets(&imap
->buf
, &rsp
)) {
1121 fprintf(stderr
, "IMAP error: no greeting response\n");
1124 arg
= next_arg(&rsp
);
1125 if (!arg
|| *arg
!= '*' || (arg
= next_arg(&rsp
)) == NULL
) {
1126 fprintf(stderr
, "IMAP error: invalid greeting response\n");
1130 if (!strcmp("PREAUTH", arg
))
1132 else if (strcmp("OK", arg
) != 0) {
1133 fprintf(stderr
, "IMAP error: unknown greeting response\n");
1136 parse_response_code(ctx
, NULL
, rsp
);
1137 if (!imap
->caps
&& imap_exec(ctx
, NULL
, "CAPABILITY") != RESP_OK
)
1142 if (!srvc
->use_ssl
&& CAP(STARTTLS
)) {
1143 if (imap_exec(ctx
, NULL
, "STARTTLS") != RESP_OK
)
1145 if (ssl_socket_connect(&imap
->buf
.sock
, 1,
1148 /* capabilities may have changed, so get the new capabilities */
1149 if (imap_exec(ctx
, NULL
, "CAPABILITY") != RESP_OK
)
1153 imap_info("Logging in...\n");
1155 fprintf(stderr
, "Skipping server %s, no user\n", srvc
->host
);
1159 struct strbuf prompt
= STRBUF_INIT
;
1160 strbuf_addf(&prompt
, "Password (%s@%s): ", srvc
->user
, srvc
->host
);
1161 arg
= git_getpass(prompt
.buf
);
1162 strbuf_release(&prompt
);
1164 fprintf(stderr
, "Skipping account %s@%s, no password\n", srvc
->user
, srvc
->host
);
1168 * getpass() returns a pointer to a static buffer. make a copy
1169 * for long term storage.
1171 srvc
->pass
= xstrdup(arg
);
1174 fprintf(stderr
, "Skipping account %s@%s, server forbids LOGIN\n", srvc
->user
, srvc
->host
);
1178 if (srvc
->auth_method
) {
1179 struct imap_cmd_cb cb
;
1181 if (!strcmp(srvc
->auth_method
, "CRAM-MD5")) {
1182 if (!CAP(AUTH_CRAM_MD5
)) {
1183 fprintf(stderr
, "You specified"
1184 "CRAM-MD5 as authentication method, "
1185 "but %s doesn't support it.\n", srvc
->host
);
1190 memset(&cb
, 0, sizeof(cb
));
1191 cb
.cont
= auth_cram_md5
;
1192 if (imap_exec(ctx
, &cb
, "AUTHENTICATE CRAM-MD5") != RESP_OK
) {
1193 fprintf(stderr
, "IMAP error: AUTHENTICATE CRAM-MD5 failed\n");
1197 fprintf(stderr
, "Unknown authentication method:%s\n", srvc
->host
);
1201 if (!imap
->buf
.sock
.ssl
)
1202 imap_warn("*** IMAP Warning *** Password is being "
1203 "sent in the clear\n");
1204 if (imap_exec(ctx
, NULL
, "LOGIN \"%s\" \"%s\"", srvc
->user
, srvc
->pass
) != RESP_OK
) {
1205 fprintf(stderr
, "IMAP error: LOGIN failed\n");
1213 return (struct store
*)ctx
;
1216 imap_close_store(&ctx
->gen
);
1220 static void lf_to_crlf(struct strbuf
*msg
)
1224 int i
, j
, lfnum
= 0;
1226 if (msg
->buf
[0] == '\n')
1228 for (i
= 1; i
< msg
->len
; i
++) {
1229 if (msg
->buf
[i
- 1] != '\r' && msg
->buf
[i
] == '\n')
1233 new_len
= msg
->len
+ lfnum
;
1234 new = xmalloc(new_len
+ 1);
1235 if (msg
->buf
[0] == '\n') {
1241 new[0] = msg
->buf
[0];
1245 for ( ; i
< msg
->len
; i
++) {
1246 if (msg
->buf
[i
] != '\n') {
1247 new[j
++] = msg
->buf
[i
];
1250 if (msg
->buf
[i
- 1] != '\r')
1252 /* otherwise it already had CR before */
1255 strbuf_attach(msg
, new, new_len
, new_len
+ 1);
1259 * Store msg to IMAP. Also detach and free the data from msg->data,
1260 * leaving msg->data empty.
1262 static int imap_store_msg(struct store
*gctx
, struct strbuf
*msg
)
1264 struct imap_store
*ctx
= (struct imap_store
*)gctx
;
1265 struct imap
*imap
= ctx
->imap
;
1266 struct imap_cmd_cb cb
;
1267 const char *prefix
, *box
;
1271 memset(&cb
, 0, sizeof(cb
));
1274 cb
.data
= strbuf_detach(msg
, NULL
);
1277 prefix
= !strcmp(box
, "INBOX") ? "" : ctx
->prefix
;
1279 ret
= imap_exec_m(ctx
, &cb
, "APPEND \"%s%s\" ", prefix
, box
);
1280 imap
->caps
= imap
->rcaps
;
1288 static void wrap_in_html(struct strbuf
*msg
)
1290 struct strbuf buf
= STRBUF_INIT
;
1291 static char *content_type
= "Content-Type: text/html;\n";
1292 static char *pre_open
= "<pre>\n";
1293 static char *pre_close
= "</pre>\n";
1294 const char *body
= strstr(msg
->buf
, "\n\n");
1297 return; /* Headers but no body; no wrapping needed */
1301 strbuf_add(&buf
, msg
->buf
, body
- msg
->buf
- 1);
1302 strbuf_addstr(&buf
, content_type
);
1303 strbuf_addch(&buf
, '\n');
1304 strbuf_addstr(&buf
, pre_open
);
1305 strbuf_addstr_xml_quoted(&buf
, body
);
1306 strbuf_addstr(&buf
, pre_close
);
1308 strbuf_release(msg
);
1312 #define CHUNKSIZE 0x1000
1314 static int read_message(FILE *f
, struct strbuf
*all_msgs
)
1317 if (strbuf_fread(all_msgs
, CHUNKSIZE
, f
) <= 0)
1321 return ferror(f
) ? -1 : 0;
1324 static int count_messages(struct strbuf
*all_msgs
)
1327 char *p
= all_msgs
->buf
;
1330 if (!prefixcmp(p
, "From ")) {
1331 p
= strstr(p
+5, "\nFrom: ");
1333 p
= strstr(p
+7, "\nDate: ");
1335 p
= strstr(p
+7, "\nSubject: ");
1340 p
= strstr(p
+5, "\nFrom ");
1349 * Copy the next message from all_msgs, starting at offset *ofs, to
1350 * msg. Update *ofs to the start of the following message. Return
1351 * true iff a message was successfully copied.
1353 static int split_msg(struct strbuf
*all_msgs
, struct strbuf
*msg
, int *ofs
)
1358 if (*ofs
>= all_msgs
->len
)
1361 data
= &all_msgs
->buf
[*ofs
];
1362 len
= all_msgs
->len
- *ofs
;
1364 if (len
< 5 || prefixcmp(data
, "From "))
1367 p
= strchr(data
, '\n');
1375 p
= strstr(data
, "\nFrom ");
1379 strbuf_add(msg
, data
, len
);
1384 static char *imap_folder
;
1386 static int git_imap_config(const char *key
, const char *val
, void *cb
)
1388 char imap_key
[] = "imap.";
1390 if (strncmp(key
, imap_key
, sizeof imap_key
- 1))
1393 key
+= sizeof imap_key
- 1;
1395 /* check booleans first, and barf on others */
1396 if (!strcmp("sslverify", key
))
1397 server
.ssl_verify
= git_config_bool(key
, val
);
1398 else if (!strcmp("preformattedhtml", key
))
1399 server
.use_html
= git_config_bool(key
, val
);
1401 return config_error_nonbool(key
);
1403 if (!strcmp("folder", key
)) {
1404 imap_folder
= xstrdup(val
);
1405 } else if (!strcmp("host", key
)) {
1406 if (!prefixcmp(val
, "imap:"))
1408 else if (!prefixcmp(val
, "imaps:")) {
1412 if (!prefixcmp(val
, "//"))
1414 server
.host
= xstrdup(val
);
1415 } else if (!strcmp("user", key
))
1416 server
.user
= xstrdup(val
);
1417 else if (!strcmp("pass", key
))
1418 server
.pass
= xstrdup(val
);
1419 else if (!strcmp("port", key
))
1420 server
.port
= git_config_int(key
, val
);
1421 else if (!strcmp("tunnel", key
))
1422 server
.tunnel
= xstrdup(val
);
1423 else if (!strcmp("authmethod", key
))
1424 server
.auth_method
= xstrdup(val
);
1429 int main(int argc
, char **argv
)
1431 struct strbuf all_msgs
= STRBUF_INIT
;
1432 struct strbuf msg
= STRBUF_INIT
;
1433 struct store
*ctx
= NULL
;
1439 git_extract_argv0_path(argv
[0]);
1441 git_setup_gettext();
1444 usage(imap_send_usage
);
1446 setup_git_directory_gently(&nongit_ok
);
1447 git_config(git_imap_config
, NULL
);
1450 server
.port
= server
.use_ssl
? 993 : 143;
1453 fprintf(stderr
, "no imap store specified\n");
1457 if (!server
.tunnel
) {
1458 fprintf(stderr
, "no imap host specified\n");
1461 server
.host
= "tunnel";
1464 /* read the messages */
1465 if (read_message(stdin
, &all_msgs
)) {
1466 fprintf(stderr
, "error reading input\n");
1470 if (all_msgs
.len
== 0) {
1471 fprintf(stderr
, "nothing to send\n");
1475 total
= count_messages(&all_msgs
);
1477 fprintf(stderr
, "no messages to send\n");
1481 /* write it to the imap server */
1482 ctx
= imap_open_store(&server
);
1484 fprintf(stderr
, "failed to open store\n");
1488 fprintf(stderr
, "sending %d message%s\n", total
, (total
!= 1) ? "s" : "");
1489 ctx
->name
= imap_folder
;
1491 unsigned percent
= n
* 100 / total
;
1493 fprintf(stderr
, "%4u%% (%d/%d) done\r", percent
, n
, total
);
1494 if (!split_msg(&all_msgs
, &msg
, &ofs
))
1496 if (server
.use_html
)
1498 r
= imap_store_msg(ctx
, &msg
);
1503 fprintf(stderr
, "\n");
1505 imap_close_store(ctx
);