Supporters update.
[dcpomatic.git] / src / lib / email.cc
1 /*
2     Copyright (C) 2015-2021 Carl Hetherington <cth@carlh.net>
3
4     This file is part of DCP-o-matic.
5
6     DCP-o-matic is free software; you can redistribute it and/or modify
7     it under the terms of the GNU General Public License as published by
8     the Free Software Foundation; either version 2 of the License, or
9     (at your option) any later version.
10
11     DCP-o-matic is distributed in the hope that it will be useful,
12     but WITHOUT ANY WARRANTY; without even the implied warranty of
13     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14     GNU General Public License for more details.
15
16     You should have received a copy of the GNU General Public License
17     along with DCP-o-matic.  If not, see <http://www.gnu.org/licenses/>.
18
19 */
20
21
22 #include "compose.hpp"
23 #include "config.h"
24 #include "email.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
30 #include "i18n.h"
31
32
33 using std::cout;
34 using std::min;
35 using std::pair;
36 using std::shared_ptr;
37 using std::string;
38 using std::vector;
39 using dcp::ArrayData;
40
41
42 Email::Email(string from, vector<string> to, string subject, string body)
43         : _from (from)
44         , _to (to)
45         , _subject (subject)
46         , _body (fix (body))
47         , _offset (0)
48 {
49
50 }
51
52
53 string
54 Email::fix(string s) const
55 {
56         boost::algorithm::replace_all (s, "\n", "\r\n");
57         boost::algorithm::replace_all (s, "\0", " ");
58         return s;
59 }
60
61
62 void
63 Email::add_cc(string cc)
64 {
65         _cc.push_back (cc);
66 }
67
68
69 void
70 Email::add_bcc(string bcc)
71 {
72         _bcc.push_back (bcc);
73 }
74
75
76 void
77 Email::add_attachment(boost::filesystem::path file, string name, string mime_type)
78 {
79         Attachment a;
80         a.file = dcp::ArrayData(file);
81         a.name = name;
82         a.mime_type = mime_type;
83         _attachments.push_back (a);
84 }
85
86
87 static size_t
88 curl_data_shim (void* ptr, size_t size, size_t nmemb, void* userp)
89 {
90         return reinterpret_cast<Email*>(userp)->get_data (ptr, size, nmemb);
91 }
92
93
94 static int
95 curl_debug_shim (CURL* curl, curl_infotype type, char* data, size_t size, void* userp)
96 {
97         return reinterpret_cast<Email*>(userp)->debug (curl, type, data, size);
98 }
99
100
101 size_t
102 Email::get_data(void* ptr, size_t size, size_t nmemb)
103 {
104         size_t const t = min (_email.length() - _offset, size * nmemb);
105         memcpy (ptr, _email.substr (_offset, t).c_str(), t);
106         _offset += t;
107         return t;
108 }
109
110
111 void
112 Email::send(string server, int port, EmailProtocol protocol, string user, string password)
113 {
114         char date_buffer[128];
115         time_t now = time (0);
116         strftime (date_buffer, sizeof(date_buffer), "%a, %d %b %Y %H:%M:%S ", localtime(&now));
117
118         auto const utc_now = boost::posix_time::second_clock::universal_time ();
119         auto const local_now = boost::date_time::c_local_adjustor<boost::posix_time::ptime>::utc_to_local (utc_now);
120         auto offset = local_now - utc_now;
121         sprintf (date_buffer + strlen(date_buffer), "%s%02d%02d", (offset.hours() >= 0 ? "+" : "-"), int(abs(offset.hours())), int(offset.minutes()));
122
123         _email = "Date: " + string(date_buffer) + "\r\n"
124                 "To: " + address_list (_to) + "\r\n"
125                 "From: " + _from + "\r\n";
126
127         if (!_cc.empty()) {
128                 _email += "Cc: " + address_list(_cc) + "\r\n";
129         }
130
131         if (!_bcc.empty()) {
132                 _email += "Bcc: " + address_list(_bcc) + "\r\n";
133         }
134
135         string const chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
136         string boundary;
137         for (int i = 0; i < 32; ++i) {
138                 boundary += chars[rand() % chars.length()];
139         }
140
141         if (!_attachments.empty ()) {
142                 _email += "MIME-Version: 1.0\r\n"
143                         "Content-Type: multipart/mixed; boundary=" + boundary + "\r\n";
144         }
145
146         _email += "Subject: " + encode_rfc1342(_subject) + "\r\n"
147                 "User-Agent: DCP-o-matic\r\n"
148                 "\r\n";
149
150         if (!_attachments.empty ()) {
151                 _email += "--" + boundary + "\r\n"
152                         + "Content-Type: text/plain; charset=utf-8\r\n\r\n";
153         }
154
155         _email += _body;
156
157         for (auto i: _attachments) {
158                 _email += "\r\n\r\n--" + boundary + "\r\n"
159                         "Content-Type: " + i.mime_type + "; name=" + encode_rfc1342(i.name) + "\r\n"
160                         "Content-Transfer-Encoding: Base64\r\n"
161                         "Content-Disposition: attachment; filename=" + encode_rfc1342(i.name) + "\r\n\r\n";
162
163                 auto b64 = BIO_new (BIO_f_base64());
164                 if (!b64) {
165                         throw std::bad_alloc();
166                 }
167
168                 auto bio = BIO_new (BIO_s_mem());
169                 if (!bio) {
170                         throw std::bad_alloc();
171                 }
172                 bio = BIO_push (b64, bio);
173
174                 BIO_write(bio, i.file.data(), i.file.size());
175                 (void) BIO_flush (bio);
176
177                 char* out;
178                 long int bytes = BIO_get_mem_data (bio, &out);
179                 _email += fix (string (out, bytes));
180
181                 BIO_free_all (b64);
182         }
183
184         if (!_attachments.empty ()) {
185                 _email += "\r\n--" + boundary + "--\r\n";
186         }
187
188         curl_global_init (CURL_GLOBAL_DEFAULT);
189
190         auto curl = curl_easy_init ();
191         if (!curl) {
192                 throw NetworkError ("Could not initialise libcurl");
193         }
194
195         if ((protocol == EmailProtocol::AUTO && port == 465) || protocol == EmailProtocol::SSL) {
196                 /* "SSL" or "Implicit TLS"; I think curl wants us to use smtps here */
197                 curl_easy_setopt (curl, CURLOPT_URL, String::compose("smtps://%1:%2", server, port).c_str());
198         } else {
199                 curl_easy_setopt (curl, CURLOPT_URL, String::compose("smtp://%1:%2", server, port).c_str());
200         }
201
202         if (!user.empty ()) {
203                 curl_easy_setopt (curl, CURLOPT_USERNAME, user.c_str ());
204         }
205         if (!password.empty ()) {
206                 curl_easy_setopt (curl, CURLOPT_PASSWORD, password.c_str());
207         }
208
209         curl_easy_setopt (curl, CURLOPT_MAIL_FROM, _from.c_str());
210
211         struct curl_slist* recipients = nullptr;
212         for (auto i: _to) {
213                 recipients = curl_slist_append (recipients, i.c_str());
214         }
215         for (auto i: _cc) {
216                 recipients = curl_slist_append (recipients, i.c_str());
217         }
218         for (auto i: _bcc) {
219                 recipients = curl_slist_append (recipients, i.c_str());
220         }
221
222         curl_easy_setopt (curl, CURLOPT_MAIL_RCPT, recipients);
223
224         curl_easy_setopt (curl, CURLOPT_READFUNCTION, curl_data_shim);
225         curl_easy_setopt (curl, CURLOPT_READDATA, this);
226         curl_easy_setopt (curl, CURLOPT_UPLOAD, 1L);
227
228         if (protocol == EmailProtocol::AUTO || protocol == EmailProtocol::STARTTLS) {
229                 curl_easy_setopt (curl, CURLOPT_USE_SSL, (long) CURLUSESSL_TRY);
230         }
231         curl_easy_setopt (curl, CURLOPT_SSL_VERIFYPEER, 0L);
232         curl_easy_setopt (curl, CURLOPT_SSL_VERIFYHOST, 0L);
233         curl_easy_setopt (curl, CURLOPT_VERBOSE, 1L);
234         curl_easy_setopt (curl, CURLOPT_DEBUGFUNCTION, curl_debug_shim);
235         curl_easy_setopt (curl, CURLOPT_DEBUGDATA, this);
236
237         auto const r = curl_easy_perform (curl);
238         if (r != CURLE_OK) {
239                 throw NetworkError (_("Failed to send email"), string(curl_easy_strerror(r)));
240         }
241
242         curl_slist_free_all (recipients);
243         curl_easy_cleanup (curl);
244         curl_global_cleanup ();
245 }
246
247
248 string
249 Email::address_list(vector<string> addresses)
250 {
251         string o;
252         for (auto i: addresses) {
253                 o += i + ", ";
254         }
255
256         return o.substr (0, o.length() - 2);
257 }
258
259
260 int
261 Email::debug(CURL *, curl_infotype type, char* data, size_t size)
262 {
263         if (type == CURLINFO_TEXT) {
264                 _notes += string (data, size);
265         } else if (type == CURLINFO_HEADER_IN) {
266                 _notes += "<- " + string (data, size);
267         } else if (type == CURLINFO_HEADER_OUT) {
268                 _notes += "-> " + string (data, size);
269         }
270         return 0;
271 }
272
273
274 string
275 Email::encode_rfc1342(string subject)
276 {
277         auto b64 = BIO_new(BIO_f_base64());
278         if (!b64) {
279                 throw std::bad_alloc();
280         }
281
282         auto bio = BIO_new(BIO_s_mem());
283         if (!bio) {
284                 throw std::bad_alloc();
285         }
286
287         bio = BIO_push(b64, bio);
288         BIO_write(bio, subject.c_str(), subject.length());
289         (void) BIO_flush(bio);
290
291         char* out;
292         long int bytes = BIO_get_mem_data(bio, &out);
293         string base64_subject(out, bytes);
294         BIO_free_all(b64);
295
296         boost::algorithm::replace_all(base64_subject, "\n", "");
297         return "=?utf-8?B?" + base64_subject + "?=";
298 }
299