-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.cpp
executable file
·2916 lines (2056 loc) · 109 KB
/
main.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
// Check if Windows
#ifdef _WIN32
// Set system version
#define _WIN32_WINNT _WIN32_WINNT_VISTA
// Use Unicode
#define UNICODE
#define _UNICODE
#endif
// Header files
#include <algorithm>
#include <atomic>
#include <cstring>
#include <filesystem>
#include <getopt.h>
#include <iostream>
#include <memory>
#include <random>
#include <signal.h>
#include <sstream>
#include <thread>
#include "event2/buffer.h"
#include "event2/bufferevent_ssl.h"
#include "event2/event.h"
#include "event2/event_struct.h"
#include "event2/http.h"
#include "event2/thread.h"
#include "http-internal.h"
#include "openssl/ssl.h"
// Extern C
extern "C" {
// Header files
#include "feature/api/tor_api.h"
#include "feature/api/tor_api_internal.h"
}
// Check if Windows
#ifdef _WIN32
// Header files
#include <ws2tcpip.h>
// Otherwise
#else
// Header files
#include <arpa/inet.h>
#endif
using namespace std;
// Definitions
// To string
#define STRINGIFY(x) #x
#define TOSTRING(x) STRINGIFY(x)
// Check if Windows or macOS
#if defined _WIN32 || defined __APPLE__
// Quick exit
#define quick_exit _exit
#endif
// Classes
// Check if Windows
#ifdef _WIN32
// Windows socket class
class WindowsSocket final {
// Public
public:
// Constructor
WindowsSocket() {
// Check if initiating Windows socket failed
WSADATA wsaData;
if(WSAStartup(MAKEWORD(WindowsSocket::MAJOR_VERSION, WindowsSocket::MINOR_VERSION), &wsaData)) {
// Throw exception
throw runtime_error("Initiating Windows socket failed");
}
}
// Destructor
~WindowsSocket() {
// Clean up Windows socket
WSACleanup();
}
// Private
private:
// Windows socket major version
static const BYTE MAJOR_VERSION = 2;
// Windows socket minor version
static const BYTE MINOR_VERSION = 2;
};
#endif
// Constants
// Default listen address
static const char *DEFAULT_LISTEN_ADDRESS = "localhost";
// Default listen port
static const uint16_t DEFAULT_LISTEN_PORT = 9060;
// Minimum TLS version
static const int MINIMUM_TLS_VERSION = TLS1_VERSION;
// Seconds in a minute
static const int SECONDS_IN_A_MINUTE = 60;
// Minutes in an hour
static const int MINUTES_IN_AN_HOUR = 60;
// Hours in a day
static const int HOURS_IN_A_DAY = 24;
// Microseconds in a millisecond
static const int MICROSECONDS_IN_A_MILLISECOND = 1000;
// Read timeout seconds
static const time_t READ_TIMEOUT_SECONDS = 1 * HOURS_IN_A_DAY * MINUTES_IN_AN_HOUR * SECONDS_IN_A_MINUTE;
// Write timeout seconds
static const time_t WRITE_TIMEOUT_SECONDS = 2 * SECONDS_IN_A_MINUTE;
// No socket
static const evutil_socket_t NO_SOCKET = -1;
// No URI port
static const int NO_URI_PORT = -1;
// HTTP port
static const ev_uint16_t HTTP_PORT = 80;
// HTTPS port
static const ev_uint16_t HTTPS_PORT = 443;
// HTTP bad gateway
static const int HTTP_BAD_GATEWAY = 502;
// HTTP gateway timeout
static const int HTTP_GATEWAY_TIMEOUT = 504;
// Check Tor connected interval microseconds
static const decltype(timeval::tv_usec) CHECK_TOR_CONNECTED_INTERVAL_MICROSECONDS = 100 * MICROSECONDS_IN_A_MILLISECOND;
// Temporary directory length
static const size_t TEMPORARY_DIRECTORY_LENGTH = 8;
// Bytes in a kilobyte
static const int BYTES_IN_A_KILOBYTE = pow(2, 10);
// Kilobytes in a megabyte
static const int KILOBYTE_IN_A_MEGABYTE = BYTES_IN_A_KILOBYTE;
// Maximum headers size
static const size_t MAXIMUM_HEADERS_SIZE = 1 * KILOBYTE_IN_A_MEGABYTE * BYTES_IN_A_KILOBYTE;
// Maximum body size
static const size_t MAXIMUM_BODY_SIZE = 10 * KILOBYTE_IN_A_MEGABYTE * BYTES_IN_A_KILOBYTE;
// SOCKS state
enum class SocksState {
// Authenticating
AUTHENTICATING,
// Connecting
CONNECTING
};
// Function prototypes
// Display options help
static void displayOptionsHelp();
// Check if Windows
#ifdef _WIN32
// Add system certificates to certificate store
static bool addSystemCertificatesToCertificateStore(X509_STORE *certificateStore, const TCHAR *systemStoreName);
#endif
// Main function
int main(int argc, char *argv[]) {
// Display message
cout << TOSTRING(PROGRAM_NAME) << " v" << TOSTRING(PROGRAM_VERSION) << endl;
// Initialize no verify
bool noVerify = false;
// Initialize listen address
string listenAddress = DEFAULT_LISTEN_ADDRESS;
// Initialize listen port
uint16_t listenPort = DEFAULT_LISTEN_PORT;
// Initialize certificate
const char *certificate = nullptr;
// Initialize key
const char *key = nullptr;
// Set options
const option options[] = {
// Version
{"version", no_argument, nullptr, 'v'},
// No verify
{"no_verify", no_argument, nullptr, 'n'},
// Address
{"address", required_argument, nullptr, 'a'},
// Port
{"port", required_argument, nullptr, 'p'},
// Certificate
{"cert", required_argument, nullptr, 'c'},
// Key
{"key", required_argument, nullptr, 'k'},
// Help
{"help", no_argument, nullptr, 'h'},
// End
{}
};
// Go through all options
for(int option = getopt_long(argc, argv, "vna:p:c:k:h", options, nullptr); option != -1; option = getopt_long(argc, argv, "vna:p:c:k:h", options, nullptr)) {
// Check option
switch(option) {
// Version
case 'v':
// Return success
return EXIT_SUCCESS;
// No verify
case 'n':
// Set no verify
noVerify = true;
// Break
break;
// Address
case 'a':
// Check if option exists
if(optarg) {
// Set listen address
listenAddress = optarg;
}
// Otherwise
else {
// Display message
cout << argv[0] << ": invalid address -- ''" << endl;
// Display message
cout << endl << "Usage:" << endl << '\t' << argv[0] << " [options]" << endl << endl;
// Display options help
displayOptionsHelp();
// Return failure
return EXIT_FAILURE;
}
// Break
break;
// Certificate
case 'c':
// Check if option exists
if(optarg) {
// Set certificate
certificate = optarg;
}
// Otherwise
else {
// Display message
cout << argv[0] << ": invalid certificate -- ''" << endl;
// Display message
cout << endl << "Usage:" << endl << '\t' << argv[0] << " [options]" << endl << endl;
// Display options help
displayOptionsHelp();
// Return failure
return EXIT_FAILURE;
}
// Break
break;
// Key
case 'k':
// Check if option exists
if(optarg) {
// Set key
key = optarg;
}
// Otherwise
else {
// Display message
cout << argv[0] << ": invalid key -- ''" << endl;
// Display message
cout << endl << "Usage:" << endl << '\t' << argv[0] << " [options]" << endl << endl;
// Display options help
displayOptionsHelp();
// Return failure
return EXIT_FAILURE;
}
// Break
break;
// Port
case 'p':
// Check if option exists
if(optarg) {
// Get port
string port = optarg;
// Check if port is numeric
if(all_of(port.begin(), port.end(), ::isdigit)) {
// Initialize error occurred
bool errorOccurred = false;
// Try
int portNumber;
try {
// Get port number from port
portNumber = stoi(port);
}
// Catch errors
catch(...) {
// Set error occurred
errorOccurred = true;
}
// Check if an error didn't occurt
if(!errorOccurred) {
// Check if port number is valid
if(portNumber >= 1 && portNumber <= UINT16_MAX) {
// Set listen port
listenPort = portNumber;
// Break
break;
}
}
}
}
// Display message
cout << argv[0] << ": invalid port -- '" << (optarg ? optarg : "") << '\'' << endl;
// Display message
cout << endl << "Usage:" << endl << '\t' << argv[0] << " [options]" << endl << endl;
// Display options help
displayOptionsHelp();
// Return failure
return EXIT_FAILURE;
// Break
break;
// Help or default
case 'h':
default:
// Display message
cout << endl << "Usage:" << endl << '\t' << argv[0] << " [options]" << endl << endl;
// Display options help
displayOptionsHelp();
// Return success
return EXIT_SUCCESS;
}
}
// Check if certificate is provided without a key or a key is provided without a certificate
if((certificate && !key) || (!certificate && key)) {
// Display message
cout << ((certificate && !key) ? "No key provided for the certificate" : "No certificate provided for the key") << endl;
// Return failure
return EXIT_FAILURE;
}
// Set using TLS server to if a certificate and key are provided
const bool usingTlsServer = certificate && key;
// Check if not Windows
#ifndef _WIN32
// Check if blocking all signals failed
sigset_t signalMask;
if(sigfillset(&signalMask) || pthread_sigmask(SIG_BLOCK, &signalMask, nullptr)) {
// Display message
cout << "Blocking all signals failed" << endl;
// Return failure
return EXIT_FAILURE;
}
#endif
// Check if Windows
#ifdef _WIN32
// Check if enabling thread support failed
if(evthread_use_windows_threads()) {
// Display message
cout << "Enabling thread support failed" << endl;
// Return failure
return EXIT_FAILURE;
}
// Otherwise
#else
// Check if enabling thread support failed
if(evthread_use_pthreads()) {
// Display message
cout << "Enabling thread support failed" << endl;
// Return failure
return EXIT_FAILURE;
}
#endif
// Check if Windows
#ifdef _WIN32
// Initialize Windows socket
unique_ptr<WindowsSocket> windowsSocket;
// Try
try {
// Set Windows socket
windowsSocket = make_unique<WindowsSocket>();
}
// Catch errors
catch(const runtime_error &error) {
// Display message
cout << error.what() << endl;
// Return failure
return EXIT_FAILURE;
}
#endif
// Check if creating TLS method failed
const SSL_METHOD *tlsMethod = TLS_method();
if(!tlsMethod) {
// Display message
cout << "Creating TLS method failed" << endl;
// Return failure
return EXIT_FAILURE;
}
// Check if creating TLS context failed
unique_ptr<SSL_CTX, decltype(&SSL_CTX_free)> tlsContext(SSL_CTX_new(tlsMethod), SSL_CTX_free);
if(!tlsContext) {
// Display message
cout << "Creating TLS context failed" << endl;
// Return failure
return EXIT_FAILURE;
}
// Check if setting TLS context's minimum TLS version failed
if(!SSL_CTX_set_min_proto_version(tlsContext.get(), MINIMUM_TLS_VERSION)) {
// Display message
cout << "Setting TLS context's minimum protocol version failed" << endl;
// Return failure
return EXIT_FAILURE;
}
// Check if Windows
#ifdef _WIN32
// Check if getting TLS context's certificate store failed
X509_STORE *certificateStore = SSL_CTX_get_cert_store(tlsContext.get());
if(!certificateStore) {
// Display message
cout << "Getting TLS context's certificate store failed" << endl;
// Return failure
return EXIT_FAILURE;
}
// Check if adding system certificates to the certificate store failed
if(!addSystemCertificatesToCertificateStore(certificateStore, TEXT("ROOT")) || !addSystemCertificatesToCertificateStore(certificateStore, TEXT("CA")) || !addSystemCertificatesToCertificateStore(certificateStore, TEXT("MY"))) {
// Display message
cout << "Adding system certificates to the certificate store failed" << endl;
// Return failure
return EXIT_FAILURE;
}
// Otherwise
#else
// Check if using the default verify paths for the TLS context failed
if(!SSL_CTX_set_default_verify_paths(tlsContext.get())) {
// Display message
cout << "Using the default verify paths for the TLS context failed" << endl;
// Return failure
return EXIT_FAILURE;
}
#endif
// Check if using TLS server
if(usingTlsServer) {
// Check if setting the TLS context's certificate and key failed
if(SSL_CTX_use_certificate_chain_file(tlsContext.get(), certificate) != 1 || SSL_CTX_use_PrivateKey_file(tlsContext.get(), key, SSL_FILETYPE_PEM) != 1 || SSL_CTX_check_private_key(tlsContext.get()) != 1) {
// Display message
cout << "Setting the TLS context's certificate and key failed" << endl;
// Return failure
return EXIT_FAILURE;
}
}
// Check if creating event base failed
shared_ptr<event_base> eventBase(event_base_new(), event_base_free);
if(!eventBase) {
// Display message
cout << "Creating event base failed" << endl;
// Return failure
return EXIT_FAILURE;
}
// Check if creating HTTP server failed
unique_ptr<evhttp, decltype(&evhttp_free)> httpServer(evhttp_new(eventBase.get()), evhttp_free);
if(!httpServer) {
// Display message
cout << "Creating HTTP server failed" << endl;
// Return failure
return EXIT_FAILURE;
}
// Set HTTP server's maximum header size
evhttp_set_max_headers_size(httpServer.get(), MAXIMUM_HEADERS_SIZE);
// Set HTTP server's maximum body size
evhttp_set_max_body_size(httpServer.get(), MAXIMUM_BODY_SIZE);
// Set HTTP server to allow all types of requests
evhttp_set_allowed_methods(httpServer.get(), EVHTTP_REQ_GET | EVHTTP_REQ_POST | EVHTTP_REQ_HEAD | EVHTTP_REQ_PUT | EVHTTP_REQ_DELETE | EVHTTP_REQ_OPTIONS | EVHTTP_REQ_TRACE | EVHTTP_REQ_CONNECT | EVHTTP_REQ_PATCH);
// Check if using TLS server
if(usingTlsServer) {
// Set HTTP server buffer event create callback
evhttp_set_bevcb(httpServer.get(), ([](event_base *eventBase, void *argument) -> bufferevent * {
// Get TLS context from argument
SSL_CTX *tlsContext = reinterpret_cast<SSL_CTX *>(argument);
// Check if creating TLS connection from the TLS context failed
unique_ptr<SSL, decltype(&SSL_free)> tlsConnection(SSL_new(tlsContext), SSL_free);
if(!tlsConnection) {
// Return null
return nullptr;
}
// Check if creating TLS buffer failed
unique_ptr<bufferevent, decltype(&bufferevent_free)> tlsBuffer(bufferevent_openssl_socket_new(eventBase, NO_SOCKET, tlsConnection.get(), BUFFEREVENT_SSL_ACCEPTING, BEV_OPT_CLOSE_ON_FREE | BEV_OPT_DEFER_CALLBACKS), bufferevent_free);
if(!tlsBuffer) {
// Return null
return nullptr;
}
// Release TLS connection
tlsConnection.release();
// Check if allow dirty shutdown for the TLS buffer failed
if(bufferevent_ssl_set_flags(tlsBuffer.get(), BUFFEREVENT_SSL_DIRTY_SHUTDOWN) == EV_UINT64_MAX) {
// Return null
return nullptr;
}
// Get buffer event
bufferevent *bufferEvent = tlsBuffer.get();
// Release TLS buffer
tlsBuffer.release();
// Return buffer event
return bufferEvent;
}), tlsContext.get());
// Set HTTP server new request callback
evhttp_set_newreqcb(httpServer.get(), [](evhttp_request *request, void *argument) -> int {
// Check if request's connection exists
evhttp_connection *requestsConnection = evhttp_request_get_connection(request);
if(requestsConnection) {
// Set request's connection close callback
evhttp_connection_set_closecb(requestsConnection, [](evhttp_connection *connection, void *argument) {
// Check if connection's buffer event exists
bufferevent *bufferEvent = evhttp_connection_get_bufferevent(connection);
if(bufferEvent) {
// Check if buffer event's TLS connection exists
SSL *tlsConnection = bufferevent_openssl_get_ssl(bufferEvent);
if(tlsConnection) {
// Shutdown TLS connection
SSL_shutdown(tlsConnection);
}
}
}, nullptr);
}
// Return success
return 0;
}, nullptr);
}
// Initialize Tor address
string torAddress;
// Initialize Tor port
uint16_t torPort;
// Initialize HTTP server request callback argument
tuple<const bool *, const string *, const uint16_t *, const bool *, SSL_CTX *, const string *, const uint16_t *> httpServerRequestCallbackArgument(&noVerify, &listenAddress, &listenPort, &usingTlsServer, tlsContext.get(), &torAddress, &torPort);
// Set HTTP server request callback
evhttp_set_gencb(httpServer.get(), ([](evhttp_request *request, void *argument) {
// Get HTTP server request callback argument from argument
tuple<const bool *, const string *, const uint16_t *, const bool *, SSL_CTX *, string *, uint16_t *> *httpServerRequestCallbackArgument = reinterpret_cast<tuple<const bool *, const string *, const uint16_t *, const bool *, SSL_CTX *, string *, uint16_t *> *>(argument);
// Get no verify from HTTP server request callback argument
const bool *noVerify = get<0>(*httpServerRequestCallbackArgument);
// Get listen address from HTTP server request callback argument
const string *listenAddress = get<1>(*httpServerRequestCallbackArgument);
// Get listen port from HTTP server request callback argument
const uint16_t *listenPort = get<2>(*httpServerRequestCallbackArgument);
// Get using TLS server from HTTP server request callback argument
const bool *usingTlsServer = get<3>(*httpServerRequestCallbackArgument);
// Get TLS context from HTTP server request callback argument
SSL_CTX *tlsContext = get<4>(*httpServerRequestCallbackArgument);
// Get Tor address from HTTP server request callback argument
const string *torAddress = get<5>(*httpServerRequestCallbackArgument);
// Get Tor port from HTTP server request callback argument
const uint16_t *torPort = get<6>(*httpServerRequestCallbackArgument);
// Check if request doesn't have a URI
if(!evhttp_request_get_uri(request) || !strlen(evhttp_request_get_uri(request))) {
// Reply with bad request error to request
evhttp_send_reply(request, HTTP_BADREQUEST, nullptr, nullptr);
}
// Otherwise
else {
// Check if parsing request's URI failed
unique_ptr<evhttp_uri, decltype(&evhttp_uri_free)> uri(evhttp_uri_parse(&evhttp_request_get_uri(request)[sizeof('/')]), evhttp_uri_free);
if(!uri) {
// Reply with bad request error to request
evhttp_send_reply(request, HTTP_BADREQUEST, nullptr, nullptr);
}
// Otherwise check if URI doesn't have a host or its host is invalid
else if(!evhttp_uri_get_host(uri.get()) || !strlen(evhttp_uri_get_host(uri.get())) || strlen(evhttp_uri_get_host(uri.get())) > UINT8_MAX) {
// Reply with bad request error to request
evhttp_send_reply(request, HTTP_BADREQUEST, nullptr, nullptr);
}
// Otherwise check if URI's scheme isn't supported
else if(evhttp_uri_get_scheme(uri.get()) && strcasecmp(evhttp_uri_get_scheme(uri.get()), "http") && strcasecmp(evhttp_uri_get_scheme(uri.get()), "https")) {
// Reply with bad request error to request
evhttp_send_reply(request, HTTP_BADREQUEST, nullptr, nullptr);
}
// Otherwise
else {
// Check if creating SOCKS buffer failed
unique_ptr<bufferevent, decltype(&bufferevent_free)> socksBuffer(bufferevent_socket_new(evhttp_connection_get_base(evhttp_request_get_connection(request)), NO_SOCKET, BEV_OPT_CLOSE_ON_FREE | BEV_OPT_DEFER_CALLBACKS), bufferevent_free);
if(!socksBuffer) {
// Reply with internal server error to request
evhttp_send_reply(request, HTTP_INTERNAL, nullptr, nullptr);
}
// Otherwise
else {
// Set read timeout
const timeval readTimeout = {
// Seconds
.tv_sec = READ_TIMEOUT_SECONDS
};
// Set write timeout
const timeval writeTimeout = {
// Seconds
.tv_sec = WRITE_TIMEOUT_SECONDS
};
// Set SOCKS buffer's read and write timeout
bufferevent_set_timeouts(socksBuffer.get(), &readTimeout, &writeTimeout);
// Check if creating SOCKS state failed
unique_ptr<SocksState> socksState = make_unique<SocksState>(SocksState::AUTHENTICATING);
if(!socksState) {
// Reply with internal server error to request
evhttp_send_reply(request, HTTP_INTERNAL, nullptr, nullptr);
}
// Otherwise
else {
// Check if creating SOCKS buffer callbacks argument failed
unique_ptr<tuple<evhttp_request *, const bool *, const string *, const uint16_t *, const bool *, SSL_CTX *, const string *, const uint16_t *, evhttp_uri *, SocksState *>> socksBufferCallbacksArgument = make_unique<tuple<evhttp_request *, const bool *, const string *, const uint16_t *, const bool *, SSL_CTX *, const string *, const uint16_t *, evhttp_uri *, SocksState *>>(request, noVerify, listenAddress, listenPort, usingTlsServer, tlsContext, torAddress, torPort, uri.get(), socksState.get());
if(!socksBufferCallbacksArgument) {
// Reply with internal server error to request
evhttp_send_reply(request, HTTP_INTERNAL, nullptr, nullptr);
}
// Otherwise
else {
// Set SOCKS buffer callbacks
bufferevent_setcb(socksBuffer.get(), ([](bufferevent *buffer, void *argument) {
// Get SOCKS buffer from buffer
unique_ptr<bufferevent, decltype(&bufferevent_free)> socksBuffer(buffer, bufferevent_free);
// Get SOCKS buffer callbacks argument from argument
unique_ptr<tuple<evhttp_request *, const bool *, const string *, const uint16_t *, const bool *, SSL_CTX *, const string *, const uint16_t *, evhttp_uri *, SocksState *>> socksBufferCallbacksArgument(reinterpret_cast<tuple<evhttp_request *, const bool *, const string *, const uint16_t *, const bool *, SSL_CTX *, const string *, const uint16_t *, evhttp_uri *, SocksState *> *>(argument));
// Get request from SOCKS buffer callbacks argument
evhttp_request *request = get<0>(*socksBufferCallbacksArgument);
// Get no verify from SOCKS buffer callbacks argument
const bool *noVerify = get<1>(*socksBufferCallbacksArgument);
// Get listen address from SOCKS buffer callbacks argument
const string *listenAddress = get<2>(*socksBufferCallbacksArgument);
// Get listen port from SOCKS buffer callbacks argument
const uint16_t *listenPort = get<3>(*socksBufferCallbacksArgument);
// Get using TLS server from SOCKS buffer callbacks argument
const bool *usingTlsServer = get<4>(*socksBufferCallbacksArgument);
// Get TLS context from SOCKS buffer callbacks argument
SSL_CTX *tlsContext = get<5>(*socksBufferCallbacksArgument);
// Get Tor address from SOCKS buffer callbacks argument
const string *torAddress = get<6>(*socksBufferCallbacksArgument);
// Get Tor port from SOCKS buffer callbacks argument
const uint16_t *torPort = get<7>(*socksBufferCallbacksArgument);
// Get URI from SOCKS buffer callbacks argument
unique_ptr<evhttp_uri, decltype(&evhttp_uri_free)> uri(get<8>(*socksBufferCallbacksArgument), evhttp_uri_free);
// Get SOCKS state from SOCKS buffer callbacks argument
unique_ptr<SocksState> socksState(get<9>(*socksBufferCallbacksArgument));
// Check if getting input from the SOCKS buffer failed
evbuffer *input = bufferevent_get_input(socksBuffer.get());
if(!input) {
// Remove SOCKS buffer callbacks
bufferevent_setcb(socksBuffer.get(), nullptr, nullptr, nullptr, nullptr);
// Reply with internal server error to request
evhttp_send_reply(request, HTTP_INTERNAL, nullptr, nullptr);
}
// Otherwise
else {
// Get input's length
const size_t length = evbuffer_get_length(input);
// Check if getting data from input failed
uint8_t data[length];
if(evbuffer_copyout(input, data, length) == -1) {
// Remove data from input
evbuffer_drain(input, length);
// Remove SOCKS buffer callbacks
bufferevent_setcb(socksBuffer.get(), nullptr, nullptr, nullptr, nullptr);
// Reply with internal server error to request
evhttp_send_reply(request, HTTP_INTERNAL, nullptr, nullptr);
}
// Otherwise check if removing data from input failed
else if(evbuffer_drain(input, length)) {
// Remove SOCKS buffer callbacks
bufferevent_setcb(socksBuffer.get(), nullptr, nullptr, nullptr, nullptr);
// Reply with internal server error to request
evhttp_send_reply(request, HTTP_INTERNAL, nullptr, nullptr);
}
// Otherwise
else {
// Check SOCKS state
switch(*socksState) {
// Authenticating
case SocksState::AUTHENTICATING:
// Check if response isn't complete
if(length != sizeof("\x05\x00") - sizeof('\0')) {
// Remove SOCKS buffer callbacks
bufferevent_setcb(socksBuffer.get(), nullptr, nullptr, nullptr, nullptr);
// Reply with internal server error to request
evhttp_send_reply(request, HTTP_INTERNAL, nullptr, nullptr);
}
// Otherwise check if authentication method isn't supported
else if(data[1] != 0) {
// Remove SOCKS buffer callbacks
bufferevent_setcb(socksBuffer.get(), nullptr, nullptr, nullptr, nullptr);
// Reply with internal server error to request
evhttp_send_reply(request, HTTP_INTERNAL, nullptr, nullptr);
}
// Otherwise
else {
// Get host
string host = evhttp_uri_get_host(uri.get());
// Check if host is enclosed in brackets
if(host.front() == '[' && host.back() == ']') {
// Remove enclosing brackets from host
host = host.substr(sizeof('['), host.size() - sizeof('[') - sizeof(']'));
}
// Get port
const uint16_t port = htons((evhttp_uri_get_port(uri.get()) != NO_URI_PORT) ? evhttp_uri_get_port(uri.get()) : (evhttp_uri_get_scheme(uri.get()) && !strcasecmp(evhttp_uri_get_scheme(uri.get()), "https")) ? HTTPS_PORT : HTTP_PORT);
// Set connection request
uint8_t connectionRequest[sizeof("\x05\x01\x00\x03") - sizeof('\0') + sizeof(uint8_t) + host.length() + sizeof(port)];
// Set connection request's information
memcpy(connectionRequest, "\x05\x01\x00\x03", sizeof("\x05\x01\x00\x03") - sizeof('\0'));
// Set connection request's host length
connectionRequest[sizeof("\x05\x01\x00\x03") - sizeof('\0')] = host.length();
// Set connection request's host
memcpy(&connectionRequest[sizeof("\x05\x01\x00\x03") - sizeof('\0') + sizeof(uint8_t)], host.c_str(), host.length());
// Set connection request's port
memcpy(&connectionRequest[sizeof("\x05\x01\x00\x03") - sizeof('\0') + sizeof(uint8_t) + host.length()], &port, sizeof(port));
// Check if sending connection requests to the SOCKS proxy failed
if(bufferevent_write(socksBuffer.get(), connectionRequest, sizeof(connectionRequest))) {
// Remove SOCKS buffer callbacks
bufferevent_setcb(socksBuffer.get(), nullptr, nullptr, nullptr, nullptr);
// Reply with internal server error to request
evhttp_send_reply(request, HTTP_INTERNAL, nullptr, nullptr);
}
else {
// Set SOCKS state to connecting
*socksState = SocksState::CONNECTING;
// Release SOCKS buffer
socksBuffer.release();
// Release SOCKS buffer callbacks argument
socksBufferCallbacksArgument.release();
// Release URI
uri.release();
// Release SOCKS state
socksState.release();
}
}
// Break
break;
// Connecting
case SocksState::CONNECTING: