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