Allow multiple recipients of KDM emails (#745).
[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, list<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 file, string name, string mime_type)
65 {
66         Attachment a;
67         a.file = file;
68         a.name = name;
69         a.mime_type = mime_type;
70         _attachments.push_back (a);
71 }
72
73 static size_t
74 curl_data_shim (void* ptr, size_t size, size_t nmemb, void* userp)
75 {
76         return reinterpret_cast<Emailer*>(userp)->get_data (ptr, size, nmemb);
77 }
78
79 static int
80 curl_debug_shim (CURL* curl, curl_infotype type, char* data, size_t size, void* userp)
81 {
82         return reinterpret_cast<Emailer*>(userp)->debug (curl, type, data, size);
83 }
84
85 size_t
86 Emailer::get_data (void* ptr, size_t size, size_t nmemb)
87 {
88         size_t const t = min (_email.length() - _offset, size * nmemb);
89         memcpy (ptr, _email.substr(_offset, size * nmemb).c_str(), size * nmemb);
90         _offset += t;
91         return t;
92 }
93
94 void
95 Emailer::send (shared_ptr<Job> job)
96 {
97         char date_buffer[32];
98         time_t now = time (0);
99         strftime (date_buffer, sizeof(date_buffer), "%a, %d %b %Y %H:%M:%S ", localtime (&now));
100
101         boost::posix_time::ptime const utc_now = boost::posix_time::second_clock::universal_time ();
102         boost::posix_time::ptime const local_now = boost::date_time::c_local_adjustor<boost::posix_time::ptime>::utc_to_local (utc_now);
103         boost::posix_time::time_duration offset = local_now - utc_now;
104         sprintf (date_buffer + strlen(date_buffer), "%s%02d%02d", (offset.hours() >= 0 ? "+" : "-"), abs (offset.hours()), offset.minutes());
105
106         stringstream email;
107
108         email << "Date: " << date_buffer << "\r\n"
109               << "To: " << address_list (_to) << "\r\n"
110               << "From: " << _from << "\r\n";
111
112         if (!_cc.empty ()) {
113                 email << "Cc: " << address_list (_cc);
114         }
115
116         if (!_bcc.empty ()) {
117                 email << "Bcc: " << address_list (_bcc);
118         }
119
120         string const chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
121         string boundary;
122         for (int i = 0; i < 32; ++i) {
123                 boundary += chars[rand() % chars.length()];
124         }
125
126         if (!_attachments.empty ()) {
127                 email << "MIME-Version: 1.0\r\n"
128                       << "Content-Type: multipart/mixed; boundary=" << boundary << "\r\n";
129         }
130
131         email << "Subject: " << _subject << "\r\n"
132               << "User-Agent: DCP-o-matic\r\n"
133               << "\r\n";
134
135         if (!_attachments.empty ()) {
136                 email << "--" << boundary << "\r\n"
137                       << "Content-Type: text/plain; charset=utf-8\r\n\r\n";
138         }
139
140         email << _body;
141
142         BOOST_FOREACH (Attachment i, _attachments) {
143                 email << "\r\n\r\n--" << boundary << "\r\n"
144                       << "Content-Type: " << i.mime_type << "; name=" << i.name << "\r\n"
145                       << "Content-Transfer-Encoding: Base64\r\n"
146                       << "Content-Disposition: attachment; filename=" << i.name << "\r\n\r\n";
147
148                 BIO* b64 = BIO_new (BIO_f_base64());
149
150                 BIO* bio = BIO_new (BIO_s_mem());
151                 bio = BIO_push (b64, bio);
152
153                 Data data (i.file);
154                 BIO_write (bio, data.data().get(), data.size());
155                 (void) BIO_flush (bio);
156
157                 char* out;
158                 long int bytes = BIO_get_mem_data (bio, &out);
159                 email << string (out, bytes);
160
161                 BIO_free_all (b64);
162         }
163
164         if (!_attachments.empty ()) {
165                 email << "\r\n--" << boundary << "--\r\n";
166         }
167
168         _email = email.str ();
169
170         curl_global_init (CURL_GLOBAL_DEFAULT);
171
172         CURL* curl = curl_easy_init ();
173         if (!curl) {
174                 throw NetworkError ("Could not initialise libcurl");
175         }
176
177         CURLM* mcurl = curl_multi_init ();
178         if (!mcurl) {
179                 throw NetworkError ("Could not initialise libcurl");
180         }
181
182         curl_easy_setopt (curl, CURLOPT_URL, String::compose (
183                                   "smtp://%1:%2",
184                                   Config::instance()->mail_server().c_str(),
185                                   Config::instance()->mail_port()
186                                   ).c_str());
187
188         if (!Config::instance()->mail_user().empty ()) {
189                 curl_easy_setopt (curl, CURLOPT_USERNAME, Config::instance()->mail_user().c_str());
190         }
191         if (!Config::instance()->mail_password().empty ()) {
192                 curl_easy_setopt (curl, CURLOPT_PASSWORD, Config::instance()->mail_password().c_str());
193         }
194
195         curl_easy_setopt (curl, CURLOPT_MAIL_FROM, _from.c_str());
196
197         struct curl_slist* recipients = 0;
198         BOOST_FOREACH (string i, _to) {
199                 curl_slist_append (recipients, i.c_str());
200         }
201         BOOST_FOREACH (string i, _cc) {
202                 recipients = curl_slist_append (recipients, i.c_str());
203         }
204         BOOST_FOREACH (string i, _bcc) {
205                 recipients = curl_slist_append (recipients, i.c_str());
206         }
207
208         curl_easy_setopt (curl, CURLOPT_MAIL_RCPT, recipients);
209
210         curl_easy_setopt (curl, CURLOPT_READFUNCTION, curl_data_shim);
211         curl_easy_setopt (curl, CURLOPT_READDATA, this);
212         curl_easy_setopt (curl, CURLOPT_UPLOAD, 1L);
213
214         curl_easy_setopt (curl, CURLOPT_USE_SSL, (long) CURLUSESSL_TRY);
215         curl_easy_setopt (curl, CURLOPT_SSL_VERIFYPEER, 0L);
216         curl_easy_setopt (curl, CURLOPT_SSL_VERIFYHOST, 0L);
217         curl_easy_setopt (curl, CURLOPT_VERBOSE, 1L);
218         curl_easy_setopt (curl, CURLOPT_DEBUGFUNCTION, curl_debug_shim);
219         curl_easy_setopt (curl, CURLOPT_DEBUGDATA, this);
220
221         curl_multi_add_handle (mcurl, curl);
222
223         time_t start = time (0);
224
225         int still_running = 1;
226         curl_multi_perform (mcurl, &still_running);
227
228         while (still_running) {
229
230                 fd_set fdread;
231                 fd_set fdwrite;
232                 fd_set fdexcep;
233
234                 FD_ZERO (&fdread);
235                 FD_ZERO (&fdwrite);
236                 FD_ZERO (&fdexcep);
237
238                 struct timeval timeout;
239                 timeout.tv_sec = 1;
240                 timeout.tv_usec = 0;
241
242                 long curl_timeout = -1;
243                 curl_multi_timeout (mcurl, &curl_timeout);
244                 if (curl_timeout >= 0) {
245                         timeout.tv_sec = curl_timeout / 1000;
246                         if (timeout.tv_sec > 1) {
247                                 timeout.tv_sec = 1;
248                         } else {
249                                 timeout.tv_usec = (curl_timeout % 1000) * 1000;
250                         }
251                 }
252
253                 int maxfd = -1;
254                 CURLMcode mc = curl_multi_fdset (mcurl, &fdread, &fdwrite, &fdexcep, &maxfd);
255
256                 if (mc != CURLM_OK) {
257                         throw KDMError (String::compose ("Failed to send KDM email to %1", address_list (_to)));
258                 }
259
260                 int rc;
261                 if (maxfd == -1) {
262 #ifdef DCPOMATIC_WINDOWS
263                         Sleep (100);
264                         rc = 0;
265 #else
266                         struct timeval wait = { 0, 100 * 1000};
267                         rc = select (0, 0, 0, 0, &wait);
268 #endif
269                 } else {
270                         rc = select (maxfd + 1, &fdread, &fdwrite, &fdexcep, &timeout);
271                 }
272
273                 if (rc < 0) {
274                         throw KDMError ("Failed to send KDM email");
275                 }
276
277                 mc = curl_multi_perform (mcurl, &still_running);
278                 if (mc != CURLM_OK) {
279                         throw KDMError (String::compose ("Failed to send KDM email (%1)", curl_multi_strerror (mc)));
280                 }
281
282                 if (job) {
283                         job->set_progress_unknown ();
284                 }
285
286                 if ((time(0) - start) > 10) {
287                         throw KDMError (_("Failed to send KDM email (timed out)"));
288                 }
289         }
290
291         int messages;
292         do {
293                 CURLMsg* m = curl_multi_info_read (mcurl, &messages);
294                 if (m && m->data.result != CURLE_OK) {
295                         throw KDMError (String::compose ("Failed to send KDM email (%1)", curl_easy_strerror (m->data.result)));
296                 }
297         } while (messages > 0);
298
299         /* XXX: we should do this stuff when an exception is thrown, but curl_multi_remove_handle
300            seems to hang if we try that.
301         */
302
303         curl_slist_free_all (recipients);
304         curl_multi_remove_handle (mcurl, curl);
305         curl_multi_cleanup (mcurl);
306         curl_easy_cleanup (curl);
307         curl_global_cleanup ();
308 }
309
310 string
311 Emailer::address_list (list<string> addresses)
312 {
313         string o;
314         BOOST_FOREACH (string i, addresses) {
315                 o += i + ", ";
316         }
317
318         return o.substr (0, o.length() - 2);
319 }
320
321 int
322 Emailer::debug (CURL *, curl_infotype type, char* data, size_t size)
323 {
324         if (type == CURLINFO_TEXT) {
325                 _notes += string (data, size);
326         } else if (type == CURLINFO_HEADER_IN) {
327                 _notes += "<- " + string (data, size);
328         } else if (type == CURLINFO_HEADER_OUT) {
329                 _notes += "-> " + string (data, size);
330         }
331         return 0;
332 }