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