forked from 3s3s/3s3s.org
-
Notifications
You must be signed in to change notification settings - Fork 0
/
simple_server.h
2803 lines (2363 loc) · 69.3 KB
/
simple_server.h
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
#ifndef _SIMPLE_SERVER
#define _SIMPLE_SERVER
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include "log.h"
#include <unordered_map>
//#include "StartupInfo.h"
//#include "custom_plugins.h"
#ifdef WIN32
#include <direct.h>
#include <sys/utime.h>
#include "./zlib-1.2.7/zlib.h"
#define _mkdir(a, b) _mkdir(a)
#define utimbuf _utimbuf
#define utime _utime
#else
#define _mkdir mkdir
#define _fileno fileno
#include <utime.h>
#include <zlib.h>
#endif
//#define _DEBUG
#define d2_printf //
#ifdef __linux__
#define _EPOLL
#define _SEND_FILE
#define Sleep(a) usleep(a*1000)
#endif
#ifdef _DEBUG
#define d_printf printf
#else
#define d_printf //
#endif
#ifdef _WIN32
#define _WIN32_WINNT 0x600
#include <io.h>
# include <Winsock2.h>
# include <WS2TCPIP.H>
# pragma comment(lib, "ws2_32.lib")
#define SET_NONBLOCK(socket) \
if (true) \
{ \
DWORD dw = true; \
ioctlsocket(socket, FIONBIO, &dw); \
}
#define SET_BLOCK(socket) \
if (true) \
{ \
DWORD dw = false; \
ioctlsocket(socket, FIONBIO, &dw); \
}
#define BEGIN_SEND //
#define END_SEND //
#define snprintf _snprintf
#define open _open
#define popen _popen
#define pclose _pclose
#define close _close
#define off_t _off_t
enum EPOLL_EVENTS
{
EPOLLIN = 0x001,
#define EPOLLIN EPOLLIN
EPOLLPRI = 0x002,
#define EPOLLPRI EPOLLPRI
EPOLLOUT = 0x004,
#define EPOLLOUT EPOLLOUT
EPOLLRDNORM = 0x040,
#define EPOLLRDNORM EPOLLRDNORM
EPOLLRDBAND = 0x080,
#define EPOLLRDBAND EPOLLRDBAND
EPOLLWRNORM = 0x100,
#define EPOLLWRNORM EPOLLWRNORM
EPOLLWRBAND = 0x200,
#define EPOLLWRBAND EPOLLWRBAND
EPOLLMSG = 0x400,
#define EPOLLMSG EPOLLMSG
EPOLLERR = 0x008,
#define EPOLLERR EPOLLERR
EPOLLHUP = 0x010,
#define EPOLLHUP EPOLLHUP
EPOLLRDHUP = 0x2000,
#define EPOLLRDHUP EPOLLRDHUP
EPOLLONESHOT = (1 << 30),
#define EPOLLONESHOT EPOLLONESHOT
EPOLLET = (1 << 31)
#define EPOLLET EPOLLET
};
/* Valid opcodes ( "op" parameter ) to issue to epoll_ctl(). */
#define EPOLL_CTL_ADD 1 /* Add a file descriptor to the interface. */
#define EPOLL_CTL_DEL 2 /* Remove a file descriptor from the interface. */
#define EPOLL_CTL_MOD 3 /* Change file descriptor epoll_event structure. */
typedef union epoll_data
{
void *ptr;
int fd;
unsigned int u32;
unsigned __int64 u64;
} epoll_data_t;
struct epoll_event
{
unsigned __int64 events; /* Epoll events */
epoll_data_t data; /* User data variable */
};
#else
# include <signal.h>
# include <sys/socket.h>
# include <sys/stat.h>
# include <unistd.h>
# include <ctype.h>
# include <netinet/in.h>
# include <netdb.h>
# include <arpa/inet.h>
# include <errno.h>
#define lseek64 _lseeki64
#define fsync(fd) _flushall()
#define closesocket(socket) close(socket)
#define WSAGetLastError() errno
#define SET_NONBLOCK(socket) \
if (fcntl( socket, F_SETFL, fcntl( socket, F_GETFL, 0 ) | O_NONBLOCK ) < 0) \
d_printf("error in fcntl errno=%i\n", errno);
//Ignoring 'broken pipe' signal
#define BEGIN_SEND \
struct sigaction sa; \
memset(&sa, 0, sizeof(sa)); \
sa.sa_handler = SIG_IGN; \
sigaction(SIGPIPE, &sa, NULL);
//Wait for 'broken pipe' signal
#define END_SEND \
memset(&sa, 0, sizeof(sa)); \
sa.sa_handler = SIG_DFL; \
sigaction(SIGPIPE, &sa, NULL);
typedef unsigned int SOCKET;
typedef unsigned char BYTE;
#define S_OK 0
#define SD_SEND 0x01
#define SD_BOTH 0x02
#define MAX_PATH 255
#define INVALID_SOCKET (SOCKET)(~0)
#define SOCKET_ERROR (-1)
#define WSAEINPROGRESS EINPROGRESS
#define WSAEWOULDBLOCK EWOULDBLOCK
#endif
#ifdef __linux__
#include <sys/sendfile.h>
#include <sys/epoll.h>
#include <netinet/tcp.h>
#include <string.h>
#endif
#ifdef _WIN32
#define O_NONBLOCK 0
#endif
#include <assert.h>
#include <memory>
#include <vector>
#include <string>
#include <map>
#include <set>
#include <iostream>
#include <sstream>
#include "curl_helper.h"
#include "html_framework.h"
#include <openssl/rsa.h> /* SSLeay stuff */
#include <openssl/crypto.h>
#include <openssl/x509.h>
#include <openssl/pem.h>
#include <openssl/ssl.h>
#include <openssl/err.h>
using namespace std;
#ifdef MYCURL
using namespace curl;
//CUrl gCURL;
#endif
extern set<string> g_vWhiteListedIP;
namespace simple_server
{
namespace utils
{
template<class T> inline void Replace(T& str, const int nPos, const T& str1, const T& str2)
{
const auto str2Size(str2.size());
const auto str1Size(str1.size());
auto n = nPos;
while (T::npos != (n = str.find(str1, n))) {
str.replace(n, str1Size, str2);
n += str2Size;
}
}
}
enum ACTION
{
A_NULL,
A_ACCEPTED,
A_READING,
A_HEADER_READED,
A_SENDING,
A_ALL_SENDED,
A_ERROR,
A_CGI_START,
A_CGI_CONTINUE,
A_CGI_END
};
#if defined(MSDOS) || defined(OS2) || defined(WIN32) || defined(__CYGWIN__)
# include <fcntl.h>
# include <io.h>
# define SET_BINARY_MODE(file) setmode(fileno(file), O_BINARY)
#else
# define SET_BINARY_MODE(file)
#endif
#define CHUNK 16384
class CFile
{
string m_strFileName;
bool m_bGzip;
explicit CFile(const CFile &file);
public:
/* Compress from file source to file dest until EOF on source.
def() returns Z_OK on success, Z_MEM_ERROR if memory could not be
allocated for processing, Z_STREAM_ERROR if an invalid compression
level is supplied, Z_VERSION_ERROR if the version of zlib.h and the
version of the library linked do not match, or Z_ERRNO if there is
an error reading or writing the files. */
static int def(FILE *source, FILE *dest)
{
int ret, flush;
unsigned have;
z_stream strm;
unsigned char in[CHUNK];
unsigned char out[CHUNK];
/* allocate deflate state */
strm.zalloc = Z_NULL;
strm.zfree = Z_NULL;
strm.opaque = Z_NULL;
//ret = deflateInit(&strm, level);
ret = deflateInit2(&strm, Z_DEFAULT_COMPRESSION, Z_DEFLATED, (15+16), 8, Z_DEFAULT_STRATEGY);
if (ret != Z_OK)
return ret;
/* compress until end of file */
do {
strm.avail_in = fread(in, 1, CHUNK, source);
if (ferror(source)) {
(void)deflateEnd(&strm);
return Z_ERRNO;
}
flush = feof(source) ? Z_FINISH : Z_NO_FLUSH;
strm.next_in = in;
/* run deflate() on input until output buffer not full, finish
compression if all of source has been read in */
do {
strm.avail_out = CHUNK;
strm.next_out = out;
ret = deflate(&strm, flush); /* no bad return value */
assert(ret != Z_STREAM_ERROR); /* state not clobbered */
have = CHUNK - strm.avail_out;
if (fwrite(out, 1, have, dest) != have || ferror(dest)) {
(void)deflateEnd(&strm);
return Z_ERRNO;
}
} while (strm.avail_out == 0);
assert(strm.avail_in == 0); /* all input will be used */
/* done when last data in file processed */
} while (flush != Z_FINISH);
assert(ret == Z_STREAM_END); /* stream will be complete */
/* clean up and return */
(void)deflateEnd(&strm);
return Z_OK;
}
public:
operator int() const {return m_nFile;}
~CFile()
{
if (m_pFile)
fclose(m_pFile);
else if (m_nFile)
close(m_nFile);
}
CFile(string strPath, bool bGzip, string strMode = "rb") :
m_nFile(0), m_bGzip(bGzip)
{
FillContentType(strPath);
Open(strPath, strMode);
}
void Open(string strPath, string strMode = "r+b")
{
size_t nPos = strPath.rfind('/');
if (nPos < strPath.length()-1)
m_strFileName = strPath.substr(nPos);
m_nFile = 0;
if ((!m_strContentType.length()) || (!m_bGzip))
{
DEBUG_LOG("open not gzipped file");
m_pFile = fopen(strPath.c_str(), strMode.c_str());
}
else
{
string strGzipPath = "./gziped_files/"+html::utils::md5(m_strFileName);
DEBUG_LOG("try mkdir");
_mkdir("./gziped_files", S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
Copy(strPath, strGzipPath);
m_pFile = fopen(strGzipPath.c_str(), strMode.c_str());
m_strContentType += "\r\nContent-Encoding: gzip";
}
if (m_pFile)
m_nFile = _fileno(m_pFile);
if (m_nFile != -1)
fstat(m_nFile, &stat_buf);
}
static void Copy(string strFrom, string strTo)
{
FILE *pFrom = fopen(strFrom.c_str(), "rb");
if (!pFrom)
return;
int nFrom = _fileno(pFrom);
if (!nFrom)
{
fclose(pFrom);
return;
}
struct stat statFrom, statTo;
fstat(nFrom, &statFrom);
FILE *pTo = fopen(strTo.c_str(), "r+b");
if (pTo)
{
int nTo = _fileno(pTo);
if (nTo)
{
fstat(nTo, &statTo);
if (statFrom.st_mtime == statTo.st_mtime)
{
fclose(pFrom);
fclose(pTo);
return;
}
}
fclose(pTo);
}
pTo = fopen(strTo.c_str(), "w+b");
if (!pTo)
{
fclose(pFrom);
return;
}
//ProcessCopy(pFrom, statFrom.st_size, pTo);
def(pFrom, pTo);
fclose(pFrom);
fclose(pTo);
struct utimbuf times;
times.actime = statFrom.st_atime;
times.modtime = statFrom.st_mtime;
utime(strTo.c_str(), ×);
}
const off_t GetFileSize() const
{
return stat_buf.st_size;
}
inline void FillContentType(string strPath)
{
string strEncodding = "charset=utf-8";
if ((strPath.rfind(".htm") == strPath.length()-4) || (strPath.rfind(".html") == strPath.length()-5))
m_strContentType = "text/html; " + strEncodding;
else if (strPath.rfind(".txt") == strPath.length()-4)
m_strContentType = "text/plain " + strEncodding;
else if (strPath.rfind(".css") == strPath.length()-4)
m_strContentType = "text/css; " + strEncodding;
else if (strPath.rfind(".xml") == strPath.length()-4)
m_strContentType = "text/xml; " + strEncodding;
else if (strPath.rfind(".js") == strPath.length()-3)
m_strContentType = "application/javascript; " + strEncodding;
else
m_strContentType = "application/octet-stream";
}
const string GetContentType() const
{
return m_strContentType;
}
const bool IsOpen () const {return ((m_pFile!=0) || (m_nFile!=0));}
inline size_t ReadBuffer(void *pBuffer, size_t nCount, size_t startPosition)
{
if (!m_pFile)
{
d_printf("ERROR: file handle is NULL\n");
return 0;
}
if (fseek(m_pFile, startPosition, SEEK_SET) != 0)
{
d_printf("ERROR: seek error\n");
return 0;
}
size_t ret = fread(pBuffer, 1, nCount, m_pFile);
if (ret == 0)
{
d_printf("fread return 0 (nCount=%i)\n", nCount);
}
return ret;
}
private:
int m_nFile;
struct stat stat_buf;
string m_strContentType;
FILE *m_pFile;
};
template <class startupType>
class CInterface
{
public:
startupType m_StartupInfo;
CInterface(startupType info) :
m_StartupInfo(info)
{
}
fd_set m_readfds, m_writefds, m_exceptfds;
vector<struct epoll_event> m_events;
};
class CSocket
{
SSL_CTX* m_pSSLContext;
SSL* m_pSSL;
explicit CSocket(const CSocket &socket) {int *p = new int;}
public:
bool ShutdownSocket(int nHow = SD_BOTH)
{
DEBUG_LOG("ShutdownSocket\n");
if (m_hSocket == INVALID_SOCKET)
return true;
shutdown(m_hSocket, nHow);
//m_bConnected = false;
return true;
}
void Cleanup()
{
m_bAllRecieved = false;
m_nAllRecieved = 0;
m_nSendPosition = 0;
m_readBuffer.clear();
m_sendBuffer.clear();
}
private:
bool CloseSocket()
{
DEBUG_LOG("CloseSocket m_hSocket=%i\n", GetHandle());
m_bConnected = false;
if (m_hSocket == INVALID_SOCKET)
return true;
ShutdownSocket();
closesocket(m_hSocket);
m_hSocket = INVALID_SOCKET;
return true;
}
bool m_bSSL;
public:
const bool IsSSL() const {return m_bSSL;}
#ifndef _DEBUG
CSocket(int nPort, bool bIsSSL) :
m_hSocket(socket(PF_INET6, SOCK_STREAM, 0)), m_nPort(nPort), m_bSSL(bIsSSL), m_pSSL(NULL), m_pSSLContext(NULL)
{
if (m_hSocket == INVALID_SOCKET)
return;
if (m_bSSL)
InitSSL();
if (m_hSocket == INVALID_SOCKET)
return;
cout << "socket created\n";
SET_NONBLOCK(m_hSocket);
struct sockaddr_in6 local;
memset(&local, 0, sizeof(local));
local.sin6_family = AF_INET6;
local.sin6_port = htons(nPort);
local.sin6_addr = in6addr_any;
const char on = 1;
setsockopt(m_hSocket, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
setsockopt(m_hSocket, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on));
if ( ::bind(m_hSocket, (struct sockaddr*)&local, sizeof(local)) == SOCKET_ERROR)
{
DEBUG_LOG("bind error = %i", errno);
CloseSocket();
return;
}
cout << "socket binded\n";
//if (m_bSSL)
// return;
if (listen(m_hSocket, SOMAXCONN) == SOCKET_ERROR)
{
DEBUG_LOG("listen error = %i", errno);
CloseSocket();
return;
}
cout << "listen - ok\n";
}
#else
CSocket(int nPort, bool bIsSSL) :
m_hSocket(socket(PF_INET, SOCK_STREAM, 0)), m_nPort(nPort), m_bSSL(bIsSSL), m_pSSL(NULL), m_pSSLContext(NULL)
{
if (m_hSocket == INVALID_SOCKET)
return;
if (m_bSSL)
InitSSL();
if (m_hSocket == INVALID_SOCKET)
return;
cout << "socket created\n";
SET_NONBLOCK(m_hSocket);
struct sockaddr_in local;
memset(&local, 0, sizeof(local));
local.sin_family = AF_INET;
local.sin_port = htons(nPort);
local.sin_addr.s_addr = htons( INADDR_ANY );
if ( ::bind(m_hSocket, (struct sockaddr*)&local, sizeof(local)) == SOCKET_ERROR)
{
DEBUG_LOG("bind error = %i", errno);
CloseSocket();
return;
}
cout << "socket binded\n";
if (listen(m_hSocket, SOMAXCONN) == SOCKET_ERROR)
{
DEBUG_LOG("listen error = %i", errno);
CloseSocket();
return;
}
cout << "listen - ok\n";
}
#endif
void InitSSL()
{
auto *meth = SSLv23_server_method();
m_pSSLContext = SSL_CTX_new (meth);
if (SSL_CTX_use_certificate_chain_file(m_pSSLContext, CERTF) <= 0)
ERR_print_errors_fp(stderr);
// SSL_CTX_set_default_passwd_cb_userdata(m_pSSLContext, (void*)(sKeyPassWord.c_str()));
if (SSL_CTX_use_PrivateKey_file(m_pSSLContext, KEYF, SSL_FILETYPE_PEM) <= 0)
ERR_print_errors_fp(stderr);
if (!SSL_CTX_check_private_key(m_pSSLContext))
{
DEBUG_LOG("error in check_private_key");
CloseSocket();
//cout << "error in check_private_key\n";
//fprintf(stderr,"Private key does not match the certificate public key\n");
}
}
CSocket(const SOCKET hAcceptedSocket, const struct sockaddr_in6 *pSockAddr, bool bIsSSL) :
m_hSocket(hAcceptedSocket), m_bConnected(true), m_nPort(pSockAddr->sin6_port), m_addr(pSockAddr->sin6_addr), m_bSSL(bIsSSL),
m_pSSL(NULL), m_pSSLContext(NULL)
{
if (m_bSSL)
InitSSL();
}
~CSocket()
{
DEBUG_LOG("Destruct CSocket");
ShutdownSocket();
CloseSocket();
if (m_pSSL)
SSL_free (m_pSSL);
if (m_pSSLContext)
SSL_CTX_free (m_pSSLContext);
}
const int GetHandle() const {return m_hSocket;}
#ifdef _WIN32
#if (_MSC_VER < 1700)
static const char* inet_ntop(int af, const void* src, char* dst, int cnt)
{
SOCKADDR_IN6 srcaddr;
memset(&srcaddr, 0, sizeof(struct sockaddr_in));
memcpy(&(srcaddr.sin6_addr), src, sizeof(srcaddr.sin6_addr));
srcaddr.sin6_family = af;
if (WSAAddressToString((struct sockaddr*) &srcaddr, sizeof(SOCKADDR_IN6), 0, dst, (LPDWORD) &cnt) != 0) {
DWORD rv = WSAGetLastError();
printf("WSAAddressToString() : %d\n",rv);
return NULL;
}
return dst;
} //InetNtop(AF_INET6, (void *)&m_addr, saddr, INET6_ADDRSTRLEN);
#endif
#endif
const string GetIP() const
{
char saddr[INET6_ADDRSTRLEN+10];
inet_ntop(AF_INET6, (void *)&m_addr, saddr, INET6_ADDRSTRLEN);
return saddr;
}
const SOCKET Accept(struct sockaddr_in6 *pServer) const
{
assert (m_hSocket != INVALID_SOCKET);
socklen_t nLen = sizeof(*pServer);
return accept(m_hSocket, (struct sockaddr*)pServer, &nLen);
}
const bool IsAccepted()
{
if ((!m_bSSL) && IsConnected())
return true;
if (!m_pSSLContext)
{
return false;
}
if (!m_pSSL)
{
m_pSSL = SSL_new (m_pSSLContext);
if (!m_pSSL)
{
return false;
}
SSL_set_fd (m_pSSL, m_hSocket);
}
const int err = SSL_accept (m_pSSL);
if (err == 1)
return true;
const int nCode = SSL_get_error(m_pSSL, err);
if ((nCode == SSL_ERROR_WANT_READ) || (nCode == SSL_ERROR_WANT_WRITE))
{
return false;
}
DEBUG_LOG("!IsAccepted");
ShutdownSocket();
CloseSocket();
return false;
}
const bool GetSertificate()
{
if (!m_pSSLContext || !m_pSSL)
return false;
/* Get client's certificate (note: beware of dynamic allocation) - opt */
X509* client_cert = SSL_get_peer_certificate (m_pSSL);
if (client_cert != NULL)
{
d_printf ("Client certificate:\n");
char* str = X509_NAME_oneline (X509_get_subject_name (client_cert), 0, 0);
if (!str)
return false;
d_printf ("\t subject: %s\n", str);
OPENSSL_free (str);
str = X509_NAME_oneline (X509_get_issuer_name (client_cert), 0, 0);
if (!str)
return false;
d_printf ("\t issuer: %s\n", str);
OPENSSL_free (str);
/* We could do all sorts of certificate verification stuff here before
deallocating the certificate. */
X509_free (client_cert);
}
else
d_printf ("Client does not have certificate.\n");
return true;
}
inline bool InitRecv(int nMaxLen)//, string strEndString)
{
m_nAllRecieved = 0;
m_bAllRecieved = false;
m_nMaxLength = nMaxLen;
m_readBuffer.clear();
bool bRet = false;
if (m_bSSL)
bRet = GetSertificate();
else
bRet = ReadSocket();
return bRet;
}
bool ReadSSL()
{
if (!m_pSSLContext || !m_pSSL)
return false;
static char szReadingBuffer[100000];
const int err = SSL_read (m_pSSL, szReadingBuffer, 100000);
if (err > 0)
{
m_readBuffer.resize(m_nAllRecieved+err);
memcpy(&m_readBuffer[m_nAllRecieved], szReadingBuffer, err);
m_nAllRecieved += err;
m_bAllRecieved = true;
return true;
}
const int nCode = SSL_get_error(m_pSSL, err);
if (nCode == SSL_ERROR_NONE)
{
m_bAllRecieved = true;
return true;
}
if ((nCode != SSL_ERROR_WANT_READ) && (nCode != SSL_ERROR_WANT_WRITE))
return false;
return true;
}
inline bool ReadSocket()
{
if ((m_hSocket == INVALID_SOCKET) || (!m_bConnected))
{
d_printf("error: invalid socket\n");
return false;
}
if (m_bSSL)
return ReadSSL();
static char szReadingBuffer[100000];
//m_readBuffer.clear();
// while(true)
// {
int nBuffLen = 100000;
//if (m_nAllRecieved+nBuffLen > m_nMaxLength)
// nBuffLen = m_nMaxLength - m_nAllRecieved;
memset(szReadingBuffer, 0, nBuffLen+10);
d_printf("try recv len=%i\n", nBuffLen);
errno = 0;
int n = recv(m_hSocket, szReadingBuffer, nBuffLen, 0);
d_printf("recv returned n=%i\n", n);
#ifdef _DEBUG
DEBUG_LOG("recv returned n=%i\n", n);
// if (n < 100000)
// DEBUG_LO
#endif
int nError = WSAGetLastError();
#ifndef _WIN32
if (nError == 115)
nError = WSAEWOULDBLOCK;
#endif
if ((nError != WSAEWOULDBLOCK) && (nError != S_OK))
{
//ShutdownSocket();
//CloseSocket();
d_printf("error: recv n=%i, errno=%i\n", n, nError);
return false;
}
if (n == SOCKET_ERROR)
return true;
if (n == 0)
{
DEBUG_LOG("recv return 0 errno=%i", nError);
m_bConnected = false;
m_bAllRecieved = true;
if (m_nAllRecieved == 0)
{
d_printf("error: recv return 0 errno=%i\n", nError);
return false;
}
/*if (m_nAllRecieved != 0)
{
m_bAllRecieved = true;
m_bConnected = false;
}*/
return true;
}
m_readBuffer.resize(m_nAllRecieved+n);
memcpy(&m_readBuffer[m_nAllRecieved], szReadingBuffer, n);
m_nAllRecieved += n;
if (m_nAllRecieved >= m_nMaxLength)
{
m_bAllRecieved = true;
return true;
}
if (nError == S_OK)
{
m_bAllRecieved = true;
return true;
}
// }
return true;
}
inline bool IsAllReaded(string strEnd, unsigned long long llLength)
{
if (m_nAllRecieved >= llLength)
return true;
string strContent = GetReadedContent();
if ((strEnd.length()) && (strContent.rfind(strEnd) == strContent.npos))
m_bAllRecieved = false;
return m_bAllRecieved;
}
void GetReadedContent(vector<BYTE> *pBuffer) const
{
(*pBuffer) = m_readBuffer;
}
const string GetReadedContent(int nStartPos = 0) const
{
string strContent;
if ((!m_nAllRecieved) || (nStartPos >= m_nAllRecieved))
return strContent;
if (!m_readBuffer[nStartPos])
return "";
vector<BYTE> ret = m_readBuffer;
ret.push_back(0);
return (const char*)&(ret[nStartPos]);
}
inline void InitSend()
{
m_nSendPosition = 0;
m_sendBuffer.clear();
}
const ACTION SendVector(vector<BYTE> *pVector)
{
if (!pVector)
return A_ERROR;
if (!pVector->size())
return A_ALL_SENDED;
if (!SendBuffer((const char *)&((*pVector)[0]), pVector->size()))
return A_ERROR;
return A_SENDING;
}
inline ACTION SendFile(const shared_ptr<CFile> pFile, size_t *pnFilePos)
{
#ifdef _SEND_FILE
if (!m_bSSL)
{
ssize_t sended = sendfile(m_hSocket, (int)(*pFile), (off_t *)pnFilePos, 1000000);
if (sended == -1)
{
d2_printf("sendfile error = %i\n", errno);
//exit(0);
return A_ERROR;
}
d_printf("filepos = %i, size = %i\n", *pnFilePos, pFile->GetFileSize());
if (pFile->GetFileSize() != *pnFilePos)
return A_SENDING;
return A_ALL_SENDED;
}
#endif
static BYTE buffer[100005];
size_t stReaded = pFile->ReadBuffer(buffer, 10000, *pnFilePos);
*pnFilePos += stReaded;
if (stReaded == 0)
return A_ALL_SENDED;
if (!SendBuffer((const char*)buffer, stReaded))
return A_ERROR;
return A_SENDING;
}
inline bool SendBuffer(const char *pszBuffer, int nBuffLen)
{
/*string strTemp;
strTemp.assign(pszBuffer, nBuffLen);
DEBUG_LOG("%s", strTemp.c_str());*/
d_printf("SendBuffer\n");
if (m_hSocket == INVALID_SOCKET)