532319527c463408a4b55d0b01980c54b5746426
[apps/madmutt.git] / send_smtp.c
1 /*
2  * Copyright notice from original mutt:
3  * [none]
4  *
5  * Parts were written/modified by:
6  * Christian Gall <cg@cgall.de>
7  * Rocco Rutte <pdmef@cs.tu-berlin.de>
8  *
9  * This file is part of mutt-ng, see http://www.muttng.org/.
10  * It's licensed under the GNU General Public License,
11  * please see the file GPL in the top level source directory.
12  */
13
14 #include <lib-lib/lib-lib.h>
15
16 #if defined(HAVE_GNUTLS_OPENSSL_H)
17 #include <openssl/ssl.h>
18 #endif
19
20 #include <auth-client.h>
21 #include <libesmtp.h>
22
23 #include <lib-ui/enter.h>
24 #include <lib-ui/curses.h>
25 #include "mutt.h"
26 #include "send_smtp.h"
27
28 static char authpass[STRING] = "";
29
30 #define FAIL() \
31   do { \
32     ret = -1; \
33     goto Done; \
34   } while (0)
35 #define MSGFAIL(msg) \
36   do { \
37     mutt_error("%s", msg); \
38     FAIL(); \
39   } while (0)
40 #define LIBCFAIL(msg) \
41   do { \
42     mutt_error("%s: %s", msg, strerror(errno)); \
43     FAIL(); \
44   } while (0)
45 #define SMTPFAIL(msg) \
46   do { \
47     _send_smtp_perror(msg); \
48     FAIL(); \
49   } while (0)
50 #define extna(msg) { mutt_error (_("SMTP Extension '%s' not supported by MTA."), \
51                                  msg); sleep (1); }
52
53 /*
54  * _send_smtp_ensure_init
55  *   Make sure the libESMTP support in mutt is initialized at some time.
56  */
57 static void _send_smtp_ensure_init ()
58 {
59   static int libesmtp_init = 0;
60
61   if (!libesmtp_init) {
62     if (SmtpAuthUser)
63       auth_client_init ();
64     libesmtp_init = 1;
65   }
66 }
67
68 /*
69  * _send_smtp_perror
70  *   Prints 'msg', a colon, and then a string representation of the
71  *   libesmtp errno as a mutt error.
72  */
73 static void _send_smtp_perror (const char *msg)
74 {
75   char buf[512];
76
77   mutt_error ("%s: %s", msg,
78               smtp_strerror (smtp_errno (), buf, sizeof (buf)));
79 }
80
81 /*
82  * _send_smtp_add_recipients
83  *   Adds every address in 'addr' as a recipient to the smtp message
84  *   'message'.  Note that this does not mean that they will necessarily
85  *   show up in the mail headers (e.g., when bcc'ing).  Returns 0 upon
86  *   success, -1 upon failure (and prints an error message).
87  *
88  *   Very similar to sendlib.c::add_args
89  */
90 static int
91 _send_smtp_add_recipients (smtp_message_t message, address_t * addr)
92 {
93   int ret = 0;
94
95   for (; addr; addr = addr->next) {
96     /* weed out group mailboxes, since those are for display only */
97     if (addr->mailbox && !addr->group) {
98       if (!smtp_add_recipient (message, addr->mailbox))
99         SMTPFAIL ("smtp_add_recipient");
100     }
101   }
102
103 Done:
104   return ret;
105 }
106
107 static int
108 _send_smtp_auth_interact (auth_client_request_t request,
109                               char **result, int fields,
110                               void *arg __attribute__ ((unused)))
111 {
112   int i;
113
114   for (i = 0; i < fields; i++) {
115     if (request[i].flags & AUTH_USER) {
116       result[i] = SmtpAuthUser;
117     } else if (request[i].flags & AUTH_PASS) {
118       if (SmtpAuthPass) {
119         result[i] = SmtpAuthPass;
120       } else {
121         if (authpass[0] == '\0') {
122           char prompt[STRING];
123
124           snprintf(prompt, sizeof(prompt), "%s%s: ", request[i].prompt,
125                    request[i].flags & AUTH_CLEARTEXT ? " (not encrypted)" :
126                    "");
127           mutt_get_field_unbuffered(prompt, authpass, sizeof(authpass),
128                                     M_PASS);
129         }
130         result[i] = authpass;
131       }
132     }
133   }
134
135   return 1;
136 }
137
138 #define BUFLEN 8192
139
140 static const char *
141 _send_smtp_messagefp_cb(void **buf, int *len, void *arg)
142 {
143   int octets;
144
145   if (*buf == NULL)
146     *buf = xmalloc(BUFLEN);
147
148   if (len == NULL) {
149     rewind ((FILE *) arg);
150     return NULL;
151   }
152
153   if (fgets (*buf, BUFLEN - 2, (FILE *) arg) == NULL) {
154     octets = 0;
155   }
156   else {
157     char *p = strchr (*buf, '\0');
158
159     if (p[-1] == '\n' && p[-2] != '\r') {
160       m_strcpy(p - 1, (char *) *buf + BUFLEN - p + 1, "\r\n");
161       p++;
162     }
163     octets = p - (char *) *buf;
164   }
165
166   *len = octets;
167   return *buf;
168 }
169
170 static int handle_invalid_peer_certificate (long vfy_result) {
171 #if defined (HAVE_GNUTLS_OPENSSL_H)
172   mutt_error (_("Error verifying certificate: %s"),
173               NONULL (X509_verify_cert_error_string (vfy_result)));
174 #else
175   mutt_error (_("Error verifying certificate. Error Code: %lu"), vfy_result);
176 #endif
177   sleep(2);
178   return 1; /* Accept the problem */
179 }
180
181 static void event_cb (smtp_session_t session __attribute__ ((unused)),
182                       int event_no, void *arg,...)
183
184   va_list alist;
185   int *ok;
186
187   va_start(alist, arg);
188   switch(event_no) {
189   case SMTP_EV_CONNECT:
190   case SMTP_EV_MAILSTATUS:
191   case SMTP_EV_RCPTSTATUS:
192   case SMTP_EV_MESSAGEDATA:
193   case SMTP_EV_MESSAGESENT:
194   case SMTP_EV_DISCONNECT: break;
195   case SMTP_EV_WEAK_CIPHER: {
196     int bits;
197     bits = va_arg(alist, long); ok = va_arg(alist, int*);
198     mutt_message (_("SMTP_EV_WEAK_CIPHER, bits=%d - accepted."), bits);
199     sleep(1);
200     *ok = 1; break;
201   } 
202   case SMTP_EV_STARTTLS_OK:
203     mutt_message (_("Using TLS"));
204     sleep(1);
205     break;
206   case SMTP_EV_INVALID_PEER_CERTIFICATE: {
207     long vfy_result;
208     vfy_result = va_arg(alist, long); ok = va_arg(alist, int*);
209     *ok = handle_invalid_peer_certificate(vfy_result);
210     sleep(1);
211     break;
212   } 
213   case SMTP_EV_NO_PEER_CERTIFICATE: {
214     ok = va_arg(alist, int*); 
215     mutt_message (_("SMTP_EV_NO_PEER_CERTIFICATE - accepted."));
216     sleep(1);
217     *ok = 1; break;
218   }
219   case SMTP_EV_WRONG_PEER_CERTIFICATE: {
220     ok = va_arg(alist, int*);
221     mutt_message (_("SMTP_EV_WRONG_PEER_CERTIFICATE - accepted."));
222     sleep(1);
223     *ok = 1; break;
224   }
225   case SMTP_EV_NO_CLIENT_CERTIFICATE: {
226     ok = va_arg(alist, int*);
227     mutt_message (_("SMTP_EV_NO_CLIENT_CERTIFICATE - accepted."));
228     sleep(1);
229     *ok = 1; break;
230   }
231   case SMTP_EV_EXTNA_DSN:
232     extna ("DSN");
233     break;
234   case SMTP_EV_EXTNA_STARTTLS:
235     extna ("StartTLS");
236     break;
237   case SMTP_EV_EXTNA_8BITMIME:
238     extna ("8BITMIME");
239     break;
240   default:
241     mutt_message(_("Got unhandled event ID = %d - ignored."), event_no);
242     sleep(1);
243   }
244   va_end(alist);
245 }
246
247 static void do_dsn_notify (smtp_message_t message, const char* from) {
248   int flags = Notify_NOTSET;
249   smtp_recipient_t self = NULL;
250
251   if (m_strisempty(MTransport.dsn_notify) || !message || m_strisempty(from) || 
252       strstr (MTransport.dsn_notify, "never") != NULL)
253     return;
254
255   if (strstr (MTransport.dsn_notify, "failure") != NULL)
256     flags |= Notify_FAILURE;
257   if (strstr (MTransport.dsn_notify, "delay") != NULL)
258     flags |= Notify_DELAY;
259   if (strstr (MTransport.dsn_notify, "success") != NULL)
260     flags |= Notify_SUCCESS;
261
262   if (flags != Notify_NOTSET) {
263     if (!(self = smtp_add_recipient (message, from)))
264       return;
265     smtp_dsn_set_notify (self, flags);
266   }
267 }
268
269 static void do_dsn_ret (smtp_message_t message) {
270   if (m_strisempty(MTransport.dsn_return) || !message)
271     return;
272   if (ascii_strncasecmp (MTransport.dsn_return, "hdrs", 4) == 0)
273     smtp_dsn_set_ret (message, Ret_HDRS);
274   else if (ascii_strncasecmp (MTransport.dsn_return, "full", 4) == 0)
275     smtp_dsn_set_ret (message, Ret_FULL);
276 }
277
278 #ifdef USE_LIBESMTP
279 int send_smtp_check_usetls (const char* option, unsigned long p,
280                                 char* errbuf, ssize_t errlen) {
281   char* val = (char*) p;
282   if (m_strisempty(val))
283     return (1);
284   if (m_strncmp(val, "enabled", 7) != 0 &&
285       m_strncmp(val, "required", 8) != 0) {
286     if (errbuf)
287       snprintf (errbuf, errlen, _("'%s' is invalid for %s"), val, option);
288     return (0);
289   }
290   return (1);
291 }
292 #endif
293
294 /*
295  * send_smtp_invoke
296  *   Sends a mail message to the provided recipients using libesmtp.
297  *   Returns 0 upon success, -1 upon failure (and prints an error
298  *   message).
299  */
300 int send_smtp_invoke (address_t * from,       /* the sender */
301                           address_t * to, address_t * cc, address_t * bcc,    /* recips */
302                           const char *msg,      /* file containing message */
303                           int eightbit)
304 {                               /* message contains 8bit chars */
305   int ret = 0;                  /* return value, default = success */
306   smtp_session_t session;
307   smtp_message_t message;
308   char *hostportstr = NULL;
309   size_t hostportlen;
310   FILE *fp = NULL;
311   auth_context_t authctx = NULL;
312   const smtp_status_t *status;
313   char* envfrom = from->mailbox;
314
315   _send_smtp_ensure_init ();
316
317   if ((session = smtp_create_session ()) == NULL)
318     SMTPFAIL ("smtp_create_session");
319
320 #ifdef HAVE_GNUTLS_OPENSSL_H
321   if (SmtpUseTLS != NULL && ascii_strncasecmp("enabled", SmtpUseTLS, 7) == 0) {
322     smtp_starttls_enable(session, Starttls_ENABLED);
323   } else if (SmtpUseTLS != NULL && ascii_strncasecmp("required", SmtpUseTLS, 8) == 0) {
324     smtp_starttls_enable(session, Starttls_REQUIRED);
325   }
326 #endif
327
328   /* Create hostname:port string and tell libesmtp */
329   /* len = SmtpHost len + colon + max port (65536 => 5 chars) + terminator */
330   hostportlen = m_strlen(SmtpHost) + 7;
331   hostportstr = p_new(char, hostportlen);
332   snprintf (hostportstr, hostportlen, "%s:%d", SmtpHost, SmtpPort);
333   if (!smtp_set_server (session, hostportstr))
334     SMTPFAIL ("smtp_set_server");
335
336   if (SmtpAuthUser) {
337     if ((authctx = auth_create_context ()) == NULL)
338       MSGFAIL ("auth_create_context failed");
339     auth_set_mechanism_flags (authctx, AUTH_PLUGIN_PLAIN, 0);
340     auth_set_interact_cb (authctx, _send_smtp_auth_interact, NULL);
341
342     if (!smtp_auth_set_context (session, authctx))
343       SMTPFAIL ("smtp_auth_set_context");
344   }
345
346 #ifdef HAVE_GNUTLS_OPENSSL_H
347   smtp_starttls_set_ctx (session, NULL);
348 #endif
349   smtp_set_eventcb (session, event_cb, NULL);
350
351   if ((message = smtp_add_message (session)) == NULL)
352     SMTPFAIL ("smtp_add_message");
353
354   /*  Initialize envelope sender */
355   if (MTransport.use_envelope_from && MTransport.envelope_from_address)
356     envfrom = MTransport.envelope_from_address->mailbox;
357   if (!smtp_set_reverse_path (message, envfrom))
358     SMTPFAIL ("smtp_set_reverse_path");
359
360   /* set up DSN for message */
361   do_dsn_notify (message, envfrom);
362   do_dsn_ret (message);
363
364   /* set up 8bitmime flag */
365   if (eightbit && MTransport.use_8bitmime)
366     smtp_8bitmime_set_body (message, E8bitmime_8BITMIME);
367
368   if ((fp = fopen (msg, "r")) == NULL)
369     LIBCFAIL ("fopen");
370   if (!smtp_set_messagecb (message, _send_smtp_messagefp_cb, fp))
371     SMTPFAIL ("smtp_set_messagecb");
372   if (_send_smtp_add_recipients (message, to))
373     FAIL ();
374   if (_send_smtp_add_recipients (message, cc))
375     FAIL ();
376   if (_send_smtp_add_recipients (message, bcc))
377     FAIL ();
378   if (!smtp_start_session (session))
379     SMTPFAIL ("smtp_start_session");
380
381   status = smtp_message_transfer_status (message);
382   if (status->code < 200 || status->code > 299) {
383     char buf[256];
384
385     snprintf (buf, sizeof (buf), "SMTP error while sending: %d %s",
386               status->code, status->text);
387     MSGFAIL (buf);
388   }
389
390 Done:
391   m_fclose(&fp);
392   if (hostportstr != NULL)
393     p_delete(&hostportstr);
394   if (session != NULL)
395     smtp_destroy_session (session);
396   if (authctx != NULL)
397     auth_destroy_context (authctx);
398
399   /* Forget user-entered SMTP AUTH password if send fails */
400   if (ret != 0)
401     authpass[0] = '\0';
402
403   return ret;
404 }