-
Notifications
You must be signed in to change notification settings - Fork 16
/
i2psam.cpp
1351 lines (1176 loc) · 41.9 KB
/
i2psam.cpp
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
/**
* Copyright (c) 2019-2022 polistern
* Copyright (c) 2017 The I2P Project
* Copyright (c) 2013-2015 The Anoncoin Core developers
* Copyright (c) 2012-2013 giv
*
* Distributed under the MIT software license, see the accompanying
* file LICENSE or http://www.opensource.org/licenses/mit-license.php.
*
* See full documentation about SAM at http://www.i2p2.i2p/samv3.html
*/
#include <ctime>
#include <cstdlib>
#include <cstring>
#include "i2psam.h"
#define PORT_ZERO 0
#define I2P_MIN_DESTINATION_SIZE 521
namespace SAM
{
#ifdef WIN32
int I2pSocket::instances_ = 0;
void I2pSocket::initWSA()
{
WSADATA wsadata;
int ret = WSAStartup(MAKEWORD(2, 2), &wsadata);
if (ret != NO_ERROR)
print_error("Failed to initialize winsock library");
}
void I2pSocket::freeWSA()
{
WSACleanup();
}
#endif // WIN32
I2pSocket::I2pSocket(const std::string &SAMHost, uint16_t SAMPort)
: socket_(INVALID_SOCKET), SAMHost_(SAMHost), SAMPort_(SAMPort) {
#ifdef WIN32
if (instances_++ == 0)
initWSA();
#endif // WIN32
memset(&servAddr_, 0, sizeof(servAddr_));
servAddr_.sin_family = AF_INET;
servAddr_.sin_addr.s_addr = inet_addr(SAMHost.c_str());
servAddr_.sin_port = htons(SAMPort);
bootstrapI2P();
}
I2pSocket::I2pSocket(const sockaddr_in &addr)
: socket_(INVALID_SOCKET), servAddr_(addr)
{
#ifdef WIN32
if (instances_++ == 0)
initWSA();
#endif // WIN32
bootstrapI2P();
}
I2pSocket::I2pSocket(const I2pSocket &rhs)
: socket_(INVALID_SOCKET), servAddr_(rhs.servAddr_)
{
#ifdef WIN32
if (instances_++ == 0)
initWSA();
#endif // WIN32
bootstrapI2P();
}
I2pSocket::~I2pSocket()
{
close();
#ifdef WIN32
if (--instances_ == 0)
freeWSA();
#endif // WIN32
}
void I2pSocket::bootstrapI2P()
{
init();
if (isOk())
handshake();
}
void I2pSocket::init()
{
/**
* Here is where the only real OS socket is called for creation to talk with the router,
* the value returned is stored in our variable socket_ which holds the connection
* to our stream for everything else
*/
socket_ = socket(AF_INET, SOCK_STREAM, 0);
if (socket_ == INVALID_SOCKET)
{
print_error("Failed to create socket");
return;
}
if (connect(socket_, (const sockaddr *) &servAddr_, sizeof(servAddr_)) == SOCKET_ERROR)
{
close();
print_error("Failed to connect to SAM");
return;
}
}
SOCKET I2pSocket::release()
{
SOCKET temp = socket_;
socket_ = INVALID_SOCKET;
return temp;
}
// If the handshake works, we're talking to a valid I2P router.
void I2pSocket::handshake()
{
this->write(Message::hello(minVer_, maxVer_));
const std::string answer = this->read();
const Message::eStatus answerStatus = Message::checkAnswer(answer);
if (answerStatus == Message::OK)
version_ = Message::getValue(answer, "VERSION");
else
print_error("Handshake failed");
}
void I2pSocket::write(const std::string &msg)
{
if (!isOk())
{
print_error("Failed to send data because socket is closed");
return;
}
#ifdef DEBUG_ON_STDOUT
std::cout << "Send: " << msg << std::endl;
#endif // DEBUG_ON_STDOUT
ssize_t sentBytes = send(socket_, msg.c_str(), msg.length(), 0);
if (sentBytes == SOCKET_ERROR)
{
close();
print_error("Failed to send data");
return;
}
if (sentBytes == 0)
{
close();
print_error("I2pSocket was closed");
return;
}
}
std::string I2pSocket::read()
{
if (!isOk())
{
print_error("Failed to read data because socket is closed");
return std::string();
}
char buffer[SAM_BUFSIZE];
memset(buffer, 0, SAM_BUFSIZE);
ssize_t recievedBytes = recv(socket_, buffer, SAM_BUFSIZE, 0);
if (recievedBytes == SOCKET_ERROR)
{
close();
print_error("Failed to receive data");
return std::string();
}
if (recievedBytes == 0)
{
close();
print_error("I2pSocket was closed");
}
#ifdef DEBUG_ON_STDOUT
std::cout << "Reply: " << buffer << std::endl;
#endif // DEBUG_ON_STDOUT
return std::string(buffer);
}
void I2pSocket::close()
{
if (socket_ != INVALID_SOCKET)
{
#ifdef WIN32
::closesocket(socket_);
#else
::close(socket_);
#endif // WIN32
socket_ = INVALID_SOCKET;
}
}
bool I2pSocket::isOk() const { return socket_ != INVALID_SOCKET; }
const std::string &I2pSocket::getHost() const { return SAMHost_; }
uint16_t I2pSocket::getPort() const { return SAMPort_; }
const std::string &I2pSocket::getVersion() const { return version_; }
const sockaddr_in &I2pSocket::getAddress() const { return servAddr_; }
//-----------------------------------------------------------------------------
SAMSession::SAMSession(
const std::string &nickname,
const std::string &SAMHost /*= SAM_DEFAULT_ADDRESS*/,
uint16_t SAMPort /*= SAM_DEFAULT_PORT_TCP*/,
const std::string &i2pOptions /*= SAM_DEFAULT_I2P_OPTIONS*/,
const std::string &signatureType /*= SAM_SIGNATURE_TYPE */)
: socket_(SAMHost, SAMPort),
nickname_(nickname),
sessionID_(generateSessionID()),
i2pOptions_(i2pOptions),
isSick_(false)
{
#ifdef DEBUG_ON_STDOUT
std::cout << "Created a brand new SAM stream session (" << sessionID_ << ")" << std::endl;
#endif // DEBUG_ON_STDOUT
}
SAMSession::SAMSession(SAMSession& rhs)
: socket_(rhs.socket_),
nickname_(rhs.nickname_),
sessionID_(generateSessionID()),
myDestination_(rhs.myDestination_),
i2pOptions_(rhs.i2pOptions_),
isSick_(false)
{
rhs.fallSick();
rhs.socket_.close();
#ifdef DEBUG_ON_STDOUT
std::cout << "Created a new SAM session (" << sessionID_ << ") from another (" << rhs.sessionID_ << ")" << std::endl;
#endif // DEBUG_ON_STDOUT
}
/*static*/
std::string SAMSession::generateSessionID()
{
static const int minSessionIDLength = 5;
static const int maxSessionIDLength = 9;
static const char sessionIDAlphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
int length = minSessionIDLength - 1;
std::string result;
srand(time(nullptr));
while (length < minSessionIDLength)
length = rand() % maxSessionIDLength;
while (length-- > 0)
result += sessionIDAlphabet[rand() % (sizeof(sessionIDAlphabet) - 1)];
#ifdef DEBUG_ON_STDOUT
std::cout << "Generated session ID: " << result << std::endl;
#endif // DEBUG_ON_STDOUT
return result;
}
RequestResult<const std::string> SAMSession::namingLookup(const std::string &name) const
{
typedef RequestResult<const std::string> ResultType;
typedef Message::Answer<const std::string> AnswerType;
std::unique_ptr<I2pSocket> newSocket(new I2pSocket(socket_));
const AnswerType answer = namingLookup(*newSocket, name);
switch (answer.status)
{
case Message::OK:
return ResultType(answer.value);
case Message::EMPTY_ANSWER:
case Message::CLOSED_SOCKET:
fallSick();
break;
default:
break;
}
return ResultType();
}
RequestResult<const FullDestination> SAMSession::destGenerate() const
{
typedef RequestResult<const FullDestination> ResultType;
typedef Message::Answer<const FullDestination> AnswerType;
std::unique_ptr<I2pSocket> newSocket(new I2pSocket(socket_));
const AnswerType answer = destGenerate(*newSocket);
switch (answer.status)
{
case Message::OK:
return ResultType(answer.value);
case Message::EMPTY_ANSWER:
case Message::CLOSED_SOCKET:
fallSick();
break;
default:
break;
}
return ResultType();
}
FullDestination SAMSession::createSession(const std::string& destination)
{
return createSession(destination, SAM_SIGNATURE_TYPE);
}
FullDestination SAMSession::createSession(const std::string& destination, const std::string& sigType)
{
return createSession(destination, sigType, i2pOptions_);
}
void SAMSession::fallSick() const { isSick_ = true; }
/*static*/
Message::Answer<const std::string> SAMSession::rawRequest(I2pSocket &socket, const std::string &requestStr)
{
typedef Message::Answer<const std::string> AnswerType;
if (!socket.isOk())
return AnswerType(Message::CLOSED_SOCKET);
socket.write(requestStr);
const std::string answer = socket.read();
const Message::eStatus status = Message::checkAnswer(answer);
return AnswerType(status, answer);
}
/*static*/
Message::Answer<const std::string> SAMSession::request(I2pSocket &socket,
const std::string &requestStr,
const std::string &keyOnSuccess)
{
typedef Message::Answer<const std::string> AnswerType;
const AnswerType answer = rawRequest(socket, requestStr);
return (answer.status == Message::OK) ? AnswerType(answer.status, Message::getValue(answer.value, keyOnSuccess))
: answer;
}
/*static*/
Message::eStatus SAMSession::request(I2pSocket &socket, const std::string &requestStr)
{
return rawRequest(socket, requestStr).status;
}
/*static*/
Message::Answer<const std::string> SAMSession::namingLookup(I2pSocket &socket, const std::string &name)
{
return request(socket, Message::namingLookup(name), "VALUE");
}
/*static*/
Message::Answer<const FullDestination> SAMSession::destGenerate(I2pSocket &socket)
{
// while answer for a DEST GENERATE request doesn't contain a "RESULT" field we parse it manually
typedef Message::Answer<const FullDestination> ResultType;
if (!socket.isOk())
return ResultType(Message::CLOSED_SOCKET, FullDestination());
socket.write(Message::destGenerate());
const std::string answer = socket.read();
const std::string pub = Message::getValue(answer, "PUB");
const std::string priv = Message::getValue(answer, "PRIV");
return (!pub.empty() && !priv.empty()) ? ResultType(Message::OK, FullDestination(pub, priv, /*isGenerated*/ true))
: ResultType(Message::EMPTY_ANSWER, FullDestination());
}
const std::string &SAMSession::getNickname() const
{
#ifdef DEBUG_ON_STDOUT
std::cout << "getNickname: " << nickname_ << std::endl;
#endif // DEBUG_ON_STDOUT
return nickname_;
}
const std::string &SAMSession::getSessionID() const
{
#ifdef DEBUG_ON_STDOUT
std::cout << "getSessionID: " << sessionID_ << std::endl;
#endif // DEBUG_ON_STDOUT
return sessionID_;
}
const std::string &SAMSession::getOptions() const
{
#ifdef DEBUG_ON_STDOUT
std::cout << "getOptions: " << i2pOptions_ << std::endl;
#endif // DEBUG_ON_STDOUT
return i2pOptions_;
}
const FullDestination &SAMSession::getMyDestination() const
{
#ifdef DEBUG_ON_STDOUT
std::cout << "getMyDestination: " << myDestination_.priv << std::endl;
#endif // DEBUG_ON_STDOUT
return myDestination_;
}
bool SAMSession::isSick() const
{
#ifdef DEBUG_ON_STDOUT
std::cout << "isSick: " << isSick_ << std::endl;
#endif // DEBUG_ON_STDOUT
return isSick_;
}
const sockaddr_in &SAMSession::getSAMAddress() const
{
#ifdef DEBUG_ON_STDOUT
// std::cout << "getSAMAddress: " << socket_.getAddress() << std::endl;
std::cout << "getSAMAddress: not yet parsed" << std::endl;
#endif // DEBUG_ON_STDOUT
return socket_.getAddress();
}
const std::string &SAMSession::getSAMHost() const
{
#ifdef DEBUG_ON_STDOUT
std::cout << "getSAMHost: " << socket_.getHost() << std::endl;
#endif // DEBUG_ON_STDOUT
return socket_.getHost();
}
uint16_t SAMSession::getSAMPort() const
{
#ifdef DEBUG_ON_STDOUT
std::cout << "getSAMPort: " << socket_.getPort() << std::endl;
#endif // DEBUG_ON_STDOUT
return socket_.getPort();
}
const std::string &SAMSession::getSAMVersion() const
{
#ifdef DEBUG_ON_STDOUT
std::cout << "getSAMVersion: " << socket_.getVersion() << std::endl;
#endif // DEBUG_ON_STDOUT
return socket_.getVersion();
}
const std::string &SAMSession::getSAMMinVer() const { return socket_.minVer_; }
const std::string &SAMSession::getSAMMaxVer() const { return socket_.maxVer_; }
//-----------------------------------------------------------------------------
StreamSession::StreamSession(
const std::string &nickname,
const std::string &SAMHost /*= SAM_DEFAULT_ADDRESS*/,
uint16_t SAMPort /*= SAM_DEFAULT_PORT_TCP*/,
const std::string &destination /*= SAM_GENERATE_MY_DESTINATION*/,
const std::string &i2pOptions /*= SAM_DEFAULT_I2P_OPTIONS*/,
const std::string &signatureType /*= SAM_SIGNATURE_TYPE */)
: SAMSession(nickname, SAMHost, SAMPort, i2pOptions, signatureType)
{
myDestination_ = createStreamSession(destination);
#ifdef DEBUG_ON_STDOUT
std::cout << "Created a brand new SAM stream session (" << sessionID_ << ")" << std::endl;
#endif // DEBUG_ON_STDOUT
}
StreamSession::StreamSession(StreamSession &rhs)
: SAMSession(rhs)
{
rhs.fallSick();
rhs.socket_.close();
(void) createStreamSession(myDestination_.priv);
for (const auto &forwardedStream : rhs.forwardedStreams_)
forward(forwardedStream.host, forwardedStream.port, forwardedStream.silent);
#ifdef DEBUG_ON_STDOUT
std::cout << "Created a new SAM stream session (" << sessionID_ << ") from another (" << rhs.sessionID_ << ")" << std::endl;
#endif // DEBUG_ON_STDOUT
}
StreamSession::~StreamSession()
{
stopForwardingAll();
#ifdef DEBUG_ON_STDOUT
std::cout << "Closing SAM stream session (" << sessionID_ << ") ..." << std::endl;
#endif // DEBUG_ON_STDOUT
}
RequestResult<std::unique_ptr<I2pSocket>> StreamSession::accept(bool silent)
{
typedef RequestResult<std::unique_ptr<I2pSocket>> ResultType;
std::unique_ptr<I2pSocket> streamSocket(new I2pSocket(socket_));
const Message::eStatus status = accept(*streamSocket, sessionID_, silent);
switch (status)
{
case Message::OK:
return ResultType(std::move(streamSocket));
case Message::EMPTY_ANSWER:
case Message::CLOSED_SOCKET:
case Message::INVALID_ID:
case Message::I2P_ERROR:
fallSick();
break;
default:
break;
}
return ResultType();
}
RequestResult<std::unique_ptr<I2pSocket>> StreamSession::connect(const std::string &destination, bool silent)
{
typedef RequestResult<std::unique_ptr<I2pSocket>> ResultType;
std::unique_ptr<I2pSocket> streamSocket(new I2pSocket(socket_));
const Message::eStatus status = connect(*streamSocket, sessionID_, destination, silent);
if (silent)
return ResultType(std::move(streamSocket));
switch (status)
{
case Message::OK:
return ResultType(std::move(streamSocket));
case Message::EMPTY_ANSWER:
case Message::CLOSED_SOCKET:
case Message::INVALID_ID:
case Message::I2P_ERROR:
fallSick();
break;
default:
break;
}
return ResultType();
}
RequestResult<void> StreamSession::forward(const std::string &host, uint16_t port, bool silent)
{
typedef RequestResult<void> ResultType;
std::unique_ptr<I2pSocket> newSocket(new I2pSocket(socket_));
const Message::eStatus status = forward(*newSocket, sessionID_, host, port, silent);
switch (status)
{
case Message::OK:
forwardedStreams_.push_back(ForwardedStream(newSocket.get(), host, port, silent));
newSocket.release(); // release after successful push_back only
return ResultType(true);
case Message::EMPTY_ANSWER:
case Message::CLOSED_SOCKET:
case Message::INVALID_ID:
case Message::I2P_ERROR:
fallSick();
break;
default:
break;
}
return ResultType();
}
FullDestination StreamSession::createStreamSession(const std::string &destination)
{
return createStreamSession(destination, SAM_SIGNATURE_TYPE);
}
FullDestination StreamSession::createStreamSession(const std::string& destination, const std::string& sigType)
{
return createStreamSession(destination, sigType, i2pOptions_);
}
FullDestination StreamSession::createStreamSession(const std::string& destination, const std::string& sigType, const std::string& i2pOptions)
{
typedef Message::Answer<const std::string> AnswerType;
const AnswerType
answer = createStreamSession(socket_, sessionID_, nickname_, destination, i2pOptions, sigType);
if (answer.status != Message::OK)
{
fallSick();
return FullDestination();
}
return FullDestination(answer.value.c_str(), answer.value, (destination == SAM_GENERATE_MY_DESTINATION));
}
FullDestination StreamSession::createSession(const std::string& destination, const std::string& sigType, const std::string& i2pOptions)
{
typedef Message::Answer<const std::string> AnswerType;
const AnswerType
answer = createStreamSession(socket_, sessionID_, nickname_, destination, i2pOptions, sigType);
if (answer.status != Message::OK)
{
fallSick();
return FullDestination();
}
return FullDestination(answer.value.c_str(), answer.value, (destination == SAM_GENERATE_MY_DESTINATION));
}
void StreamSession::stopForwarding(const std::string &host, uint16_t port)
{
for (auto it = forwardedStreams_.begin(); it != forwardedStreams_.end();)
{
if (it->port == port && it->host == host)
{
delete (it->socket);
it = forwardedStreams_.erase(it);
}
else
++it;
}
}
void StreamSession::stopForwardingAll()
{
for (auto &forwardedStream : forwardedStreams_)
delete (forwardedStream.socket);
forwardedStreams_.clear();
socket_.close();
}
/*static*/
Message::Answer<const std::string> StreamSession::createStreamSession(I2pSocket &socket,
const std::string &sessionID,
const std::string &nickname,
const std::string &destination,
const std::string &options,
const std::string &signatureType)
{
return request(socket,
Message::sessionCreate(Message::sssStream, sessionID, nickname, destination, options, signatureType),
"DESTINATION");
}
/*static*/
Message::eStatus StreamSession::accept(I2pSocket &socket, const std::string &sessionID, bool silent)
{
return request(socket, Message::streamAccept(sessionID, silent));
}
/*static*/
Message::eStatus StreamSession::connect(I2pSocket &socket,
const std::string &sessionID,
const std::string &destination,
bool silent)
{
return request(socket, Message::streamConnect(sessionID, destination, silent));
}
/*static*/
Message::eStatus StreamSession::forward(I2pSocket &socket,
const std::string &sessionID,
const std::string &host,
uint16_t port,
bool silent)
{
return request(socket, Message::streamForward(sessionID, host, port, silent));
}
//--------------------------------------------------------------------------------------------------
DatagramSession::DatagramSession(
const std::string &nickname,
const std::string &SAMHost /* = SAM_DEFAULT_ADDRESS*/,
uint16_t SAMPortTCP /*= SAM_DEFAULT_PORT_TCP*/,
uint16_t SAMPortUDP /*= SAM_DEFAULT_PORT_UDP*/,
const std::string &listenAddress /*= SAM_DEFAULT_ADDRESS*/,
uint16_t ClientPortUDP /*= SAM_DEFAULT_CLIENT_UDP*/,
const std::string &destination /*= SAM_GENERATE_MY_DESTINATION*/,
const std::string &i2pOptions /*= SAM_DEFAULT_I2P_OPTIONS*/,
const std::string &signatureType /*= SAM_SIGNATURE_TYPE*/)
: SAMSession(nickname, SAMHost, SAMPortTCP, i2pOptions, signatureType)
{
listenAddress_ = listenAddress;
listenPortUDP_ = ClientPortUDP;
SAMPortUDP_ = SAMPortUDP;
myDestination_ = createDatagramSession(destination);
#ifdef DEBUG_ON_STDOUT
std::cout << "Created a brand new SAM datagram session (" << sessionID_ << ")" << std::endl;
#endif // DEBUG_ON_STDOUT
}
DatagramSession::DatagramSession(DatagramSession &rhs)
: SAMSession(rhs),
listenAddress_(rhs.listenAddress_), listenPortUDP_(rhs.listenPortUDP_), SAMPortUDP_(rhs.SAMPortUDP_)
{
myDestination_ = rhs.myDestination_;
rhs.fallSick();
rhs.socket_.close();
(void) createDatagramSession(myDestination_.priv);
#ifdef DEBUG_ON_STDOUT
std::cout << "Created a new SAM datagram session (" << sessionID_ << ") from another (" << rhs.sessionID_ << ")" << std::endl;
#endif // DEBUG_ON_STDOUT
}
DatagramSession::~DatagramSession()
{
#ifdef DEBUG_ON_STDOUT
std::cout << "Closing SAM datagram session (" << sessionID_ << ") ..." << std::endl;
#endif // DEBUG_ON_STDOUT
}
FullDestination DatagramSession::createDatagramSession(const std::string& destination)
{
return createDatagramSession(destination, SAM_SIGNATURE_TYPE);
}
FullDestination DatagramSession::createDatagramSession(const std::string& destination, const std::string& sigType)
{
return createDatagramSession(destination, sigType, i2pOptions_);
}
FullDestination DatagramSession::createDatagramSession(const std::string& destination, const std::string& sigType, const std::string& i2pOptions)
{
typedef Message::Answer<const std::string> AnswerType;
const AnswerType answer = createDatagramSession(socket_, sessionID_, nickname_, listenPortUDP_, listenAddress_, destination, i2pOptions, sigType);
if (answer.status != Message::OK)
{
fallSick();
return FullDestination();
}
return FullDestination(answer.value.c_str(), answer.value, (destination == SAM_GENERATE_MY_DESTINATION));
}
FullDestination DatagramSession::createSession(const std::string& destination, const std::string& sigType, const std::string& i2pOptions)
{
typedef Message::Answer<const std::string> AnswerType;
const AnswerType answer = createDatagramSession(socket_, sessionID_, nickname_, listenPortUDP_, listenAddress_, destination, i2pOptions, sigType);
if (answer.status != Message::OK)
{
fallSick();
return FullDestination();
}
return FullDestination(answer.value.c_str(), answer.value, (destination == SAM_GENERATE_MY_DESTINATION));
}
/*static*/
Message::Answer<const std::string> DatagramSession::createDatagramSession(I2pSocket &socket,
const std::string &sessionID,
const std::string &nickname,
const uint16_t port,
const std::string &host,
const std::string &destination,
const std::string &options,
const std::string &signatureType)
{
return request(socket,
Message::sessionCreate(Message::sssDatagram,
sessionID,
nickname,
port,
host,
destination,
options,
signatureType),
"DESTINATION");
}
//--------------------------------------------------------------------------------------------------
RawSession::RawSession(
const std::string &nickname,
const std::string &SAMHost /* = SAM_DEFAULT_ADDRESS*/,
uint16_t SAMPortTCP /* = SAM_DEFAULT_PORT_TCP*/,
uint16_t SAMPortUDP /* = SAM_DEFAULT_PORT_UDP*/,
const std::string &listenAddress /* = SAM_DEFAULT_ADDRESS*/,
uint16_t ClientPortUDP /* = SAM_DEFAULT_CLIENT_UDP*/,
const std::string &destination /* = SAM_GENERATE_MY_DESTINATION*/,
const std::string &i2pOptions /* = SAM_DEFAULT_I2P_OPTIONS*/,
const std::string &signatureType /* = SAM_SIGNATURE_TYPE*/)
: SAMSession(nickname, SAMHost, SAMPortTCP, i2pOptions, signatureType),
listenAddress_(listenAddress), listenPortUDP_(ClientPortUDP), SAMPortUDP_(SAMPortUDP)
{
myDestination_ = createRawSession(destination);
#ifdef DEBUG_ON_STDOUT
std::cout << "Created a brand new SAM datagram session (" << sessionID_ << ")" << std::endl;
#endif // DEBUG_ON_STDOUT
}
RawSession::RawSession(RawSession &rhs)
: SAMSession(rhs),
listenAddress_(rhs.listenAddress_), listenPortUDP_(rhs.listenPortUDP_), SAMPortUDP_(rhs.SAMPortUDP_)
{
myDestination_ = rhs.myDestination_;
rhs.fallSick();
rhs.socket_.close();
(void) createRawSession(myDestination_.priv);
#ifdef DEBUG_ON_STDOUT
std::cout << "Created a new SAM datagram session (" << sessionID_ << ") from another (" << rhs.sessionID_ << ")" << std::endl;
#endif // DEBUG_ON_STDOUT
}
RawSession::~RawSession()
{
#ifdef DEBUG_ON_STDOUT
std::cout << "Closing SAM datagram session (" << sessionID_ << ") ..." << std::endl;
#endif // DEBUG_ON_STDOUT
}
FullDestination RawSession::createRawSession(const std::string& destination)
{
return createRawSession(destination, SAM_SIGNATURE_TYPE);
}
FullDestination RawSession::createRawSession(const std::string& destination, const std::string& sigType)
{
return createRawSession(destination, sigType, i2pOptions_);
}
FullDestination RawSession::createRawSession(const std::string& destination, const std::string& sigType, const std::string& i2pOptions)
{
typedef Message::Answer<const std::string> AnswerType;
const AnswerType answer = createRawSession(socket_, sessionID_, nickname_, listenPortUDP_, listenAddress_, destination, i2pOptions, sigType);
if (answer.status != Message::OK)
{
fallSick();
return FullDestination();
}
return FullDestination(answer.value.c_str(), answer.value, (destination == SAM_GENERATE_MY_DESTINATION));
}
FullDestination RawSession::createSession(const std::string& destination, const std::string& sigType, const std::string& i2pOptions)
{
typedef Message::Answer<const std::string> AnswerType;
const AnswerType answer = createRawSession(socket_, sessionID_, nickname_, listenPortUDP_, listenAddress_, destination, i2pOptions, sigType);
if (answer.status != Message::OK)
{
fallSick();
return FullDestination();
}
return FullDestination(answer.value.c_str(), answer.value, (destination == SAM_GENERATE_MY_DESTINATION));
}
/*static*/
Message::Answer<const std::string> RawSession::createRawSession(I2pSocket &socket,
const std::string &sessionID,
const std::string &nickname,
const uint16_t port,
const std::string &host,
const std::string &destination,
const std::string &options,
const std::string &signatureType)
{
return request(socket, Message::sessionCreate(Message::sssRaw, sessionID, nickname, port, host, destination, options, signatureType), "DESTINATION");
}
//-----------------------------------------------------------------------------
std::string Message::hello(const std::string &minVer, const std::string &maxVer)
{
/**
* -> HELLO VERSION
* MIN=$min
* MAX=$max
*
* <- HELLO REPLY
* RESULT=OK
* VERSION=$version
*/
static const char *helloFormat = "HELLO VERSION MIN=%s MAX=%s\n";
return createSAMRequest(helloFormat, minVer.c_str(), maxVer.c_str());
}
std::string Message::sessionCreate(SessionStyle style,
const std::string &sessionID,
const std::string &nickname,
const std::string &destination /*= SAM_GENERATE_MY_DESTINATION*/,
const std::string &options /*= ""*/,
const std::string &signatureType /*= SAM_SIGNATURE_TYPE*/)
{
/**
* -> SESSION CREATE
* STYLE={STREAM,DATAGRAM,RAW}
* ID={$nickname}
* DESTINATION={$private_destination_key,TRANSIENT}
* [option=value]*
*
* <- SESSION STATUS
* RESULT=OK
* DESTINATION=$private_destination_key
*/
std::string sessionStyle;
switch (style)
{
case sssStream:sessionStyle = "STREAM";
break;
case sssDatagram:sessionStyle = "DATAGRAM";
break;
case sssRaw:sessionStyle = "RAW";
break;
}
static const char *sessionCreateFormat =
"SESSION CREATE STYLE=%s ID=%s DESTINATION=%s SIGNATURE_TYPE=%s inbound.nickname=%s %s\n"; // we add inbound.nickname option
return createSAMRequest(sessionCreateFormat,
sessionStyle.c_str(),
sessionID.c_str(),
destination.c_str(),
signatureType.c_str(),
nickname.c_str(),
options.c_str());
}
std::string Message::sessionCreate(SessionStyle style,
const std::string &sessionID,
const std::string &nickname,
const uint16_t port,
const std::string &host,
const std::string &destination /*= SAM_GENERATE_MY_DESTINATION*/,
const std::string &options /*= ""*/,
const std::string &signatureType /*= SAM_SIGNATURE_TYPE*/)
{
/**
* -> SESSION CREATE
* STYLE={STREAM,DATAGRAM,RAW}
* ID={$nickname}
* DESTINATION={$private_destination_key,TRANSIENT}
* [SIGNATURE_TYPE=value] # SAM 3.1 or higher only, for DESTINATION=TRANSIENT only, default DSA_SHA1
* [PORT=$port] # Required for DATAGRAM and RAW, invalid for STREAM
* [HOST=$host] # Optional for DATAGRAM and RAW, invalid for STREAM
* [FROM_PORT=nnn] # SAM 3.2 or higher only, default 0
* [TO_PORT=nnn] # SAM 3.2 or higher only, default 0
* [PROTOCOL=nnn] # SAM 3.2 or higher only, for STYLE=RAW only, default 18
* [HEADER={true,false}] # SAM 3.2 or higher only, for STYLE=RAW only, default false
* [option=value]* # I2CP and streaming options
*
* <- SESSION STATUS
* RESULT=OK
* DESTINATION=$private_destination_key
*/
std::string sessionStyle;
switch (style)
{
case sssStream:sessionStyle = "STREAM";
break;
case sssDatagram:sessionStyle = "DATAGRAM";
break;
case sssRaw:sessionStyle = "RAW";
break;
}
// we add inbound.nickname option
static const char *sessionCreateFormat =
"SESSION CREATE STYLE=%s ID=%s DESTINATION=%s SIGNATURE_TYPE=%s PORT=%s HOST=%s inbound.nickname=%s %s\n";
return createSAMRequest(sessionCreateFormat,
sessionStyle.c_str(),
sessionID.c_str(),
destination.c_str(),
signatureType.c_str(),
std::to_string(port).c_str(),
host.c_str(),
nickname.c_str(),
options.c_str());
}
std::string Message::streamAccept(const std::string &sessionID,
bool silent /*= false*/)
{
/**
* -> STREAM ACCEPT
* ID={$nickname}
* [SILENT={true,false}]
*
* <- STREAM STATUS
* RESULT=$result
* [MESSAGE=...]
*/
static const char *streamAcceptFormat = "STREAM ACCEPT ID=%s SILENT=%s\n";
return createSAMRequest(streamAcceptFormat,
sessionID.c_str(),
silent ? "true" : "false");
}
std::string Message::streamConnect(const std::string &sessionID,
const std::string &destination,
bool silent /*= false*/)
{
/**
* -> STREAM CONNECT
* ID={$nickname}
* DESTINATION=$peer_public_base64_key
* [SILENT={true,false}]
*
* <- STREAM STATUS
* RESULT=$result
* [MESSAGE=...]
*/
static const char *streamConnectFormat = "STREAM CONNECT ID=%s DESTINATION=%s SILENT=%s\n";
return createSAMRequest(streamConnectFormat,
sessionID.c_str(),