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 static int handle_invalid_peer_certificate (long vfy_result) {
178 #if defined (USE_SSL) || (defined (USE_GNUTLS) && defined (HAVE_GNUTLS_OPENSSL_H))
179   mutt_error (_("Error verifying certificate: %s"),
180               NONULL (X509_verify_cert_error_string (vfy_result)));
181 #else
182   mutt_error (_("Error verifying certificate. Error Code: %lu"), vfy_result);
183 #endif
184   sleep(2);
185   return 1; /* Accept the problem */
186 }
187
188 static void event_cb (smtp_session_t session, int event_no, void *arg,...)
189
190   va_list alist;
191   int *ok;
192
193   va_start(alist, arg);
194   switch(event_no) {
195   case SMTP_EV_CONNECT:
196   case SMTP_EV_MAILSTATUS:
197   case SMTP_EV_RCPTSTATUS:
198   case SMTP_EV_MESSAGEDATA:
199   case SMTP_EV_MESSAGESENT:
200   case SMTP_EV_DISCONNECT: break;
201   case SMTP_EV_WEAK_CIPHER: {
202     int bits;
203     bits = va_arg(alist, long); ok = va_arg(alist, int*);
204     mutt_message (_("SMTP_EV_WEAK_CIPHER, bits=%d - accepted."), bits);
205     sleep(1);
206     *ok = 1; break;
207   } 
208   case SMTP_EV_STARTTLS_OK:
209     mutt_message (_("Using TLS"));
210     sleep(1);
211     break;
212   case SMTP_EV_INVALID_PEER_CERTIFICATE: {
213     long vfy_result;
214     vfy_result = va_arg(alist, long); ok = va_arg(alist, int*);
215     *ok = handle_invalid_peer_certificate(vfy_result);
216     sleep(1);
217     break;
218   } 
219   case SMTP_EV_NO_PEER_CERTIFICATE: {
220     ok = va_arg(alist, int*); 
221     mutt_message (_("SMTP_EV_NO_PEER_CERTIFICATE - accepted."));
222     sleep(1);
223     *ok = 1; break;
224   }
225   case SMTP_EV_WRONG_PEER_CERTIFICATE: {
226     ok = va_arg(alist, int*);
227     mutt_message (_("SMTP_EV_WRONG_PEER_CERTIFICATE - accepted."));
228     sleep(1);
229     *ok = 1; break;
230   }
231   case SMTP_EV_NO_CLIENT_CERTIFICATE: {
232     ok = va_arg(alist, int*);
233     mutt_message (_("SMTP_EV_NO_CLIENT_CERTIFICATE - accepted."));
234     sleep(1);
235     *ok = 1; break;
236   }
237   case SMTP_EV_EXTNA_DSN:
238     extna ("DSN");
239     break;
240   case SMTP_EV_EXTNA_STARTTLS:
241     extna ("StartTLS");
242     break;
243   case SMTP_EV_EXTNA_8BITMIME:
244     extna ("8BITMIME");
245     break;
246   default:
247     mutt_message(_("Got unhandled event ID = %d - ignored."), event_no);
248     sleep(1);
249   }
250   va_end(alist);
251 }
252
253 static void do_dsn_notify (smtp_message_t message, const char* from) {
254   int flags = Notify_NOTSET;
255   smtp_recipient_t self = NULL;
256
257   if (!DsnNotify || !*DsnNotify || !message || !from || !*from || 
258       strstr (DsnNotify, "never") != NULL)
259     return;
260
261   if (strstr (DsnNotify, "failure") != NULL)
262     flags |= Notify_FAILURE;
263   if (strstr (DsnNotify, "delay") != NULL)
264     flags |= Notify_DELAY;
265   if (strstr (DsnNotify, "success") != NULL)
266     flags |= Notify_SUCCESS;
267
268   if (flags != Notify_NOTSET) {
269     if (!(self = smtp_add_recipient (message, from)))
270       return;
271     smtp_dsn_set_notify (self, flags);
272   }
273 }
274
275 static void do_dsn_ret (smtp_message_t message) {
276   if (!DsnReturn || !*DsnReturn || !message)
277     return;
278   if (ascii_strncasecmp (DsnReturn, "hdrs", 4) == 0)
279     smtp_dsn_set_ret (message, Ret_HDRS);
280   else if (ascii_strncasecmp (DsnReturn, "full", 4) == 0)
281     smtp_dsn_set_ret (message, Ret_FULL);
282 }
283
284 #if defined (USE_LIBESMTP) && (defined (USE_SSL) || defined (USE_GNUTLS))
285 int mutt_libesmtp_check_usetls (const char* option, unsigned long p,
286                                 char* errbuf, size_t errlen) {
287   char* val = (char*) p;
288   if (!val || !*val)
289     return (1);
290   if (str_ncmp (val, "enabled", 7) != 0 &&
291       str_ncmp (val, "required", 8) != 0) {
292     if (errbuf)
293       snprintf (errbuf, errlen, _("'%s' is invalid for %s"), val, option);
294     return (0);
295   }
296   return (1);
297 }
298 #endif
299
300 /*
301  * mutt_libesmtp_invoke
302  *   Sends a mail message to the provided recipients using libesmtp.
303  *   Returns 0 upon success, -1 upon failure (and prints an error
304  *   message).
305  */
306 int mutt_libesmtp_invoke (ADDRESS * from,       /* the sender */
307                           ADDRESS * to, ADDRESS * cc, ADDRESS * bcc,    /* recips */
308                           const char *msg,      /* file containing message */
309                           int eightbit)
310 {                               /* message contains 8bit chars */
311   int ret = 0;                  /* return value, default = success */
312   smtp_session_t session;
313   smtp_message_t message;
314   char *hostportstr = NULL;
315   size_t hostportlen;
316   FILE *fp = NULL;
317   auth_context_t authctx = NULL;
318   const smtp_status_t *status;
319   char* envfrom = from->mailbox;
320
321   _mutt_libesmtp_ensure_init ();
322
323   if ((session = smtp_create_session ()) == NULL)
324     SMTPFAIL ("smtp_create_session");
325
326 #if defined (USE_SSL) || (defined (USE_GNUTLS) && defined (HAVE_GNUTLS_OPENSSL_H))
327   if (SmtpUseTLS != NULL && ascii_strncasecmp("enabled", SmtpUseTLS, 7) == 0) {
328     smtp_starttls_enable(session, Starttls_ENABLED);
329   } else if (SmtpUseTLS != NULL && ascii_strncasecmp("required", SmtpUseTLS, 8) == 0) {
330     smtp_starttls_enable(session, Starttls_REQUIRED);
331   }
332 #endif
333
334   /* Create hostname:port string and tell libesmtp */
335   /* len = SmtpHost len + colon + max port (65536 => 5 chars) + terminator */
336   hostportlen = str_len (SmtpHost) + 7;
337   hostportstr = mem_malloc (hostportlen);
338   snprintf (hostportstr, hostportlen, "%s:%d", SmtpHost, SmtpPort);
339   if (!smtp_set_server (session, hostportstr))
340     SMTPFAIL ("smtp_set_server");
341
342   if (SmtpAuthUser) {
343     if ((authctx = auth_create_context ()) == NULL)
344       MSGFAIL ("auth_create_context failed");
345     auth_set_mechanism_flags (authctx, AUTH_PLUGIN_PLAIN, 0);
346     auth_set_interact_cb (authctx, _mutt_libesmtp_auth_interact, NULL);
347
348     if (!smtp_auth_set_context (session, authctx))
349       SMTPFAIL ("smtp_auth_set_context");
350   }
351
352 #if defined (USE_SSL) || (defined (USE_GNUTLS) && defined (HAVE_GNUTLS_OPENSSL_H))
353   smtp_starttls_set_ctx (session, NULL);
354 #endif
355   smtp_set_eventcb (session, event_cb, NULL);
356
357   if ((message = smtp_add_message (session)) == NULL)
358     SMTPFAIL ("smtp_add_message");
359
360   /*  Initialize envelope sender */
361   if (SmtpEnvFrom && *SmtpEnvFrom)
362     envfrom = SmtpEnvFrom;
363   if (!smtp_set_reverse_path (message, envfrom))
364     SMTPFAIL ("smtp_set_reverse_path");
365
366   /* set up DSN for message */
367   do_dsn_notify (message, envfrom);
368   do_dsn_ret (message);
369
370   /* set up 8bitmime flag */
371   if (eightbit && option (OPTUSE8BITMIME))
372     smtp_8bitmime_set_body (message, E8bitmime_8BITMIME);
373
374   if ((fp = fopen (msg, "r")) == NULL)
375     LIBCFAIL ("fopen");
376   if (!smtp_set_messagecb (message, _mutt_libesmtp_messagefp_cb, fp))
377     SMTPFAIL ("smtp_set_messagecb");
378   if (_mutt_libesmtp_add_recipients (message, to))
379     FAIL ();
380   if (_mutt_libesmtp_add_recipients (message, cc))
381     FAIL ();
382   if (_mutt_libesmtp_add_recipients (message, bcc))
383     FAIL ();
384   if (!smtp_start_session (session))
385     SMTPFAIL ("smtp_start_session");
386
387   status = smtp_message_transfer_status (message);
388   if (status->code < 200 || status->code > 299) {
389     char buf[256];
390
391     snprintf (buf, sizeof (buf), "SMTP error while sending: %d %s",
392               status->code, status->text);
393     MSGFAIL (buf);
394   }
395
396 Done:
397   if (fp != NULL)
398     fclose (fp);
399   if (hostportstr != NULL)
400     free (hostportstr);
401   if (session != NULL)
402     smtp_destroy_session (session);
403   if (authctx != NULL)
404     auth_destroy_context (authctx);
405
406   /* Forget user-entered SMTP AUTH password if send fails */
407   if (ret != 0)
408     authpass[0] = '\0';
409
410   return ret;
411 }