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