http.c 126 KB

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