http.c 131 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592
  1. /********************************************************************
  2. * *
  3. * THIS FILE IS PART OF THE libopusfile SOFTWARE CODEC SOURCE CODE. *
  4. * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS *
  5. * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE *
  6. * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. *
  7. * *
  8. * THE libopusfile SOURCE CODE IS (C) COPYRIGHT 2012-2020 *
  9. * by the Xiph.Org Foundation and contributors https://xiph.org/ *
  10. * *
  11. ********************************************************************/
  12. #ifdef HAVE_CONFIG_H
  13. #include "config.h"
  14. #endif
  15. #include "internal.h"
  16. #include <ctype.h>
  17. #include <errno.h>
  18. #include <limits.h>
  19. #include <string.h>
  20. /*RFCs referenced in this file:
  21. RFC 761: DOD Standard Transmission Control Protocol
  22. RFC 1535: A Security Problem and Proposed Correction With Widely Deployed DNS
  23. Software
  24. RFC 1738: Uniform Resource Locators (URL)
  25. RFC 1945: Hypertext Transfer Protocol -- HTTP/1.0
  26. RFC 2068: Hypertext Transfer Protocol -- HTTP/1.1
  27. RFC 2145: Use and Interpretation of HTTP Version Numbers
  28. RFC 2246: The TLS Protocol Version 1.0
  29. RFC 2459: Internet X.509 Public Key Infrastructure Certificate and
  30. Certificate Revocation List (CRL) Profile
  31. RFC 2616: Hypertext Transfer Protocol -- HTTP/1.1
  32. RFC 2617: HTTP Authentication: Basic and Digest Access Authentication
  33. RFC 2817: Upgrading to TLS Within HTTP/1.1
  34. RFC 2818: HTTP Over TLS
  35. RFC 3492: Punycode: A Bootstring encoding of Unicode for Internationalized
  36. Domain Names in Applications (IDNA)
  37. RFC 3986: Uniform Resource Identifier (URI): Generic Syntax
  38. RFC 3987: Internationalized Resource Identifiers (IRIs)
  39. RFC 4343: Domain Name System (DNS) Case Insensitivity Clarification
  40. RFC 5894: Internationalized Domain Names for Applications (IDNA):
  41. Background, Explanation, and Rationale
  42. RFC 6066: Transport Layer Security (TLS) Extensions: Extension Definitions
  43. RFC 6125: Representation and Verification of Domain-Based Application Service
  44. Identity within Internet Public Key Infrastructure Using X.509 (PKIX)
  45. Certificates in the Context of Transport Layer Security (TLS)
  46. RFC 6555: Happy Eyeballs: Success with Dual-Stack Hosts*/
  47. typedef struct OpusParsedURL OpusParsedURL;
  48. typedef struct OpusStringBuf OpusStringBuf;
  49. typedef struct OpusHTTPConn OpusHTTPConn;
  50. typedef struct OpusHTTPStream OpusHTTPStream;
  51. static char *op_string_range_dup(const char *_start,const char *_end){
  52. size_t len;
  53. char *ret;
  54. OP_ASSERT(_start<=_end);
  55. len=_end-_start;
  56. /*This is to help avoid overflow elsewhere, later.*/
  57. if(OP_UNLIKELY(len>=INT_MAX))return NULL;
  58. ret=(char *)_ogg_malloc(sizeof(*ret)*(len+1));
  59. if(OP_LIKELY(ret!=NULL)){
  60. ret=(char *)memcpy(ret,_start,sizeof(*ret)*(len));
  61. ret[len]='\0';
  62. }
  63. return ret;
  64. }
  65. static char *op_string_dup(const char *_s){
  66. return op_string_range_dup(_s,_s+strlen(_s));
  67. }
  68. static char *op_string_tolower(char *_s){
  69. int i;
  70. for(i=0;_s[i]!='\0';i++){
  71. int c;
  72. c=_s[i];
  73. if(c>='A'&&c<='Z')c+='a'-'A';
  74. _s[i]=(char)c;
  75. }
  76. return _s;
  77. }
  78. /*URI character classes (from RFC 3986).*/
  79. #define OP_URL_ALPHA \
  80. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
  81. #define OP_URL_DIGIT "0123456789"
  82. #define OP_URL_HEXDIGIT "0123456789ABCDEFabcdef"
  83. /*Not a character class, but the characters allowed in <scheme>.*/
  84. #define OP_URL_SCHEME OP_URL_ALPHA OP_URL_DIGIT "+-."
  85. #define OP_URL_GEN_DELIMS "#/:?@[]"
  86. #define OP_URL_SUB_DELIMS "!$&'()*+,;="
  87. #define OP_URL_RESERVED OP_URL_GEN_DELIMS OP_URL_SUB_DELIMS
  88. #define OP_URL_UNRESERVED OP_URL_ALPHA OP_URL_DIGIT "-._~"
  89. /*Not a character class, but the characters allowed in <pct-encoded>.*/
  90. #define OP_URL_PCT_ENCODED "%"
  91. /*Not a character class or production rule, but for convenience.*/
  92. #define OP_URL_PCHAR_BASE \
  93. OP_URL_UNRESERVED OP_URL_PCT_ENCODED OP_URL_SUB_DELIMS
  94. #define OP_URL_PCHAR OP_URL_PCHAR_BASE ":@"
  95. /*Not a character class, but the characters allowed in <userinfo> and
  96. <IP-literal>.*/
  97. #define OP_URL_PCHAR_NA OP_URL_PCHAR_BASE ":"
  98. /*Not a character class, but the characters allowed in <segment-nz-nc>.*/
  99. #define OP_URL_PCHAR_NC OP_URL_PCHAR_BASE "@"
  100. /*Not a character clsss, but the characters allowed in <path>.*/
  101. #define OP_URL_PATH OP_URL_PCHAR "/"
  102. /*Not a character class, but the characters allowed in <query> / <fragment>.*/
  103. #define OP_URL_QUERY_FRAG OP_URL_PCHAR "/?"
  104. /*Check the <% HEXDIG HEXDIG> escapes of a URL for validity.
  105. Return: 0 if valid, or a negative value on failure.*/
  106. static int op_validate_url_escapes(const char *_s){
  107. int i;
  108. for(i=0;_s[i];i++){
  109. if(_s[i]=='%'){
  110. if(OP_UNLIKELY(!isxdigit(_s[i+1]))
  111. ||OP_UNLIKELY(!isxdigit(_s[i+2]))
  112. /*RFC 3986 says %00 "should be rejected if the application is not
  113. expecting to receive raw data within a component."*/
  114. ||OP_UNLIKELY(_s[i+1]=='0'&&_s[i+2]=='0')){
  115. return OP_FALSE;
  116. }
  117. i+=2;
  118. }
  119. }
  120. return 0;
  121. }
  122. /*Convert a hex digit to its actual value.
  123. _c: The hex digit to convert.
  124. Presumed to be valid ('0'...'9', 'A'...'F', or 'a'...'f').
  125. Return: The value of the digit, in the range [0,15].*/
  126. static int op_hex_value(int _c){
  127. return _c>='a'?_c-'a'+10:_c>='A'?_c-'A'+10:_c-'0';
  128. }
  129. /*Unescape all the <% HEXDIG HEXDIG> sequences in a string in-place.
  130. This does no validity checking.*/
  131. static char *op_unescape_url_component(char *_s){
  132. int i;
  133. int j;
  134. for(i=j=0;_s[i];i++,j++){
  135. if(_s[i]=='%'){
  136. _s[i]=(char)(op_hex_value(_s[i+1])<<4|op_hex_value(_s[i+2]));
  137. i+=2;
  138. }
  139. }
  140. return _s;
  141. }
  142. /*Parse a file: URL.
  143. This code is not meant to be fast: strspn() with large sets is likely to be
  144. slow, but it is very convenient.
  145. It is meant to be RFC 1738-compliant (as updated by RFC 3986).*/
  146. static const char *op_parse_file_url(const char *_src){
  147. const char *scheme_end;
  148. const char *path;
  149. const char *path_end;
  150. scheme_end=_src+strspn(_src,OP_URL_SCHEME);
  151. if(OP_UNLIKELY(*scheme_end!=':')
  152. ||scheme_end-_src!=4||op_strncasecmp(_src,"file",4)!=0){
  153. /*Unsupported protocol.*/
  154. return NULL;
  155. }
  156. /*Make sure all escape sequences are valid to simplify unescaping later.*/
  157. if(OP_UNLIKELY(op_validate_url_escapes(scheme_end+1)<0))return NULL;
  158. if(scheme_end[1]=='/'&&scheme_end[2]=='/'){
  159. const char *host;
  160. /*file: URLs can have a host!
  161. Yeah, I was surprised, too, but that's what RFC 1738 says.
  162. It also says, "The file URL scheme is unusual in that it does not specify
  163. an Internet protocol or access method for such files; as such, its
  164. utility in network protocols between hosts is limited," which is a mild
  165. understatement.*/
  166. host=scheme_end+3;
  167. /*The empty host is what we expect.*/
  168. if(OP_LIKELY(*host=='/'))path=host;
  169. else{
  170. const char *host_end;
  171. char host_buf[28];
  172. /*RFC 1738 says localhost "is interpreted as `the machine from which the
  173. URL is being interpreted,'" so let's check for it.*/
  174. host_end=host+strspn(host,OP_URL_PCHAR_BASE);
  175. /*No <port> allowed.
  176. This also rejects IP-Literals.*/
  177. if(*host_end!='/')return NULL;
  178. /*An escaped "localhost" can take at most 27 characters.*/
  179. if(OP_UNLIKELY(host_end-host>27))return NULL;
  180. memcpy(host_buf,host,sizeof(*host_buf)*(host_end-host));
  181. host_buf[host_end-host]='\0';
  182. op_unescape_url_component(host_buf);
  183. op_string_tolower(host_buf);
  184. /*Some other host: give up.*/
  185. if(OP_UNLIKELY(strcmp(host_buf,"localhost")!=0))return NULL;
  186. path=host_end;
  187. }
  188. }
  189. else path=scheme_end+1;
  190. path_end=path+strspn(path,OP_URL_PATH);
  191. /*This will reject a <query> or <fragment> component, too.
  192. I don't know what to do with queries, but a temporal fragment would at
  193. least make sense.
  194. RFC 1738 pretty clearly defines a <searchpart> that's equivalent to the
  195. RFC 3986 <query> component for other schemes, but not the file: scheme,
  196. so I'm going to just reject it.*/
  197. if(*path_end!='\0')return NULL;
  198. return path;
  199. }
  200. #if defined(OP_ENABLE_HTTP)
  201. # if defined(_WIN32)
  202. # include <winsock2.h>
  203. # include <ws2tcpip.h>
  204. # include <openssl/ssl.h>
  205. # include <openssl/asn1.h>
  206. # include "winerrno.h"
  207. typedef SOCKET op_sock;
  208. # define OP_INVALID_SOCKET (INVALID_SOCKET)
  209. /*Vista and later support WSAPoll(), but we don't want to rely on that.
  210. Instead we re-implement it badly using select().
  211. Unfortunately, they define a conflicting struct pollfd, so we only define our
  212. own if it looks like that one has not already been defined.*/
  213. # if !defined(POLLIN)
  214. /*Equivalent to POLLIN.*/
  215. # define POLLRDNORM (0x0100)
  216. /*Priority band data can be read.*/
  217. # define POLLRDBAND (0x0200)
  218. /*There is data to read.*/
  219. # define POLLIN (POLLRDNORM|POLLRDBAND)
  220. /*There is urgent data to read.*/
  221. # define POLLPRI (0x0400)
  222. /*Equivalent to POLLOUT.*/
  223. # define POLLWRNORM (0x0010)
  224. /*Writing now will not block.*/
  225. # define POLLOUT (POLLWRNORM)
  226. /*Priority data may be written.*/
  227. # define POLLWRBAND (0x0020)
  228. /*Error condition (output only).*/
  229. # define POLLERR (0x0001)
  230. /*Hang up (output only).*/
  231. # define POLLHUP (0x0002)
  232. /*Invalid request: fd not open (output only).*/
  233. # define POLLNVAL (0x0004)
  234. struct pollfd{
  235. /*File descriptor.*/
  236. op_sock fd;
  237. /*Requested events.*/
  238. short events;
  239. /*Returned events.*/
  240. short revents;
  241. };
  242. # endif
  243. /*But Winsock never defines nfds_t (it's simply hard-coded to ULONG).*/
  244. typedef unsigned long nfds_t;
  245. /*The usage of FD_SET() below is O(N^2).
  246. This is okay because select() is limited to 64 sockets in Winsock, anyway.
  247. In practice, we only ever call it with one or two sockets.*/
  248. static int op_poll_win32(struct pollfd *_fds,nfds_t _nfds,int _timeout){
  249. struct timeval tv;
  250. fd_set ifds;
  251. fd_set ofds;
  252. fd_set efds;
  253. nfds_t i;
  254. int ret;
  255. FD_ZERO(&ifds);
  256. FD_ZERO(&ofds);
  257. FD_ZERO(&efds);
  258. for(i=0;i<_nfds;i++){
  259. _fds[i].revents=0;
  260. if(_fds[i].events&POLLIN)FD_SET(_fds[i].fd,&ifds);
  261. if(_fds[i].events&POLLOUT)FD_SET(_fds[i].fd,&ofds);
  262. FD_SET(_fds[i].fd,&efds);
  263. }
  264. if(_timeout>=0){
  265. tv.tv_sec=_timeout/1000;
  266. tv.tv_usec=(_timeout%1000)*1000;
  267. }
  268. ret=select(-1,&ifds,&ofds,&efds,_timeout<0?NULL:&tv);
  269. if(ret>0){
  270. for(i=0;i<_nfds;i++){
  271. if(FD_ISSET(_fds[i].fd,&ifds))_fds[i].revents|=POLLIN;
  272. if(FD_ISSET(_fds[i].fd,&ofds))_fds[i].revents|=POLLOUT;
  273. /*This isn't correct: there are several different things that might have
  274. happened to a fd in efds, but I don't know a good way to distinguish
  275. them without more context from the caller.
  276. It's okay, because we don't actually check any of these bits, we just
  277. need _some_ bit set.*/
  278. if(FD_ISSET(_fds[i].fd,&efds))_fds[i].revents|=POLLHUP;
  279. }
  280. }
  281. return ret;
  282. }
  283. /*We define op_errno() to make it clear that it's not an l-value like normal
  284. errno is.*/
  285. # define op_errno() (WSAGetLastError()?WSAGetLastError()-WSABASEERR:0)
  286. # define op_reset_errno() (WSASetLastError(0))
  287. /*The remaining functions don't get an op_ prefix even though they only
  288. operate on sockets, because we don't use non-socket I/O here, and this
  289. minimizes the changes needed to deal with Winsock.*/
  290. # define close(_fd) closesocket(_fd)
  291. /*This takes an int for the address length, even though the value is of type
  292. socklen_t (defined as an unsigned integer type with at least 32 bits).*/
  293. # define connect(_fd,_addr,_addrlen) \
  294. (OP_UNLIKELY((_addrlen)>(socklen_t)INT_MAX)? \
  295. WSASetLastError(WSA_NOT_ENOUGH_MEMORY),-1: \
  296. connect(_fd,_addr,(int)(_addrlen)))
  297. /*This relies on sizeof(u_long)==sizeof(int), which is always true on both
  298. Win32 and Win64.*/
  299. # define ioctl(_fd,_req,_arg) ioctlsocket(_fd,_req,(u_long *)(_arg))
  300. # define getsockopt(_fd,_level,_name,_val,_len) \
  301. getsockopt(_fd,_level,_name,(char *)(_val),_len)
  302. # define setsockopt(_fd,_level,_name,_val,_len) \
  303. setsockopt(_fd,_level,_name,(const char *)(_val),_len)
  304. # define poll(_fds,_nfds,_timeout) op_poll_win32(_fds,_nfds,_timeout)
  305. # if defined(_MSC_VER)
  306. typedef ptrdiff_t ssize_t;
  307. # endif
  308. /*Load certificates from the built-in certificate store.*/
  309. int SSL_CTX_set_default_verify_paths_win32(SSL_CTX *_ssl_ctx);
  310. # define SSL_CTX_set_default_verify_paths \
  311. SSL_CTX_set_default_verify_paths_win32
  312. # else
  313. /*Normal Berkeley sockets.*/
  314. # ifndef BSD_COMP
  315. # define BSD_COMP 1 /* for FIONREAD on Solaris/Illumos */
  316. # endif
  317. # include <sys/ioctl.h>
  318. # include <sys/types.h>
  319. # include <sys/socket.h>
  320. # include <arpa/inet.h>
  321. # include <netinet/in.h>
  322. # include <netinet/tcp.h>
  323. # include <fcntl.h>
  324. # include <netdb.h>
  325. # include <poll.h>
  326. # include <unistd.h>
  327. # include <openssl/ssl.h>
  328. # include <openssl/asn1.h>
  329. typedef int op_sock;
  330. # define OP_INVALID_SOCKET (-1)
  331. # define op_errno() (errno)
  332. # define op_reset_errno() (errno=0)
  333. # endif
  334. # ifdef OP_HAVE_CLOCK_GETTIME
  335. # include <time.h>
  336. typedef struct timespec op_time;
  337. # else
  338. # include <sys/timeb.h>
  339. typedef struct timeb op_time;
  340. # endif
  341. # include <openssl/x509v3.h>
  342. # if (defined(LIBRESSL_VERSION_NUMBER)&&OPENSSL_VERSION_NUMBER==0x20000000L)
  343. # undef OPENSSL_VERSION_NUMBER
  344. # define OPENSSL_VERSION_NUMBER 0x1000115fL
  345. # endif
  346. /*The maximum number of simultaneous connections.
  347. RFC 2616 says this SHOULD NOT be more than 2, but everyone on the modern web
  348. ignores that (e.g., IE 8 bumped theirs up from 2 to 6, Firefox uses 15).
  349. If it makes you feel better, we'll only ever actively read from one of these
  350. at a time.
  351. The others are kept around mainly to avoid slow-starting a new connection
  352. when seeking, and time out rapidly.*/
  353. # define OP_NCONNS_MAX (4)
  354. /*The amount of time before we attempt to re-resolve the host.
  355. This is 10 minutes, as recommended in RFC 6555 for expiring cached connection
  356. results for dual-stack hosts.*/
  357. # define OP_RESOLVE_CACHE_TIMEOUT_MS (10*60*(opus_int32)1000)
  358. /*The number of redirections at which we give up.
  359. The value here is the current default in Firefox.
  360. RFC 2068 mandated a maximum of 5, but RFC 2616 relaxed that to "a client
  361. SHOULD detect infinite redirection loops."
  362. Fortunately, 20 is less than infinity.*/
  363. # define OP_REDIRECT_LIMIT (20)
  364. /*The initial size of the buffer used to read a response message (before the
  365. body).*/
  366. # define OP_RESPONSE_SIZE_MIN (510)
  367. /*The maximum size of a response message (before the body).
  368. Responses larger than this will be discarded.
  369. I've seen a real server return 20 kB of data for a 302 Found response.
  370. Increasing this beyond 32kB will cause problems on platforms with a 16-bit
  371. int.*/
  372. # define OP_RESPONSE_SIZE_MAX (32766)
  373. /*The number of milliseconds we will allow a connection to sit idle before we
  374. refuse to resurrect it.
  375. Apache as of 2.2 has reduced its default timeout to 5 seconds (from 15), so
  376. that's what we'll use here.*/
  377. # define OP_CONNECTION_IDLE_TIMEOUT_MS (5*1000)
  378. /*The number of milliseconds we will wait to send or receive data before giving
  379. up.*/
  380. # define OP_POLL_TIMEOUT_MS (30*1000)
  381. /*We will always attempt to read ahead at least this much in preference to
  382. opening a new connection.*/
  383. # define OP_READAHEAD_THRESH_MIN (32*(opus_int32)1024)
  384. /*The amount of data to request after a seek.
  385. This is a trade-off between read throughput after a seek vs. the the ability
  386. to quickly perform another seek with the same connection.*/
  387. # define OP_PIPELINE_CHUNK_SIZE (32*(opus_int32)1024)
  388. /*Subsequent chunks are requested with larger and larger sizes until they pass
  389. this threshold, after which we just ask for the rest of the resource.*/
  390. # define OP_PIPELINE_CHUNK_SIZE_MAX (1024*(opus_int32)1024)
  391. /*This is the maximum number of requests we'll make with a single connection.
  392. Many servers will simply disconnect after we attempt some number of requests,
  393. possibly without sending a Connection: close header, meaning we won't
  394. discover it until we try to read beyond the end of the current chunk.
  395. We can reconnect when that happens, but this is slow.
  396. Instead, we impose a limit ourselves (set to the default for Apache
  397. installations and thus likely the most common value in use).*/
  398. # define OP_PIPELINE_MAX_REQUESTS (100)
  399. /*This should be the number of requests, starting from a chunk size of
  400. OP_PIPELINE_CHUNK_SIZE and doubling each time, until we exceed
  401. OP_PIPELINE_CHUNK_SIZE_MAX and just request the rest of the file.
  402. We won't reuse a connection when seeking unless it has at least this many
  403. requests left, to reduce the chances we'll have to open a new connection
  404. while reading forward afterwards.*/
  405. # define OP_PIPELINE_MIN_REQUESTS (7)
  406. /*Is this an https URL?
  407. For now we can simply check the last letter of the scheme.*/
  408. # define OP_URL_IS_SSL(_url) ((_url)->scheme[4]=='s')
  409. /*Does this URL use the default port for its scheme?*/
  410. # define OP_URL_IS_DEFAULT_PORT(_url) \
  411. (!OP_URL_IS_SSL(_url)&&(_url)->port==80 \
  412. ||OP_URL_IS_SSL(_url)&&(_url)->port==443)
  413. struct OpusParsedURL{
  414. /*Either "http" or "https".*/
  415. char *scheme;
  416. /*The user name from the <userinfo> component, or NULL.*/
  417. char *user;
  418. /*The password from the <userinfo> component, or NULL.*/
  419. char *pass;
  420. /*The <host> component.
  421. This may not be NULL.*/
  422. char *host;
  423. /*The <path> and <query> components.
  424. This may not be NULL.*/
  425. char *path;
  426. /*The <port> component.
  427. This is set to the default port if the URL did not contain one.*/
  428. unsigned port;
  429. };
  430. /*Parse a URL.
  431. This code is not meant to be fast: strspn() with large sets is likely to be
  432. slow, but it is very convenient.
  433. It is meant to be RFC 3986-compliant.
  434. We currently do not support IRIs (Internationalized Resource Identifiers,
  435. RFC 3987).
  436. Callers should translate them to URIs first.*/
  437. static int op_parse_url_impl(OpusParsedURL *_dst,const char *_src){
  438. const char *scheme_end;
  439. const char *authority;
  440. const char *userinfo_end;
  441. const char *user;
  442. const char *user_end;
  443. const char *pass;
  444. const char *hostport;
  445. const char *hostport_end;
  446. const char *host_end;
  447. const char *port;
  448. opus_int32 port_num;
  449. const char *port_end;
  450. const char *path;
  451. const char *path_end;
  452. const char *uri_end;
  453. scheme_end=_src+strspn(_src,OP_URL_SCHEME);
  454. if(OP_UNLIKELY(*scheme_end!=':')
  455. ||OP_UNLIKELY(scheme_end-_src<4)||OP_UNLIKELY(scheme_end-_src>5)
  456. ||OP_UNLIKELY(op_strncasecmp(_src,"https",(int)(scheme_end-_src))!=0)){
  457. /*Unsupported protocol.*/
  458. return OP_EIMPL;
  459. }
  460. if(OP_UNLIKELY(scheme_end[1]!='/')||OP_UNLIKELY(scheme_end[2]!='/')){
  461. /*We require an <authority> component.*/
  462. return OP_EINVAL;
  463. }
  464. authority=scheme_end+3;
  465. /*Make sure all escape sequences are valid to simplify unescaping later.*/
  466. if(OP_UNLIKELY(op_validate_url_escapes(authority)<0))return OP_EINVAL;
  467. /*Look for a <userinfo> component.*/
  468. userinfo_end=authority+strspn(authority,OP_URL_PCHAR_NA);
  469. if(*userinfo_end=='@'){
  470. /*Found one.*/
  471. user=authority;
  472. /*Look for a password (yes, clear-text passwords are deprecated, I know,
  473. but what else are people supposed to use? use SSL if you care).*/
  474. user_end=authority+strspn(authority,OP_URL_PCHAR_BASE);
  475. if(*user_end==':')pass=user_end+1;
  476. else pass=NULL;
  477. hostport=userinfo_end+1;
  478. }
  479. else{
  480. /*We shouldn't have to initialize user_end, but gcc is too dumb to figure
  481. out that user!=NULL below means we didn't take this else branch.*/
  482. user=user_end=NULL;
  483. pass=NULL;
  484. hostport=authority;
  485. }
  486. /*Try to figure out where the <host> component ends.*/
  487. if(hostport[0]=='['){
  488. hostport++;
  489. /*We have an <IP-literal>, which can contain colons.*/
  490. hostport_end=host_end=hostport+strspn(hostport,OP_URL_PCHAR_NA);
  491. if(OP_UNLIKELY(*hostport_end++!=']'))return OP_EINVAL;
  492. }
  493. /*Currently we don't support IDNA (RFC 5894), because I don't want to deal
  494. with the policy about which domains should not be internationalized to
  495. avoid confusing similarities.
  496. Give this API Punycode (RFC 3492) domain names instead.*/
  497. else hostport_end=host_end=hostport+strspn(hostport,OP_URL_PCHAR_BASE);
  498. /*TODO: Validate host.*/
  499. /*Is there a port number?*/
  500. port_num=-1;
  501. if(*hostport_end==':'){
  502. int i;
  503. port=hostport_end+1;
  504. port_end=port+strspn(port,OP_URL_DIGIT);
  505. path=port_end;
  506. /*Not part of RFC 3986, but require port numbers in the range 0...65535.*/
  507. if(OP_LIKELY(port_end-port>0)){
  508. while(*port=='0')port++;
  509. if(OP_UNLIKELY(port_end-port>5))return OP_EINVAL;
  510. port_num=0;
  511. for(i=0;i<port_end-port;i++)port_num=port_num*10+port[i]-'0';
  512. if(OP_UNLIKELY(port_num>65535))return OP_EINVAL;
  513. }
  514. }
  515. else path=hostport_end;
  516. path_end=path+strspn(path,OP_URL_PATH);
  517. /*If the path is not empty, it must begin with a '/'.*/
  518. if(OP_LIKELY(path_end>path)&&OP_UNLIKELY(path[0]!='/'))return OP_EINVAL;
  519. /*Consume the <query> component, if any (right now we don't split this out
  520. from the <path> component).*/
  521. if(*path_end=='?')path_end=path_end+strspn(path_end,OP_URL_QUERY_FRAG);
  522. /*Discard the <fragment> component, if any.
  523. This doesn't get sent to the server.
  524. Some day we should add support for Media Fragment URIs
  525. <https://www.w3.org/TR/media-frags/>.*/
  526. if(*path_end=='#')uri_end=path_end+1+strspn(path_end+1,OP_URL_QUERY_FRAG);
  527. else uri_end=path_end;
  528. /*If there's anything left, this was not a valid URL.*/
  529. if(OP_UNLIKELY(*uri_end!='\0'))return OP_EINVAL;
  530. _dst->scheme=op_string_range_dup(_src,scheme_end);
  531. if(OP_UNLIKELY(_dst->scheme==NULL))return OP_EFAULT;
  532. op_string_tolower(_dst->scheme);
  533. if(user!=NULL){
  534. _dst->user=op_string_range_dup(user,user_end);
  535. if(OP_UNLIKELY(_dst->user==NULL))return OP_EFAULT;
  536. op_unescape_url_component(_dst->user);
  537. /*Unescaping might have created a ':' in the username.
  538. That's not allowed by RFC 2617's Basic Authentication Scheme.*/
  539. if(OP_UNLIKELY(strchr(_dst->user,':')!=NULL))return OP_EINVAL;
  540. }
  541. else _dst->user=NULL;
  542. if(pass!=NULL){
  543. _dst->pass=op_string_range_dup(pass,userinfo_end);
  544. if(OP_UNLIKELY(_dst->pass==NULL))return OP_EFAULT;
  545. op_unescape_url_component(_dst->pass);
  546. }
  547. else _dst->pass=NULL;
  548. _dst->host=op_string_range_dup(hostport,host_end);
  549. if(OP_UNLIKELY(_dst->host==NULL))return OP_EFAULT;
  550. if(port_num<0){
  551. if(_src[4]=='s')port_num=443;
  552. else port_num=80;
  553. }
  554. _dst->port=(unsigned)port_num;
  555. /*RFC 2616 says an empty <abs-path> component is equivalent to "/", and we
  556. MUST use the latter in the Request-URI.
  557. Reserve space for the slash here.*/
  558. if(path==path_end||path[0]=='?')path--;
  559. _dst->path=op_string_range_dup(path,path_end);
  560. if(OP_UNLIKELY(_dst->path==NULL))return OP_EFAULT;
  561. /*And force-set it here.*/
  562. _dst->path[0]='/';
  563. return 0;
  564. }
  565. static void op_parsed_url_init(OpusParsedURL *_url){
  566. memset(_url,0,sizeof(*_url));
  567. }
  568. static void op_parsed_url_clear(OpusParsedURL *_url){
  569. _ogg_free(_url->scheme);
  570. _ogg_free(_url->user);
  571. _ogg_free(_url->pass);
  572. _ogg_free(_url->host);
  573. _ogg_free(_url->path);
  574. }
  575. static int op_parse_url(OpusParsedURL *_dst,const char *_src){
  576. OpusParsedURL url;
  577. int ret;
  578. op_parsed_url_init(&url);
  579. ret=op_parse_url_impl(&url,_src);
  580. if(OP_UNLIKELY(ret<0))op_parsed_url_clear(&url);
  581. else *_dst=*&url;
  582. return ret;
  583. }
  584. /*A buffer to hold growing strings.
  585. The main purpose of this is to consolidate allocation checks and simplify
  586. cleanup on a failed allocation.*/
  587. struct OpusStringBuf{
  588. char *buf;
  589. int nbuf;
  590. int cbuf;
  591. };
  592. static void op_sb_init(OpusStringBuf *_sb){
  593. _sb->buf=NULL;
  594. _sb->nbuf=0;
  595. _sb->cbuf=0;
  596. }
  597. static void op_sb_clear(OpusStringBuf *_sb){
  598. _ogg_free(_sb->buf);
  599. }
  600. /*Make sure we have room for at least _capacity characters (plus 1 more for the
  601. terminating NUL).*/
  602. static int op_sb_ensure_capacity(OpusStringBuf *_sb,int _capacity){
  603. char *buf;
  604. int cbuf;
  605. buf=_sb->buf;
  606. cbuf=_sb->cbuf;
  607. if(_capacity>=cbuf-1){
  608. if(OP_UNLIKELY(cbuf>INT_MAX-1>>1))return OP_EFAULT;
  609. if(OP_UNLIKELY(_capacity>=INT_MAX-1))return OP_EFAULT;
  610. cbuf=OP_MAX(2*cbuf+1,_capacity+1);
  611. buf=_ogg_realloc(buf,sizeof(*buf)*cbuf);
  612. if(OP_UNLIKELY(buf==NULL))return OP_EFAULT;
  613. _sb->buf=buf;
  614. _sb->cbuf=cbuf;
  615. }
  616. return 0;
  617. }
  618. /*Increase the capacity of the buffer, but not to more than _max_size
  619. characters (plus 1 more for the terminating NUL).*/
  620. static int op_sb_grow(OpusStringBuf *_sb,int _max_size){
  621. char *buf;
  622. int cbuf;
  623. buf=_sb->buf;
  624. cbuf=_sb->cbuf;
  625. OP_ASSERT(_max_size<=INT_MAX-1);
  626. cbuf=cbuf<=_max_size-1>>1?2*cbuf+1:_max_size+1;
  627. buf=_ogg_realloc(buf,sizeof(*buf)*cbuf);
  628. if(OP_UNLIKELY(buf==NULL))return OP_EFAULT;
  629. _sb->buf=buf;
  630. _sb->cbuf=cbuf;
  631. return 0;
  632. }
  633. static int op_sb_append(OpusStringBuf *_sb,const char *_s,int _len){
  634. char *buf;
  635. int nbuf;
  636. int ret;
  637. nbuf=_sb->nbuf;
  638. if(OP_UNLIKELY(nbuf>INT_MAX-_len))return OP_EFAULT;
  639. ret=op_sb_ensure_capacity(_sb,nbuf+_len);
  640. if(OP_UNLIKELY(ret<0))return ret;
  641. buf=_sb->buf;
  642. memcpy(buf+nbuf,_s,sizeof(*buf)*_len);
  643. nbuf+=_len;
  644. buf[nbuf]='\0';
  645. _sb->nbuf=nbuf;
  646. return 0;
  647. }
  648. static int op_sb_append_string(OpusStringBuf *_sb,const char *_s){
  649. size_t len;
  650. len=strlen(_s);
  651. if(OP_UNLIKELY(len>(size_t)INT_MAX))return OP_EFAULT;
  652. return op_sb_append(_sb,_s,(int)len);
  653. }
  654. static int op_sb_append_port(OpusStringBuf *_sb,unsigned _port){
  655. char port_buf[7];
  656. OP_ASSERT(_port<=65535U);
  657. sprintf(port_buf,":%u",_port);
  658. return op_sb_append_string(_sb,port_buf);
  659. }
  660. static int op_sb_append_nonnegative_int64(OpusStringBuf *_sb,opus_int64 _i){
  661. char digit;
  662. int nbuf_start;
  663. int ret;
  664. OP_ASSERT(_i>=0);
  665. nbuf_start=_sb->nbuf;
  666. ret=0;
  667. do{
  668. digit='0'+_i%10;
  669. ret|=op_sb_append(_sb,&digit,1);
  670. _i/=10;
  671. }
  672. while(_i>0);
  673. if(OP_LIKELY(ret>=0)){
  674. char *buf;
  675. int nbuf_end;
  676. buf=_sb->buf;
  677. nbuf_end=_sb->nbuf-1;
  678. /*We've added the digits backwards.
  679. Reverse them.*/
  680. while(nbuf_start<nbuf_end){
  681. digit=buf[nbuf_start];
  682. buf[nbuf_start]=buf[nbuf_end];
  683. buf[nbuf_end]=digit;
  684. nbuf_start++;
  685. nbuf_end--;
  686. }
  687. }
  688. return ret;
  689. }
  690. static struct addrinfo *op_resolve(const char *_host,unsigned _port){
  691. struct addrinfo *addrs;
  692. struct addrinfo hints;
  693. char service[6];
  694. memset(&hints,0,sizeof(hints));
  695. hints.ai_socktype=SOCK_STREAM;
  696. #if defined(AI_NUMERICSERV)
  697. hints.ai_flags=AI_NUMERICSERV;
  698. #endif
  699. OP_ASSERT(_port<=65535U);
  700. sprintf(service,"%u",_port);
  701. if(OP_LIKELY(!getaddrinfo(_host,service,&hints,&addrs)))return addrs;
  702. return NULL;
  703. }
  704. static int op_sock_set_nonblocking(op_sock _fd,int _nonblocking){
  705. #if !defined(_WIN32)
  706. int flags;
  707. flags=fcntl(_fd,F_GETFL);
  708. if(OP_UNLIKELY(flags<0))return flags;
  709. if(_nonblocking)flags|=O_NONBLOCK;
  710. else flags&=~O_NONBLOCK;
  711. return fcntl(_fd,F_SETFL,flags);
  712. #else
  713. return ioctl(_fd,FIONBIO,&_nonblocking);
  714. #endif
  715. }
  716. /*Disable/enable write coalescing if we can.
  717. We always send whole requests at once and always parse the response headers
  718. before sending another one, so normally write coalescing just causes added
  719. delay.*/
  720. static void op_sock_set_tcp_nodelay(op_sock _fd,int _nodelay){
  721. # if defined(TCP_NODELAY)&&(defined(IPPROTO_TCP)||defined(SOL_TCP))
  722. # if defined(IPPROTO_TCP)
  723. # define OP_SO_LEVEL IPPROTO_TCP
  724. # else
  725. # define OP_SO_LEVEL SOL_TCP
  726. # endif
  727. /*It doesn't really matter if this call fails, but it would be interesting
  728. to hit a case where it does.*/
  729. OP_ALWAYS_TRUE(!setsockopt(_fd,OP_SO_LEVEL,TCP_NODELAY,
  730. &_nodelay,sizeof(_nodelay)));
  731. # endif
  732. }
  733. #if defined(_WIN32)
  734. static void op_init_winsock(){
  735. static LONG count;
  736. static WSADATA wsadata;
  737. if(InterlockedIncrement(&count)==1)WSAStartup(0x0202,&wsadata);
  738. }
  739. #endif
  740. /*A single physical connection to an HTTP server.
  741. We may have several of these open at once.*/
  742. struct OpusHTTPConn{
  743. /*The current position indicator for this connection.*/
  744. opus_int64 pos;
  745. /*The position where the current request will end, or -1 if we're reading
  746. until EOF (an unseekable stream or the initial HTTP/1.0 request).*/
  747. opus_int64 end_pos;
  748. /*The position where next request we've sent will start, or -1 if we haven't
  749. sent the next request yet.*/
  750. opus_int64 next_pos;
  751. /*The end of the next request or -1 if we requested the rest of the resource.
  752. This is only set to a meaningful value if next_pos is not -1.*/
  753. opus_int64 next_end;
  754. /*The SSL connection, if this is https.*/
  755. SSL *ssl_conn;
  756. /*The next connection in either the LRU or free list.*/
  757. OpusHTTPConn *next;
  758. /*The last time we blocked for reading from this connection.*/
  759. op_time read_time;
  760. /*The number of bytes we've read since the last time we blocked.*/
  761. opus_int64 read_bytes;
  762. /*The estimated throughput of this connection, in bytes/s.*/
  763. opus_int64 read_rate;
  764. /*The socket we're reading from.*/
  765. op_sock fd;
  766. /*The number of remaining requests we are allowed on this connection.*/
  767. int nrequests_left;
  768. /*The chunk size to use for pipelining requests.*/
  769. opus_int32 chunk_size;
  770. };
  771. static void op_http_conn_init(OpusHTTPConn *_conn){
  772. _conn->next_pos=-1;
  773. _conn->ssl_conn=NULL;
  774. _conn->next=NULL;
  775. _conn->fd=OP_INVALID_SOCKET;
  776. }
  777. static void op_http_conn_clear(OpusHTTPConn *_conn){
  778. if(_conn->ssl_conn!=NULL)SSL_free(_conn->ssl_conn);
  779. /*SSL frees the BIO for us.*/
  780. if(_conn->fd!=OP_INVALID_SOCKET)close(_conn->fd);
  781. }
  782. /*The global stream state.*/
  783. struct OpusHTTPStream{
  784. /*The list of connections.*/
  785. OpusHTTPConn conns[OP_NCONNS_MAX];
  786. /*The context object used as a framework for TLS/SSL functions.*/
  787. SSL_CTX *ssl_ctx;
  788. /*The cached session to reuse for future connections.*/
  789. SSL_SESSION *ssl_session;
  790. /*The LRU list (ordered from MRU to LRU) of currently connected
  791. connections.*/
  792. OpusHTTPConn *lru_head;
  793. /*The free list.*/
  794. OpusHTTPConn *free_head;
  795. /*The URL to connect to.*/
  796. OpusParsedURL url;
  797. /*Information about the address we connected to.*/
  798. struct addrinfo addr_info;
  799. /*The address we connected to.*/
  800. union{
  801. struct sockaddr s;
  802. struct sockaddr_in v4;
  803. struct sockaddr_in6 v6;
  804. } addr;
  805. /*The last time we re-resolved the host.*/
  806. op_time resolve_time;
  807. /*A buffer used to build HTTP requests.*/
  808. OpusStringBuf request;
  809. /*A buffer used to build proxy CONNECT requests.*/
  810. OpusStringBuf proxy_connect;
  811. /*A buffer used to receive the response headers.*/
  812. OpusStringBuf response;
  813. /*The Content-Length, if specified, or -1 otherwise.
  814. This will always be specified for seekable streams.*/
  815. opus_int64 content_length;
  816. /*The position indicator used when no connection is active.*/
  817. opus_int64 pos;
  818. /*The host we actually connected to.*/
  819. char *connect_host;
  820. /*The port we actually connected to.*/
  821. unsigned connect_port;
  822. /*The connection we're currently reading from.
  823. This can be -1 if no connection is active.*/
  824. int cur_conni;
  825. /*Whether or not the server supports range requests.*/
  826. int seekable;
  827. /*Whether or not the server supports HTTP/1.1 with persistent connections.*/
  828. int pipeline;
  829. /*Whether or not we should skip certificate checks.*/
  830. int skip_certificate_check;
  831. /*The offset of the tail of the request.
  832. Only the offset in the Range: header appears after this, allowing us to
  833. quickly edit the request to ask for a new range.*/
  834. int request_tail;
  835. /*The estimated time required to open a new connection, in milliseconds.*/
  836. opus_int32 connect_rate;
  837. };
  838. static void op_http_stream_init(OpusHTTPStream *_stream){
  839. OpusHTTPConn **pnext;
  840. int ci;
  841. pnext=&_stream->free_head;
  842. for(ci=0;ci<OP_NCONNS_MAX;ci++){
  843. op_http_conn_init(_stream->conns+ci);
  844. *pnext=_stream->conns+ci;
  845. pnext=&_stream->conns[ci].next;
  846. }
  847. _stream->ssl_ctx=NULL;
  848. _stream->ssl_session=NULL;
  849. _stream->lru_head=NULL;
  850. op_parsed_url_init(&_stream->url);
  851. op_sb_init(&_stream->request);
  852. op_sb_init(&_stream->proxy_connect);
  853. op_sb_init(&_stream->response);
  854. _stream->connect_host=NULL;
  855. _stream->seekable=0;
  856. }
  857. /*Close the connection and move it to the free list.
  858. _stream: The stream containing the free list.
  859. _conn: The connection to close.
  860. _pnext: The linked-list pointer currently pointing to this connection.
  861. _gracefully: Whether or not to shut down cleanly.*/
  862. static void op_http_conn_close(OpusHTTPStream *_stream,OpusHTTPConn *_conn,
  863. OpusHTTPConn **_pnext,int _gracefully){
  864. /*If we don't shut down gracefully, the server MUST NOT re-use our session
  865. according to RFC 2246, because it can't tell the difference between an
  866. abrupt close and a truncation attack.
  867. So we shut down gracefully if we can.
  868. However, we will not wait if this would block (it's not worth the savings
  869. from session resumption to do so).
  870. Clients (that's us) MAY resume a TLS session that ended with an incomplete
  871. close, according to RFC 2818, so there's no reason to make sure the server
  872. shut things down gracefully.*/
  873. if(_gracefully&&_conn->ssl_conn!=NULL)SSL_shutdown(_conn->ssl_conn);
  874. op_http_conn_clear(_conn);
  875. _conn->next_pos=-1;
  876. _conn->ssl_conn=NULL;
  877. _conn->fd=OP_INVALID_SOCKET;
  878. OP_ASSERT(*_pnext==_conn);
  879. *_pnext=_conn->next;
  880. _conn->next=_stream->free_head;
  881. _stream->free_head=_conn;
  882. }
  883. static void op_http_stream_clear(OpusHTTPStream *_stream){
  884. while(_stream->lru_head!=NULL){
  885. op_http_conn_close(_stream,_stream->lru_head,&_stream->lru_head,0);
  886. }
  887. if(_stream->ssl_session!=NULL)SSL_SESSION_free(_stream->ssl_session);
  888. if(_stream->ssl_ctx!=NULL)SSL_CTX_free(_stream->ssl_ctx);
  889. op_sb_clear(&_stream->response);
  890. op_sb_clear(&_stream->proxy_connect);
  891. op_sb_clear(&_stream->request);
  892. if(_stream->connect_host!=_stream->url.host)_ogg_free(_stream->connect_host);
  893. op_parsed_url_clear(&_stream->url);
  894. }
  895. static int op_http_conn_write_fully(OpusHTTPConn *_conn,
  896. const char *_buf,int _buf_size){
  897. struct pollfd fd;
  898. SSL *ssl_conn;
  899. fd.fd=_conn->fd;
  900. ssl_conn=_conn->ssl_conn;
  901. while(_buf_size>0){
  902. int err;
  903. if(ssl_conn!=NULL){
  904. int ret;
  905. ret=SSL_write(ssl_conn,_buf,_buf_size);
  906. if(ret>0){
  907. /*Wrote some data.*/
  908. _buf+=ret;
  909. _buf_size-=ret;
  910. continue;
  911. }
  912. /*Connection closed.*/
  913. else if(ret==0)return OP_FALSE;
  914. err=SSL_get_error(ssl_conn,ret);
  915. /*Yes, renegotiations can cause SSL_write() to block for reading.*/
  916. if(err==SSL_ERROR_WANT_READ)fd.events=POLLIN;
  917. else if(err==SSL_ERROR_WANT_WRITE)fd.events=POLLOUT;
  918. else return OP_FALSE;
  919. }
  920. else{
  921. ssize_t ret;
  922. op_reset_errno();
  923. ret=send(fd.fd,_buf,_buf_size,0);
  924. if(ret>0){
  925. _buf+=ret;
  926. OP_ASSERT(ret<=_buf_size);
  927. _buf_size-=(int)ret;
  928. continue;
  929. }
  930. err=op_errno();
  931. if(err!=EAGAIN&&err!=EWOULDBLOCK)return OP_FALSE;
  932. fd.events=POLLOUT;
  933. }
  934. if(poll(&fd,1,OP_POLL_TIMEOUT_MS)<=0)return OP_FALSE;
  935. }
  936. return 0;
  937. }
  938. static int op_http_conn_estimate_available(OpusHTTPConn *_conn){
  939. int available;
  940. int ret;
  941. ret=ioctl(_conn->fd,FIONREAD,&available);
  942. if(ret<0)available=0;
  943. /*This requires the SSL read_ahead flag to be unset to work.
  944. We ignore partial records as well as the protocol overhead for any pending
  945. bytes.
  946. This means we might return somewhat less than can truly be read without
  947. blocking (if there's a partial record).
  948. This is okay, because we're using this value to estimate network transfer
  949. time, and we _have_ already received those bytes.
  950. We also might return slightly more (due to protocol overhead), but that's
  951. small enough that it probably doesn't matter.*/
  952. if(_conn->ssl_conn!=NULL)available+=SSL_pending(_conn->ssl_conn);
  953. return available;
  954. }
  955. static void op_time_get(op_time *now){
  956. # ifdef OP_HAVE_CLOCK_GETTIME
  957. /*Prefer a monotonic clock that continues to increment during suspend.*/
  958. # ifdef CLOCK_BOOTTIME
  959. if(clock_gettime(CLOCK_BOOTTIME,now)!=0)
  960. # endif
  961. # ifdef CLOCK_MONOTONIC
  962. if(clock_gettime(CLOCK_MONOTONIC,now)!=0)
  963. # endif
  964. OP_ALWAYS_TRUE(!clock_gettime(CLOCK_REALTIME,now));
  965. # else
  966. ftime(now);
  967. # endif
  968. }
  969. static opus_int32 op_time_diff_ms(const op_time *_end, const op_time *_start){
  970. # ifdef OP_HAVE_CLOCK_GETTIME
  971. opus_int64 dtime;
  972. dtime=_end->tv_sec-(opus_int64)_start->tv_sec;
  973. OP_ASSERT(_end->tv_nsec<1000000000);
  974. OP_ASSERT(_start->tv_nsec<1000000000);
  975. if(OP_UNLIKELY(dtime>(OP_INT32_MAX-1000)/1000))return OP_INT32_MAX;
  976. if(OP_UNLIKELY(dtime<(OP_INT32_MIN+1000)/1000))return OP_INT32_MIN;
  977. return (opus_int32)dtime*1000+(_end->tv_nsec-_start->tv_nsec)/1000000;
  978. # else
  979. opus_int64 dtime;
  980. dtime=_end->time-(opus_int64)_start->time;
  981. OP_ASSERT(_end->millitm<1000);
  982. OP_ASSERT(_start->millitm<1000);
  983. if(OP_UNLIKELY(dtime>(OP_INT32_MAX-1000)/1000))return OP_INT32_MAX;
  984. if(OP_UNLIKELY(dtime<(OP_INT32_MIN+1000)/1000))return OP_INT32_MIN;
  985. return (opus_int32)dtime*1000+_end->millitm-_start->millitm;
  986. # endif
  987. }
  988. /*Update the read rate estimate for this connection.*/
  989. static void op_http_conn_read_rate_update(OpusHTTPConn *_conn){
  990. op_time read_time;
  991. opus_int32 read_delta_ms;
  992. opus_int64 read_delta_bytes;
  993. opus_int64 read_rate;
  994. read_delta_bytes=_conn->read_bytes;
  995. if(read_delta_bytes<=0)return;
  996. op_time_get(&read_time);
  997. read_delta_ms=op_time_diff_ms(&read_time,&_conn->read_time);
  998. read_rate=_conn->read_rate;
  999. read_delta_ms=OP_MAX(read_delta_ms,1);
  1000. read_rate+=read_delta_bytes*1000/read_delta_ms-read_rate+4>>3;
  1001. *&_conn->read_time=*&read_time;
  1002. _conn->read_bytes=0;
  1003. _conn->read_rate=read_rate;
  1004. }
  1005. /*Tries to read from the given connection.
  1006. [out] _buf: Returns the data read.
  1007. _buf_size: The size of the buffer.
  1008. _blocking: Whether or not to block until some data is retrieved.
  1009. Return: A positive number of bytes read on success.
  1010. 0: The read would block, or the connection was closed.
  1011. OP_EREAD: There was a fatal read error.*/
  1012. static int op_http_conn_read(OpusHTTPConn *_conn,
  1013. char *_buf,int _buf_size,int _blocking){
  1014. struct pollfd fd;
  1015. SSL *ssl_conn;
  1016. int nread;
  1017. int nread_unblocked;
  1018. fd.fd=_conn->fd;
  1019. ssl_conn=_conn->ssl_conn;
  1020. nread=nread_unblocked=0;
  1021. /*RFC 2818 says "client implementations MUST treat any premature closes as
  1022. errors and the data received as potentially truncated," so we make very
  1023. sure to report read errors upwards.*/
  1024. do{
  1025. int err;
  1026. if(ssl_conn!=NULL){
  1027. int ret;
  1028. ret=SSL_read(ssl_conn,_buf+nread,_buf_size-nread);
  1029. OP_ASSERT(ret<=_buf_size-nread);
  1030. if(ret>0){
  1031. /*Read some data.
  1032. Keep going to see if there's more.*/
  1033. nread+=ret;
  1034. nread_unblocked+=ret;
  1035. continue;
  1036. }
  1037. /*If we already read some data, return it right now.*/
  1038. if(nread>0)break;
  1039. err=SSL_get_error(ssl_conn,ret);
  1040. if(ret==0){
  1041. /*Connection close.
  1042. Check for a clean shutdown to prevent truncation attacks.
  1043. This check always succeeds for SSLv2, as it has no "close notify"
  1044. message and thus can't verify an orderly shutdown.*/
  1045. return err==SSL_ERROR_ZERO_RETURN?0:OP_EREAD;
  1046. }
  1047. if(err==SSL_ERROR_WANT_READ)fd.events=POLLIN;
  1048. /*Yes, renegotiations can cause SSL_read() to block for writing.*/
  1049. else if(err==SSL_ERROR_WANT_WRITE)fd.events=POLLOUT;
  1050. /*Some other error.*/
  1051. else return OP_EREAD;
  1052. }
  1053. else{
  1054. ssize_t ret;
  1055. op_reset_errno();
  1056. ret=recv(fd.fd,_buf+nread,_buf_size-nread,0);
  1057. OP_ASSERT(ret<=_buf_size-nread);
  1058. if(ret>0){
  1059. /*Read some data.
  1060. Keep going to see if there's more.*/
  1061. OP_ASSERT(ret<=_buf_size-nread);
  1062. nread+=(int)ret;
  1063. nread_unblocked+=(int)ret;
  1064. continue;
  1065. }
  1066. /*If we already read some data or the connection was closed, return
  1067. right now.*/
  1068. if(ret==0||nread>0)break;
  1069. err=op_errno();
  1070. if(err!=EAGAIN&&err!=EWOULDBLOCK)return OP_EREAD;
  1071. fd.events=POLLIN;
  1072. }
  1073. _conn->read_bytes+=nread_unblocked;
  1074. op_http_conn_read_rate_update(_conn);
  1075. nread_unblocked=0;
  1076. if(!_blocking)break;
  1077. /*Need to wait to get any data at all.*/
  1078. if(poll(&fd,1,OP_POLL_TIMEOUT_MS)<=0)return OP_EREAD;
  1079. }
  1080. while(nread<_buf_size);
  1081. _conn->read_bytes+=nread_unblocked;
  1082. return nread;
  1083. }
  1084. /*Tries to look at the pending data for a connection without consuming it.
  1085. [out] _buf: Returns the data at which we're peeking.
  1086. _buf_size: The size of the buffer.*/
  1087. static int op_http_conn_peek(OpusHTTPConn *_conn,char *_buf,int _buf_size){
  1088. struct pollfd fd;
  1089. SSL *ssl_conn;
  1090. int ret;
  1091. fd.fd=_conn->fd;
  1092. ssl_conn=_conn->ssl_conn;
  1093. for(;;){
  1094. int err;
  1095. if(ssl_conn!=NULL){
  1096. ret=SSL_peek(ssl_conn,_buf,_buf_size);
  1097. /*Either saw some data or the connection was closed.*/
  1098. if(ret>=0)return ret;
  1099. err=SSL_get_error(ssl_conn,ret);
  1100. if(err==SSL_ERROR_WANT_READ)fd.events=POLLIN;
  1101. /*Yes, renegotiations can cause SSL_peek() to block for writing.*/
  1102. else if(err==SSL_ERROR_WANT_WRITE)fd.events=POLLOUT;
  1103. else return 0;
  1104. }
  1105. else{
  1106. op_reset_errno();
  1107. ret=(int)recv(fd.fd,_buf,_buf_size,MSG_PEEK);
  1108. /*Either saw some data or the connection was closed.*/
  1109. if(ret>=0)return ret;
  1110. err=op_errno();
  1111. if(err!=EAGAIN&&err!=EWOULDBLOCK)return 0;
  1112. fd.events=POLLIN;
  1113. }
  1114. /*Need to wait to get any data at all.*/
  1115. if(poll(&fd,1,OP_POLL_TIMEOUT_MS)<=0)return 0;
  1116. }
  1117. }
  1118. /*When parsing response headers, RFC 2616 mandates that all lines end in CR LF.
  1119. However, even in the year 2012, I have seen broken servers use just a LF.
  1120. This is the evil that Postel's advice from RFC 761 breeds.*/
  1121. /*Reads the entirety of a response to an HTTP request into the response buffer.
  1122. Actual parsing and validation is done later.
  1123. Return: The number of bytes in the response on success, OP_EREAD if the
  1124. connection was closed before reading any data, or another negative
  1125. value on any other error.*/
  1126. static int op_http_conn_read_response(OpusHTTPConn *_conn,
  1127. OpusStringBuf *_response){
  1128. int ret;
  1129. _response->nbuf=0;
  1130. ret=op_sb_ensure_capacity(_response,OP_RESPONSE_SIZE_MIN);
  1131. if(OP_UNLIKELY(ret<0))return ret;
  1132. for(;;){
  1133. char *buf;
  1134. int size;
  1135. int capacity;
  1136. int read_limit;
  1137. int terminated;
  1138. size=_response->nbuf;
  1139. capacity=_response->cbuf-1;
  1140. if(OP_UNLIKELY(size>=capacity)){
  1141. ret=op_sb_grow(_response,OP_RESPONSE_SIZE_MAX);
  1142. if(OP_UNLIKELY(ret<0))return ret;
  1143. capacity=_response->cbuf-1;
  1144. /*The response was too large.
  1145. This prevents a bad server from running us out of memory.*/
  1146. if(OP_UNLIKELY(size>=capacity))return OP_EIMPL;
  1147. }
  1148. buf=_response->buf;
  1149. ret=op_http_conn_peek(_conn,buf+size,capacity-size);
  1150. if(OP_UNLIKELY(ret<=0))return size<=0?OP_EREAD:OP_FALSE;
  1151. /*We read some data.*/
  1152. /*Make sure the starting characters are "HTTP".
  1153. Otherwise we could wind up waiting for a response from something that is
  1154. not an HTTP server until we time out.*/
  1155. if(size<4&&op_strncasecmp(buf,"HTTP",OP_MIN(size+ret,4))!=0){
  1156. return OP_FALSE;
  1157. }
  1158. /*How far can we read without passing the "\r\n\r\n" terminator?*/
  1159. buf[size+ret]='\0';
  1160. terminated=0;
  1161. for(read_limit=OP_MAX(size-3,0);read_limit<size+ret;read_limit++){
  1162. /*We don't look for the leading '\r' thanks to broken servers.*/
  1163. if(buf[read_limit]=='\n'){
  1164. if(buf[read_limit+1]=='\r'&&OP_LIKELY(buf[read_limit+2]=='\n')){
  1165. terminated=3;
  1166. break;
  1167. }
  1168. /*This case is for broken servers.*/
  1169. else if(OP_UNLIKELY(buf[read_limit+1]=='\n')){
  1170. terminated=2;
  1171. break;
  1172. }
  1173. }
  1174. }
  1175. read_limit+=terminated;
  1176. OP_ASSERT(size<=read_limit);
  1177. OP_ASSERT(read_limit<=size+ret);
  1178. /*Actually consume that data.*/
  1179. ret=op_http_conn_read(_conn,buf+size,read_limit-size,1);
  1180. if(OP_UNLIKELY(ret<=0))return OP_FALSE;
  1181. size+=ret;
  1182. buf[size]='\0';
  1183. _response->nbuf=size;
  1184. /*We found the terminator and read all the data up to and including it.*/
  1185. if(terminated&&OP_LIKELY(size>=read_limit))return size;
  1186. }
  1187. return OP_EIMPL;
  1188. }
  1189. # define OP_HTTP_DIGIT "0123456789"
  1190. /*The Reason-Phrase is not allowed to contain control characters, except
  1191. horizontal tab (HT: \011).*/
  1192. # define OP_HTTP_CREASON_PHRASE \
  1193. "\001\002\003\004\005\006\007\010\012\013\014\015\016\017\020\021" \
  1194. "\022\023\024\025\026\027\030\031\032\033\034\035\036\037\177"
  1195. # define OP_HTTP_CTLS \
  1196. "\001\002\003\004\005\006\007\010\011\012\013\014\015\016\017\020" \
  1197. "\021\022\023\024\025\026\027\030\031\032\033\034\035\036\037\177"
  1198. /*This also includes '\t', but we get that from OP_HTTP_CTLS.*/
  1199. # define OP_HTTP_SEPARATORS " \"(),/:;<=>?@[\\]{}"
  1200. /*TEXT can also include LWS, but that has structure, so we parse it
  1201. separately.*/
  1202. # define OP_HTTP_CTOKEN OP_HTTP_CTLS OP_HTTP_SEPARATORS
  1203. /*Return: The amount of linear white space (LWS) at the start of _s.*/
  1204. static int op_http_lwsspn(const char *_s){
  1205. int i;
  1206. for(i=0;;){
  1207. if(_s[0]=='\r'&&_s[1]=='\n'&&(_s[2]=='\t'||_s[2]==' '))i+=3;
  1208. /*This case is for broken servers.*/
  1209. else if(_s[0]=='\n'&&(_s[1]=='\t'||_s[1]==' '))i+=2;
  1210. else if(_s[i]=='\t'||_s[i]==' ')i++;
  1211. else return i;
  1212. }
  1213. }
  1214. static char *op_http_parse_status_line(int *_v1_1_compat,
  1215. char **_status_code,char *_response){
  1216. char *next;
  1217. char *status_code;
  1218. int v1_1_compat;
  1219. size_t d;
  1220. /*RFC 2616 Section 6.1 does not say if the tokens in the Status-Line can be
  1221. separated by optional LWS, but since it specifically calls out where
  1222. spaces are to be placed and that CR and LF are not allowed except at the
  1223. end, we are assuming extra LWS is not allowed.*/
  1224. /*We already validated that this starts with "HTTP"*/
  1225. OP_ASSERT(op_strncasecmp(_response,"HTTP",4)==0);
  1226. next=_response+4;
  1227. if(OP_UNLIKELY(*next++!='/'))return NULL;
  1228. d=strspn(next,OP_HTTP_DIGIT);
  1229. /*"Leading zeros MUST be ignored by recipients."*/
  1230. while(*next=='0'){
  1231. next++;
  1232. OP_ASSERT(d>0);
  1233. d--;
  1234. }
  1235. /*We only support version 1.x*/
  1236. if(OP_UNLIKELY(d!=1)||OP_UNLIKELY(*next++!='1'))return NULL;
  1237. if(OP_UNLIKELY(*next++!='.'))return NULL;
  1238. d=strspn(next,OP_HTTP_DIGIT);
  1239. if(OP_UNLIKELY(d<=0))return NULL;
  1240. /*"Leading zeros MUST be ignored by recipients."*/
  1241. while(*next=='0'){
  1242. next++;
  1243. OP_ASSERT(d>0);
  1244. d--;
  1245. }
  1246. /*We don't need to parse the version number.
  1247. Any non-zero digit means it's at least 1.*/
  1248. v1_1_compat=d>0;
  1249. next+=d;
  1250. if(OP_UNLIKELY(*next++!=' '))return NULL;
  1251. status_code=next;
  1252. d=strspn(next,OP_HTTP_DIGIT);
  1253. if(OP_UNLIKELY(d!=3))return NULL;
  1254. next+=d;
  1255. /*The Reason-Phrase can be empty, but the space must be here.*/
  1256. if(OP_UNLIKELY(*next++!=' '))return NULL;
  1257. next+=strcspn(next,OP_HTTP_CREASON_PHRASE);
  1258. /*We are not mandating this be present thanks to broken servers.*/
  1259. if(OP_LIKELY(*next=='\r'))next++;
  1260. if(OP_UNLIKELY(*next++!='\n'))return NULL;
  1261. if(_v1_1_compat!=NULL)*_v1_1_compat=v1_1_compat;
  1262. *_status_code=status_code;
  1263. return next;
  1264. }
  1265. /*Get the next response header.
  1266. [out] _header: The header token, NUL-terminated, with leading and trailing
  1267. whitespace stripped, and converted to lower case (to simplify
  1268. case-insensitive comparisons), or NULL if there are no more
  1269. response headers.
  1270. [out] _cdr: The remaining contents of the header, excluding the initial
  1271. colon (':') and the terminating CRLF ("\r\n"),
  1272. NUL-terminated, and with leading and trailing whitespace
  1273. stripped, or NULL if there are no more response headers.
  1274. [inout] _s: On input, this points to the start of the current line of the
  1275. response headers.
  1276. On output, it points to the start of the first line following
  1277. this header, or NULL if there are no more response headers.
  1278. Return: 0 on success, or a negative value on failure.*/
  1279. static int op_http_get_next_header(char **_header,char **_cdr,char **_s){
  1280. char *header;
  1281. char *header_end;
  1282. char *cdr;
  1283. char *cdr_end;
  1284. char *next;
  1285. size_t d;
  1286. next=*_s;
  1287. /*The second case is for broken servers.*/
  1288. if(next[0]=='\r'&&next[1]=='\n'||OP_UNLIKELY(next[0]=='\n')){
  1289. /*No more headers.*/
  1290. *_header=NULL;
  1291. *_cdr=NULL;
  1292. *_s=NULL;
  1293. return 0;
  1294. }
  1295. header=next+op_http_lwsspn(next);
  1296. d=strcspn(header,OP_HTTP_CTOKEN);
  1297. if(OP_UNLIKELY(d<=0))return OP_FALSE;
  1298. header_end=header+d;
  1299. next=header_end+op_http_lwsspn(header_end);
  1300. if(OP_UNLIKELY(*next++!=':'))return OP_FALSE;
  1301. next+=op_http_lwsspn(next);
  1302. cdr=next;
  1303. do{
  1304. cdr_end=next+strcspn(next,OP_HTTP_CTLS);
  1305. next=cdr_end+op_http_lwsspn(cdr_end);
  1306. }
  1307. while(next>cdr_end);
  1308. /*We are not mandating this be present thanks to broken servers.*/
  1309. if(OP_LIKELY(*next=='\r'))next++;
  1310. if(OP_UNLIKELY(*next++!='\n'))return OP_FALSE;
  1311. *header_end='\0';
  1312. *cdr_end='\0';
  1313. /*Field names are case-insensitive.*/
  1314. op_string_tolower(header);
  1315. *_header=header;
  1316. *_cdr=cdr;
  1317. *_s=next;
  1318. return 0;
  1319. }
  1320. static opus_int64 op_http_parse_nonnegative_int64(const char **_next,
  1321. const char *_cdr){
  1322. const char *next;
  1323. opus_int64 ret;
  1324. int i;
  1325. next=_cdr+strspn(_cdr,OP_HTTP_DIGIT);
  1326. *_next=next;
  1327. if(OP_UNLIKELY(next<=_cdr))return OP_FALSE;
  1328. while(*_cdr=='0')_cdr++;
  1329. if(OP_UNLIKELY(next-_cdr>19))return OP_EIMPL;
  1330. ret=0;
  1331. for(i=0;i<next-_cdr;i++){
  1332. int digit;
  1333. digit=_cdr[i]-'0';
  1334. /*Check for overflow.*/
  1335. if(OP_UNLIKELY(ret>(OP_INT64_MAX-9)/10+(digit<=7)))return OP_EIMPL;
  1336. ret=ret*10+digit;
  1337. }
  1338. return ret;
  1339. }
  1340. static opus_int64 op_http_parse_content_length(const char *_cdr){
  1341. const char *next;
  1342. opus_int64 content_length;
  1343. content_length=op_http_parse_nonnegative_int64(&next,_cdr);
  1344. if(OP_UNLIKELY(*next!='\0'))return OP_FALSE;
  1345. return content_length;
  1346. }
  1347. static int op_http_parse_content_range(opus_int64 *_first,opus_int64 *_last,
  1348. opus_int64 *_length,const char *_cdr){
  1349. opus_int64 first;
  1350. opus_int64 last;
  1351. opus_int64 length;
  1352. size_t d;
  1353. if(OP_UNLIKELY(op_strncasecmp(_cdr,"bytes",5)!=0))return OP_FALSE;
  1354. _cdr+=5;
  1355. d=op_http_lwsspn(_cdr);
  1356. if(OP_UNLIKELY(d<=0))return OP_FALSE;
  1357. _cdr+=d;
  1358. if(*_cdr!='*'){
  1359. first=op_http_parse_nonnegative_int64(&_cdr,_cdr);
  1360. if(OP_UNLIKELY(first<0))return (int)first;
  1361. _cdr+=op_http_lwsspn(_cdr);
  1362. if(*_cdr++!='-')return OP_FALSE;
  1363. _cdr+=op_http_lwsspn(_cdr);
  1364. last=op_http_parse_nonnegative_int64(&_cdr,_cdr);
  1365. if(OP_UNLIKELY(last<0))return (int)last;
  1366. _cdr+=op_http_lwsspn(_cdr);
  1367. }
  1368. else{
  1369. /*This is for a 416 response (Requested range not satisfiable).*/
  1370. first=last=-1;
  1371. _cdr++;
  1372. }
  1373. if(OP_UNLIKELY(*_cdr++!='/'))return OP_FALSE;
  1374. if(*_cdr!='*'){
  1375. length=op_http_parse_nonnegative_int64(&_cdr,_cdr);
  1376. if(OP_UNLIKELY(length<0))return (int)length;
  1377. }
  1378. else{
  1379. /*The total length is unspecified.*/
  1380. _cdr++;
  1381. length=-1;
  1382. }
  1383. if(OP_UNLIKELY(*_cdr!='\0'))return OP_FALSE;
  1384. if(OP_UNLIKELY(last<first))return OP_FALSE;
  1385. if(length>=0&&OP_UNLIKELY(last>=length))return OP_FALSE;
  1386. *_first=first;
  1387. *_last=last;
  1388. *_length=length;
  1389. return 0;
  1390. }
  1391. /*Parse the Connection response header and look for a "close" token.
  1392. Return: 1 if a "close" token is found, 0 if it's not found, and a negative
  1393. value on error.*/
  1394. static int op_http_parse_connection(char *_cdr){
  1395. size_t d;
  1396. int ret;
  1397. ret=0;
  1398. for(;;){
  1399. d=strcspn(_cdr,OP_HTTP_CTOKEN);
  1400. if(OP_UNLIKELY(d<=0))return OP_FALSE;
  1401. if(op_strncasecmp(_cdr,"close",(int)d)==0)ret=1;
  1402. /*We're supposed to strip and ignore any headers mentioned in the
  1403. Connection header if this response is from an HTTP/1.0 server (to
  1404. work around forwarding of hop-by-hop headers by old proxies), but the
  1405. only hop-by-hop header we look at is Connection itself.
  1406. Everything else is a well-defined end-to-end header, and going back and
  1407. undoing the things we did based on already-examined headers would be
  1408. hard (since we only scan them once, in a destructive manner).
  1409. Therefore we just ignore all the other tokens.*/
  1410. _cdr+=d;
  1411. d=op_http_lwsspn(_cdr);
  1412. if(d<=0)break;
  1413. _cdr+=d;
  1414. }
  1415. return OP_UNLIKELY(*_cdr!='\0')?OP_FALSE:ret;
  1416. }
  1417. typedef int (*op_ssl_step_func)(SSL *_ssl_conn);
  1418. /*Try to run an SSL function to completion (blocking if necessary).*/
  1419. static int op_do_ssl_step(SSL *_ssl_conn,op_sock _fd,op_ssl_step_func _step){
  1420. struct pollfd fd;
  1421. fd.fd=_fd;
  1422. for(;;){
  1423. int ret;
  1424. int err;
  1425. ret=(*_step)(_ssl_conn);
  1426. if(ret>=0)return ret;
  1427. err=SSL_get_error(_ssl_conn,ret);
  1428. if(err==SSL_ERROR_WANT_READ)fd.events=POLLIN;
  1429. else if(err==SSL_ERROR_WANT_WRITE)fd.events=POLLOUT;
  1430. else return OP_FALSE;
  1431. if(poll(&fd,1,OP_POLL_TIMEOUT_MS)<=0)return OP_FALSE;
  1432. }
  1433. }
  1434. /*Implement a BIO type that just indicates every operation should be retried.
  1435. We use this when initializing an SSL connection via a proxy to allow the
  1436. initial handshake to proceed all the way up to the first read attempt, and
  1437. then return.
  1438. This allows the TLS client hello message to be pipelined with the HTTP
  1439. CONNECT request.*/
  1440. static int op_bio_retry_write(BIO *_b,const char *_buf,int _num){
  1441. (void)_buf;
  1442. (void)_num;
  1443. BIO_clear_retry_flags(_b);
  1444. BIO_set_retry_write(_b);
  1445. return -1;
  1446. }
  1447. static int op_bio_retry_read(BIO *_b,char *_buf,int _num){
  1448. (void)_buf;
  1449. (void)_num;
  1450. BIO_clear_retry_flags(_b);
  1451. BIO_set_retry_read(_b);
  1452. return -1;
  1453. }
  1454. static int op_bio_retry_puts(BIO *_b,const char *_str){
  1455. return op_bio_retry_write(_b,_str,0);
  1456. }
  1457. static long op_bio_retry_ctrl(BIO *_b,int _cmd,long _num,void *_ptr){
  1458. long ret;
  1459. (void)_b;
  1460. (void)_num;
  1461. (void)_ptr;
  1462. ret=0;
  1463. switch(_cmd){
  1464. case BIO_CTRL_RESET:
  1465. case BIO_C_RESET_READ_REQUEST:{
  1466. BIO_clear_retry_flags(_b);
  1467. }
  1468. /*Fall through.*/
  1469. case BIO_CTRL_EOF:
  1470. case BIO_CTRL_SET:
  1471. case BIO_CTRL_SET_CLOSE:
  1472. case BIO_CTRL_FLUSH:
  1473. case BIO_CTRL_DUP:{
  1474. ret=1;
  1475. }break;
  1476. }
  1477. return ret;
  1478. }
  1479. # if (OPENSSL_VERSION_NUMBER<0x10100000L&&LIBRESSL_VERSION_NUMBER<0x2070000fL)
  1480. # define BIO_set_data(_b,_ptr) ((_b)->ptr=(_ptr))
  1481. # define BIO_set_init(_b,_init) ((_b)->init=(_init))
  1482. # define ASN1_STRING_get0_data ASN1_STRING_data
  1483. # endif
  1484. static int op_bio_retry_new(BIO *_b){
  1485. BIO_set_init(_b,1);
  1486. # if (OPENSSL_VERSION_NUMBER<0x10100000L&&LIBRESSL_VERSION_NUMBER<0x2070000fL)
  1487. _b->num=0;
  1488. # endif
  1489. BIO_set_data(_b,NULL);
  1490. return 1;
  1491. }
  1492. static int op_bio_retry_free(BIO *_b){
  1493. return _b!=NULL;
  1494. }
  1495. # if (OPENSSL_VERSION_NUMBER<0x10100000L&&LIBRESSL_VERSION_NUMBER<0x2070000fL)
  1496. /*This is not const because OpenSSL doesn't allow it, even though it won't
  1497. write to it.*/
  1498. static BIO_METHOD op_bio_retry_method={
  1499. BIO_TYPE_NULL,
  1500. "retry",
  1501. op_bio_retry_write,
  1502. op_bio_retry_read,
  1503. op_bio_retry_puts,
  1504. NULL,
  1505. op_bio_retry_ctrl,
  1506. op_bio_retry_new,
  1507. op_bio_retry_free,
  1508. NULL
  1509. };
  1510. # endif
  1511. /*Establish a CONNECT tunnel and pipeline the start of the TLS handshake for
  1512. proxying https URL requests.*/
  1513. static int op_http_conn_establish_tunnel(OpusHTTPStream *_stream,
  1514. OpusHTTPConn *_conn,op_sock _fd,SSL *_ssl_conn,BIO *_ssl_bio){
  1515. # if (OPENSSL_VERSION_NUMBER>=0x10100000L||LIBRESSL_VERSION_NUMBER>=0x2070000fL)
  1516. BIO_METHOD *bio_retry_method;
  1517. # endif
  1518. BIO *retry_bio;
  1519. char *status_code;
  1520. char *next;
  1521. int ret;
  1522. _conn->ssl_conn=NULL;
  1523. _conn->fd=_fd;
  1524. OP_ASSERT(_stream->proxy_connect.nbuf>0);
  1525. ret=op_http_conn_write_fully(_conn,
  1526. _stream->proxy_connect.buf,_stream->proxy_connect.nbuf);
  1527. if(OP_UNLIKELY(ret<0))return ret;
  1528. # if (OPENSSL_VERSION_NUMBER>=0x10100000L||LIBRESSL_VERSION_NUMBER>=0x2070000fL)
  1529. bio_retry_method=BIO_meth_new(BIO_TYPE_NULL,"retry");
  1530. if(bio_retry_method==NULL)return OP_EFAULT;
  1531. BIO_meth_set_write(bio_retry_method,op_bio_retry_write);
  1532. BIO_meth_set_read(bio_retry_method,op_bio_retry_read);
  1533. BIO_meth_set_puts(bio_retry_method,op_bio_retry_puts);
  1534. BIO_meth_set_ctrl(bio_retry_method,op_bio_retry_ctrl);
  1535. BIO_meth_set_create(bio_retry_method,op_bio_retry_new);
  1536. BIO_meth_set_destroy(bio_retry_method,op_bio_retry_free);
  1537. retry_bio=BIO_new(bio_retry_method);
  1538. if(OP_UNLIKELY(retry_bio==NULL)){
  1539. BIO_meth_free(bio_retry_method);
  1540. return OP_EFAULT;
  1541. }
  1542. # else
  1543. retry_bio=BIO_new(&op_bio_retry_method);
  1544. if(OP_UNLIKELY(retry_bio==NULL))return OP_EFAULT;
  1545. # endif
  1546. SSL_set_bio(_ssl_conn,retry_bio,_ssl_bio);
  1547. SSL_set_connect_state(_ssl_conn);
  1548. /*This shouldn't succeed, since we can't read yet.*/
  1549. OP_ALWAYS_TRUE(SSL_connect(_ssl_conn)<0);
  1550. SSL_set_bio(_ssl_conn,_ssl_bio,_ssl_bio);
  1551. # if (OPENSSL_VERSION_NUMBER>=0x10100000L||LIBRESSL_VERSION_NUMBER>=0x2070000fL)
  1552. BIO_meth_free(bio_retry_method);
  1553. # endif
  1554. /*Only now do we disable write coalescing, to allow the CONNECT
  1555. request and the start of the TLS handshake to be combined.*/
  1556. op_sock_set_tcp_nodelay(_fd,1);
  1557. ret=op_http_conn_read_response(_conn,&_stream->response);
  1558. if(OP_UNLIKELY(ret<0))return ret;
  1559. next=op_http_parse_status_line(NULL,&status_code,_stream->response.buf);
  1560. /*According to RFC 2817, "Any successful (2xx) response to a
  1561. CONNECT request indicates that the proxy has established a
  1562. connection to the requested host and port."*/
  1563. if(OP_UNLIKELY(next==NULL)||OP_UNLIKELY(status_code[0]!='2'))return OP_FALSE;
  1564. return 0;
  1565. }
  1566. /*Convert a host to a numeric address, if possible.
  1567. Return: A struct addrinfo containing the address, if it was numeric, and NULL
  1568. otherwise.*/
  1569. static struct addrinfo *op_inet_pton(const char *_host){
  1570. struct addrinfo *addrs;
  1571. struct addrinfo hints;
  1572. memset(&hints,0,sizeof(hints));
  1573. hints.ai_socktype=SOCK_STREAM;
  1574. hints.ai_flags=AI_NUMERICHOST;
  1575. if(!getaddrinfo(_host,NULL,&hints,&addrs))return addrs;
  1576. return NULL;
  1577. }
  1578. # if (OPENSSL_VERSION_NUMBER<0x10002000L&&LIBRESSL_VERSION_NUMBER<0x2070000fL)
  1579. /*Match a host name against a host with a possible wildcard pattern according
  1580. to the rules of RFC 6125 Section 6.4.3.
  1581. Return: 0 if the pattern doesn't match, and a non-zero value if it does.*/
  1582. static int op_http_hostname_match(const char *_host,size_t _host_len,
  1583. ASN1_STRING *_pattern){
  1584. const char *pattern;
  1585. size_t host_label_len;
  1586. size_t host_suffix_len;
  1587. size_t pattern_len;
  1588. size_t pattern_label_len;
  1589. size_t pattern_prefix_len;
  1590. size_t pattern_suffix_len;
  1591. if(OP_UNLIKELY(_host_len>(size_t)INT_MAX))return 0;
  1592. pattern=(const char *)ASN1_STRING_get0_data(_pattern);
  1593. pattern_len=strlen(pattern);
  1594. /*Check the pattern for embedded NULs.*/
  1595. if(OP_UNLIKELY(pattern_len!=(size_t)ASN1_STRING_length(_pattern)))return 0;
  1596. pattern_label_len=strcspn(pattern,".");
  1597. OP_ASSERT(pattern_label_len<=pattern_len);
  1598. pattern_prefix_len=strcspn(pattern,"*");
  1599. if(OP_UNLIKELY(pattern_prefix_len>(size_t)INT_MAX))return 0;
  1600. if(pattern_prefix_len>=pattern_label_len){
  1601. /*"The client SHOULD NOT attempt to match a presented identifier in which
  1602. the wildcard character comprises a label other than the left-most label
  1603. (e.g., do not match bar.*.example.net)." [RFC 6125 Section 6.4.3]*/
  1604. if(pattern_prefix_len<pattern_len)return 0;
  1605. /*If the pattern does not contain a wildcard in the first element, do an
  1606. exact match.
  1607. Don't use the system strcasecmp here, as that uses the locale and
  1608. RFC 4343 makes clear that DNS's case-insensitivity only applies to
  1609. the ASCII range.*/
  1610. return _host_len==pattern_len
  1611. &&op_strncasecmp(_host,pattern,(int)_host_len)==0;
  1612. }
  1613. /*"However, the client SHOULD NOT attempt to match a presented identifier
  1614. where the wildcard character is embedded within an A-label or U-label of
  1615. an internationalized domain name." [RFC 6125 Section 6.4.3]*/
  1616. if(op_strncasecmp(pattern,"xn--",4)==0)return 0;
  1617. host_label_len=strcspn(_host,".");
  1618. /*Make sure the host has at least two dots, to prevent the wildcard match
  1619. from being ridiculously wide.
  1620. We should have already checked to ensure it had at least one.*/
  1621. if(OP_UNLIKELY(_host[host_label_len]!='.')
  1622. ||strchr(_host+host_label_len+1,'.')==NULL){
  1623. return 0;
  1624. }
  1625. OP_ASSERT(host_label_len<_host_len);
  1626. /*"If the wildcard character is the only character of the left-most label in
  1627. the presented identifier, the client SHOULD NOT compare against anything
  1628. but the left-most label of the reference identifier (e.g., *.example.com
  1629. would match foo.example.com but not bar.foo.example.com)." [RFC 6125
  1630. Section 6.4.3]
  1631. This is really confusingly worded, as we check this by actually comparing
  1632. the rest of the pattern for an exact match.
  1633. We also use the fact that the wildcard must match at least one character,
  1634. so the left-most label of the hostname must be at least as large as the
  1635. left-most label of the pattern.*/
  1636. if(host_label_len<pattern_label_len)return 0;
  1637. OP_ASSERT(pattern[pattern_prefix_len]=='*');
  1638. /*"The client MAY match a presented identifier in which the wildcard
  1639. character is not the only character of the label (e.g., baz*.example.net
  1640. and *baz.example.net and b*z.example.net would be taken to match
  1641. baz1.example.net and foobaz.example.net and buzz.example.net,
  1642. respectively)." [RFC 6125 Section 6.4.3]*/
  1643. pattern_suffix_len=pattern_len-pattern_prefix_len-1;
  1644. host_suffix_len=_host_len-host_label_len
  1645. +pattern_label_len-pattern_prefix_len-1;
  1646. OP_ASSERT(host_suffix_len<=_host_len);
  1647. return pattern_suffix_len==host_suffix_len
  1648. &&op_strncasecmp(_host,pattern,(int)pattern_prefix_len)==0
  1649. &&op_strncasecmp(_host+_host_len-host_suffix_len,
  1650. pattern+pattern_prefix_len+1,(int)host_suffix_len)==0;
  1651. }
  1652. /*Verify the server's hostname matches the certificate they presented using
  1653. the procedure from Section 6 of RFC 6125.
  1654. Return: 0 if the certificate doesn't match, and a non-zero value if it does.*/
  1655. static int op_http_verify_hostname(OpusHTTPStream *_stream,SSL *_ssl_conn){
  1656. X509 *peer_cert;
  1657. struct addrinfo *addr;
  1658. char *host;
  1659. size_t host_len;
  1660. unsigned char *ip;
  1661. int ip_len;
  1662. int check_cn;
  1663. int ret;
  1664. host=_stream->url.host;
  1665. host_len=strlen(host);
  1666. peer_cert=SSL_get_peer_certificate(_ssl_conn);
  1667. /*We set VERIFY_PEER, so we shouldn't get here without a certificate.*/
  1668. if(OP_UNLIKELY(peer_cert==NULL))return 0;
  1669. ret=0;
  1670. OP_ASSERT(host_len<INT_MAX);
  1671. /*By default, fall back to checking the Common Name if we don't check any
  1672. subjectAltNames of type dNSName.*/
  1673. check_cn=1;
  1674. /*Check to see if the host was specified as a simple IP address.*/
  1675. addr=op_inet_pton(host);
  1676. ip=NULL;
  1677. ip_len=0;
  1678. if(addr!=NULL){
  1679. switch(addr->ai_family){
  1680. case AF_INET:{
  1681. struct sockaddr_in *s;
  1682. s=(struct sockaddr_in *)addr->ai_addr;
  1683. OP_ASSERT(addr->ai_addrlen>=sizeof(*s));
  1684. ip=(unsigned char *)&s->sin_addr;
  1685. ip_len=sizeof(s->sin_addr);
  1686. /*RFC 6125 says, "In this case, the iPAddress subjectAltName must [sic]
  1687. be present in the certificate and must [sic] exactly match the IP in
  1688. the URI."
  1689. So don't allow falling back to a Common Name.*/
  1690. check_cn=0;
  1691. }break;
  1692. case AF_INET6:{
  1693. struct sockaddr_in6 *s;
  1694. s=(struct sockaddr_in6 *)addr->ai_addr;
  1695. OP_ASSERT(addr->ai_addrlen>=sizeof(*s));
  1696. ip=(unsigned char *)&s->sin6_addr;
  1697. ip_len=sizeof(s->sin6_addr);
  1698. check_cn=0;
  1699. }break;
  1700. }
  1701. }
  1702. /*We can only verify IP addresses and "fully-qualified" domain names.
  1703. To quote RFC 6125: "The extracted data MUST include only information that
  1704. can be securely parsed out of the inputs (e.g., parsing the fully
  1705. qualified DNS domain name out of the "host" component (or its
  1706. equivalent) of a URI or deriving the application service type from the
  1707. scheme of a URI) ..."
  1708. We don't have a way to check (without relying on DNS records, which might
  1709. be subverted) if this address is fully-qualified.
  1710. This is particularly problematic when using a CONNECT tunnel, as it is
  1711. the server that does DNS lookup, not us.
  1712. However, we are certain that if the hostname has no '.', it is definitely
  1713. not a fully-qualified domain name (with the exception of crazy TLDs that
  1714. actually resolve, like "uz", but I am willing to ignore those).
  1715. RFC 1535 says "...in any event where a '.' exists in a specified name it
  1716. should be assumed to be a fully qualified domain name (FQDN) and SHOULD
  1717. be tried as a rooted name first."
  1718. That doesn't give us any security guarantees, of course (a subverted DNS
  1719. could fail the original query and our resolver might still retry with a
  1720. local domain appended).*/
  1721. if(ip!=NULL||strchr(host,'.')!=NULL){
  1722. STACK_OF(GENERAL_NAME) *san_names;
  1723. /*RFC 2818 says (after correcting for Eratta 1077): "If a subjectAltName
  1724. extension of type dNSName is present, that MUST be used as the identity.
  1725. Otherwise, the (most specific) Common Name field in the Subject field of
  1726. the certificate MUST be used.
  1727. Although the use of the Common Name is existing practice, it is
  1728. deprecated and Certification Authorities are encouraged to use the
  1729. dNSName instead."
  1730. "Matching is performed using the matching rules specified by RFC 2459.
  1731. If more than one identity of a given type is present in the certificate
  1732. (e.g., more than one dNSName name), a match in any one of the set is
  1733. considered acceptable.
  1734. Names may contain the wildcard character * which is condered to match any
  1735. single domain name component or component fragment.
  1736. E.g., *.a.com matches foo.a.com but not bar.foo.a.com.
  1737. f*.com matches foo.com but not bar.com."
  1738. "In some cases, the URI is specified as an IP address rather than a
  1739. hostname.
  1740. In this case, the iPAddress subjectAltName must be present in the
  1741. certificate and must exactly match the IP in the URI."*/
  1742. san_names=X509_get_ext_d2i(peer_cert,NID_subject_alt_name,NULL,NULL);
  1743. if(san_names!=NULL){
  1744. int nsan_names;
  1745. int sni;
  1746. /*RFC 2459 says there MUST be at least one, but we don't depend on it.*/
  1747. nsan_names=sk_GENERAL_NAME_num(san_names);
  1748. for(sni=0;sni<nsan_names;sni++){
  1749. const GENERAL_NAME *name;
  1750. name=sk_GENERAL_NAME_value(san_names,sni);
  1751. if(ip==NULL){
  1752. if(name->type==GEN_DNS){
  1753. /*We have a subjectAltName extension of type dNSName, so don't fall
  1754. back to a Common Name.
  1755. https://marc.info/?l=openssl-dev&m=139617145216047&w=2 says that
  1756. subjectAltNames of other types do not trigger this restriction,
  1757. (e.g., if they are all IP addresses, we will still check a
  1758. non-IP hostname against a Common Name).*/
  1759. check_cn=0;
  1760. if(op_http_hostname_match(host,host_len,name->d.dNSName)){
  1761. ret=1;
  1762. break;
  1763. }
  1764. }
  1765. }
  1766. else if(name->type==GEN_IPADD){
  1767. unsigned const char *cert_ip;
  1768. /*If we do have an IP address, compare it directly.
  1769. RFC 6125: "When the reference identity is an IP address, the
  1770. identity MUST be converted to the 'network byte order' octet
  1771. string representation.
  1772. For IP Version 4, as specified in RFC 791, the octet string will
  1773. contain exactly four octets.
  1774. For IP Version 6, as specified in RFC 2460, the octet string will
  1775. contain exactly sixteen octets.
  1776. This octet string is then compared against subjectAltName values of
  1777. type iPAddress.
  1778. A match occurs if the reference identity octet string and the value
  1779. octet strings are identical."*/
  1780. cert_ip=ASN1_STRING_get0_data(name->d.iPAddress);
  1781. if(ip_len==ASN1_STRING_length(name->d.iPAddress)
  1782. &&memcmp(ip,cert_ip,ip_len)==0){
  1783. ret=1;
  1784. break;
  1785. }
  1786. }
  1787. }
  1788. sk_GENERAL_NAME_pop_free(san_names,GENERAL_NAME_free);
  1789. }
  1790. /*If we're supposed to fall back to a Common Name, match against it here.*/
  1791. if(check_cn){
  1792. int last_cn_loc;
  1793. int cn_loc;
  1794. /*RFC 6125 says that at least one significant CA is known to issue certs
  1795. with multiple CNs, although it SHOULD NOT.
  1796. It also says: "The server's identity may also be verified by comparing
  1797. the reference identity to the Common Name (CN) value in the last
  1798. Relative Distinguished Name (RDN) of the subject field of the server's
  1799. certificate (where "last" refers to the DER-encoded order...)."
  1800. So find the last one and check it.*/
  1801. cn_loc=-1;
  1802. do{
  1803. last_cn_loc=cn_loc;
  1804. cn_loc=X509_NAME_get_index_by_NID(X509_get_subject_name(peer_cert),
  1805. NID_commonName,last_cn_loc);
  1806. }
  1807. while(cn_loc>=0);
  1808. ret=last_cn_loc>=0
  1809. &&op_http_hostname_match(host,host_len,
  1810. X509_NAME_ENTRY_get_data(
  1811. X509_NAME_get_entry(X509_get_subject_name(peer_cert),last_cn_loc)));
  1812. }
  1813. }
  1814. if(addr!=NULL)freeaddrinfo(addr);
  1815. X509_free(peer_cert);
  1816. return ret;
  1817. }
  1818. # endif
  1819. /*Perform the TLS handshake on a new connection.*/
  1820. static int op_http_conn_start_tls(OpusHTTPStream *_stream,OpusHTTPConn *_conn,
  1821. op_sock _fd,SSL *_ssl_conn){
  1822. SSL_SESSION *ssl_session;
  1823. BIO *ssl_bio;
  1824. int skip_certificate_check;
  1825. int ret;
  1826. /*This always takes an int, even though with Winsock op_sock is a SOCKET.*/
  1827. ssl_bio=BIO_new_socket((int)_fd,BIO_NOCLOSE);
  1828. if(OP_LIKELY(ssl_bio==NULL))return OP_FALSE;
  1829. # if !defined(OPENSSL_NO_TLSEXT)
  1830. /*Support for RFC 6066 Server Name Indication.*/
  1831. SSL_set_tlsext_host_name(_ssl_conn,_stream->url.host);
  1832. # endif
  1833. skip_certificate_check=_stream->skip_certificate_check;
  1834. # if (OPENSSL_VERSION_NUMBER>=0x10002000L||LIBRESSL_VERSION_NUMBER>=0x2070000fL)
  1835. /*As of version 1.0.2, OpenSSL can finally do hostname checks automatically.
  1836. Of course, they make it much more complicated than it needs to be.*/
  1837. if(!skip_certificate_check){
  1838. X509_VERIFY_PARAM *param;
  1839. struct addrinfo *addr;
  1840. char *host;
  1841. unsigned char *ip;
  1842. int ip_len;
  1843. param=SSL_get0_param(_ssl_conn);
  1844. OP_ASSERT(param!=NULL);
  1845. host=_stream->url.host;
  1846. ip=NULL;
  1847. ip_len=0;
  1848. /*Check to see if the host was specified as a simple IP address.*/
  1849. addr=op_inet_pton(host);
  1850. if(addr!=NULL){
  1851. switch(addr->ai_family){
  1852. case AF_INET:{
  1853. struct sockaddr_in *s;
  1854. s=(struct sockaddr_in *)addr->ai_addr;
  1855. OP_ASSERT(addr->ai_addrlen>=sizeof(*s));
  1856. ip=(unsigned char *)&s->sin_addr;
  1857. ip_len=sizeof(s->sin_addr);
  1858. host=NULL;
  1859. }break;
  1860. case AF_INET6:{
  1861. struct sockaddr_in6 *s;
  1862. s=(struct sockaddr_in6 *)addr->ai_addr;
  1863. OP_ASSERT(addr->ai_addrlen>=sizeof(*s));
  1864. ip=(unsigned char *)&s->sin6_addr;
  1865. ip_len=sizeof(s->sin6_addr);
  1866. host=NULL;
  1867. }break;
  1868. }
  1869. }
  1870. /*Always set both host and ip to prevent matching against an old one.
  1871. One of the two will always be NULL, clearing that parameter.*/
  1872. X509_VERIFY_PARAM_set1_host(param,host,0);
  1873. X509_VERIFY_PARAM_set1_ip(param,ip,ip_len);
  1874. if(addr!=NULL)freeaddrinfo(addr);
  1875. }
  1876. # endif
  1877. /*Resume a previous session if available.*/
  1878. if(_stream->ssl_session!=NULL){
  1879. SSL_set_session(_ssl_conn,_stream->ssl_session);
  1880. }
  1881. /*If we're proxying, establish the CONNECT tunnel.*/
  1882. if(_stream->proxy_connect.nbuf>0){
  1883. ret=op_http_conn_establish_tunnel(_stream,_conn,
  1884. _fd,_ssl_conn,ssl_bio);
  1885. if(OP_UNLIKELY(ret<0))return ret;
  1886. }
  1887. else{
  1888. /*Otherwise, just use this socket directly.*/
  1889. op_sock_set_tcp_nodelay(_fd,1);
  1890. SSL_set_bio(_ssl_conn,ssl_bio,ssl_bio);
  1891. SSL_set_connect_state(_ssl_conn);
  1892. }
  1893. ret=op_do_ssl_step(_ssl_conn,_fd,SSL_connect);
  1894. if(OP_UNLIKELY(ret<=0))return OP_FALSE;
  1895. ssl_session=_stream->ssl_session;
  1896. if(ssl_session==NULL
  1897. # if (OPENSSL_VERSION_NUMBER<0x10002000L&&LIBRESSL_VERSION_NUMBER<0x2070000fL)
  1898. ||!skip_certificate_check
  1899. # endif
  1900. ){
  1901. ret=op_do_ssl_step(_ssl_conn,_fd,SSL_do_handshake);
  1902. if(OP_UNLIKELY(ret<=0))return OP_FALSE;
  1903. # if (OPENSSL_VERSION_NUMBER<0x10002000L&&LIBRESSL_VERSION_NUMBER<0x2070000fL)
  1904. /*OpenSSL before version 1.0.2 does not do automatic hostname verification,
  1905. despite the fact that we just passed it the hostname above in the call
  1906. to SSL_set_tlsext_host_name().
  1907. Do it for them.*/
  1908. if(!skip_certificate_check&&!op_http_verify_hostname(_stream,_ssl_conn)){
  1909. return OP_FALSE;
  1910. }
  1911. # endif
  1912. if(ssl_session==NULL){
  1913. /*Save the session for later resumption.*/
  1914. _stream->ssl_session=SSL_get1_session(_ssl_conn);
  1915. }
  1916. }
  1917. _conn->ssl_conn=_ssl_conn;
  1918. _conn->fd=_fd;
  1919. _conn->nrequests_left=OP_PIPELINE_MAX_REQUESTS;
  1920. return 0;
  1921. }
  1922. /*Try to start a connection to the next address in the given list of a given
  1923. type.
  1924. _fd: The socket to connect with.
  1925. [inout] _addr: A pointer to the list of addresses.
  1926. This will be advanced to the first one that matches the given
  1927. address family (possibly the current one).
  1928. _ai_family: The address family to connect to.
  1929. Return: 1 If the connection was successful.
  1930. 0 If the connection is in progress.
  1931. OP_FALSE If the connection failed and there were no more addresses
  1932. left to try.
  1933. *_addr will be set to NULL in this case.*/
  1934. static int op_sock_connect_next(op_sock _fd,
  1935. struct addrinfo **_addr,int _ai_family){
  1936. struct addrinfo *addr;
  1937. int err;
  1938. for(addr=*_addr;;addr=addr->ai_next){
  1939. /*Move to the next address of the requested type.*/
  1940. for(;addr!=NULL&&addr->ai_family!=_ai_family;addr=addr->ai_next);
  1941. *_addr=addr;
  1942. /*No more: failure.*/
  1943. if(addr==NULL)return OP_FALSE;
  1944. if(connect(_fd,addr->ai_addr,addr->ai_addrlen)>=0)return 1;
  1945. err=op_errno();
  1946. /*Winsock will set WSAEWOULDBLOCK.*/
  1947. if(OP_LIKELY(err==EINPROGRESS||err==EWOULDBLOCK))return 0;
  1948. }
  1949. }
  1950. /*The number of address families to try connecting to simultaneously.*/
  1951. # define OP_NPROTOS (2)
  1952. static int op_http_connect_impl(OpusHTTPStream *_stream,OpusHTTPConn *_conn,
  1953. struct addrinfo *_addrs,op_time *_start_time){
  1954. struct addrinfo *addr;
  1955. struct addrinfo *addrs[OP_NPROTOS];
  1956. struct pollfd fds[OP_NPROTOS];
  1957. int ai_family;
  1958. int nprotos;
  1959. int ret;
  1960. int pi;
  1961. int pj;
  1962. for(pi=0;pi<OP_NPROTOS;pi++)addrs[pi]=NULL;
  1963. /*Try connecting via both IPv4 and IPv6 simultaneously, and keep the first
  1964. one that succeeds.
  1965. Start by finding the first address from each family.
  1966. We order the first connection attempts in the same order the address
  1967. families were returned in the DNS records in accordance with RFC 6555.*/
  1968. for(addr=_addrs,nprotos=0;addr!=NULL&&nprotos<OP_NPROTOS;addr=addr->ai_next){
  1969. if(addr->ai_family==AF_INET6||addr->ai_family==AF_INET){
  1970. OP_ASSERT(addr->ai_addrlen<=
  1971. OP_MAX(sizeof(struct sockaddr_in6),sizeof(struct sockaddr_in)));
  1972. /*If we've seen this address family before, skip this address for now.*/
  1973. for(pi=0;pi<nprotos;pi++)if(addrs[pi]->ai_family==addr->ai_family)break;
  1974. if(pi<nprotos)continue;
  1975. addrs[nprotos++]=addr;
  1976. }
  1977. }
  1978. /*Pop the connection off the free list and put it on the LRU list.*/
  1979. OP_ASSERT(_stream->free_head==_conn);
  1980. _stream->free_head=_conn->next;
  1981. _conn->next=_stream->lru_head;
  1982. _stream->lru_head=_conn;
  1983. op_time_get(_start_time);
  1984. *&_conn->read_time=*_start_time;
  1985. _conn->read_bytes=0;
  1986. _conn->read_rate=0;
  1987. /*Try to start a connection to each protocol.
  1988. RFC 6555 says it is RECOMMENDED that connection attempts be paced
  1989. 150...250 ms apart "to balance human factors against network load", but
  1990. that "stateful algorithms" (that's us) "are expected to be more
  1991. aggressive".
  1992. We are definitely more aggressive: we don't pace at all.*/
  1993. for(pi=0;pi<nprotos;pi++){
  1994. ai_family=addrs[pi]->ai_family;
  1995. fds[pi].fd=socket(ai_family,SOCK_STREAM,addrs[pi]->ai_protocol);
  1996. fds[pi].events=POLLOUT;
  1997. if(OP_LIKELY(fds[pi].fd!=OP_INVALID_SOCKET)){
  1998. if(OP_LIKELY(op_sock_set_nonblocking(fds[pi].fd,1)>=0)){
  1999. ret=op_sock_connect_next(fds[pi].fd,addrs+pi,ai_family);
  2000. if(OP_UNLIKELY(ret>0)){
  2001. /*It succeeded right away (technically possible), so stop.*/
  2002. nprotos=pi+1;
  2003. break;
  2004. }
  2005. /*Otherwise go on to the next protocol, and skip the clean-up below.*/
  2006. else if(ret==0)continue;
  2007. /*Tried all the addresses for this protocol.*/
  2008. }
  2009. /*Clean up the socket.*/
  2010. close(fds[pi].fd);
  2011. }
  2012. /*Remove this protocol from the list.*/
  2013. memmove(addrs+pi,addrs+pi+1,sizeof(*addrs)*(nprotos-pi-1));
  2014. nprotos--;
  2015. pi--;
  2016. }
  2017. /*Wait for one of the connections to finish.*/
  2018. while(pi>=nprotos&&nprotos>0&&poll(fds,nprotos,OP_POLL_TIMEOUT_MS)>0){
  2019. for(pi=0;pi<nprotos;pi++){
  2020. socklen_t errlen;
  2021. int err;
  2022. /*Still waiting...*/
  2023. if(!fds[pi].revents)continue;
  2024. errlen=sizeof(err);
  2025. /*Some platforms will return the pending error in &err and return 0.
  2026. Others will put it in errno and return -1.*/
  2027. ret=getsockopt(fds[pi].fd,SOL_SOCKET,SO_ERROR,&err,&errlen);
  2028. if(ret<0)err=op_errno();
  2029. /*Success!*/
  2030. if(err==0||err==EISCONN)break;
  2031. /*Move on to the next address for this protocol.*/
  2032. ai_family=addrs[pi]->ai_family;
  2033. addrs[pi]=addrs[pi]->ai_next;
  2034. ret=op_sock_connect_next(fds[pi].fd,addrs+pi,ai_family);
  2035. /*It succeeded right away, so stop.*/
  2036. if(ret>0)break;
  2037. /*Otherwise go on to the next protocol, and skip the clean-up below.*/
  2038. else if(ret==0)continue;
  2039. /*Tried all the addresses for this protocol.
  2040. Remove it from the list.*/
  2041. close(fds[pi].fd);
  2042. memmove(fds+pi,fds+pi+1,sizeof(*fds)*(nprotos-pi-1));
  2043. memmove(addrs+pi,addrs+pi+1,sizeof(*addrs)*(nprotos-pi-1));
  2044. nprotos--;
  2045. pi--;
  2046. }
  2047. }
  2048. /*Close all the other sockets.*/
  2049. for(pj=0;pj<nprotos;pj++)if(pi!=pj)close(fds[pj].fd);
  2050. /*If none of them succeeded, we're done.*/
  2051. if(pi>=nprotos)return OP_FALSE;
  2052. /*Save this address for future connection attempts.*/
  2053. if(addrs[pi]!=&_stream->addr_info){
  2054. memcpy(&_stream->addr_info,addrs[pi],sizeof(_stream->addr_info));
  2055. _stream->addr_info.ai_addr=&_stream->addr.s;
  2056. _stream->addr_info.ai_next=NULL;
  2057. memcpy(&_stream->addr,addrs[pi]->ai_addr,addrs[pi]->ai_addrlen);
  2058. }
  2059. if(OP_URL_IS_SSL(&_stream->url)){
  2060. SSL *ssl_conn;
  2061. /*Start the SSL connection.*/
  2062. OP_ASSERT(_stream->ssl_ctx!=NULL);
  2063. ssl_conn=SSL_new(_stream->ssl_ctx);
  2064. if(OP_LIKELY(ssl_conn!=NULL)){
  2065. ret=op_http_conn_start_tls(_stream,_conn,fds[pi].fd,ssl_conn);
  2066. if(OP_LIKELY(ret>=0))return ret;
  2067. SSL_free(ssl_conn);
  2068. }
  2069. close(fds[pi].fd);
  2070. _conn->fd=OP_INVALID_SOCKET;
  2071. return OP_FALSE;
  2072. }
  2073. /*Just a normal non-SSL connection.*/
  2074. _conn->ssl_conn=NULL;
  2075. _conn->fd=fds[pi].fd;
  2076. _conn->nrequests_left=OP_PIPELINE_MAX_REQUESTS;
  2077. /*Disable write coalescing.
  2078. We always send whole requests at once and always parse the response headers
  2079. before sending another one.*/
  2080. op_sock_set_tcp_nodelay(fds[pi].fd,1);
  2081. return 0;
  2082. }
  2083. static int op_http_connect(OpusHTTPStream *_stream,OpusHTTPConn *_conn,
  2084. struct addrinfo *_addrs,op_time *_start_time){
  2085. op_time resolve_time;
  2086. struct addrinfo *new_addrs;
  2087. int ret;
  2088. /*Re-resolve the host if we need to (RFC 6555 says we MUST do so
  2089. occasionally).*/
  2090. new_addrs=NULL;
  2091. op_time_get(&resolve_time);
  2092. if(_addrs!=&_stream->addr_info||op_time_diff_ms(&resolve_time,
  2093. &_stream->resolve_time)>=OP_RESOLVE_CACHE_TIMEOUT_MS){
  2094. new_addrs=op_resolve(_stream->connect_host,_stream->connect_port);
  2095. if(OP_LIKELY(new_addrs!=NULL)){
  2096. _addrs=new_addrs;
  2097. *&_stream->resolve_time=*&resolve_time;
  2098. }
  2099. else if(OP_LIKELY(_addrs==NULL))return OP_FALSE;
  2100. }
  2101. ret=op_http_connect_impl(_stream,_conn,_addrs,_start_time);
  2102. if(new_addrs!=NULL)freeaddrinfo(new_addrs);
  2103. return ret;
  2104. }
  2105. # define OP_BASE64_LENGTH(_len) (((_len)+2)/3*4)
  2106. static const char BASE64_TABLE[64]={
  2107. 'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P',
  2108. 'Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f',
  2109. 'g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v',
  2110. 'w','x','y','z','0','1','2','3','4','5','6','7','8','9','+','/'
  2111. };
  2112. static char *op_base64_encode(char *_dst,const char *_src,int _len){
  2113. unsigned s0;
  2114. unsigned s1;
  2115. unsigned s2;
  2116. int ngroups;
  2117. int i;
  2118. ngroups=_len/3;
  2119. for(i=0;i<ngroups;i++){
  2120. s0=_src[3*i+0];
  2121. s1=_src[3*i+1];
  2122. s2=_src[3*i+2];
  2123. _dst[4*i+0]=BASE64_TABLE[s0>>2];
  2124. _dst[4*i+1]=BASE64_TABLE[(s0&3)<<4|s1>>4];
  2125. _dst[4*i+2]=BASE64_TABLE[(s1&15)<<2|s2>>6];
  2126. _dst[4*i+3]=BASE64_TABLE[s2&63];
  2127. }
  2128. _len-=3*i;
  2129. if(_len==1){
  2130. s0=_src[3*i+0];
  2131. _dst[4*i+0]=BASE64_TABLE[s0>>2];
  2132. _dst[4*i+1]=BASE64_TABLE[(s0&3)<<4];
  2133. _dst[4*i+2]='=';
  2134. _dst[4*i+3]='=';
  2135. i++;
  2136. }
  2137. else if(_len==2){
  2138. s0=_src[3*i+0];
  2139. s1=_src[3*i+1];
  2140. _dst[4*i+0]=BASE64_TABLE[s0>>2];
  2141. _dst[4*i+1]=BASE64_TABLE[(s0&3)<<4|s1>>4];
  2142. _dst[4*i+2]=BASE64_TABLE[(s1&15)<<2];
  2143. _dst[4*i+3]='=';
  2144. i++;
  2145. }
  2146. _dst[4*i]='\0';
  2147. return _dst+4*i;
  2148. }
  2149. /*Construct an HTTP authorization header using RFC 2617's Basic Authentication
  2150. Scheme and append it to the given string buffer.*/
  2151. static int op_sb_append_basic_auth_header(OpusStringBuf *_sb,
  2152. const char *_header,const char *_user,const char *_pass){
  2153. size_t user_len;
  2154. size_t pass_len;
  2155. int user_pass_len;
  2156. int base64_len;
  2157. int nbuf_total;
  2158. int ret;
  2159. ret=op_sb_append_string(_sb,_header);
  2160. ret|=op_sb_append(_sb,": Basic ",8);
  2161. user_len=strlen(_user);
  2162. pass_len=strlen(_pass);
  2163. if(OP_UNLIKELY(user_len>(size_t)INT_MAX))return OP_EFAULT;
  2164. if(OP_UNLIKELY(pass_len>INT_MAX-user_len))return OP_EFAULT;
  2165. if(OP_UNLIKELY((int)(user_len+pass_len)>(INT_MAX>>2)*3-3))return OP_EFAULT;
  2166. user_pass_len=(int)(user_len+pass_len)+1;
  2167. base64_len=OP_BASE64_LENGTH(user_pass_len);
  2168. /*Stick "user:pass" at the end of the buffer so we can Base64 encode it
  2169. in-place.*/
  2170. nbuf_total=_sb->nbuf;
  2171. if(OP_UNLIKELY(base64_len>INT_MAX-nbuf_total))return OP_EFAULT;
  2172. nbuf_total+=base64_len;
  2173. ret|=op_sb_ensure_capacity(_sb,nbuf_total);
  2174. if(OP_UNLIKELY(ret<0))return ret;
  2175. _sb->nbuf=nbuf_total-user_pass_len;
  2176. OP_ALWAYS_TRUE(!op_sb_append(_sb,_user,(int)user_len));
  2177. OP_ALWAYS_TRUE(!op_sb_append(_sb,":",1));
  2178. OP_ALWAYS_TRUE(!op_sb_append(_sb,_pass,(int)pass_len));
  2179. op_base64_encode(_sb->buf+nbuf_total-base64_len,
  2180. _sb->buf+nbuf_total-user_pass_len,user_pass_len);
  2181. return op_sb_append(_sb,"\r\n",2);
  2182. }
  2183. static int op_http_allow_pipelining(const char *_server){
  2184. /*Servers known to do bad things with pipelined requests.
  2185. This list is taken from Gecko's nsHttpConnection::SupportsPipelining() (in
  2186. netwerk/protocol/http/nsHttpConnection.cpp).*/
  2187. static const char *BAD_SERVERS[]={
  2188. "EFAServer/",
  2189. "Microsoft-IIS/4.",
  2190. "Microsoft-IIS/5.",
  2191. "Netscape-Enterprise/3.",
  2192. "Netscape-Enterprise/4.",
  2193. "Netscape-Enterprise/5.",
  2194. "Netscape-Enterprise/6.",
  2195. "WebLogic 3.",
  2196. "WebLogic 4.",
  2197. "WebLogic 5.",
  2198. "WebLogic 6.",
  2199. "Winstone Servlet Engine v0."
  2200. };
  2201. # define NBAD_SERVERS ((int)(sizeof(BAD_SERVERS)/sizeof(*BAD_SERVERS)))
  2202. if(*_server>='E'&&*_server<='W'){
  2203. int si;
  2204. for(si=0;si<NBAD_SERVERS;si++){
  2205. if(strncmp(_server,BAD_SERVERS[si],strlen(BAD_SERVERS[si]))==0){
  2206. return 0;
  2207. }
  2208. }
  2209. }
  2210. return 1;
  2211. # undef NBAD_SERVERS
  2212. }
  2213. static int op_http_stream_open(OpusHTTPStream *_stream,const char *_url,
  2214. int _skip_certificate_check,const char *_proxy_host,unsigned _proxy_port,
  2215. const char *_proxy_user,const char *_proxy_pass,OpusServerInfo *_info){
  2216. struct addrinfo *addrs;
  2217. int nredirs;
  2218. int ret;
  2219. #if defined(_WIN32)
  2220. op_init_winsock();
  2221. #endif
  2222. ret=op_parse_url(&_stream->url,_url);
  2223. if(OP_UNLIKELY(ret<0))return ret;
  2224. if(_proxy_host!=NULL){
  2225. if(OP_UNLIKELY(_proxy_port>65535U))return OP_EINVAL;
  2226. _stream->connect_host=op_string_dup(_proxy_host);
  2227. _stream->connect_port=_proxy_port;
  2228. }
  2229. else{
  2230. _stream->connect_host=_stream->url.host;
  2231. _stream->connect_port=_stream->url.port;
  2232. }
  2233. addrs=NULL;
  2234. for(nredirs=0;nredirs<OP_REDIRECT_LIMIT;nredirs++){
  2235. OpusParsedURL next_url;
  2236. op_time start_time;
  2237. op_time end_time;
  2238. char *next;
  2239. char *status_code;
  2240. int minor_version_pos;
  2241. int v1_1_compat;
  2242. /*Initialize the SSL library if necessary.*/
  2243. if(OP_URL_IS_SSL(&_stream->url)&&_stream->ssl_ctx==NULL){
  2244. SSL_CTX *ssl_ctx;
  2245. # if (OPENSSL_VERSION_NUMBER<0x10100000L&&LIBRESSL_VERSION_NUMBER<0x2070000fL)
  2246. # if !defined(OPENSSL_NO_LOCKING)
  2247. /*The documentation says SSL_library_init() is not reentrant.
  2248. We don't want to add our own depenencies on a threading library, and it
  2249. appears that it's safe to call OpenSSL's locking functions before the
  2250. library is initialized, so that's what we'll do (really OpenSSL should
  2251. do this for us).
  2252. This doesn't guarantee that _other_ threads in the application aren't
  2253. calling SSL_library_init() at the same time, but there's not much we
  2254. can do about that.*/
  2255. CRYPTO_w_lock(CRYPTO_LOCK_SSL);
  2256. # endif
  2257. SSL_library_init();
  2258. /*Needed to get SHA2 algorithms with old OpenSSL versions.*/
  2259. OpenSSL_add_ssl_algorithms();
  2260. # if !defined(OPENSSL_NO_LOCKING)
  2261. CRYPTO_w_unlock(CRYPTO_LOCK_SSL);
  2262. # endif
  2263. # else
  2264. /*Finally, OpenSSL does this for us, but as penance, it can now fail.*/
  2265. if(!OPENSSL_init_ssl(0,NULL))return OP_EFAULT;
  2266. # endif
  2267. ssl_ctx=SSL_CTX_new(SSLv23_client_method());
  2268. if(ssl_ctx==NULL)return OP_EFAULT;
  2269. if(!_skip_certificate_check){
  2270. /*We don't do anything if this fails, since it just means we won't load
  2271. any certificates (and thus all checks will fail).
  2272. However, as that is probably the result of a system
  2273. mis-configuration, assert here to make it easier to identify.*/
  2274. OP_ALWAYS_TRUE(SSL_CTX_set_default_verify_paths(ssl_ctx));
  2275. SSL_CTX_set_verify(ssl_ctx,SSL_VERIFY_PEER,NULL);
  2276. }
  2277. _stream->ssl_ctx=ssl_ctx;
  2278. _stream->skip_certificate_check=_skip_certificate_check;
  2279. if(_proxy_host!=NULL){
  2280. /*We need to establish a CONNECT tunnel to handle https proxying.
  2281. Build the request we'll send to do so.*/
  2282. _stream->proxy_connect.nbuf=0;
  2283. ret=op_sb_append(&_stream->proxy_connect,"CONNECT ",8);
  2284. ret|=op_sb_append_string(&_stream->proxy_connect,_stream->url.host);
  2285. ret|=op_sb_append_port(&_stream->proxy_connect,_stream->url.port);
  2286. /*CONNECT requires at least HTTP 1.1.*/
  2287. ret|=op_sb_append(&_stream->proxy_connect," HTTP/1.1\r\n",11);
  2288. ret|=op_sb_append(&_stream->proxy_connect,"Host: ",6);
  2289. ret|=op_sb_append_string(&_stream->proxy_connect,_stream->url.host);
  2290. /*The example in RFC 2817 Section 5.2 specifies an explicit port even
  2291. when connecting to the default port.
  2292. Given that the proxy doesn't know whether we're trying to connect to
  2293. an http or an https URL except by the port number, this seems like a
  2294. good idea.*/
  2295. ret|=op_sb_append_port(&_stream->proxy_connect,_stream->url.port);
  2296. ret|=op_sb_append(&_stream->proxy_connect,"\r\n",2);
  2297. ret|=op_sb_append(&_stream->proxy_connect,"User-Agent: .\r\n",15);
  2298. if(_proxy_user!=NULL&&_proxy_pass!=NULL){
  2299. ret|=op_sb_append_basic_auth_header(&_stream->proxy_connect,
  2300. "Proxy-Authorization",_proxy_user,_proxy_pass);
  2301. }
  2302. /*For backwards compatibility.*/
  2303. ret|=op_sb_append(&_stream->proxy_connect,
  2304. "Proxy-Connection: keep-alive\r\n",30);
  2305. ret|=op_sb_append(&_stream->proxy_connect,"\r\n",2);
  2306. if(OP_UNLIKELY(ret<0))return ret;
  2307. }
  2308. }
  2309. /*Actually make the connection.*/
  2310. ret=op_http_connect(_stream,_stream->conns+0,addrs,&start_time);
  2311. if(OP_UNLIKELY(ret<0))return ret;
  2312. /*Build the request to send.*/
  2313. _stream->request.nbuf=0;
  2314. ret=op_sb_append(&_stream->request,"GET ",4);
  2315. ret|=op_sb_append_string(&_stream->request,
  2316. _proxy_host!=NULL?_url:_stream->url.path);
  2317. /*Send HTTP/1.0 by default for maximum compatibility (so we don't have to
  2318. re-try if HTTP/1.1 fails, though it shouldn't, even for a 1.0 server).
  2319. This means we aren't conditionally compliant with RFC 2145, because we
  2320. violate the requirement that "An HTTP client SHOULD send a request
  2321. version equal to the highest version for which the client is at least
  2322. conditionally compliant...".
  2323. According to RFC 2145, that means we can't claim any compliance with any
  2324. IETF HTTP specification.*/
  2325. ret|=op_sb_append(&_stream->request," HTTP/1.0\r\n",11);
  2326. /*Remember where this is so we can upgrade to HTTP/1.1 if the server
  2327. supports it.*/
  2328. minor_version_pos=_stream->request.nbuf-3;
  2329. ret|=op_sb_append(&_stream->request,"Host: ",6);
  2330. ret|=op_sb_append_string(&_stream->request,_stream->url.host);
  2331. if(!OP_URL_IS_DEFAULT_PORT(&_stream->url)){
  2332. ret|=op_sb_append_port(&_stream->request,_stream->url.port);
  2333. }
  2334. ret|=op_sb_append(&_stream->request,"\r\n",2);
  2335. /*User-Agents have been a bad idea, so send as little as possible.
  2336. RFC 2616 requires at least one token in the User-Agent, which must have
  2337. at least one character.*/
  2338. ret|=op_sb_append(&_stream->request,"User-Agent: .\r\n",15);
  2339. if(_proxy_host!=NULL&&!OP_URL_IS_SSL(&_stream->url)
  2340. &&_proxy_user!=NULL&&_proxy_pass!=NULL){
  2341. ret|=op_sb_append_basic_auth_header(&_stream->request,
  2342. "Proxy-Authorization",_proxy_user,_proxy_pass);
  2343. }
  2344. if(_stream->url.user!=NULL&&_stream->url.pass!=NULL){
  2345. ret|=op_sb_append_basic_auth_header(&_stream->request,
  2346. "Authorization",_stream->url.user,_stream->url.pass);
  2347. }
  2348. /*Always send a Referer [sic] header.
  2349. It's common to refuse to serve a resource unless one is present.
  2350. We just use the relative "/" URI to suggest we came from the same domain,
  2351. as this is the most common check.
  2352. This might violate RFC 2616's mandate that the field "MUST NOT be sent if
  2353. the Request-URI was obtained from a source that does not have its own
  2354. URI, such as input from the user keyboard," but we don't really have any
  2355. way to know.*/
  2356. /*TODO: Should we update this on redirects?*/
  2357. ret|=op_sb_append(&_stream->request,"Referer: /\r\n",12);
  2358. /*Always send a Range request header to find out if we're seekable.
  2359. This requires an HTTP/1.1 server to succeed, but we'll still get what we
  2360. want with an HTTP/1.0 server that ignores this request header.*/
  2361. ret|=op_sb_append(&_stream->request,"Range: bytes=0-\r\n",17);
  2362. /*Remember where this is so we can append offsets to it later.*/
  2363. _stream->request_tail=_stream->request.nbuf-4;
  2364. ret|=op_sb_append(&_stream->request,"\r\n",2);
  2365. if(OP_UNLIKELY(ret<0))return ret;
  2366. ret=op_http_conn_write_fully(_stream->conns+0,
  2367. _stream->request.buf,_stream->request.nbuf);
  2368. if(OP_UNLIKELY(ret<0))return ret;
  2369. ret=op_http_conn_read_response(_stream->conns+0,&_stream->response);
  2370. if(OP_UNLIKELY(ret<0))return ret;
  2371. op_time_get(&end_time);
  2372. next=op_http_parse_status_line(&v1_1_compat,&status_code,
  2373. _stream->response.buf);
  2374. if(OP_UNLIKELY(next==NULL))return OP_FALSE;
  2375. if(status_code[0]=='2'){
  2376. opus_int64 content_length;
  2377. opus_int64 range_length;
  2378. int pipeline_supported;
  2379. int pipeline_disabled;
  2380. /*We only understand 20x codes.*/
  2381. if(status_code[1]!='0')return OP_FALSE;
  2382. content_length=-1;
  2383. range_length=-1;
  2384. /*Pipelining must be explicitly enabled.*/
  2385. pipeline_supported=0;
  2386. pipeline_disabled=0;
  2387. for(;;){
  2388. char *header;
  2389. char *cdr;
  2390. ret=op_http_get_next_header(&header,&cdr,&next);
  2391. if(OP_UNLIKELY(ret<0))return ret;
  2392. if(header==NULL)break;
  2393. if(strcmp(header,"content-length")==0){
  2394. /*Two Content-Length headers?*/
  2395. if(OP_UNLIKELY(content_length>=0))return OP_FALSE;
  2396. content_length=op_http_parse_content_length(cdr);
  2397. if(OP_UNLIKELY(content_length<0))return (int)content_length;
  2398. /*Make sure the Content-Length and Content-Range headers match.*/
  2399. if(range_length>=0&&OP_UNLIKELY(content_length!=range_length)){
  2400. return OP_FALSE;
  2401. }
  2402. }
  2403. else if(strcmp(header,"content-range")==0){
  2404. opus_int64 range_first;
  2405. opus_int64 range_last;
  2406. /*Two Content-Range headers?*/
  2407. if(OP_UNLIKELY(range_length>=0))return OP_FALSE;
  2408. ret=op_http_parse_content_range(&range_first,&range_last,
  2409. &range_length,cdr);
  2410. if(OP_UNLIKELY(ret<0))return ret;
  2411. /*"A response with satus code 206 (Partial Content) MUST NOT
  2412. include a Content-Range field with a byte-range-resp-spec of
  2413. '*'."*/
  2414. if(status_code[2]=='6'
  2415. &&(OP_UNLIKELY(range_first<0)||OP_UNLIKELY(range_last<0))){
  2416. return OP_FALSE;
  2417. }
  2418. /*We asked for the entire resource.*/
  2419. if(range_length>=0){
  2420. /*Quit if we didn't get it.*/
  2421. if(range_last>=0&&OP_UNLIKELY(range_last!=range_length-1)){
  2422. return OP_FALSE;
  2423. }
  2424. }
  2425. /*If there was no length, use the end of the range.*/
  2426. else if(range_last>=0)range_length=range_last+1;
  2427. /*Make sure the Content-Length and Content-Range headers match.*/
  2428. if(content_length>=0&&OP_UNLIKELY(content_length!=range_length)){
  2429. return OP_FALSE;
  2430. }
  2431. }
  2432. else if(strcmp(header,"connection")==0){
  2433. /*According to RFC 2616, if an HTTP/1.1 application does not support
  2434. pipelining, it "MUST include the 'close' connection option in
  2435. every message."
  2436. Therefore, if we receive one in the initial response, disable
  2437. pipelining entirely.
  2438. The server still might support it (e.g., we might just have hit the
  2439. request limit for a temporary child process), but if it doesn't
  2440. and we assume it does, every time we cross a chunk boundary we'll
  2441. error out and reconnect, adding lots of latency.*/
  2442. ret=op_http_parse_connection(cdr);
  2443. if(OP_UNLIKELY(ret<0))return ret;
  2444. pipeline_disabled|=ret;
  2445. }
  2446. else if(strcmp(header,"server")==0){
  2447. /*If we got a Server response header, and it wasn't from a known-bad
  2448. server, enable pipelining, as long as it's at least HTTP/1.1.
  2449. According to RFC 2145, the server is supposed to respond with the
  2450. highest minor version number it supports unless it is known or
  2451. suspected that we incorrectly implement the HTTP specification.
  2452. So it should send back at least HTTP/1.1, despite our HTTP/1.0
  2453. request.*/
  2454. pipeline_supported=v1_1_compat;
  2455. if(v1_1_compat)pipeline_disabled|=!op_http_allow_pipelining(cdr);
  2456. if(_info!=NULL&&_info->server==NULL)_info->server=op_string_dup(cdr);
  2457. }
  2458. /*Collect station information headers if the caller requested it.
  2459. If there's more than one copy of a header, the first one wins.*/
  2460. else if(_info!=NULL){
  2461. if(strcmp(header,"content-type")==0){
  2462. if(_info->content_type==NULL){
  2463. _info->content_type=op_string_dup(cdr);
  2464. }
  2465. }
  2466. else if(header[0]=='i'&&header[1]=='c'
  2467. &&(header[2]=='e'||header[2]=='y')&&header[3]=='-'){
  2468. if(strcmp(header+4,"name")==0){
  2469. if(_info->name==NULL)_info->name=op_string_dup(cdr);
  2470. }
  2471. else if(strcmp(header+4,"description")==0){
  2472. if(_info->description==NULL)_info->description=op_string_dup(cdr);
  2473. }
  2474. else if(strcmp(header+4,"genre")==0){
  2475. if(_info->genre==NULL)_info->genre=op_string_dup(cdr);
  2476. }
  2477. else if(strcmp(header+4,"url")==0){
  2478. if(_info->url==NULL)_info->url=op_string_dup(cdr);
  2479. }
  2480. else if(strcmp(header,"icy-br")==0
  2481. ||strcmp(header,"ice-bitrate")==0){
  2482. if(_info->bitrate_kbps<0){
  2483. opus_int64 bitrate_kbps;
  2484. /*Just re-using this function to parse a random unsigned
  2485. integer field.*/
  2486. bitrate_kbps=op_http_parse_content_length(cdr);
  2487. if(bitrate_kbps>=0&&bitrate_kbps<=OP_INT32_MAX){
  2488. _info->bitrate_kbps=(opus_int32)bitrate_kbps;
  2489. }
  2490. }
  2491. }
  2492. else if(strcmp(header,"icy-pub")==0
  2493. ||strcmp(header,"ice-public")==0){
  2494. if(_info->is_public<0&&(cdr[0]=='0'||cdr[0]=='1')&&cdr[1]=='\0'){
  2495. _info->is_public=cdr[0]-'0';
  2496. }
  2497. }
  2498. }
  2499. }
  2500. }
  2501. switch(status_code[2]){
  2502. /*200 OK*/
  2503. case '0':break;
  2504. /*203 Non-Authoritative Information*/
  2505. case '3':break;
  2506. /*204 No Content*/
  2507. case '4':{
  2508. if(content_length>=0&&OP_UNLIKELY(content_length!=0)){
  2509. return OP_FALSE;
  2510. }
  2511. }break;
  2512. /*206 Partial Content*/
  2513. case '6':{
  2514. /*No Content-Range header.*/
  2515. if(OP_UNLIKELY(range_length<0))return OP_FALSE;
  2516. content_length=range_length;
  2517. /*The server supports range requests for this resource.
  2518. We can seek.*/
  2519. _stream->seekable=1;
  2520. }break;
  2521. /*201 Created: the response "SHOULD include an entity containing a list
  2522. of resource characteristics and location(s)," but not an Opus file.
  2523. 202 Accepted: the response "SHOULD include an indication of request's
  2524. current status and either a pointer to a status monitor or some
  2525. estimate of when the user can expect the request to be fulfilled,"
  2526. but not an Opus file.
  2527. 205 Reset Content: this "MUST NOT include an entity," meaning no Opus
  2528. file.
  2529. 207...209 are not yet defined, so we don't know how to handle them.*/
  2530. default:return OP_FALSE;
  2531. }
  2532. _stream->content_length=content_length;
  2533. _stream->pipeline=pipeline_supported&&!pipeline_disabled;
  2534. /*Pipelining requires HTTP/1.1 persistent connections.*/
  2535. if(_stream->pipeline)_stream->request.buf[minor_version_pos]='1';
  2536. _stream->conns[0].pos=0;
  2537. _stream->conns[0].end_pos=_stream->seekable?content_length:-1;
  2538. _stream->conns[0].chunk_size=-1;
  2539. _stream->cur_conni=0;
  2540. _stream->connect_rate=op_time_diff_ms(&end_time,&start_time);
  2541. _stream->connect_rate=OP_MAX(_stream->connect_rate,1);
  2542. if(_info!=NULL)_info->is_ssl=OP_URL_IS_SSL(&_stream->url);
  2543. /*The URL has been successfully opened.*/
  2544. return 0;
  2545. }
  2546. /*Shouldn't get 1xx; 4xx and 5xx are both failures (and we don't retry).
  2547. Everything else is undefined.*/
  2548. else if(status_code[0]!='3')return OP_FALSE;
  2549. /*We have some form of redirect request.*/
  2550. /*We only understand 30x codes.*/
  2551. if(status_code[1]!='0')return OP_FALSE;
  2552. switch(status_code[2]){
  2553. /*300 Multiple Choices: "If the server has a preferred choice of
  2554. representation, it SHOULD include the specific URI for that
  2555. representation in the Location field," otherwise we'll fail.*/
  2556. case '0':
  2557. /*301 Moved Permanently*/
  2558. case '1':
  2559. /*302 Found*/
  2560. case '2':
  2561. /*307 Temporary Redirect*/
  2562. case '7':
  2563. /*308 Permanent Redirect (defined by draft-reschke-http-status-308-07).*/
  2564. case '8':break;
  2565. /*305 Use Proxy: "The Location field gives the URI of the proxy."
  2566. TODO: This shouldn't actually be that hard to do.*/
  2567. case '5':return OP_EIMPL;
  2568. /*303 See Other: "The new URI is not a substitute reference for the
  2569. originally requested resource."
  2570. 304 Not Modified: "The 304 response MUST NOT contain a message-body."
  2571. 306 (Unused)
  2572. 309 is not yet defined, so we don't know how to handle it.*/
  2573. default:return OP_FALSE;
  2574. }
  2575. _url=NULL;
  2576. for(;;){
  2577. char *header;
  2578. char *cdr;
  2579. ret=op_http_get_next_header(&header,&cdr,&next);
  2580. if(OP_UNLIKELY(ret<0))return ret;
  2581. if(header==NULL)break;
  2582. if(strcmp(header,"location")==0&&OP_LIKELY(_url==NULL))_url=cdr;
  2583. }
  2584. if(OP_UNLIKELY(_url==NULL))return OP_FALSE;
  2585. ret=op_parse_url(&next_url,_url);
  2586. if(OP_UNLIKELY(ret<0))return ret;
  2587. if(_proxy_host==NULL||_stream->ssl_session!=NULL){
  2588. if(strcmp(_stream->url.host,next_url.host)==0
  2589. &&_stream->url.port==next_url.port){
  2590. /*Try to skip re-resolve when connecting to the same host.*/
  2591. addrs=&_stream->addr_info;
  2592. }
  2593. else{
  2594. if(_stream->ssl_session!=NULL){
  2595. /*Forget any cached SSL session from the last host.*/
  2596. SSL_SESSION_free(_stream->ssl_session);
  2597. _stream->ssl_session=NULL;
  2598. }
  2599. }
  2600. }
  2601. if(_proxy_host==NULL){
  2602. OP_ASSERT(_stream->connect_host==_stream->url.host);
  2603. _stream->connect_host=next_url.host;
  2604. _stream->connect_port=next_url.port;
  2605. }
  2606. /*Always try to skip re-resolve for proxy connections.*/
  2607. else addrs=&_stream->addr_info;
  2608. op_parsed_url_clear(&_stream->url);
  2609. *&_stream->url=*&next_url;
  2610. /*TODO: On servers/proxies that support pipelining, we might be able to
  2611. re-use this connection.*/
  2612. op_http_conn_close(_stream,_stream->conns+0,&_stream->lru_head,1);
  2613. }
  2614. /*Redirection limit reached.*/
  2615. return OP_FALSE;
  2616. }
  2617. static int op_http_conn_send_request(OpusHTTPStream *_stream,
  2618. OpusHTTPConn *_conn,opus_int64 _pos,opus_int32 _chunk_size,
  2619. int _try_not_to_block){
  2620. opus_int64 next_end;
  2621. int ret;
  2622. /*We shouldn't have another request outstanding.*/
  2623. OP_ASSERT(_conn->next_pos<0);
  2624. /*Build the request to send.*/
  2625. OP_ASSERT(_stream->request.nbuf>=_stream->request_tail);
  2626. _stream->request.nbuf=_stream->request_tail;
  2627. ret=op_sb_append_nonnegative_int64(&_stream->request,_pos);
  2628. ret|=op_sb_append(&_stream->request,"-",1);
  2629. if(_chunk_size>0&&OP_ADV_OFFSET(_pos,2*_chunk_size)<_stream->content_length){
  2630. /*We shouldn't be pipelining requests with non-HTTP/1.1 servers.*/
  2631. OP_ASSERT(_stream->pipeline);
  2632. next_end=_pos+_chunk_size;
  2633. ret|=op_sb_append_nonnegative_int64(&_stream->request,next_end-1);
  2634. /*Use a larger chunk size for our next request.*/
  2635. _chunk_size<<=1;
  2636. /*But after a while, just request the rest of the resource.*/
  2637. if(_chunk_size>OP_PIPELINE_CHUNK_SIZE_MAX)_chunk_size=-1;
  2638. }
  2639. else{
  2640. /*Either this was a non-pipelined request or we were close enough to the
  2641. end to just ask for the rest.*/
  2642. next_end=-1;
  2643. _chunk_size=-1;
  2644. }
  2645. ret|=op_sb_append(&_stream->request,"\r\n\r\n",4);
  2646. if(OP_UNLIKELY(ret<0))return ret;
  2647. /*If we don't want to block, check to see if there's enough space in the send
  2648. queue.
  2649. There's still a chance we might block, even if there is enough space, but
  2650. it's a much slimmer one.
  2651. Blocking at all is pretty unlikely, as we won't have any requests queued
  2652. when _try_not_to_block is set, so if FIONSPACE isn't available (e.g., on
  2653. Linux), just skip the test.*/
  2654. if(_try_not_to_block){
  2655. # if defined(FIONSPACE)
  2656. int available;
  2657. ret=ioctl(_conn->fd,FIONSPACE,&available);
  2658. if(ret<0||available<_stream->request.nbuf)return 1;
  2659. # endif
  2660. }
  2661. ret=op_http_conn_write_fully(_conn,
  2662. _stream->request.buf,_stream->request.nbuf);
  2663. if(OP_UNLIKELY(ret<0))return ret;
  2664. _conn->next_pos=_pos;
  2665. _conn->next_end=next_end;
  2666. /*Save the chunk size to use for the next request.*/
  2667. _conn->chunk_size=_chunk_size;
  2668. _conn->nrequests_left--;
  2669. return ret;
  2670. }
  2671. /*Handles the response to all requests after the first one.
  2672. Return: 1 if the connection was closed or timed out, 0 on success, or a
  2673. negative value on any other error.*/
  2674. static int op_http_conn_handle_response(OpusHTTPStream *_stream,
  2675. OpusHTTPConn *_conn){
  2676. char *next;
  2677. char *status_code;
  2678. opus_int64 range_length;
  2679. opus_int64 next_pos;
  2680. opus_int64 next_end;
  2681. int ret;
  2682. ret=op_http_conn_read_response(_conn,&_stream->response);
  2683. /*If the server just closed the connection on us, we may have just hit a
  2684. connection re-use limit, so we might want to retry.*/
  2685. if(OP_UNLIKELY(ret<0))return ret==OP_EREAD?1:ret;
  2686. next=op_http_parse_status_line(NULL,&status_code,_stream->response.buf);
  2687. if(OP_UNLIKELY(next==NULL))return OP_FALSE;
  2688. /*We _need_ a 206 Partial Content response.
  2689. Nothing else will do.*/
  2690. if(strncmp(status_code,"206",3)!=0){
  2691. /*But on a 408 Request Timeout, we might want to re-try.*/
  2692. return strncmp(status_code,"408",3)==0?1:OP_FALSE;
  2693. }
  2694. next_pos=_conn->next_pos;
  2695. next_end=_conn->next_end;
  2696. range_length=-1;
  2697. for(;;){
  2698. char *header;
  2699. char *cdr;
  2700. ret=op_http_get_next_header(&header,&cdr,&next);
  2701. if(OP_UNLIKELY(ret<0))return ret;
  2702. if(header==NULL)break;
  2703. if(strcmp(header,"content-range")==0){
  2704. opus_int64 range_first;
  2705. opus_int64 range_last;
  2706. /*Two Content-Range headers?*/
  2707. if(OP_UNLIKELY(range_length>=0))return OP_FALSE;
  2708. ret=op_http_parse_content_range(&range_first,&range_last,
  2709. &range_length,cdr);
  2710. if(OP_UNLIKELY(ret<0))return ret;
  2711. /*"A response with satus code 206 (Partial Content) MUST NOT
  2712. include a Content-Range field with a byte-range-resp-spec of
  2713. '*'."*/
  2714. if(OP_UNLIKELY(range_first<0)||OP_UNLIKELY(range_last<0))return OP_FALSE;
  2715. /*We also don't want range_last to overflow.*/
  2716. if(OP_UNLIKELY(range_last>=OP_INT64_MAX))return OP_FALSE;
  2717. range_last++;
  2718. /*Quit if we didn't get the offset we asked for.*/
  2719. if(range_first!=next_pos)return OP_FALSE;
  2720. if(next_end<0){
  2721. /*We asked for the rest of the resource.*/
  2722. if(range_length>=0){
  2723. /*Quit if we didn't get it.*/
  2724. if(OP_UNLIKELY(range_last!=range_length))return OP_FALSE;
  2725. }
  2726. /*If there was no length, use the end of the range.*/
  2727. else range_length=range_last;
  2728. next_end=range_last;
  2729. }
  2730. else{
  2731. if(range_last!=next_end)return OP_FALSE;
  2732. /*If there was no length, use the larger of the content length or the
  2733. end of this chunk.*/
  2734. if(range_length<0){
  2735. range_length=OP_MAX(range_last,_stream->content_length);
  2736. }
  2737. }
  2738. }
  2739. else if(strcmp(header,"content-length")==0){
  2740. opus_int64 content_length;
  2741. /*Validate the Content-Length header, if present, against the request we
  2742. made.*/
  2743. content_length=op_http_parse_content_length(cdr);
  2744. if(OP_UNLIKELY(content_length<0))return (int)content_length;
  2745. if(next_end<0){
  2746. /*If we haven't seen the Content-Range header yet and we asked for the
  2747. rest of the resource, set next_end, so we can make sure they match
  2748. when we do find the Content-Range header.*/
  2749. if(OP_UNLIKELY(next_pos>OP_INT64_MAX-content_length))return OP_FALSE;
  2750. next_end=next_pos+content_length;
  2751. }
  2752. /*Otherwise, make sure they match now.*/
  2753. else if(OP_UNLIKELY(next_end-next_pos!=content_length))return OP_FALSE;
  2754. }
  2755. else if(strcmp(header,"connection")==0){
  2756. ret=op_http_parse_connection(cdr);
  2757. if(OP_UNLIKELY(ret<0))return ret;
  2758. /*If the server told us it was going to close the connection, don't make
  2759. any more requests.*/
  2760. if(OP_UNLIKELY(ret>0))_conn->nrequests_left=0;
  2761. }
  2762. }
  2763. /*No Content-Range header.*/
  2764. if(OP_UNLIKELY(range_length<0))return OP_FALSE;
  2765. /*Update the content_length if necessary.*/
  2766. _stream->content_length=range_length;
  2767. _conn->pos=next_pos;
  2768. _conn->end_pos=next_end;
  2769. _conn->next_pos=-1;
  2770. return 0;
  2771. }
  2772. /*Open a new connection that will start reading at byte offset _pos.
  2773. _pos: The byte offset to start reading from.
  2774. _chunk_size: The number of bytes to ask for in the initial request, or -1 to
  2775. request the rest of the resource.
  2776. This may be more bytes than remain, in which case it will be
  2777. converted into a request for the rest.*/
  2778. static int op_http_conn_open_pos(OpusHTTPStream *_stream,
  2779. OpusHTTPConn *_conn,opus_int64 _pos,opus_int32 _chunk_size){
  2780. op_time start_time;
  2781. op_time end_time;
  2782. opus_int32 connect_rate;
  2783. opus_int32 connect_time;
  2784. int ret;
  2785. ret=op_http_connect(_stream,_conn,&_stream->addr_info,&start_time);
  2786. if(OP_UNLIKELY(ret<0))return ret;
  2787. ret=op_http_conn_send_request(_stream,_conn,_pos,_chunk_size,0);
  2788. if(OP_UNLIKELY(ret<0))return ret;
  2789. ret=op_http_conn_handle_response(_stream,_conn);
  2790. if(OP_UNLIKELY(ret!=0))return OP_FALSE;
  2791. op_time_get(&end_time);
  2792. _stream->cur_conni=(int)(_conn-_stream->conns);
  2793. OP_ASSERT(_stream->cur_conni>=0&&_stream->cur_conni<OP_NCONNS_MAX);
  2794. /*The connection has been successfully opened.
  2795. Update the connection time estimate.*/
  2796. connect_time=op_time_diff_ms(&end_time,&start_time);
  2797. connect_rate=_stream->connect_rate;
  2798. connect_rate+=OP_MAX(connect_time,1)-connect_rate+8>>4;
  2799. _stream->connect_rate=connect_rate;
  2800. return 0;
  2801. }
  2802. /*Read data from the current response body.
  2803. If we're pipelining and we get close to the end of this response, queue
  2804. another request.
  2805. If we've reached the end of this response body, parse the next response and
  2806. keep going.
  2807. [out] _buf: Returns the data read.
  2808. _buf_size: The size of the buffer.
  2809. Return: A positive number of bytes read on success.
  2810. 0: The connection was closed.
  2811. OP_EREAD: There was a fatal read error.*/
  2812. static int op_http_conn_read_body(OpusHTTPStream *_stream,
  2813. OpusHTTPConn *_conn,unsigned char *_buf,int _buf_size){
  2814. opus_int64 pos;
  2815. opus_int64 end_pos;
  2816. opus_int64 next_pos;
  2817. opus_int64 content_length;
  2818. int nread;
  2819. int pipeline;
  2820. int ret;
  2821. /*Currently this function can only be called on the LRU head.
  2822. Otherwise, we'd need a _pnext pointer if we needed to close the connection,
  2823. and re-opening it would re-organize the lists.*/
  2824. OP_ASSERT(_stream->lru_head==_conn);
  2825. /*We should have filtered out empty reads by this point.*/
  2826. OP_ASSERT(_buf_size>0);
  2827. pos=_conn->pos;
  2828. end_pos=_conn->end_pos;
  2829. next_pos=_conn->next_pos;
  2830. pipeline=_stream->pipeline;
  2831. content_length=_stream->content_length;
  2832. if(end_pos>=0){
  2833. /*Have we reached the end of the current response body?*/
  2834. if(pos>=end_pos){
  2835. OP_ASSERT(content_length>=0);
  2836. /*If this was the end of the stream, we're done.
  2837. Also return early if a non-blocking read was requested (regardless of
  2838. whether we might be able to parse the next response without
  2839. blocking).*/
  2840. if(content_length<=end_pos)return 0;
  2841. /*Otherwise, start on the next response.*/
  2842. if(next_pos<0){
  2843. /*We haven't issued another request yet.*/
  2844. if(!pipeline||_conn->nrequests_left<=0){
  2845. /*There are two ways to get here: either the server told us it was
  2846. going to close the connection after the last request, or we
  2847. thought we were reading the whole resource, but it grew while we
  2848. were reading it.
  2849. The only way the latter could have happened is if content_length
  2850. changed while seeking.
  2851. Open a new request to read the rest.*/
  2852. OP_ASSERT(_stream->seekable);
  2853. /*Try to open a new connection to read another chunk.*/
  2854. op_http_conn_close(_stream,_conn,&_stream->lru_head,1);
  2855. /*If we're not pipelining, we should be requesting the rest.*/
  2856. OP_ASSERT(pipeline||_conn->chunk_size==-1);
  2857. ret=op_http_conn_open_pos(_stream,_conn,end_pos,_conn->chunk_size);
  2858. if(OP_UNLIKELY(ret<0))return OP_EREAD;
  2859. }
  2860. else{
  2861. /*Issue the request now (better late than never).*/
  2862. ret=op_http_conn_send_request(_stream,_conn,pos,_conn->chunk_size,0);
  2863. if(OP_UNLIKELY(ret<0))return OP_EREAD;
  2864. next_pos=_conn->next_pos;
  2865. OP_ASSERT(next_pos>=0);
  2866. }
  2867. }
  2868. if(next_pos>=0){
  2869. /*We shouldn't be trying to read past the current request body if we're
  2870. seeking somewhere else.*/
  2871. OP_ASSERT(next_pos==end_pos);
  2872. ret=op_http_conn_handle_response(_stream,_conn);
  2873. if(OP_UNLIKELY(ret<0))return OP_EREAD;
  2874. if(OP_UNLIKELY(ret>0)&&pipeline){
  2875. opus_int64 next_end;
  2876. next_end=_conn->next_end;
  2877. /*Our request timed out or the server closed the connection.
  2878. Try re-connecting.*/
  2879. op_http_conn_close(_stream,_conn,&_stream->lru_head,1);
  2880. /*Unless there's a bug, we should be able to convert
  2881. (next_pos,next_end) into valid (_pos,_chunk_size) parameters.*/
  2882. OP_ASSERT(next_end<0
  2883. ||next_end-next_pos>=0&&next_end-next_pos<=OP_INT32_MAX);
  2884. ret=op_http_conn_open_pos(_stream,_conn,next_pos,
  2885. next_end<0?-1:(opus_int32)(next_end-next_pos));
  2886. if(OP_UNLIKELY(ret<0))return OP_EREAD;
  2887. }
  2888. else if(OP_UNLIKELY(ret!=0))return OP_EREAD;
  2889. }
  2890. pos=_conn->pos;
  2891. end_pos=_conn->end_pos;
  2892. content_length=_stream->content_length;
  2893. }
  2894. OP_ASSERT(end_pos>pos);
  2895. _buf_size=(int)OP_MIN(_buf_size,end_pos-pos);
  2896. }
  2897. nread=op_http_conn_read(_conn,(char *)_buf,_buf_size,1);
  2898. if(OP_UNLIKELY(nread<0))return nread;
  2899. pos+=nread;
  2900. _conn->pos=pos;
  2901. OP_ASSERT(end_pos<0||content_length>=0);
  2902. /*TODO: If nrequests_left<=0, we can't make a new request, and there will be
  2903. a big pause after we hit the end of the chunk while we open a new
  2904. connection.
  2905. It would be nice to be able to start that process now, but we have no way
  2906. to do it in the background without blocking (even if we could start it, we
  2907. have no guarantee the application will return control to us in a
  2908. sufficiently timely manner to allow us to complete it, and this is
  2909. uncommon enough that it's not worth using threads just for this).*/
  2910. if(end_pos>=0&&end_pos<content_length&&next_pos<0
  2911. &&pipeline&&OP_LIKELY(_conn->nrequests_left>0)){
  2912. opus_int64 request_thresh;
  2913. opus_int32 chunk_size;
  2914. /*Are we getting close to the end of the current response body?
  2915. If so, we should request more data.*/
  2916. request_thresh=_stream->connect_rate*_conn->read_rate>>12;
  2917. /*But don't commit ourselves too quickly.*/
  2918. chunk_size=_conn->chunk_size;
  2919. if(chunk_size>=0)request_thresh=OP_MIN(chunk_size>>2,request_thresh);
  2920. if(end_pos-pos<request_thresh){
  2921. ret=op_http_conn_send_request(_stream,_conn,end_pos,_conn->chunk_size,1);
  2922. if(OP_UNLIKELY(ret<0))return OP_EREAD;
  2923. }
  2924. }
  2925. return nread;
  2926. }
  2927. static int op_http_stream_read(void *_stream,
  2928. unsigned char *_ptr,int _buf_size){
  2929. OpusHTTPStream *stream;
  2930. int nread;
  2931. opus_int64 size;
  2932. opus_int64 pos;
  2933. int ci;
  2934. stream=(OpusHTTPStream *)_stream;
  2935. /*Check for an empty read.*/
  2936. if(_buf_size<=0)return 0;
  2937. ci=stream->cur_conni;
  2938. /*No current connection => EOF.*/
  2939. if(ci<0)return 0;
  2940. pos=stream->conns[ci].pos;
  2941. size=stream->content_length;
  2942. /*Check for EOF.*/
  2943. if(size>=0){
  2944. if(pos>=size)return 0;
  2945. /*Check for a short read.*/
  2946. if(_buf_size>size-pos)_buf_size=(int)(size-pos);
  2947. }
  2948. nread=op_http_conn_read_body(stream,stream->conns+ci,_ptr,_buf_size);
  2949. if(OP_UNLIKELY(nread<=0)){
  2950. /*We hit an error or EOF.
  2951. Either way, we're done with this connection.*/
  2952. op_http_conn_close(stream,stream->conns+ci,&stream->lru_head,1);
  2953. stream->cur_conni=-1;
  2954. stream->pos=pos;
  2955. }
  2956. return nread;
  2957. }
  2958. /*Discard data until we reach the _target position.
  2959. This destroys the contents of _stream->response.buf, as we need somewhere to
  2960. read this data, and that is a convenient place.
  2961. _just_read_ahead: Whether or not this is a plain fast-forward.
  2962. If 0, we need to issue a new request for a chunk at _target
  2963. and discard all the data from our current request(s).
  2964. Otherwise, we should be able to reach _target without
  2965. issuing any new requests.
  2966. _target: The stream position to which to read ahead.*/
  2967. static int op_http_conn_read_ahead(OpusHTTPStream *_stream,
  2968. OpusHTTPConn *_conn,int _just_read_ahead,opus_int64 _target){
  2969. opus_int64 pos;
  2970. opus_int64 end_pos;
  2971. opus_int64 next_pos;
  2972. opus_int64 next_end;
  2973. ptrdiff_t nread;
  2974. int ret;
  2975. pos=_conn->pos;
  2976. end_pos=_conn->end_pos;
  2977. next_pos=_conn->next_pos;
  2978. next_end=_conn->next_end;
  2979. if(!_just_read_ahead){
  2980. /*We need to issue a new pipelined request.
  2981. This is the only case where we allow more than one outstanding request
  2982. at a time, so we need to reset next_pos (we'll restore it below if we
  2983. did have an outstanding request).*/
  2984. OP_ASSERT(_stream->pipeline);
  2985. _conn->next_pos=-1;
  2986. ret=op_http_conn_send_request(_stream,_conn,_target,
  2987. OP_PIPELINE_CHUNK_SIZE,0);
  2988. if(OP_UNLIKELY(ret<0))return ret;
  2989. }
  2990. /*We can reach the target position by reading forward in the current chunk.*/
  2991. if(_just_read_ahead&&(end_pos<0||_target<end_pos))end_pos=_target;
  2992. else if(next_pos>=0){
  2993. opus_int64 next_next_pos;
  2994. opus_int64 next_next_end;
  2995. /*We already have a request outstanding.
  2996. Finish off the current chunk.*/
  2997. while(pos<end_pos){
  2998. nread=op_http_conn_read(_conn,_stream->response.buf,
  2999. (int)OP_MIN(end_pos-pos,_stream->response.cbuf),1);
  3000. /*We failed to read ahead.*/
  3001. if(nread<=0)return OP_FALSE;
  3002. pos+=nread;
  3003. }
  3004. OP_ASSERT(pos==end_pos);
  3005. if(_just_read_ahead){
  3006. next_next_pos=next_next_end=-1;
  3007. end_pos=_target;
  3008. }
  3009. else{
  3010. OP_ASSERT(_conn->next_pos==_target);
  3011. next_next_pos=_target;
  3012. next_next_end=_conn->next_end;
  3013. _conn->next_pos=next_pos;
  3014. _conn->next_end=next_end;
  3015. end_pos=next_end;
  3016. }
  3017. ret=op_http_conn_handle_response(_stream,_conn);
  3018. if(OP_UNLIKELY(ret!=0))return OP_FALSE;
  3019. _conn->next_pos=next_next_pos;
  3020. _conn->next_end=next_next_end;
  3021. }
  3022. while(pos<end_pos){
  3023. nread=op_http_conn_read(_conn,_stream->response.buf,
  3024. (int)OP_MIN(end_pos-pos,_stream->response.cbuf),1);
  3025. /*We failed to read ahead.*/
  3026. if(nread<=0)return OP_FALSE;
  3027. pos+=nread;
  3028. }
  3029. OP_ASSERT(pos==end_pos);
  3030. if(!_just_read_ahead){
  3031. ret=op_http_conn_handle_response(_stream,_conn);
  3032. if(OP_UNLIKELY(ret!=0))return OP_FALSE;
  3033. }
  3034. else _conn->pos=end_pos;
  3035. OP_ASSERT(_conn->pos==_target);
  3036. return 0;
  3037. }
  3038. static int op_http_stream_seek(void *_stream,opus_int64 _offset,int _whence){
  3039. op_time seek_time;
  3040. OpusHTTPStream *stream;
  3041. OpusHTTPConn *conn;
  3042. OpusHTTPConn **pnext;
  3043. OpusHTTPConn *close_conn;
  3044. OpusHTTPConn **close_pnext;
  3045. opus_int64 content_length;
  3046. opus_int64 pos;
  3047. int pipeline;
  3048. int ci;
  3049. int ret;
  3050. stream=(OpusHTTPStream *)_stream;
  3051. if(!stream->seekable)return -1;
  3052. content_length=stream->content_length;
  3053. /*If we're seekable, we should have gotten a Content-Length.*/
  3054. OP_ASSERT(content_length>=0);
  3055. ci=stream->cur_conni;
  3056. pos=ci<0?content_length:stream->conns[ci].pos;
  3057. switch(_whence){
  3058. case SEEK_SET:{
  3059. /*Check for overflow:*/
  3060. if(_offset<0)return -1;
  3061. pos=_offset;
  3062. }break;
  3063. case SEEK_CUR:{
  3064. /*Check for overflow:*/
  3065. if(_offset<-pos||_offset>OP_INT64_MAX-pos)return -1;
  3066. pos+=_offset;
  3067. }break;
  3068. case SEEK_END:{
  3069. /*Check for overflow:*/
  3070. if(_offset<-content_length||_offset>OP_INT64_MAX-content_length){
  3071. return -1;
  3072. }
  3073. pos=content_length+_offset;
  3074. }break;
  3075. default:return -1;
  3076. }
  3077. /*Mark when we deactivated the active connection.*/
  3078. if(ci>=0){
  3079. op_http_conn_read_rate_update(stream->conns+ci);
  3080. *&seek_time=*&stream->conns[ci].read_time;
  3081. }
  3082. else op_time_get(&seek_time);
  3083. /*If we seeked past the end of the stream, just disable the active
  3084. connection.*/
  3085. if(pos>=content_length){
  3086. stream->cur_conni=-1;
  3087. stream->pos=pos;
  3088. return 0;
  3089. }
  3090. /*First try to find a connection we can use without waiting.*/
  3091. pnext=&stream->lru_head;
  3092. conn=stream->lru_head;
  3093. while(conn!=NULL){
  3094. opus_int64 conn_pos;
  3095. opus_int64 end_pos;
  3096. int available;
  3097. /*If this connection has been dormant too long or has made too many
  3098. requests, close it.
  3099. This is to prevent us from hitting server limits/firewall timeouts.*/
  3100. if(op_time_diff_ms(&seek_time,&conn->read_time)>
  3101. OP_CONNECTION_IDLE_TIMEOUT_MS
  3102. ||conn->nrequests_left<OP_PIPELINE_MIN_REQUESTS){
  3103. op_http_conn_close(stream,conn,pnext,1);
  3104. conn=*pnext;
  3105. continue;
  3106. }
  3107. available=op_http_conn_estimate_available(conn);
  3108. conn_pos=conn->pos;
  3109. end_pos=conn->end_pos;
  3110. if(conn->next_pos>=0){
  3111. OP_ASSERT(end_pos>=0);
  3112. OP_ASSERT(conn->next_pos==end_pos);
  3113. end_pos=conn->next_end;
  3114. }
  3115. OP_ASSERT(end_pos<0||conn_pos<=end_pos);
  3116. /*Can we quickly read ahead without issuing a new request or waiting for
  3117. any more data?
  3118. If we have an oustanding request, we'll over-estimate the amount of data
  3119. it has available (because we'll count the response headers, too), but
  3120. that probably doesn't matter.*/
  3121. if(conn_pos<=pos&&pos-conn_pos<=available&&(end_pos<0||pos<end_pos)){
  3122. /*Found a suitable connection to re-use.*/
  3123. ret=op_http_conn_read_ahead(stream,conn,1,pos);
  3124. if(OP_UNLIKELY(ret<0)){
  3125. /*The connection might have become stale, so close it and keep going.*/
  3126. op_http_conn_close(stream,conn,pnext,1);
  3127. conn=*pnext;
  3128. continue;
  3129. }
  3130. /*Sucessfully resurrected this connection.*/
  3131. *pnext=conn->next;
  3132. conn->next=stream->lru_head;
  3133. stream->lru_head=conn;
  3134. stream->cur_conni=(int)(conn-stream->conns);
  3135. OP_ASSERT(stream->cur_conni>=0&&stream->cur_conni<OP_NCONNS_MAX);
  3136. return 0;
  3137. }
  3138. pnext=&conn->next;
  3139. conn=conn->next;
  3140. }
  3141. /*Chances are that didn't work, so now try to find one we can use by reading
  3142. ahead a reasonable amount and/or by issuing a new request.*/
  3143. close_pnext=NULL;
  3144. close_conn=NULL;
  3145. pnext=&stream->lru_head;
  3146. conn=stream->lru_head;
  3147. pipeline=stream->pipeline;
  3148. while(conn!=NULL){
  3149. opus_int64 conn_pos;
  3150. opus_int64 end_pos;
  3151. opus_int64 read_ahead_thresh;
  3152. int available;
  3153. int just_read_ahead;
  3154. /*Dividing by 2048 instead of 1000 scales this by nearly 1/2, biasing away
  3155. from connection re-use (and roughly compensating for the lag required to
  3156. reopen the TCP window of a connection that's been idle).
  3157. There's no overflow checking here, because it's vanishingly unlikely, and
  3158. all it would do is cause us to make poor decisions.*/
  3159. read_ahead_thresh=OP_MAX(OP_READAHEAD_THRESH_MIN,
  3160. stream->connect_rate*conn->read_rate>>11);
  3161. available=op_http_conn_estimate_available(conn);
  3162. conn_pos=conn->pos;
  3163. end_pos=conn->end_pos;
  3164. if(conn->next_pos>=0){
  3165. OP_ASSERT(end_pos>=0);
  3166. OP_ASSERT(conn->next_pos==end_pos);
  3167. end_pos=conn->next_end;
  3168. }
  3169. OP_ASSERT(end_pos<0||conn_pos<=end_pos);
  3170. /*Can we quickly read ahead without issuing a new request?*/
  3171. just_read_ahead=conn_pos<=pos&&pos-conn_pos-available<=read_ahead_thresh
  3172. &&(end_pos<0||pos<end_pos);
  3173. if(just_read_ahead||pipeline&&end_pos>=0
  3174. &&end_pos-conn_pos-available<=read_ahead_thresh){
  3175. /*Found a suitable connection to re-use.*/
  3176. ret=op_http_conn_read_ahead(stream,conn,just_read_ahead,pos);
  3177. if(OP_UNLIKELY(ret<0)){
  3178. /*The connection might have become stale, so close it and keep going.*/
  3179. op_http_conn_close(stream,conn,pnext,1);
  3180. conn=*pnext;
  3181. continue;
  3182. }
  3183. /*Sucessfully resurrected this connection.*/
  3184. *pnext=conn->next;
  3185. conn->next=stream->lru_head;
  3186. stream->lru_head=conn;
  3187. stream->cur_conni=(int)(conn-stream->conns);
  3188. OP_ASSERT(stream->cur_conni>=0&&stream->cur_conni<OP_NCONNS_MAX);
  3189. return 0;
  3190. }
  3191. close_pnext=pnext;
  3192. close_conn=conn;
  3193. pnext=&conn->next;
  3194. conn=conn->next;
  3195. }
  3196. /*No suitable connections.
  3197. Open a new one.*/
  3198. if(stream->free_head==NULL){
  3199. /*All connections in use.
  3200. Expire one of them (we should have already picked which one when scanning
  3201. the list).*/
  3202. OP_ASSERT(close_conn!=NULL);
  3203. OP_ASSERT(close_pnext!=NULL);
  3204. op_http_conn_close(stream,close_conn,close_pnext,1);
  3205. }
  3206. OP_ASSERT(stream->free_head!=NULL);
  3207. conn=stream->free_head;
  3208. /*If we can pipeline, only request a chunk of data.
  3209. If we're seeking now, there's a good chance we will want to seek again
  3210. soon, and this avoids committing this connection to reading the rest of
  3211. the stream.
  3212. Particularly with SSL or proxies, issuing a new request on the same
  3213. connection can be substantially faster than opening a new one.
  3214. This also limits the amount of data the server will blast at us on this
  3215. connection if we later seek elsewhere and start reading from a different
  3216. connection.*/
  3217. ret=op_http_conn_open_pos(stream,conn,pos,
  3218. pipeline?OP_PIPELINE_CHUNK_SIZE:-1);
  3219. if(OP_UNLIKELY(ret<0)){
  3220. op_http_conn_close(stream,conn,&stream->lru_head,1);
  3221. return -1;
  3222. }
  3223. return 0;
  3224. }
  3225. static opus_int64 op_http_stream_tell(void *_stream){
  3226. OpusHTTPStream *stream;
  3227. int ci;
  3228. stream=(OpusHTTPStream *)_stream;
  3229. ci=stream->cur_conni;
  3230. return ci<0?stream->pos:stream->conns[ci].pos;
  3231. }
  3232. static int op_http_stream_close(void *_stream){
  3233. OpusHTTPStream *stream;
  3234. stream=(OpusHTTPStream *)_stream;
  3235. if(OP_LIKELY(stream!=NULL)){
  3236. op_http_stream_clear(stream);
  3237. _ogg_free(stream);
  3238. }
  3239. return 0;
  3240. }
  3241. static const OpusFileCallbacks OP_HTTP_CALLBACKS={
  3242. op_http_stream_read,
  3243. op_http_stream_seek,
  3244. op_http_stream_tell,
  3245. op_http_stream_close
  3246. };
  3247. #endif
  3248. void opus_server_info_init(OpusServerInfo *_info){
  3249. _info->name=NULL;
  3250. _info->description=NULL;
  3251. _info->genre=NULL;
  3252. _info->url=NULL;
  3253. _info->server=NULL;
  3254. _info->content_type=NULL;
  3255. _info->bitrate_kbps=-1;
  3256. _info->is_public=-1;
  3257. _info->is_ssl=0;
  3258. }
  3259. void opus_server_info_clear(OpusServerInfo *_info){
  3260. _ogg_free(_info->content_type);
  3261. _ogg_free(_info->server);
  3262. _ogg_free(_info->url);
  3263. _ogg_free(_info->genre);
  3264. _ogg_free(_info->description);
  3265. _ogg_free(_info->name);
  3266. }
  3267. /*The actual URL stream creation function.
  3268. This one isn't extensible like the application-level interface, but because
  3269. it isn't public, we're free to change it in the future.*/
  3270. static void *op_url_stream_create_impl(OpusFileCallbacks *_cb,const char *_url,
  3271. int _skip_certificate_check,const char *_proxy_host,unsigned _proxy_port,
  3272. const char *_proxy_user,const char *_proxy_pass,OpusServerInfo *_info){
  3273. const char *path;
  3274. /*Check to see if this is a valid file: URL.*/
  3275. path=op_parse_file_url(_url);
  3276. if(path!=NULL){
  3277. char *unescaped_path;
  3278. void *ret;
  3279. unescaped_path=op_string_dup(path);
  3280. if(OP_UNLIKELY(unescaped_path==NULL))return NULL;
  3281. ret=op_fopen(_cb,op_unescape_url_component(unescaped_path),"rb");
  3282. _ogg_free(unescaped_path);
  3283. return ret;
  3284. }
  3285. #if defined(OP_ENABLE_HTTP)
  3286. /*If not, try http/https.*/
  3287. else{
  3288. OpusHTTPStream *stream;
  3289. int ret;
  3290. stream=(OpusHTTPStream *)_ogg_malloc(sizeof(*stream));
  3291. if(OP_UNLIKELY(stream==NULL))return NULL;
  3292. op_http_stream_init(stream);
  3293. ret=op_http_stream_open(stream,_url,_skip_certificate_check,
  3294. _proxy_host,_proxy_port,_proxy_user,_proxy_pass,_info);
  3295. if(OP_UNLIKELY(ret<0)){
  3296. op_http_stream_clear(stream);
  3297. _ogg_free(stream);
  3298. return NULL;
  3299. }
  3300. *_cb=*&OP_HTTP_CALLBACKS;
  3301. return stream;
  3302. }
  3303. #else
  3304. (void)_skip_certificate_check;
  3305. (void)_proxy_host;
  3306. (void)_proxy_port;
  3307. (void)_proxy_user;
  3308. (void)_proxy_pass;
  3309. (void)_info;
  3310. return NULL;
  3311. #endif
  3312. }
  3313. /*The actual implementation of op_url_stream_vcreate().
  3314. We have to do a careful dance here to avoid potential memory leaks if
  3315. OpusServerInfo is requested, since this function is also used by
  3316. op_vopen_url() and op_vtest_url().
  3317. Even if this function succeeds, those functions might ultimately fail.
  3318. If they do, they should return without having touched the OpusServerInfo
  3319. passed by the application.
  3320. Therefore, if this function succeeds and OpusServerInfo is requested, the
  3321. actual info will be stored in *_info and a pointer to the application's
  3322. storage will be placed in *_pinfo.
  3323. If this function fails or if the application did not request OpusServerInfo,
  3324. *_pinfo will be NULL.
  3325. Our caller is responsible for copying *_info to **_pinfo if it ultimately
  3326. succeeds, or for clearing *_info if it ultimately fails.*/
  3327. static void *op_url_stream_vcreate_impl(OpusFileCallbacks *_cb,
  3328. const char *_url,OpusServerInfo *_info,OpusServerInfo **_pinfo,va_list _ap){
  3329. int skip_certificate_check;
  3330. const char *proxy_host;
  3331. opus_int32 proxy_port;
  3332. const char *proxy_user;
  3333. const char *proxy_pass;
  3334. OpusServerInfo *pinfo;
  3335. skip_certificate_check=0;
  3336. proxy_host=NULL;
  3337. proxy_port=8080;
  3338. proxy_user=NULL;
  3339. proxy_pass=NULL;
  3340. pinfo=NULL;
  3341. *_pinfo=NULL;
  3342. for(;;){
  3343. ptrdiff_t request;
  3344. request=va_arg(_ap,char *)-(char *)NULL;
  3345. /*If we hit NULL, we're done processing options.*/
  3346. if(!request)break;
  3347. switch(request){
  3348. case OP_SSL_SKIP_CERTIFICATE_CHECK_REQUEST:{
  3349. skip_certificate_check=!!va_arg(_ap,opus_int32);
  3350. }break;
  3351. case OP_HTTP_PROXY_HOST_REQUEST:{
  3352. proxy_host=va_arg(_ap,const char *);
  3353. }break;
  3354. case OP_HTTP_PROXY_PORT_REQUEST:{
  3355. proxy_port=va_arg(_ap,opus_int32);
  3356. if(proxy_port<0||proxy_port>(opus_int32)65535)return NULL;
  3357. }break;
  3358. case OP_HTTP_PROXY_USER_REQUEST:{
  3359. proxy_user=va_arg(_ap,const char *);
  3360. }break;
  3361. case OP_HTTP_PROXY_PASS_REQUEST:{
  3362. proxy_pass=va_arg(_ap,const char *);
  3363. }break;
  3364. case OP_GET_SERVER_INFO_REQUEST:{
  3365. pinfo=va_arg(_ap,OpusServerInfo *);
  3366. }break;
  3367. /*Some unknown option.*/
  3368. default:return NULL;
  3369. }
  3370. }
  3371. /*If the caller has requested server information, proxy it to a local copy to
  3372. simplify error handling.*/
  3373. if(pinfo!=NULL){
  3374. void *ret;
  3375. opus_server_info_init(_info);
  3376. ret=op_url_stream_create_impl(_cb,_url,skip_certificate_check,
  3377. proxy_host,proxy_port,proxy_user,proxy_pass,_info);
  3378. if(ret!=NULL)*_pinfo=pinfo;
  3379. else opus_server_info_clear(_info);
  3380. return ret;
  3381. }
  3382. return op_url_stream_create_impl(_cb,_url,skip_certificate_check,
  3383. proxy_host,proxy_port,proxy_user,proxy_pass,NULL);
  3384. }
  3385. void *op_url_stream_vcreate(OpusFileCallbacks *_cb,
  3386. const char *_url,va_list _ap){
  3387. OpusServerInfo info;
  3388. OpusServerInfo *pinfo;
  3389. void *ret;
  3390. ret=op_url_stream_vcreate_impl(_cb,_url,&info,&pinfo,_ap);
  3391. if(pinfo!=NULL)*pinfo=*&info;
  3392. return ret;
  3393. }
  3394. void *op_url_stream_create(OpusFileCallbacks *_cb,
  3395. const char *_url,...){
  3396. va_list ap;
  3397. void *ret;
  3398. va_start(ap,_url);
  3399. ret=op_url_stream_vcreate(_cb,_url,ap);
  3400. va_end(ap);
  3401. return ret;
  3402. }
  3403. /*Convenience routines to open/test URLs in a single step.*/
  3404. OggOpusFile *op_vopen_url(const char *_url,int *_error,va_list _ap){
  3405. OpusFileCallbacks cb;
  3406. OggOpusFile *of;
  3407. OpusServerInfo info;
  3408. OpusServerInfo *pinfo;
  3409. void *source;
  3410. source=op_url_stream_vcreate_impl(&cb,_url,&info,&pinfo,_ap);
  3411. if(OP_UNLIKELY(source==NULL)){
  3412. OP_ASSERT(pinfo==NULL);
  3413. if(_error!=NULL)*_error=OP_EFAULT;
  3414. return NULL;
  3415. }
  3416. of=op_open_callbacks(source,&cb,NULL,0,_error);
  3417. if(OP_UNLIKELY(of==NULL)){
  3418. if(pinfo!=NULL)opus_server_info_clear(&info);
  3419. (*cb.close)(source);
  3420. }
  3421. else if(pinfo!=NULL)*pinfo=*&info;
  3422. return of;
  3423. }
  3424. OggOpusFile *op_open_url(const char *_url,int *_error,...){
  3425. OggOpusFile *ret;
  3426. va_list ap;
  3427. va_start(ap,_error);
  3428. ret=op_vopen_url(_url,_error,ap);
  3429. va_end(ap);
  3430. return ret;
  3431. }
  3432. OggOpusFile *op_vtest_url(const char *_url,int *_error,va_list _ap){
  3433. OpusFileCallbacks cb;
  3434. OggOpusFile *of;
  3435. OpusServerInfo info;
  3436. OpusServerInfo *pinfo;
  3437. void *source;
  3438. source=op_url_stream_vcreate_impl(&cb,_url,&info,&pinfo,_ap);
  3439. if(OP_UNLIKELY(source==NULL)){
  3440. OP_ASSERT(pinfo==NULL);
  3441. if(_error!=NULL)*_error=OP_EFAULT;
  3442. return NULL;
  3443. }
  3444. of=op_test_callbacks(source,&cb,NULL,0,_error);
  3445. if(OP_UNLIKELY(of==NULL)){
  3446. if(pinfo!=NULL)opus_server_info_clear(&info);
  3447. (*cb.close)(source);
  3448. }
  3449. else if(pinfo!=NULL)*pinfo=*&info;
  3450. return of;
  3451. }
  3452. OggOpusFile *op_test_url(const char *_url,int *_error,...){
  3453. OggOpusFile *ret;
  3454. va_list ap;
  3455. va_start(ap,_error);
  3456. ret=op_vtest_url(_url,_error,ap);
  3457. va_end(ap);
  3458. return ret;
  3459. }