lime_x3dh_protocol.cpp 28.7 KB
Newer Older
johan's avatar
johan committed
1 2
/*
	lime_x3dh_protocol.cpp
johan's avatar
johan committed
3 4
	@author Johan Pascal
	@copyright	Copyright (C) 2017  Belledonne Communications SARL
johan's avatar
johan committed
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27

	This program is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#define BCTBX_LOG_DOMAIN "lime"
#include <bctoolbox/logging.h>

#include "lime/lime.hpp"
#include "lime_x3dh_protocol.hpp"
johan's avatar
johan committed
28
#include "lime_settings.hpp"
johan's avatar
johan committed
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
#include "lime_impl.hpp"

#include "bctoolbox/exception.hh"

using namespace::std;
using namespace::lime;

namespace lime {
	// Group in this namespace all the functions related to building or parsing x3dh packets
	namespace x3dh_protocol {
		/* Version 0x01:
		 *	Header is : Protccol Version Number<1 byte> || Message type<1 byte> || Curve id<1 byte>
		 *	Messages are : header<3 bytes> || Message content
		 *
		 *	If not an error the server responds with a message holding just a header of the same message type
		 *	except for getPeerBundle which shall be answered with a peerBundle message
		 *
		 *	Message types description :
		 *		- registerUser : Identity Key<EDDSA Public Key length>
		 *		- deleteUser : empty message, user to delete is retrieved from header From
		 *
		 *		- postSPk :	SPk<ECDH Public key length> ||
		 *				SPk Signature<Signature Length> ||
		 *				SPk Id < 4 bytes>
		 *
		 *		- postOPks : 	Keys Count<2 bytes unsigned integer Big endian> ||
		 *				( OPk<ECDH Public key length> || OPk Id <4 bytes>){Keys Count}
		 *
		 *		- getPeerBundle : request Count < 2 bytes unsigned Big Endian> ||
		 *				(userId Size <2 bytes unsigned Big Endian> || UserId <...> (the GRUU of user we wan't to send a message)) {request Count}
		 *
		 *		- peerBundle :	bundle Count < 2 bytes unsigned Big Endian> ||
		 *				(   Flag<1 byte: 0 if no OPK in bundle, 1 if present> ||
		 *				    Ik <EDDSA Public Key Length> ||
		 *				    SPk <ECDH Public Key Length> || SPK id <4 bytes>
		 *				    SPk_sig <Signature Length> ||
		 *				    (OPk <ECDH Public Key Length> || OPk id <4 bytes>){0,1 in accordance to flag}
		 *				) { bundle Count}
		 *
johan's avatar
johan committed
68 69 70 71 72
		 *		- getSelfOPks : empty message, ask server for the OPk Id it still holds for us
		 *
		 *		- selfOPks : OPk Count <2 bytes unsigned integer Big Endian> ||
		 *				(OPk id <4 bytes uint32_t big endian>){OPk Count}
		 *
johan's avatar
johan committed
73 74 75 76 77 78 79 80 81 82 83 84
		 *		- error :	errorCode<1 byte> || (errorMessage<...>){0,1}
		 */

		constexpr uint8_t X3DH_protocolVersion = 0x01;
		constexpr size_t X3DH_headerSize = 3;
		enum class x3dh_message_type : uint8_t{	unset_type=0x00,
							registerUser=0x01,
							deleteUser=0x02,
							postSPk=0x03,
							postOPks=0x04,
							getPeerBundle=0x05,
							peerBundle=0x06,
johan's avatar
johan committed
85 86
							getSelfOPks=0x07,
							selfOPks=0x08,
johan's avatar
johan committed
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
							error=0xff};

		enum class x3dh_error_code : uint8_t{	bad_content_type=0x00,
							bad_curve=0x01,
							missing_senderId=0x02,
							bad_x3dh_protocol_version=0x03,
							bad_size=0x04,
							user_already_in=0x05,
							user_not_found=0x06,
							db_error=0x07,
							bad_request=0x08,
							unset_error_code=0xff};
		/* X3DH protocol packets builds */
		static std::vector<uint8_t> X3DH_makeHeader(const x3dh_message_type message_type, const lime::CurveId curve) noexcept{
			return std::vector<uint8_t> {X3DH_protocolVersion, static_cast<uint8_t>(message_type), static_cast<uint8_t>(curve)};
		}

		// registerUser : Identity Key<EDDSA Public Key length>
		template <typename Curve>
		void buildMessage_registerUser(std::vector<uint8_t> &message, const ED<Curve> &Ik) noexcept {
			// create the header
			message = X3DH_makeHeader(x3dh_message_type::registerUser, Curve::curveId());
			// append the Ik
Johan Pascal's avatar
Johan Pascal committed
110
			message.insert(message.end(), Ik.cbegin(), Ik.cend());
johan's avatar
johan committed
111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128
		}

		// deleteUser : empty message, server retrieves deviceId to delete from authentication header, you cannot delete someone else!
		template <typename Curve>
		void buildMessage_deleteUser(std::vector<uint8_t> &message) noexcept {
			// create the header
			message = X3DH_makeHeader(x3dh_message_type::deleteUser, Curve::curveId());
		}


		// postSPk :	SPk<ECDH Public key length> ||
		//		SPk Signature<Signature Length> ||
		//		SPk Id < 4 bytes>
		template <typename Curve>
		void buildMessage_publishSPk(std::vector<uint8_t> &message, const X<Curve> &SPk, const Signature<Curve> &Sig, const uint32_t SPk_id) noexcept {
			// create the header
			message = X3DH_makeHeader(x3dh_message_type::postSPk, Curve::curveId());
			// append SPk, Signature and SPkId
Johan Pascal's avatar
Johan Pascal committed
129 130
			message.insert(message.end(), SPk.cbegin(), SPk.cend());
			message.insert(message.end(), Sig.cbegin(), Sig.cend());
johan's avatar
johan committed
131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149
			message.push_back(static_cast<uint8_t>((SPk_id>>24)&0xFF));
			message.push_back(static_cast<uint8_t>((SPk_id>>16)&0xFF));
			message.push_back(static_cast<uint8_t>((SPk_id>>8)&0xFF));
			message.push_back(static_cast<uint8_t>((SPk_id)&0xFF));
		}

		// postOPks : 	Keys Count<2 bytes unsigned integer Big endian> ||
		//		( OPk<ECDH Public key length> || OPk Id <4 bytes>){Keys Count}
		template <typename Curve>
		void buildMessage_publishOPks(std::vector<uint8_t> &message, const std::vector<X<Curve>> &OPks, const std::vector<uint32_t> &OPk_ids) noexcept {
			// create the header
			message = X3DH_makeHeader(x3dh_message_type::postOPks, Curve::curveId());

			auto OPkCount = OPks.size();
			// append OPks number and a sequence of OPk || OPk_id
			message.push_back(static_cast<uint8_t>(((OPkCount)>>8)&0xFF));
			message.push_back(static_cast<uint8_t>((OPkCount)&0xFF));

			for (decltype(OPkCount) i=0; i<OPkCount; i++) {
Johan Pascal's avatar
Johan Pascal committed
150
				message.insert(message.end(), OPks[i].cbegin(), OPks[i].cend());
johan's avatar
johan committed
151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169
				message.push_back(static_cast<uint8_t>((OPk_ids[i]>>24)&0xFF));
				message.push_back(static_cast<uint8_t>((OPk_ids[i]>>16)&0xFF));
				message.push_back(static_cast<uint8_t>((OPk_ids[i]>>8)&0xFF));
				message.push_back(static_cast<uint8_t>((OPk_ids[i])&0xFF));
			}
		}

		// getPeerBundle :	request Count < 2 bytes unsigned Big Endian> ||
		//			(userId Size <2 bytes unsigned Big Endian> || UserId <...> (the GRUU of user we wan't to send a message)) {request Count}
		template <typename Curve>
		void buildMessage_getPeerBundles(std::vector<uint8_t> &message, std::vector<std::string> &peer_device_ids) noexcept {
			// create the header
			message = X3DH_makeHeader(x3dh_message_type::getPeerBundle, Curve::curveId());

			// append peer number
			message.push_back(static_cast<uint8_t>(((peer_device_ids.size())>>8)&0xFF));
			message.push_back(static_cast<uint8_t>((peer_device_ids.size())&0xFF));

			if (peer_device_ids.size()>0xFFFF) { // we're asking for more than 2^16 key bundles, really?
johan's avatar
johan committed
170
				BCTBX_SLOGW<<"We are about to request for more than 2^16 key bundles to the X3DH server, it won't fit in protocol, truncate the request to 2^16 but it's very very unusual";
johan's avatar
johan committed
171 172 173 174
				peer_device_ids.resize(0xFFFF); // resize to max possible value
			}

			// append a sequence of peer device Id size(on 2 bytes) || device id
Johan Pascal's avatar
Johan Pascal committed
175
			for (const auto &peer_device_id : peer_device_ids) {
johan's avatar
johan committed
176 177
				message.push_back(static_cast<uint8_t>(((peer_device_id.size())>>8)&0xFF));
				message.push_back(static_cast<uint8_t>((peer_device_id.size())&0xFF));
Johan Pascal's avatar
Johan Pascal committed
178
				message.insert(message.end(),peer_device_id.cbegin(), peer_device_id.cend());
johan's avatar
johan committed
179
				BCTBX_SLOGI<<"Request X3DH keys for device "<<peer_device_id;
johan's avatar
johan committed
180 181 182
			}
		}

johan's avatar
johan committed
183 184 185 186 187 188 189 190
		// getSelfOPks : empty message, ask server for the OPk Id it still holds for us
		template <typename Curve>
		void buildMessage_getSelfOPks(std::vector<uint8_t> &message) noexcept {
			// create the header
			message = X3DH_makeHeader(x3dh_message_type::getSelfOPks, Curve::curveId());
		}


johan's avatar
johan committed
191 192 193 194 195 196 197 198 199
		/*
		 * @brief Perform validity verifications on x3dh message and extract its type and error code if its the case
		 *
		 * @param[in]	body		a buffer holding the message
		 * @param[out]	message_type	the message type
		 * @param[out]	error_code	the error code, unchanged if the message type is not error
		 * @param[in]	callback	in case of error, directly call it giving a meaningfull error message
		 */
		template <typename Curve>
200
		bool parseMessage_getType(const std::vector<uint8_t> &body, x3dh_message_type &message_type, x3dh_error_code &error_code, const limeCallback callback) noexcept {
johan's avatar
johan committed
201
			// check message holds at leat a header before trying to read it
202
			if (body.size()<X3DH_headerSize) {
johan's avatar
johan committed
203
				BCTBX_SLOGE<<"Got an invalid response from X3DH server";
johan's avatar
johan committed
204 205 206 207 208 209
				if (callback) callback(lime::callbackReturn::fail, "Got an invalid response from X3DH server");
				return false;
			}

			// check X3DH protocol version
			if (body[0] != static_cast<uint8_t>(X3DH_protocolVersion)) {
johan's avatar
johan committed
210
				BCTBX_SLOGE<<"X3DH server runs an other version of X3DH protocol(server "<<int(body[0])<<" - local "<<static_cast<uint8_t>(X3DH_protocolVersion)<<")";
johan's avatar
johan committed
211 212 213 214 215 216
				if (callback) callback(lime::callbackReturn::fail, "X3DH server and client protocol version mismatch");
				return false;
			}

			// check curve id
			if (body[2] != static_cast<uint8_t>(Curve::curveId())) {
johan's avatar
johan committed
217
				BCTBX_SLOGE<<"X3DH server runs curve Id "<<int(body[2])<<" while local is set to "<<static_cast<uint8_t>(Curve::curveId())<<" for this server)";
johan's avatar
johan committed
218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241
				if (callback) callback(lime::callbackReturn::fail, "X3DH server and client curve Id mismatch");
				return false;
			}

			// retrieve message_type from body[1]
			switch (static_cast<uint8_t>(body[1])) {
				case static_cast<uint8_t>(x3dh_message_type::registerUser) :
					message_type = x3dh_message_type::registerUser;
					break;
				case static_cast<uint8_t>(x3dh_message_type::deleteUser) :
					message_type = x3dh_message_type::deleteUser;
					break;
				case static_cast<uint8_t>(x3dh_message_type::postSPk) :
					message_type = x3dh_message_type::postSPk;
					break;
				case static_cast<uint8_t>(x3dh_message_type::postOPks) :
					message_type = x3dh_message_type::postOPks;
					break;
				case static_cast<uint8_t>(x3dh_message_type::getPeerBundle) :
					message_type = x3dh_message_type::getPeerBundle;
					break;
				case static_cast<uint8_t>(x3dh_message_type::peerBundle) :
					message_type = x3dh_message_type::peerBundle;
					break;
johan's avatar
johan committed
242 243 244 245 246 247
				case static_cast<uint8_t>(x3dh_message_type::getSelfOPks) :
					message_type = x3dh_message_type::getSelfOPks;
					break;
				case static_cast<uint8_t>(x3dh_message_type::selfOPks) :
					message_type = x3dh_message_type::selfOPks;
					break;
johan's avatar
johan committed
248 249 250 251 252 253 254 255 256
				case static_cast<uint8_t>(x3dh_message_type::error) :
					message_type = x3dh_message_type::error;
					break;
				default: // unknown message type: invalid packet
					return false;
			}

			// retrieve the error code if needed
			if (message_type == x3dh_message_type::error) {
257
				if (body.size()<X3DH_headerSize+1) { // error message contains at least 1 byte of error code + possible message
johan's avatar
johan committed
258 259 260
					return false;
				}

261
				if (body.size() == X3DH_headerSize+1) {
johan's avatar
johan committed
262
					BCTBX_SLOGE<<"X3DH server respond error : code "<<int(body[X3DH_headerSize])<<" (no error message)";
johan's avatar
johan committed
263
				} else {
Johan Pascal's avatar
Johan Pascal committed
264
					BCTBX_SLOGE<<"X3DH server respond error : code "<<int(body[X3DH_headerSize])<<" : "<<std::string(body.cbegin()+X3DH_headerSize+1, body.cend());
johan's avatar
johan committed
265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321
				}

				switch (static_cast<uint8_t>(body[X3DH_headerSize])) {
					case static_cast<uint8_t>(x3dh_error_code::bad_content_type):
						error_code = x3dh_error_code::bad_content_type;
						break;
					case static_cast<uint8_t>(x3dh_error_code::bad_curve):
						error_code = x3dh_error_code::bad_curve;
						break;
					case static_cast<uint8_t>(x3dh_error_code::missing_senderId):
						error_code = x3dh_error_code::missing_senderId;
						break;
					case static_cast<uint8_t>(x3dh_error_code::bad_x3dh_protocol_version):
						error_code = x3dh_error_code::bad_x3dh_protocol_version;
						break;
					case static_cast<uint8_t>(x3dh_error_code::bad_size):
						error_code = x3dh_error_code::bad_size;
						break;
					case static_cast<uint8_t>(x3dh_error_code::user_already_in):
						error_code = x3dh_error_code::user_already_in;
						break;
					case static_cast<uint8_t>(x3dh_error_code::user_not_found):
						error_code = x3dh_error_code::user_not_found;
						break;
					case static_cast<uint8_t>(x3dh_error_code::db_error):
						error_code = x3dh_error_code::db_error;
						break;
					case static_cast<uint8_t>(x3dh_error_code::bad_request):
						error_code = x3dh_error_code::bad_request;
						break;
					default: // unknown error code: invalid packet
						return false;
				}
			}
			return true;
		}

		/* peerBundle :	bundle Count < 2 bytes unsigned Big Endian> ||
		 *	(   deviceId Size < 2 bytes unsigned Big Endian > || deviceId
		 *	    Flag<1 byte: 0 if no OPK in bundle, 1 if present> ||
		 *		   Ik <EDDSA Public Key Length> ||
		 *		   SPk <ECDH Public Key Length> || SPK id <4 bytes>
		 *		   SPk_sig <Signature Length> ||
		 *		   (OPk <ECDH Public Key Length> || OPk id <4 bytes>){0,1 in accordance to flag}
		 *	) { bundle Count}
		 */

		/**
		 * @brief Parse a peerBundles message and populate a vector of peerBundles
		 * Warning: no checks are done on message type, they are performed before calling this function
		 *
		 * @param[in]	body		a buffer holding the message
		 * @param[out]	peersBundle	a vector to be populated from message content, is empty if none found
		 *
		 * @return true if all went ok, false and empty peersBundle otherwise
		 */
		template <typename Curve>
322
		bool parseMessage_getPeerBundles(const std::vector<uint8_t> &body, std::vector<X3DH_peerBundle<Curve>> &peersBundle) noexcept {
johan's avatar
johan committed
323
			peersBundle.clear();
324
			if (body.size() < X3DH_headerSize+2) { // we must be able to at least have a count of bundles
johan's avatar
johan committed
325 326 327 328 329 330 331 332
				return false;
			}

			uint16_t peersBundleCount = (static_cast<uint16_t>(body[X3DH_headerSize]))<<8|body[X3DH_headerSize+1];
			size_t index = X3DH_headerSize+2;

			// loop on all expected bundles
			for (auto i=0; i<peersBundleCount; i++) {
333
				if (body.size() < index + 2) { // check we have at least a device size to read
johan's avatar
johan committed
334 335 336 337 338 339 340 341
					peersBundle.clear();
					return false;
				}

				// get device id (ASCII string)
				uint16_t deviceIdSize = (static_cast<uint16_t>(body[index]))<<8|body[index+1];
				index += 2;

342
				if (body.size() < index + deviceIdSize + 1) { // check we have at enough data to read: device size and the following OPk flag
johan's avatar
johan committed
343 344 345
					peersBundle.clear();
					return false;
				}
Johan Pascal's avatar
Johan Pascal committed
346
				std::string deviceId{body.cbegin()+index, body.cbegin()+index+deviceIdSize};
johan's avatar
johan committed
347 348 349 350 351 352 353
				index += deviceIdSize;

				// check if we have an OPk
				bool haveOPk = (body[index]==0)?false:true;
				index += 1;


354
				if (body.size() < index + ED<Curve>::keyLength() + X<Curve>::keyLength() + Signature<Curve>::signatureLength() + 4 + (haveOPk?(X<Curve>::keyLength()+4):0) ) {
johan's avatar
johan committed
355 356 357 358 359
					peersBundle.clear();
					return false;
				}

				// retrieve simple pointers to all keys and signature, the X3DH_peerBundle constructor will construct the keys out of them
Johan Pascal's avatar
Johan Pascal committed
360 361
				const auto Ik = body.cbegin()+index; index += ED<Curve>::keyLength();
				const auto SPk = body.cbegin()+index; index += X<Curve>::keyLength();
johan's avatar
johan committed
362 363 364 365 366
				uint32_t SPk_id = static_cast<uint32_t>(body[index])<<24 |
						static_cast<uint32_t>(body[index+1])<<16 |
						static_cast<uint32_t>(body[index+2])<<8 |
						static_cast<uint32_t>(body[index+3]);
				index += 4;
Johan Pascal's avatar
Johan Pascal committed
367
				const auto SPk_sig = body.cbegin()+index; index += Signature<Curve>::signatureLength();
johan's avatar
johan committed
368
				if (haveOPk) {
Johan Pascal's avatar
Johan Pascal committed
369
					const auto OPk = body.cbegin()+index; index += X<Curve>::keyLength();
johan's avatar
johan committed
370 371 372 373 374 375 376 377 378 379 380 381 382
					uint32_t OPk_id = static_cast<uint32_t>(body[index])<<24 |
						static_cast<uint32_t>(body[index+1])<<16 |
						static_cast<uint32_t>(body[index+2])<<8 |
						static_cast<uint32_t>(body[index+3]);
					index += 4;
					peersBundle.emplace_back(std::move(deviceId), Ik, SPk, SPk_id, SPk_sig, OPk, OPk_id);
				} else {
					peersBundle.emplace_back(std::move(deviceId), Ik, SPk, SPk_id, SPk_sig);
				}
			}
			return true;
		}

johan's avatar
johan committed
383 384 385 386 387 388 389 390 391 392 393 394 395 396
		/*
		 * selfOPks : OPk Count <2 bytes unsigned integer Big Endian> ||
		 *	(OPk id <4 bytes uint32_t big endian>){OPk Count}
		 */
		/**
		 * @brief Parse a selfPk message and populate a self OPk ids
		 * Warning: no checks are done on message type, they are performed before calling this function
		 *
		 * @param[in]	body		a buffer holding the message
		 * @param[out]	selfOPkIds	a vector to be populated from message content, is empty if no OPk returned
		 *
		 * @return true if all went ok, false otherwise
		 */
		template <typename Curve>
397
		bool parseMessage_selfOPks(const std::vector<uint8_t> &body, std::vector<uint32_t> &selfOPkIds) noexcept {
johan's avatar
johan committed
398
			selfOPkIds.clear();
399
			if (body.size() < X3DH_headerSize+2) { // we must be able to at least have a count of bundles
johan's avatar
johan committed
400 401 402 403 404
				return false;
			}

			uint16_t selfOPkIdsCount = (static_cast<uint16_t>(body[X3DH_headerSize]))<<8|body[X3DH_headerSize+1];

405
			if (body.size() < X3DH_headerSize+2+4*selfOPkIdsCount) { // this expected message size
johan's avatar
johan committed
406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421
				return false;
			}
			size_t index = X3DH_headerSize+2;
			// loop on all OPk Ids
			for (auto i=0; i<selfOPkIdsCount; i++) { // they are in big endian
				uint32_t OPkId = static_cast<uint32_t>(body[index])<<24 |
						static_cast<uint32_t>(body[index+1])<<16 |
						static_cast<uint32_t>(body[index+2])<<8 |
						static_cast<uint32_t>(body[index+3]);
				index+=4;
				selfOPkIds.push_back(OPkId);
			}
			return true;
		}


johan's avatar
johan committed
422 423 424 425 426 427 428
		/* Instanciate templated functions */
#ifdef EC25519_ENABLED
		template void buildMessage_registerUser<C255>(std::vector<uint8_t> &message, const ED<C255> &Ik) noexcept;
		template void buildMessage_deleteUser<C255>(std::vector<uint8_t> &message) noexcept;
		template void buildMessage_publishSPk<C255>(std::vector<uint8_t> &message, const X<C255> &SPk, const Signature<C255> &Sig, const uint32_t SPk_id) noexcept;
		template void buildMessage_publishOPks<C255>(std::vector<uint8_t> &message, const std::vector<X<C255>> &OPks, const std::vector<uint32_t> &OPk_ids) noexcept;
		template void buildMessage_getPeerBundles<C255>(std::vector<uint8_t> &message, std::vector<std::string> &peer_device_ids) noexcept;
johan's avatar
johan committed
429
		template void buildMessage_getSelfOPks<C255>(std::vector<uint8_t> &message) noexcept;
johan's avatar
johan committed
430 431 432 433 434 435 436 437
#endif

#ifdef EC448_ENABLED
		template void buildMessage_registerUser<C448>(std::vector<uint8_t> &message, const ED<C448> &Ik) noexcept;
		template void buildMessage_deleteUser<C448>(std::vector<uint8_t> &message) noexcept;
		template void buildMessage_publishSPk<C448>(std::vector<uint8_t> &message, const X<C448> &SPk, const Signature<C448> &Sig, const uint32_t SPk_id) noexcept;
		template void buildMessage_publishOPks<C448>(std::vector<uint8_t> &message, const std::vector<X<C448>> &OPks, const std::vector<uint32_t> &OPk_ids) noexcept;
		template void buildMessage_getPeerBundles<C448>(std::vector<uint8_t> &message, std::vector<std::string> &peer_device_ids) noexcept;
johan's avatar
johan committed
438
		template void buildMessage_getSelfOPks<C448>(std::vector<uint8_t> &message) noexcept;
johan's avatar
johan committed
439 440 441 442 443 444
#endif
	} //namespace x3dh_protocol

	/**
	 * @brief Clean user data in case of problem or when we're done, it also process the asynchronous encryption queue
	 *
445
	 * @param[in/out] userData	the structure holding the data structure captured by the process response lambda
johan's avatar
johan committed
446 447
	 */
	template <typename Curve>
448
	void Lime<Curve>::cleanUserData(std::shared_ptr<callbackUserData<Curve>> userData) {
johan's avatar
johan committed
449 450 451 452 453 454 455 456 457
		if (userData->plainMessage!=nullptr) { // only encryption request for X3DH bundle would populate the plainMessage field of user data structure
			// userData is actually a part of the Lime Object and allocated as a shared pointer, just set it to nullptr it will cleanly destroy it
			m_ongoing_encryption = nullptr;
			// check if others encryptions are in queue and call them if needed
			if (!m_encryption_queue.empty()) {
				auto userData = m_encryption_queue.front();
				m_encryption_queue.pop(); // remove it from queue and do it, as there is no more ongoing it shall be processed even if the queue still holds elements
				encrypt(userData->recipientUserId, userData->recipients, userData->plainMessage, userData->cipherMessage, userData->callback);
			}
458 459
		} else { // its not an encryption, just set userData to null it shall destroy it
			userData = nullptr;
johan's avatar
johan committed
460 461 462 463
		}
	}

	template <typename Curve>
464 465 466 467 468 469 470 471 472 473
	void Lime<Curve>::process_response(std::shared_ptr<callbackUserData<Curve>> userData, int responseCode, const std::vector<uint8_t> &responseBody) noexcept {
		auto callback = userData->callback; // get callback

		if (responseCode == 200) { // HTTP server is happy with our packet
			// check response from X3DH server: header shall be X3DH protocol version || message type || curveId
			lime::x3dh_protocol::x3dh_message_type message_type{x3dh_protocol::x3dh_message_type::unset_type};
			lime::x3dh_protocol::x3dh_error_code error_code{x3dh_protocol::x3dh_error_code::unset_error_code};
			// check message validity, extract type and error code(if any)
			if (!x3dh_protocol::parseMessage_getType<Curve>(responseBody, message_type, error_code, callback)) {
				cleanUserData(userData);
474 475
				return;
			}
476 477 478 479 480 481 482 483 484

			switch (message_type) {
				// for registerUser, deleteUser, postSPk and postOPks, on success, server will respond with an identical header
				// but we cannot get from server unset_type, getPeerBundle or getSelfOPks message
				case x3dh_protocol::x3dh_message_type::unset_type:
				case x3dh_protocol::x3dh_message_type::getPeerBundle:
				case x3dh_protocol::x3dh_message_type::getSelfOPks: {
					if (callback) callback(lime::callbackReturn::fail, "X3DH unexpected message from server");
					cleanUserData(userData);
johan's avatar
johan committed
485
				}
486
				return;
johan's avatar
johan committed
487

488 489 490 491 492 493 494 495 496 497 498 499 500 501 502
				case x3dh_protocol::x3dh_message_type::registerUser: {
					// server response to a registerUser, we shall have the network state machine set to next action: sendSPk, just check it
					if (userData->network_state_machine == lime::network_state::sendSPk) {
						userData->network_state_machine = lime::network_state::sendOPk;
						// generate and publish the SPk
						X<Curve> SPk{};
						Signature<Curve> SPk_sig{};
						uint32_t SPk_id=0;
						X3DH_generate_SPk(SPk, SPk_sig, SPk_id);
						std::vector<uint8_t> X3DHmessage{};
						x3dh_protocol::buildMessage_publishSPk(X3DHmessage, SPk, SPk_sig, SPk_id);
						postToX3DHServer(userData, X3DHmessage);
					} else { // after registering a user, we must post SPk and OPks
						if (callback) callback(lime::callbackReturn::fail, "Internal Error: we registered a new user on X3DH server but do not plan to post SPk or OPks");
						cleanUserData(userData);
johan's avatar
johan committed
503
					}
504 505 506 507 508 509 510 511 512 513 514 515 516 517 518
				}
				return;

				case x3dh_protocol::x3dh_message_type::postSPk: {
					// server response to a post SPk, if we are at user creation, the state machine is set to next action post OPk, do it
					if (userData->network_state_machine == lime::network_state::sendOPk) {
						userData->network_state_machine = lime::network_state::done;
						// generate and publish the OPks
						std::vector<X<Curve>> OPks{};
						std::vector<uint32_t> OPk_ids{};
						X3DH_generate_OPks(OPks, OPk_ids, userData->OPkBatchSize);
						std::vector<uint8_t> X3DHmessage{};
						x3dh_protocol::buildMessage_publishOPks(X3DHmessage, OPks, OPk_ids);
						postToX3DHServer(userData, X3DHmessage);
						return;
johan's avatar
johan committed
519
					}
520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536
				}
				break;

				case x3dh_protocol::x3dh_message_type::deleteUser:
				case x3dh_protocol::x3dh_message_type::postOPks:
					// server response to deleteUser or postOPks, nothing to do really
					// success callback is the common behavior, performed after the switch
				break;

				case x3dh_protocol::x3dh_message_type::peerBundle: {
					// server response to a getPeerBundle packet
					std::vector<X3DH_peerBundle<Curve>> peersBundle;
					if (!x3dh_protocol::parseMessage_getPeerBundles(responseBody, peersBundle)) { // parsing went wrong
						BCTBX_SLOGE<<"Got an invalid peerBundle packet from X3DH server";
						if (callback) callback(lime::callbackReturn::fail, "Got an invalid peerBundle packet from X3DH server");
						cleanUserData(userData);
						return;
johan's avatar
johan committed
537 538
					}

539 540 541 542 543 544 545 546 547 548
					// generate X3DH init packets, create a store DR Sessions(in Lime obj cache, they'll be stored in DB when the first encryption will occurs)
					try {
						//Note: if while we were waiting for the peer bundle we did get an init message from him and created a session
						// just do nothing : create a second session with the peer bundle we retrieved and at some point one session will stale
						// when message stop crossing themselves on the network
						X3DH_init_sender_session(peersBundle);
					} catch (BctbxException &e) { // something went wrong, go for callback as this function may be called by code not supporting exceptions
						if (callback) callback(lime::callbackReturn::fail, std::string{"Error during the peer Bundle processing : "}.append(e.what()));
						cleanUserData(userData);
						return;
johan's avatar
johan committed
549
					}
550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566

					// call the encrypt function again, it will call the callback when done, encryption queue won't be processed as still locked by the m_ongoing_encryption member
					encrypt(userData->recipientUserId, userData->recipients, userData->plainMessage, userData->cipherMessage, callback);

					// now we can safely delete the user data, note that this may trigger an other encryption if there is one in queue
					cleanUserData(userData);
				}
				return;

				case x3dh_protocol::x3dh_message_type::selfOPks: {
					// server response to a getSelfOPks
					std::vector<uint32_t> selfOPkIds{};
					if (!x3dh_protocol::parseMessage_selfOPks<Curve>(responseBody, selfOPkIds)) { // parsing went wrong
						BCTBX_SLOGE<<"Got an invalid selfOPKs packet from X3DH server";
						if (callback) callback(lime::callbackReturn::fail, "Got an invalid selfOPKs packet from X3DH server");
						cleanUserData(userData);
						return;
johan's avatar
johan committed
567 568
					}

569 570 571 572 573 574 575 576 577 578 579 580 581 582 583
					// update in LocalStorage the OPk status: tag removed from server and delete old keys
					X3DH_updateOPkStatus(selfOPkIds);

					// Check if we shall upload more packets
					if (selfOPkIds.size() < userData->OPkServerLowLimit) {
						// generate and publish the OPks
						std::vector<X<Curve>> OPks{};
						std::vector<uint32_t> OPk_ids{};
						X3DH_generate_OPks(OPks, OPk_ids, userData->OPkBatchSize);
						std::vector<uint8_t> X3DHmessage{};
						x3dh_protocol::buildMessage_publishOPks(X3DHmessage, OPks, OPk_ids);
						postToX3DHServer(userData, X3DHmessage);
					} else { /* nothing to do, just call the callback */
						if (callback) callback(lime::callbackReturn::success, "");
						cleanUserData(userData);
johan's avatar
johan committed
584 585
					}
				}
johan's avatar
johan committed
586 587
				return;

588 589 590 591 592
				case x3dh_protocol::x3dh_message_type::error: {
					// error messages are logged inside the parseMessage_getType function, just return failure to callback
					if (callback) callback(lime::callbackReturn::fail, "X3DH server error");
					cleanUserData(userData);
				}
593
				return;
johan's avatar
johan committed
594 595
			}

596 597 598
			// we get here only if processing is over and response was the expected one
			if (callback) callback(lime::callbackReturn::success, "");
			cleanUserData(userData);
599
			return;
johan's avatar
johan committed
600

601 602 603
		} else { // response code is not 200Ok
			if (callback) callback(lime::callbackReturn::fail, std::string("Got a non Ok response from server : ").append(std::to_string(responseCode)));
			cleanUserData(userData);
604
			return;
johan's avatar
johan committed
605 606 607 608
		}
	}

	template <typename Curve>
609 610 611 612 613 614 615 616 617 618 619
	void Lime<Curve>::postToX3DHServer(std::shared_ptr<callbackUserData<Curve>> userData, const std::vector<uint8_t> &message) {
		// copy capture the shared_ptr to userData
		m_X3DH_post_data(m_X3DH_Server_URL, m_selfDeviceId, message, [userData](int responseCode, const std::vector<uint8_t> &responseBody) {
				auto thiz = userData->limeObj.lock(); // get a shared pointer to Lime Object from the weak pointer stored in userData
				// check it is valid (lock() returns nullptr)
				if (!thiz) { // our Lime caller object doesn't exists anymore
					BCTBX_SLOGE<<"Got response from X3DH server but our Lime Object has been destroyed";
					return; // the captured shared_ptr on userData will be freed when this capture will be destroyed
				}
				thiz->process_response(userData, responseCode, responseBody);
			});
johan's avatar
johan committed
620 621 622 623 624 625 626
	}


	/* X3DH Messages building functions */

	/* Instanciate templated member functions */
#ifdef EC25519_ENABLED
627 628 629
	template void Lime<C255>::postToX3DHServer(std::shared_ptr<callbackUserData<C255>> userData, const std::vector<uint8_t> &message);
	template void Lime<C255>::process_response(std::shared_ptr<callbackUserData<C255>> userData, int responseCode, const std::vector<uint8_t> &responseBody) noexcept;
	template void Lime<C255>::cleanUserData(std::shared_ptr<callbackUserData<C255>> userData);
johan's avatar
johan committed
630 631 632
#endif

#ifdef EC448_ENABLED
633 634 635
	template void Lime<C448>::postToX3DHServer(std::shared_ptr<callbackUserData<C448>> userData, const std::vector<uint8_t> &message);
	template void Lime<C448>::process_response(std::shared_ptr<callbackUserData<C448>> userData, int responseCode, const std::vector<uint8_t> &responseBody) noexcept;
	template void Lime<C448>::cleanUserData(std::shared_ptr<callbackUserData<C448>> userData);
johan's avatar
johan committed
636 637
#endif
} //namespace lime