File: I2CP.cpp

package info (click to toggle)
i2pd 2.58.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 3,612 kB
  • sloc: cpp: 59,663; makefile: 224; sh: 138
file content (1242 lines) | stat: -rw-r--r-- 39,398 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
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
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
/*
* Copyright (c) 2013-2025, The PurpleI2P Project
*
* This file is part of Purple i2pd project and licensed under BSD3
*
* See full license text in LICENSE file at top of project tree
*/

#include <string.h>
#include <stdlib.h>
#include <openssl/rand.h>
#include "I2PEndian.h"
#include "Log.h"
#include "Timestamp.h"
#include "LeaseSet.h"
#include "ClientContext.h"
#include "Transports.h"
#include "Signature.h"
#include "Config.h"
#include "I2CP.h"

namespace i2p
{
namespace client
{

	I2CPDestination::I2CPDestination (boost::asio::io_context& service, std::shared_ptr<I2CPSession> owner,
		std::shared_ptr<const i2p::data::IdentityEx> identity, bool isPublic, bool isSameThread,
	    const std::map<std::string, std::string>& params):
		LeaseSetDestination (service, isPublic, &params),
		m_Owner (owner), m_Identity (identity), m_IsCreatingLeaseSet (false), m_IsSameThread (isSameThread), 
		m_LeaseSetCreationTimer (service), m_ReadinessCheckTimer (service)
	{
	}

	void I2CPDestination::Stop ()
	{
		m_LeaseSetCreationTimer.cancel ();
		m_ReadinessCheckTimer.cancel ();
		LeaseSetDestination::Stop ();
		m_Owner = nullptr;
	}

	void I2CPDestination::SetEncryptionPrivateKey (i2p::data::CryptoKeyType keyType, const uint8_t * key)
	{
		bool exist = false;
		auto it = m_EncryptionKeys.find (keyType);
		if (it != m_EncryptionKeys.end () && !memcmp (it->second->priv.data (), key, it->second->priv.size ())) // new key?
			exist = true;
		if (!exist)
		{
			auto encryptionKey = std::make_shared<i2p::crypto::LocalEncryptionKey> (keyType);
			memcpy (encryptionKey->priv.data (), key, encryptionKey->priv.size ());
			encryptionKey->CreateDecryptor (); // from private key
			m_EncryptionKeys.insert_or_assign (keyType, encryptionKey);
		}
	}

	void I2CPDestination::SetECIESx25519EncryptionPrivateKey (i2p::data::CryptoKeyType keyType, const uint8_t * key)
	{
		bool exist = false;
		auto it = m_EncryptionKeys.find (keyType);
		if (it != m_EncryptionKeys.end () && !memcmp (it->second->priv.data (), key, it->second->priv.size ())) // new key?
			exist = true;
		if (!exist)
		{
			auto encryptionKey = std::make_shared<i2p::crypto::LocalEncryptionKey> (keyType);
			memcpy (encryptionKey->priv.data (), key, encryptionKey->priv.size ());
			// create decryptor manually
			auto decryptor = std::make_shared<i2p::crypto::ECIESX25519AEADRatchetDecryptor>(key, true); // calculate publicKey
			encryptionKey->decryptor = decryptor;
			// assign public key from decryptor
			memcpy (encryptionKey->pub.data (), decryptor->GetPubicKey (), encryptionKey->pub.size ());
			// insert or replace new
			m_EncryptionKeys.insert_or_assign (keyType, encryptionKey);
		}
	}

	bool I2CPDestination::Decrypt (const uint8_t * encrypted, uint8_t * data, i2p::data::CryptoKeyType preferredCrypto) const
	{
		std::shared_ptr<i2p::crypto::LocalEncryptionKey> encryptionKey;
		if (!m_EncryptionKeys.empty ())
		{
			if (m_EncryptionKeys.rbegin ()->first == preferredCrypto)
				encryptionKey = m_EncryptionKeys.rbegin ()->second;
			else
			{
				auto it = m_EncryptionKeys.find (preferredCrypto);
				if (it != m_EncryptionKeys.end ())
					encryptionKey = it->second;
			}	
			if (!encryptionKey)
				encryptionKey = m_EncryptionKeys.rbegin ()->second;
		}	
		if (encryptionKey)
			return encryptionKey->decryptor->Decrypt (encrypted, data);
		else
			LogPrint (eLogError, "I2CP: Decryptor is not set");
		return false;
	}

	const uint8_t * I2CPDestination::GetEncryptionPublicKey (i2p::data::CryptoKeyType keyType) const
	{
		auto it = m_EncryptionKeys.find (keyType);
		if (it != m_EncryptionKeys.end ())
			return it->second->pub.data ();
		return nullptr;
	}

	bool I2CPDestination::SupportsEncryptionType (i2p::data::CryptoKeyType keyType) const
	{
#if __cplusplus >= 202002L // C++20
		return m_EncryptionKeys.contains (keyType);
#else		
		return m_EncryptionKeys.count (keyType) > 0;
#endif	
	}

	i2p::data::CryptoKeyType I2CPDestination::GetPreferredCryptoType () const
	{
		return !m_EncryptionKeys.empty () ? m_EncryptionKeys.rbegin ()->first : 0;
	}	

	i2p::data::CryptoKeyType I2CPDestination::GetRatchetsHighestCryptoType () const
	{
		if (m_EncryptionKeys.empty ()) return 0;
		auto cryptoType = m_EncryptionKeys.rbegin ()->first; 
		return cryptoType >= i2p::data::CRYPTO_KEY_TYPE_ECIES_X25519_AEAD ? cryptoType : 0;
	}
		
	void I2CPDestination::HandleDataMessage (const uint8_t * buf, size_t len, 
		i2p::garlic::ECIESX25519AEADRatchetSession * from)
	{
		uint32_t length = bufbe32toh (buf);
		if (length > len - 4) length = len - 4;
		if (m_Owner)
			m_Owner->SendMessagePayloadMessage (buf + 4, length);
	}

	void I2CPDestination::CreateNewLeaseSet (const std::vector<std::shared_ptr<i2p::tunnel::InboundTunnel> >& tunnels)
	{
		boost::asio::post (GetService (), std::bind (&I2CPDestination::PostCreateNewLeaseSet, GetSharedFromThis (), tunnels));
	}

	void I2CPDestination::PostCreateNewLeaseSet (std::vector<std::shared_ptr<i2p::tunnel::InboundTunnel> > tunnels)
	{
		if (m_IsCreatingLeaseSet)
		{
			LogPrint (eLogInfo, "I2CP: LeaseSet is being created");
			return;
		}
		m_ReadinessCheckTimer.cancel ();
		auto pool = GetTunnelPool ();
		if (!pool || pool->GetOutboundTunnels ().empty ())
		{
			// try again later
			m_ReadinessCheckTimer.expires_from_now (boost::posix_time::seconds(I2CP_DESTINATION_READINESS_CHECK_INTERVAL));
			m_ReadinessCheckTimer.async_wait(
				[s=GetSharedFromThis (), tunnels=std::move(tunnels)](const boost::system::error_code& ecode)
			    {
					if (ecode != boost::asio::error::operation_aborted)
						s->PostCreateNewLeaseSet (tunnels);
				});	
			return;
		}	
		uint8_t priv[256] = {0};
		i2p::data::LocalLeaseSet ls (m_Identity, priv, tunnels); // we don't care about encryption key, we need leases only
		m_LeaseSetExpirationTime = ls.GetExpirationTime ();
		uint8_t * leases = ls.GetLeases ();
		int numLeases = leases[-1];
		if (m_Owner && numLeases)
		{
			uint16_t sessionID = m_Owner->GetSessionID ();
			if (sessionID != 0xFFFF)
			{
				m_IsCreatingLeaseSet = true;
				htobe16buf (leases - 3, sessionID);
				size_t l = 2/*sessionID*/ + 1/*num leases*/ + i2p::data::LEASE_SIZE*numLeases;
				m_Owner->SendI2CPMessage (I2CP_REQUEST_VARIABLE_LEASESET_MESSAGE, leases - 3, l);
				m_LeaseSetCreationTimer.expires_from_now (boost::posix_time::seconds (I2CP_LEASESET_CREATION_TIMEOUT));
				auto s = GetSharedFromThis ();
				m_LeaseSetCreationTimer.async_wait ([s](const boost::system::error_code& ecode)
				{
					if (ecode != boost::asio::error::operation_aborted)
					{
						LogPrint (eLogInfo, "I2CP: LeaseSet creation timeout expired. Terminate");
						if (s->m_Owner) s->m_Owner->Stop ();
					}
				});
			}
		}
		else
			LogPrint (eLogError, "I2CP: Can't request LeaseSet");
	}

	void I2CPDestination::LeaseSetCreated (const uint8_t * buf, size_t len)
	{
		m_IsCreatingLeaseSet = false;
		m_LeaseSetCreationTimer.cancel ();
		auto ls = std::make_shared<i2p::data::LocalLeaseSet> (m_Identity, buf, len);
		ls->SetExpirationTime (m_LeaseSetExpirationTime);
		SetLeaseSet (ls);
	}

	void I2CPDestination::LeaseSet2Created (uint8_t storeType, const uint8_t * buf, size_t len)
	{
		m_IsCreatingLeaseSet = false;
		m_LeaseSetCreationTimer.cancel ();
		auto ls = (storeType == i2p::data::NETDB_STORE_TYPE_ENCRYPTED_LEASESET2) ?
			std::make_shared<i2p::data::LocalEncryptedLeaseSet2> (m_Identity, buf, len):
			std::make_shared<i2p::data::LocalLeaseSet2> (storeType, m_Identity, buf, len);
		ls->SetExpirationTime (m_LeaseSetExpirationTime);
		SetLeaseSet (ls);
	}

	void I2CPDestination::SendMsgTo (const uint8_t * payload, size_t len, const i2p::data::IdentHash& ident, uint32_t nonce)
	{
		auto msg = m_I2NPMsgsPool.AcquireSharedMt ();
		uint8_t * buf = msg->GetPayload ();
		htobe32buf (buf, len);
		memcpy (buf + 4, payload, len);
		msg->len += len + 4;
		msg->FillI2NPMessageHeader (eI2NPData);
		auto remote = FindLeaseSet (ident);
		if (remote)
		{
			if (m_IsSameThread)
			{
				// send right a way
				bool sent = SendMsg (msg, remote);
				if (m_Owner)
					m_Owner->SendMessageStatusMessage (nonce, sent ? eI2CPMessageStatusGuaranteedSuccess : eI2CPMessageStatusGuaranteedFailure);
			}	
			else
			{	
				// send in destination's thread
				auto s = GetSharedFromThis ();
				boost::asio::post (GetService (),
					[s, msg, remote, nonce]()
					{
						bool sent = s->SendMsg (msg, remote);
						if (s->m_Owner)
							s->m_Owner->SendMessageStatusMessage (nonce, sent ? eI2CPMessageStatusGuaranteedSuccess : eI2CPMessageStatusGuaranteedFailure);
					});
			}	
		}
		else
		{
			auto s = GetSharedFromThis ();
			RequestDestination (ident,
				[s, msg, nonce](std::shared_ptr<i2p::data::LeaseSet> ls)
				{
					if (ls)
					{
						bool sent = s->SendMsg (msg, ls);
						if (s->m_Owner)
							s->m_Owner->SendMessageStatusMessage (nonce, sent ? eI2CPMessageStatusGuaranteedSuccess : eI2CPMessageStatusGuaranteedFailure);
					}
					else if (s->m_Owner)
						s->m_Owner->SendMessageStatusMessage (nonce, eI2CPMessageStatusNoLeaseSet);
				});
		}
	}

	bool I2CPDestination::SendMsg (std::shared_ptr<I2NPMessage> msg, std::shared_ptr<const i2p::data::LeaseSet> remote)
	{
		auto remoteSession = GetRoutingSession (remote, true);
		if (!remoteSession)
		{
			LogPrint (eLogError, "I2CP: Failed to create remote session");
			return false;
		}
		auto garlic = remoteSession->WrapSingleMessage (msg); // shared routing path mitgh be dropped here
		auto path = remoteSession->GetSharedRoutingPath ();
		std::shared_ptr<i2p::tunnel::OutboundTunnel> outboundTunnel;
		std::shared_ptr<const i2p::data::Lease> remoteLease;
		if (path)
		{
			if (!remoteSession->CleanupUnconfirmedTags ()) // no stuck tags
			{
				outboundTunnel = path->outboundTunnel;
				remoteLease = path->remoteLease;
			}
			else
				remoteSession->SetSharedRoutingPath (nullptr);
		}
		if (!outboundTunnel || !remoteLease)
		{
			auto leases = remote->GetNonExpiredLeases (false); // without threshold
			if (leases.empty ())
				leases = remote->GetNonExpiredLeases (true); // with threshold
			if (!leases.empty ())
			{
				auto pool = GetTunnelPool ();
				remoteLease = leases[(pool ? pool->GetRng ()() : rand ()) % leases.size ()];
				auto leaseRouter = i2p::data::netdb.FindRouter (remoteLease->tunnelGateway);
				outboundTunnel = GetTunnelPool ()->GetNextOutboundTunnel (nullptr,
					leaseRouter ? leaseRouter->GetCompatibleTransports (false) : (i2p::data::RouterInfo::CompatibleTransports)i2p::data::RouterInfo::eAllTransports);
			}
			if (remoteLease && outboundTunnel)
				remoteSession->SetSharedRoutingPath (std::make_shared<i2p::garlic::GarlicRoutingPath> (
					i2p::garlic::GarlicRoutingPath{outboundTunnel, remoteLease, 10000, 0})); // 10 secs RTT
			else
				remoteSession->SetSharedRoutingPath (nullptr);
		}
		m_Owner->AddRoutingSession (remote->GetIdentity ()->GetStandardIdentity ().signingKey + 96, remoteSession); // last 32 bytes
		return SendMsg (garlic, outboundTunnel, remoteLease);
	}

	bool I2CPDestination::SendMsg (std::shared_ptr<I2NPMessage> garlic, 
	    std::shared_ptr<i2p::tunnel::OutboundTunnel> outboundTunnel, std::shared_ptr<const i2p::data::Lease> remoteLease)
	{
		if (remoteLease && outboundTunnel)
		{
			outboundTunnel->SendTunnelDataMsgs (
			    {
					i2p::tunnel::TunnelMessageBlock
					{
						i2p::tunnel::eDeliveryTypeTunnel,
						remoteLease->tunnelGateway, remoteLease->tunnelID,
						garlic
					}
				});
			return true;
		}
		else
		{
			if (outboundTunnel)
				LogPrint (eLogWarning, "I2CP: Failed to send message. All leases expired");
			else
				LogPrint (eLogWarning, "I2CP: Failed to send message. No outbound tunnels");
			return false;
		}		
	}	

	bool I2CPDestination::SendMsg (const uint8_t * payload, size_t len, 
		std::shared_ptr<i2p::garlic::GarlicRoutingSession> remoteSession, uint32_t nonce)
	{
		if (!remoteSession) return false;
		auto path = remoteSession->GetSharedRoutingPath ();
		if (!path) return false;
		// get tunnels
		std::shared_ptr<i2p::tunnel::OutboundTunnel> outboundTunnel;
		std::shared_ptr<const i2p::data::Lease> remoteLease;
		if (!remoteSession->CleanupUnconfirmedTags ()) // no stuck tags
		{
			outboundTunnel = path->outboundTunnel;
			remoteLease = path->remoteLease;
		}
		else
		{	
			remoteSession->SetSharedRoutingPath (nullptr);
			return false;
		}	
		// create Data message
		auto msg = m_I2NPMsgsPool.AcquireSharedMt ();
		uint8_t * buf = msg->GetPayload ();
		htobe32buf (buf, len);
		memcpy (buf + 4, payload, len);
		msg->len += len + 4;
		msg->FillI2NPMessageHeader (eI2NPData);
		// wrap in gralic
		auto garlic = remoteSession->WrapSingleMessage (msg);
		// send
		bool sent = SendMsg (garlic, outboundTunnel, remoteLease);
		m_Owner->SendMessageStatusMessage (nonce, sent ? eI2CPMessageStatusGuaranteedSuccess : eI2CPMessageStatusGuaranteedFailure);
		if (!sent)
			remoteSession->SetSharedRoutingPath (nullptr);
		return sent;
	}

	void I2CPDestination::CleanupDestination ()
	{
		m_I2NPMsgsPool.CleanUpMt ();
		if (m_Owner) m_Owner->CleanupRoutingSessions ();
	}	
		
	RunnableI2CPDestination::RunnableI2CPDestination (std::shared_ptr<I2CPSession> owner,
		std::shared_ptr<const i2p::data::IdentityEx> identity, bool isPublic, const std::map<std::string, std::string>& params):
		RunnableService ("I2CP"),
		I2CPDestination (GetIOService (), owner, identity, isPublic, false, params)
	{
	}

	RunnableI2CPDestination::~RunnableI2CPDestination ()
	{
		if (IsRunning ())
			Stop ();
	}

	void RunnableI2CPDestination::Start ()
	{
		if (!IsRunning ())
		{
			I2CPDestination::Start ();
			StartIOService ();
		}
	}

	void RunnableI2CPDestination::Stop ()
	{
		if (IsRunning ())
		{
			I2CPDestination::Stop ();
			StopIOService ();
		}
	}

	I2CPSession::I2CPSession (I2CPServer& owner, std::shared_ptr<boost::asio::ip::tcp::socket> socket):
		m_Owner (owner), m_Socket (socket), m_SessionID (0xFFFF), m_MessageID (0), 
		m_IsSendAccepted (true), m_IsSending (false)
	{
	}

	I2CPSession::~I2CPSession ()
	{
		Terminate ();
	}

	void I2CPSession::Start ()
	{
		if (m_Socket)
		{	
			m_Socket->set_option (boost::asio::socket_base::receive_buffer_size (I2CP_MAX_MESSAGE_LENGTH));
			m_Socket->set_option (boost::asio::socket_base::send_buffer_size (I2CP_MAX_MESSAGE_LENGTH));
		}	
		ReadProtocolByte ();
	}

	void I2CPSession::Stop ()
	{
		Terminate ();
	}

	void I2CPSession::ReadProtocolByte ()
	{
		if (m_Socket)
		{
			auto s = shared_from_this ();
			m_Socket->async_read_some (boost::asio::buffer (m_Header, 1),
				[s](const boost::system::error_code& ecode, std::size_t bytes_transferred)
					{
						if (!ecode && bytes_transferred > 0 && s->m_Header[0] == I2CP_PROTOCOL_BYTE)
							s->ReceiveHeader ();
						else
							s->Terminate ();
					});
		}
	}

	void I2CPSession::ReceiveHeader ()
	{
		if (!m_Socket)
		{
			LogPrint (eLogError, "I2CP: Can't receive header");
			return;
		}
		boost::asio::async_read (*m_Socket, boost::asio::buffer (m_Header, I2CP_HEADER_SIZE),
			boost::asio::transfer_all (),
			std::bind (&I2CPSession::HandleReceivedHeader, shared_from_this (), std::placeholders::_1, std::placeholders::_2));
	}

	void I2CPSession::HandleReceivedHeader (const boost::system::error_code& ecode, std::size_t bytes_transferred)
	{
		if (ecode)
			Terminate ();
		else
		{
			m_PayloadLen = bufbe32toh (m_Header + I2CP_HEADER_LENGTH_OFFSET);
			if (m_PayloadLen > 0)
			{
				if (m_PayloadLen <= I2CP_MAX_MESSAGE_LENGTH)
				{
					if (!m_Socket) return;
					boost::system::error_code ec;
					size_t moreBytes = m_Socket->available(ec);
					if (!ec)
					{	
						if (moreBytes >= m_PayloadLen)
						{
							// read and process payload immediately if available
							moreBytes = boost::asio::read (*m_Socket, boost::asio::buffer(m_Payload, m_PayloadLen), boost::asio::transfer_all (), ec);
							HandleReceivedPayload (ec, moreBytes);
						}	
						else	
							ReceivePayload ();
					}	
					else
					{
						LogPrint (eLogWarning, "I2CP: Socket error: ", ec.message ());
						Terminate ();
					}	
				}	
				else
				{
					LogPrint (eLogError, "I2CP: Unexpected payload length ", m_PayloadLen);
					Terminate ();
				}
			}
			else // no following payload
			{
				HandleMessage ();
				ReceiveHeader (); // next message
			}
		}
	}

	void I2CPSession::ReceivePayload ()
	{
		if (!m_Socket)
		{
			LogPrint (eLogError, "I2CP: Can't receive payload");
			return;
		}
		boost::asio::async_read (*m_Socket, boost::asio::buffer (m_Payload, m_PayloadLen),
			boost::asio::transfer_all (),
			std::bind (&I2CPSession::HandleReceivedPayload, shared_from_this (), std::placeholders::_1, std::placeholders::_2));
	}

	void I2CPSession::HandleReceivedPayload (const boost::system::error_code& ecode, std::size_t bytes_transferred)
	{
		if (ecode)
			Terminate ();
		else
		{
			HandleMessage ();
			m_PayloadLen = 0;
			ReceiveHeader (); // next message
		}
	}

	void I2CPSession::HandleMessage ()
	{
		auto handler = m_Owner.GetMessagesHandlers ()[m_Header[I2CP_HEADER_TYPE_OFFSET]];
		if (handler)
			(this->*handler)(m_Payload, m_PayloadLen);
		else
			LogPrint (eLogError, "I2CP: Unknown I2CP message ", (int)m_Header[I2CP_HEADER_TYPE_OFFSET]);
	}

	void I2CPSession::Terminate ()
	{
		if (m_Destination)
		{
			m_Destination->Stop ();
			m_Destination = nullptr;
		}
		if (m_Socket)
		{
			m_Socket->close ();
			m_Socket = nullptr;
		}
		if (!m_SendQueue.IsEmpty ())
			m_SendQueue.CleanUp ();
		if (m_SessionID != 0xFFFF)
		{
			m_Owner.RemoveSession (GetSessionID ());
			LogPrint (eLogDebug, "I2CP: Session ", m_SessionID, " terminated");
			m_SessionID = 0xFFFF;
		}
	}

	void I2CPSession::SendI2CPMessage (uint8_t type, const uint8_t * payload, size_t len)
	{
		auto l = len + I2CP_HEADER_SIZE;
		if (l > I2CP_MAX_MESSAGE_LENGTH)
		{
			LogPrint (eLogError, "I2CP: Message to send is too long ", l);
			return;
		}
		auto sendBuf = m_IsSending ? std::make_shared<i2p::stream::SendBuffer> (l) : nullptr;
		uint8_t * buf = sendBuf ? sendBuf->buf : m_SendBuffer;
		htobe32buf (buf + I2CP_HEADER_LENGTH_OFFSET, len);
		buf[I2CP_HEADER_TYPE_OFFSET] = type;
		memcpy (buf + I2CP_HEADER_SIZE, payload, len);
		if (sendBuf)
		{
			if (m_SendQueue.GetSize () < I2CP_MAX_SEND_QUEUE_SIZE)
				m_SendQueue.Add (std::move(sendBuf));
			else
			{
				LogPrint (eLogWarning, "I2CP: Send queue size exceeds ", I2CP_MAX_SEND_QUEUE_SIZE);
				return;
			}
		}
		else
		{
			auto socket = m_Socket;
			if (socket)
			{
				m_IsSending = true;
				boost::asio::async_write (*socket, boost::asio::buffer (m_SendBuffer, l),
					boost::asio::transfer_all (), std::bind(&I2CPSession::HandleI2CPMessageSent,
					shared_from_this (), std::placeholders::_1, std::placeholders::_2));
			}
		}
	}

	void I2CPSession::HandleI2CPMessageSent (const boost::system::error_code& ecode, std::size_t bytes_transferred)
	{
		if (ecode)
		{
			if (ecode != boost::asio::error::operation_aborted)
				Terminate ();
		}
		else if (!m_SendQueue.IsEmpty ())
		{
			auto socket = m_Socket;
			if (socket)
			{
				auto len = m_SendQueue.Get (m_SendBuffer, I2CP_MAX_MESSAGE_LENGTH);
				boost::asio::async_write (*socket, boost::asio::buffer (m_SendBuffer, len),
					boost::asio::transfer_all (),std::bind(&I2CPSession::HandleI2CPMessageSent,
					shared_from_this (), std::placeholders::_1, std::placeholders::_2));
			}
			else
				m_IsSending = false;
		}
		else
			m_IsSending = false;
	}

	std::string_view I2CPSession::ExtractString (const uint8_t * buf, size_t len) const
	{
		uint8_t l = buf[0];
		if (l > len) l = len;
		return { (const char *)(buf + 1), l };
	}

	size_t I2CPSession::PutString (uint8_t * buf, size_t len, std::string_view str)
	{
		auto l = str.length ();
		if (l + 1 >= len) l = len - 1;
		if (l > 255) l = 255; // 1 byte max
		buf[0] = l;
		memcpy (buf + 1, str.data (), l);
		return l + 1;
	}

	void I2CPSession::ExtractMapping (const uint8_t * buf, size_t len, std::map<std::string, std::string>& mapping) const
	// TODO: move to Base.cpp
	{
		size_t offset = 0;
		while (offset < len)
		{
			auto param = ExtractString (buf + offset, len - offset);
			offset += param.length () + 1;
			if (buf[offset] != '=')
			{
				LogPrint (eLogWarning, "I2CP: Unexpected character ", buf[offset], " instead '=' after ", param);
				break;
			}
			offset++;

			auto value = ExtractString (buf + offset, len - offset);
			offset += value.length () + 1;
			if (buf[offset] != ';')
			{
				LogPrint (eLogWarning, "I2CP: Unexpected character ", buf[offset], " instead ';' after ", value);
				break;
			}
			offset++;
			mapping.emplace (param, value);
		}
	}

	void I2CPSession::GetDateMessageHandler (const uint8_t * buf, size_t len)
	{
		constexpr std::string_view version(I2P_VERSION);
		std::array<uint8_t, version.size() + 8 + 1> payload;
		// set date
		auto ts = i2p::util::GetMillisecondsSinceEpoch ();
		htobe64buf (payload.data(), ts);
		// send our version back
		PutString (payload.data() + 8, payload.size() - 8, version);
		SendI2CPMessage (I2CP_SET_DATE_MESSAGE, payload.data(), payload.size());
	}

	void I2CPSession::CreateSessionMessageHandler (const uint8_t * buf, size_t len)
	{
		RAND_bytes ((uint8_t *)&m_SessionID, 2);
		auto identity = std::make_shared<i2p::data::IdentityEx>();
		size_t offset = identity->FromBuffer (buf, len);
		if (!offset)
		{
			LogPrint (eLogError, "I2CP: Create session malformed identity");
			SendSessionStatusMessage (eI2CPSessionStatusInvalid); // invalid
			return;
		}
		if (m_Owner.FindSessionByIdentHash (identity->GetIdentHash ()))
		{
			LogPrint (eLogError, "I2CP: Create session duplicate address ", identity->GetIdentHash ().ToBase32 ());
			SendSessionStatusMessage (eI2CPSessionStatusInvalid); // invalid
			return;
		}
		uint16_t optionsSize = bufbe16toh (buf + offset);
		offset += 2;
		if (optionsSize > len - offset)
		{
			LogPrint (eLogError, "I2CP: Options size ", optionsSize, "exceeds message size");
			SendSessionStatusMessage (eI2CPSessionStatusInvalid); // invalid
			return;
		}
		std::map<std::string, std::string> params;
		ExtractMapping (buf + offset, optionsSize, params);
		offset += optionsSize; // options
		if (params[I2CP_PARAM_MESSAGE_RELIABILITY] == "none") m_IsSendAccepted = false;

		offset += 8; // date
		if (identity->Verify (buf, offset, buf + offset)) // signature
		{
			if (!m_Destination)
			{
				m_Destination = m_Owner.IsSingleThread () ?
					std::make_shared<I2CPDestination>(m_Owner.GetService (), shared_from_this (), identity, true, true, params):
					std::make_shared<RunnableI2CPDestination>(shared_from_this (), identity, true, params);
				if (m_Owner.InsertSession (shared_from_this ()))
				{
					LogPrint (eLogDebug, "I2CP: Session ", m_SessionID, " created");
					m_Destination->Start ();
					SendSessionStatusMessage (eI2CPSessionStatusCreated); // created
				}
				else
				{
					LogPrint (eLogError, "I2CP: Session already exists");
					SendSessionStatusMessage (eI2CPSessionStatusRefused);
				}
			}
			else
			{
				LogPrint (eLogError, "I2CP: Session already exists");
				SendSessionStatusMessage (eI2CPSessionStatusRefused); // refused
			}
		}
		else
		{
			LogPrint (eLogError, "I2CP: Create session signature verification failed");
			SendSessionStatusMessage (eI2CPSessionStatusInvalid); // invalid
		}
	}
	
	void I2CPSession::DestroySessionMessageHandler (const uint8_t * buf, size_t len)
	{
		SendSessionStatusMessage (eI2CPSessionStatusDestroyed); // destroy
		LogPrint (eLogDebug, "I2CP: Session ", m_SessionID, " destroyed");
		Terminate ();
	}

	void I2CPSession::ReconfigureSessionMessageHandler (const uint8_t * buf, size_t len)
	{
		I2CPSessionStatus status = eI2CPSessionStatusInvalid; // rejected
		if(len > sizeof(uint16_t))
		{
			uint16_t sessionID = bufbe16toh(buf);
			if(sessionID == m_SessionID)
			{
				buf += sizeof(uint16_t);
				const uint8_t * body = buf;
				i2p::data::IdentityEx ident;
				if(ident.FromBuffer(buf, len - sizeof(uint16_t)))
				{
					if (ident == *m_Destination->GetIdentity())
					{
						size_t identsz = ident.GetFullLen();
						buf += identsz;
						uint16_t optssize = bufbe16toh(buf);
						if (optssize <= len - sizeof(uint16_t) - sizeof(uint64_t) - identsz - ident.GetSignatureLen() - sizeof(uint16_t))
						{
							buf += sizeof(uint16_t);
							std::map<std::string, std::string> opts;
							ExtractMapping(buf, optssize, opts);
							buf += optssize;
							//uint64_t date = bufbe64toh(buf);
							buf += sizeof(uint64_t);
							const uint8_t * sig = buf;
							if(ident.Verify(body, len - sizeof(uint16_t) - ident.GetSignatureLen(), sig))
							{
								if(m_Destination->Reconfigure(opts))
								{
									LogPrint(eLogInfo, "I2CP: Reconfigured destination");
									status = eI2CPSessionStatusUpdated; // updated
								}
								else
									LogPrint(eLogWarning, "I2CP: Failed to reconfigure destination");
							}
							else
								LogPrint(eLogError, "I2CP: Invalid reconfigure message signature");
						}
						else
							LogPrint(eLogError, "I2CP: Mapping size mismatch");
					}
					else
						LogPrint(eLogError, "I2CP: Destination mismatch");
				}
				else
					LogPrint(eLogError, "I2CP: Malfromed destination");
			}
			else
				LogPrint(eLogError, "I2CP: Session mismatch");
		}
		else
			LogPrint(eLogError, "I2CP: Short message");
		SendSessionStatusMessage (status);
	}

	void I2CPSession::SendSessionStatusMessage (I2CPSessionStatus status)
	{
		uint8_t buf[3];
		htobe16buf (buf, m_SessionID);
		buf[2] = (uint8_t)status;
		SendI2CPMessage (I2CP_SESSION_STATUS_MESSAGE, buf, 3);
	}

	void I2CPSession::SendMessageStatusMessage (uint32_t nonce, I2CPMessageStatus status)
	{
		if (!nonce) return; // don't send status with zero nonce
		uint8_t buf[15];
		htobe16buf (buf, m_SessionID);
		htobe32buf (buf + 2, m_MessageID++);
		buf[6] = (uint8_t)status;
		memset (buf + 7, 0, 4); // size
		htobe32buf (buf + 11, nonce);
		SendI2CPMessage (I2CP_MESSAGE_STATUS_MESSAGE, buf, 15);
	}

	void I2CPSession::AddRoutingSession (const i2p::data::IdentHash& signingKey, std::shared_ptr<i2p::garlic::GarlicRoutingSession> remoteSession)
	{
		if (!remoteSession) return;
		remoteSession->SetAckRequestInterval (I2CP_SESSION_ACK_REQUEST_INTERVAL);
		std::lock_guard<std::mutex> l(m_RoutingSessionsMutex);
		m_RoutingSessions[signingKey] = remoteSession;
	}

	void I2CPSession::CleanupRoutingSessions ()
	{
		std::lock_guard<std::mutex> l(m_RoutingSessionsMutex);
		for (auto it = m_RoutingSessions.begin (); it != m_RoutingSessions.end ();)
		{
			if (it->second->IsTerminated ())
				it = m_RoutingSessions.erase (it);
			else	
				it++;
		}	
	}	
		
	void I2CPSession::CreateLeaseSetMessageHandler (const uint8_t * buf, size_t len)
	{
		uint16_t sessionID = bufbe16toh (buf);
		if (sessionID == m_SessionID)
		{
			size_t offset = 2;
			if (m_Destination)
			{
				offset += i2p::crypto::DSA_PRIVATE_KEY_LENGTH; // skip signing private key
				// we always assume this field as 20 bytes (DSA) regardless actual size
				// instead of
				//offset += m_Destination->GetIdentity ()->GetSigningPrivateKeyLen ();
				m_Destination->SetEncryptionPrivateKey (i2p::data::CRYPTO_KEY_TYPE_ELGAMAL, buf + offset);
				offset += 256;
				m_Destination->LeaseSetCreated (buf + offset, len - offset);
			}
		}
		else
			LogPrint (eLogError, "I2CP: Unexpected sessionID ", sessionID);
	}

	void I2CPSession::CreateLeaseSet2MessageHandler (const uint8_t * buf, size_t len)
	{
		uint16_t sessionID = bufbe16toh (buf);
		if (sessionID == m_SessionID)
		{
			size_t offset = 2;
			if (m_Destination)
			{
				uint8_t storeType = buf[offset]; offset++; // store type
				i2p::data::LeaseSet2 ls (storeType, buf + offset, len - offset); // outer layer only for encrypted
				if (!ls.IsValid ())
				{
					LogPrint (eLogError, "I2CP: Invalid LeaseSet2 of type ", storeType);
					return;
				}
				offset += ls.GetBufferLen ();
				// private keys
				int numPrivateKeys = buf[offset]; offset++;
				for (int i = 0; i < numPrivateKeys; i++)
				{
					if (offset + 4 > len) return;
					uint16_t keyType = bufbe16toh (buf + offset); offset += 2; // encryption type
					uint16_t keyLen = bufbe16toh (buf + offset); offset += 2; // private key length
					if (offset + keyLen > len) return;
					if (keyType >= i2p::data::CRYPTO_KEY_TYPE_ECIES_X25519_AEAD)
						m_Destination->SetECIESx25519EncryptionPrivateKey (keyType, buf + offset);
					else
						m_Destination->SetEncryptionPrivateKey (keyType, buf + offset); // from identity
					offset += keyLen;
				}

				m_Destination->LeaseSet2Created (storeType, ls.GetBuffer (), ls.GetBufferLen ());
			}
		}
		else
			LogPrint (eLogError, "I2CP: Unexpected sessionID ", sessionID);
	}

	void I2CPSession::SendMessageMessageHandler (const uint8_t * buf, size_t len)
	{
		uint16_t sessionID = bufbe16toh (buf);
		if (sessionID == m_SessionID)
		{
			size_t offset = 2;
			if (m_Destination)
			{
				const uint8_t * ident = buf + offset;
				size_t identSize = i2p::data::GetIdentityBufferLen (ident, len - offset);
				if (identSize)
				{
					offset += identSize;
					uint32_t payloadLen = bufbe32toh (buf + offset);
					if (payloadLen + offset <= len)
					{
						offset += 4;
						uint32_t nonce = bufbe32toh (buf + offset + payloadLen);
						if (m_Destination->IsReady ())
						{	
							if (m_IsSendAccepted)
								SendMessageStatusMessage (nonce, eI2CPMessageStatusAccepted); // accepted
							std::shared_ptr<i2p::garlic::GarlicRoutingSession> remoteSession;
							{
								std::lock_guard<std::mutex> l(m_RoutingSessionsMutex);
								auto it = m_RoutingSessions.find (ident + i2p::data::DEFAULT_IDENTITY_SIZE - 35); // 32 bytes signing key
								if (it != m_RoutingSessions.end ())
								{		
									if (!it->second->IsTerminated ())
										remoteSession = it->second;
									else
										m_RoutingSessions.erase (it);
								}
							}
							if (!remoteSession || !m_Destination->SendMsg (buf + offset, payloadLen, remoteSession, nonce))
							{	
								i2p::data::IdentHash identHash;
								SHA256(ident, identSize, identHash); // calculate ident hash, because we don't need full identity
								m_Destination->SendMsgTo (buf + offset, payloadLen, identHash, nonce);
							}	
						}
						else
						{
							LogPrint(eLogInfo, "I2CP: Destination is not ready");
							SendMessageStatusMessage (nonce, eI2CPMessageStatusNoLocalTunnels);
						}	
					}
					else
						LogPrint(eLogError, "I2CP: Cannot send message, too big");
				}
				else
					LogPrint(eLogError, "I2CP: Invalid identity");
			}
		}
		else
			LogPrint (eLogError, "I2CP: Unexpected sessionID ", sessionID);
	}

	void I2CPSession::SendMessageExpiresMessageHandler (const uint8_t * buf, size_t len)
	{
		SendMessageMessageHandler (buf, len - 8); // ignore flags(2) and expiration(6)
	}

	void I2CPSession::HostLookupMessageHandler (const uint8_t * buf, size_t len)
	{
		uint16_t sessionID = bufbe16toh (buf);
		if (sessionID == m_SessionID || sessionID == 0xFFFF) // -1 means without session
		{
			uint32_t requestID = bufbe32toh (buf + 2);
			//uint32_t timeout = bufbe32toh (buf + 6);
			i2p::data::IdentHash ident;
			switch (buf[10])
			{
				case 0: // hash
					ident = i2p::data::IdentHash (buf + 11);
				break;
				case 1: // address
				{
					auto name = ExtractString (buf + 11, len - 11);
					auto addr = i2p::client::context.GetAddressBook ().GetAddress (name);
					if (!addr || !addr->IsIdentHash ())
					{
						// TODO: handle blinded addresses
						LogPrint (eLogError, "I2CP: Address ", name, " not found");
						SendHostReplyMessage (requestID, nullptr);
						return;
					}
					else
						ident = addr->identHash;
					break;
				}
				default:
					LogPrint (eLogError, "I2CP: Request type ", (int)buf[10], " is not supported");
					SendHostReplyMessage (requestID, nullptr);
					return;
			}

			std::shared_ptr<LeaseSetDestination> destination = m_Destination;
			if(!destination) destination = i2p::client::context.GetSharedLocalDestination ();
			if (destination)
			{
				auto ls = destination->FindLeaseSet (ident);
				if (ls)
					SendHostReplyMessage (requestID, ls->GetIdentity ());
				else
				{
					auto s = shared_from_this ();
					destination->RequestDestination (ident,
						[s, requestID](std::shared_ptr<i2p::data::LeaseSet> leaseSet)
						{
							s->SendHostReplyMessage (requestID, leaseSet ? leaseSet->GetIdentity () : nullptr);
						});
				}
			}
			else
				SendHostReplyMessage (requestID, nullptr);
		}
		else
			LogPrint (eLogError, "I2CP: Unexpected sessionID ", sessionID);
	}

	void I2CPSession::SendHostReplyMessage (uint32_t requestID, std::shared_ptr<const i2p::data::IdentityEx> identity)
	{
		if (identity)
		{
			size_t l = identity->GetFullLen () + 7;
			uint8_t * buf = new uint8_t[l];
			htobe16buf (buf, m_SessionID);
			htobe32buf (buf + 2, requestID);
			buf[6] = 0; // result code
			identity->ToBuffer (buf + 7, l - 7);
			SendI2CPMessage (I2CP_HOST_REPLY_MESSAGE, buf, l);
			delete[] buf;
		}
		else
		{
			uint8_t buf[7];
			htobe16buf (buf, m_SessionID);
			htobe32buf (buf + 2, requestID);
			buf[6] = 1; // result code
			SendI2CPMessage (I2CP_HOST_REPLY_MESSAGE, buf, 7);
		}
	}

	void I2CPSession::DestLookupMessageHandler (const uint8_t * buf, size_t len)
	{
		if (m_Destination)
		{
			auto ls = m_Destination->FindLeaseSet (buf);
			if (ls)
			{
				auto l = ls->GetIdentity ()->GetFullLen ();
				uint8_t * identBuf = new uint8_t[l];
				ls->GetIdentity ()->ToBuffer (identBuf, l);
				SendI2CPMessage (I2CP_DEST_REPLY_MESSAGE, identBuf, l);
				delete[] identBuf;
			}
			else
			{
				auto s = shared_from_this ();
				i2p::data::IdentHash ident (buf);
				m_Destination->RequestDestination (ident,
					[s, ident](std::shared_ptr<i2p::data::LeaseSet> leaseSet)
					{
						if (leaseSet) // found
						{
							auto l = leaseSet->GetIdentity ()->GetFullLen ();
							uint8_t * identBuf = new uint8_t[l];
							leaseSet->GetIdentity ()->ToBuffer (identBuf, l);
							s->SendI2CPMessage (I2CP_DEST_REPLY_MESSAGE, identBuf, l);
							delete[] identBuf;
						}
						else
							s->SendI2CPMessage (I2CP_DEST_REPLY_MESSAGE, ident, 32); // not found
					});
			}
		}
		else
			SendI2CPMessage (I2CP_DEST_REPLY_MESSAGE, buf, 32);
	}

	void I2CPSession::GetBandwidthLimitsMessageHandler (const uint8_t * buf, size_t len)
	{
		uint8_t limits[64];
		memset (limits, 0, 64);
		uint32_t limit; i2p::config::GetOption("i2cp.inboundlimit", limit);
		if (!limit) limit = i2p::context.GetBandwidthLimit ();
		htobe32buf (limits, limit); // inbound
		i2p::config::GetOption("i2cp.outboundlimit", limit);
		if (!limit) limit = i2p::context.GetBandwidthLimit ();
		htobe32buf (limits + 4, limit); // outbound
		SendI2CPMessage (I2CP_BANDWIDTH_LIMITS_MESSAGE, limits, 64);
	}

	void I2CPSession::SendMessagePayloadMessage (const uint8_t * payload, size_t len)
	{
		// we don't use SendI2CPMessage to eliminate additional copy
		auto l = len + 10 + I2CP_HEADER_SIZE;
		if (l > I2CP_MAX_MESSAGE_LENGTH)
		{
			LogPrint (eLogError, "I2CP: Message to send is too long ", l);
			return;
		}
		auto sendBuf = m_IsSending ? std::make_shared<i2p::stream::SendBuffer> (l) : nullptr;
		uint8_t * buf = sendBuf ? sendBuf->buf : m_SendBuffer;
		htobe32buf (buf + I2CP_HEADER_LENGTH_OFFSET, len + 10);
		buf[I2CP_HEADER_TYPE_OFFSET] = I2CP_MESSAGE_PAYLOAD_MESSAGE;
		htobe16buf (buf + I2CP_HEADER_SIZE, m_SessionID);
		htobe32buf (buf + I2CP_HEADER_SIZE + 2, m_MessageID++);
		htobe32buf (buf + I2CP_HEADER_SIZE + 6, len);
		memcpy (buf + I2CP_HEADER_SIZE + 10, payload, len);
		if (sendBuf)
		{
			if (m_SendQueue.GetSize () < I2CP_MAX_SEND_QUEUE_SIZE)
				m_SendQueue.Add (std::move(sendBuf));
			else
			{
				LogPrint (eLogWarning, "I2CP: Send queue size exceeds ", I2CP_MAX_SEND_QUEUE_SIZE);
				return;
			}
		}
		else
		{
			auto socket = m_Socket;
			if (socket)
			{
				m_IsSending = true;
				boost::asio::async_write (*socket, boost::asio::buffer (m_SendBuffer, l),
					boost::asio::transfer_all (), std::bind(&I2CPSession::HandleI2CPMessageSent,
					shared_from_this (), std::placeholders::_1, std::placeholders::_2));
			}
		}
	}

	I2CPServer::I2CPServer (const std::string& interface, uint16_t port, bool isSingleThread):
		RunnableService ("I2CP"), m_IsSingleThread (isSingleThread),
		m_Acceptor (GetIOService (),
		boost::asio::ip::tcp::endpoint(boost::asio::ip::make_address(interface), port))
	{
		memset (m_MessagesHandlers, 0, sizeof (m_MessagesHandlers));
		m_MessagesHandlers[I2CP_GET_DATE_MESSAGE] = &I2CPSession::GetDateMessageHandler;
		m_MessagesHandlers[I2CP_CREATE_SESSION_MESSAGE] = &I2CPSession::CreateSessionMessageHandler;
		m_MessagesHandlers[I2CP_DESTROY_SESSION_MESSAGE] = &I2CPSession::DestroySessionMessageHandler;
		m_MessagesHandlers[I2CP_RECONFIGURE_SESSION_MESSAGE] = &I2CPSession::ReconfigureSessionMessageHandler;
		m_MessagesHandlers[I2CP_CREATE_LEASESET_MESSAGE] = &I2CPSession::CreateLeaseSetMessageHandler;
		m_MessagesHandlers[I2CP_CREATE_LEASESET2_MESSAGE] = &I2CPSession::CreateLeaseSet2MessageHandler;
		m_MessagesHandlers[I2CP_SEND_MESSAGE_MESSAGE] = &I2CPSession::SendMessageMessageHandler;
		m_MessagesHandlers[I2CP_SEND_MESSAGE_EXPIRES_MESSAGE] = &I2CPSession::SendMessageExpiresMessageHandler;
		m_MessagesHandlers[I2CP_HOST_LOOKUP_MESSAGE] = &I2CPSession::HostLookupMessageHandler;
		m_MessagesHandlers[I2CP_DEST_LOOKUP_MESSAGE] = &I2CPSession::DestLookupMessageHandler;
		m_MessagesHandlers[I2CP_GET_BANDWIDTH_LIMITS_MESSAGE] = &I2CPSession::GetBandwidthLimitsMessageHandler;
	}

	I2CPServer::~I2CPServer ()
	{
		if (IsRunning ())
			Stop ();
	}

	void I2CPServer::Start ()
	{
		Accept ();
		StartIOService ();
	}

	void I2CPServer::Stop ()
	{
		m_Acceptor.cancel ();
		
		decltype(m_Sessions) sessions;
		m_Sessions.swap (sessions);
		for (auto& it: sessions)
			it.second->Stop ();
		
		StopIOService ();
	}

	void I2CPServer::Accept ()
	{
		auto newSocket = std::make_shared<boost::asio::ip::tcp::socket> (GetIOService ());
		m_Acceptor.async_accept (*newSocket, std::bind (&I2CPServer::HandleAccept, this,
			std::placeholders::_1, newSocket));
	}

	void I2CPServer::HandleAccept(const boost::system::error_code& ecode,
		std::shared_ptr<boost::asio::ip::tcp::socket> socket)
	{
		if (!ecode && socket)
		{
			boost::system::error_code ec;
			auto ep = socket->remote_endpoint (ec);
			if (!ec)
			{
				LogPrint (eLogDebug, "I2CP: New connection from ", ep);
				auto session = std::make_shared<I2CPSession>(*this, socket);
				session->Start ();
			}
			else
				LogPrint (eLogError, "I2CP: Incoming connection error ", ec.message ());
		}
		else
			LogPrint (eLogError, "I2CP: Accept error: ", ecode.message ());

		if (ecode != boost::asio::error::operation_aborted)
			Accept ();
	}

	bool I2CPServer::InsertSession (std::shared_ptr<I2CPSession> session)
	{
		if (!session) return false;
		if (!m_Sessions.insert({session->GetSessionID (), session}).second)
		{
			LogPrint (eLogError, "I2CP: Duplicate session id ", session->GetSessionID ());
			return false;
		}
		return true;
	}

	void I2CPServer::RemoveSession (uint16_t sessionID)
	{
		m_Sessions.erase (sessionID);
	}

	std::shared_ptr<I2CPSession> I2CPServer::FindSessionByIdentHash (const i2p::data::IdentHash& ident) const
	{
		for (const auto& it: m_Sessions)
		{
			if (it.second)
			{
				auto dest = it.second->GetDestination ();
				if (dest && dest->GetIdentHash () == ident)
					return it.second;
			}
		}
		return nullptr;
	}
}
}