-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathglove.cpp
More file actions
2343 lines (2051 loc) · 72.8 KB
/
glove.cpp
File metadata and controls
2343 lines (2051 loc) · 72.8 KB
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
/**
*************************************************************
* @file glove.cpp
* @brief Tiny and standalone TCP socket C++11 wrapper and more
*
* @author Gaspar Fernández <blakeyed@totaki.com>
* @version
* @date 07 ago 2014
*
* Notes:
* - Some ideas borrowed from some projects I've made in the past.
* - Some code borrowed from r-lyeh's knot ( https://github.com/r-lyeh/knot )
* - urlencode/urldecode borrowed from knot base on code by Fred Bulback
* - base64 encode/decode functions by René Nyffenegger (https://github.com/ReneNyffenegger/development_misc/tree/master/base64)
* - send() and recv() are called just once (well recv() twice), so we can replace these functions
* - I want to abstract the final user (application programmer) from socket operations but without losing control and information
*
* Changelog
* 20180515 : - Compatibility with newer OpenSSL versions
* - New SSL method (DTLSv1_1), TLS and DTLS generic methods.
* - Removed SSLv3 compatibility.
* 20170717 : - Fixed local connection detection. Not merged right from another project.
* 20170131 : - OpenSSL initialization is *not* thread safe. Added a little mutex
* 20170127 : - sets tlsext_host_name when connecting with SSL. (SNI support!!)
* 20161016 : - Client objects know if they are local connections
* 20161007 : - bug fixed parsing URI arguments
* 20161004 : - minor bugs to free resources when closing unfinished connections
* : - getservbyname wrapper with additional services (for now, only ws:// and wss://)
* : - remove CRLF constants and use it from GloveDef (global constants for all Glove headers)
* 20161003 : - fixed bugs when connecting non-ssl when service is SSL
* 20161002 : - merged SSL server code (I thought it was)
* : - SSL disconnection algorithm in loop
* 20160928 : - get service and host from uri. To automatically get http(s)://host:port/
* 20160926 : - base64_encode/decode ; urlencode / urldecode moved to GloveCoding namespace
* 20160919 : - Fixed compilation for GCC >=5.2:
* 20160813 : - prevent old openSSL hung in faulty server responses. SSL_read() is ran in other thread, this one
* has a timeout. If GCC<4.9.0 it will use pthread functions directly as workaround. Older G++
* versions don't manage timed_mutex.try_lock_for() correctly.
* 20160516 : - fixed some compiling issues for old compilers when SSL_CTX_new() must have a SSL_METHOD* and not
* a const SSL_METHOD* (merged 20160919)
* 20160420 : - get_from_uri() arguments separated in extract_uri_arguments to make x-www-form-urlencoded
* easier to parse.
* 20160201 : - select() is now static function too and can handle just one fd, but you can specify.
* - receive_fixed don't run input filters on timeout anymore when read_once is enabled
* 20160129 : - Allowing or denying connection filters
* 20160128 : - Incoming connection log
* - Incoming connection reject message and callback
* - Connection filters and policies are not ready.
* DON'T USE THIS VERSION
* 20160127 : - Deleting closed connections from memory
* 20160126 : - MatchIP matches IP ranges by CIDR (x.x.x.x/y) or by wildcard (x.x.*.*) with option Not Only CIDR
* 20151216 : - Clean SSL context and structure when disconnect()
* 20151212 : - URI struct now know if it's a secure or a non-secure service.
* - Bug fixed: Segfault when server has port open but isn't accepting connections
* - connect() now support Glove::uri and string as uri
* - Glove() constructor now support direct URI connection
* 20151211 : - Automatically get port when getting from URI
* 20151210 : - Bug fixing in non-ssl connections trying to call ssl functions (regression)
* 20150503 : - Bug fixing in non-ssl connections trying to call ssl functions
* 20150502 : - Error documentation.
* - Changed error 100 "Peer shutdown" to error 21
* - First steps with openSSL connections
* 20150501 : - Connection Info is filled in a separate function, allowing us to get the service name
* even when resolve_hostnames is false. That's because we may want to guess
* if the service is secure (by service name)
* - (this->connected == false) condition when connecting to a server
* - Fixed resolveHost() to resolve IPv6 and IPv4, whatever it comes to it.
* - Bug fixing on flag manipulations. Added functions and manipulators for exceptions
* 20150430 : some more more doc for Doxygen (in glove.hpp) (I'd like to comment everything)
* 20150425 : some more doc for Doxygen (in glove.hpp)
* 20150418 : some doc for Doxygen (in glove.hpp)
* 20150404 : urlencode/urldecode/base64 encode/base64 decode helpers
* 20140923 : get_from_uri() - The unmaintainable!
* 20140919 : build_uri(), better test_connected()
* 20140914 : Some bugfixing and Glove constructors
* 20140913 : Created GloveBase, deleted Util namespace and duplicated code
* 20140908 : Now, it can be a server
* 20140807 : Begin this project
*
* To-do:
* 1 - Match IP for IPv6
* 2 - epoll support
* 6 - be able to connect with protocol/service names
* 7 - set_option(...) allowing a variadic template to set every client or server option
* 8 - allowed client list (IPs list with allowed clients)
* 8 - create GloveHTTP behind GloveHTTPServer and GloveHTTPClient
* 9 - logger callback
* 10 - test_connected fussion with is_connected()
* 11 - GloveBase::getServByPort() must check _additional services
* 15 - Winsock support (far far in the future)
*
* MIT Licensed:
* Copyright (c) 2014 Gaspar Fernández
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*************************************************************/
/*
* Some more doc, error! GloveException codes:
*
* 1: "Failed to resolve": Can't resolve host
* Found on Glove::connect()
* Glove::resolveHost()
* 2: "Failed to resolve": Can't get IP address, host
* Found on Glove::resolveHost()
* Glove::fill_connection_info() (only if server_options.resolve_hostnames is true)
* 3: "Cannot get IP address": Current address structure don't have valid information for current domain
* Maybe we have a IPv6 address and try to get as IPv4
* Found on Glove::fill_connection_info()
* Glove::resolveHost()
* 4: "Cannot connect to the server" : We've tried but cannot connect
* Found on Glove::connect()
* 5: "Not connected" : We're not connected!!
* Found on Glove::test_connected() if we're not connected and EXCEPTION_DISCONNECTED is enabled
* 6: "Socket error when sending" : send() returns -1 (if secure connection SSL_write() returns -1
* Found on GloveBase::_send()
* 7: "Timed out while receiving data" : We were waiting for data which didn't come after
* waiting for [timeout] seconds.
* Found on GloveBase::_receive_fixed() when timeout, exception_on_timeout=true
* BUT if we've already received data, timeout_when_data must be true too.
* 8: "Error while waiting for data" : We were waiting for data, but received an unexpected error.
* Found on GloveBase::_receive_fixed()
* 9: "Error receiving data" : recv() returns -1 (if secure connection SSL_read() returns -1)
* Found on GloveBase::_receive_fixed()
* 10: "Socket was not closed" : Problem closing socket (bad socket? IO Error?)
* Found on GloveBase::disconnect()
* 11: "Cannot create socket"
* Found on Glove::listen()
* Glove::connect()
* 12: "Cannot bind to port"
* Found on Glove::listen()
* 13: "Cannot perform listen"
* Found on Glove::listen()
* 14: "Failed to set option on socket" : setsockopt() returns -1
* Found on GloveBase::setsockopt()
* 15: "Failed to get option on socket" : getsockopt() returns -1
* Found on GloveBase::getsockopt()
* 16: "Unrecognised socket option, or it does not accept ints" : socket option not recognised
* (maybe my fault, because not implemented)
* Found on GloveBase::get_integer_sockopts_level() used by GloveBase::setsockopt() and GloveBase::getsockopt()
* 17: "TCP Error" : TCP Error on connection
* Found on GloveBase::connect_nonblocking()
* 18: "Socket error" : error receiving when checking connection
* Found on Glove::is_connected()
* 19: "Error calling getsockname()"
* Found on GloveBase::get_address()
* 20: "Socket was not shutted down" : Error on shutdown()
* Found on GloveBase::disconnect()
* 21: "Peer shutdown" : Peer shutdown when receiving
* Found on GloveBase::_receive_fixed()
* 22: "Couldn't create SSL context" :
* Found on Glove::SSLClientHandshake() when connecting TO a server
* Glove::SSLServerInitialize() when creating server context
* 23: "Couldn't create SSL handler
* Found on Glove::SSLClientHandshake()
* 24: "Couldn't assign socket to SSL session"
* Found on Glove::SSLClientHandshake()
* 25: "SSL handshake failure"
* Found on Glove::SSLClientHandshake()
* 26: "Couldn't load CA path" : Can't load certificate authorities!
* Found on Glove::SSLClientHandshake() ssl_options.flags must have SSL_FLAG_VERIFY_CA enabled
* 27: "Couldn't get certificate chain" : Tried to get certificate chain, but couldn't
* Found on Glove::SSLGetCertificatesInfo()
* 28: "Bad 'Not Before' time in certificate"
* Found on Glove::SSLGetCertificatesInfo();
* 29: "Bad 'Not After' time in certificate"
* Found on Glove::SSLGetCertificatesInfo();
* 30: "Certificate chain file XXXX does not exist"
* Found on Glove::SSLServerInitialize() when trying to load the certificate chain file
* 31: "There was a problem reading certificate chain file XXXX."
* Found on Glove::SSLServerInitialize() when trying to load the certificate chain file
* 32: "Certificate key file XXXX does not exist"
* Found on Glove::SSLServerInitialize() when trying to load the certificate key file
* 33: "There was a problem reading certificate key file XXXX."
* Found on Glove::SSLServerInitialize() when trying to load the certificate key file
* 34: "Can't load certificate chain file XXXXX"
* Found on Glove::SSLServerInitialize() when trying to load the certificate chain file
* 35: "Can't load certificate key file XXXXXX"
* Found on Glove::SSLServerInitialize() when trying to load the certificate key file
* 36: "Private key doesn't match the certificate"
* Found on Glove::SSLServerInitialize() when certificate and key are loaded
* 37: "Given IP Address is not valid"
* Found on GloveBase::inet_pton4() when doing inet_pton() and it results 0
* 38: "Wrong family specified"
* Found on GloveBase::inet_pton4() when doing inet_pton() and it results <0
* 39: "Wrong CIDR input"
* Found on GloveBase::getNetworkAndMask() when validating CIDR expression
* 40: "SSL Timeout. Some kind of bug makes SSL_read() freeze with strange server response on
* certain openSSL versions. With this, an additional timeout is applied, and this
* timeout has ran out.
* 41: "SSL Method not specified"
* Found on Glove::getSSLClientMethod() and Glove::getSSLServerMethod() when SSL connection
* method is not in ssl_options.ssl_method.
* 42: "Failed setting TLS host name"
* Found on Glove::SSLClientHandshake() when setting tlsext_host_name.
*
*/
#undef _GLIBCXX_USE_CLOCK_MONOTONIC
#include "glove.hpp"
#include "glovecoding.hpp"
#include <cstring> // memset(), strerror()
#include <iostream> // debug only
#include <arpa/inet.h>
#include <netinet/tcp.h> // TCP_NODELAY
#include <thread>
#include <mutex>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <bitset>
#include <iomanip>
/** Initialization (if any), it was intended to be cross-platform, but time
goes by and I needed to get this lib in a decent point for Linux. So I didn't
care about Windows.
*/
#define INIT()
/**
* Calls socket()
*/
#define SOCKET(A,B,C) ::socket((A),(B),(C))
/** Calls accept() */
#define ACCEPT(A,B,C) ::accept((A),(B),(C))
/** Calls connect() */
#define CONNECT(A,B,C) ::connect((A),(B),(C))
/** Calls close() */
#define CLOSE(A) ::close((A))
/** Calls read() */
#define READ(A,B,C) ::read((A),(B),(C))
/** Calls recv() */
#define RECV(A,B,C,D) ::recv((A), (void *)(B), (C), (D))
/** Calls select() */
#define SELECT(A,B,C,D,E) ::select((A),(B),(C),(D),(E))
/** Calls send() */
#define SEND(A,B,C,D) ::send((A), (const char *)(B), (C), (D))
/** Calls write() */
#define WRITE(A,B,C) ::write((A),(B),(C))
/** Calls getsockopt() */
#define GETSOCKOPT(A,B,C,D,E) ::getsockopt((int)(A),(int)(B),(int)(C),( void *)(D),(socklen_t *)(E))
/** Calls setsockopt() */
#define SETSOCKOPT(A,B,C,D,E) ::setsockopt((int)(A),(int)(B),(int)(C),(const void *)(D),(socklen_t)(E))
/** Calls bind() */
#define BIND(A,B,C) ::bind((A),(B),(C))
/** Calls listen() */
#define LISTEN(A,B) ::listen((A),(B))
/** Calls shutdown() */
#define SHUTDOWN(A,B) ::shutdown((A),(B))
/* These constants may help developers when handling errors */
/* Number separation is intended to insert more log types when
using other layer services like http, websockets, etc. These
services may have CRITICAL or ERROR for this particular layer.*/
const uint16_t LOG_CRITICAL = 0; /* Live or death errors */
const uint16_t LOG_ERROR = 20; /* Errors*/
const uint16_t LOG_WARNING = 40; /* Warnings*/
const uint16_t LOG_NOTICE = 60; /* Notices*/
const uint16_t LOG_PROCESS = 80; /* Process exaplaining */
std::map<std::string, uint16_t> GloveBase::_additionalServices = {
{ "ws", 80 }, /* Web Sockets */
{ "wss", 443 } /* Web Sockets (secure)*/
};
#if ENABLE_OPENSSL
bool Glove::openSSLInitialized = false;
#endif
namespace
{
enum
{
TCP_OK = 0,
TCP_ERROR = -1,
TCP_TIMEOUT = -2
};
/* Some bundled functions to make life easier */
static timeval as_timeval ( double seconds )
{
timeval tv;
tv.tv_sec = (int)(seconds);
tv.tv_usec = (int)((seconds - (int)(seconds)) * 1000000.0);
return tv;
}
/* std::stod is fast, sprintf is faster, but this is faster
and it's just what i want in some cases. */
char* __itoa(int val, char* buf)
{
int i = 10;
for(; val && i ; --i, val /= 10)
{
buf[i] = "0123456789"[val % 10];
}
return &buf[i+1];
}
template <typename delimiters_t>
std::vector< std::string > split(const std::string & str, const delimiters_t & sep, uint32_t maxsplit = 0)
{
std::vector< std::string > result;
// Skip delimiters at beginning.
std::string::size_type lastPos = str.find_first_not_of(sep, 0);
// Find first "non-delimiter".
std::string::size_type pos = str.find_first_of(sep, lastPos);
while (std::string::npos != pos || std::string::npos != lastPos)
{
// Found a token, add it to the vector.
result.push_back(str.substr(lastPos, pos - lastPos));
// Skip delimiters. Note the "not_of"
lastPos = str.find_first_not_of(sep, pos);
// Find next "non-delimiter"
pos = str.find_first_of(sep, lastPos);
}
return result;
}
int _serverFilterMatchIp (const Glove* server, std::string ipAddress, std::string hostname, uint16_t remotePort, std::string data0, std::string data1, uint32_t data2, double data3)
{
/* data0 stores the CIDR or mask */
/* data2 is 0 to deny CIDR, any othre value is to accept */
if (GloveBase::matchIp(ipAddress, data0))
return (data2)?1:-1;
else
return 0;
}
#if ENABLE_OPENSSL
/**
* Extract a substring from origin into buffer, updating starting
* value to call in chain. Used by ASN1_TIME_to_time_t to extract
* substrings easyly
*
* @param buffer Where to write to
* @param origin Original string
* @param from Where to start from.
* Updated to the last position after end.
* @param size Characters to extract.
*
* @return char* reference to buffer
*/
char* join(char* buffer, const char* origin, size_t *from, size_t size)
{
size_t i=0;
while (i<size)
{
buffer[i++] = origin[(*from)++];
}
buffer[i] = '\0';
return buffer;
}
/**
* Transforms ASN1 time sring to time_t (except milliseconds and time zone)
* Ideas from: http://stackoverflow.com/questions/10975542/asn1-time-conversion
*
* @param time SSL ASN1_TIME pointer
* @param tmt time_t pointer to write to
*
* @return int 0 if OK, <0 if anything goes wrong
*/
int ASN1_TIME_to_time_t(ASN1_TIME* time, time_t *tmt)
{
const char* data = (char*)time->data;
size_t p = 0;
char buf[5];
struct tm t;
memset(&t, 0, sizeof(t));
size_t datalen = strlen(data);
if (time->type == V_ASN1_UTCTIME) {/* two digit year */
/* error checking YYMMDDHH at least */
if (datalen<8)
return -1;
t.tm_year = atoi (join(buf, data, &p, 2));
if (t.tm_year<70)
t.tm_year += 100;
datalen = strlen(data+2);
} else if (time->type == V_ASN1_GENERALIZEDTIME) {/* four digit year */
/* error checking YYYYMMDDHH at least*/
if (datalen<10)
return -1;
t.tm_year = atoi (join(buf, data, &p, 4));
t.tm_year -= 1900;
datalen = strlen(data+4);
}
/* the year is out of datalen. Now datalen is fixed */
t.tm_mon = atoi (join(buf, data, &p, 2))-1; /* January is 0 for time_t */
t.tm_mday= atoi (join(buf, data, &p, 2));
t.tm_hour= atoi (join(buf, data, &p, 2));
if (datalen<8)
return !(*tmt = mktime(&t));
t.tm_min = atoi (join(buf, data, &p, 2));
if (datalen<10)
return !(*tmt = mktime(&t));
t.tm_sec = atoi (join(buf, data, &p, 2));
/* Ignore millisecnds and time zone */
return !(*tmt = mktime(&t));
}
/**
* Test if file exists
*
* @param filename File Name in char*
*
* @return 1 if file exists, 0 if not, -1 if errors
*/
short fileExists(const char *filename)
{
int fd=open(filename, O_RDONLY);
if (fd==-1)
{
if (errno==2) /* If errno==2 it means file not found */
return 0; /* otherwise there is another error at */
else /* reading file, for example path not */
return -1; /* found, no memory, etc */
}
close(fd); /* If we close the file, it exists */
return 1;
}
#endif
};
/* Support for older versions of GCC */
#if defined(__GNUC__) && (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__ <= 50200 )
namespace std
{
static std::string put_time( const std::tm* tmb, const char* fmt )
{
std::string s( 128, '\0' );
size_t written;
while( !(written=strftime( &s[0], s.size(), fmt, tmb ) ) )
s.resize( s.size() + 128 );
s[written] = '\0';
return s.c_str();
}
}
#endif
namespace
{
/**
* Writes formatted time on string
*
*/
std::string timeformat(const std::chrono::system_clock::time_point& moment, const std::string &format)
{
std::tm tm;
const time_t tim = std::chrono::system_clock::to_time_t(moment);
localtime_r(&tim, &tm);
std::stringstream ss;
ss << std::put_time(&tm, format.c_str());
return ss.str();
}
};
void GloveBase::setsockopt(int level, int optname, void *optval, socklen_t optlen)
{
if (SETSOCKOPT(conn.sockfd, level, optname, optval, optlen) < 0)
throw GloveException(14, append_errno("Failed to set option on socket: "));
}
void GloveBase::getsockopt(int level, int optname, void *optval, socklen_t *optlen)
{
if (GETSOCKOPT(conn.sockfd, level, optname, optval, optlen) < 0)
throw GloveException(15, append_errno("Failed to get option on socket: "));
}
int GloveBase::get_integer_sockopts_level(int optname)
{
switch (optname)
{
case SO_KEEPALIVE:
case SO_REUSEADDR:
return SOL_SOCKET;
default:
throw GloveException(16, "Unrecognised socket option, or it does not accepts int");
}
}
void GloveBase::setsockopt(int optname, int val)
{
int level = get_integer_sockopts_level(optname);
setsockopt(level, optname, &val, sizeof(val));
}
void GloveBase::getsockopt(int optname, int &val)
{
socklen_t val_len = sizeof(val);
int level = get_integer_sockopts_level(optname);
getsockopt(level, optname, &val, &val_len);
}
void GloveBase::log(uint8_t type, uint16_t code, std::string message, std::string more)
{
if (_loggerCallback == nullptr)
return;
_loggerCallback(type, code, message, more);
}
bool GloveBase::is_connected()
{
char buf;
int res = RECV(conn.sockfd, &buf, 1, MSG_PEEK | MSG_DONTWAIT);
if (res<0)
{
// Maybe disconnected or maybe not...
if (errno == EAGAIN || errno == EWOULDBLOCK)
return true;
else
throw GloveException(18, append_errno("Socket error"));
}
else if (res==0)
{
return false;
}
return true;
}
int GloveBase::matchIp(const uint32_t address, const uint32_t network, const uint8_t bits=24)
{
/* Some inspiration for IPv6:
https://github.com/symfony/http-foundation/blob/652e8af9d22c16c5b6556048136021db0b8c6640/IpUtils.php
http://stackoverflow.com/questions/7213995/ip-cidr-match-function
*/
// from addr4_match() method: http://fxr.watson.org/fxr/source/include/net/xfrm.h?v=linux-2.6#L840
if (bits == 0)
return true;
return !((address ^network) & htonl(0xFFFFFFFFu << (32 - bits)));
}
int GloveBase::matchIp(const std::string address, const std::string cidr, bool notOnlyCIDR, bool noException)
{
in_addr ipAddress;
int pton_res;
pton_res = inet_pton4(address, &ipAddress, noException);
if (pton_res<=0)
return -1;
/* Only IP4 at this moment */
auto baseIpAndMask = GloveBase::getNetworkAndMask(cidr, notOnlyCIDR, noException);
return !((ipAddress.s_addr ^ baseIpAndMask.first) & baseIpAndMask.second);
}
int GloveBase::inet_pton4(const std::string addr, in_addr* result, bool noException)
{
int pton_res = inet_pton(AF_INET, addr.c_str(), result);
if (!noException) /* If we want exceptions*/
{
if (pton_res == 0)
{
throw GloveException(37, "Given IP Address is not valid");
}
else if (pton_res<0)
{
throw GloveException(38, "Wrong family specified.");
}
}
return pton_res;
}
std::pair<uint32_t, uint32_t> GloveBase::getNetworkAndMask(const std::string cidr, bool notOnlyCIDR, bool noException)
{
uint32_t mask = 0xFFFFFFFFu, finalAddress;
auto slash = cidr.find('/');
if (slash != std::string::npos)
{
/* Have slash ! */
auto addressStr = cidr.substr(0, slash);
auto bitsQty = std::stoi(cidr.substr(slash+1));
if ( (bitsQty<0) || (bitsQty>32) )
{
if (noException)
return std::pair<uint32_t, uint32_t>(0, 0);
else
throw GloveException(39, "Wrong CIDR input");
}
mask = mask << (32 - bitsQty);
in_addr tempNw;
/* Return only if noException */
if (inet_pton4(addressStr, &tempNw, noException)<=0)
return std::pair<uint32_t, uint32_t>(0, 0);
finalAddress = tempNw.s_addr;
}
else if (notOnlyCIDR)
{
auto ipNumbers = split(cidr, ".");
if (ipNumbers.size()!=4)
throw GloveException(39, "Wrong CIDR input");
uint32_t mult=1;
finalAddress=0;
mask=~0;
for (auto n=ipNumbers.rbegin(); n!= ipNumbers.rend(); ++n)
{
if (*n=="*")
{
mask-=0xff*mult;
}
else
{
finalAddress+= std::stoi(*n)*mult;
}
mult*=256;
}
finalAddress = htonl(finalAddress);
/* Don't have a slash */
}
else
{
in_addr tempNw;
if (inet_pton4(cidr, &tempNw, noException)<=0)
return std::pair<uint32_t, uint32_t>(0, 0);
finalAddress=tempNw.s_addr;
mask=(uint32_t)~0;
/* Only CIDR or simple IP */
}
return std::pair<uint32_t, uint32_t>(finalAddress, htonl(mask));
}
void GloveBase::register_dtm()
{
start_dtm = std::chrono::system_clock::now();
}
std::string GloveBase::append_errno(std::string message)
{
return message +std::string(strerror(errno));
}
int GloveBase::select(int fd, const double timeout, int test)
{
// set up the file descriptor set
fd_set fds;
FD_ZERO(&fds);
FD_SET(fd, &fds);
fd_set *rset=NULL, *wset=NULL;
// set up the struct timeval for the timeout
timeval tv = as_timeval( timeout );
if (test & SELECT_READ)
rset=&fds;
if (test & SELECT_WRITE)
wset=&fds;
// wait until timeout or data received
// if tv = {n,m}, then select() waits up to n.m seconds
// if tv = {0,0}, then select() does polling
// if &tv = NULL, then select() waits forever
int ret = SELECT(fd+1, rset, wset, NULL, &tv);
return ( ret == -1 ? fd = -1, TCP_ERROR : ret == 0 ? TCP_TIMEOUT : TCP_OK );
}
int GloveBase::select(const double timeout, int test)
{
return GloveBase::select(conn.sockfd, timeout, test);
/* // set up the file descriptor set */
/* fd_set fds; */
/* FD_ZERO(&fds); */
/* FD_SET(conn.sockfd, &fds); */
/* fd_set *rset=NULL, *wset=NULL; */
/* // set up the struct timeval for the timeout */
/* timeval tv = as_timeval( timeout ); */
/* if (test & SELECT_READ) */
/* rset=&fds; */
/* if (test & SELECT_WRITE) */
/* wset=&fds; */
/* // wait until timeout or data received */
/* // if tv = {n,m}, then select() waits up to n.m seconds */
/* // if tv = {0,0}, then select() does polling */
/* // if &tv = NULL, then select() waits forever */
/* int ret = SELECT(conn.sockfd+1, rset, wset, NULL, &tv); */
/* return ( ret == -1 ? conn.sockfd = -1, TCP_ERROR : ret == 0 ? TCP_TIMEOUT : TCP_OK ); */
}
void GloveBase::_send(const std::string &data)
{
std::string out = run_filters(FILTER_OUTPUT, data);
int bytes_sent;
do
{
#if ENABLE_OPENSSL
/* Sent with SSL or not */
if (conn.secureConnection == ENABLE_SSL)
bytes_sent = SSL_write(conn.ssl, out.c_str(), out.size());
else
#endif
// msg_nosignal avoid systems signals
bytes_sent = SEND( conn.sockfd, out.c_str(), out.size(), MSG_NOSIGNAL);
if (bytes_sent == -1)
{
throw GloveException(6, append_errno("Socket error when sending: "));
}
out = out.substr ( bytes_sent );
}
while (out.size() > 0);
}
std::string GloveBase::_receive_fixed(const size_t size, double timeout, const bool timeout_when_data, size_t _buffer_size, short _read_once, bool exception_on_timeout)
{
std::string in;
int bytes_received;
size_t requested_size=size;
#if ENABLE_OPENSSL
/* openssl has not downloaded all bytes from the buffer */
size_t pending_bytes=0;
#endif
if (timeout==-1)
timeout = default_values.timeout;
bool read_once = (_read_once == -1)?default_values.read_once:_read_once;
do
{
int error;
#if ENABLE_OPENSSL
if (!pending_bytes)
#endif
if ( (timeout > 0.0) && ( ( ( error= select(timeout) ) != TCP_OK) ) )
{
if (error == TCP_TIMEOUT)
{
if ( (!exception_on_timeout) || ( (in.length()>0) && (!timeout_when_data) && (size==0) ) )
{
if (_read_once) /* If we return directly we won't apply filters on timeout */
return "";
else
break;
}
// break; // Sometimes we don't want to return an exception here.
// But, we must have low timeout.
// Not when fixed
else
throw GloveException(7, "Timed out while receiving data");
}
else
throw GloveException(8, append_errno("Error while waiting for data: "));
}
/* Can put this before de do {} */
int __buffer_size = (size>0)?((requested_size>_buffer_size)?_buffer_size:requested_size):_buffer_size;
std::string buffer(__buffer_size, '\0');
/* #if ENABLE_OPENSSL */
/* std::cout << "SSL:"<<conn.secureConnection<<"\n"; */
/* if (conn.secureConnection == ENABLE_SSL) */
/* { */
/* std::cout << "SSL ENABLED\n"; */
/* if (default_values.ssltimeout) */
/* { */
/* std::timed_mutex sslreadmutex; */
/* sslreadmutex.lock(); */
/* std::thread sslthread([&]() { */
/* bytes_received = SSL_read(conn.ssl, &buffer[0], buffer.size()-1); */
/* sslreadmutex.unlock(); */
/* }); */
/* sslthread.detach(); */
/* # if defined(__GNUC__) && (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__ >= 40900 ) */
/* if (!sslreadmutex.try_lock_for(std::chrono::milliseconds((unsigned)(timeout*1000)))) */
/* { */
/* # else */
/* # warning "Older GCC version, using workaround to get timed locks" */
/* struct timespec ttout; */
/* clock_gettime(CLOCK_REALTIME, &ttout); */
/* ttout.tv_nsec+= (unsigned)(((long double)timeout-floor(timeout))*1000000000L); */
/* ttout.tv_sec += (time_t)floor(timeout)+ttout.tv_nsec/1000000000L ; */
/* ttout.tv_nsec= ttout.tv_nsec%1000000000L; */
/* int pmt = pthread_mutex_timedlock(sslreadmutex.native_handle(), &ttout); */
/* if (pmt!=0) */
/* # endif */
/* { */
/* pthread_cancel(sslthread.native_handle()); */
/* throw GloveException(40, "Timed out while receiving SSL data"); */
/* } */
/* sslreadmutex.unlock(); */
/* # if defined(__GNUC__) && (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__ >= 40900 ) */
/* } */
/* # endif */
/* } */
/* else */
/* bytes_received = SSL_read(conn.ssl, &buffer[0], buffer.size()-1); */
/* } */
/* else */
/* #endif */
#if ENABLE_OPENSSL
if (conn.secureConnection == ENABLE_SSL)
{
if (default_values.ssltimeout)
{
std::timed_mutex sslreadmutex;
sslreadmutex.lock();
std::thread sslthread([&]() {
bytes_received = SSL_read(conn.ssl, &buffer[0], buffer.size()-1);
sslreadmutex.unlock();
});
sslthread.detach();
# if defined(__GNUC__) && (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__ >= 40900 )
if (!sslreadmutex.try_lock_for(std::chrono::milliseconds((unsigned)(timeout*1000))))
{
# else
# warning "Older GCC version, using workaround to get timed locks"
struct timespec ttout;
clock_gettime(CLOCK_REALTIME, &ttout);
ttout.tv_nsec+= (unsigned)(((long double)timeout-floor(timeout))*1000000000L);
ttout.tv_sec += (time_t)floor(timeout)+ttout.tv_nsec/1000000000L ;
ttout.tv_nsec= ttout.tv_nsec%1000000000L;
int pmt = pthread_mutex_timedlock(sslreadmutex.native_handle(), &ttout);
if (pmt!=0)
{
# endif
pthread_cancel(sslthread.native_handle());
throw GloveException(40, "Timed out while receiving SSL data");
}
else
sslreadmutex.unlock();
}
else
bytes_received = SSL_read(conn.ssl, &buffer[0], buffer.size()-1);
}
else
#endif
bytes_received = RECV (conn.sockfd, &buffer[0], buffer.size(), 0);
if (bytes_received < 0)
throw GloveException(9, append_errno("Error receiving data: "));
if (bytes_received == 0)
{
if (default_values.exceptions & EXCEPTION_DISCONNECTED)
throw GloveException(21, "Peer shutdown");
else
break;
}
// return in;
requested_size-=bytes_received;
in +=buffer.substr(0, bytes_received);
if (size>0)
{
requested_size-=bytes_received;
if (requested_size<=0)
break;
}
#if ENABLE_OPENSSL
// pending_bytes = SSL_pending(conn.ssl);
if ( (conn.secureConnection == ENABLE_SSL) && (pending_bytes = SSL_pending(conn.ssl)) )
{
continue;
}
#endif
}
while ( (requested_size > 0) && (!read_once) );
return run_filters(FILTER_INPUT, in);
}
void GloveBase::add_filter(GloveBase::filter_type type, std::string name, GloveBase::filter_callback filter, std::string option, std::string value)
{
auto& filter_vector = (type==FILTER_INPUT)?input_filters:output_filters;
if (option=="start" || option=="beginning")
filter_vector.insert(filter_vector.begin(), {name, filter});
else if (option == "before")
{
for (auto it = filter_vector.begin(); it!= filter_vector.end(); ++it)
{
if (it->name == value)
{
filter_vector.insert(it, {name, filter});
return;
}
}
}
else
filter_vector.push_back({name, filter});
}
bool GloveBase::remove_filter(GloveBase::filter_type type, std::string name)
{
auto& filter_vector = (type==FILTER_INPUT)?input_filters:output_filters;
for(auto it = filter_vector.begin(); it != filter_vector.end(); ++it)
if (it->name == name)
{
filter_vector.erase(it);
return true;
}
// false not removed
return false;
}
std::vector<std::string> GloveBase::get_filters(GloveBase::filter_type type)
{
auto& filter_vector = (type==FILTER_INPUT)?input_filters:output_filters;
std::vector <std::string> out;
for(auto it = filter_vector.begin(); it != filter_vector.end(); ++it)
out.push_back(it->name);
return out;
}
std::string GloveBase::run_filters(GloveBase::filter_type type, const std::string &_input)
{
if ( (type == FILTER_INPUT) && (!default_values.enable_input_filters) )
return _input;
else if ( (type == FILTER_OUTPUT) && (!default_values.enable_output_filters) )
return _input;
std::string input = _input;
auto& filter_vector = (type==FILTER_INPUT)?input_filters:output_filters;
for (auto f = filter_vector.begin(); f!= filter_vector.end(); ++f)
{
input = f->filter(input);
}
return input;
}
void GloveBase::disconnect(int how)
{
if (how == SHUT_XX)
{
if (CLOSE(conn.sockfd) < 0)
throw GloveException(10, append_errno("Socket was not closed successfully: "));
}
else
{
if (SHUTDOWN(conn.sockfd, how) < 0)
throw GloveException(20, append_errno("Socket was not shutted down successfully"));
}
}
std::string GloveBase::user_and_pass(const std::string& user, const std::string &password)
{
if ( (password != "") && (user == "") )
throw GloveUriException(1000, "User must be present if password is");
std::string res=user;
if (password != "")
res+=":"+password;
if (res != "")
res+="@";
return res;
}