Debian Codegraph @

src/wallet/message_transporter.cpp

raw symbols SCIP
1 // Copyright (c) 2018-2022, The Monero Project
2
3 //
4 // All rights reserved.
5 //
6 // Redistribution and use in source and binary forms, with or without modification, are
7 // permitted provided that the following conditions are met:
8 //
9 // 1. Redistributions of source code must retain the above copyright notice, this list of
10 // conditions and the following disclaimer.
11 //
12 // 2. Redistributions in binary form must reproduce the above copyright notice, this list
13 // of conditions and the following disclaimer in the documentation and/or other
14 // materials provided with the distribution.
15 //
16 // 3. Neither the name of the copyright holder nor the names of its contributors may be
17 // used to endorse or promote products derived from this software without specific
18 // prior written permission.
19 //
20 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
21 // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
22 // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
23 // THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
25 // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26 // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
27 // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
28 // THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29
30 #include "message_transporter.h"
31 #include "string_coding.h"
32 #include <boost/format.hpp>
33 #include "wallet_errors.h"
34 #include "net/http_client.h"
35 #include "net/net_parse_helpers.h"
36 #include <algorithm>
37
38 #undef MONERO_DEFAULT_LOG_CATEGORY
39 #define MONERO_DEFAULT_LOG_CATEGORY "wallet.mms"
40 #define PYBITMESSAGE_DEFAULT_API_PORT 8442
41
42 namespace mms
43 {
44
45 namespace bitmessage_rpc
46 {
47
48 struct message_info_t
49 {
50 uint32_t encodingType;
51 std::string toAddress;
52 uint32_t read;
53 std::string msgid;
54 std::string message;
55 std::string fromAddress;
56 std::string receivedTime;
57 std::string subject;
58
59 BEGIN_KV_SERIALIZE_MAP()
60 KV_SERIALIZE(encodingType)
61 KV_SERIALIZE(toAddress)
62 KV_SERIALIZE(read)
63 KV_SERIALIZE(msgid)
64 KV_SERIALIZE(message);
65 KV_SERIALIZE(fromAddress)
66 KV_SERIALIZE(receivedTime)
67 KV_SERIALIZE(subject)
68 END_KV_SERIALIZE_MAP()
69 };
70 typedef epee::misc_utils::struct_init<message_info_t> message_info;
71
72 struct inbox_messages_response_t
73 {
74 std::vector<message_info> inboxMessages;
75
76 BEGIN_KV_SERIALIZE_MAP()
77 KV_SERIALIZE(inboxMessages)
78 END_KV_SERIALIZE_MAP()
79 };
80 typedef epee::misc_utils::struct_init<inbox_messages_response_t> inbox_messages_response;
81
82 }
83
84 message_transporter::message_transporter(std::unique_ptr<epee::net_utils::http::abstract_http_client> http_client) : m_http_client(std::move(http_client))
85 {
86 m_run = true;
87 }
88
89 void message_transporter::set_options(const std::string &bitmessage_address, const epee::wipeable_string &bitmessage_login)
90 {
91 m_bitmessage_url = bitmessage_address;
92 epee::net_utils::http::url_content address_parts{};
93 epee::net_utils::parse_url(m_bitmessage_url, address_parts);
94 if (address_parts.port == 0)
95 {
96 address_parts.port = PYBITMESSAGE_DEFAULT_API_PORT;
97 }
98 m_bitmessage_login = bitmessage_login;
99
100 m_http_client->set_server(address_parts.host, std::to_string(address_parts.port), boost::none);
101 }
102
103 bool message_transporter::receive_messages(const std::vector<std::string> &destination_transport_addresses,
104 std::vector<transport_message> &messages)
105 {
106 // The message body of the Bitmessage message is basically the transport message, as JSON (and nothing more).
107 // Weeding out other, non-MMS messages is done in a simple way: If it deserializes without error, it's an MMS message
108 // That JSON is Base64-encoded by the MMS because the Monero epee JSON serializer does not escape anything and happily
109 // includes even 0 (NUL) in strings, which might confuse Bitmessage or at least display confusingly in the client.
110 // There is yet another Base64-encoding of course as part of the Bitmessage API for the message body parameter
111 // The Bitmessage API call "getAllInboxMessages" gives back a JSON array with all the messages (despite using
112 // XML-RPC for the calls, and not JSON-RPC ...)
113 m_run.store(true, std::memory_order_relaxed);
114 std::string request;
115 start_xml_rpc_cmd(request, "getAllInboxMessages");
116 end_xml_rpc_cmd(request);
117 std::string answer;
118 post_request(request, answer);
119
120 std::string json = get_str_between_tags(answer, "<string>", "</string>");
121 bitmessage_rpc::inbox_messages_response bitmessage_res;
122 if (!epee::serialization::load_t_from_json(bitmessage_res, json))
123 {
124 MERROR("Failed to deserialize messages");
125 return true;
126 }
127 size_t size = bitmessage_res.inboxMessages.size();
128 messages.clear();
129
130 for (size_t i = 0; i < size; ++i)
131 {
132 if (!m_run.load(std::memory_order_relaxed))
133 {
134 // Stop was called, don't waste time processing any more messages
135 return false;
136 }
137 const bitmessage_rpc::message_info &message_info = bitmessage_res.inboxMessages[i];
138 if (std::find(destination_transport_addresses.begin(), destination_transport_addresses.end(), message_info.toAddress) != destination_transport_addresses.end())
139 {
140 transport_message message;
141 bool is_mms_message = false;
142 try
143 {
144 // First Base64-decoding: The message body is Base64 in the Bitmessage API
145 std::string message_body = epee::string_encoding::base64_decode(message_info.message);
146 // Second Base64-decoding: The MMS uses Base64 to hide non-textual data in its JSON from Bitmessage
147 json = epee::string_encoding::base64_decode(message_body);
148 if (!epee::serialization::load_t_from_json(message, json))
149 MERROR("Failed to deserialize message");
150 else
151 is_mms_message = true;
152 }
153 catch(const std::exception& e)
154 {
155 }
156 if (is_mms_message)
157 {
158 message.transport_id = message_info.msgid;
159 messages.push_back(message);
160 }
161 }
162 }
163
164 return true;
165 }
166
167 bool message_transporter::send_message(const transport_message &message)
168 {
169 // <toAddress> <fromAddress> <subject> <message> [encodingType [TTL]]
170 std::string request;
171 start_xml_rpc_cmd(request, "sendMessage");
172 add_xml_rpc_string_param(request, message.destination_transport_address);
173 add_xml_rpc_string_param(request, message.source_transport_address);
174 add_xml_rpc_base64_param(request, message.subject);
175 std::string json = epee::serialization::store_t_to_json(message);
176 std::string message_body = epee::string_encoding::base64_encode(json); // See comment in "receive_message" about reason for (double-)Base64 encoding
177 add_xml_rpc_base64_param(request, message_body);
178 add_xml_rpc_integer_param(request, 2);
179 end_xml_rpc_cmd(request);
180 std::string answer;
181 post_request(request, answer);
182 return true;
183 }
184
185 bool message_transporter::delete_message(const std::string &transport_id)
186 {
187 std::string request;
188 start_xml_rpc_cmd(request, "trashMessage");
189 add_xml_rpc_string_param(request, transport_id);
190 end_xml_rpc_cmd(request);
191 std::string answer;
192 post_request(request, answer);
193 return true;
194 }
195
196 // Deterministically derive a new transport address from 'seed' (the 10-hex-digits auto-config
197 // token will be used) and set it up for sending and receiving
198 // In a first attempt a normal Bitmessage address was used here, but it turned out the
199 // key exchange necessary to put it into service could take a long time or even did not
200 // work out at all sometimes. Also there were problems when deleting those temporary
201 // addresses again after auto-config. Now a chan is used which avoids all these drawbacks
202 // quite nicely.
203 std::string message_transporter::derive_transport_address(const std::string &seed)
204 {
205 // Don't use the seed directly as chan name; that would be too dangerous, e.g. in the
206 // case of a PyBitmessage instance used by multiple unrelated people
207 // If an auto-config token gets hashed in another context use different salt instead of "chan"
208 std::string salted_seed = seed + "chan";
209 std::string chan_name = epee::string_tools::pod_to_hex(crypto::cn_fast_hash(salted_seed.data(), salted_seed.size()));
210
211 // Calculate the Bitmessage address that the chan will get for being able to
212 // use 'joinChain', as 'createChan' will fail and not tell the address if the chan
213 // already exists (which it can if all auto-config participants share a PyBitmessage
214 // instance). 'joinChan' will also fail in that case, but that won't matter.
215 std::string request;
216 start_xml_rpc_cmd(request, "getDeterministicAddress");
217 add_xml_rpc_base64_param(request, chan_name);
218 add_xml_rpc_integer_param(request, 4); // addressVersionNumber
219 add_xml_rpc_integer_param(request, 1); // streamNumber
220 end_xml_rpc_cmd(request);
221 std::string answer;
222 post_request(request, answer);
223 std::string address = get_str_between_tags(answer, "<string>", "</string>");
224
225 start_xml_rpc_cmd(request, "joinChan");
226 add_xml_rpc_base64_param(request, chan_name);
227 add_xml_rpc_string_param(request, address);
228 end_xml_rpc_cmd(request);
229 post_request(request, answer);
230 return address;
231 }
232
233 bool message_transporter::delete_transport_address(const std::string &transport_address)
234 {
235 std::string request;
236 start_xml_rpc_cmd(request, "leaveChan");
237 add_xml_rpc_string_param(request, transport_address);
238 end_xml_rpc_cmd(request);
239 std::string answer;
240 return post_request(request, answer);
241 }
242
243 bool message_transporter::post_request(const std::string &request, std::string &answer)
244 {
245 // Somehow things do not work out if one tries to connect "m_http_client" to Bitmessage
246 // and keep it connected over the course of several calls. But with a new connection per
247 // call and disconnecting after the call there is no problem (despite perhaps a small
248 // slowdown)
249 epee::net_utils::http::fields_list additional_params;
250
251 // Basic access authentication according to RFC 7617 (which the epee HTTP classes do not seem to support?)
252 // "m_bitmessage_login" just contains what is needed here, "user:password"
253 std::string auth_string = epee::string_encoding::base64_encode((const unsigned char*)m_bitmessage_login.data(), m_bitmessage_login.size());
254 auth_string.insert(0, "Basic ");
255 additional_params.push_back(std::make_pair("Authorization", auth_string));
256
257 additional_params.push_back(std::make_pair("Content-Type", "application/xml; charset=utf-8"));
258 const epee::net_utils::http::http_response_info* response = NULL;
259 std::chrono::milliseconds timeout = std::chrono::seconds(15);
260 bool r = m_http_client->invoke("/", "POST", request, timeout, std::addressof(response), std::move(additional_params));
261 if (r)
262 {
263 answer = response->m_body;
264 }
265 else
266 {
267 LOG_ERROR("POST request to Bitmessage failed: " << request.substr(0, 300));
268 THROW_WALLET_EXCEPTION(tools::error::no_connection_to_bitmessage, m_bitmessage_url);
269 }
270 m_http_client->disconnect(); // see comment above
271 std::string string_value = get_str_between_tags(answer, "<string>", "</string>");
272 if ((string_value.find("API Error") == 0) || (string_value.find("RPC ") == 0))
273 {
274 if ((string_value.find("API Error 0021") == 0) && (request.find("joinChan") != std::string::npos))
275 {
276 // Error that occurs if one tries to join an already joined chan, which can happen
277 // if several auto-config participants share one PyBitmessage instance: As a little
278 // hack simply ignore the error. (A clean solution would be to check for the chan
279 // with 'listAddresses2', but parsing the returned array is much more complicated.)
280 }
281 else if ((string_value.find("API Error 0013") == 0) && (request.find("leaveChan") != std::string::npos))
282 {
283 // Error that occurs if one tries to leave an already left / deleted chan, which can happen
284 // if several auto-config participants share one PyBitmessage instance: Also ignore.
285 }
286 else
287 {
288 THROW_WALLET_EXCEPTION(tools::error::bitmessage_api_error, string_value);
289 }
290 }
291
292 return r;
293 }
294
295 // Pick some string between two delimiters
296 // When parsing the XML returned by PyBitmessage, don't bother to fully parse it but as a little hack rely on the
297 // fact that e.g. a single string returned will be, however deeply nested in "<params><param><value>...", delivered
298 // between the very first "<string>" and "</string>" tags to be found in the XML
299 std::string message_transporter::get_str_between_tags(const std::string &s, const std::string &start_delim, const std::string &stop_delim)
300 {
301 size_t first_delim_pos = s.find(start_delim);
302 if (first_delim_pos != std::string::npos)
303 {
304 size_t end_pos_of_first_delim = first_delim_pos + start_delim.length();
305 size_t last_delim_pos = s.find(stop_delim);
306 if (last_delim_pos != std::string::npos)
307 {
308 return s.substr(end_pos_of_first_delim, last_delim_pos - end_pos_of_first_delim);
309 }
310 }
311 return std::string();
312 }
313
314 void message_transporter::start_xml_rpc_cmd(std::string &xml, const std::string &method_name)
315 {
316 xml = (boost::format("<?xml version=\"1.0\"?><methodCall><methodName>%s</methodName><params>") % method_name).str();
317 }
318
319 void message_transporter::add_xml_rpc_string_param(std::string &xml, const std::string &param)
320 {
321 xml += (boost::format("<param><value><string>%s</string></value></param>") % param).str();
322 }
323
324 void message_transporter::add_xml_rpc_base64_param(std::string &xml, const std::string &param)
325 {
326 // Bitmessage expects some arguments Base64-encoded, but it wants them as parameters of type "string", not "base64" that is also part of XML-RPC
327 std::string encoded_param = epee::string_encoding::base64_encode(param);
328 xml += (boost::format("<param><value><string>%s</string></value></param>") % encoded_param).str();
329 }
330
331 void message_transporter::add_xml_rpc_integer_param(std::string &xml, const int32_t &param)
332 {
333 xml += (boost::format("<param><value><int>%i</int></value></param>") % param).str();
334 }
335
336 void message_transporter::end_xml_rpc_cmd(std::string &xml)
337 {
338 xml += "</params></methodCall>";
339 }
340
341 }