0febb56ab6601ff3eec9350708ca0cbc291cce24
[dcpomatic.git] / src / lib / emailer.cc
1 /*
2     Copyright (C) 2015 Carl Hetherington <cth@carlh.net>
3
4     This program is free software; you can redistribute it and/or modify
5     it under the terms of the GNU General Public License as published by
6     the Free Software Foundation; either version 2 of the License, or
7     (at your option) any later version.
8
9     This program is distributed in the hope that it will be useful,
10     but WITHOUT ANY WARRANTY; without even the implied warranty of
11     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12     GNU General Public License for more details.
13
14     You should have received a copy of the GNU General Public License
15     along with this program; if not, write to the Free Software
16     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17
18 */
19
20 #include "compose.hpp"
21 #include "job.h"
22 #include "data.h"
23 #include "config.h"
24 #include "emailer.h"
25 #include "exceptions.h"
26 #include <curl/curl.h>
27 #include <boost/algorithm/string.hpp>
28 #include <boost/date_time/c_local_time_adjustor.hpp>
29 #include <boost/foreach.hpp>
30
31 #include "i18n.h"
32
33 using std::string;
34 using std::stringstream;
35 using std::min;
36 using std::list;
37 using std::cout;
38 using std::pair;
39 using boost::shared_ptr;
40
41 Emailer::Emailer (string from, string to, string subject, string body)
42         : _from (from)
43         , _to (to)
44         , _subject (subject)
45         , _body (body)
46         , _offset (0)
47 {
48         boost::algorithm::replace_all (_body, "\n", "\r\n");
49 }
50
51 void
52 Emailer::add_cc (string cc)
53 {
54         _cc.push_back (cc);
55 }
56
57 void
58 Emailer::add_bcc (string bcc)
59 {
60         _bcc.push_back (bcc);
61 }
62
63 void
64 Emailer::add_attachment (boost::filesystem::path attachment, string mime_type)
65 {
66         _attachments.push_back (make_pair (attachment, mime_type));
67 }
68
69 static size_t
70 curl_data_shim (void* ptr, size_t size, size_t nmemb, void* userp)
71 {
72         return reinterpret_cast<Emailer*>(userp)->get_data (ptr, size, nmemb);
73 }
74
75 size_t
76 Emailer::get_data (void* ptr, size_t size, size_t nmemb)
77 {
78         size_t const t = min (_email.length() - _offset, size * nmemb);
79         memcpy (ptr, _email.substr(_offset, size * nmemb).c_str(), size * nmemb);
80         _offset += t;
81         return t;
82 }
83
84 void
85 Emailer::send (shared_ptr<Job> job)
86 {
87         char date_buffer[32];
88         time_t now = time (0);
89         strftime (date_buffer, sizeof(date_buffer), "%a, %d %b %Y %H:%M:%S ", localtime (&now));
90
91         boost::posix_time::ptime const utc_now = boost::posix_time::second_clock::universal_time ();
92         boost::posix_time::ptime const local_now = boost::date_time::c_local_adjustor<boost::posix_time::ptime>::utc_to_local (utc_now);
93         boost::posix_time::time_duration offset = local_now - utc_now;
94         sprintf (date_buffer + strlen(date_buffer), "%s%02d%02d", (offset.hours() >= 0 ? "+" : "-"), abs (offset.hours()), offset.minutes());
95
96         stringstream email;
97
98         email << "Date: " << date_buffer << "\r\n"
99               << "To: " << _to << "\r\n"
100               << "From: " << _from << "\r\n";
101
102         if (!_cc.empty ()) {
103                 email << "Cc: " << address_list (_cc);
104         }
105
106         if (!_bcc.empty ()) {
107                 email << "Bcc: " << address_list (_bcc);
108         }
109
110         string const chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
111         string boundary;
112         for (int i = 0; i < 32; ++i) {
113                 boundary += chars[rand() % chars.length()];
114         }
115
116         if (!_attachments.empty ()) {
117                 email << "MIME-Version: 1.0\r\n"
118                       << "Content-Type: multipart/alternative; boundary=" << boundary << "\r\n";
119         }
120
121         email << "Subject: " << _subject << "\r\n"
122               << "User-Agent: DCP-o-matic\r\n"
123               << "\r\n";
124
125         if (!_attachments.empty ()) {
126                 email << "--" << boundary << "\r\n"
127                       << "Content-Type: text/plain; charset=utf-8\r\n\r\n";
128         }
129
130         email << _body;
131
132         for (list<pair<boost::filesystem::path, string> >::const_iterator i = _attachments.begin(); i != _attachments.end(); ++i) {
133                 email << "\r\n\r\n--" << boundary << "\r\n"
134                       << "Content-Type: " << i->second << "; name=" << i->first.leaf() << "\r\n"
135                       << "Content-Transfer-Encoding: Base64\r\n"
136                       << "Content-Disposition: attachment; filename=" << i->first.leaf() << "\r\n\r\n";
137
138                 BIO* b64 = BIO_new (BIO_f_base64());
139
140                 BIO* bio = BIO_new (BIO_s_mem());
141                 bio = BIO_push (b64, bio);
142
143                 Data data (i->first);
144                 BIO_write (bio, data.data().get(), data.size());
145                 (void) BIO_flush (bio);
146
147                 char* out;
148                 long int bytes = BIO_get_mem_data (bio, &out);
149                 email << string (out, bytes);
150
151                 BIO_free_all (b64);
152         }
153
154         if (!_attachments.empty ()) {
155                 email << "\r\n--" << boundary << "--\r\n";
156         }
157
158         _email = email.str ();
159
160         curl_global_init (CURL_GLOBAL_DEFAULT);
161
162         CURL* curl = curl_easy_init ();
163         if (!curl) {
164                 throw NetworkError ("Could not initialise libcurl");
165         }
166
167         CURLM* mcurl = curl_multi_init ();
168         if (!mcurl) {
169                 throw NetworkError ("Could not initialise libcurl");
170         }
171
172         curl_easy_setopt (curl, CURLOPT_URL, String::compose (
173                                   "smtp://%1:%2",
174                                   Config::instance()->mail_server().c_str(),
175                                   Config::instance()->mail_port()
176                                   ).c_str());
177
178         if (!Config::instance()->mail_user().empty ()) {
179                 curl_easy_setopt (curl, CURLOPT_USERNAME, Config::instance()->mail_user().c_str());
180         }
181         if (!Config::instance()->mail_password().empty ()) {
182                 curl_easy_setopt (curl, CURLOPT_PASSWORD, Config::instance()->mail_password().c_str());
183         }
184
185         curl_easy_setopt (curl, CURLOPT_MAIL_FROM, _from.c_str());
186
187         struct curl_slist* recipients = curl_slist_append (0, _to.c_str());
188         BOOST_FOREACH (string i, _cc) {
189                 recipients = curl_slist_append (recipients, i.c_str());
190         }
191         BOOST_FOREACH (string i, _bcc) {
192                 recipients = curl_slist_append (recipients, i.c_str());
193         }
194
195         curl_easy_setopt (curl, CURLOPT_MAIL_RCPT, recipients);
196
197         curl_easy_setopt (curl, CURLOPT_READFUNCTION, curl_data_shim);
198         curl_easy_setopt (curl, CURLOPT_READDATA, this);
199         curl_easy_setopt (curl, CURLOPT_UPLOAD, 1L);
200
201         curl_easy_setopt (curl, CURLOPT_USE_SSL, (long) CURLUSESSL_TRY);
202         curl_easy_setopt (curl, CURLOPT_SSL_VERIFYPEER, 0L);
203         curl_easy_setopt (curl, CURLOPT_SSL_VERIFYHOST, 0L);
204         curl_easy_setopt (curl, CURLOPT_VERBOSE, 1L);
205
206         _notes_buffer.reset (new char[65536]);
207         FILE* notes = fmemopen (_notes_buffer.get(), 65536, "w");
208         curl_easy_setopt (curl, CURLOPT_STDERR, notes);
209
210         curl_multi_add_handle (mcurl, curl);
211
212         time_t start = time (0);
213
214         int still_running = 1;
215         curl_multi_perform (mcurl, &still_running);
216
217         while (still_running) {
218
219                 fd_set fdread;
220                 fd_set fdwrite;
221                 fd_set fdexcep;
222
223                 FD_ZERO (&fdread);
224                 FD_ZERO (&fdwrite);
225                 FD_ZERO (&fdexcep);
226
227                 struct timeval timeout;
228                 timeout.tv_sec = 1;
229                 timeout.tv_usec = 0;
230
231                 long curl_timeout = -1;
232                 curl_multi_timeout (mcurl, &curl_timeout);
233                 if (curl_timeout >= 0) {
234                         timeout.tv_sec = curl_timeout / 1000;
235                         if (timeout.tv_sec > 1) {
236                                 timeout.tv_sec = 1;
237                         } else {
238                                 timeout.tv_usec = (curl_timeout % 1000) * 1000;
239                         }
240                 }
241
242                 int maxfd = -1;
243                 CURLMcode mc = curl_multi_fdset (mcurl, &fdread, &fdwrite, &fdexcep, &maxfd);
244
245                 if (mc != CURLM_OK) {
246                         fclose (notes);
247                         throw KDMError (String::compose ("Failed to send KDM email to %1", _to));
248                 }
249
250                 int rc;
251                 if (maxfd == -1) {
252 #ifdef DCPOMATIC_WINDOWS
253                         Sleep (100);
254                         rc = 0;
255 #else
256                         struct timeval wait = { 0, 100 * 1000};
257                         rc = select (0, 0, 0, 0, &wait);
258 #endif
259                 } else {
260                         rc = select (maxfd + 1, &fdread, &fdwrite, &fdexcep, &timeout);
261                 }
262
263                 if (rc < 0) {
264                         throw KDMError ("Failed to send KDM email");
265                 }
266
267                 mc = curl_multi_perform (mcurl, &still_running);
268                 if (mc != CURLM_OK) {
269                         fclose (notes);
270                         throw KDMError (String::compose ("Failed to send KDM email (%1)", curl_multi_strerror (mc)));
271                 }
272
273                 if (job) {
274                         job->set_progress_unknown ();
275                 }
276
277                 if ((time(0) - start) > 10) {
278                         fclose (notes);
279                         throw KDMError (_("Failed to send KDM email (timed out)"));
280                 }
281         }
282
283         int messages;
284         do {
285                 CURLMsg* m = curl_multi_info_read (mcurl, &messages);
286                 if (m && m->data.result != CURLE_OK) {
287                         fclose (notes);
288                         throw KDMError (String::compose ("Failed to send KDM email (%1)", curl_easy_strerror (m->data.result)));
289                 }
290         } while (messages > 0);
291
292         /* XXX: we should do this stuff when an exception is thrown, but curl_multi_remove_handle
293            seems to hang if we try that.
294         */
295
296         curl_slist_free_all (recipients);
297         curl_multi_remove_handle (mcurl, curl);
298         curl_multi_cleanup (mcurl);
299         curl_easy_cleanup (curl);
300         curl_global_cleanup ();
301
302         fclose (notes);
303 }
304
305 string
306 Emailer::address_list (list<string> addresses)
307 {
308         string o;
309         BOOST_FOREACH (string i, addresses) {
310                 o += i + ", ";
311         }
312
313         return o.substr (0, o.length() - 2);
314 }
315
316 string
317 Emailer::notes () const
318 {
319         return string (_notes_buffer.get());
320 }