-
Notifications
You must be signed in to change notification settings - Fork 0
/
http.c
3314 lines (3172 loc) · 124 KB
/
http.c
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
/********************************************************************
* *
* THIS FILE IS PART OF THE libopusfile SOFTWARE CODEC SOURCE CODE. *
* USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS *
* GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE *
* IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. *
* *
* THE libopusfile SOURCE CODE IS (C) COPYRIGHT 2012 *
* by the Xiph.Org Foundation and contributors http://www.xiph.org/ *
********************************************************************
* This file was heavily modified by Rymond Gillibert mail me at: *
* I Mostly removed all SSL/TSL related stuf in order to build the *
* URL support for libopusfile-0.11 without requiring openSSL In *
* addition some modifications were made to be able to build on *
* Windows 95 without Windows Socket 2 upgrade *
* *
********************************************************************/
#define OP_ENABLE_HTTP 1
#include "http.h"
#include <ctype.h>
#include <errno.h>
#include <limits.h>
#include <string.h>
#include "wspiapi.h" // This is a modified version
////////////////////////////////
/*RFCs referenced in this file:
* RFC 761: DOD Standard Transmission Control Protocol
* RFC 1535: A Security Problem and Proposed Correction With Widely Deployed DNS
* Software
* RFC 1738: Uniform Resource Locators (URL)
* RFC 1945: Hypertext Transfer Protocol -- HTTP/1.0
* RFC 2068: Hypertext Transfer Protocol -- HTTP/1.1
* RFC 2145: Use and Interpretation of HTTP Version Numbers
* RFC 2246: The TLS Protocol Version 1.0
* RFC 2459: Internet X.509 Public Key Infrastructure Certificate and
* Certificate Revocation List (CRL) Profile
* RFC 2616: Hypertext Transfer Protocol -- HTTP/1.1
* RFC 2617: HTTP Authentication: Basic and Digest Access Authentication
* RFC 2817: Upgrading to TLS Within HTTP/1.1
* RFC 2818: HTTP Over TLS
* RFC 3492: Punycode: A Bootstring encoding of Unicode for Internationalized
* Domain Names in Applications (IDNA)
* RFC 3986: Uniform Resource Identifier (URI): Generic Syntax
* RFC 3987: Internationalized Resource Identifiers (IRIs)
* RFC 4343: Domain Name System (DNS) Case Insensitivity Clarification
* RFC 5894: Internationalized Domain Names for Applications (IDNA):
* Background, Explanation, and Rationale
* RFC 6066: Transport Layer Security (TLS) Extensions: Extension Definitions
* RFC 6125: Representation and Verification of Domain-Based Application Service
* Identity within Internet Public Key Infrastructure Using X.509 (PKIX)
* Certificates in the Context of Transport Layer Security (TLS)
* RFC 6555: Happy Eyeballs: Success with Dual-Stack Hosts
**/
typedef struct OpusParsedURL OpusParsedURL;
typedef struct OpusStringBuf OpusStringBuf;
typedef struct OpusHTTPConn OpusHTTPConn;
typedef struct OpusHTTPStream OpusHTTPStream;
static char *op_string_range_dup(const char *_start, const char *_end)
{
size_t len;
char *ret;
OP_ASSERT(_start <= _end);
len = _end - _start;
/*This is to help avoid overflow elsewhere, later. */
if (len >= INT_MAX)
return NULL;
ret = _ogg_malloc(sizeof(*ret) * (len + 1));
if (ret != NULL) {
ret = (char *) memcpy(ret, _start, sizeof(*ret) * (len));
ret[len] = '\0';
}
return ret;
}
static char *op_string_dup(const char *_s)
{
return op_string_range_dup(_s, _s + strlen(_s));
}
static char *op_string_tolower(char *_s)
{
int i;
for (i = 0; _s[i] != '\0'; i++) {
int c;
c = _s[i];
if (c >= 'A' && c <= 'Z')
c += 'a' - 'A';
_s[i] = (char) c;
}
return _s;
}
/*URI character classes (from RFC 3986).*/
#define OP_URL_ALPHA \
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
#define OP_URL_DIGIT "0123456789"
#define OP_URL_HEXDIGIT "0123456789ABCDEFabcdef"
/*Not a character class, but the characters allowed in <scheme>.*/
#define OP_URL_SCHEME OP_URL_ALPHA OP_URL_DIGIT "+-."
#define OP_URL_GEN_DELIMS "#/:?@[]"
#define OP_URL_SUB_DELIMS "!$&'()*+,;="
#define OP_URL_RESERVED OP_URL_GEN_DELIMS OP_URL_SUB_DELIMS
#define OP_URL_UNRESERVED OP_URL_ALPHA OP_URL_DIGIT "-._~"
/*Not a character class, but the characters allowed in <pct-encoded>.*/
#define OP_URL_PCT_ENCODED "%"
/*Not a character class or production rule, but for convenience.*/
#define OP_URL_PCHAR_BASE \
OP_URL_UNRESERVED OP_URL_PCT_ENCODED OP_URL_SUB_DELIMS
#define OP_URL_PCHAR OP_URL_PCHAR_BASE ":@"
/*Not a character class, but the characters allowed in <userinfo> and <IP-literal>.*/
#define OP_URL_PCHAR_NA OP_URL_PCHAR_BASE ":"
/*Not a character class, but the characters allowed in <segment-nz-nc>.*/
#define OP_URL_PCHAR_NC OP_URL_PCHAR_BASE "@"
/*Not a character clsss, but the characters allowed in <path>.*/
#define OP_URL_PATH OP_URL_PCHAR "/"
/*Not a character class, but the characters allowed in <query> / <fragment>.*/
#define OP_URL_QUERY_FRAG OP_URL_PCHAR "/?"
/* Check the <% HEXDIG HEXDIG> escapes of a URL for validity.
* Return: 0 if valid, or a negative value (OP_FALSE) on failure.
* RFC 3986 says %00 "should be rejected if the application is not
* expecting to receive raw data within a component."
*/
static int op_validate_url_escapes(const char *_s)
{
int i;
for (i = 0; _s[i]; i++) {
if (_s[i] == '%') {
if (!isxdigit(_s[i + 1]) || !isxdigit(_s[i + 2])
|| (_s[i + 1] == '0' && _s[i + 2] == '0')) {
return OP_FALSE;
} else {
i += 2;
}
}
}
return 0;
}
/* Convert a hex digit to its actual value.
* _c: The hex digit to convert.
* Presumed to be valid ('0'...'9', 'A'...'F', or 'a'...'f').
* Return: The value of the digit, in the range [0,15].
*/
static int op_hex_value(int _c)
{
return (_c >= 'a') ? _c - 'a' + 10 : (_c >='A') ? _c - 'A' + 10 : _c - '0';
}
/* Unescape all the <% HEXDIG HEXDIG> sequences in a string in-place.
* This does no validity checking.
*/
static char *op_unescape_url_component(char *_s)
{
int i, j;
for (i = j = 0; _s[i]; i++, j++) {
if (_s[i] == '%') {
_s[i] = (char) (op_hex_value(_s[i+1]) << 4
| op_hex_value(_s[i+2]));
i+=2;
}
}
return _s;
}
/* Parse a file: URL.
* This code is not meant to be fast: strspn() with large sets is likely to be
* slow, but it is very convenient.
* It is meant to be RFC 1738-compliant (as updated by RFC 3986).
*/
static const char *op_parse_file_url(const char *_src)
{
const char *scheme_end;
const char *path;
const char *path_end;
scheme_end = _src + strspn(_src, OP_URL_SCHEME);
if ( *scheme_end != ':'
|| scheme_end - _src != 4 || op_strncasecmp(_src, "file", 4) != 0) {
/*Unsupported protocol. */
return NULL;
}
/*Make sure all escape sequences are valid to simplify unescaping later. */
if (op_validate_url_escapes(scheme_end + 1) < 0)
return NULL;
if (scheme_end[1] == '/' && scheme_end[2] == '/') {
const char *host;
/* file: URLs can have a host!
* Yeah, I was surprised, too, but that's what RFC 1738 says.
* It also says, "The file URL scheme is unusual in that it does not specify
* an Internet protocol or access method for such files; as such, its
* utility in network protocols between hosts is limited," which is a mild
* understatement.*/
host = scheme_end + 3;
/*The empty host is what we expect. */
if (*host == '/') {
path = host;
} else {
const char *host_end;
char host_buf[28];
/* RFC 1738 says localhost "is interpreted as `the machine from which the
* URL is being interpreted,'" so let's check for it.*/
host_end = host + strspn(host, OP_URL_PCHAR_BASE);
/* No <port> allowed.
* This also rejects IP-Literals.*/
if (*host_end != '/')
return NULL;
/* An escaped "localhost" can take at most 27 characters. */
if (host_end - host > 27)
return NULL;
memcpy(host_buf, host, sizeof(*host_buf) * (host_end - host));
host_buf[host_end - host] = '\0';
op_unescape_url_component(host_buf);
op_string_tolower(host_buf);
/* Some other host: give up. */
if (strcmp(host_buf, "localhost") != 0)
return NULL;
path = host_end;
}
} else {
path = scheme_end + 1;
}
path_end = path + strspn(path, OP_URL_PATH);
/* This will reject a <query> or <fragment> component, too.
* I don't know what to do with queries, but a temporal fragment would at
* least make sense.
* RFC 1738 pretty clearly defines a <searchpart> that's equivalent to the
* RFC 3986 <query> component for other schemes, but not the file: scheme,
* so I'm going to just reject it. */
if (*path_end != '\0')
return NULL;
return path;
}
#if defined(OP_ENABLE_HTTP)
# if defined(_WIN32)
# include <winsock2.h>
# include <ws2tcpip.h>
# include "winerrno.h"
typedef SOCKET op_sock;
# define OP_INVALID_SOCKET (INVALID_SOCKET)
/* Vista and later support WSAPoll(), but we don't want to rely on that.
* Instead we re-implement it badly using select().
* Unfortunately, they define a conflicting struct pollfd, so we only define our
* own if it looks like that one has not already been defined.
*/
#if !defined(POLLIN)
# define POLLRDNORM (0x0100) /*Equivalent to POLLIN.*/
# define POLLRDBAND (0x0200) /*Priority band data can be read.*/
# define POLLIN (POLLRDNORM|POLLRDBAND) /*There is data to read.*/
# define POLLPRI (0x0400) /*There is urgent data to read.*/
# define POLLWRNORM (0x0010) /*Equivalent to POLLOUT.*/
# define POLLOUT (POLLWRNORM) /*Writing now will not block.*/
# define POLLWRBAND (0x0020) /*Priority data may be written.*/
# define POLLERR (0x0001) /*Error condition (output only).*/
# define POLLHUP (0x0002) /*Hang up (output only).*/
# define POLLNVAL (0x0004) /*Invalid request: fd not open (output only).*/
struct pollfd {
op_sock fd; /*File descriptor. */
short events; /*Requested events.*/
short revents; /*Returned events. */
};
#endif /*POLLIN*/
/* But Winsock never defines nfds_t (it's simply hard-coded to ULONG).*/
typedef unsigned long nfds_t;
/* The usage of FD_SET() below is O(N^2).
* This is okay because select() is limited to 64 sockets in Winsock, anyway.
* In practice, we only ever call it with one or two sockets.
*/
static int op_poll_win32(struct pollfd *_fds, nfds_t _nfds, int _timeout)
{
struct timeval tv;
fd_set ifds;
fd_set ofds;
fd_set efds;
nfds_t i;
int ret;
FD_ZERO(&ifds);
FD_ZERO(&ofds);
FD_ZERO(&efds);
for (i = 0; i < _nfds; i++) {
_fds[i].revents = 0;
if (_fds[i].events & POLLIN)
FD_SET(_fds[i].fd, &ifds);
if (_fds[i].events & POLLOUT)
FD_SET(_fds[i].fd, &ofds);
FD_SET(_fds[i].fd, &efds);
}
if (_timeout >= 0) {
tv.tv_sec = _timeout / 1000;
tv.tv_usec = (_timeout % 1000) * 1000;
}
ret = select(-1, &ifds, &ofds, &efds, _timeout < 0 ? NULL : &tv);
if (ret > 0) {
for (i = 0; i < _nfds; i++) {
if (FD_ISSET(_fds[i].fd, &ifds))
_fds[i].revents |= POLLIN;
if (FD_ISSET(_fds[i].fd, &ofds))
_fds[i].revents |= POLLOUT;
/* This isn't correct: there are several different things that might have
* happened to a fd in efds, but I don't know a good way to distinguish
* them without more context from the caller.
* It's okay, because we don't actually check any of these bits, we just
* need _some_ bit set.*/
if (FD_ISSET(_fds[i].fd, &efds))
_fds[i].revents |= POLLHUP;
}
}
return ret;
}
/*We define op_errno() to make it clear that it's not an l-value like normal
* errno is.
*/
# define op_errno() (WSAGetLastError()?WSAGetLastError()-WSABASEERR:0)
# define op_reset_errno() (WSASetLastError(0))
/* The remaining functions don't get an op_ prefix even though they only
* operate on sockets, because we don't use non-socket I/O here, and this
* minimizes the changes needed to deal with Winsock.
*/
# define close(_fd) closesocket(_fd)
/* This takes an int for the address length, even though the value is of type
* socklen_t (defined as an unsigned integer type with at least 32 bits).*/
# define connect(_fd,_addr,_addrlen) \
(((_addrlen)>(socklen_t)INT_MAX)? \
WSASetLastError(WSA_NOT_ENOUGH_MEMORY),-1: \
connect(_fd,_addr,(int)(_addrlen)))
/* This relies on sizeof(u_long)==sizeof(int), which is always true on both
* Win32 and Win64.*/
# define ioctl(_fd,_req,_arg) ioctlsocket(_fd,_req,(u_long *)(_arg))
# define getsockopt(_fd,_level,_name,_val,_len) \
getsockopt(_fd,_level,_name,(char *)(_val),_len)
# define setsockopt(_fd,_level,_name,_val,_len) \
setsockopt(_fd,_level,_name,(const char *)(_val),_len)
# define poll(_fds,_nfds,_timeout) op_poll_win32(_fds,_nfds,_timeout)
# if defined(_MSC_VER)
typedef ptrdiff_t ssize_t;
# endif
# else
/*Normal Berkeley sockets.*/
# include <sys/ioctl.h>
# include <sys/types.h>
# include <sys/socket.h>
# include <arpa/inet.h>
# include <netinet/in.h>
# include <netinet/tcp.h>
# include <fcntl.h>
# include <netdb.h>
# include <poll.h>
# include <unistd.h>
typedef int op_sock;
# define OP_INVALID_SOCKET (-1)
//# define op_errno() (errno)
//# define op_reset_errno() (errno=0)
# endif /* _WIN32 */
# include <sys/timeb.h>
/* The maximum number of simultaneous connections.
* RFC 2616 says this SHOULD NOT be more than 2, but everyone on the modern web
* ignores that (e.g., IE 8 bumped theirs up from 2 to 6, Firefox uses 15).
* If it makes you feel better, we'll only ever actively read from one of these
* at a time.
* The others are kept around mainly to avoid slow-starting a new connection
* when seeking, and time out rapidly.
*/
# define OP_NCONNS_MAX (4)
/* The amount of time before we attempt to re-resolve the host.
* This is 10 minutes, as recommended in RFC 6555 for expiring cached connection
* results for dual-stack hosts.
*/
# define OP_RESOLVE_CACHE_TIMEOUT_MS (10*60*(opus_int32)1000)
/* The number of redirections at which we give up.
* The value here is the current default in Firefox.
* RFC 2068 mandated a maximum of 5, but RFC 2616 relaxed that to "a client
* SHOULD detect infinite redirection loops."
* Fortunately, 20 is less than infinity.
*/
# define OP_REDIRECT_LIMIT (20)
/* The initial size of the buffer used to read a response message (before the
* body).
*/
# define OP_RESPONSE_SIZE_MIN (510)
/* The maximum size of a response message (before the body).
* Responses larger than this will be discarded.
* I've seen a real server return 20 kB of data for a 302 Found response.
* Increasing this beyond 32kB will cause problems on platforms with a 16-bit int.
*/
# define OP_RESPONSE_SIZE_MAX (32766)
/* The number of milliseconds we will allow a connection to sit idle before we
* refuse to resurrect it.
* Apache as of 2.2 has reduced its default timeout to 5 seconds (from 15), so
* that's what we'll use here.
*/
# define OP_CONNECTION_IDLE_TIMEOUT_MS (5*1000)
/*The number of milliseconds we will wait to send or receive data before giving
up. (30 seconds) */
# define OP_POLL_TIMEOUT_MS (30*1000)
/*We will always attempt to read ahead at least this much in preference to
opening a new connection.*/
# define OP_READAHEAD_THRESH_MIN (32*(opus_int32)1024)
/*The amount of data to request after a seek.
This is a trade-off between read throughput after a seek vs. the the ability
to quickly perform another seek with the same connection.*/
# define OP_PIPELINE_CHUNK_SIZE (32*(opus_int32)1024)
/*Subsequent chunks are requested with larger and larger sizes until they pass
this threshold, after which we just ask for the rest of the resource.*/
# define OP_PIPELINE_CHUNK_SIZE_MAX (1024*(opus_int32)1024)
/*This is the maximum number of requests we'll make with a single connection.
Many servers will simply disconnect after we attempt some number of requests,
possibly without sending a Connection: close header, meaning we won't
discover it until we try to read beyond the end of the current chunk.
We can reconnect when that happens, but this is slow.
Instead, we impose a limit ourselves (set to the default for Apache
installations and thus likely the most common value in use).*/
# define OP_PIPELINE_MAX_REQUESTS (100)
/*This should be the number of requests, starting from a chunk size of
OP_PIPELINE_CHUNK_SIZE and doubling each time, until we exceed
OP_PIPELINE_CHUNK_SIZE_MAX and just request the rest of the file.
We won't reuse a connection when seeking unless it has at least this many
requests left, to reduce the chances we'll have to open a new connection
while reading forward afterwards.*/
# define OP_PIPELINE_MIN_REQUESTS (7)
/*Is this an https URL?
For now we can simply check the last letter of the scheme.*/
//# define OP_URL_IS_SSL(_url) ((_url)->scheme[4]=='s')
# define OP_URL_IS_SSL(_url) 0
/*Does this URL use the default port for its scheme?*/
# define OP_URL_IS_DEFAULT_PORT(_url) ( (!OP_URL_IS_SSL(_url)&&(_url)->port==80) \
||(OP_URL_IS_SSL(_url)&&(_url)->port==443) )
struct OpusParsedURL {
/*Either "http" or "https". */
char *scheme;
/*The user name from the <userinfo> component, or NULL. */
char *user;
/*The password from the <userinfo> component, or NULL. */
char *pass;
/*The <host> component.
This may not be NULL. */
char *host;
/*The <path> and <query> components.
This may not be NULL. */
char *path;
/*The <port> component.
This is set to the default port if the URL did not contain one. */
unsigned port;
};
/* Parse a URL.
* This code is not meant to be fast: strspn() with large sets is likely to be
* slow, but it is very convenient.
* It is meant to be RFC 3986-compliant.
* We currently do not support IRIs
* (Internationalized Resource Identifiers, RFC 3987).
* Callers should translate them to URIs first.
*/
static int op_parse_url_impl(OpusParsedURL * _dst, const char *_src)
{
const char *scheme_end;
const char *authority;
const char *userinfo_end;
const char *user;
const char *user_end;
const char *pass;
const char *hostport;
const char *hostport_end;
const char *host_end;
const char *port;
opus_int32 port_num;
const char *port_end;
const char *path;
const char *path_end;
const char *uri_end;
scheme_end = _src + strspn(_src, OP_URL_SCHEME);
if ( (*scheme_end != ':')
|| (scheme_end - _src < 4)
|| (scheme_end - _src > 5)
|| op_strncasecmp(_src, "https", (int) (scheme_end - _src)) != 0) {
/*Unsupported protocol. */
return OP_EIMPL;
} else if (scheme_end[1] != '/' || scheme_end[2] != '/') {
/*We require an <authority> component. */
return OP_EINVAL;
}
authority = scheme_end + 3;
/*Make sure all escape sequences are valid to simplify unescaping later. */
if (op_validate_url_escapes(authority) < 0)
return OP_EINVAL;
/*Look for a <userinfo> component. */
userinfo_end = authority + strspn(authority, OP_URL_PCHAR_NA);
if (*userinfo_end == '@') {
/*Found one. */
user = authority;
/* Look for a password (yes, clear-text passwords are deprecated, I know,
* but what else are people supposed to use? use SSL if you care). */
user_end = authority + strspn(authority, OP_URL_PCHAR_BASE);
if (*user_end == ':')
pass = user_end + 1;
else
pass = NULL;
hostport = userinfo_end + 1;
} else {
/*We shouldn't have to initialize user_end, but gcc is too dumb to figure
out that user!=NULL below means we didn't take this else branch. */
user = user_end = NULL;
pass = NULL;
hostport = authority;
}
/*Try to figure out where the <host> component ends. */
if (hostport[0] == '[') {
hostport++;
/*We have an <IP-literal>, which can contain colons. */
hostport_end = host_end =
hostport + strspn(hostport, OP_URL_PCHAR_NA);
if (*hostport_end++ != ']')
return OP_EINVAL;
}
/* Currently we don't support IDNA (RFC 5894), because I don't want to deal
* with the policy about which domains should not be internationalized to
* avoid confusing similarities.
* Give this API Punycode (RFC 3492) domain names instead.
*/
else
hostport_end = host_end =
hostport + strspn(hostport, OP_URL_PCHAR_BASE);
/*TODO: Validate host. */
/*Is there a port number? */
port_num = -1;
if (*hostport_end == ':') {
int i;
port = hostport_end + 1;
port_end = port + strspn(port, OP_URL_DIGIT);
path = port_end;
/*Not part of RFC 3986, but require port numbers in the range 0...65535. */
if (port_end - port > 0) {
while (*port == '0')
port++;
if (port_end - port > 5)
return OP_EINVAL;
port_num = 0;
for (i = 0; i < port_end - port; i++)
port_num = port_num * 10 + port[i] - '0';
if (port_num > 65535)
return OP_EINVAL;
}
} else
path = hostport_end;
path_end = path + strspn(path, OP_URL_PATH);
/*If the path is not empty, it must begin with a '/'. */
if (path_end > path && path[0] != '/')
return OP_EINVAL;
/*Consume the <query> component, if any (right now we don't split this out
from the <path> component). */
if (*path_end == '?')
path_end = path_end + strspn(path_end, OP_URL_QUERY_FRAG);
/*Discard the <fragment> component, if any.
This doesn't get sent to the server.
Some day we should add support for Media Fragment URIs
<http://www.w3.org/TR/media-frags/>. */
if (*path_end == '#')
uri_end = path_end + 1 + strspn(path_end + 1, OP_URL_QUERY_FRAG);
else
uri_end = path_end;
/*If there's anything left, this was not a valid URL. */
if (*uri_end != '\0')
return OP_EINVAL;
_dst->scheme = op_string_range_dup(_src, scheme_end);
if (_dst->scheme == NULL)
return OP_EFAULT;
op_string_tolower(_dst->scheme);
if (user != NULL) {
_dst->user = op_string_range_dup(user, user_end);
if (_dst->user == NULL)
return OP_EFAULT;
op_unescape_url_component(_dst->user);
/*Unescaping might have created a ':' in the username.
That's not allowed by RFC 2617's Basic Authentication Scheme. */
if (strchr(_dst->user, ':') != NULL)
return OP_EINVAL;
} else
_dst->user = NULL;
if (pass != NULL) {
_dst->pass = op_string_range_dup(pass, userinfo_end);
if (_dst->pass == NULL)
return OP_EFAULT;
op_unescape_url_component(_dst->pass);
} else
_dst->pass = NULL;
_dst->host = op_string_range_dup(hostport, host_end);
if (_dst->host == NULL)
return OP_EFAULT;
if (port_num < 0) {
if (_src[4] == 's')
port_num = 443;
else
port_num = 80;
}
_dst->port = (unsigned) port_num;
/*RFC 2616 says an empty <abs-path> component is equivalent to "/", and we
MUST use the latter in the Request-URI.
Reserve space for the slash here. */
if (path == path_end || path[0] == '?')
path--;
_dst->path = op_string_range_dup(path, path_end);
if (_dst->path == NULL)
return OP_EFAULT;
/*And force-set it here. */
_dst->path[0] = '/';
return 0;
}
static void op_parsed_url_init(OpusParsedURL * _url)
{
memset(_url, 0, sizeof(*_url));
}
static void op_parsed_url_clear(OpusParsedURL * _url)
{
_ogg_free(_url->scheme);
_ogg_free(_url->user);
_ogg_free(_url->pass);
_ogg_free(_url->host);
_ogg_free(_url->path);
}
static int op_parse_url(OpusParsedURL * _dst, const char *_src)
{
OpusParsedURL url;
int ret;
op_parsed_url_init(&url);
ret = op_parse_url_impl(&url, _src);
if (ret < 0)
op_parsed_url_clear(&url);
else
*_dst = url;
return ret;
}
/* A buffer to hold growing strings.
* The main purpose of this is to consolidate allocation checks and simplify
* cleanup on a failed allocation.
*/
struct OpusStringBuf {
char *buf;
int nbuf;
int cbuf;
};
static void op_sb_init(OpusStringBuf * _sb)
{
_sb->buf = NULL;
_sb->nbuf = 0;
_sb->cbuf = 0;
}
static void op_sb_clear(OpusStringBuf * _sb)
{
_ogg_free(_sb->buf);
}
/* Make sure we have room for at least _capacity characters (plus 1 more for the
* terminating NUL).
*/
static int op_sb_ensure_capacity(OpusStringBuf * _sb, int _capacity)
{
char *buf;
int cbuf;
buf = _sb->buf;
cbuf = _sb->cbuf;
if (_capacity >= cbuf - 1) {
if (cbuf > (INT_MAX - 1) >> 1)
return OP_EFAULT;
if (_capacity >= INT_MAX - 1)
return OP_EFAULT;
cbuf = OP_MAX(2 * cbuf + 1, _capacity + 1);
buf = _ogg_realloc(buf, sizeof(*buf) * cbuf);
if (buf == NULL)
return OP_EFAULT;
_sb->buf = buf;
_sb->cbuf = cbuf;
}
return 0;
}
/* Increase the capacity of the buffer, but not to more than _max_size
* characters (plus 1 more for the terminating NUL).
*/
static int op_sb_grow(OpusStringBuf * _sb, int _max_size)
{
char *buf;
int cbuf;
buf = _sb->buf;
cbuf = _sb->cbuf;
OP_ASSERT(_max_size <= INT_MAX - 1);
cbuf = cbuf <= (_max_size - 1) >> 1 ? 2 * cbuf + 1 : _max_size + 1;
buf = _ogg_realloc(buf, sizeof(*buf) * cbuf);
if (buf == NULL)
return OP_EFAULT;
_sb->buf = buf;
_sb->cbuf = cbuf;
return 0;
}
static int op_sb_append(OpusStringBuf * _sb, const char *_s, int _len)
{
char *buf;
int nbuf;
int ret;
nbuf = _sb->nbuf;
if (nbuf > INT_MAX - _len)
return OP_EFAULT;
ret = op_sb_ensure_capacity(_sb, nbuf + _len);
if (ret < 0)
return ret;
buf = _sb->buf;
memcpy(buf + nbuf, _s, sizeof(*buf) * _len);
nbuf += _len;
buf[nbuf] = '\0';
_sb->nbuf = nbuf;
return 0;
}
static int op_sb_append_string(OpusStringBuf * _sb, const char *_s)
{
size_t len;
len = strlen(_s);
if (len > (size_t) INT_MAX)
return OP_EFAULT;
return op_sb_append(_sb, _s, (int) len);
}
static int op_sb_append_port(OpusStringBuf * _sb, unsigned _port)
{
char port_buf[7];
OP_ASSERT(_port <= 65535U);
sprintf(port_buf, ":%u", _port);
return op_sb_append_string(_sb, port_buf);
}
static int op_sb_append_nonnegative_int64(OpusStringBuf * _sb, opus_int64 _i)
{
char digit;
int nbuf_start;
int ret;
OP_ASSERT(_i >= 0);
nbuf_start = _sb->nbuf;
ret = 0;
do {
digit = '0' + _i % 10;
ret |= op_sb_append(_sb, &digit, 1);
_i /= 10;
}
while (_i > 0);
if (ret >= 0) {
char *buf;
int nbuf_end;
buf = _sb->buf;
nbuf_end = _sb->nbuf - 1;
/*We've added the digits backwards.
Reverse them. */
while (nbuf_start < nbuf_end) {
digit = buf[nbuf_start];
buf[nbuf_start] = buf[nbuf_end];
buf[nbuf_end] = digit;
nbuf_start++;
nbuf_end--;
}
}
return ret;
}
static struct addrinfo *op_resolve(const char *_host, unsigned _port)
{
struct addrinfo *addrs;
struct addrinfo hints;
char service[6];
memset(&hints, 0, sizeof(hints));
hints.ai_socktype = SOCK_STREAM;
#if defined(AI_NUMERICSERV)
hints.ai_flags = AI_NUMERICSERV;
#endif
OP_ASSERT(_port <= 65535U);
sprintf(service, "%u", _port);
if ((!WspiapiLegacyGetAddrInfo(_host, service, &hints, &addrs)))
return addrs;
return NULL;
}
static int op_sock_set_nonblocking(op_sock _fd, int _nonblocking)
{
#if !defined(_WIN32)
int flags;
flags = fcntl(_fd, F_GETFL);
if (flags < 0)
return flags;
if (_nonblocking)
flags |= O_NONBLOCK;
else
flags &= ~O_NONBLOCK;
return fcntl(_fd, F_SETFL, flags);
#else
return ioctl(_fd, FIONBIO, &_nonblocking);
#endif
}
/* Disable/enable write coalescing if we can.
* We always send whole requests at once and always parse the response headers
* before sending another one, so normally write coalescing just causes added
* delay.
*/
static void op_sock_set_tcp_nodelay(op_sock _fd, int _nodelay)
{
# if defined(TCP_NODELAY)&&(defined(IPPROTO_TCP)||defined(SOL_TCP))
# if defined(IPPROTO_TCP)
# define OP_SO_LEVEL IPPROTO_TCP
# else
# define OP_SO_LEVEL SOL_TCP
# endif
/*It doesn't really matter if this call fails, but it would be interesting
to hit a case where it does. */
OP_ALWAYS_TRUE(!setsockopt(_fd, OP_SO_LEVEL, TCP_NODELAY,
&_nodelay, sizeof(_nodelay)));
# endif
}
#if defined(_WIN32)
static void op_init_winsock()
{
static LONG count;
static WSADATA wsadata;
if (InterlockedIncrement(&count) == 1)
WSAStartup(0x0202, &wsadata);
}
#endif
/*A single physical connection to an HTTP server.
We may have several of these open at once.*/
struct OpusHTTPConn {
/*The current position indicator for this connection. */
opus_int64 pos;
/*The position where the current request will end, or -1 if we're reading
until EOF (an unseekable stream or the initial HTTP/1.0 request). */
opus_int64 end_pos;
/*The position where next request we've sent will start, or -1 if we haven't
sent the next request yet. */
opus_int64 next_pos;
/*The end of the next request or -1 if we requested the rest of the resource.
This is only set to a meaningful value if next_pos is not -1. */
opus_int64 next_end;
/*The SSL connection, if this is https. */
// SSL *ssl_conn;
/*The next connection in either the LRU or free list. */
OpusHTTPConn *next;
/*The last time we blocked for reading from this connection. */
struct _timeb read_time;
/*The number of bytes we've read since the last time we blocked. */
opus_int64 read_bytes;
/*The estimated throughput of this connection, in bytes/s. */
opus_int64 read_rate;
/*The socket we're reading from. */
op_sock fd;
/*The number of remaining requests we are allowed on this connection. */
int nrequests_left;
/*The chunk size to use for pipelining requests. */
opus_int32 chunk_size;
};
static void op_http_conn_init(OpusHTTPConn * _conn)
{
_conn->next_pos = -1;
// _conn->ssl_conn=NULL;
_conn->next = NULL;
_conn->fd = OP_INVALID_SOCKET;
}
static void op_http_conn_clear(OpusHTTPConn * _conn)
{
/*SSL frees the BIO for us. */
if (_conn->fd != OP_INVALID_SOCKET)
close(_conn->fd);
}
/*The global stream state.*/
struct OpusHTTPStream {
/*The list of connections. */
OpusHTTPConn conns[OP_NCONNS_MAX];
/*The context object used as a framework for TLS/SSL functions. */
// SSL_CTX *ssl_ctx;
/*The cached session to reuse for future connections. */
// SSL_SESSION *ssl_session;
/*The LRU list (ordered from MRU to LRU) of currently connected
connections. */
OpusHTTPConn *lru_head;
/*The free list. */
OpusHTTPConn *free_head;
/*The URL to connect to. */
OpusParsedURL url;
/*Information about the address we connected to. */
struct addrinfo addr_info;
/*The address we connected to. */
union {
struct sockaddr s;
struct sockaddr_in v4;
struct sockaddr_in6 v6;
} addr;
/*The last time we re-resolved the host. */
struct _timeb resolve_time;
/*A buffer used to build HTTP requests. */
OpusStringBuf request;
/*A buffer used to build proxy CONNECT requests. */
OpusStringBuf proxy_connect;
/*A buffer used to receive the response headers. */
OpusStringBuf response;
/*The Content-Length, if specified, or -1 otherwise.
This will always be specified for seekable streams. */
opus_int64 content_length;
/*The position indicator used when no connection is active. */
opus_int64 pos;
/*The host we actually connected to. */
char *connect_host;
/*The port we actually connected to. */
unsigned connect_port;
/*The connection we're currently reading from.
This can be -1 if no connection is active. */
int cur_conni;
/*Whether or not the server supports range requests. */
int seekable;
/*Whether or not the server supports HTTP/1.1 with persistent connections. */
int pipeline;
/*Whether or not we should skip certificate checks. */
int skip_certificate_check;
/*The offset of the tail of the request.
Only the offset in the Range: header appears after this, allowing us to
quickly edit the request to ask for a new range. */
int request_tail;
/*The estimated time required to open a new connection, in milliseconds. */
opus_int32 connect_rate;
};
static void op_http_stream_init(OpusHTTPStream * _stream)
{
OpusHTTPConn **pnext;
int ci;
pnext = &_stream->free_head;
for (ci = 0; ci < OP_NCONNS_MAX; ci++) {
op_http_conn_init(_stream->conns + ci);
*pnext = _stream->conns + ci;
pnext = &_stream->conns[ci].next;
}
_stream->lru_head = NULL;
op_parsed_url_init(&_stream->url);
op_sb_init(&_stream->request);
op_sb_init(&_stream->proxy_connect);
op_sb_init(&_stream->response);
_stream->connect_host = NULL;
_stream->seekable = 0;
}
/* Close the connection and move it to the free list.
* _stream: The stream containing the free list.
* _conn: The connection to close.