url.c 150 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850
  1. /***************************************************************************
  2. * _ _ ____ _
  3. * Project ___| | | | _ \| |
  4. * / __| | | | |_) | |
  5. * | (__| |_| | _ <| |___
  6. * \___|\___/|_| \_\_____|
  7. *
  8. * Copyright (C) 1998 - 2018, Daniel Stenberg, <daniel@haxx.se>, et al.
  9. *
  10. * This software is licensed as described in the file COPYING, which
  11. * you should have received as part of this distribution. The terms
  12. * are also available at https://curl.haxx.se/docs/copyright.html.
  13. *
  14. * You may opt to use, copy, modify, merge, publish, distribute and/or sell
  15. * copies of the Software, and permit persons to whom the Software is
  16. * furnished to do so, under the terms of the COPYING file.
  17. *
  18. * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
  19. * KIND, either express or implied.
  20. *
  21. ***************************************************************************/
  22. #include "curl_setup.h"
  23. #ifdef HAVE_NETINET_IN_H
  24. #include <netinet/in.h>
  25. #endif
  26. #ifdef HAVE_NETDB_H
  27. #include <netdb.h>
  28. #endif
  29. #ifdef HAVE_ARPA_INET_H
  30. #include <arpa/inet.h>
  31. #endif
  32. #ifdef HAVE_NET_IF_H
  33. #include <net/if.h>
  34. #endif
  35. #ifdef HAVE_SYS_IOCTL_H
  36. #include <sys/ioctl.h>
  37. #endif
  38. #ifdef HAVE_SYS_PARAM_H
  39. #include <sys/param.h>
  40. #endif
  41. #ifdef __VMS
  42. #include <in.h>
  43. #include <inet.h>
  44. #endif
  45. #ifdef HAVE_SYS_UN_H
  46. #include <sys/un.h>
  47. #endif
  48. #ifndef HAVE_SOCKET
  49. #error "We can't compile without socket() support!"
  50. #endif
  51. #include <limits.h>
  52. #ifdef USE_LIBIDN2
  53. #include <idn2.h>
  54. #elif defined(USE_WIN32_IDN)
  55. /* prototype for curl_win32_idn_to_ascii() */
  56. bool curl_win32_idn_to_ascii(const char *in, char **out);
  57. #endif /* USE_LIBIDN2 */
  58. #include "urldata.h"
  59. #include "netrc.h"
  60. #include "formdata.h"
  61. #include "mime.h"
  62. #include "vtls/vtls.h"
  63. #include "hostip.h"
  64. #include "transfer.h"
  65. #include "sendf.h"
  66. #include "progress.h"
  67. #include "cookie.h"
  68. #include "strcase.h"
  69. #include "strerror.h"
  70. #include "escape.h"
  71. #include "strtok.h"
  72. #include "share.h"
  73. #include "content_encoding.h"
  74. #include "http_digest.h"
  75. #include "http_negotiate.h"
  76. #include "select.h"
  77. #include "multiif.h"
  78. #include "easyif.h"
  79. #include "speedcheck.h"
  80. #include "warnless.h"
  81. #include "non-ascii.h"
  82. #include "inet_pton.h"
  83. #include "getinfo.h"
  84. /* And now for the protocols */
  85. #include "ftp.h"
  86. #include "dict.h"
  87. #include "telnet.h"
  88. #include "tftp.h"
  89. #include "http.h"
  90. #include "http2.h"
  91. #include "file.h"
  92. #include "curl_ldap.h"
  93. #include "ssh.h"
  94. #include "imap.h"
  95. #include "url.h"
  96. #include "connect.h"
  97. #include "inet_ntop.h"
  98. #include "http_ntlm.h"
  99. #include "curl_ntlm_wb.h"
  100. #include "socks.h"
  101. #include "curl_rtmp.h"
  102. #include "gopher.h"
  103. #include "http_proxy.h"
  104. #include "conncache.h"
  105. #include "multihandle.h"
  106. #include "pipeline.h"
  107. #include "dotdot.h"
  108. #include "strdup.h"
  109. #include "setopt.h"
  110. /* The last 3 #include files should be in this order */
  111. #include "curl_printf.h"
  112. #include "curl_memory.h"
  113. #include "memdebug.h"
  114. static void conn_free(struct connectdata *conn);
  115. static void free_fixed_hostname(struct hostname *host);
  116. static void signalPipeClose(struct curl_llist *pipeline, bool pipe_broke);
  117. static CURLcode parse_url_login(struct Curl_easy *data,
  118. struct connectdata *conn,
  119. char **userptr, char **passwdptr,
  120. char **optionsptr);
  121. static unsigned int get_protocol_family(unsigned int protocol);
  122. /* Some parts of the code (e.g. chunked encoding) assume this buffer has at
  123. * more than just a few bytes to play with. Don't let it become too small or
  124. * bad things will happen.
  125. */
  126. #if READBUFFER_SIZE < READBUFFER_MIN
  127. # error READBUFFER_SIZE is too small
  128. #endif
  129. /*
  130. * Protocol table.
  131. */
  132. static const struct Curl_handler * const protocols[] = {
  133. #ifndef CURL_DISABLE_HTTP
  134. &Curl_handler_http,
  135. #endif
  136. #if defined(USE_SSL) && !defined(CURL_DISABLE_HTTP)
  137. &Curl_handler_https,
  138. #endif
  139. #ifndef CURL_DISABLE_FTP
  140. &Curl_handler_ftp,
  141. #endif
  142. #if defined(USE_SSL) && !defined(CURL_DISABLE_FTP)
  143. &Curl_handler_ftps,
  144. #endif
  145. #ifndef CURL_DISABLE_TELNET
  146. &Curl_handler_telnet,
  147. #endif
  148. #ifndef CURL_DISABLE_DICT
  149. &Curl_handler_dict,
  150. #endif
  151. #ifndef CURL_DISABLE_LDAP
  152. &Curl_handler_ldap,
  153. #if !defined(CURL_DISABLE_LDAPS) && \
  154. ((defined(USE_OPENLDAP) && defined(USE_SSL)) || \
  155. (!defined(USE_OPENLDAP) && defined(HAVE_LDAP_SSL)))
  156. &Curl_handler_ldaps,
  157. #endif
  158. #endif
  159. #ifndef CURL_DISABLE_FILE
  160. &Curl_handler_file,
  161. #endif
  162. #ifndef CURL_DISABLE_TFTP
  163. &Curl_handler_tftp,
  164. #endif
  165. #if defined(USE_LIBSSH2) || defined(USE_LIBSSH)
  166. &Curl_handler_scp,
  167. #endif
  168. #if defined(USE_LIBSSH2) || defined(USE_LIBSSH)
  169. &Curl_handler_sftp,
  170. #endif
  171. #ifndef CURL_DISABLE_IMAP
  172. &Curl_handler_imap,
  173. #ifdef USE_SSL
  174. &Curl_handler_imaps,
  175. #endif
  176. #endif
  177. #ifndef CURL_DISABLE_POP3
  178. &Curl_handler_pop3,
  179. #ifdef USE_SSL
  180. &Curl_handler_pop3s,
  181. #endif
  182. #endif
  183. #if !defined(CURL_DISABLE_SMB) && defined(USE_NTLM) && \
  184. (CURL_SIZEOF_CURL_OFF_T > 4) && \
  185. (!defined(USE_WINDOWS_SSPI) || defined(USE_WIN32_CRYPTO))
  186. &Curl_handler_smb,
  187. #ifdef USE_SSL
  188. &Curl_handler_smbs,
  189. #endif
  190. #endif
  191. #ifndef CURL_DISABLE_SMTP
  192. &Curl_handler_smtp,
  193. #ifdef USE_SSL
  194. &Curl_handler_smtps,
  195. #endif
  196. #endif
  197. #ifndef CURL_DISABLE_RTSP
  198. &Curl_handler_rtsp,
  199. #endif
  200. #ifndef CURL_DISABLE_GOPHER
  201. &Curl_handler_gopher,
  202. #endif
  203. #ifdef USE_LIBRTMP
  204. &Curl_handler_rtmp,
  205. &Curl_handler_rtmpt,
  206. &Curl_handler_rtmpe,
  207. &Curl_handler_rtmpte,
  208. &Curl_handler_rtmps,
  209. &Curl_handler_rtmpts,
  210. #endif
  211. (struct Curl_handler *) NULL
  212. };
  213. /*
  214. * Dummy handler for undefined protocol schemes.
  215. */
  216. static const struct Curl_handler Curl_handler_dummy = {
  217. "<no protocol>", /* scheme */
  218. ZERO_NULL, /* setup_connection */
  219. ZERO_NULL, /* do_it */
  220. ZERO_NULL, /* done */
  221. ZERO_NULL, /* do_more */
  222. ZERO_NULL, /* connect_it */
  223. ZERO_NULL, /* connecting */
  224. ZERO_NULL, /* doing */
  225. ZERO_NULL, /* proto_getsock */
  226. ZERO_NULL, /* doing_getsock */
  227. ZERO_NULL, /* domore_getsock */
  228. ZERO_NULL, /* perform_getsock */
  229. ZERO_NULL, /* disconnect */
  230. ZERO_NULL, /* readwrite */
  231. ZERO_NULL, /* connection_check */
  232. 0, /* defport */
  233. 0, /* protocol */
  234. PROTOPT_NONE /* flags */
  235. };
  236. void Curl_freeset(struct Curl_easy *data)
  237. {
  238. /* Free all dynamic strings stored in the data->set substructure. */
  239. enum dupstring i;
  240. for(i = (enum dupstring)0; i < STRING_LAST; i++) {
  241. Curl_safefree(data->set.str[i]);
  242. }
  243. if(data->change.referer_alloc) {
  244. Curl_safefree(data->change.referer);
  245. data->change.referer_alloc = FALSE;
  246. }
  247. data->change.referer = NULL;
  248. if(data->change.url_alloc) {
  249. Curl_safefree(data->change.url);
  250. data->change.url_alloc = FALSE;
  251. }
  252. data->change.url = NULL;
  253. Curl_mime_cleanpart(&data->set.mimepost);
  254. }
  255. /*
  256. * This is the internal function curl_easy_cleanup() calls. This should
  257. * cleanup and free all resources associated with this sessionhandle.
  258. *
  259. * NOTE: if we ever add something that attempts to write to a socket or
  260. * similar here, we must ignore SIGPIPE first. It is currently only done
  261. * when curl_easy_perform() is invoked.
  262. */
  263. CURLcode Curl_close(struct Curl_easy *data)
  264. {
  265. struct Curl_multi *m;
  266. if(!data)
  267. return CURLE_OK;
  268. Curl_expire_clear(data); /* shut off timers */
  269. m = data->multi;
  270. if(m)
  271. /* This handle is still part of a multi handle, take care of this first
  272. and detach this handle from there. */
  273. curl_multi_remove_handle(data->multi, data);
  274. if(data->multi_easy)
  275. /* when curl_easy_perform() is used, it creates its own multi handle to
  276. use and this is the one */
  277. curl_multi_cleanup(data->multi_easy);
  278. /* Destroy the timeout list that is held in the easy handle. It is
  279. /normally/ done by curl_multi_remove_handle() but this is "just in
  280. case" */
  281. Curl_llist_destroy(&data->state.timeoutlist, NULL);
  282. data->magic = 0; /* force a clear AFTER the possibly enforced removal from
  283. the multi handle, since that function uses the magic
  284. field! */
  285. if(data->state.rangestringalloc)
  286. free(data->state.range);
  287. /* Free the pathbuffer */
  288. Curl_safefree(data->state.pathbuffer);
  289. data->state.path = NULL;
  290. /* freed here just in case DONE wasn't called */
  291. Curl_free_request_state(data);
  292. /* Close down all open SSL info and sessions */
  293. Curl_ssl_close_all(data);
  294. Curl_safefree(data->state.first_host);
  295. Curl_safefree(data->state.scratch);
  296. Curl_ssl_free_certinfo(data);
  297. /* Cleanup possible redirect junk */
  298. free(data->req.newurl);
  299. data->req.newurl = NULL;
  300. if(data->change.referer_alloc) {
  301. Curl_safefree(data->change.referer);
  302. data->change.referer_alloc = FALSE;
  303. }
  304. data->change.referer = NULL;
  305. if(data->change.url_alloc) {
  306. Curl_safefree(data->change.url);
  307. data->change.url_alloc = FALSE;
  308. }
  309. data->change.url = NULL;
  310. Curl_safefree(data->state.buffer);
  311. Curl_safefree(data->state.headerbuff);
  312. Curl_flush_cookies(data, 1);
  313. Curl_digest_cleanup(data);
  314. Curl_safefree(data->info.contenttype);
  315. Curl_safefree(data->info.wouldredirect);
  316. /* this destroys the channel and we cannot use it anymore after this */
  317. Curl_resolver_cleanup(data->state.resolver);
  318. Curl_http2_cleanup_dependencies(data);
  319. Curl_convert_close(data);
  320. /* No longer a dirty share, if it exists */
  321. if(data->share) {
  322. Curl_share_lock(data, CURL_LOCK_DATA_SHARE, CURL_LOCK_ACCESS_SINGLE);
  323. data->share->dirty--;
  324. Curl_share_unlock(data, CURL_LOCK_DATA_SHARE);
  325. }
  326. /* destruct wildcard structures if it is needed */
  327. Curl_wildcard_dtor(&data->wildcard);
  328. Curl_freeset(data);
  329. free(data);
  330. return CURLE_OK;
  331. }
  332. /*
  333. * Initialize the UserDefined fields within a Curl_easy.
  334. * This may be safely called on a new or existing Curl_easy.
  335. */
  336. CURLcode Curl_init_userdefined(struct Curl_easy *data)
  337. {
  338. struct UserDefined *set = &data->set;
  339. CURLcode result = CURLE_OK;
  340. set->out = stdout; /* default output to stdout */
  341. set->in_set = stdin; /* default input from stdin */
  342. set->err = stderr; /* default stderr to stderr */
  343. /* use fwrite as default function to store output */
  344. set->fwrite_func = (curl_write_callback)fwrite;
  345. /* use fread as default function to read input */
  346. set->fread_func_set = (curl_read_callback)fread;
  347. set->is_fread_set = 0;
  348. set->is_fwrite_set = 0;
  349. set->seek_func = ZERO_NULL;
  350. set->seek_client = ZERO_NULL;
  351. /* conversion callbacks for non-ASCII hosts */
  352. set->convfromnetwork = ZERO_NULL;
  353. set->convtonetwork = ZERO_NULL;
  354. set->convfromutf8 = ZERO_NULL;
  355. set->filesize = -1; /* we don't know the size */
  356. set->postfieldsize = -1; /* unknown size */
  357. set->maxredirs = -1; /* allow any amount by default */
  358. set->httpreq = HTTPREQ_GET; /* Default HTTP request */
  359. set->rtspreq = RTSPREQ_OPTIONS; /* Default RTSP request */
  360. set->ftp_use_epsv = TRUE; /* FTP defaults to EPSV operations */
  361. set->ftp_use_eprt = TRUE; /* FTP defaults to EPRT operations */
  362. set->ftp_use_pret = FALSE; /* mainly useful for drftpd servers */
  363. set->ftp_filemethod = FTPFILE_MULTICWD;
  364. set->dns_cache_timeout = 60; /* Timeout every 60 seconds by default */
  365. /* Set the default size of the SSL session ID cache */
  366. set->general_ssl.max_ssl_sessions = 5;
  367. set->proxyport = 0;
  368. set->proxytype = CURLPROXY_HTTP; /* defaults to HTTP proxy */
  369. set->httpauth = CURLAUTH_BASIC; /* defaults to basic */
  370. set->proxyauth = CURLAUTH_BASIC; /* defaults to basic */
  371. /* SOCKS5 proxy auth defaults to username/password + GSS-API */
  372. set->socks5auth = CURLAUTH_BASIC | CURLAUTH_GSSAPI;
  373. /* make libcurl quiet by default: */
  374. set->hide_progress = TRUE; /* CURLOPT_NOPROGRESS changes these */
  375. Curl_mime_initpart(&set->mimepost, data);
  376. /*
  377. * libcurl 7.10 introduced SSL verification *by default*! This needs to be
  378. * switched off unless wanted.
  379. */
  380. set->ssl.primary.verifypeer = TRUE;
  381. set->ssl.primary.verifyhost = TRUE;
  382. #ifdef USE_TLS_SRP
  383. set->ssl.authtype = CURL_TLSAUTH_NONE;
  384. #endif
  385. set->ssh_auth_types = CURLSSH_AUTH_DEFAULT; /* defaults to any auth
  386. type */
  387. set->ssl.primary.sessionid = TRUE; /* session ID caching enabled by
  388. default */
  389. set->proxy_ssl = set->ssl;
  390. set->new_file_perms = 0644; /* Default permissions */
  391. set->new_directory_perms = 0755; /* Default permissions */
  392. /* for the *protocols fields we don't use the CURLPROTO_ALL convenience
  393. define since we internally only use the lower 16 bits for the passed
  394. in bitmask to not conflict with the private bits */
  395. set->allowed_protocols = CURLPROTO_ALL;
  396. set->redir_protocols = CURLPROTO_ALL & /* All except FILE, SCP and SMB */
  397. ~(CURLPROTO_FILE | CURLPROTO_SCP | CURLPROTO_SMB |
  398. CURLPROTO_SMBS);
  399. #if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI)
  400. /*
  401. * disallow unprotected protection negotiation NEC reference implementation
  402. * seem not to follow rfc1961 section 4.3/4.4
  403. */
  404. set->socks5_gssapi_nec = FALSE;
  405. #endif
  406. /* This is our preferred CA cert bundle/path since install time */
  407. #if defined(CURL_CA_BUNDLE)
  408. result = Curl_setstropt(&set->str[STRING_SSL_CAFILE_ORIG], CURL_CA_BUNDLE);
  409. if(result)
  410. return result;
  411. result = Curl_setstropt(&set->str[STRING_SSL_CAFILE_PROXY], CURL_CA_BUNDLE);
  412. if(result)
  413. return result;
  414. #endif
  415. #if defined(CURL_CA_PATH)
  416. result = Curl_setstropt(&set->str[STRING_SSL_CAPATH_ORIG], CURL_CA_PATH);
  417. if(result)
  418. return result;
  419. result = Curl_setstropt(&set->str[STRING_SSL_CAPATH_PROXY], CURL_CA_PATH);
  420. if(result)
  421. return result;
  422. #endif
  423. set->wildcard_enabled = FALSE;
  424. set->chunk_bgn = ZERO_NULL;
  425. set->chunk_end = ZERO_NULL;
  426. /* tcp keepalives are disabled by default, but provide reasonable values for
  427. * the interval and idle times.
  428. */
  429. set->tcp_keepalive = FALSE;
  430. set->tcp_keepintvl = 60;
  431. set->tcp_keepidle = 60;
  432. set->tcp_fastopen = FALSE;
  433. set->tcp_nodelay = TRUE;
  434. set->ssl_enable_npn = TRUE;
  435. set->ssl_enable_alpn = TRUE;
  436. set->expect_100_timeout = 1000L; /* Wait for a second by default. */
  437. set->sep_headers = TRUE; /* separated header lists by default */
  438. set->buffer_size = READBUFFER_SIZE;
  439. Curl_http2_init_userset(set);
  440. return result;
  441. }
  442. /**
  443. * Curl_open()
  444. *
  445. * @param curl is a pointer to a sessionhandle pointer that gets set by this
  446. * function.
  447. * @return CURLcode
  448. */
  449. CURLcode Curl_open(struct Curl_easy **curl)
  450. {
  451. CURLcode result;
  452. struct Curl_easy *data;
  453. /* Very simple start-up: alloc the struct, init it with zeroes and return */
  454. data = calloc(1, sizeof(struct Curl_easy));
  455. if(!data) {
  456. /* this is a very serious error */
  457. DEBUGF(fprintf(stderr, "Error: calloc of Curl_easy failed\n"));
  458. return CURLE_OUT_OF_MEMORY;
  459. }
  460. data->magic = CURLEASY_MAGIC_NUMBER;
  461. result = Curl_resolver_init(&data->state.resolver);
  462. if(result) {
  463. DEBUGF(fprintf(stderr, "Error: resolver_init failed\n"));
  464. free(data);
  465. return result;
  466. }
  467. /* We do some initial setup here, all those fields that can't be just 0 */
  468. data->state.buffer = malloc(READBUFFER_SIZE + 1);
  469. if(!data->state.buffer) {
  470. DEBUGF(fprintf(stderr, "Error: malloc of buffer failed\n"));
  471. result = CURLE_OUT_OF_MEMORY;
  472. }
  473. else {
  474. data->state.headerbuff = malloc(HEADERSIZE);
  475. if(!data->state.headerbuff) {
  476. DEBUGF(fprintf(stderr, "Error: malloc of headerbuff failed\n"));
  477. result = CURLE_OUT_OF_MEMORY;
  478. }
  479. else {
  480. result = Curl_init_userdefined(data);
  481. data->state.headersize = HEADERSIZE;
  482. Curl_convert_init(data);
  483. Curl_initinfo(data);
  484. /* most recent connection is not yet defined */
  485. data->state.lastconnect = NULL;
  486. data->progress.flags |= PGRS_HIDE;
  487. data->state.current_speed = -1; /* init to negative == impossible */
  488. data->set.fnmatch = ZERO_NULL;
  489. data->set.maxconnects = DEFAULT_CONNCACHE_SIZE; /* for easy handles */
  490. Curl_http2_init_state(&data->state);
  491. }
  492. }
  493. if(result) {
  494. Curl_resolver_cleanup(data->state.resolver);
  495. free(data->state.buffer);
  496. free(data->state.headerbuff);
  497. Curl_freeset(data);
  498. free(data);
  499. data = NULL;
  500. }
  501. else
  502. *curl = data;
  503. return result;
  504. }
  505. #ifdef USE_RECV_BEFORE_SEND_WORKAROUND
  506. static void conn_reset_postponed_data(struct connectdata *conn, int num)
  507. {
  508. struct postponed_data * const psnd = &(conn->postponed[num]);
  509. if(psnd->buffer) {
  510. DEBUGASSERT(psnd->allocated_size > 0);
  511. DEBUGASSERT(psnd->recv_size <= psnd->allocated_size);
  512. DEBUGASSERT(psnd->recv_size ?
  513. (psnd->recv_processed < psnd->recv_size) :
  514. (psnd->recv_processed == 0));
  515. DEBUGASSERT(psnd->bindsock != CURL_SOCKET_BAD);
  516. free(psnd->buffer);
  517. psnd->buffer = NULL;
  518. psnd->allocated_size = 0;
  519. psnd->recv_size = 0;
  520. psnd->recv_processed = 0;
  521. #ifdef DEBUGBUILD
  522. psnd->bindsock = CURL_SOCKET_BAD; /* used only for DEBUGASSERT */
  523. #endif /* DEBUGBUILD */
  524. }
  525. else {
  526. DEBUGASSERT(psnd->allocated_size == 0);
  527. DEBUGASSERT(psnd->recv_size == 0);
  528. DEBUGASSERT(psnd->recv_processed == 0);
  529. DEBUGASSERT(psnd->bindsock == CURL_SOCKET_BAD);
  530. }
  531. }
  532. static void conn_reset_all_postponed_data(struct connectdata *conn)
  533. {
  534. conn_reset_postponed_data(conn, 0);
  535. conn_reset_postponed_data(conn, 1);
  536. }
  537. #else /* ! USE_RECV_BEFORE_SEND_WORKAROUND */
  538. /* Use "do-nothing" macro instead of function when workaround not used */
  539. #define conn_reset_all_postponed_data(c) do {} WHILE_FALSE
  540. #endif /* ! USE_RECV_BEFORE_SEND_WORKAROUND */
  541. static void conn_free(struct connectdata *conn)
  542. {
  543. if(!conn)
  544. return;
  545. /* possible left-overs from the async name resolvers */
  546. Curl_resolver_cancel(conn);
  547. /* close the SSL stuff before we close any sockets since they will/may
  548. write to the sockets */
  549. Curl_ssl_close(conn, FIRSTSOCKET);
  550. Curl_ssl_close(conn, SECONDARYSOCKET);
  551. /* close possibly still open sockets */
  552. if(CURL_SOCKET_BAD != conn->sock[SECONDARYSOCKET])
  553. Curl_closesocket(conn, conn->sock[SECONDARYSOCKET]);
  554. if(CURL_SOCKET_BAD != conn->sock[FIRSTSOCKET])
  555. Curl_closesocket(conn, conn->sock[FIRSTSOCKET]);
  556. if(CURL_SOCKET_BAD != conn->tempsock[0])
  557. Curl_closesocket(conn, conn->tempsock[0]);
  558. if(CURL_SOCKET_BAD != conn->tempsock[1])
  559. Curl_closesocket(conn, conn->tempsock[1]);
  560. #if !defined(CURL_DISABLE_HTTP) && defined(USE_NTLM) && \
  561. defined(NTLM_WB_ENABLED)
  562. Curl_ntlm_wb_cleanup(conn);
  563. #endif
  564. Curl_safefree(conn->user);
  565. Curl_safefree(conn->passwd);
  566. Curl_safefree(conn->oauth_bearer);
  567. Curl_safefree(conn->options);
  568. Curl_safefree(conn->http_proxy.user);
  569. Curl_safefree(conn->socks_proxy.user);
  570. Curl_safefree(conn->http_proxy.passwd);
  571. Curl_safefree(conn->socks_proxy.passwd);
  572. Curl_safefree(conn->allocptr.proxyuserpwd);
  573. Curl_safefree(conn->allocptr.uagent);
  574. Curl_safefree(conn->allocptr.userpwd);
  575. Curl_safefree(conn->allocptr.accept_encoding);
  576. Curl_safefree(conn->allocptr.te);
  577. Curl_safefree(conn->allocptr.rangeline);
  578. Curl_safefree(conn->allocptr.ref);
  579. Curl_safefree(conn->allocptr.host);
  580. Curl_safefree(conn->allocptr.cookiehost);
  581. Curl_safefree(conn->allocptr.rtsp_transport);
  582. Curl_safefree(conn->trailer);
  583. Curl_safefree(conn->host.rawalloc); /* host name buffer */
  584. Curl_safefree(conn->conn_to_host.rawalloc); /* host name buffer */
  585. Curl_safefree(conn->secondaryhostname);
  586. Curl_safefree(conn->http_proxy.host.rawalloc); /* http proxy name buffer */
  587. Curl_safefree(conn->socks_proxy.host.rawalloc); /* socks proxy name buffer */
  588. Curl_safefree(conn->master_buffer);
  589. Curl_safefree(conn->connect_state);
  590. conn_reset_all_postponed_data(conn);
  591. Curl_llist_destroy(&conn->send_pipe, NULL);
  592. Curl_llist_destroy(&conn->recv_pipe, NULL);
  593. Curl_safefree(conn->localdev);
  594. Curl_free_primary_ssl_config(&conn->ssl_config);
  595. Curl_free_primary_ssl_config(&conn->proxy_ssl_config);
  596. #ifdef USE_UNIX_SOCKETS
  597. Curl_safefree(conn->unix_domain_socket);
  598. #endif
  599. #ifdef USE_SSL
  600. Curl_safefree(conn->ssl_extra);
  601. #endif
  602. free(conn); /* free all the connection oriented data */
  603. }
  604. /*
  605. * Disconnects the given connection. Note the connection may not be the
  606. * primary connection, like when freeing room in the connection cache or
  607. * killing of a dead old connection.
  608. *
  609. * This function MUST NOT reset state in the Curl_easy struct if that
  610. * isn't strictly bound to the life-time of *this* particular connection.
  611. *
  612. */
  613. CURLcode Curl_disconnect(struct connectdata *conn, bool dead_connection)
  614. {
  615. struct Curl_easy *data;
  616. if(!conn)
  617. return CURLE_OK; /* this is closed and fine already */
  618. data = conn->data;
  619. if(!data) {
  620. DEBUGF(fprintf(stderr, "DISCONNECT without easy handle, ignoring\n"));
  621. return CURLE_OK;
  622. }
  623. /*
  624. * If this connection isn't marked to force-close, leave it open if there
  625. * are other users of it
  626. */
  627. if(!conn->bits.close &&
  628. (conn->send_pipe.size + conn->recv_pipe.size)) {
  629. DEBUGF(infof(data, "Curl_disconnect, usecounter: %d\n",
  630. conn->send_pipe.size + conn->recv_pipe.size));
  631. return CURLE_OK;
  632. }
  633. if(conn->dns_entry != NULL) {
  634. Curl_resolv_unlock(data, conn->dns_entry);
  635. conn->dns_entry = NULL;
  636. }
  637. Curl_hostcache_prune(data); /* kill old DNS cache entries */
  638. #if !defined(CURL_DISABLE_HTTP) && defined(USE_NTLM)
  639. /* Cleanup NTLM connection-related data */
  640. Curl_http_ntlm_cleanup(conn);
  641. #endif
  642. if(conn->handler->disconnect)
  643. /* This is set if protocol-specific cleanups should be made */
  644. conn->handler->disconnect(conn, dead_connection);
  645. /* unlink ourselves! */
  646. infof(data, "Closing connection %ld\n", conn->connection_id);
  647. Curl_conncache_remove_conn(conn, TRUE);
  648. free_fixed_hostname(&conn->host);
  649. free_fixed_hostname(&conn->conn_to_host);
  650. free_fixed_hostname(&conn->http_proxy.host);
  651. free_fixed_hostname(&conn->socks_proxy.host);
  652. Curl_ssl_close(conn, FIRSTSOCKET);
  653. /* Indicate to all handles on the pipe that we're dead */
  654. if(Curl_pipeline_wanted(data->multi, CURLPIPE_ANY)) {
  655. signalPipeClose(&conn->send_pipe, TRUE);
  656. signalPipeClose(&conn->recv_pipe, TRUE);
  657. }
  658. conn_free(conn);
  659. return CURLE_OK;
  660. }
  661. /*
  662. * This function should return TRUE if the socket is to be assumed to
  663. * be dead. Most commonly this happens when the server has closed the
  664. * connection due to inactivity.
  665. */
  666. static bool SocketIsDead(curl_socket_t sock)
  667. {
  668. int sval;
  669. bool ret_val = TRUE;
  670. sval = SOCKET_READABLE(sock, 0);
  671. if(sval == 0)
  672. /* timeout */
  673. ret_val = FALSE;
  674. return ret_val;
  675. }
  676. /*
  677. * IsPipeliningPossible()
  678. *
  679. * Return a bitmask with the available pipelining and multiplexing options for
  680. * the given requested connection.
  681. */
  682. static int IsPipeliningPossible(const struct Curl_easy *handle,
  683. const struct connectdata *conn)
  684. {
  685. int avail = 0;
  686. /* If a HTTP protocol and pipelining is enabled */
  687. if((conn->handler->protocol & PROTO_FAMILY_HTTP) &&
  688. (!conn->bits.protoconnstart || !conn->bits.close)) {
  689. if(Curl_pipeline_wanted(handle->multi, CURLPIPE_HTTP1) &&
  690. (handle->set.httpversion != CURL_HTTP_VERSION_1_0) &&
  691. (handle->set.httpreq == HTTPREQ_GET ||
  692. handle->set.httpreq == HTTPREQ_HEAD))
  693. /* didn't ask for HTTP/1.0 and a GET or HEAD */
  694. avail |= CURLPIPE_HTTP1;
  695. if(Curl_pipeline_wanted(handle->multi, CURLPIPE_MULTIPLEX) &&
  696. (handle->set.httpversion >= CURL_HTTP_VERSION_2))
  697. /* allows HTTP/2 */
  698. avail |= CURLPIPE_MULTIPLEX;
  699. }
  700. return avail;
  701. }
  702. int Curl_removeHandleFromPipeline(struct Curl_easy *handle,
  703. struct curl_llist *pipeline)
  704. {
  705. if(pipeline) {
  706. struct curl_llist_element *curr;
  707. curr = pipeline->head;
  708. while(curr) {
  709. if(curr->ptr == handle) {
  710. Curl_llist_remove(pipeline, curr, NULL);
  711. return 1; /* we removed a handle */
  712. }
  713. curr = curr->next;
  714. }
  715. }
  716. return 0;
  717. }
  718. #if 0 /* this code is saved here as it is useful for debugging purposes */
  719. static void Curl_printPipeline(struct curl_llist *pipeline)
  720. {
  721. struct curl_llist_element *curr;
  722. curr = pipeline->head;
  723. while(curr) {
  724. struct Curl_easy *data = (struct Curl_easy *) curr->ptr;
  725. infof(data, "Handle in pipeline: %s\n", data->state.path);
  726. curr = curr->next;
  727. }
  728. }
  729. #endif
  730. static struct Curl_easy* gethandleathead(struct curl_llist *pipeline)
  731. {
  732. struct curl_llist_element *curr = pipeline->head;
  733. if(curr) {
  734. return (struct Curl_easy *) curr->ptr;
  735. }
  736. return NULL;
  737. }
  738. /* remove the specified connection from all (possible) pipelines and related
  739. queues */
  740. void Curl_getoff_all_pipelines(struct Curl_easy *data,
  741. struct connectdata *conn)
  742. {
  743. bool recv_head = (conn->readchannel_inuse &&
  744. Curl_recvpipe_head(data, conn));
  745. bool send_head = (conn->writechannel_inuse &&
  746. Curl_sendpipe_head(data, conn));
  747. if(Curl_removeHandleFromPipeline(data, &conn->recv_pipe) && recv_head)
  748. Curl_pipeline_leave_read(conn);
  749. if(Curl_removeHandleFromPipeline(data, &conn->send_pipe) && send_head)
  750. Curl_pipeline_leave_write(conn);
  751. }
  752. static void signalPipeClose(struct curl_llist *pipeline, bool pipe_broke)
  753. {
  754. struct curl_llist_element *curr;
  755. if(!pipeline)
  756. return;
  757. curr = pipeline->head;
  758. while(curr) {
  759. struct curl_llist_element *next = curr->next;
  760. struct Curl_easy *data = (struct Curl_easy *) curr->ptr;
  761. #ifdef DEBUGBUILD /* debug-only code */
  762. if(data->magic != CURLEASY_MAGIC_NUMBER) {
  763. /* MAJOR BADNESS */
  764. infof(data, "signalPipeClose() found BAAD easy handle\n");
  765. }
  766. #endif
  767. if(pipe_broke)
  768. data->state.pipe_broke = TRUE;
  769. Curl_multi_handlePipeBreak(data);
  770. Curl_llist_remove(pipeline, curr, NULL);
  771. curr = next;
  772. }
  773. }
  774. static bool
  775. proxy_info_matches(const struct proxy_info* data,
  776. const struct proxy_info* needle)
  777. {
  778. if((data->proxytype == needle->proxytype) &&
  779. (data->port == needle->port) &&
  780. Curl_safe_strcasecompare(data->host.name, needle->host.name))
  781. return TRUE;
  782. return FALSE;
  783. }
  784. /*
  785. * This function checks if the given connection is dead and extracts it from
  786. * the connection cache if so.
  787. *
  788. * When this is called as a Curl_conncache_foreach() callback, the connection
  789. * cache lock is held!
  790. *
  791. * Returns TRUE if the connection was dead and extracted.
  792. */
  793. static bool extract_if_dead(struct connectdata *conn,
  794. struct Curl_easy *data)
  795. {
  796. size_t pipeLen = conn->send_pipe.size + conn->recv_pipe.size;
  797. if(!pipeLen && !conn->inuse) {
  798. /* The check for a dead socket makes sense only if there are no
  799. handles in pipeline and the connection isn't already marked in
  800. use */
  801. bool dead;
  802. if(conn->handler->connection_check) {
  803. /* The protocol has a special method for checking the state of the
  804. connection. Use it to check if the connection is dead. */
  805. unsigned int state;
  806. state = conn->handler->connection_check(conn, CONNCHECK_ISDEAD);
  807. dead = (state & CONNRESULT_DEAD);
  808. }
  809. else {
  810. /* Use the general method for determining the death of a connection */
  811. dead = SocketIsDead(conn->sock[FIRSTSOCKET]);
  812. }
  813. if(dead) {
  814. conn->data = data;
  815. infof(data, "Connection %ld seems to be dead!\n", conn->connection_id);
  816. Curl_conncache_remove_conn(conn, FALSE);
  817. return TRUE;
  818. }
  819. }
  820. return FALSE;
  821. }
  822. struct prunedead {
  823. struct Curl_easy *data;
  824. struct connectdata *extracted;
  825. };
  826. /*
  827. * Wrapper to use extract_if_dead() function in Curl_conncache_foreach()
  828. *
  829. */
  830. static int call_extract_if_dead(struct connectdata *conn, void *param)
  831. {
  832. struct prunedead *p = (struct prunedead *)param;
  833. if(extract_if_dead(conn, p->data)) {
  834. /* stop the iteration here, pass back the connection that was extracted */
  835. p->extracted = conn;
  836. return 1;
  837. }
  838. return 0; /* continue iteration */
  839. }
  840. /*
  841. * This function scans the connection cache for half-open/dead connections,
  842. * closes and removes them.
  843. * The cleanup is done at most once per second.
  844. */
  845. static void prune_dead_connections(struct Curl_easy *data)
  846. {
  847. struct curltime now = Curl_now();
  848. time_t elapsed = Curl_timediff(now, data->state.conn_cache->last_cleanup);
  849. if(elapsed >= 1000L) {
  850. struct prunedead prune;
  851. prune.data = data;
  852. prune.extracted = NULL;
  853. while(Curl_conncache_foreach(data, data->state.conn_cache, &prune,
  854. call_extract_if_dead)) {
  855. /* disconnect it */
  856. (void)Curl_disconnect(prune.extracted, /* dead_connection */TRUE);
  857. }
  858. data->state.conn_cache->last_cleanup = now;
  859. }
  860. }
  861. static size_t max_pipeline_length(struct Curl_multi *multi)
  862. {
  863. return multi ? multi->max_pipeline_length : 0;
  864. }
  865. /*
  866. * Given one filled in connection struct (named needle), this function should
  867. * detect if there already is one that has all the significant details
  868. * exactly the same and thus should be used instead.
  869. *
  870. * If there is a match, this function returns TRUE - and has marked the
  871. * connection as 'in-use'. It must later be called with ConnectionDone() to
  872. * return back to 'idle' (unused) state.
  873. *
  874. * The force_reuse flag is set if the connection must be used, even if
  875. * the pipelining strategy wants to open a new connection instead of reusing.
  876. */
  877. static bool
  878. ConnectionExists(struct Curl_easy *data,
  879. struct connectdata *needle,
  880. struct connectdata **usethis,
  881. bool *force_reuse,
  882. bool *waitpipe)
  883. {
  884. struct connectdata *check;
  885. struct connectdata *chosen = 0;
  886. bool foundPendingCandidate = FALSE;
  887. int canpipe = IsPipeliningPossible(data, needle);
  888. struct connectbundle *bundle;
  889. #ifdef USE_NTLM
  890. bool wantNTLMhttp = ((data->state.authhost.want &
  891. (CURLAUTH_NTLM | CURLAUTH_NTLM_WB)) &&
  892. (needle->handler->protocol & PROTO_FAMILY_HTTP));
  893. bool wantProxyNTLMhttp = (needle->bits.proxy_user_passwd &&
  894. ((data->state.authproxy.want &
  895. (CURLAUTH_NTLM | CURLAUTH_NTLM_WB)) &&
  896. (needle->handler->protocol & PROTO_FAMILY_HTTP)));
  897. #endif
  898. *force_reuse = FALSE;
  899. *waitpipe = FALSE;
  900. /* We can't pipeline if the site is blacklisted */
  901. if((canpipe & CURLPIPE_HTTP1) &&
  902. Curl_pipeline_site_blacklisted(data, needle))
  903. canpipe &= ~ CURLPIPE_HTTP1;
  904. /* Look up the bundle with all the connections to this particular host.
  905. Locks the connection cache, beware of early returns! */
  906. bundle = Curl_conncache_find_bundle(needle, data->state.conn_cache);
  907. if(bundle) {
  908. /* Max pipe length is zero (unlimited) for multiplexed connections */
  909. size_t max_pipe_len = (bundle->multiuse != BUNDLE_MULTIPLEX)?
  910. max_pipeline_length(data->multi):0;
  911. size_t best_pipe_len = max_pipe_len;
  912. struct curl_llist_element *curr;
  913. infof(data, "Found bundle for host %s: %p [%s]\n",
  914. (needle->bits.conn_to_host ? needle->conn_to_host.name :
  915. needle->host.name), (void *)bundle,
  916. (bundle->multiuse == BUNDLE_PIPELINING ?
  917. "can pipeline" :
  918. (bundle->multiuse == BUNDLE_MULTIPLEX ?
  919. "can multiplex" : "serially")));
  920. /* We can't pipeline if we don't know anything about the server */
  921. if(canpipe) {
  922. if(bundle->multiuse <= BUNDLE_UNKNOWN) {
  923. if((bundle->multiuse == BUNDLE_UNKNOWN) && data->set.pipewait) {
  924. infof(data, "Server doesn't support multi-use yet, wait\n");
  925. *waitpipe = TRUE;
  926. Curl_conncache_unlock(needle);
  927. return FALSE; /* no re-use */
  928. }
  929. infof(data, "Server doesn't support multi-use (yet)\n");
  930. canpipe = 0;
  931. }
  932. if((bundle->multiuse == BUNDLE_PIPELINING) &&
  933. !Curl_pipeline_wanted(data->multi, CURLPIPE_HTTP1)) {
  934. /* not asked for, switch off */
  935. infof(data, "Could pipeline, but not asked to!\n");
  936. canpipe = 0;
  937. }
  938. else if((bundle->multiuse == BUNDLE_MULTIPLEX) &&
  939. !Curl_pipeline_wanted(data->multi, CURLPIPE_MULTIPLEX)) {
  940. infof(data, "Could multiplex, but not asked to!\n");
  941. canpipe = 0;
  942. }
  943. }
  944. curr = bundle->conn_list.head;
  945. while(curr) {
  946. bool match = FALSE;
  947. size_t pipeLen;
  948. /*
  949. * Note that if we use a HTTP proxy in normal mode (no tunneling), we
  950. * check connections to that proxy and not to the actual remote server.
  951. */
  952. check = curr->ptr;
  953. curr = curr->next;
  954. if(extract_if_dead(check, data)) {
  955. /* disconnect it */
  956. (void)Curl_disconnect(check, /* dead_connection */TRUE);
  957. continue;
  958. }
  959. pipeLen = check->send_pipe.size + check->recv_pipe.size;
  960. if(canpipe) {
  961. if(check->bits.protoconnstart && check->bits.close)
  962. continue;
  963. if(!check->bits.multiplex) {
  964. /* If not multiplexing, make sure the connection is fine for HTTP/1
  965. pipelining */
  966. struct Curl_easy* sh = gethandleathead(&check->send_pipe);
  967. struct Curl_easy* rh = gethandleathead(&check->recv_pipe);
  968. if(sh) {
  969. if(!(IsPipeliningPossible(sh, check) & CURLPIPE_HTTP1))
  970. continue;
  971. }
  972. else if(rh) {
  973. if(!(IsPipeliningPossible(rh, check) & CURLPIPE_HTTP1))
  974. continue;
  975. }
  976. }
  977. }
  978. else {
  979. if(pipeLen > 0) {
  980. /* can only happen within multi handles, and means that another easy
  981. handle is using this connection */
  982. continue;
  983. }
  984. if(Curl_resolver_asynch()) {
  985. /* ip_addr_str[0] is NUL only if the resolving of the name hasn't
  986. completed yet and until then we don't re-use this connection */
  987. if(!check->ip_addr_str[0]) {
  988. infof(data,
  989. "Connection #%ld is still name resolving, can't reuse\n",
  990. check->connection_id);
  991. continue;
  992. }
  993. }
  994. if((check->sock[FIRSTSOCKET] == CURL_SOCKET_BAD) ||
  995. check->bits.close) {
  996. if(!check->bits.close)
  997. foundPendingCandidate = TRUE;
  998. /* Don't pick a connection that hasn't connected yet or that is going
  999. to get closed. */
  1000. infof(data, "Connection #%ld isn't open enough, can't reuse\n",
  1001. check->connection_id);
  1002. #ifdef DEBUGBUILD
  1003. if(check->recv_pipe.size > 0) {
  1004. infof(data,
  1005. "BAD! Unconnected #%ld has a non-empty recv pipeline!\n",
  1006. check->connection_id);
  1007. }
  1008. #endif
  1009. continue;
  1010. }
  1011. }
  1012. #ifdef USE_UNIX_SOCKETS
  1013. if(needle->unix_domain_socket) {
  1014. if(!check->unix_domain_socket)
  1015. continue;
  1016. if(strcmp(needle->unix_domain_socket, check->unix_domain_socket))
  1017. continue;
  1018. if(needle->abstract_unix_socket != check->abstract_unix_socket)
  1019. continue;
  1020. }
  1021. else if(check->unix_domain_socket)
  1022. continue;
  1023. #endif
  1024. if((needle->handler->flags&PROTOPT_SSL) !=
  1025. (check->handler->flags&PROTOPT_SSL))
  1026. /* don't do mixed SSL and non-SSL connections */
  1027. if(get_protocol_family(check->handler->protocol) !=
  1028. needle->handler->protocol || !check->tls_upgraded)
  1029. /* except protocols that have been upgraded via TLS */
  1030. continue;
  1031. if(needle->bits.httpproxy != check->bits.httpproxy ||
  1032. needle->bits.socksproxy != check->bits.socksproxy)
  1033. continue;
  1034. if(needle->bits.socksproxy && !proxy_info_matches(&needle->socks_proxy,
  1035. &check->socks_proxy))
  1036. continue;
  1037. if(needle->bits.conn_to_host != check->bits.conn_to_host)
  1038. /* don't mix connections that use the "connect to host" feature and
  1039. * connections that don't use this feature */
  1040. continue;
  1041. if(needle->bits.conn_to_port != check->bits.conn_to_port)
  1042. /* don't mix connections that use the "connect to port" feature and
  1043. * connections that don't use this feature */
  1044. continue;
  1045. if(needle->bits.httpproxy) {
  1046. if(!proxy_info_matches(&needle->http_proxy, &check->http_proxy))
  1047. continue;
  1048. if(needle->bits.tunnel_proxy != check->bits.tunnel_proxy)
  1049. continue;
  1050. if(needle->http_proxy.proxytype == CURLPROXY_HTTPS) {
  1051. /* use https proxy */
  1052. if(needle->handler->flags&PROTOPT_SSL) {
  1053. /* use double layer ssl */
  1054. if(!Curl_ssl_config_matches(&needle->proxy_ssl_config,
  1055. &check->proxy_ssl_config))
  1056. continue;
  1057. if(check->proxy_ssl[FIRSTSOCKET].state != ssl_connection_complete)
  1058. continue;
  1059. }
  1060. else {
  1061. if(!Curl_ssl_config_matches(&needle->ssl_config,
  1062. &check->ssl_config))
  1063. continue;
  1064. if(check->ssl[FIRSTSOCKET].state != ssl_connection_complete)
  1065. continue;
  1066. }
  1067. }
  1068. }
  1069. if(!canpipe && check->inuse)
  1070. /* this request can't be pipelined but the checked connection is
  1071. already in use so we skip it */
  1072. continue;
  1073. if((check->inuse) && (check->data->multi != needle->data->multi))
  1074. /* this could be subject for pipeline/multiplex use, but only
  1075. if they belong to the same multi handle */
  1076. continue;
  1077. if(needle->localdev || needle->localport) {
  1078. /* If we are bound to a specific local end (IP+port), we must not
  1079. re-use a random other one, although if we didn't ask for a
  1080. particular one we can reuse one that was bound.
  1081. This comparison is a bit rough and too strict. Since the input
  1082. parameters can be specified in numerous ways and still end up the
  1083. same it would take a lot of processing to make it really accurate.
  1084. Instead, this matching will assume that re-uses of bound connections
  1085. will most likely also re-use the exact same binding parameters and
  1086. missing out a few edge cases shouldn't hurt anyone very much.
  1087. */
  1088. if((check->localport != needle->localport) ||
  1089. (check->localportrange != needle->localportrange) ||
  1090. (needle->localdev &&
  1091. (!check->localdev || strcmp(check->localdev, needle->localdev))))
  1092. continue;
  1093. }
  1094. if(!(needle->handler->flags & PROTOPT_CREDSPERREQUEST)) {
  1095. /* This protocol requires credentials per connection,
  1096. so verify that we're using the same name and password as well */
  1097. if(strcmp(needle->user, check->user) ||
  1098. strcmp(needle->passwd, check->passwd)) {
  1099. /* one of them was different */
  1100. continue;
  1101. }
  1102. }
  1103. if(!needle->bits.httpproxy || (needle->handler->flags&PROTOPT_SSL) ||
  1104. needle->bits.tunnel_proxy) {
  1105. /* The requested connection does not use a HTTP proxy or it uses SSL or
  1106. it is a non-SSL protocol tunneled or it is a non-SSL protocol which
  1107. is allowed to be upgraded via TLS */
  1108. if((strcasecompare(needle->handler->scheme, check->handler->scheme) ||
  1109. (get_protocol_family(check->handler->protocol) ==
  1110. needle->handler->protocol && check->tls_upgraded)) &&
  1111. (!needle->bits.conn_to_host || strcasecompare(
  1112. needle->conn_to_host.name, check->conn_to_host.name)) &&
  1113. (!needle->bits.conn_to_port ||
  1114. needle->conn_to_port == check->conn_to_port) &&
  1115. strcasecompare(needle->host.name, check->host.name) &&
  1116. needle->remote_port == check->remote_port) {
  1117. /* The schemes match or the the protocol family is the same and the
  1118. previous connection was TLS upgraded, and the hostname and host
  1119. port match */
  1120. if(needle->handler->flags & PROTOPT_SSL) {
  1121. /* This is a SSL connection so verify that we're using the same
  1122. SSL options as well */
  1123. if(!Curl_ssl_config_matches(&needle->ssl_config,
  1124. &check->ssl_config)) {
  1125. DEBUGF(infof(data,
  1126. "Connection #%ld has different SSL parameters, "
  1127. "can't reuse\n",
  1128. check->connection_id));
  1129. continue;
  1130. }
  1131. if(check->ssl[FIRSTSOCKET].state != ssl_connection_complete) {
  1132. foundPendingCandidate = TRUE;
  1133. DEBUGF(infof(data,
  1134. "Connection #%ld has not started SSL connect, "
  1135. "can't reuse\n",
  1136. check->connection_id));
  1137. continue;
  1138. }
  1139. }
  1140. match = TRUE;
  1141. }
  1142. }
  1143. else {
  1144. /* The requested connection is using the same HTTP proxy in normal
  1145. mode (no tunneling) */
  1146. match = TRUE;
  1147. }
  1148. if(match) {
  1149. #if defined(USE_NTLM)
  1150. /* If we are looking for an HTTP+NTLM connection, check if this is
  1151. already authenticating with the right credentials. If not, keep
  1152. looking so that we can reuse NTLM connections if
  1153. possible. (Especially we must not reuse the same connection if
  1154. partway through a handshake!) */
  1155. if(wantNTLMhttp) {
  1156. if(strcmp(needle->user, check->user) ||
  1157. strcmp(needle->passwd, check->passwd))
  1158. continue;
  1159. }
  1160. else if(check->ntlm.state != NTLMSTATE_NONE) {
  1161. /* Connection is using NTLM auth but we don't want NTLM */
  1162. continue;
  1163. }
  1164. /* Same for Proxy NTLM authentication */
  1165. if(wantProxyNTLMhttp) {
  1166. /* Both check->http_proxy.user and check->http_proxy.passwd can be
  1167. * NULL */
  1168. if(!check->http_proxy.user || !check->http_proxy.passwd)
  1169. continue;
  1170. if(strcmp(needle->http_proxy.user, check->http_proxy.user) ||
  1171. strcmp(needle->http_proxy.passwd, check->http_proxy.passwd))
  1172. continue;
  1173. }
  1174. else if(check->proxyntlm.state != NTLMSTATE_NONE) {
  1175. /* Proxy connection is using NTLM auth but we don't want NTLM */
  1176. continue;
  1177. }
  1178. if(wantNTLMhttp || wantProxyNTLMhttp) {
  1179. /* Credentials are already checked, we can use this connection */
  1180. chosen = check;
  1181. if((wantNTLMhttp &&
  1182. (check->ntlm.state != NTLMSTATE_NONE)) ||
  1183. (wantProxyNTLMhttp &&
  1184. (check->proxyntlm.state != NTLMSTATE_NONE))) {
  1185. /* We must use this connection, no other */
  1186. *force_reuse = TRUE;
  1187. break;
  1188. }
  1189. /* Continue look up for a better connection */
  1190. continue;
  1191. }
  1192. #endif
  1193. if(canpipe) {
  1194. /* We can pipeline if we want to. Let's continue looking for
  1195. the optimal connection to use, i.e the shortest pipe that is not
  1196. blacklisted. */
  1197. if(pipeLen == 0) {
  1198. /* We have the optimal connection. Let's stop looking. */
  1199. chosen = check;
  1200. break;
  1201. }
  1202. /* We can't use the connection if the pipe is full */
  1203. if(max_pipe_len && (pipeLen >= max_pipe_len)) {
  1204. infof(data, "Pipe is full, skip (%zu)\n", pipeLen);
  1205. continue;
  1206. }
  1207. #ifdef USE_NGHTTP2
  1208. /* If multiplexed, make sure we don't go over concurrency limit */
  1209. if(check->bits.multiplex) {
  1210. /* Multiplexed connections can only be HTTP/2 for now */
  1211. struct http_conn *httpc = &check->proto.httpc;
  1212. if(pipeLen >= httpc->settings.max_concurrent_streams) {
  1213. infof(data, "MAX_CONCURRENT_STREAMS reached, skip (%zu)\n",
  1214. pipeLen);
  1215. continue;
  1216. }
  1217. }
  1218. #endif
  1219. /* We can't use the connection if the pipe is penalized */
  1220. if(Curl_pipeline_penalized(data, check)) {
  1221. infof(data, "Penalized, skip\n");
  1222. continue;
  1223. }
  1224. if(max_pipe_len) {
  1225. if(pipeLen < best_pipe_len) {
  1226. /* This connection has a shorter pipe so far. We'll pick this
  1227. and continue searching */
  1228. chosen = check;
  1229. best_pipe_len = pipeLen;
  1230. continue;
  1231. }
  1232. }
  1233. else {
  1234. /* When not pipelining (== multiplexed), we have a match here! */
  1235. chosen = check;
  1236. infof(data, "Multiplexed connection found!\n");
  1237. break;
  1238. }
  1239. }
  1240. else {
  1241. /* We have found a connection. Let's stop searching. */
  1242. chosen = check;
  1243. break;
  1244. }
  1245. }
  1246. }
  1247. }
  1248. if(chosen) {
  1249. /* mark it as used before releasing the lock */
  1250. chosen->inuse = TRUE;
  1251. Curl_conncache_unlock(needle);
  1252. *usethis = chosen;
  1253. return TRUE; /* yes, we found one to use! */
  1254. }
  1255. Curl_conncache_unlock(needle);
  1256. if(foundPendingCandidate && data->set.pipewait) {
  1257. infof(data,
  1258. "Found pending candidate for reuse and CURLOPT_PIPEWAIT is set\n");
  1259. *waitpipe = TRUE;
  1260. }
  1261. return FALSE; /* no matching connecting exists */
  1262. }
  1263. /* after a TCP connection to the proxy has been verified, this function does
  1264. the next magic step.
  1265. Note: this function's sub-functions call failf()
  1266. */
  1267. CURLcode Curl_connected_proxy(struct connectdata *conn, int sockindex)
  1268. {
  1269. CURLcode result = CURLE_OK;
  1270. if(conn->bits.socksproxy) {
  1271. #ifndef CURL_DISABLE_PROXY
  1272. /* for the secondary socket (FTP), use the "connect to host"
  1273. * but ignore the "connect to port" (use the secondary port)
  1274. */
  1275. const char * const host = conn->bits.httpproxy ?
  1276. conn->http_proxy.host.name :
  1277. conn->bits.conn_to_host ?
  1278. conn->conn_to_host.name :
  1279. sockindex == SECONDARYSOCKET ?
  1280. conn->secondaryhostname : conn->host.name;
  1281. const int port = conn->bits.httpproxy ? (int)conn->http_proxy.port :
  1282. sockindex == SECONDARYSOCKET ? conn->secondary_port :
  1283. conn->bits.conn_to_port ? conn->conn_to_port :
  1284. conn->remote_port;
  1285. conn->bits.socksproxy_connecting = TRUE;
  1286. switch(conn->socks_proxy.proxytype) {
  1287. case CURLPROXY_SOCKS5:
  1288. case CURLPROXY_SOCKS5_HOSTNAME:
  1289. result = Curl_SOCKS5(conn->socks_proxy.user, conn->socks_proxy.passwd,
  1290. host, port, sockindex, conn);
  1291. break;
  1292. case CURLPROXY_SOCKS4:
  1293. case CURLPROXY_SOCKS4A:
  1294. result = Curl_SOCKS4(conn->socks_proxy.user, host, port, sockindex,
  1295. conn);
  1296. break;
  1297. default:
  1298. failf(conn->data, "unknown proxytype option given");
  1299. result = CURLE_COULDNT_CONNECT;
  1300. } /* switch proxytype */
  1301. conn->bits.socksproxy_connecting = FALSE;
  1302. #else
  1303. (void)sockindex;
  1304. #endif /* CURL_DISABLE_PROXY */
  1305. }
  1306. return result;
  1307. }
  1308. /*
  1309. * verboseconnect() displays verbose information after a connect
  1310. */
  1311. #ifndef CURL_DISABLE_VERBOSE_STRINGS
  1312. void Curl_verboseconnect(struct connectdata *conn)
  1313. {
  1314. if(conn->data->set.verbose)
  1315. infof(conn->data, "Connected to %s (%s) port %ld (#%ld)\n",
  1316. conn->bits.socksproxy ? conn->socks_proxy.host.dispname :
  1317. conn->bits.httpproxy ? conn->http_proxy.host.dispname :
  1318. conn->bits.conn_to_host ? conn->conn_to_host.dispname :
  1319. conn->host.dispname,
  1320. conn->ip_addr_str, conn->port, conn->connection_id);
  1321. }
  1322. #endif
  1323. int Curl_protocol_getsock(struct connectdata *conn,
  1324. curl_socket_t *socks,
  1325. int numsocks)
  1326. {
  1327. if(conn->handler->proto_getsock)
  1328. return conn->handler->proto_getsock(conn, socks, numsocks);
  1329. return GETSOCK_BLANK;
  1330. }
  1331. int Curl_doing_getsock(struct connectdata *conn,
  1332. curl_socket_t *socks,
  1333. int numsocks)
  1334. {
  1335. if(conn && conn->handler->doing_getsock)
  1336. return conn->handler->doing_getsock(conn, socks, numsocks);
  1337. return GETSOCK_BLANK;
  1338. }
  1339. /*
  1340. * We are doing protocol-specific connecting and this is being called over and
  1341. * over from the multi interface until the connection phase is done on
  1342. * protocol layer.
  1343. */
  1344. CURLcode Curl_protocol_connecting(struct connectdata *conn,
  1345. bool *done)
  1346. {
  1347. CURLcode result = CURLE_OK;
  1348. if(conn && conn->handler->connecting) {
  1349. *done = FALSE;
  1350. result = conn->handler->connecting(conn, done);
  1351. }
  1352. else
  1353. *done = TRUE;
  1354. return result;
  1355. }
  1356. /*
  1357. * We are DOING this is being called over and over from the multi interface
  1358. * until the DOING phase is done on protocol layer.
  1359. */
  1360. CURLcode Curl_protocol_doing(struct connectdata *conn, bool *done)
  1361. {
  1362. CURLcode result = CURLE_OK;
  1363. if(conn && conn->handler->doing) {
  1364. *done = FALSE;
  1365. result = conn->handler->doing(conn, done);
  1366. }
  1367. else
  1368. *done = TRUE;
  1369. return result;
  1370. }
  1371. /*
  1372. * We have discovered that the TCP connection has been successful, we can now
  1373. * proceed with some action.
  1374. *
  1375. */
  1376. CURLcode Curl_protocol_connect(struct connectdata *conn,
  1377. bool *protocol_done)
  1378. {
  1379. CURLcode result = CURLE_OK;
  1380. *protocol_done = FALSE;
  1381. if(conn->bits.tcpconnect[FIRSTSOCKET] && conn->bits.protoconnstart) {
  1382. /* We already are connected, get back. This may happen when the connect
  1383. worked fine in the first call, like when we connect to a local server
  1384. or proxy. Note that we don't know if the protocol is actually done.
  1385. Unless this protocol doesn't have any protocol-connect callback, as
  1386. then we know we're done. */
  1387. if(!conn->handler->connecting)
  1388. *protocol_done = TRUE;
  1389. return CURLE_OK;
  1390. }
  1391. if(!conn->bits.protoconnstart) {
  1392. result = Curl_proxy_connect(conn, FIRSTSOCKET);
  1393. if(result)
  1394. return result;
  1395. if(CONNECT_FIRSTSOCKET_PROXY_SSL())
  1396. /* wait for HTTPS proxy SSL initialization to complete */
  1397. return CURLE_OK;
  1398. if(conn->bits.tunnel_proxy && conn->bits.httpproxy &&
  1399. Curl_connect_ongoing(conn))
  1400. /* when using an HTTP tunnel proxy, await complete tunnel establishment
  1401. before proceeding further. Return CURLE_OK so we'll be called again */
  1402. return CURLE_OK;
  1403. if(conn->handler->connect_it) {
  1404. /* is there a protocol-specific connect() procedure? */
  1405. /* Call the protocol-specific connect function */
  1406. result = conn->handler->connect_it(conn, protocol_done);
  1407. }
  1408. else
  1409. *protocol_done = TRUE;
  1410. /* it has started, possibly even completed but that knowledge isn't stored
  1411. in this bit! */
  1412. if(!result)
  1413. conn->bits.protoconnstart = TRUE;
  1414. }
  1415. return result; /* pass back status */
  1416. }
  1417. /*
  1418. * Helpers for IDNA conversions.
  1419. */
  1420. static bool is_ASCII_name(const char *hostname)
  1421. {
  1422. const unsigned char *ch = (const unsigned char *)hostname;
  1423. while(*ch) {
  1424. if(*ch++ & 0x80)
  1425. return FALSE;
  1426. }
  1427. return TRUE;
  1428. }
  1429. /*
  1430. * Perform any necessary IDN conversion of hostname
  1431. */
  1432. static CURLcode fix_hostname(struct connectdata *conn, struct hostname *host)
  1433. {
  1434. size_t len;
  1435. struct Curl_easy *data = conn->data;
  1436. #ifndef USE_LIBIDN2
  1437. (void)data;
  1438. (void)conn;
  1439. #elif defined(CURL_DISABLE_VERBOSE_STRINGS)
  1440. (void)conn;
  1441. #endif
  1442. /* set the name we use to display the host name */
  1443. host->dispname = host->name;
  1444. len = strlen(host->name);
  1445. if(len && (host->name[len-1] == '.'))
  1446. /* strip off a single trailing dot if present, primarily for SNI but
  1447. there's no use for it */
  1448. host->name[len-1] = 0;
  1449. /* Check name for non-ASCII and convert hostname to ACE form if we can */
  1450. if(!is_ASCII_name(host->name)) {
  1451. #ifdef USE_LIBIDN2
  1452. if(idn2_check_version(IDN2_VERSION)) {
  1453. char *ace_hostname = NULL;
  1454. #if IDN2_VERSION_NUMBER >= 0x00140000
  1455. /* IDN2_NFC_INPUT: Normalize input string using normalization form C.
  1456. IDN2_NONTRANSITIONAL: Perform Unicode TR46 non-transitional
  1457. processing. */
  1458. int flags = IDN2_NFC_INPUT | IDN2_NONTRANSITIONAL;
  1459. #else
  1460. int flags = IDN2_NFC_INPUT;
  1461. #endif
  1462. int rc = idn2_lookup_ul((const char *)host->name, &ace_hostname, flags);
  1463. if(rc == IDN2_OK) {
  1464. host->encalloc = (char *)ace_hostname;
  1465. /* change the name pointer to point to the encoded hostname */
  1466. host->name = host->encalloc;
  1467. }
  1468. else {
  1469. failf(data, "Failed to convert %s to ACE; %s\n", host->name,
  1470. idn2_strerror(rc));
  1471. return CURLE_URL_MALFORMAT;
  1472. }
  1473. }
  1474. #elif defined(USE_WIN32_IDN)
  1475. char *ace_hostname = NULL;
  1476. if(curl_win32_idn_to_ascii(host->name, &ace_hostname)) {
  1477. host->encalloc = ace_hostname;
  1478. /* change the name pointer to point to the encoded hostname */
  1479. host->name = host->encalloc;
  1480. }
  1481. else {
  1482. failf(data, "Failed to convert %s to ACE;\n", host->name);
  1483. return CURLE_URL_MALFORMAT;
  1484. }
  1485. #else
  1486. infof(data, "IDN support not present, can't parse Unicode domains\n");
  1487. #endif
  1488. }
  1489. {
  1490. char *hostp;
  1491. for(hostp = host->name; *hostp; hostp++) {
  1492. if(*hostp <= 32) {
  1493. failf(data, "Host name '%s' contains bad letter", host->name);
  1494. return CURLE_URL_MALFORMAT;
  1495. }
  1496. }
  1497. }
  1498. return CURLE_OK;
  1499. }
  1500. /*
  1501. * Frees data allocated by fix_hostname()
  1502. */
  1503. static void free_fixed_hostname(struct hostname *host)
  1504. {
  1505. #if defined(USE_LIBIDN2)
  1506. if(host->encalloc) {
  1507. idn2_free(host->encalloc); /* must be freed with idn2_free() since this was
  1508. allocated by libidn */
  1509. host->encalloc = NULL;
  1510. }
  1511. #elif defined(USE_WIN32_IDN)
  1512. free(host->encalloc); /* must be freed with free() since this was
  1513. allocated by curl_win32_idn_to_ascii */
  1514. host->encalloc = NULL;
  1515. #else
  1516. (void)host;
  1517. #endif
  1518. }
  1519. static void llist_dtor(void *user, void *element)
  1520. {
  1521. (void)user;
  1522. (void)element;
  1523. /* Do nothing */
  1524. }
  1525. /*
  1526. * Allocate and initialize a new connectdata object.
  1527. */
  1528. static struct connectdata *allocate_conn(struct Curl_easy *data)
  1529. {
  1530. struct connectdata *conn = calloc(1, sizeof(struct connectdata));
  1531. if(!conn)
  1532. return NULL;
  1533. #ifdef USE_SSL
  1534. /* The SSL backend-specific data (ssl_backend_data) objects are allocated as
  1535. a separate array to ensure suitable alignment.
  1536. Note that these backend pointers can be swapped by vtls (eg ssl backend
  1537. data becomes proxy backend data). */
  1538. {
  1539. size_t sslsize = Curl_ssl->sizeof_ssl_backend_data;
  1540. char *ssl = calloc(4, sslsize);
  1541. if(!ssl) {
  1542. free(conn);
  1543. return NULL;
  1544. }
  1545. conn->ssl_extra = ssl;
  1546. conn->ssl[0].backend = (void *)ssl;
  1547. conn->ssl[1].backend = (void *)(ssl + sslsize);
  1548. conn->proxy_ssl[0].backend = (void *)(ssl + 2 * sslsize);
  1549. conn->proxy_ssl[1].backend = (void *)(ssl + 3 * sslsize);
  1550. }
  1551. #endif
  1552. conn->handler = &Curl_handler_dummy; /* Be sure we have a handler defined
  1553. already from start to avoid NULL
  1554. situations and checks */
  1555. /* and we setup a few fields in case we end up actually using this struct */
  1556. conn->sock[FIRSTSOCKET] = CURL_SOCKET_BAD; /* no file descriptor */
  1557. conn->sock[SECONDARYSOCKET] = CURL_SOCKET_BAD; /* no file descriptor */
  1558. conn->tempsock[0] = CURL_SOCKET_BAD; /* no file descriptor */
  1559. conn->tempsock[1] = CURL_SOCKET_BAD; /* no file descriptor */
  1560. conn->connection_id = -1; /* no ID */
  1561. conn->port = -1; /* unknown at this point */
  1562. conn->remote_port = -1; /* unknown at this point */
  1563. #if defined(USE_RECV_BEFORE_SEND_WORKAROUND) && defined(DEBUGBUILD)
  1564. conn->postponed[0].bindsock = CURL_SOCKET_BAD; /* no file descriptor */
  1565. conn->postponed[1].bindsock = CURL_SOCKET_BAD; /* no file descriptor */
  1566. #endif /* USE_RECV_BEFORE_SEND_WORKAROUND && DEBUGBUILD */
  1567. /* Default protocol-independent behavior doesn't support persistent
  1568. connections, so we set this to force-close. Protocols that support
  1569. this need to set this to FALSE in their "curl_do" functions. */
  1570. connclose(conn, "Default to force-close");
  1571. /* Store creation time to help future close decision making */
  1572. conn->created = Curl_now();
  1573. conn->data = data; /* Setup the association between this connection
  1574. and the Curl_easy */
  1575. conn->http_proxy.proxytype = data->set.proxytype;
  1576. conn->socks_proxy.proxytype = CURLPROXY_SOCKS4;
  1577. #ifdef CURL_DISABLE_PROXY
  1578. conn->bits.proxy = FALSE;
  1579. conn->bits.httpproxy = FALSE;
  1580. conn->bits.socksproxy = FALSE;
  1581. conn->bits.proxy_user_passwd = FALSE;
  1582. conn->bits.tunnel_proxy = FALSE;
  1583. #else /* CURL_DISABLE_PROXY */
  1584. /* note that these two proxy bits are now just on what looks to be
  1585. requested, they may be altered down the road */
  1586. conn->bits.proxy = (data->set.str[STRING_PROXY] &&
  1587. *data->set.str[STRING_PROXY]) ? TRUE : FALSE;
  1588. conn->bits.httpproxy = (conn->bits.proxy &&
  1589. (conn->http_proxy.proxytype == CURLPROXY_HTTP ||
  1590. conn->http_proxy.proxytype == CURLPROXY_HTTP_1_0 ||
  1591. conn->http_proxy.proxytype == CURLPROXY_HTTPS)) ?
  1592. TRUE : FALSE;
  1593. conn->bits.socksproxy = (conn->bits.proxy &&
  1594. !conn->bits.httpproxy) ? TRUE : FALSE;
  1595. if(data->set.str[STRING_PRE_PROXY] && *data->set.str[STRING_PRE_PROXY]) {
  1596. conn->bits.proxy = TRUE;
  1597. conn->bits.socksproxy = TRUE;
  1598. }
  1599. conn->bits.proxy_user_passwd =
  1600. (data->set.str[STRING_PROXYUSERNAME]) ? TRUE : FALSE;
  1601. conn->bits.tunnel_proxy = data->set.tunnel_thru_httpproxy;
  1602. #endif /* CURL_DISABLE_PROXY */
  1603. conn->bits.user_passwd = (data->set.str[STRING_USERNAME]) ? TRUE : FALSE;
  1604. conn->bits.ftp_use_epsv = data->set.ftp_use_epsv;
  1605. conn->bits.ftp_use_eprt = data->set.ftp_use_eprt;
  1606. conn->ssl_config.verifystatus = data->set.ssl.primary.verifystatus;
  1607. conn->ssl_config.verifypeer = data->set.ssl.primary.verifypeer;
  1608. conn->ssl_config.verifyhost = data->set.ssl.primary.verifyhost;
  1609. conn->proxy_ssl_config.verifystatus =
  1610. data->set.proxy_ssl.primary.verifystatus;
  1611. conn->proxy_ssl_config.verifypeer = data->set.proxy_ssl.primary.verifypeer;
  1612. conn->proxy_ssl_config.verifyhost = data->set.proxy_ssl.primary.verifyhost;
  1613. conn->ip_version = data->set.ipver;
  1614. #if !defined(CURL_DISABLE_HTTP) && defined(USE_NTLM) && \
  1615. defined(NTLM_WB_ENABLED)
  1616. conn->ntlm_auth_hlpr_socket = CURL_SOCKET_BAD;
  1617. conn->ntlm_auth_hlpr_pid = 0;
  1618. conn->challenge_header = NULL;
  1619. conn->response_header = NULL;
  1620. #endif
  1621. if(Curl_pipeline_wanted(data->multi, CURLPIPE_HTTP1) &&
  1622. !conn->master_buffer) {
  1623. /* Allocate master_buffer to be used for HTTP/1 pipelining */
  1624. conn->master_buffer = calloc(MASTERBUF_SIZE, sizeof(char));
  1625. if(!conn->master_buffer)
  1626. goto error;
  1627. }
  1628. /* Initialize the pipeline lists */
  1629. Curl_llist_init(&conn->send_pipe, (curl_llist_dtor) llist_dtor);
  1630. Curl_llist_init(&conn->recv_pipe, (curl_llist_dtor) llist_dtor);
  1631. #ifdef HAVE_GSSAPI
  1632. conn->data_prot = PROT_CLEAR;
  1633. #endif
  1634. /* Store the local bind parameters that will be used for this connection */
  1635. if(data->set.str[STRING_DEVICE]) {
  1636. conn->localdev = strdup(data->set.str[STRING_DEVICE]);
  1637. if(!conn->localdev)
  1638. goto error;
  1639. }
  1640. conn->localportrange = data->set.localportrange;
  1641. conn->localport = data->set.localport;
  1642. /* the close socket stuff needs to be copied to the connection struct as
  1643. it may live on without (this specific) Curl_easy */
  1644. conn->fclosesocket = data->set.fclosesocket;
  1645. conn->closesocket_client = data->set.closesocket_client;
  1646. return conn;
  1647. error:
  1648. Curl_llist_destroy(&conn->send_pipe, NULL);
  1649. Curl_llist_destroy(&conn->recv_pipe, NULL);
  1650. free(conn->master_buffer);
  1651. free(conn->localdev);
  1652. #ifdef USE_SSL
  1653. free(conn->ssl_extra);
  1654. #endif
  1655. free(conn);
  1656. return NULL;
  1657. }
  1658. static CURLcode findprotocol(struct Curl_easy *data,
  1659. struct connectdata *conn,
  1660. const char *protostr)
  1661. {
  1662. const struct Curl_handler * const *pp;
  1663. const struct Curl_handler *p;
  1664. /* Scan protocol handler table and match against 'protostr' to set a few
  1665. variables based on the URL. Now that the handler may be changed later
  1666. when the protocol specific setup function is called. */
  1667. for(pp = protocols; (p = *pp) != NULL; pp++) {
  1668. if(strcasecompare(p->scheme, protostr)) {
  1669. /* Protocol found in table. Check if allowed */
  1670. if(!(data->set.allowed_protocols & p->protocol))
  1671. /* nope, get out */
  1672. break;
  1673. /* it is allowed for "normal" request, now do an extra check if this is
  1674. the result of a redirect */
  1675. if(data->state.this_is_a_follow &&
  1676. !(data->set.redir_protocols & p->protocol))
  1677. /* nope, get out */
  1678. break;
  1679. /* Perform setup complement if some. */
  1680. conn->handler = conn->given = p;
  1681. /* 'port' and 'remote_port' are set in setup_connection_internals() */
  1682. return CURLE_OK;
  1683. }
  1684. }
  1685. /* The protocol was not found in the table, but we don't have to assign it
  1686. to anything since it is already assigned to a dummy-struct in the
  1687. create_conn() function when the connectdata struct is allocated. */
  1688. failf(data, "Protocol \"%s\" not supported or disabled in " LIBCURL_NAME,
  1689. protostr);
  1690. return CURLE_UNSUPPORTED_PROTOCOL;
  1691. }
  1692. /*
  1693. * Parse URL and fill in the relevant members of the connection struct.
  1694. */
  1695. static CURLcode parseurlandfillconn(struct Curl_easy *data,
  1696. struct connectdata *conn,
  1697. bool *prot_missing,
  1698. char **userp, char **passwdp,
  1699. char **optionsp)
  1700. {
  1701. char *at;
  1702. char *fragment;
  1703. char *path = data->state.path;
  1704. char *query;
  1705. int i;
  1706. int rc;
  1707. const char *protop = "";
  1708. CURLcode result;
  1709. bool rebuild_url = FALSE;
  1710. bool url_has_scheme = FALSE;
  1711. char protobuf[16];
  1712. *prot_missing = FALSE;
  1713. /* We might pass the entire URL into the request so we need to make sure
  1714. * there are no bad characters in there.*/
  1715. if(strpbrk(data->change.url, "\r\n")) {
  1716. failf(data, "Illegal characters found in URL");
  1717. return CURLE_URL_MALFORMAT;
  1718. }
  1719. /*************************************************************
  1720. * Parse the URL.
  1721. *
  1722. * We need to parse the url even when using the proxy, because we will need
  1723. * the hostname and port in case we are trying to SSL connect through the
  1724. * proxy -- and we don't know if we will need to use SSL until we parse the
  1725. * url ...
  1726. ************************************************************/
  1727. if(data->change.url[0] == ':') {
  1728. failf(data, "Bad URL, colon is first character");
  1729. return CURLE_URL_MALFORMAT;
  1730. }
  1731. /* MSDOS/Windows style drive prefix, eg c: in c:foo */
  1732. #define STARTS_WITH_DRIVE_PREFIX(str) \
  1733. ((('a' <= str[0] && str[0] <= 'z') || \
  1734. ('A' <= str[0] && str[0] <= 'Z')) && \
  1735. (str[1] == ':'))
  1736. /* MSDOS/Windows style drive prefix, optionally with
  1737. * a '|' instead of ':', followed by a slash or NUL */
  1738. #define STARTS_WITH_URL_DRIVE_PREFIX(str) \
  1739. ((('a' <= (str)[0] && (str)[0] <= 'z') || \
  1740. ('A' <= (str)[0] && (str)[0] <= 'Z')) && \
  1741. ((str)[1] == ':' || (str)[1] == '|') && \
  1742. ((str)[2] == '/' || (str)[2] == '\\' || (str)[2] == 0))
  1743. /* Don't mistake a drive letter for a scheme if the default protocol is file.
  1744. curld --proto-default file c:/foo/bar.txt */
  1745. if(STARTS_WITH_DRIVE_PREFIX(data->change.url) &&
  1746. data->set.str[STRING_DEFAULT_PROTOCOL] &&
  1747. strcasecompare(data->set.str[STRING_DEFAULT_PROTOCOL], "file")) {
  1748. ; /* do nothing */
  1749. }
  1750. else { /* check for a scheme */
  1751. for(i = 0; i < 16 && data->change.url[i]; ++i) {
  1752. if(data->change.url[i] == '/')
  1753. break;
  1754. if(data->change.url[i] == ':') {
  1755. url_has_scheme = TRUE;
  1756. break;
  1757. }
  1758. }
  1759. }
  1760. /* handle the file: scheme */
  1761. if((url_has_scheme && strncasecompare(data->change.url, "file:", 5)) ||
  1762. (!url_has_scheme && data->set.str[STRING_DEFAULT_PROTOCOL] &&
  1763. strcasecompare(data->set.str[STRING_DEFAULT_PROTOCOL], "file"))) {
  1764. if(url_has_scheme)
  1765. rc = sscanf(data->change.url, "%*15[^\n/:]:%[^\n]", path);
  1766. else
  1767. rc = sscanf(data->change.url, "%[^\n]", path);
  1768. if(rc != 1) {
  1769. failf(data, "Bad URL");
  1770. return CURLE_URL_MALFORMAT;
  1771. }
  1772. if(url_has_scheme && path[0] == '/' && path[1] == '/' &&
  1773. path[2] == '/' && path[3] == '/') {
  1774. /* This appears to be a UNC string (usually indicating a SMB share).
  1775. * We don't do SMB in file: URLs. (TODO?)
  1776. */
  1777. failf(data, "SMB shares are not supported in file: URLs.");
  1778. return CURLE_URL_MALFORMAT;
  1779. }
  1780. /* Extra handling URLs with an authority component (i.e. that start with
  1781. * "file://")
  1782. *
  1783. * We allow omitted hostname (e.g. file:/<path>) -- valid according to
  1784. * RFC 8089, but not the (current) WHAT-WG URL spec.
  1785. */
  1786. if(url_has_scheme && path[0] == '/' && path[1] == '/') {
  1787. /* swallow the two slashes */
  1788. char *ptr = &path[2];
  1789. /*
  1790. * According to RFC 8089, a file: URL can be reliably dereferenced if:
  1791. *
  1792. * o it has no/blank hostname, or
  1793. *
  1794. * o the hostname matches "localhost" (case-insensitively), or
  1795. *
  1796. * o the hostname is a FQDN that resolves to this machine.
  1797. *
  1798. * For brevity, we only consider URLs with empty, "localhost", or
  1799. * "127.0.0.1" hostnames as local.
  1800. *
  1801. * Additionally, there is an exception for URLs with a Windows drive
  1802. * letter in the authority (which was accidentally omitted from RFC 8089
  1803. * Appendix E, but believe me, it was meant to be there. --MK)
  1804. */
  1805. if(ptr[0] != '/' && !STARTS_WITH_URL_DRIVE_PREFIX(ptr)) {
  1806. /* the URL includes a host name, it must match "localhost" or
  1807. "127.0.0.1" to be valid */
  1808. if(!checkprefix("localhost/", ptr) &&
  1809. !checkprefix("127.0.0.1/", ptr)) {
  1810. failf(data, "Invalid file://hostname/, "
  1811. "expected localhost or 127.0.0.1 or none");
  1812. return CURLE_URL_MALFORMAT;
  1813. }
  1814. ptr += 9; /* now points to the slash after the host */
  1815. }
  1816. /*
  1817. * RFC 8089, Appendix D, Section D.1, says:
  1818. *
  1819. * > In a POSIX file system, the root of the file system is represented
  1820. * > as a directory with a zero-length name, usually written as "/"; the
  1821. * > presence of this root in a file URI can be taken as given by the
  1822. * > initial slash in the "path-absolute" rule.
  1823. *
  1824. * i.e. the first slash is part of the path.
  1825. *
  1826. * However in RFC 1738 the "/" between the host (or port) and the
  1827. * URL-path was NOT part of the URL-path. Any agent that followed the
  1828. * older spec strictly, and wanted to refer to a file with an absolute
  1829. * path, would have included a second slash. So if there are two
  1830. * slashes, swallow one.
  1831. */
  1832. if('/' == ptr[1]) /* note: the only way ptr[0]!='/' is if ptr[1]==':' */
  1833. ptr++;
  1834. /* This cannot be done with strcpy, as the memory chunks overlap! */
  1835. memmove(path, ptr, strlen(ptr) + 1);
  1836. }
  1837. #if !defined(MSDOS) && !defined(WIN32) && !defined(__CYGWIN__)
  1838. /* Don't allow Windows drive letters when not in Windows.
  1839. * This catches both "file:/c:" and "file:c:" */
  1840. if(('/' == path[0] && STARTS_WITH_URL_DRIVE_PREFIX(&path[1])) ||
  1841. STARTS_WITH_URL_DRIVE_PREFIX(path)) {
  1842. failf(data, "File drive letters are only accepted in MSDOS/Windows.");
  1843. return CURLE_URL_MALFORMAT;
  1844. }
  1845. #else
  1846. /* If the path starts with a slash and a drive letter, ditch the slash */
  1847. if('/' == path[0] && STARTS_WITH_URL_DRIVE_PREFIX(&path[1])) {
  1848. /* This cannot be done with strcpy, as the memory chunks overlap! */
  1849. memmove(path, &path[1], strlen(&path[1]) + 1);
  1850. }
  1851. #endif
  1852. protop = "file"; /* protocol string */
  1853. *prot_missing = !url_has_scheme;
  1854. }
  1855. else {
  1856. /* clear path */
  1857. char slashbuf[4];
  1858. path[0] = 0;
  1859. rc = sscanf(data->change.url,
  1860. "%15[^\n/:]:%3[/]%[^\n/?#]%[^\n]",
  1861. protobuf, slashbuf, conn->host.name, path);
  1862. if(2 == rc) {
  1863. failf(data, "Bad URL");
  1864. return CURLE_URL_MALFORMAT;
  1865. }
  1866. if(3 > rc) {
  1867. /*
  1868. * The URL was badly formatted, let's try the browser-style _without_
  1869. * protocol specified like 'http://'.
  1870. */
  1871. rc = sscanf(data->change.url, "%[^\n/?#]%[^\n]", conn->host.name, path);
  1872. if(1 > rc) {
  1873. /*
  1874. * We couldn't even get this format.
  1875. * djgpp 2.04 has a sscanf() bug where 'conn->host.name' is
  1876. * assigned, but the return value is EOF!
  1877. */
  1878. #if defined(__DJGPP__) && (DJGPP_MINOR == 4)
  1879. if(!(rc == -1 && *conn->host.name))
  1880. #endif
  1881. {
  1882. failf(data, "<url> malformed");
  1883. return CURLE_URL_MALFORMAT;
  1884. }
  1885. }
  1886. /*
  1887. * Since there was no protocol part specified in the URL use the
  1888. * user-specified default protocol. If we weren't given a default make a
  1889. * guess by matching some protocols against the host's outermost
  1890. * sub-domain name. Finally if there was no match use HTTP.
  1891. */
  1892. protop = data->set.str[STRING_DEFAULT_PROTOCOL];
  1893. if(!protop) {
  1894. /* Note: if you add a new protocol, please update the list in
  1895. * lib/version.c too! */
  1896. if(checkprefix("FTP.", conn->host.name))
  1897. protop = "ftp";
  1898. else if(checkprefix("DICT.", conn->host.name))
  1899. protop = "DICT";
  1900. else if(checkprefix("LDAP.", conn->host.name))
  1901. protop = "LDAP";
  1902. else if(checkprefix("IMAP.", conn->host.name))
  1903. protop = "IMAP";
  1904. else if(checkprefix("SMTP.", conn->host.name))
  1905. protop = "smtp";
  1906. else if(checkprefix("POP3.", conn->host.name))
  1907. protop = "pop3";
  1908. else
  1909. protop = "http";
  1910. }
  1911. *prot_missing = TRUE; /* not given in URL */
  1912. }
  1913. else {
  1914. size_t s = strlen(slashbuf);
  1915. protop = protobuf;
  1916. if(s != 2) {
  1917. infof(data, "Unwillingly accepted illegal URL using %d slash%s!\n",
  1918. s, s>1?"es":"");
  1919. if(data->change.url_alloc)
  1920. free(data->change.url);
  1921. /* repair the URL to use two slashes */
  1922. data->change.url = aprintf("%s://%s%s",
  1923. protobuf, conn->host.name, path);
  1924. if(!data->change.url)
  1925. return CURLE_OUT_OF_MEMORY;
  1926. data->change.url_alloc = TRUE;
  1927. }
  1928. }
  1929. }
  1930. /* We search for '?' in the host name (but only on the right side of a
  1931. * @-letter to allow ?-letters in username and password) to handle things
  1932. * like http://example.com?param= (notice the missing '/').
  1933. */
  1934. at = strchr(conn->host.name, '@');
  1935. if(at)
  1936. query = strchr(at + 1, '?');
  1937. else
  1938. query = strchr(conn->host.name, '?');
  1939. if(query) {
  1940. /* We must insert a slash before the '?'-letter in the URL. If the URL had
  1941. a slash after the '?', that is where the path currently begins and the
  1942. '?string' is still part of the host name.
  1943. We must move the trailing part from the host name and put it first in
  1944. the path. And have it all prefixed with a slash.
  1945. */
  1946. size_t hostlen = strlen(query);
  1947. size_t pathlen = strlen(path);
  1948. /* move the existing path plus the zero byte forward, to make room for
  1949. the host-name part */
  1950. memmove(path + hostlen + 1, path, pathlen + 1);
  1951. /* now copy the trailing host part in front of the existing path */
  1952. memcpy(path + 1, query, hostlen);
  1953. path[0]='/'; /* prepend the missing slash */
  1954. rebuild_url = TRUE;
  1955. *query = 0; /* now cut off the hostname at the ? */
  1956. }
  1957. else if(!path[0]) {
  1958. /* if there's no path set, use a single slash */
  1959. strcpy(path, "/");
  1960. rebuild_url = TRUE;
  1961. }
  1962. /* If the URL is malformatted (missing a '/' after hostname before path) we
  1963. * insert a slash here. The only letters except '/' that can start a path is
  1964. * '?' and '#' - as controlled by the two sscanf() patterns above.
  1965. */
  1966. if(path[0] != '/') {
  1967. /* We need this function to deal with overlapping memory areas. We know
  1968. that the memory area 'path' points to is 'urllen' bytes big and that
  1969. is bigger than the path. Use +1 to move the zero byte too. */
  1970. memmove(&path[1], path, strlen(path) + 1);
  1971. path[0] = '/';
  1972. rebuild_url = TRUE;
  1973. }
  1974. else if(!data->set.path_as_is) {
  1975. /* sanitise paths and remove ../ and ./ sequences according to RFC3986 */
  1976. char *newp = Curl_dedotdotify(path);
  1977. if(!newp)
  1978. return CURLE_OUT_OF_MEMORY;
  1979. if(strcmp(newp, path)) {
  1980. rebuild_url = TRUE;
  1981. free(data->state.pathbuffer);
  1982. data->state.pathbuffer = newp;
  1983. data->state.path = newp;
  1984. path = newp;
  1985. }
  1986. else
  1987. free(newp);
  1988. }
  1989. /*
  1990. * "rebuild_url" means that one or more URL components have been modified so
  1991. * we need to generate an updated full version. We need the corrected URL
  1992. * when communicating over HTTP proxy and we don't know at this point if
  1993. * we're using a proxy or not.
  1994. */
  1995. if(rebuild_url) {
  1996. char *reurl;
  1997. size_t plen = strlen(path); /* new path, should be 1 byte longer than
  1998. the original */
  1999. size_t prefixlen = strlen(conn->host.name);
  2000. if(!*prot_missing) {
  2001. size_t protolen = strlen(protop);
  2002. if(curl_strnequal(protop, data->change.url, protolen))
  2003. prefixlen += protolen;
  2004. else {
  2005. failf(data, "<url> malformed");
  2006. return CURLE_URL_MALFORMAT;
  2007. }
  2008. if(curl_strnequal("://", &data->change.url[protolen], 3))
  2009. prefixlen += 3;
  2010. /* only file: is allowed to omit one or both slashes */
  2011. else if(curl_strnequal("file:", data->change.url, 5))
  2012. prefixlen += 1 + (data->change.url[5] == '/');
  2013. else {
  2014. failf(data, "<url> malformed");
  2015. return CURLE_URL_MALFORMAT;
  2016. }
  2017. }
  2018. reurl = malloc(prefixlen + plen + 1);
  2019. if(!reurl)
  2020. return CURLE_OUT_OF_MEMORY;
  2021. /* copy the prefix */
  2022. memcpy(reurl, data->change.url, prefixlen);
  2023. /* append the trailing piece + zerobyte */
  2024. memcpy(&reurl[prefixlen], path, plen + 1);
  2025. /* possible free the old one */
  2026. if(data->change.url_alloc) {
  2027. Curl_safefree(data->change.url);
  2028. data->change.url_alloc = FALSE;
  2029. }
  2030. infof(data, "Rebuilt URL to: %s\n", reurl);
  2031. data->change.url = reurl;
  2032. data->change.url_alloc = TRUE; /* free this later */
  2033. }
  2034. result = findprotocol(data, conn, protop);
  2035. if(result)
  2036. return result;
  2037. /*
  2038. * Parse the login details from the URL and strip them out of
  2039. * the host name
  2040. */
  2041. result = parse_url_login(data, conn, userp, passwdp, optionsp);
  2042. if(result)
  2043. return result;
  2044. if(conn->host.name[0] == '[') {
  2045. /* This looks like an IPv6 address literal. See if there is an address
  2046. scope if there is no location header */
  2047. char *percent = strchr(conn->host.name, '%');
  2048. if(percent) {
  2049. unsigned int identifier_offset = 3;
  2050. char *endp;
  2051. unsigned long scope;
  2052. if(strncmp("%25", percent, 3) != 0) {
  2053. infof(data,
  2054. "Please URL encode %% as %%25, see RFC 6874.\n");
  2055. identifier_offset = 1;
  2056. }
  2057. scope = strtoul(percent + identifier_offset, &endp, 10);
  2058. if(*endp == ']') {
  2059. /* The address scope was well formed. Knock it out of the
  2060. hostname. */
  2061. memmove(percent, endp, strlen(endp) + 1);
  2062. conn->scope_id = (unsigned int)scope;
  2063. }
  2064. else {
  2065. /* Zone identifier is not numeric */
  2066. #if defined(HAVE_NET_IF_H) && defined(IFNAMSIZ) && defined(HAVE_IF_NAMETOINDEX)
  2067. char ifname[IFNAMSIZ + 2];
  2068. char *square_bracket;
  2069. unsigned int scopeidx = 0;
  2070. strncpy(ifname, percent + identifier_offset, IFNAMSIZ + 2);
  2071. /* Ensure nullbyte termination */
  2072. ifname[IFNAMSIZ + 1] = '\0';
  2073. square_bracket = strchr(ifname, ']');
  2074. if(square_bracket) {
  2075. /* Remove ']' */
  2076. *square_bracket = '\0';
  2077. scopeidx = if_nametoindex(ifname);
  2078. if(scopeidx == 0) {
  2079. infof(data, "Invalid network interface: %s; %s\n", ifname,
  2080. strerror(errno));
  2081. }
  2082. }
  2083. if(scopeidx > 0) {
  2084. char *p = percent + identifier_offset + strlen(ifname);
  2085. /* Remove zone identifier from hostname */
  2086. memmove(percent, p, strlen(p) + 1);
  2087. conn->scope_id = scopeidx;
  2088. }
  2089. else
  2090. #endif /* HAVE_NET_IF_H && IFNAMSIZ */
  2091. infof(data, "Invalid IPv6 address format\n");
  2092. }
  2093. }
  2094. }
  2095. if(data->set.scope_id)
  2096. /* Override any scope that was set above. */
  2097. conn->scope_id = data->set.scope_id;
  2098. /* Remove the fragment part of the path. Per RFC 2396, this is always the
  2099. last part of the URI. We are looking for the first '#' so that we deal
  2100. gracefully with non conformant URI such as http://example.com#foo#bar. */
  2101. fragment = strchr(path, '#');
  2102. if(fragment) {
  2103. *fragment = 0;
  2104. /* we know the path part ended with a fragment, so we know the full URL
  2105. string does too and we need to cut it off from there so it isn't used
  2106. over proxy */
  2107. fragment = strchr(data->change.url, '#');
  2108. if(fragment)
  2109. *fragment = 0;
  2110. }
  2111. /*
  2112. * So if the URL was A://B/C#D,
  2113. * protop is A
  2114. * conn->host.name is B
  2115. * data->state.path is /C
  2116. */
  2117. return CURLE_OK;
  2118. }
  2119. /*
  2120. * If we're doing a resumed transfer, we need to setup our stuff
  2121. * properly.
  2122. */
  2123. static CURLcode setup_range(struct Curl_easy *data)
  2124. {
  2125. struct UrlState *s = &data->state;
  2126. s->resume_from = data->set.set_resume_from;
  2127. if(s->resume_from || data->set.str[STRING_SET_RANGE]) {
  2128. if(s->rangestringalloc)
  2129. free(s->range);
  2130. if(s->resume_from)
  2131. s->range = aprintf("%" CURL_FORMAT_CURL_OFF_TU "-", s->resume_from);
  2132. else
  2133. s->range = strdup(data->set.str[STRING_SET_RANGE]);
  2134. s->rangestringalloc = (s->range) ? TRUE : FALSE;
  2135. if(!s->range)
  2136. return CURLE_OUT_OF_MEMORY;
  2137. /* tell ourselves to fetch this range */
  2138. s->use_range = TRUE; /* enable range download */
  2139. }
  2140. else
  2141. s->use_range = FALSE; /* disable range download */
  2142. return CURLE_OK;
  2143. }
  2144. /*
  2145. * setup_connection_internals() -
  2146. *
  2147. * Setup connection internals specific to the requested protocol in the
  2148. * Curl_easy. This is inited and setup before the connection is made but
  2149. * is about the particular protocol that is to be used.
  2150. *
  2151. * This MUST get called after proxy magic has been figured out.
  2152. */
  2153. static CURLcode setup_connection_internals(struct connectdata *conn)
  2154. {
  2155. const struct Curl_handler * p;
  2156. CURLcode result;
  2157. struct Curl_easy *data = conn->data;
  2158. /* in some case in the multi state-machine, we go back to the CONNECT state
  2159. and then a second (or third or...) call to this function will be made
  2160. without doing a DISCONNECT or DONE in between (since the connection is
  2161. yet in place) and therefore this function needs to first make sure
  2162. there's no lingering previous data allocated. */
  2163. Curl_free_request_state(data);
  2164. memset(&data->req, 0, sizeof(struct SingleRequest));
  2165. data->req.maxdownload = -1;
  2166. conn->socktype = SOCK_STREAM; /* most of them are TCP streams */
  2167. /* Perform setup complement if some. */
  2168. p = conn->handler;
  2169. if(p->setup_connection) {
  2170. result = (*p->setup_connection)(conn);
  2171. if(result)
  2172. return result;
  2173. p = conn->handler; /* May have changed. */
  2174. }
  2175. if(conn->port < 0)
  2176. /* we check for -1 here since if proxy was detected already, this
  2177. was very likely already set to the proxy port */
  2178. conn->port = p->defport;
  2179. return CURLE_OK;
  2180. }
  2181. /*
  2182. * Curl_free_request_state() should free temp data that was allocated in the
  2183. * Curl_easy for this single request.
  2184. */
  2185. void Curl_free_request_state(struct Curl_easy *data)
  2186. {
  2187. Curl_safefree(data->req.protop);
  2188. Curl_safefree(data->req.newurl);
  2189. }
  2190. #ifndef CURL_DISABLE_PROXY
  2191. /****************************************************************
  2192. * Checks if the host is in the noproxy list. returns true if it matches
  2193. * and therefore the proxy should NOT be used.
  2194. ****************************************************************/
  2195. static bool check_noproxy(const char *name, const char *no_proxy)
  2196. {
  2197. /* no_proxy=domain1.dom,host.domain2.dom
  2198. * (a comma-separated list of hosts which should
  2199. * not be proxied, or an asterisk to override
  2200. * all proxy variables)
  2201. */
  2202. size_t tok_start;
  2203. size_t tok_end;
  2204. const char *separator = ", ";
  2205. size_t no_proxy_len;
  2206. size_t namelen;
  2207. char *endptr;
  2208. if(no_proxy && no_proxy[0]) {
  2209. if(strcasecompare("*", no_proxy)) {
  2210. return TRUE;
  2211. }
  2212. /* NO_PROXY was specified and it wasn't just an asterisk */
  2213. no_proxy_len = strlen(no_proxy);
  2214. endptr = strchr(name, ':');
  2215. if(endptr)
  2216. namelen = endptr - name;
  2217. else
  2218. namelen = strlen(name);
  2219. for(tok_start = 0; tok_start < no_proxy_len; tok_start = tok_end + 1) {
  2220. while(tok_start < no_proxy_len &&
  2221. strchr(separator, no_proxy[tok_start]) != NULL) {
  2222. /* Look for the beginning of the token. */
  2223. ++tok_start;
  2224. }
  2225. if(tok_start == no_proxy_len)
  2226. break; /* It was all trailing separator chars, no more tokens. */
  2227. for(tok_end = tok_start; tok_end < no_proxy_len &&
  2228. strchr(separator, no_proxy[tok_end]) == NULL; ++tok_end)
  2229. /* Look for the end of the token. */
  2230. ;
  2231. /* To match previous behaviour, where it was necessary to specify
  2232. * ".local.com" to prevent matching "notlocal.com", we will leave
  2233. * the '.' off.
  2234. */
  2235. if(no_proxy[tok_start] == '.')
  2236. ++tok_start;
  2237. if((tok_end - tok_start) <= namelen) {
  2238. /* Match the last part of the name to the domain we are checking. */
  2239. const char *checkn = name + namelen - (tok_end - tok_start);
  2240. if(strncasecompare(no_proxy + tok_start, checkn,
  2241. tok_end - tok_start)) {
  2242. if((tok_end - tok_start) == namelen || *(checkn - 1) == '.') {
  2243. /* We either have an exact match, or the previous character is a .
  2244. * so it is within the same domain, so no proxy for this host.
  2245. */
  2246. return TRUE;
  2247. }
  2248. }
  2249. } /* if((tok_end - tok_start) <= namelen) */
  2250. } /* for(tok_start = 0; tok_start < no_proxy_len;
  2251. tok_start = tok_end + 1) */
  2252. } /* NO_PROXY was specified and it wasn't just an asterisk */
  2253. return FALSE;
  2254. }
  2255. #ifndef CURL_DISABLE_HTTP
  2256. /****************************************************************
  2257. * Detect what (if any) proxy to use. Remember that this selects a host
  2258. * name and is not limited to HTTP proxies only.
  2259. * The returned pointer must be freed by the caller (unless NULL)
  2260. ****************************************************************/
  2261. static char *detect_proxy(struct connectdata *conn)
  2262. {
  2263. char *proxy = NULL;
  2264. /* If proxy was not specified, we check for default proxy environment
  2265. * variables, to enable i.e Lynx compliance:
  2266. *
  2267. * http_proxy=http://some.server.dom:port/
  2268. * https_proxy=http://some.server.dom:port/
  2269. * ftp_proxy=http://some.server.dom:port/
  2270. * no_proxy=domain1.dom,host.domain2.dom
  2271. * (a comma-separated list of hosts which should
  2272. * not be proxied, or an asterisk to override
  2273. * all proxy variables)
  2274. * all_proxy=http://some.server.dom:port/
  2275. * (seems to exist for the CERN www lib. Probably
  2276. * the first to check for.)
  2277. *
  2278. * For compatibility, the all-uppercase versions of these variables are
  2279. * checked if the lowercase versions don't exist.
  2280. */
  2281. char proxy_env[128];
  2282. const char *protop = conn->handler->scheme;
  2283. char *envp = proxy_env;
  2284. char *prox;
  2285. /* Now, build <protocol>_proxy and check for such a one to use */
  2286. while(*protop)
  2287. *envp++ = (char)tolower((int)*protop++);
  2288. /* append _proxy */
  2289. strcpy(envp, "_proxy");
  2290. /* read the protocol proxy: */
  2291. prox = curl_getenv(proxy_env);
  2292. /*
  2293. * We don't try the uppercase version of HTTP_PROXY because of
  2294. * security reasons:
  2295. *
  2296. * When curl is used in a webserver application
  2297. * environment (cgi or php), this environment variable can
  2298. * be controlled by the web server user by setting the
  2299. * http header 'Proxy:' to some value.
  2300. *
  2301. * This can cause 'internal' http/ftp requests to be
  2302. * arbitrarily redirected by any external attacker.
  2303. */
  2304. if(!prox && !strcasecompare("http_proxy", proxy_env)) {
  2305. /* There was no lowercase variable, try the uppercase version: */
  2306. Curl_strntoupper(proxy_env, proxy_env, sizeof(proxy_env));
  2307. prox = curl_getenv(proxy_env);
  2308. }
  2309. if(prox)
  2310. proxy = prox; /* use this */
  2311. else {
  2312. proxy = curl_getenv("all_proxy"); /* default proxy to use */
  2313. if(!proxy)
  2314. proxy = curl_getenv("ALL_PROXY");
  2315. }
  2316. return proxy;
  2317. }
  2318. #endif /* CURL_DISABLE_HTTP */
  2319. /*
  2320. * If this is supposed to use a proxy, we need to figure out the proxy
  2321. * host name, so that we can re-use an existing connection
  2322. * that may exist registered to the same proxy host.
  2323. */
  2324. static CURLcode parse_proxy(struct Curl_easy *data,
  2325. struct connectdata *conn, char *proxy,
  2326. curl_proxytype proxytype)
  2327. {
  2328. char *prox_portno;
  2329. char *endofprot;
  2330. /* We use 'proxyptr' to point to the proxy name from now on... */
  2331. char *proxyptr;
  2332. char *portptr;
  2333. char *atsign;
  2334. long port = -1;
  2335. char *proxyuser = NULL;
  2336. char *proxypasswd = NULL;
  2337. bool sockstype;
  2338. /* We do the proxy host string parsing here. We want the host name and the
  2339. * port name. Accept a protocol:// prefix
  2340. */
  2341. /* Parse the protocol part if present */
  2342. endofprot = strstr(proxy, "://");
  2343. if(endofprot) {
  2344. proxyptr = endofprot + 3;
  2345. if(checkprefix("https", proxy))
  2346. proxytype = CURLPROXY_HTTPS;
  2347. else if(checkprefix("socks5h", proxy))
  2348. proxytype = CURLPROXY_SOCKS5_HOSTNAME;
  2349. else if(checkprefix("socks5", proxy))
  2350. proxytype = CURLPROXY_SOCKS5;
  2351. else if(checkprefix("socks4a", proxy))
  2352. proxytype = CURLPROXY_SOCKS4A;
  2353. else if(checkprefix("socks4", proxy) || checkprefix("socks", proxy))
  2354. proxytype = CURLPROXY_SOCKS4;
  2355. else if(checkprefix("http:", proxy))
  2356. ; /* leave it as HTTP or HTTP/1.0 */
  2357. else {
  2358. /* Any other xxx:// reject! */
  2359. failf(data, "Unsupported proxy scheme for \'%s\'", proxy);
  2360. return CURLE_COULDNT_CONNECT;
  2361. }
  2362. }
  2363. else
  2364. proxyptr = proxy; /* No xxx:// head: It's a HTTP proxy */
  2365. #ifdef USE_SSL
  2366. if(!Curl_ssl->support_https_proxy)
  2367. #endif
  2368. if(proxytype == CURLPROXY_HTTPS) {
  2369. failf(data, "Unsupported proxy \'%s\', libcurl is built without the "
  2370. "HTTPS-proxy support.", proxy);
  2371. return CURLE_NOT_BUILT_IN;
  2372. }
  2373. sockstype = proxytype == CURLPROXY_SOCKS5_HOSTNAME ||
  2374. proxytype == CURLPROXY_SOCKS5 ||
  2375. proxytype == CURLPROXY_SOCKS4A ||
  2376. proxytype == CURLPROXY_SOCKS4;
  2377. /* Is there a username and password given in this proxy url? */
  2378. atsign = strchr(proxyptr, '@');
  2379. if(atsign) {
  2380. CURLcode result =
  2381. Curl_parse_login_details(proxyptr, atsign - proxyptr,
  2382. &proxyuser, &proxypasswd, NULL);
  2383. if(result)
  2384. return result;
  2385. proxyptr = atsign + 1;
  2386. }
  2387. /* start scanning for port number at this point */
  2388. portptr = proxyptr;
  2389. /* detect and extract RFC6874-style IPv6-addresses */
  2390. if(*proxyptr == '[') {
  2391. char *ptr = ++proxyptr; /* advance beyond the initial bracket */
  2392. while(*ptr && (ISXDIGIT(*ptr) || (*ptr == ':') || (*ptr == '.')))
  2393. ptr++;
  2394. if(*ptr == '%') {
  2395. /* There might be a zone identifier */
  2396. if(strncmp("%25", ptr, 3))
  2397. infof(data, "Please URL encode %% as %%25, see RFC 6874.\n");
  2398. ptr++;
  2399. /* Allow unreserved characters as defined in RFC 3986 */
  2400. while(*ptr && (ISALPHA(*ptr) || ISXDIGIT(*ptr) || (*ptr == '-') ||
  2401. (*ptr == '.') || (*ptr == '_') || (*ptr == '~')))
  2402. ptr++;
  2403. }
  2404. if(*ptr == ']')
  2405. /* yeps, it ended nicely with a bracket as well */
  2406. *ptr++ = 0;
  2407. else
  2408. infof(data, "Invalid IPv6 address format\n");
  2409. portptr = ptr;
  2410. /* Note that if this didn't end with a bracket, we still advanced the
  2411. * proxyptr first, but I can't see anything wrong with that as no host
  2412. * name nor a numeric can legally start with a bracket.
  2413. */
  2414. }
  2415. /* Get port number off proxy.server.com:1080 */
  2416. prox_portno = strchr(portptr, ':');
  2417. if(prox_portno) {
  2418. char *endp = NULL;
  2419. *prox_portno = 0x0; /* cut off number from host name */
  2420. prox_portno ++;
  2421. /* now set the local port number */
  2422. port = strtol(prox_portno, &endp, 10);
  2423. if((endp && *endp && (*endp != '/') && (*endp != ' ')) ||
  2424. (port < 0) || (port > 65535)) {
  2425. /* meant to detect for example invalid IPv6 numerical addresses without
  2426. brackets: "2a00:fac0:a000::7:13". Accept a trailing slash only
  2427. because we then allow "URL style" with the number followed by a
  2428. slash, used in curl test cases already. Space is also an acceptable
  2429. terminating symbol. */
  2430. infof(data, "No valid port number in proxy string (%s)\n",
  2431. prox_portno);
  2432. }
  2433. else
  2434. conn->port = port;
  2435. }
  2436. else {
  2437. if(proxyptr[0]=='/') {
  2438. /* If the first character in the proxy string is a slash, fail
  2439. immediately. The following code will otherwise clear the string which
  2440. will lead to code running as if no proxy was set! */
  2441. Curl_safefree(proxyuser);
  2442. Curl_safefree(proxypasswd);
  2443. return CURLE_COULDNT_RESOLVE_PROXY;
  2444. }
  2445. /* without a port number after the host name, some people seem to use
  2446. a slash so we strip everything from the first slash */
  2447. atsign = strchr(proxyptr, '/');
  2448. if(atsign)
  2449. *atsign = '\0'; /* cut off path part from host name */
  2450. if(data->set.proxyport)
  2451. /* None given in the proxy string, then get the default one if it is
  2452. given */
  2453. port = data->set.proxyport;
  2454. else {
  2455. if(proxytype == CURLPROXY_HTTPS)
  2456. port = CURL_DEFAULT_HTTPS_PROXY_PORT;
  2457. else
  2458. port = CURL_DEFAULT_PROXY_PORT;
  2459. }
  2460. }
  2461. if(*proxyptr) {
  2462. struct proxy_info *proxyinfo =
  2463. sockstype ? &conn->socks_proxy : &conn->http_proxy;
  2464. proxyinfo->proxytype = proxytype;
  2465. if(proxyuser) {
  2466. /* found user and password, rip them out. note that we are unescaping
  2467. them, as there is otherwise no way to have a username or password
  2468. with reserved characters like ':' in them. */
  2469. Curl_safefree(proxyinfo->user);
  2470. proxyinfo->user = curl_easy_unescape(data, proxyuser, 0, NULL);
  2471. Curl_safefree(proxyuser);
  2472. if(!proxyinfo->user) {
  2473. Curl_safefree(proxypasswd);
  2474. return CURLE_OUT_OF_MEMORY;
  2475. }
  2476. Curl_safefree(proxyinfo->passwd);
  2477. if(proxypasswd && strlen(proxypasswd) < MAX_CURL_PASSWORD_LENGTH)
  2478. proxyinfo->passwd = curl_easy_unescape(data, proxypasswd, 0, NULL);
  2479. else
  2480. proxyinfo->passwd = strdup("");
  2481. Curl_safefree(proxypasswd);
  2482. if(!proxyinfo->passwd)
  2483. return CURLE_OUT_OF_MEMORY;
  2484. conn->bits.proxy_user_passwd = TRUE; /* enable it */
  2485. }
  2486. if(port >= 0) {
  2487. proxyinfo->port = port;
  2488. if(conn->port < 0 || sockstype || !conn->socks_proxy.host.rawalloc)
  2489. conn->port = port;
  2490. }
  2491. /* now, clone the cleaned proxy host name */
  2492. Curl_safefree(proxyinfo->host.rawalloc);
  2493. proxyinfo->host.rawalloc = strdup(proxyptr);
  2494. proxyinfo->host.name = proxyinfo->host.rawalloc;
  2495. if(!proxyinfo->host.rawalloc)
  2496. return CURLE_OUT_OF_MEMORY;
  2497. }
  2498. Curl_safefree(proxyuser);
  2499. Curl_safefree(proxypasswd);
  2500. return CURLE_OK;
  2501. }
  2502. /*
  2503. * Extract the user and password from the authentication string
  2504. */
  2505. static CURLcode parse_proxy_auth(struct Curl_easy *data,
  2506. struct connectdata *conn)
  2507. {
  2508. char proxyuser[MAX_CURL_USER_LENGTH]="";
  2509. char proxypasswd[MAX_CURL_PASSWORD_LENGTH]="";
  2510. CURLcode result;
  2511. if(data->set.str[STRING_PROXYUSERNAME] != NULL) {
  2512. strncpy(proxyuser, data->set.str[STRING_PROXYUSERNAME],
  2513. MAX_CURL_USER_LENGTH);
  2514. proxyuser[MAX_CURL_USER_LENGTH-1] = '\0'; /*To be on safe side*/
  2515. }
  2516. if(data->set.str[STRING_PROXYPASSWORD] != NULL) {
  2517. strncpy(proxypasswd, data->set.str[STRING_PROXYPASSWORD],
  2518. MAX_CURL_PASSWORD_LENGTH);
  2519. proxypasswd[MAX_CURL_PASSWORD_LENGTH-1] = '\0'; /*To be on safe side*/
  2520. }
  2521. result = Curl_urldecode(data, proxyuser, 0, &conn->http_proxy.user, NULL,
  2522. FALSE);
  2523. if(!result)
  2524. result = Curl_urldecode(data, proxypasswd, 0, &conn->http_proxy.passwd,
  2525. NULL, FALSE);
  2526. return result;
  2527. }
  2528. /* create_conn helper to parse and init proxy values. to be called after unix
  2529. socket init but before any proxy vars are evaluated. */
  2530. static CURLcode create_conn_helper_init_proxy(struct connectdata *conn)
  2531. {
  2532. char *proxy = NULL;
  2533. char *socksproxy = NULL;
  2534. char *no_proxy = NULL;
  2535. CURLcode result = CURLE_OK;
  2536. struct Curl_easy *data = conn->data;
  2537. /*************************************************************
  2538. * Extract the user and password from the authentication string
  2539. *************************************************************/
  2540. if(conn->bits.proxy_user_passwd) {
  2541. result = parse_proxy_auth(data, conn);
  2542. if(result)
  2543. goto out;
  2544. }
  2545. /*************************************************************
  2546. * Detect what (if any) proxy to use
  2547. *************************************************************/
  2548. if(data->set.str[STRING_PROXY]) {
  2549. proxy = strdup(data->set.str[STRING_PROXY]);
  2550. /* if global proxy is set, this is it */
  2551. if(NULL == proxy) {
  2552. failf(data, "memory shortage");
  2553. result = CURLE_OUT_OF_MEMORY;
  2554. goto out;
  2555. }
  2556. }
  2557. if(data->set.str[STRING_PRE_PROXY]) {
  2558. socksproxy = strdup(data->set.str[STRING_PRE_PROXY]);
  2559. /* if global socks proxy is set, this is it */
  2560. if(NULL == socksproxy) {
  2561. failf(data, "memory shortage");
  2562. result = CURLE_OUT_OF_MEMORY;
  2563. goto out;
  2564. }
  2565. }
  2566. if(!data->set.str[STRING_NOPROXY]) {
  2567. no_proxy = curl_getenv("no_proxy");
  2568. if(!no_proxy)
  2569. no_proxy = curl_getenv("NO_PROXY");
  2570. }
  2571. if(check_noproxy(conn->host.name, data->set.str[STRING_NOPROXY] ?
  2572. data->set.str[STRING_NOPROXY] : no_proxy)) {
  2573. Curl_safefree(proxy);
  2574. Curl_safefree(socksproxy);
  2575. }
  2576. #ifndef CURL_DISABLE_HTTP
  2577. else if(!proxy && !socksproxy)
  2578. /* if the host is not in the noproxy list, detect proxy. */
  2579. proxy = detect_proxy(conn);
  2580. #endif /* CURL_DISABLE_HTTP */
  2581. Curl_safefree(no_proxy);
  2582. #ifdef USE_UNIX_SOCKETS
  2583. /* For the time being do not mix proxy and unix domain sockets. See #1274 */
  2584. if(proxy && conn->unix_domain_socket) {
  2585. free(proxy);
  2586. proxy = NULL;
  2587. }
  2588. #endif
  2589. if(proxy && (!*proxy || (conn->handler->flags & PROTOPT_NONETWORK))) {
  2590. free(proxy); /* Don't bother with an empty proxy string or if the
  2591. protocol doesn't work with network */
  2592. proxy = NULL;
  2593. }
  2594. if(socksproxy && (!*socksproxy ||
  2595. (conn->handler->flags & PROTOPT_NONETWORK))) {
  2596. free(socksproxy); /* Don't bother with an empty socks proxy string or if
  2597. the protocol doesn't work with network */
  2598. socksproxy = NULL;
  2599. }
  2600. /***********************************************************************
  2601. * If this is supposed to use a proxy, we need to figure out the proxy host
  2602. * name, proxy type and port number, so that we can re-use an existing
  2603. * connection that may exist registered to the same proxy host.
  2604. ***********************************************************************/
  2605. if(proxy || socksproxy) {
  2606. if(proxy) {
  2607. result = parse_proxy(data, conn, proxy, conn->http_proxy.proxytype);
  2608. Curl_safefree(proxy); /* parse_proxy copies the proxy string */
  2609. if(result)
  2610. goto out;
  2611. }
  2612. if(socksproxy) {
  2613. result = parse_proxy(data, conn, socksproxy,
  2614. conn->socks_proxy.proxytype);
  2615. /* parse_proxy copies the socks proxy string */
  2616. Curl_safefree(socksproxy);
  2617. if(result)
  2618. goto out;
  2619. }
  2620. if(conn->http_proxy.host.rawalloc) {
  2621. #ifdef CURL_DISABLE_HTTP
  2622. /* asking for a HTTP proxy is a bit funny when HTTP is disabled... */
  2623. result = CURLE_UNSUPPORTED_PROTOCOL;
  2624. goto out;
  2625. #else
  2626. /* force this connection's protocol to become HTTP if compatible */
  2627. if(!(conn->handler->protocol & PROTO_FAMILY_HTTP)) {
  2628. if((conn->handler->flags & PROTOPT_PROXY_AS_HTTP) &&
  2629. !conn->bits.tunnel_proxy)
  2630. conn->handler = &Curl_handler_http;
  2631. else
  2632. /* if not converting to HTTP over the proxy, enforce tunneling */
  2633. conn->bits.tunnel_proxy = TRUE;
  2634. }
  2635. conn->bits.httpproxy = TRUE;
  2636. #endif
  2637. }
  2638. else {
  2639. conn->bits.httpproxy = FALSE; /* not a HTTP proxy */
  2640. conn->bits.tunnel_proxy = FALSE; /* no tunneling if not HTTP */
  2641. }
  2642. if(conn->socks_proxy.host.rawalloc) {
  2643. if(!conn->http_proxy.host.rawalloc) {
  2644. /* once a socks proxy */
  2645. if(!conn->socks_proxy.user) {
  2646. conn->socks_proxy.user = conn->http_proxy.user;
  2647. conn->http_proxy.user = NULL;
  2648. Curl_safefree(conn->socks_proxy.passwd);
  2649. conn->socks_proxy.passwd = conn->http_proxy.passwd;
  2650. conn->http_proxy.passwd = NULL;
  2651. }
  2652. }
  2653. conn->bits.socksproxy = TRUE;
  2654. }
  2655. else
  2656. conn->bits.socksproxy = FALSE; /* not a socks proxy */
  2657. }
  2658. else {
  2659. conn->bits.socksproxy = FALSE;
  2660. conn->bits.httpproxy = FALSE;
  2661. }
  2662. conn->bits.proxy = conn->bits.httpproxy || conn->bits.socksproxy;
  2663. if(!conn->bits.proxy) {
  2664. /* we aren't using the proxy after all... */
  2665. conn->bits.proxy = FALSE;
  2666. conn->bits.httpproxy = FALSE;
  2667. conn->bits.socksproxy = FALSE;
  2668. conn->bits.proxy_user_passwd = FALSE;
  2669. conn->bits.tunnel_proxy = FALSE;
  2670. }
  2671. out:
  2672. free(socksproxy);
  2673. free(proxy);
  2674. return result;
  2675. }
  2676. #endif /* CURL_DISABLE_PROXY */
  2677. /*
  2678. * parse_url_login()
  2679. *
  2680. * Parse the login details (user name, password and options) from the URL and
  2681. * strip them out of the host name
  2682. *
  2683. * Inputs: data->set.use_netrc (CURLOPT_NETRC)
  2684. * conn->host.name
  2685. *
  2686. * Outputs: (almost :- all currently undefined)
  2687. * conn->bits.user_passwd - non-zero if non-default passwords exist
  2688. * user - non-zero length if defined
  2689. * passwd - non-zero length if defined
  2690. * options - non-zero length if defined
  2691. * conn->host.name - remove user name and password
  2692. */
  2693. static CURLcode parse_url_login(struct Curl_easy *data,
  2694. struct connectdata *conn,
  2695. char **user, char **passwd, char **options)
  2696. {
  2697. CURLcode result = CURLE_OK;
  2698. char *userp = NULL;
  2699. char *passwdp = NULL;
  2700. char *optionsp = NULL;
  2701. /* At this point, we're hoping all the other special cases have
  2702. * been taken care of, so conn->host.name is at most
  2703. * [user[:password][;options]]@]hostname
  2704. *
  2705. * We need somewhere to put the embedded details, so do that first.
  2706. */
  2707. char *ptr = strchr(conn->host.name, '@');
  2708. char *login = conn->host.name;
  2709. DEBUGASSERT(!**user);
  2710. DEBUGASSERT(!**passwd);
  2711. DEBUGASSERT(!**options);
  2712. DEBUGASSERT(conn->handler);
  2713. if(!ptr)
  2714. goto out;
  2715. /* We will now try to extract the
  2716. * possible login information in a string like:
  2717. * ftp://user:password@ftp.my.site:8021/README */
  2718. conn->host.name = ++ptr;
  2719. /* So the hostname is sane. Only bother interpreting the
  2720. * results if we could care. It could still be wasted
  2721. * work because it might be overtaken by the programmatically
  2722. * set user/passwd, but doing that first adds more cases here :-(
  2723. */
  2724. if(data->set.use_netrc == CURL_NETRC_REQUIRED)
  2725. goto out;
  2726. /* We could use the login information in the URL so extract it. Only parse
  2727. options if the handler says we should. */
  2728. result =
  2729. Curl_parse_login_details(login, ptr - login - 1,
  2730. &userp, &passwdp,
  2731. (conn->handler->flags & PROTOPT_URLOPTIONS)?
  2732. &optionsp:NULL);
  2733. if(result)
  2734. goto out;
  2735. if(userp) {
  2736. char *newname;
  2737. /* We have a user in the URL */
  2738. conn->bits.userpwd_in_url = TRUE;
  2739. conn->bits.user_passwd = TRUE; /* enable user+password */
  2740. /* Decode the user */
  2741. result = Curl_urldecode(data, userp, 0, &newname, NULL, FALSE);
  2742. if(result) {
  2743. goto out;
  2744. }
  2745. free(*user);
  2746. *user = newname;
  2747. }
  2748. if(passwdp) {
  2749. /* We have a password in the URL so decode it */
  2750. char *newpasswd;
  2751. result = Curl_urldecode(data, passwdp, 0, &newpasswd, NULL, FALSE);
  2752. if(result) {
  2753. goto out;
  2754. }
  2755. free(*passwd);
  2756. *passwd = newpasswd;
  2757. }
  2758. if(optionsp) {
  2759. /* We have an options list in the URL so decode it */
  2760. char *newoptions;
  2761. result = Curl_urldecode(data, optionsp, 0, &newoptions, NULL, FALSE);
  2762. if(result) {
  2763. goto out;
  2764. }
  2765. free(*options);
  2766. *options = newoptions;
  2767. }
  2768. out:
  2769. free(userp);
  2770. free(passwdp);
  2771. free(optionsp);
  2772. return result;
  2773. }
  2774. /*
  2775. * Curl_parse_login_details()
  2776. *
  2777. * This is used to parse a login string for user name, password and options in
  2778. * the following formats:
  2779. *
  2780. * user
  2781. * user:password
  2782. * user:password;options
  2783. * user;options
  2784. * user;options:password
  2785. * :password
  2786. * :password;options
  2787. * ;options
  2788. * ;options:password
  2789. *
  2790. * Parameters:
  2791. *
  2792. * login [in] - The login string.
  2793. * len [in] - The length of the login string.
  2794. * userp [in/out] - The address where a pointer to newly allocated memory
  2795. * holding the user will be stored upon completion.
  2796. * passdwp [in/out] - The address where a pointer to newly allocated memory
  2797. * holding the password will be stored upon completion.
  2798. * optionsp [in/out] - The address where a pointer to newly allocated memory
  2799. * holding the options will be stored upon completion.
  2800. *
  2801. * Returns CURLE_OK on success.
  2802. */
  2803. CURLcode Curl_parse_login_details(const char *login, const size_t len,
  2804. char **userp, char **passwdp,
  2805. char **optionsp)
  2806. {
  2807. CURLcode result = CURLE_OK;
  2808. char *ubuf = NULL;
  2809. char *pbuf = NULL;
  2810. char *obuf = NULL;
  2811. const char *psep = NULL;
  2812. const char *osep = NULL;
  2813. size_t ulen;
  2814. size_t plen;
  2815. size_t olen;
  2816. /* Attempt to find the password separator */
  2817. if(passwdp) {
  2818. psep = strchr(login, ':');
  2819. /* Within the constraint of the login string */
  2820. if(psep >= login + len)
  2821. psep = NULL;
  2822. }
  2823. /* Attempt to find the options separator */
  2824. if(optionsp) {
  2825. osep = strchr(login, ';');
  2826. /* Within the constraint of the login string */
  2827. if(osep >= login + len)
  2828. osep = NULL;
  2829. }
  2830. /* Calculate the portion lengths */
  2831. ulen = (psep ?
  2832. (size_t)(osep && psep > osep ? osep - login : psep - login) :
  2833. (osep ? (size_t)(osep - login) : len));
  2834. plen = (psep ?
  2835. (osep && osep > psep ? (size_t)(osep - psep) :
  2836. (size_t)(login + len - psep)) - 1 : 0);
  2837. olen = (osep ?
  2838. (psep && psep > osep ? (size_t)(psep - osep) :
  2839. (size_t)(login + len - osep)) - 1 : 0);
  2840. /* Allocate the user portion buffer */
  2841. if(userp && ulen) {
  2842. ubuf = malloc(ulen + 1);
  2843. if(!ubuf)
  2844. result = CURLE_OUT_OF_MEMORY;
  2845. }
  2846. /* Allocate the password portion buffer */
  2847. if(!result && passwdp && plen) {
  2848. pbuf = malloc(plen + 1);
  2849. if(!pbuf) {
  2850. free(ubuf);
  2851. result = CURLE_OUT_OF_MEMORY;
  2852. }
  2853. }
  2854. /* Allocate the options portion buffer */
  2855. if(!result && optionsp && olen) {
  2856. obuf = malloc(olen + 1);
  2857. if(!obuf) {
  2858. free(pbuf);
  2859. free(ubuf);
  2860. result = CURLE_OUT_OF_MEMORY;
  2861. }
  2862. }
  2863. if(!result) {
  2864. /* Store the user portion if necessary */
  2865. if(ubuf) {
  2866. memcpy(ubuf, login, ulen);
  2867. ubuf[ulen] = '\0';
  2868. Curl_safefree(*userp);
  2869. *userp = ubuf;
  2870. }
  2871. /* Store the password portion if necessary */
  2872. if(pbuf) {
  2873. memcpy(pbuf, psep + 1, plen);
  2874. pbuf[plen] = '\0';
  2875. Curl_safefree(*passwdp);
  2876. *passwdp = pbuf;
  2877. }
  2878. /* Store the options portion if necessary */
  2879. if(obuf) {
  2880. memcpy(obuf, osep + 1, olen);
  2881. obuf[olen] = '\0';
  2882. Curl_safefree(*optionsp);
  2883. *optionsp = obuf;
  2884. }
  2885. }
  2886. return result;
  2887. }
  2888. /*************************************************************
  2889. * Figure out the remote port number and fix it in the URL
  2890. *
  2891. * No matter if we use a proxy or not, we have to figure out the remote
  2892. * port number of various reasons.
  2893. *
  2894. * To be able to detect port number flawlessly, we must not confuse them
  2895. * IPv6-specified addresses in the [0::1] style. (RFC2732)
  2896. *
  2897. * The conn->host.name is currently [user:passwd@]host[:port] where host
  2898. * could be a hostname, IPv4 address or IPv6 address.
  2899. *
  2900. * The port number embedded in the URL is replaced, if necessary.
  2901. *************************************************************/
  2902. static CURLcode parse_remote_port(struct Curl_easy *data,
  2903. struct connectdata *conn)
  2904. {
  2905. char *portptr;
  2906. char endbracket;
  2907. /* Note that at this point, the IPv6 address cannot contain any scope
  2908. suffix as that has already been removed in the parseurlandfillconn()
  2909. function */
  2910. if((1 == sscanf(conn->host.name, "[%*45[0123456789abcdefABCDEF:.]%c",
  2911. &endbracket)) &&
  2912. (']' == endbracket)) {
  2913. /* this is a RFC2732-style specified IP-address */
  2914. conn->bits.ipv6_ip = TRUE;
  2915. conn->host.name++; /* skip over the starting bracket */
  2916. portptr = strchr(conn->host.name, ']');
  2917. if(portptr) {
  2918. *portptr++ = '\0'; /* zero terminate, killing the bracket */
  2919. if(*portptr) {
  2920. if (*portptr != ':') {
  2921. failf(data, "IPv6 closing bracket followed by '%c'", *portptr);
  2922. return CURLE_URL_MALFORMAT;
  2923. }
  2924. }
  2925. else
  2926. portptr = NULL; /* no port number available */
  2927. }
  2928. }
  2929. else {
  2930. #ifdef ENABLE_IPV6
  2931. struct in6_addr in6;
  2932. if(Curl_inet_pton(AF_INET6, conn->host.name, &in6) > 0) {
  2933. /* This is a numerical IPv6 address, meaning this is a wrongly formatted
  2934. URL */
  2935. failf(data, "IPv6 numerical address used in URL without brackets");
  2936. return CURLE_URL_MALFORMAT;
  2937. }
  2938. #endif
  2939. portptr = strchr(conn->host.name, ':');
  2940. }
  2941. if(data->set.use_port && data->state.allow_port) {
  2942. /* if set, we use this and ignore the port possibly given in the URL */
  2943. conn->remote_port = (unsigned short)data->set.use_port;
  2944. if(portptr)
  2945. *portptr = '\0'; /* cut off the name there anyway - if there was a port
  2946. number - since the port number is to be ignored! */
  2947. if(conn->bits.httpproxy) {
  2948. /* we need to create new URL with the new port number */
  2949. char *url;
  2950. char type[12]="";
  2951. if(conn->bits.type_set)
  2952. snprintf(type, sizeof(type), ";type=%c",
  2953. data->set.prefer_ascii?'A':
  2954. (data->set.ftp_list_only?'D':'I'));
  2955. /*
  2956. * This synthesized URL isn't always right--suffixes like ;type=A are
  2957. * stripped off. It would be better to work directly from the original
  2958. * URL and simply replace the port part of it.
  2959. */
  2960. url = aprintf("%s://%s%s%s:%hu%s%s%s", conn->given->scheme,
  2961. conn->bits.ipv6_ip?"[":"", conn->host.name,
  2962. conn->bits.ipv6_ip?"]":"", conn->remote_port,
  2963. data->state.slash_removed?"/":"", data->state.path,
  2964. type);
  2965. if(!url)
  2966. return CURLE_OUT_OF_MEMORY;
  2967. if(data->change.url_alloc) {
  2968. Curl_safefree(data->change.url);
  2969. data->change.url_alloc = FALSE;
  2970. }
  2971. data->change.url = url;
  2972. data->change.url_alloc = TRUE;
  2973. }
  2974. }
  2975. else if(portptr) {
  2976. /* no CURLOPT_PORT given, extract the one from the URL */
  2977. char *rest;
  2978. long port;
  2979. port = strtol(portptr + 1, &rest, 10); /* Port number must be decimal */
  2980. if((port < 0) || (port > 0xffff)) {
  2981. /* Single unix standard says port numbers are 16 bits long */
  2982. failf(data, "Port number out of range");
  2983. return CURLE_URL_MALFORMAT;
  2984. }
  2985. if(rest[0]) {
  2986. failf(data, "Port number ended with '%c'", rest[0]);
  2987. return CURLE_URL_MALFORMAT;
  2988. }
  2989. if(rest != &portptr[1]) {
  2990. *portptr = '\0'; /* cut off the name there */
  2991. conn->remote_port = curlx_ultous(port);
  2992. }
  2993. else {
  2994. /* Browser behavior adaptation. If there's a colon with no digits after,
  2995. just cut off the name there which makes us ignore the colon and just
  2996. use the default port. Firefox and Chrome both do that. */
  2997. *portptr = '\0';
  2998. }
  2999. }
  3000. /* only if remote_port was not already parsed off the URL we use the
  3001. default port number */
  3002. if(conn->remote_port < 0)
  3003. conn->remote_port = (unsigned short)conn->given->defport;
  3004. return CURLE_OK;
  3005. }
  3006. /*
  3007. * Override the login details from the URL with that in the CURLOPT_USERPWD
  3008. * option or a .netrc file, if applicable.
  3009. */
  3010. static CURLcode override_login(struct Curl_easy *data,
  3011. struct connectdata *conn,
  3012. char **userp, char **passwdp, char **optionsp)
  3013. {
  3014. if(data->set.str[STRING_USERNAME]) {
  3015. free(*userp);
  3016. *userp = strdup(data->set.str[STRING_USERNAME]);
  3017. if(!*userp)
  3018. return CURLE_OUT_OF_MEMORY;
  3019. }
  3020. if(data->set.str[STRING_PASSWORD]) {
  3021. free(*passwdp);
  3022. *passwdp = strdup(data->set.str[STRING_PASSWORD]);
  3023. if(!*passwdp)
  3024. return CURLE_OUT_OF_MEMORY;
  3025. }
  3026. if(data->set.str[STRING_OPTIONS]) {
  3027. free(*optionsp);
  3028. *optionsp = strdup(data->set.str[STRING_OPTIONS]);
  3029. if(!*optionsp)
  3030. return CURLE_OUT_OF_MEMORY;
  3031. }
  3032. conn->bits.netrc = FALSE;
  3033. if(data->set.use_netrc != CURL_NETRC_IGNORED) {
  3034. int ret = Curl_parsenetrc(conn->host.name,
  3035. userp, passwdp,
  3036. data->set.str[STRING_NETRC_FILE]);
  3037. if(ret > 0) {
  3038. infof(data, "Couldn't find host %s in the "
  3039. DOT_CHAR "netrc file; using defaults\n",
  3040. conn->host.name);
  3041. }
  3042. else if(ret < 0) {
  3043. return CURLE_OUT_OF_MEMORY;
  3044. }
  3045. else {
  3046. /* set bits.netrc TRUE to remember that we got the name from a .netrc
  3047. file, so that it is safe to use even if we followed a Location: to a
  3048. different host or similar. */
  3049. conn->bits.netrc = TRUE;
  3050. conn->bits.user_passwd = TRUE; /* enable user+password */
  3051. }
  3052. }
  3053. return CURLE_OK;
  3054. }
  3055. /*
  3056. * Set the login details so they're available in the connection
  3057. */
  3058. static CURLcode set_login(struct connectdata *conn,
  3059. const char *user, const char *passwd,
  3060. const char *options)
  3061. {
  3062. CURLcode result = CURLE_OK;
  3063. /* If our protocol needs a password and we have none, use the defaults */
  3064. if((conn->handler->flags & PROTOPT_NEEDSPWD) && !conn->bits.user_passwd) {
  3065. /* Store the default user */
  3066. conn->user = strdup(CURL_DEFAULT_USER);
  3067. /* Store the default password */
  3068. if(conn->user)
  3069. conn->passwd = strdup(CURL_DEFAULT_PASSWORD);
  3070. else
  3071. conn->passwd = NULL;
  3072. /* This is the default password, so DON'T set conn->bits.user_passwd */
  3073. }
  3074. else {
  3075. /* Store the user, zero-length if not set */
  3076. conn->user = strdup(user);
  3077. /* Store the password (only if user is present), zero-length if not set */
  3078. if(conn->user)
  3079. conn->passwd = strdup(passwd);
  3080. else
  3081. conn->passwd = NULL;
  3082. }
  3083. if(!conn->user || !conn->passwd)
  3084. result = CURLE_OUT_OF_MEMORY;
  3085. /* Store the options, null if not set */
  3086. if(!result && options[0]) {
  3087. conn->options = strdup(options);
  3088. if(!conn->options)
  3089. result = CURLE_OUT_OF_MEMORY;
  3090. }
  3091. return result;
  3092. }
  3093. /*
  3094. * Parses a "host:port" string to connect to.
  3095. * The hostname and the port may be empty; in this case, NULL is returned for
  3096. * the hostname and -1 for the port.
  3097. */
  3098. static CURLcode parse_connect_to_host_port(struct Curl_easy *data,
  3099. const char *host,
  3100. char **hostname_result,
  3101. int *port_result)
  3102. {
  3103. char *host_dup;
  3104. char *hostptr;
  3105. char *host_portno;
  3106. char *portptr;
  3107. int port = -1;
  3108. #if defined(CURL_DISABLE_VERBOSE_STRINGS)
  3109. (void) data;
  3110. #endif
  3111. *hostname_result = NULL;
  3112. *port_result = -1;
  3113. if(!host || !*host)
  3114. return CURLE_OK;
  3115. host_dup = strdup(host);
  3116. if(!host_dup)
  3117. return CURLE_OUT_OF_MEMORY;
  3118. hostptr = host_dup;
  3119. /* start scanning for port number at this point */
  3120. portptr = hostptr;
  3121. /* detect and extract RFC6874-style IPv6-addresses */
  3122. if(*hostptr == '[') {
  3123. #ifdef ENABLE_IPV6
  3124. char *ptr = ++hostptr; /* advance beyond the initial bracket */
  3125. while(*ptr && (ISXDIGIT(*ptr) || (*ptr == ':') || (*ptr == '.')))
  3126. ptr++;
  3127. if(*ptr == '%') {
  3128. /* There might be a zone identifier */
  3129. if(strncmp("%25", ptr, 3))
  3130. infof(data, "Please URL encode %% as %%25, see RFC 6874.\n");
  3131. ptr++;
  3132. /* Allow unreserved characters as defined in RFC 3986 */
  3133. while(*ptr && (ISALPHA(*ptr) || ISXDIGIT(*ptr) || (*ptr == '-') ||
  3134. (*ptr == '.') || (*ptr == '_') || (*ptr == '~')))
  3135. ptr++;
  3136. }
  3137. if(*ptr == ']')
  3138. /* yeps, it ended nicely with a bracket as well */
  3139. *ptr++ = '\0';
  3140. else
  3141. infof(data, "Invalid IPv6 address format\n");
  3142. portptr = ptr;
  3143. /* Note that if this didn't end with a bracket, we still advanced the
  3144. * hostptr first, but I can't see anything wrong with that as no host
  3145. * name nor a numeric can legally start with a bracket.
  3146. */
  3147. #else
  3148. failf(data, "Use of IPv6 in *_CONNECT_TO without IPv6 support built-in!");
  3149. free(host_dup);
  3150. return CURLE_NOT_BUILT_IN;
  3151. #endif
  3152. }
  3153. /* Get port number off server.com:1080 */
  3154. host_portno = strchr(portptr, ':');
  3155. if(host_portno) {
  3156. char *endp = NULL;
  3157. *host_portno = '\0'; /* cut off number from host name */
  3158. host_portno++;
  3159. if(*host_portno) {
  3160. long portparse = strtol(host_portno, &endp, 10);
  3161. if((endp && *endp) || (portparse < 0) || (portparse > 65535)) {
  3162. infof(data, "No valid port number in connect to host string (%s)\n",
  3163. host_portno);
  3164. hostptr = NULL;
  3165. port = -1;
  3166. }
  3167. else
  3168. port = (int)portparse; /* we know it will fit */
  3169. }
  3170. }
  3171. /* now, clone the cleaned host name */
  3172. if(hostptr) {
  3173. *hostname_result = strdup(hostptr);
  3174. if(!*hostname_result) {
  3175. free(host_dup);
  3176. return CURLE_OUT_OF_MEMORY;
  3177. }
  3178. }
  3179. *port_result = port;
  3180. free(host_dup);
  3181. return CURLE_OK;
  3182. }
  3183. /*
  3184. * Parses one "connect to" string in the form:
  3185. * "HOST:PORT:CONNECT-TO-HOST:CONNECT-TO-PORT".
  3186. */
  3187. static CURLcode parse_connect_to_string(struct Curl_easy *data,
  3188. struct connectdata *conn,
  3189. const char *conn_to_host,
  3190. char **host_result,
  3191. int *port_result)
  3192. {
  3193. CURLcode result = CURLE_OK;
  3194. const char *ptr = conn_to_host;
  3195. int host_match = FALSE;
  3196. int port_match = FALSE;
  3197. *host_result = NULL;
  3198. *port_result = -1;
  3199. if(*ptr == ':') {
  3200. /* an empty hostname always matches */
  3201. host_match = TRUE;
  3202. ptr++;
  3203. }
  3204. else {
  3205. /* check whether the URL's hostname matches */
  3206. size_t hostname_to_match_len;
  3207. char *hostname_to_match = aprintf("%s%s%s",
  3208. conn->bits.ipv6_ip ? "[" : "",
  3209. conn->host.name,
  3210. conn->bits.ipv6_ip ? "]" : "");
  3211. if(!hostname_to_match)
  3212. return CURLE_OUT_OF_MEMORY;
  3213. hostname_to_match_len = strlen(hostname_to_match);
  3214. host_match = strncasecompare(ptr, hostname_to_match,
  3215. hostname_to_match_len);
  3216. free(hostname_to_match);
  3217. ptr += hostname_to_match_len;
  3218. host_match = host_match && *ptr == ':';
  3219. ptr++;
  3220. }
  3221. if(host_match) {
  3222. if(*ptr == ':') {
  3223. /* an empty port always matches */
  3224. port_match = TRUE;
  3225. ptr++;
  3226. }
  3227. else {
  3228. /* check whether the URL's port matches */
  3229. char *ptr_next = strchr(ptr, ':');
  3230. if(ptr_next) {
  3231. char *endp = NULL;
  3232. long port_to_match = strtol(ptr, &endp, 10);
  3233. if((endp == ptr_next) && (port_to_match == conn->remote_port)) {
  3234. port_match = TRUE;
  3235. ptr = ptr_next + 1;
  3236. }
  3237. }
  3238. }
  3239. }
  3240. if(host_match && port_match) {
  3241. /* parse the hostname and port to connect to */
  3242. result = parse_connect_to_host_port(data, ptr, host_result, port_result);
  3243. }
  3244. return result;
  3245. }
  3246. /*
  3247. * Processes all strings in the "connect to" slist, and uses the "connect
  3248. * to host" and "connect to port" of the first string that matches.
  3249. */
  3250. static CURLcode parse_connect_to_slist(struct Curl_easy *data,
  3251. struct connectdata *conn,
  3252. struct curl_slist *conn_to_host)
  3253. {
  3254. CURLcode result = CURLE_OK;
  3255. char *host = NULL;
  3256. int port = -1;
  3257. while(conn_to_host && !host && port == -1) {
  3258. result = parse_connect_to_string(data, conn, conn_to_host->data,
  3259. &host, &port);
  3260. if(result)
  3261. return result;
  3262. if(host && *host) {
  3263. conn->conn_to_host.rawalloc = host;
  3264. conn->conn_to_host.name = host;
  3265. conn->bits.conn_to_host = TRUE;
  3266. infof(data, "Connecting to hostname: %s\n", host);
  3267. }
  3268. else {
  3269. /* no "connect to host" */
  3270. conn->bits.conn_to_host = FALSE;
  3271. Curl_safefree(host);
  3272. }
  3273. if(port >= 0) {
  3274. conn->conn_to_port = port;
  3275. conn->bits.conn_to_port = TRUE;
  3276. infof(data, "Connecting to port: %d\n", port);
  3277. }
  3278. else {
  3279. /* no "connect to port" */
  3280. conn->bits.conn_to_port = FALSE;
  3281. port = -1;
  3282. }
  3283. conn_to_host = conn_to_host->next;
  3284. }
  3285. return result;
  3286. }
  3287. /*************************************************************
  3288. * Resolve the address of the server or proxy
  3289. *************************************************************/
  3290. static CURLcode resolve_server(struct Curl_easy *data,
  3291. struct connectdata *conn,
  3292. bool *async)
  3293. {
  3294. CURLcode result = CURLE_OK;
  3295. timediff_t timeout_ms = Curl_timeleft(data, NULL, TRUE);
  3296. /*************************************************************
  3297. * Resolve the name of the server or proxy
  3298. *************************************************************/
  3299. if(conn->bits.reuse)
  3300. /* We're reusing the connection - no need to resolve anything, and
  3301. fix_hostname() was called already in create_conn() for the re-use
  3302. case. */
  3303. *async = FALSE;
  3304. else {
  3305. /* this is a fresh connect */
  3306. int rc;
  3307. struct Curl_dns_entry *hostaddr;
  3308. #ifdef USE_UNIX_SOCKETS
  3309. if(conn->unix_domain_socket) {
  3310. /* Unix domain sockets are local. The host gets ignored, just use the
  3311. * specified domain socket address. Do not cache "DNS entries". There is
  3312. * no DNS involved and we already have the filesystem path available */
  3313. const char *path = conn->unix_domain_socket;
  3314. hostaddr = calloc(1, sizeof(struct Curl_dns_entry));
  3315. if(!hostaddr)
  3316. result = CURLE_OUT_OF_MEMORY;
  3317. else {
  3318. bool longpath = FALSE;
  3319. hostaddr->addr = Curl_unix2addr(path, &longpath,
  3320. conn->abstract_unix_socket);
  3321. if(hostaddr->addr)
  3322. hostaddr->inuse++;
  3323. else {
  3324. /* Long paths are not supported for now */
  3325. if(longpath) {
  3326. failf(data, "Unix socket path too long: '%s'", path);
  3327. result = CURLE_COULDNT_RESOLVE_HOST;
  3328. }
  3329. else
  3330. result = CURLE_OUT_OF_MEMORY;
  3331. free(hostaddr);
  3332. hostaddr = NULL;
  3333. }
  3334. }
  3335. }
  3336. else
  3337. #endif
  3338. if(!conn->bits.proxy) {
  3339. struct hostname *connhost;
  3340. if(conn->bits.conn_to_host)
  3341. connhost = &conn->conn_to_host;
  3342. else
  3343. connhost = &conn->host;
  3344. /* If not connecting via a proxy, extract the port from the URL, if it is
  3345. * there, thus overriding any defaults that might have been set above. */
  3346. if(conn->bits.conn_to_port)
  3347. conn->port = conn->conn_to_port;
  3348. else
  3349. conn->port = conn->remote_port;
  3350. /* Resolve target host right on */
  3351. rc = Curl_resolv_timeout(conn, connhost->name, (int)conn->port,
  3352. &hostaddr, timeout_ms);
  3353. if(rc == CURLRESOLV_PENDING)
  3354. *async = TRUE;
  3355. else if(rc == CURLRESOLV_TIMEDOUT)
  3356. result = CURLE_OPERATION_TIMEDOUT;
  3357. else if(!hostaddr) {
  3358. failf(data, "Couldn't resolve host '%s'", connhost->dispname);
  3359. result = CURLE_COULDNT_RESOLVE_HOST;
  3360. /* don't return yet, we need to clean up the timeout first */
  3361. }
  3362. }
  3363. else {
  3364. /* This is a proxy that hasn't been resolved yet. */
  3365. struct hostname * const host = conn->bits.socksproxy ?
  3366. &conn->socks_proxy.host : &conn->http_proxy.host;
  3367. /* resolve proxy */
  3368. rc = Curl_resolv_timeout(conn, host->name, (int)conn->port,
  3369. &hostaddr, timeout_ms);
  3370. if(rc == CURLRESOLV_PENDING)
  3371. *async = TRUE;
  3372. else if(rc == CURLRESOLV_TIMEDOUT)
  3373. result = CURLE_OPERATION_TIMEDOUT;
  3374. else if(!hostaddr) {
  3375. failf(data, "Couldn't resolve proxy '%s'", host->dispname);
  3376. result = CURLE_COULDNT_RESOLVE_PROXY;
  3377. /* don't return yet, we need to clean up the timeout first */
  3378. }
  3379. }
  3380. DEBUGASSERT(conn->dns_entry == NULL);
  3381. conn->dns_entry = hostaddr;
  3382. }
  3383. return result;
  3384. }
  3385. /*
  3386. * Cleanup the connection just allocated before we can move along and use the
  3387. * previously existing one. All relevant data is copied over and old_conn is
  3388. * ready for freeing once this function returns.
  3389. */
  3390. static void reuse_conn(struct connectdata *old_conn,
  3391. struct connectdata *conn)
  3392. {
  3393. free_fixed_hostname(&old_conn->http_proxy.host);
  3394. free_fixed_hostname(&old_conn->socks_proxy.host);
  3395. free(old_conn->http_proxy.host.rawalloc);
  3396. free(old_conn->socks_proxy.host.rawalloc);
  3397. /* free the SSL config struct from this connection struct as this was
  3398. allocated in vain and is targeted for destruction */
  3399. Curl_free_primary_ssl_config(&old_conn->ssl_config);
  3400. Curl_free_primary_ssl_config(&old_conn->proxy_ssl_config);
  3401. conn->data = old_conn->data;
  3402. /* get the user+password information from the old_conn struct since it may
  3403. * be new for this request even when we re-use an existing connection */
  3404. conn->bits.user_passwd = old_conn->bits.user_passwd;
  3405. if(conn->bits.user_passwd) {
  3406. /* use the new user name and password though */
  3407. Curl_safefree(conn->user);
  3408. Curl_safefree(conn->passwd);
  3409. conn->user = old_conn->user;
  3410. conn->passwd = old_conn->passwd;
  3411. old_conn->user = NULL;
  3412. old_conn->passwd = NULL;
  3413. }
  3414. conn->bits.proxy_user_passwd = old_conn->bits.proxy_user_passwd;
  3415. if(conn->bits.proxy_user_passwd) {
  3416. /* use the new proxy user name and proxy password though */
  3417. Curl_safefree(conn->http_proxy.user);
  3418. Curl_safefree(conn->socks_proxy.user);
  3419. Curl_safefree(conn->http_proxy.passwd);
  3420. Curl_safefree(conn->socks_proxy.passwd);
  3421. conn->http_proxy.user = old_conn->http_proxy.user;
  3422. conn->socks_proxy.user = old_conn->socks_proxy.user;
  3423. conn->http_proxy.passwd = old_conn->http_proxy.passwd;
  3424. conn->socks_proxy.passwd = old_conn->socks_proxy.passwd;
  3425. old_conn->http_proxy.user = NULL;
  3426. old_conn->socks_proxy.user = NULL;
  3427. old_conn->http_proxy.passwd = NULL;
  3428. old_conn->socks_proxy.passwd = NULL;
  3429. }
  3430. /* host can change, when doing keepalive with a proxy or if the case is
  3431. different this time etc */
  3432. free_fixed_hostname(&conn->host);
  3433. free_fixed_hostname(&conn->conn_to_host);
  3434. Curl_safefree(conn->host.rawalloc);
  3435. Curl_safefree(conn->conn_to_host.rawalloc);
  3436. conn->host = old_conn->host;
  3437. conn->conn_to_host = old_conn->conn_to_host;
  3438. conn->conn_to_port = old_conn->conn_to_port;
  3439. conn->remote_port = old_conn->remote_port;
  3440. /* persist connection info in session handle */
  3441. Curl_persistconninfo(conn);
  3442. conn_reset_all_postponed_data(old_conn); /* free buffers */
  3443. /* re-use init */
  3444. conn->bits.reuse = TRUE; /* yes, we're re-using here */
  3445. Curl_safefree(old_conn->user);
  3446. Curl_safefree(old_conn->passwd);
  3447. Curl_safefree(old_conn->http_proxy.user);
  3448. Curl_safefree(old_conn->socks_proxy.user);
  3449. Curl_safefree(old_conn->http_proxy.passwd);
  3450. Curl_safefree(old_conn->socks_proxy.passwd);
  3451. Curl_safefree(old_conn->localdev);
  3452. Curl_llist_destroy(&old_conn->send_pipe, NULL);
  3453. Curl_llist_destroy(&old_conn->recv_pipe, NULL);
  3454. Curl_safefree(old_conn->master_buffer);
  3455. #ifdef USE_UNIX_SOCKETS
  3456. Curl_safefree(old_conn->unix_domain_socket);
  3457. #endif
  3458. }
  3459. /**
  3460. * create_conn() sets up a new connectdata struct, or re-uses an already
  3461. * existing one, and resolves host name.
  3462. *
  3463. * if this function returns CURLE_OK and *async is set to TRUE, the resolve
  3464. * response will be coming asynchronously. If *async is FALSE, the name is
  3465. * already resolved.
  3466. *
  3467. * @param data The sessionhandle pointer
  3468. * @param in_connect is set to the next connection data pointer
  3469. * @param async is set TRUE when an async DNS resolution is pending
  3470. * @see Curl_setup_conn()
  3471. *
  3472. * *NOTE* this function assigns the conn->data pointer!
  3473. */
  3474. static CURLcode create_conn(struct Curl_easy *data,
  3475. struct connectdata **in_connect,
  3476. bool *async)
  3477. {
  3478. CURLcode result = CURLE_OK;
  3479. struct connectdata *conn;
  3480. struct connectdata *conn_temp = NULL;
  3481. size_t urllen;
  3482. char *user = NULL;
  3483. char *passwd = NULL;
  3484. char *options = NULL;
  3485. bool reuse;
  3486. bool prot_missing = FALSE;
  3487. bool connections_available = TRUE;
  3488. bool force_reuse = FALSE;
  3489. bool waitpipe = FALSE;
  3490. size_t max_host_connections = Curl_multi_max_host_connections(data->multi);
  3491. size_t max_total_connections = Curl_multi_max_total_connections(data->multi);
  3492. *async = FALSE;
  3493. /*************************************************************
  3494. * Check input data
  3495. *************************************************************/
  3496. if(!data->change.url) {
  3497. result = CURLE_URL_MALFORMAT;
  3498. goto out;
  3499. }
  3500. /* First, split up the current URL in parts so that we can use the
  3501. parts for checking against the already present connections. In order
  3502. to not have to modify everything at once, we allocate a temporary
  3503. connection data struct and fill in for comparison purposes. */
  3504. conn = allocate_conn(data);
  3505. if(!conn) {
  3506. result = CURLE_OUT_OF_MEMORY;
  3507. goto out;
  3508. }
  3509. /* We must set the return variable as soon as possible, so that our
  3510. parent can cleanup any possible allocs we may have done before
  3511. any failure */
  3512. *in_connect = conn;
  3513. /* This initing continues below, see the comment "Continue connectdata
  3514. * initialization here" */
  3515. /***********************************************************
  3516. * We need to allocate memory to store the path in. We get the size of the
  3517. * full URL to be sure, and we need to make it at least 256 bytes since
  3518. * other parts of the code will rely on this fact
  3519. ***********************************************************/
  3520. #define LEAST_PATH_ALLOC 256
  3521. urllen = strlen(data->change.url);
  3522. if(urllen < LEAST_PATH_ALLOC)
  3523. urllen = LEAST_PATH_ALLOC;
  3524. /*
  3525. * We malloc() the buffers below urllen+2 to make room for 2 possibilities:
  3526. * 1 - an extra terminating zero
  3527. * 2 - an extra slash (in case a syntax like "www.host.com?moo" is used)
  3528. */
  3529. Curl_safefree(data->state.pathbuffer);
  3530. data->state.path = NULL;
  3531. data->state.pathbuffer = malloc(urllen + 2);
  3532. if(NULL == data->state.pathbuffer) {
  3533. result = CURLE_OUT_OF_MEMORY; /* really bad error */
  3534. goto out;
  3535. }
  3536. data->state.path = data->state.pathbuffer;
  3537. conn->host.rawalloc = malloc(urllen + 2);
  3538. if(NULL == conn->host.rawalloc) {
  3539. Curl_safefree(data->state.pathbuffer);
  3540. data->state.path = NULL;
  3541. result = CURLE_OUT_OF_MEMORY;
  3542. goto out;
  3543. }
  3544. conn->host.name = conn->host.rawalloc;
  3545. conn->host.name[0] = 0;
  3546. user = strdup("");
  3547. passwd = strdup("");
  3548. options = strdup("");
  3549. if(!user || !passwd || !options) {
  3550. result = CURLE_OUT_OF_MEMORY;
  3551. goto out;
  3552. }
  3553. result = parseurlandfillconn(data, conn, &prot_missing, &user, &passwd,
  3554. &options);
  3555. if(result)
  3556. goto out;
  3557. /*************************************************************
  3558. * No protocol part in URL was used, add it!
  3559. *************************************************************/
  3560. if(prot_missing) {
  3561. /* We're guessing prefixes here and if we're told to use a proxy or if
  3562. we're gonna follow a Location: later or... then we need the protocol
  3563. part added so that we have a valid URL. */
  3564. char *reurl;
  3565. char *ch_lower;
  3566. reurl = aprintf("%s://%s", conn->handler->scheme, data->change.url);
  3567. if(!reurl) {
  3568. result = CURLE_OUT_OF_MEMORY;
  3569. goto out;
  3570. }
  3571. /* Change protocol prefix to lower-case */
  3572. for(ch_lower = reurl; *ch_lower != ':'; ch_lower++)
  3573. *ch_lower = (char)TOLOWER(*ch_lower);
  3574. if(data->change.url_alloc) {
  3575. Curl_safefree(data->change.url);
  3576. data->change.url_alloc = FALSE;
  3577. }
  3578. data->change.url = reurl;
  3579. data->change.url_alloc = TRUE; /* free this later */
  3580. }
  3581. /*************************************************************
  3582. * If the protocol can't handle url query strings, then cut
  3583. * off the unhandable part
  3584. *************************************************************/
  3585. if((conn->given->flags&PROTOPT_NOURLQUERY)) {
  3586. char *path_q_sep = strchr(conn->data->state.path, '?');
  3587. if(path_q_sep) {
  3588. /* according to rfc3986, allow the query (?foo=bar)
  3589. also on protocols that can't handle it.
  3590. cut the string-part after '?'
  3591. */
  3592. /* terminate the string */
  3593. path_q_sep[0] = 0;
  3594. }
  3595. }
  3596. if(data->set.str[STRING_BEARER]) {
  3597. conn->oauth_bearer = strdup(data->set.str[STRING_BEARER]);
  3598. if(!conn->oauth_bearer) {
  3599. result = CURLE_OUT_OF_MEMORY;
  3600. goto out;
  3601. }
  3602. }
  3603. #ifdef USE_UNIX_SOCKETS
  3604. if(data->set.str[STRING_UNIX_SOCKET_PATH]) {
  3605. conn->unix_domain_socket = strdup(data->set.str[STRING_UNIX_SOCKET_PATH]);
  3606. if(conn->unix_domain_socket == NULL) {
  3607. result = CURLE_OUT_OF_MEMORY;
  3608. goto out;
  3609. }
  3610. conn->abstract_unix_socket = data->set.abstract_unix_socket;
  3611. }
  3612. #endif
  3613. /* After the unix socket init but before the proxy vars are used, parse and
  3614. initialize the proxy vars */
  3615. #ifndef CURL_DISABLE_PROXY
  3616. result = create_conn_helper_init_proxy(conn);
  3617. if(result)
  3618. goto out;
  3619. #endif
  3620. /*************************************************************
  3621. * If the protocol is using SSL and HTTP proxy is used, we set
  3622. * the tunnel_proxy bit.
  3623. *************************************************************/
  3624. if((conn->given->flags&PROTOPT_SSL) && conn->bits.httpproxy)
  3625. conn->bits.tunnel_proxy = TRUE;
  3626. /*************************************************************
  3627. * Figure out the remote port number and fix it in the URL
  3628. *************************************************************/
  3629. result = parse_remote_port(data, conn);
  3630. if(result)
  3631. goto out;
  3632. /* Check for overridden login details and set them accordingly so they
  3633. they are known when protocol->setup_connection is called! */
  3634. result = override_login(data, conn, &user, &passwd, &options);
  3635. if(result)
  3636. goto out;
  3637. result = set_login(conn, user, passwd, options);
  3638. if(result)
  3639. goto out;
  3640. /*************************************************************
  3641. * Process the "connect to" linked list of hostname/port mappings.
  3642. * Do this after the remote port number has been fixed in the URL.
  3643. *************************************************************/
  3644. result = parse_connect_to_slist(data, conn, data->set.connect_to);
  3645. if(result)
  3646. goto out;
  3647. /*************************************************************
  3648. * IDN-fix the hostnames
  3649. *************************************************************/
  3650. result = fix_hostname(conn, &conn->host);
  3651. if(result)
  3652. goto out;
  3653. if(conn->bits.conn_to_host) {
  3654. result = fix_hostname(conn, &conn->conn_to_host);
  3655. if(result)
  3656. goto out;
  3657. }
  3658. if(conn->bits.httpproxy) {
  3659. result = fix_hostname(conn, &conn->http_proxy.host);
  3660. if(result)
  3661. goto out;
  3662. }
  3663. if(conn->bits.socksproxy) {
  3664. result = fix_hostname(conn, &conn->socks_proxy.host);
  3665. if(result)
  3666. goto out;
  3667. }
  3668. /*************************************************************
  3669. * Check whether the host and the "connect to host" are equal.
  3670. * Do this after the hostnames have been IDN-fixed.
  3671. *************************************************************/
  3672. if(conn->bits.conn_to_host &&
  3673. strcasecompare(conn->conn_to_host.name, conn->host.name)) {
  3674. conn->bits.conn_to_host = FALSE;
  3675. }
  3676. /*************************************************************
  3677. * Check whether the port and the "connect to port" are equal.
  3678. * Do this after the remote port number has been fixed in the URL.
  3679. *************************************************************/
  3680. if(conn->bits.conn_to_port && conn->conn_to_port == conn->remote_port) {
  3681. conn->bits.conn_to_port = FALSE;
  3682. }
  3683. /*************************************************************
  3684. * If the "connect to" feature is used with an HTTP proxy,
  3685. * we set the tunnel_proxy bit.
  3686. *************************************************************/
  3687. if((conn->bits.conn_to_host || conn->bits.conn_to_port) &&
  3688. conn->bits.httpproxy)
  3689. conn->bits.tunnel_proxy = TRUE;
  3690. /*************************************************************
  3691. * Setup internals depending on protocol. Needs to be done after
  3692. * we figured out what/if proxy to use.
  3693. *************************************************************/
  3694. result = setup_connection_internals(conn);
  3695. if(result)
  3696. goto out;
  3697. conn->recv[FIRSTSOCKET] = Curl_recv_plain;
  3698. conn->send[FIRSTSOCKET] = Curl_send_plain;
  3699. conn->recv[SECONDARYSOCKET] = Curl_recv_plain;
  3700. conn->send[SECONDARYSOCKET] = Curl_send_plain;
  3701. conn->bits.tcp_fastopen = data->set.tcp_fastopen;
  3702. /***********************************************************************
  3703. * file: is a special case in that it doesn't need a network connection
  3704. ***********************************************************************/
  3705. #ifndef CURL_DISABLE_FILE
  3706. if(conn->handler->flags & PROTOPT_NONETWORK) {
  3707. bool done;
  3708. /* this is supposed to be the connect function so we better at least check
  3709. that the file is present here! */
  3710. DEBUGASSERT(conn->handler->connect_it);
  3711. result = conn->handler->connect_it(conn, &done);
  3712. /* Setup a "faked" transfer that'll do nothing */
  3713. if(!result) {
  3714. conn->data = data;
  3715. conn->bits.tcpconnect[FIRSTSOCKET] = TRUE; /* we are "connected */
  3716. Curl_conncache_add_conn(data->state.conn_cache, conn);
  3717. /*
  3718. * Setup whatever necessary for a resumed transfer
  3719. */
  3720. result = setup_range(data);
  3721. if(result) {
  3722. DEBUGASSERT(conn->handler->done);
  3723. /* we ignore the return code for the protocol-specific DONE */
  3724. (void)conn->handler->done(conn, result, FALSE);
  3725. goto out;
  3726. }
  3727. Curl_setup_transfer(conn, -1, -1, FALSE, NULL, /* no download */
  3728. -1, NULL); /* no upload */
  3729. }
  3730. /* since we skip do_init() */
  3731. Curl_init_do(data, conn);
  3732. goto out;
  3733. }
  3734. #endif
  3735. /* Get a cloned copy of the SSL config situation stored in the
  3736. connection struct. But to get this going nicely, we must first make
  3737. sure that the strings in the master copy are pointing to the correct
  3738. strings in the session handle strings array!
  3739. Keep in mind that the pointers in the master copy are pointing to strings
  3740. that will be freed as part of the Curl_easy struct, but all cloned
  3741. copies will be separately allocated.
  3742. */
  3743. data->set.ssl.primary.CApath = data->set.str[STRING_SSL_CAPATH_ORIG];
  3744. data->set.proxy_ssl.primary.CApath = data->set.str[STRING_SSL_CAPATH_PROXY];
  3745. data->set.ssl.primary.CAfile = data->set.str[STRING_SSL_CAFILE_ORIG];
  3746. data->set.proxy_ssl.primary.CAfile = data->set.str[STRING_SSL_CAFILE_PROXY];
  3747. data->set.ssl.primary.random_file = data->set.str[STRING_SSL_RANDOM_FILE];
  3748. data->set.proxy_ssl.primary.random_file =
  3749. data->set.str[STRING_SSL_RANDOM_FILE];
  3750. data->set.ssl.primary.egdsocket = data->set.str[STRING_SSL_EGDSOCKET];
  3751. data->set.proxy_ssl.primary.egdsocket = data->set.str[STRING_SSL_EGDSOCKET];
  3752. data->set.ssl.primary.cipher_list =
  3753. data->set.str[STRING_SSL_CIPHER_LIST_ORIG];
  3754. data->set.proxy_ssl.primary.cipher_list =
  3755. data->set.str[STRING_SSL_CIPHER_LIST_PROXY];
  3756. data->set.ssl.CRLfile = data->set.str[STRING_SSL_CRLFILE_ORIG];
  3757. data->set.proxy_ssl.CRLfile = data->set.str[STRING_SSL_CRLFILE_PROXY];
  3758. data->set.ssl.issuercert = data->set.str[STRING_SSL_ISSUERCERT_ORIG];
  3759. data->set.proxy_ssl.issuercert = data->set.str[STRING_SSL_ISSUERCERT_PROXY];
  3760. data->set.ssl.cert = data->set.str[STRING_CERT_ORIG];
  3761. data->set.proxy_ssl.cert = data->set.str[STRING_CERT_PROXY];
  3762. data->set.ssl.cert_type = data->set.str[STRING_CERT_TYPE_ORIG];
  3763. data->set.proxy_ssl.cert_type = data->set.str[STRING_CERT_TYPE_PROXY];
  3764. data->set.ssl.key = data->set.str[STRING_KEY_ORIG];
  3765. data->set.proxy_ssl.key = data->set.str[STRING_KEY_PROXY];
  3766. data->set.ssl.key_type = data->set.str[STRING_KEY_TYPE_ORIG];
  3767. data->set.proxy_ssl.key_type = data->set.str[STRING_KEY_TYPE_PROXY];
  3768. data->set.ssl.key_passwd = data->set.str[STRING_KEY_PASSWD_ORIG];
  3769. data->set.proxy_ssl.key_passwd = data->set.str[STRING_KEY_PASSWD_PROXY];
  3770. data->set.ssl.primary.clientcert = data->set.str[STRING_CERT_ORIG];
  3771. data->set.proxy_ssl.primary.clientcert = data->set.str[STRING_CERT_PROXY];
  3772. #ifdef USE_TLS_SRP
  3773. data->set.ssl.username = data->set.str[STRING_TLSAUTH_USERNAME_ORIG];
  3774. data->set.proxy_ssl.username = data->set.str[STRING_TLSAUTH_USERNAME_PROXY];
  3775. data->set.ssl.password = data->set.str[STRING_TLSAUTH_PASSWORD_ORIG];
  3776. data->set.proxy_ssl.password = data->set.str[STRING_TLSAUTH_PASSWORD_PROXY];
  3777. #endif
  3778. if(!Curl_clone_primary_ssl_config(&data->set.ssl.primary,
  3779. &conn->ssl_config)) {
  3780. result = CURLE_OUT_OF_MEMORY;
  3781. goto out;
  3782. }
  3783. if(!Curl_clone_primary_ssl_config(&data->set.proxy_ssl.primary,
  3784. &conn->proxy_ssl_config)) {
  3785. result = CURLE_OUT_OF_MEMORY;
  3786. goto out;
  3787. }
  3788. prune_dead_connections(data);
  3789. /*************************************************************
  3790. * Check the current list of connections to see if we can
  3791. * re-use an already existing one or if we have to create a
  3792. * new one.
  3793. *************************************************************/
  3794. /* reuse_fresh is TRUE if we are told to use a new connection by force, but
  3795. we only acknowledge this option if this is not a re-used connection
  3796. already (which happens due to follow-location or during a HTTP
  3797. authentication phase). */
  3798. if(data->set.reuse_fresh && !data->state.this_is_a_follow)
  3799. reuse = FALSE;
  3800. else
  3801. reuse = ConnectionExists(data, conn, &conn_temp, &force_reuse, &waitpipe);
  3802. /* If we found a reusable connection that is now marked as in use, we may
  3803. still want to open a new connection if we are pipelining. */
  3804. if(reuse && !force_reuse && IsPipeliningPossible(data, conn_temp)) {
  3805. size_t pipelen = conn_temp->send_pipe.size + conn_temp->recv_pipe.size;
  3806. if(pipelen > 0) {
  3807. infof(data, "Found connection %ld, with requests in the pipe (%zu)\n",
  3808. conn_temp->connection_id, pipelen);
  3809. if(Curl_conncache_bundle_size(conn_temp) < max_host_connections &&
  3810. Curl_conncache_size(data) < max_total_connections) {
  3811. /* We want a new connection anyway */
  3812. reuse = FALSE;
  3813. infof(data, "We can reuse, but we want a new connection anyway\n");
  3814. Curl_conncache_return_conn(conn_temp);
  3815. }
  3816. }
  3817. }
  3818. if(reuse) {
  3819. /*
  3820. * We already have a connection for this, we got the former connection
  3821. * in the conn_temp variable and thus we need to cleanup the one we
  3822. * just allocated before we can move along and use the previously
  3823. * existing one.
  3824. */
  3825. reuse_conn(conn, conn_temp);
  3826. #ifdef USE_SSL
  3827. free(conn->ssl_extra);
  3828. #endif
  3829. free(conn); /* we don't need this anymore */
  3830. conn = conn_temp;
  3831. *in_connect = conn;
  3832. infof(data, "Re-using existing connection! (#%ld) with %s %s\n",
  3833. conn->connection_id,
  3834. conn->bits.proxy?"proxy":"host",
  3835. conn->socks_proxy.host.name ? conn->socks_proxy.host.dispname :
  3836. conn->http_proxy.host.name ? conn->http_proxy.host.dispname :
  3837. conn->host.dispname);
  3838. }
  3839. else {
  3840. /* We have decided that we want a new connection. However, we may not
  3841. be able to do that if we have reached the limit of how many
  3842. connections we are allowed to open. */
  3843. if(conn->handler->flags & PROTOPT_ALPN_NPN) {
  3844. /* The protocol wants it, so set the bits if enabled in the easy handle
  3845. (default) */
  3846. if(data->set.ssl_enable_alpn)
  3847. conn->bits.tls_enable_alpn = TRUE;
  3848. if(data->set.ssl_enable_npn)
  3849. conn->bits.tls_enable_npn = TRUE;
  3850. }
  3851. if(waitpipe)
  3852. /* There is a connection that *might* become usable for pipelining
  3853. "soon", and we wait for that */
  3854. connections_available = FALSE;
  3855. else {
  3856. /* this gets a lock on the conncache */
  3857. struct connectbundle *bundle =
  3858. Curl_conncache_find_bundle(conn, data->state.conn_cache);
  3859. if(max_host_connections > 0 && bundle &&
  3860. (bundle->num_connections >= max_host_connections)) {
  3861. struct connectdata *conn_candidate;
  3862. /* The bundle is full. Extract the oldest connection. */
  3863. conn_candidate = Curl_conncache_extract_bundle(data, bundle);
  3864. Curl_conncache_unlock(conn);
  3865. if(conn_candidate) {
  3866. /* Set the connection's owner correctly, then kill it */
  3867. conn_candidate->data = data;
  3868. (void)Curl_disconnect(conn_candidate, /* dead_connection */ FALSE);
  3869. }
  3870. else {
  3871. infof(data, "No more connections allowed to host: %d\n",
  3872. max_host_connections);
  3873. connections_available = FALSE;
  3874. }
  3875. }
  3876. else
  3877. Curl_conncache_unlock(conn);
  3878. }
  3879. if(connections_available &&
  3880. (max_total_connections > 0) &&
  3881. (Curl_conncache_size(data) >= max_total_connections)) {
  3882. struct connectdata *conn_candidate;
  3883. /* The cache is full. Let's see if we can kill a connection. */
  3884. conn_candidate = Curl_conncache_extract_oldest(data);
  3885. if(conn_candidate) {
  3886. /* Set the connection's owner correctly, then kill it */
  3887. conn_candidate->data = data;
  3888. (void)Curl_disconnect(conn_candidate, /* dead_connection */ FALSE);
  3889. }
  3890. else {
  3891. infof(data, "No connections available in cache\n");
  3892. connections_available = FALSE;
  3893. }
  3894. }
  3895. if(!connections_available) {
  3896. infof(data, "No connections available.\n");
  3897. conn_free(conn);
  3898. *in_connect = NULL;
  3899. result = CURLE_NO_CONNECTION_AVAILABLE;
  3900. goto out;
  3901. }
  3902. else {
  3903. /* Mark the connection as used, before we add it */
  3904. conn->inuse = TRUE;
  3905. /*
  3906. * This is a brand new connection, so let's store it in the connection
  3907. * cache of ours!
  3908. */
  3909. Curl_conncache_add_conn(data->state.conn_cache, conn);
  3910. }
  3911. #if defined(USE_NTLM)
  3912. /* If NTLM is requested in a part of this connection, make sure we don't
  3913. assume the state is fine as this is a fresh connection and NTLM is
  3914. connection based. */
  3915. if((data->state.authhost.picked & (CURLAUTH_NTLM | CURLAUTH_NTLM_WB)) &&
  3916. data->state.authhost.done) {
  3917. infof(data, "NTLM picked AND auth done set, clear picked!\n");
  3918. data->state.authhost.picked = CURLAUTH_NONE;
  3919. data->state.authhost.done = FALSE;
  3920. }
  3921. if((data->state.authproxy.picked & (CURLAUTH_NTLM | CURLAUTH_NTLM_WB)) &&
  3922. data->state.authproxy.done) {
  3923. infof(data, "NTLM-proxy picked AND auth done set, clear picked!\n");
  3924. data->state.authproxy.picked = CURLAUTH_NONE;
  3925. data->state.authproxy.done = FALSE;
  3926. }
  3927. #endif
  3928. }
  3929. /* Setup and init stuff before DO starts, in preparing for the transfer. */
  3930. Curl_init_do(data, conn);
  3931. /*
  3932. * Setup whatever necessary for a resumed transfer
  3933. */
  3934. result = setup_range(data);
  3935. if(result)
  3936. goto out;
  3937. /* Continue connectdata initialization here. */
  3938. /*
  3939. * Inherit the proper values from the urldata struct AFTER we have arranged
  3940. * the persistent connection stuff
  3941. */
  3942. conn->seek_func = data->set.seek_func;
  3943. conn->seek_client = data->set.seek_client;
  3944. /*************************************************************
  3945. * Resolve the address of the server or proxy
  3946. *************************************************************/
  3947. result = resolve_server(data, conn, async);
  3948. out:
  3949. free(options);
  3950. free(passwd);
  3951. free(user);
  3952. return result;
  3953. }
  3954. /* Curl_setup_conn() is called after the name resolve initiated in
  3955. * create_conn() is all done.
  3956. *
  3957. * Curl_setup_conn() also handles reused connections
  3958. *
  3959. * conn->data MUST already have been setup fine (in create_conn)
  3960. */
  3961. CURLcode Curl_setup_conn(struct connectdata *conn,
  3962. bool *protocol_done)
  3963. {
  3964. CURLcode result = CURLE_OK;
  3965. struct Curl_easy *data = conn->data;
  3966. Curl_pgrsTime(data, TIMER_NAMELOOKUP);
  3967. if(conn->handler->flags & PROTOPT_NONETWORK) {
  3968. /* nothing to setup when not using a network */
  3969. *protocol_done = TRUE;
  3970. return result;
  3971. }
  3972. *protocol_done = FALSE; /* default to not done */
  3973. /* set proxy_connect_closed to false unconditionally already here since it
  3974. is used strictly to provide extra information to a parent function in the
  3975. case of proxy CONNECT failures and we must make sure we don't have it
  3976. lingering set from a previous invoke */
  3977. conn->bits.proxy_connect_closed = FALSE;
  3978. /*
  3979. * Set user-agent. Used for HTTP, but since we can attempt to tunnel
  3980. * basically anything through a http proxy we can't limit this based on
  3981. * protocol.
  3982. */
  3983. if(data->set.str[STRING_USERAGENT]) {
  3984. Curl_safefree(conn->allocptr.uagent);
  3985. conn->allocptr.uagent =
  3986. aprintf("User-Agent: %s\r\n", data->set.str[STRING_USERAGENT]);
  3987. if(!conn->allocptr.uagent)
  3988. return CURLE_OUT_OF_MEMORY;
  3989. }
  3990. data->req.headerbytecount = 0;
  3991. #ifdef CURL_DO_LINEEND_CONV
  3992. data->state.crlf_conversions = 0; /* reset CRLF conversion counter */
  3993. #endif /* CURL_DO_LINEEND_CONV */
  3994. /* set start time here for timeout purposes in the connect procedure, it
  3995. is later set again for the progress meter purpose */
  3996. conn->now = Curl_now();
  3997. if(CURL_SOCKET_BAD == conn->sock[FIRSTSOCKET]) {
  3998. conn->bits.tcpconnect[FIRSTSOCKET] = FALSE;
  3999. result = Curl_connecthost(conn, conn->dns_entry);
  4000. if(result)
  4001. return result;
  4002. }
  4003. else {
  4004. Curl_pgrsTime(data, TIMER_CONNECT); /* we're connected already */
  4005. Curl_pgrsTime(data, TIMER_APPCONNECT); /* we're connected already */
  4006. conn->bits.tcpconnect[FIRSTSOCKET] = TRUE;
  4007. *protocol_done = TRUE;
  4008. Curl_updateconninfo(conn, conn->sock[FIRSTSOCKET]);
  4009. Curl_verboseconnect(conn);
  4010. }
  4011. conn->now = Curl_now(); /* time this *after* the connect is done, we set
  4012. this here perhaps a second time */
  4013. return result;
  4014. }
  4015. CURLcode Curl_connect(struct Curl_easy *data,
  4016. struct connectdata **in_connect,
  4017. bool *asyncp,
  4018. bool *protocol_done)
  4019. {
  4020. CURLcode result;
  4021. *asyncp = FALSE; /* assume synchronous resolves by default */
  4022. /* call the stuff that needs to be called */
  4023. result = create_conn(data, in_connect, asyncp);
  4024. if(!result) {
  4025. /* no error */
  4026. if((*in_connect)->send_pipe.size || (*in_connect)->recv_pipe.size)
  4027. /* pipelining */
  4028. *protocol_done = TRUE;
  4029. else if(!*asyncp) {
  4030. /* DNS resolution is done: that's either because this is a reused
  4031. connection, in which case DNS was unnecessary, or because DNS
  4032. really did finish already (synch resolver/fast async resolve) */
  4033. result = Curl_setup_conn(*in_connect, protocol_done);
  4034. }
  4035. }
  4036. if(result == CURLE_NO_CONNECTION_AVAILABLE) {
  4037. *in_connect = NULL;
  4038. return result;
  4039. }
  4040. if(result && *in_connect) {
  4041. /* We're not allowed to return failure with memory left allocated
  4042. in the connectdata struct, free those here */
  4043. Curl_disconnect(*in_connect, FALSE); /* close the connection */
  4044. *in_connect = NULL; /* return a NULL */
  4045. }
  4046. return result;
  4047. }
  4048. /*
  4049. * Curl_init_do() inits the readwrite session. This is inited each time (in
  4050. * the DO function before the protocol-specific DO functions are invoked) for
  4051. * a transfer, sometimes multiple times on the same Curl_easy. Make sure
  4052. * nothing in here depends on stuff that are setup dynamically for the
  4053. * transfer.
  4054. *
  4055. * Allow this function to get called with 'conn' set to NULL.
  4056. */
  4057. CURLcode Curl_init_do(struct Curl_easy *data, struct connectdata *conn)
  4058. {
  4059. struct SingleRequest *k = &data->req;
  4060. conn->bits.do_more = FALSE; /* by default there's no curl_do_more() to
  4061. use */
  4062. data->state.done = FALSE; /* *_done() is not called yet */
  4063. data->state.expect100header = FALSE;
  4064. /* if the protocol used doesn't support wildcards, switch it off */
  4065. if(data->state.wildcardmatch &&
  4066. !(conn->handler->flags & PROTOPT_WILDCARD))
  4067. data->state.wildcardmatch = FALSE;
  4068. if(data->set.opt_no_body)
  4069. /* in HTTP lingo, no body means using the HEAD request... */
  4070. data->set.httpreq = HTTPREQ_HEAD;
  4071. else if(HTTPREQ_HEAD == data->set.httpreq)
  4072. /* ... but if unset there really is no perfect method that is the
  4073. "opposite" of HEAD but in reality most people probably think GET
  4074. then. The important thing is that we can't let it remain HEAD if the
  4075. opt_no_body is set FALSE since then we'll behave wrong when getting
  4076. HTTP. */
  4077. data->set.httpreq = HTTPREQ_GET;
  4078. k->start = Curl_now(); /* start time */
  4079. k->now = k->start; /* current time is now */
  4080. k->header = TRUE; /* assume header */
  4081. k->bytecount = 0;
  4082. k->buf = data->state.buffer;
  4083. k->hbufp = data->state.headerbuff;
  4084. k->ignorebody = FALSE;
  4085. Curl_speedinit(data);
  4086. Curl_pgrsSetUploadCounter(data, 0);
  4087. Curl_pgrsSetDownloadCounter(data, 0);
  4088. return CURLE_OK;
  4089. }
  4090. /*
  4091. * get_protocol_family()
  4092. *
  4093. * This is used to return the protocol family for a given protocol.
  4094. *
  4095. * Parameters:
  4096. *
  4097. * protocol [in] - A single bit protocol identifier such as HTTP or HTTPS.
  4098. *
  4099. * Returns the family as a single bit protocol identifier.
  4100. */
  4101. static unsigned int get_protocol_family(unsigned int protocol)
  4102. {
  4103. unsigned int family;
  4104. switch(protocol) {
  4105. case CURLPROTO_HTTP:
  4106. case CURLPROTO_HTTPS:
  4107. family = CURLPROTO_HTTP;
  4108. break;
  4109. case CURLPROTO_FTP:
  4110. case CURLPROTO_FTPS:
  4111. family = CURLPROTO_FTP;
  4112. break;
  4113. case CURLPROTO_SCP:
  4114. family = CURLPROTO_SCP;
  4115. break;
  4116. case CURLPROTO_SFTP:
  4117. family = CURLPROTO_SFTP;
  4118. break;
  4119. case CURLPROTO_TELNET:
  4120. family = CURLPROTO_TELNET;
  4121. break;
  4122. case CURLPROTO_LDAP:
  4123. case CURLPROTO_LDAPS:
  4124. family = CURLPROTO_LDAP;
  4125. break;
  4126. case CURLPROTO_DICT:
  4127. family = CURLPROTO_DICT;
  4128. break;
  4129. case CURLPROTO_FILE:
  4130. family = CURLPROTO_FILE;
  4131. break;
  4132. case CURLPROTO_TFTP:
  4133. family = CURLPROTO_TFTP;
  4134. break;
  4135. case CURLPROTO_IMAP:
  4136. case CURLPROTO_IMAPS:
  4137. family = CURLPROTO_IMAP;
  4138. break;
  4139. case CURLPROTO_POP3:
  4140. case CURLPROTO_POP3S:
  4141. family = CURLPROTO_POP3;
  4142. break;
  4143. case CURLPROTO_SMTP:
  4144. case CURLPROTO_SMTPS:
  4145. family = CURLPROTO_SMTP;
  4146. break;
  4147. case CURLPROTO_RTSP:
  4148. family = CURLPROTO_RTSP;
  4149. break;
  4150. case CURLPROTO_RTMP:
  4151. case CURLPROTO_RTMPS:
  4152. family = CURLPROTO_RTMP;
  4153. break;
  4154. case CURLPROTO_RTMPT:
  4155. case CURLPROTO_RTMPTS:
  4156. family = CURLPROTO_RTMPT;
  4157. break;
  4158. case CURLPROTO_RTMPE:
  4159. family = CURLPROTO_RTMPE;
  4160. break;
  4161. case CURLPROTO_RTMPTE:
  4162. family = CURLPROTO_RTMPTE;
  4163. break;
  4164. case CURLPROTO_GOPHER:
  4165. family = CURLPROTO_GOPHER;
  4166. break;
  4167. case CURLPROTO_SMB:
  4168. case CURLPROTO_SMBS:
  4169. family = CURLPROTO_SMB;
  4170. break;
  4171. default:
  4172. family = 0;
  4173. break;
  4174. }
  4175. return family;
  4176. }