-
Notifications
You must be signed in to change notification settings - Fork 34
/
Copy pathminihttp.cpp
1432 lines (1227 loc) · 35 KB
/
minihttp.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
// minihttp.cpp - All functionality required for a minimal TCP/HTTP client packed in one file.
// Released under the WTFPL (See minihttp.h)
#ifdef _MSC_VER
# ifndef _CRT_SECURE_NO_WARNINGS
# define _CRT_SECURE_NO_WARNINGS
# endif
# ifndef _CRT_SECURE_NO_DEPRECATE
# define _CRT_SECURE_NO_DEPRECATE
# endif
#endif
#ifdef _WIN32
# ifndef _WIN32_WINNT
# define _WIN32_WINNT 0x0501
# endif
# include <winsock2.h>
# include <ws2tcpip.h>
# ifndef EWOULDBLOCK
# define EWOULDBLOCK WSAEWOULDBLOCK
# endif
# ifndef ETIMEDOUT
# define ETIMEDOUT WSAETIMEDOUT
# endif
# ifndef ECONNRESET
# define ECONNRESET WSAECONNRESET
# endif
# ifndef ENOTCONN
# define ENOTCONN WSAENOTCONN
# endif
# include <io.h>
#else
# include <sys/types.h>
# include <unistd.h>
# include <fcntl.h>
# include <sys/socket.h>
# include <netinet/in.h>
# include <netdb.h>
# define SOCKET_ERROR (-1)
# define INVALID_SOCKET (SOCKET)(~0)
typedef intptr_t SOCKET;
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sstream>
#include <cctype>
#include <cerrno>
#include <algorithm>
#include <assert.h>
#ifdef MINIHTTP_USE_MBEDTLS
# include <mbedtls/net.h>
# include <mbedtls/ssl.h>
# include <mbedtls/entropy.h>
# include <mbedtls/ctr_drbg.h>
#endif
#include "minihttp.h"
#define SOCKETVALID(s) ((s) != INVALID_SOCKET)
#ifdef _MSC_VER
# define STRNICMP _strnicmp
#else
# define STRNICMP strncasecmp
#endif
#ifdef _DEBUG
# define traceprint(...) {printf(__VA_ARGS__);}
#else
# define traceprint(...) {}
#endif
namespace minihttp {
#ifdef MINIHTTP_USE_MBEDTLS
// ------------------------ SSL STUFF -------------------------
bool HasSSL()
{
// compile time assertion that mbedtls_net_context really is just an int
switch(0) { case 0:; case (sizeof(mbedtls_net_context) == sizeof(int)):; }
return true;
}
void traceprint_ssl(void *ctx, int level, const char *file, int line, const char *str )
{
(void)ctx;
printf("ssl(%s:%04d) [%d] %s\n", file, line, level, str);
}
struct SSLCtx
{
SSLCtx()
{
mbedtls_entropy_init(&entropy);
mbedtls_x509_crt_init(&cacert);
mbedtls_ssl_init(&ssl);
mbedtls_ctr_drbg_init(&ctr_drbg);
mbedtls_ssl_config_init(&conf);
}
~SSLCtx()
{
mbedtls_entropy_free(&entropy);
mbedtls_x509_crt_free(&cacert);
mbedtls_ssl_free(&ssl);
mbedtls_ctr_drbg_free(&ctr_drbg);
mbedtls_ssl_config_free(&conf);
}
bool init()
{
const char *pers = "minihttp";
const size_t perslen = strlen(pers);
int err = mbedtls_ctr_drbg_seed(&ctr_drbg, mbedtls_entropy_func, &entropy, (const unsigned char *)pers, perslen);
if(err)
{
traceprint("SSLCtx::init(): mbedtls_ctr_drbg_seed() returned %d\n", err);
return false;
}
err = mbedtls_ssl_config_defaults(&conf,
MBEDTLS_SSL_IS_CLIENT,
MBEDTLS_SSL_TRANSPORT_STREAM,
MBEDTLS_SSL_PRESET_DEFAULT);
if(err)
{
traceprint("SSLCtx::init(): mbedtls_ssl_config_defaults() returned %d\n", err);
return false;
}
mbedtls_ssl_conf_authmode(&conf, MBEDTLS_SSL_VERIFY_OPTIONAL);
mbedtls_ssl_conf_ca_chain(&conf, &cacert, NULL);
/* SSLv3 is deprecated, set minimum to TLS 1.0 */
mbedtls_ssl_conf_min_version(&conf, MBEDTLS_SSL_MAJOR_VERSION_3, MBEDTLS_SSL_MINOR_VERSION_1);
mbedtls_ssl_conf_rng(&conf, mbedtls_ctr_drbg_random, &ctr_drbg);
mbedtls_ssl_conf_dbg(&conf, traceprint_ssl, NULL);
err = mbedtls_ssl_setup(&ssl, &conf);
if(err)
{
traceprint("SSLCtx::init(): mbedtls_ssl_init() returned %d\n", err);
return false;
}
return true;
}
void reset()
{
mbedtls_ssl_session_reset(&ssl);
}
mbedtls_entropy_context entropy;
mbedtls_ctr_drbg_context ctr_drbg;
mbedtls_ssl_context ssl;
mbedtls_x509_crt cacert;
mbedtls_ssl_config conf;
};
// ------------------------------------------------------------
#else// MINIHTTP_USE_MBEDTLS
bool HasSSL() { return false; }
#endif
#define DEFAULT_BUFSIZE 4096
inline int _GetError()
{
#ifdef _WIN32
return WSAGetLastError();
#else
return errno;
#endif
}
inline std::string _GetErrorStr(int e)
{
std::string ret;
#ifdef _WIN32
LPTSTR s;
::FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, NULL, e, 0, (LPTSTR)&s, 0, NULL);
if(s)
ret = (const char*)s;
::LocalFree(s);
#else
const char *s = strerror(e);
if(s)
ret = s;
#endif
return ret;
}
static bool _networkInitDone = false;
bool InitNetwork()
{
#ifdef _WIN32
WSADATA wsadata;
if(WSAStartup(MAKEWORD(2,2), &wsadata))
{
traceprint("WSAStartup ERROR: %s", _GetErrorStr(_GetError()).c_str());
return false;
}
#endif
_networkInitDone = true;
return true;
}
void StopNetwork()
{
#ifdef _WIN32
WSACleanup();
#endif
_networkInitDone = false;
}
static bool _Resolve(const char *host, unsigned int port, struct sockaddr_in *addr)
{
char port_str[16];
sprintf(port_str, "%u", port);
struct addrinfo hnt, *res = 0;
memset(&hnt, 0, sizeof(hnt));
hnt.ai_family = AF_INET;
hnt.ai_socktype = SOCK_STREAM;
if (getaddrinfo(host, port_str, &hnt, &res))
{
traceprint("RESOLVE ERROR: %s", _GetErrorStr(_GetError()).c_str());
return false;
}
if (res)
{
if (res->ai_family != AF_INET)
{
traceprint("RESOLVE WTF: %s", _GetErrorStr(_GetError()).c_str());
freeaddrinfo(res);
return false;
}
memcpy(addr, res->ai_addr, res->ai_addrlen);
freeaddrinfo(res);
return true;
}
return false;
}
// FIXME: this does currently not handle links like:
// http://example.com/index.html#pos
bool SplitURI(const std::string& uri, std::string& protocol, std::string& host, std::string& file, int& port, bool& useSSL)
{
const char *p = uri.c_str();
const char *sl = strstr(p, "//");
unsigned int offs = 0;
port = -1;
bool ssl = false;
if(sl)
{
size_t colon = uri.find(':');
size_t firstslash = uri.find('/');
if(colon < firstslash)
protocol = uri.substr(0, colon);
if(strncmp(p, "http://", 7) == 0)
{
offs = 7;
port = 80;
}
else if(strncmp(p, "https://", 8) == 0)
{
offs = 8;
port = 443;
ssl = true;
}
else
return false;
p = sl + 2;
}
sl = strchr(p, '/');
if(!sl)
{
host = p;
file = "/";
}
else
{
host = uri.substr(offs, sl - p);
file = sl;
}
size_t colon = host.find(':');
if(colon != std::string::npos)
{
port = atoi(host.c_str() + colon + 1);
host.erase(colon);
}
useSSL = ssl;
return true;
}
void URLEncode(const std::string& s, std::string& enc)
{
const size_t len = s.length();
char buf[3];
buf[0] = '%';
for(size_t i = 0; i < len; i++)
{
const unsigned char c = s[i];
// from https://www.ietf.org/rfc/rfc1738.txt, page 3
// with some changes for compatibility
if(isalnum(c) || c == '-' || c == '_' || c == '.' || c == ',')
enc += (char)c;
else if(c == ' ')
enc += '+';
else
{
unsigned nib = (c >> 4) & 0xf;
buf[1] = nib < 10 ? '0' + nib : 'a' + (nib-10);
nib = c & 0xf;
buf[2] = nib < 10 ? '0' + nib : 'a' + (nib-10);
enc.append(&buf[0], 3);
}
}
}
static bool _SetNonBlocking(SOCKET s, bool nonblock)
{
if(!SOCKETVALID(s))
return false;
#ifdef MINIHTTP_USE_MBEDTLS
if(nonblock)
return mbedtls_net_set_nonblock((mbedtls_net_context*)&s) == 0; // this horrible hackery is okay as long as the compile assert in HasSSL() holds
else
return mbedtls_net_set_block((mbedtls_net_context*)&s) == 0;
#elif defined(_WIN32)
ULONG tmp = !!nonblock;
if(::ioctlsocket(s, FIONBIO, &tmp) == SOCKET_ERROR)
return false;
#else
int tmp = ::fcntl(s, F_GETFL);
if(tmp < 0)
return false;
if(::fcntl(s, F_SETFL, nonblock ? (tmp|O_NONBLOCK) : (tmp|=~O_NONBLOCK)) < 0)
return false;
#endif
return true;
}
TcpSocket::TcpSocket()
: _inbuf(NULL)
, _readptr(NULL)
, _inbufSize(0)
, _recvSize(0)
, _lastport(0)
, _s(INVALID_SOCKET)
, _sslctx(NULL)
{
#ifdef MINIHTTP_USE_MBEDTLS
mbedtls_net_init((mbedtls_net_context*)&_s);
#endif
}
TcpSocket::~TcpSocket()
{
close();
if(_inbuf)
free(_inbuf);
}
bool TcpSocket::isOpen(void)
{
return SOCKETVALID(_s);
}
void TcpSocket::close(void)
{
if(!SOCKETVALID(_s))
return;
traceprint("TcpSocket::close\n");
_OnCloseInternal();
#ifdef MINIHTTP_USE_MBEDTLS
if(_sslctx)
((SSLCtx*)_sslctx)->reset();
mbedtls_net_free((mbedtls_net_context*)&_s);
shutdownSSL();
#else
# ifdef _WIN32
::closesocket((SOCKET)_s);
# else
::close(_s);
# endif
#endif
_s = INVALID_SOCKET;
_recvSize = 0;
}
void TcpSocket::_OnCloseInternal()
{
_OnClose();
}
bool TcpSocket::SetNonBlocking(bool nonblock)
{
_nonblocking = nonblock;
return _SetNonBlocking(_s, nonblock);
}
void TcpSocket::SetBufsizeIn(unsigned int s)
{
if(s < 512)
s = 512;
if(s != _inbufSize)
_inbuf = (char*)realloc(_inbuf, s);
_inbufSize = s;
_writeSize = s - 1;
_readptr = _writeptr = _inbuf;
}
static bool _openSocket(SOCKET *ps, const char *host, unsigned port)
{
#ifdef MINIHTTP_USE_MBEDTLS
int s;
char portstr[16];
sprintf(portstr, "%d", port);
int err = mbedtls_net_connect((mbedtls_net_context*)&s, host, portstr, MBEDTLS_NET_PROTO_TCP);
if(err)
{
traceprint("open_ssl: net_connect(%s, %u) returned %d\n", host, port, err);
return false;
}
#else
sockaddr_in addr;
if(!_Resolve(host, port, &addr))
{
traceprint("RESOLV ERROR: %s\n", _GetErrorStr(_GetError()).c_str());
return false;
}
SOCKET s = socket(AF_INET, SOCK_STREAM, 0);
if(!SOCKETVALID(s))
{
traceprint("SOCKET ERROR: %s\n", _GetErrorStr(_GetError()).c_str());
return false;
}
if (::connect(s, (sockaddr*)&addr, sizeof(sockaddr)))
{
traceprint("CONNECT ERROR: %s\n", _GetErrorStr(_GetError()).c_str());
return false;
}
#endif
*ps = s;
return true;
}
#ifdef MINIHTTP_USE_MBEDTLS
static bool _openSSL(void *ps, SSLCtx *ctx)
{
mbedtls_ssl_set_bio(&ctx->ssl, (mbedtls_net_context*)ps, mbedtls_net_send, mbedtls_net_recv, NULL);
traceprint("SSL handshake now...\n");
int err;
while( (err = mbedtls_ssl_handshake(&ctx->ssl)) )
{
if(err != MBEDTLS_ERR_SSL_WANT_READ && err != MBEDTLS_ERR_SSL_WANT_WRITE)
{
traceprint("open_ssl: ssl_handshake returned -0x%x\n\n", -err);
return false;
}
}
traceprint("SSL handshake done\n");
return true;
}
#endif
bool TcpSocket::open(const char *host /* = NULL */, unsigned int port /* = 0 */)
{
if(isOpen())
{
if( (host && host != _host) || (port && port != _lastport) )
close();
// ... and continue connecting to new host/port
else
return true; // still connected, to same host and port.
}
if(host)
_host = host;
else
host = _host.c_str();
if(port)
_lastport = port;
else
{
port = _lastport;
if(!port)
return false;
}
traceprint("TcpSocket::open(): host = [%s], port = %d\n", host, port);
assert(!SOCKETVALID(_s));
_recvSize = 0;
{
SOCKET s;
if(!_openSocket(&s, host, port))
return false;
_s = s;
#ifdef SO_NOSIGPIPE
// Don't fire SIGPIPE when trying to write to a closed socket
{
int set = 1;
setsockopt(s, SOL_SOCKET, SO_NOSIGPIPE, (void *)&set, sizeof(int));
}
#endif
}
_SetNonBlocking(_s, _nonblocking); // restore setting if it was set in invalid state. static call because _s is intentionally still invalid here.
#ifdef MINIHTTP_USE_MBEDTLS
if(_sslctx)
{
traceprint("TcpSocket::open(): SSL requested...\n");
if(!_openSSL(&_s, (SSLCtx*)_sslctx))
{
close();
return false;
}
}
#endif
_OnOpen();
return true;
}
#ifdef MINIHTTP_USE_MBEDTLS
void TcpSocket::shutdownSSL()
{
delete ((SSLCtx*)_sslctx);
_sslctx = NULL;
}
bool TcpSocket::initSSL(const char *certs)
{
SSLCtx *ctx = (SSLCtx*)_sslctx;
if(ctx)
ctx->reset();
else
{
ctx = new SSLCtx();
_sslctx = ctx;
if(!ctx->init())
{
shutdownSSL();
return false;
}
}
if(certs)
{
int err = mbedtls_x509_crt_parse(&ctx->cacert, (const unsigned char*)certs, strlen(certs));
if(err)
{
shutdownSSL();
traceprint("x509_crt_parse() returned %d\n", err);
return false;
}
}
return true;
}
SSLResult TcpSocket::verifySSL(char *buf, unsigned bufsize)
{
if(!_sslctx)
return SSLR_NO_SSL;
SSLCtx *ctx = (SSLCtx*)_sslctx;
unsigned r = SSLR_OK;
int res = mbedtls_ssl_get_verify_result(&ctx->ssl);
if(res)
{
if(res & MBEDTLS_X509_BADCERT_EXPIRED)
r |= SSLR_CERT_EXPIRED;
if(res & MBEDTLS_X509_BADCERT_REVOKED)
r |= SSLR_CERT_REVOKED;
if(res & MBEDTLS_X509_BADCERT_CN_MISMATCH)
r |= SSLR_CERT_CN_MISMATCH;
if(res & MBEDTLS_X509_BADCERT_NOT_TRUSTED)
r |= SSLR_CERT_NOT_TRUSTED;
if(res & MBEDTLS_X509_BADCERT_MISSING)
r |= SSLR_CERT_MISSING;
if(res & MBEDTLS_X509_BADCERT_SKIP_VERIFY)
r |= SSLR_CERT_SKIP_VERIFY;
if(res & MBEDTLS_X509_BADCERT_FUTURE)
r |= SSLR_CERT_FUTURE;
// More than just this?
if(res & (MBEDTLS_X509_BADCERT_SKIP_VERIFY | MBEDTLS_X509_BADCERT_NOT_TRUSTED))
r |= SSLR_FAIL;
}
if(buf && bufsize)
mbedtls_x509_crt_verify_info(buf, bufsize, "", res);
return (SSLResult)r;
}
#else // MINIHTTP_USE_MBEDTLS
void TcpSocket::shutdownSSL() {}
bool TcpSocket::initSSL(const char *certs)
{
traceprint("initSSL: Compiled without SSL support!\n");
return false;
}
SSLResult TcpSocket::verifySSL(char *buf, unsigned buflen) { return SSLR_NO_SSL; }
#endif
bool TcpSocket::SendBytes(const void *str, unsigned int len)
{
if(!len)
return true;
if(!SOCKETVALID(_s))
return false;
//traceprint("SEND: '%s'\n", str);
unsigned written = 0;
while(true) // FIXME: buffer bytes to an internal queue instead?
{
int ret = _writeBytes((const unsigned char*)str + written, len - written);
if(ret > 0)
{
assert((unsigned)ret <= len);
written += (unsigned)ret;
if(written >= len)
break;
}
else if(ret < 0)
{
int err = ret == -1 ? _GetError() : ret;
traceprint("SendBytes: error %d: %s\n", err, _GetErrorStr(err).c_str());
close();
return false;
}
// and if ret == 0, keep trying.
}
assert(written == len);
return true;
}
int TcpSocket::_writeBytes(const unsigned char *buf, size_t len)
{
int ret = 0;
#ifdef MINIHTTP_USE_MBEDTLS
int err;
if(_sslctx)
err = mbedtls_ssl_write(&((SSLCtx*)_sslctx)->ssl, buf, len);
else
err = mbedtls_net_send(&_s, buf, len);
switch(err)
{
case MBEDTLS_ERR_SSL_WANT_WRITE:
ret = 0; // FIXME: Nothing written, try later?
default:
ret = err;
}
#else
int flags = 0;
#ifdef MSG_NOSIGNAL
flags |= MSG_NOSIGNAL;
#endif
return ::send(_s, (const char*)buf, len, flags);
#endif
return ret;
}
void TcpSocket::_ShiftBuffer(void)
{
size_t by = _readptr - _inbuf;
memmove(_inbuf, _readptr, by);
_readptr = _inbuf;
_writeptr = _inbuf + by;
_writeSize = _inbufSize - by - 1;
}
void TcpSocket::_OnData()
{
_OnRecv(_readptr, _recvSize);
}
int TcpSocket::_readBytes(unsigned char *buf, size_t maxlen)
{
#ifdef MINIHTTP_USE_MBEDTLS
if(_sslctx)
return mbedtls_ssl_read(&((SSLCtx*)_sslctx)->ssl, buf, maxlen);
else
return mbedtls_net_recv(&_s, buf, maxlen);
#else
return recv(_s, (char*)buf, maxlen, 0); // last char is used as string terminator
#endif
}
bool TcpSocket::update(void)
{
if(!_OnUpdate())
return false;
if(!isOpen())
return false;
if(!_inbuf)
SetBufsizeIn(DEFAULT_BUFSIZE);
int bytes = _readBytes((unsigned char*)_writeptr, _writeSize);
//traceprint("TcpSocket::update: _readBytes() result %d\n", bytes);
if(bytes > 0) // we received something
{
_inbuf[bytes] = 0;
_recvSize = bytes;
// reset pointers for next read
_writeSize = _inbufSize - 1;
_readptr = _writeptr = _inbuf;
_OnData();
}
else if(bytes == 0) // remote has closed the connection
{
close();
}
else // whoops, error?
{
// Possible that the error is returned directly (in that case, < -1, or -1 is returned and the error has to be retrieved seperately.
// But in the latter case, error numbers may be positive (at least on windows...)
int err = bytes == -1 ? _GetError() : bytes;
switch(err)
{
case EWOULDBLOCK:
#if defined(EAGAIN) && (EWOULDBLOCK != EAGAIN)
case EAGAIN: // linux man pages say this can also happen instead of EWOULDBLOCK
#endif
return false;
#ifdef MINIHTTP_USE_MBEDTLS
case MBEDTLS_ERR_SSL_WANT_READ:
break; // Try again later
#endif
default:
traceprint("SOCKET UPDATE ERROR: (%d): %s\n", err, _GetErrorStr(err).c_str());
case ECONNRESET:
case ENOTCONN:
case ETIMEDOUT:
#ifdef _WIN32
case WSAECONNABORTED:
case WSAESHUTDOWN:
#endif
close();
break;
}
}
return true;
}
// ==========================
// ===== HTTP SPECIFIC ======
// ==========================
#ifdef MINIHTTP_SUPPORT_HTTP
static void strToLower(std::string& s)
{
std::transform(s.begin(), s.end(), s.begin(), tolower);
}
POST& POST::add(const char *key, const char *value)
{
if(!empty())
data += '&';
URLEncode(key, data);
data += '=';
URLEncode(value, data);
return *this;
}
HttpSocket::HttpSocket()
: TcpSocket()
, _keep_alive(0)
, _remaining(0)
, _status(0)
, _inProgress(false)
, _chunkedTransfer(false)
, _mustClose(true)
, _followRedir(true)
, _alwaysHandle(false)
{
}
HttpSocket::~HttpSocket()
{
}
void HttpSocket::_OnOpen()
{
TcpSocket::_OnOpen();
_chunkedTransfer = false;
_mustClose = true;
}
void HttpSocket::_OnCloseInternal()
{
if(!IsRedirecting() || _alwaysHandle)
_OnClose();
}
bool HttpSocket::_OnUpdate()
{
if(!TcpSocket::_OnUpdate())
return false;
if(_inProgress && !_chunkedTransfer && !_remaining && _status)
_FinishRequest();
//traceprint("HttpSocket::_OnUpdate, Q = %d\n", (unsigned)_requestQ.size());
// initiate transfer if queue is not empty, but the socket somehow forgot to proceed
if(_requestQ.size() && !_remaining && !_chunkedTransfer && !_inProgress)
_DequeueMore();
return true;
}
bool HttpSocket::Download(const std::string& url, const char *extraRequest /*= NULL*/, void *user /* = NULL */, const POST *post /*= NULL*/)
{
Request req;
req.user = user;
if(post)
req.post = *post;
SplitURI(url, req.protocol, req.host, req.resource, req.port, req.useSSL);
if(IsRedirecting() && req.host.empty()) // if we're following a redirection to the same host, the server is likely to omit its hostname
req.host = _curRequest.host;
if(req.port < 0)
req.port = 80;
if(extraRequest)
req.extraGetHeaders = extraRequest;
return SendRequest(req, false);
}
bool HttpSocket::_Redirect(const std::string& loc, bool forceGET)
{
traceprint("Following HTTP redirect to: %s\n", loc.c_str());
if(loc.empty())
return false;
Request req;
req.user = _curRequest.user;
req.useSSL = _curRequest.useSSL;
if(!forceGET)
req.post = _curRequest.post;
SplitURI(loc, req.protocol, req.host, req.resource, req.port, req.useSSL);
if(req.protocol.empty()) // assume local resource
{
req.host = _curRequest.host;
req.resource = loc;
}
if(req.host.empty())
req.host = _curRequest.host;
if(req.port < 0)
req.port = _curRequest.port;
req.extraGetHeaders = _curRequest.extraGetHeaders;
return SendRequest(req, false);
}
bool HttpSocket::SendRequest(const std::string& what, const char *extraRequest /*= NULL*/, void *user /* = NULL */)
{
Request req(what, _host, _lastport, user);
if(extraRequest)
req.extraGetHeaders = extraRequest;
return SendRequest(req, false);
}
bool HttpSocket::QueueRequest(const std::string& what, const char *extraRequest /*= NULL*/, void *user /* = NULL */)
{
Request req(what, _host, _lastport, user);
if(extraRequest)
req.extraGetHeaders = extraRequest;
return SendRequest(req, true);
}
bool HttpSocket::SendRequest(Request& req, bool enqueue)
{
if(req.host.empty() || !req.port)
return false;
const bool post = !req.post.empty();
std::stringstream r;
const char *crlf = "\r\n";
r << (post ? "POST " : "GET ") << req.resource << " HTTP/1.1" << crlf;
r << "Host: " << req.host << crlf;
if(_keep_alive)
{
r << "Connection: Keep-Alive" << crlf;
r << "Keep-Alive: " << _keep_alive << crlf;
}
else
r << "Connection: close" << crlf;
if(_user_agent.length())
r << "User-Agent: " << _user_agent << crlf;
if(_accept_encoding.length())
r << "Accept-Encoding: " << _accept_encoding << crlf;
if(post)
{
r << "Content-Length: " << req.post.length() << crlf;
r << "Content-Type: application/x-www-form-urlencoded" << crlf;
}
if(req.extraGetHeaders.length())
{
r << req.extraGetHeaders;
if(req.extraGetHeaders.compare(req.extraGetHeaders.length() - 2, std::string::npos, crlf))
r << crlf;
}
r << crlf; // header terminator
// FIXME: appending this to the 'header' field is probably not a good idea
if(post)
r << req.post.str();
req.header = r.str();
return _EnqueueOrSend(req, enqueue);
}
bool HttpSocket::_EnqueueOrSend(const Request& req, bool forceQueue /* = false */)
{
traceprint("HttpSocket::_EnqueueOrSend, forceQueue = %d\n", forceQueue);
if(_inProgress || forceQueue) // do not send while receiving other data
{
traceprint("HTTP: Transfer pending; putting into queue. Now %u waiting.\n", (unsigned int)_requestQ.size());
_requestQ.push(req);
return true;
}
// ok, we can send directly
traceprint("HTTP: Open request for immediate send.\n");
if(!_OpenRequest(req))
return false;
bool sent = SendBytes(req.header.c_str(), req.header.length());
_inProgress = sent;
return sent;
}
// called whenever a request is finished completely and the socket checks for more things to send
void HttpSocket::_DequeueMore(void)
{
traceprint("HttpSocket::_DequeueMore, Q = %u\n", (unsigned)_requestQ.size());
_FinishRequest(); // In case this was not done yet.
// _inProgress is known to be false here
if(_requestQ.size()) // still have other requests queued?
if(_EnqueueOrSend(_requestQ.front(), false)) // could we send?
_requestQ.pop(); // if so, we are done with this request
// otherwise, we are done for now. socket is kept alive for future sends. Nothing to do.
}