8a061738bd14c86bfd6658bc5b194def845c94b0
[dcpomatic.git] / src / lib / emailer.cc
1 /*
2     Copyright (C) 2015-2019 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 #include "compose.hpp"
22 #include "config.h"
23 #include "emailer.h"
24 #include "exceptions.h"
25 #include <curl/curl.h>
26 #include <boost/algorithm/string.hpp>
27 #include <boost/date_time/c_local_time_adjustor.hpp>
28
29 #include "i18n.h"
30
31 using std::string;
32 using std::min;
33 using std::list;
34 using std::cout;
35 using std::pair;
36 using std::shared_ptr;
37 using dcp::ArrayData;
38
39 Emailer::Emailer (string from, list<string> to, string subject, string body)
40         : _from (from)
41         , _to (to)
42         , _subject (subject)
43         , _body (fix (body))
44         , _offset (0)
45 {
46
47 }
48
49 string
50 Emailer::fix (string s) const
51 {
52         boost::algorithm::replace_all (s, "\n", "\r\n");
53         boost::algorithm::replace_all (s, "\0", " ");
54         return s;
55 }
56
57 void
58 Emailer::add_cc (string cc)
59 {
60         _cc.push_back (cc);
61 }
62
63 void
64 Emailer::add_bcc (string bcc)
65 {
66         _bcc.push_back (bcc);
67 }
68
69 void
70 Emailer::add_attachment (boost::filesystem::path file, string name, string mime_type)
71 {
72         Attachment a;
73         a.file = file;
74         a.name = name;
75         a.mime_type = mime_type;
76         _attachments.push_back (a);
77 }
78
79 static size_t
80 curl_data_shim (void* ptr, size_t size, size_t nmemb, void* userp)
81 {
82         return reinterpret_cast<Emailer*>(userp)->get_data (ptr, size, nmemb);
83 }
84
85 static int
86 curl_debug_shim (CURL* curl, curl_infotype type, char* data, size_t size, void* userp)
87 {
88         return reinterpret_cast<Emailer*>(userp)->debug (curl, type, data, size);
89 }
90
91 size_t
92 Emailer::get_data (void* ptr, size_t size, size_t nmemb)
93 {
94         size_t const t = min (_email.length() - _offset, size * nmemb);
95         memcpy (ptr, _email.substr (_offset, t).c_str(), t);
96         _offset += t;
97         return t;
98 }
99
100 void
101 Emailer::send (string server, int port, EmailProtocol protocol, string user, string password)
102 {
103         char date_buffer[128];
104         time_t now = time (0);
105         strftime (date_buffer, sizeof(date_buffer), "%a, %d %b %Y %H:%M:%S ", localtime (&now));
106
107         boost::posix_time::ptime const utc_now = boost::posix_time::second_clock::universal_time ();
108         boost::posix_time::ptime const local_now = boost::date_time::c_local_adjustor<boost::posix_time::ptime>::utc_to_local (utc_now);
109         boost::posix_time::time_duration offset = local_now - utc_now;
110         sprintf (date_buffer + strlen(date_buffer), "%s%02d%02d", (offset.hours() >= 0 ? "+" : "-"), int(abs(offset.hours())), int(offset.minutes()));
111
112         _email = "Date: " + string(date_buffer) + "\r\n"
113                 "To: " + address_list (_to) + "\r\n"
114                 "From: " + _from + "\r\n";
115
116         if (!_cc.empty ()) {
117                 _email += "Cc: " + address_list (_cc) + "\r\n";
118         }
119
120         if (!_bcc.empty ()) {
121                 _email += "Bcc: " + address_list (_bcc) + "\r\n";
122         }
123
124         string const chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
125         string boundary;
126         for (int i = 0; i < 32; ++i) {
127                 boundary += chars[rand() % chars.length()];
128         }
129
130         if (!_attachments.empty ()) {
131                 _email += "MIME-Version: 1.0\r\n"
132                         "Content-Type: multipart/mixed; boundary=" + boundary + "\r\n";
133         }
134
135         _email += "Subject: " + _subject + "\r\n"
136                 "User-Agent: DCP-o-matic\r\n"
137                 "\r\n";
138
139         if (!_attachments.empty ()) {
140                 _email += "--" + boundary + "\r\n"
141                         + "Content-Type: text/plain; charset=utf-8\r\n\r\n";
142         }
143
144         _email += _body;
145
146         for (auto i: _attachments) {
147                 _email += "\r\n\r\n--" + boundary + "\r\n"
148                         "Content-Type: " + i.mime_type + "; name=" + i.name + "\r\n"
149                         "Content-Transfer-Encoding: Base64\r\n"
150                         "Content-Disposition: attachment; filename=" + i.name + "\r\n\r\n";
151
152                 BIO* b64 = BIO_new (BIO_f_base64());
153
154                 BIO* bio = BIO_new (BIO_s_mem());
155                 bio = BIO_push (b64, bio);
156
157                 ArrayData data (i.file);
158                 BIO_write (bio, data.data(), data.size());
159                 (void) BIO_flush (bio);
160
161                 char* out;
162                 long int bytes = BIO_get_mem_data (bio, &out);
163                 _email += fix (string (out, bytes));
164
165                 BIO_free_all (b64);
166         }
167
168         if (!_attachments.empty ()) {
169                 _email += "\r\n--" + boundary + "--\r\n";
170         }
171
172         curl_global_init (CURL_GLOBAL_DEFAULT);
173
174         CURL* curl = curl_easy_init ();
175         if (!curl) {
176                 throw NetworkError ("Could not initialise libcurl");
177         }
178
179         if ((protocol == EmailProtocol::AUTO && port == 465) || protocol == EmailProtocol::SSL) {
180                 /* "SSL" or "Implicit TLS"; I think curl wants us to use smtps here */
181                 curl_easy_setopt (curl, CURLOPT_URL, String::compose("smtps://%1:%2", server, port).c_str());
182         } else {
183                 curl_easy_setopt (curl, CURLOPT_URL, String::compose("smtp://%1:%2", server, port).c_str());
184         }
185
186         if (!user.empty ()) {
187                 curl_easy_setopt (curl, CURLOPT_USERNAME, user.c_str ());
188         }
189         if (!password.empty ()) {
190                 curl_easy_setopt (curl, CURLOPT_PASSWORD, password.c_str());
191         }
192
193         curl_easy_setopt (curl, CURLOPT_MAIL_FROM, _from.c_str());
194
195         struct curl_slist* recipients = 0;
196         for (auto i: _to) {
197                 recipients = curl_slist_append (recipients, i.c_str());
198         }
199         for (auto i: _cc) {
200                 recipients = curl_slist_append (recipients, i.c_str());
201         }
202         for (auto i: _bcc) {
203                 recipients = curl_slist_append (recipients, i.c_str());
204         }
205
206         curl_easy_setopt (curl, CURLOPT_MAIL_RCPT, recipients);
207
208         curl_easy_setopt (curl, CURLOPT_READFUNCTION, curl_data_shim);
209         curl_easy_setopt (curl, CURLOPT_READDATA, this);
210         curl_easy_setopt (curl, CURLOPT_UPLOAD, 1L);
211
212         if (protocol == EmailProtocol::AUTO || protocol == EmailProtocol::STARTTLS) {
213                 curl_easy_setopt (curl, CURLOPT_USE_SSL, (long) CURLUSESSL_TRY);
214         }
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         CURLcode const r = curl_easy_perform (curl);
222         if (r != CURLE_OK) {
223                 throw KDMError (_("Failed to send email"), curl_easy_strerror (r));
224         }
225
226         curl_slist_free_all (recipients);
227         curl_easy_cleanup (curl);
228         curl_global_cleanup ();
229 }
230
231 string
232 Emailer::address_list (list<string> addresses)
233 {
234         string o;
235         for (auto i: addresses) {
236                 o += i + ", ";
237         }
238
239         return o.substr (0, o.length() - 2);
240 }
241
242 int
243 Emailer::debug (CURL *, curl_infotype type, char* data, size_t size)
244 {
245         if (type == CURLINFO_TEXT) {
246                 _notes += string (data, size);
247         } else if (type == CURLINFO_HEADER_IN) {
248                 _notes += "<- " + string (data, size);
249         } else if (type == CURLINFO_HEADER_OUT) {
250                 _notes += "-> " + string (data, size);
251         }
252         return 0;
253 }