http.c 125 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924
  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. #ifndef CURL_DISABLE_HTTP
  24. #ifdef HAVE_NETINET_IN_H
  25. #include <netinet/in.h>
  26. #endif
  27. #ifdef HAVE_NETDB_H
  28. #include <netdb.h>
  29. #endif
  30. #ifdef HAVE_ARPA_INET_H
  31. #include <arpa/inet.h>
  32. #endif
  33. #ifdef HAVE_NET_IF_H
  34. #include <net/if.h>
  35. #endif
  36. #ifdef HAVE_SYS_IOCTL_H
  37. #include <sys/ioctl.h>
  38. #endif
  39. #ifdef HAVE_SYS_PARAM_H
  40. #include <sys/param.h>
  41. #endif
  42. #include "urldata.h"
  43. #include <curl/curl.h>
  44. #include "transfer.h"
  45. #include "sendf.h"
  46. #include "formdata.h"
  47. #include "mime.h"
  48. #include "progress.h"
  49. #include "curl_base64.h"
  50. #include "cookie.h"
  51. #include "vauth/vauth.h"
  52. #include "vtls/vtls.h"
  53. #include "http_digest.h"
  54. #include "http_ntlm.h"
  55. #include "curl_ntlm_wb.h"
  56. #include "http_negotiate.h"
  57. #include "url.h"
  58. #include "share.h"
  59. #include "hostip.h"
  60. #include "http.h"
  61. #include "select.h"
  62. #include "parsedate.h" /* for the week day and month names */
  63. #include "strtoofft.h"
  64. #include "multiif.h"
  65. #include "strcase.h"
  66. #include "content_encoding.h"
  67. #include "http_proxy.h"
  68. #include "warnless.h"
  69. #include "non-ascii.h"
  70. #include "pipeline.h"
  71. #include "http2.h"
  72. #include "connect.h"
  73. #include "strdup.h"
  74. /* The last 3 #include files should be in this order */
  75. #include "curl_printf.h"
  76. #include "curl_memory.h"
  77. #include "memdebug.h"
  78. /*
  79. * Forward declarations.
  80. */
  81. static int http_getsock_do(struct connectdata *conn,
  82. curl_socket_t *socks,
  83. int numsocks);
  84. static int http_should_fail(struct connectdata *conn);
  85. static CURLcode add_haproxy_protocol_header(struct connectdata *conn);
  86. #ifdef USE_SSL
  87. static CURLcode https_connecting(struct connectdata *conn, bool *done);
  88. static int https_getsock(struct connectdata *conn,
  89. curl_socket_t *socks,
  90. int numsocks);
  91. #else
  92. #define https_connecting(x,y) CURLE_COULDNT_CONNECT
  93. #endif
  94. /*
  95. * HTTP handler interface.
  96. */
  97. const struct Curl_handler Curl_handler_http = {
  98. "HTTP", /* scheme */
  99. Curl_http_setup_conn, /* setup_connection */
  100. Curl_http, /* do_it */
  101. Curl_http_done, /* done */
  102. ZERO_NULL, /* do_more */
  103. Curl_http_connect, /* connect_it */
  104. ZERO_NULL, /* connecting */
  105. ZERO_NULL, /* doing */
  106. ZERO_NULL, /* proto_getsock */
  107. http_getsock_do, /* doing_getsock */
  108. ZERO_NULL, /* domore_getsock */
  109. ZERO_NULL, /* perform_getsock */
  110. ZERO_NULL, /* disconnect */
  111. ZERO_NULL, /* readwrite */
  112. ZERO_NULL, /* connection_check */
  113. PORT_HTTP, /* defport */
  114. CURLPROTO_HTTP, /* protocol */
  115. PROTOPT_CREDSPERREQUEST /* flags */
  116. };
  117. #ifdef USE_SSL
  118. /*
  119. * HTTPS handler interface.
  120. */
  121. const struct Curl_handler Curl_handler_https = {
  122. "HTTPS", /* scheme */
  123. Curl_http_setup_conn, /* setup_connection */
  124. Curl_http, /* do_it */
  125. Curl_http_done, /* done */
  126. ZERO_NULL, /* do_more */
  127. Curl_http_connect, /* connect_it */
  128. https_connecting, /* connecting */
  129. ZERO_NULL, /* doing */
  130. https_getsock, /* proto_getsock */
  131. http_getsock_do, /* doing_getsock */
  132. ZERO_NULL, /* domore_getsock */
  133. ZERO_NULL, /* perform_getsock */
  134. ZERO_NULL, /* disconnect */
  135. ZERO_NULL, /* readwrite */
  136. ZERO_NULL, /* connection_check */
  137. PORT_HTTPS, /* defport */
  138. CURLPROTO_HTTPS, /* protocol */
  139. PROTOPT_SSL | PROTOPT_CREDSPERREQUEST | PROTOPT_ALPN_NPN /* flags */
  140. };
  141. #endif
  142. CURLcode Curl_http_setup_conn(struct connectdata *conn)
  143. {
  144. /* allocate the HTTP-specific struct for the Curl_easy, only to survive
  145. during this request */
  146. struct HTTP *http;
  147. struct Curl_easy *data = conn->data;
  148. DEBUGASSERT(data->req.protop == NULL);
  149. http = calloc(1, sizeof(struct HTTP));
  150. if(!http)
  151. return CURLE_OUT_OF_MEMORY;
  152. Curl_mime_initpart(&http->form, conn->data);
  153. data->req.protop = http;
  154. if(!CONN_INUSE(conn))
  155. /* if not alredy multi-using, setup connection details */
  156. Curl_http2_setup_conn(conn);
  157. Curl_http2_setup_req(data);
  158. return CURLE_OK;
  159. }
  160. /*
  161. * checkProxyHeaders() checks the linked list of custom proxy headers
  162. * if proxy headers are not available, then it will lookup into http header
  163. * link list
  164. *
  165. * It takes a connectdata struct as input instead of the Curl_easy simply to
  166. * know if this is a proxy request or not, as it then might check a different
  167. * header list. Provide the header prefix without colon!.
  168. */
  169. char *Curl_checkProxyheaders(const struct connectdata *conn,
  170. const char *thisheader)
  171. {
  172. struct curl_slist *head;
  173. size_t thislen = strlen(thisheader);
  174. struct Curl_easy *data = conn->data;
  175. for(head = (conn->bits.proxy && data->set.sep_headers) ?
  176. data->set.proxyheaders : data->set.headers;
  177. head; head = head->next) {
  178. if(strncasecompare(head->data, thisheader, thislen) &&
  179. Curl_headersep(head->data[thislen]))
  180. return head->data;
  181. }
  182. return NULL;
  183. }
  184. /*
  185. * Strip off leading and trailing whitespace from the value in the
  186. * given HTTP header line and return a strdupped copy. Returns NULL in
  187. * case of allocation failure. Returns an empty string if the header value
  188. * consists entirely of whitespace.
  189. */
  190. char *Curl_copy_header_value(const char *header)
  191. {
  192. const char *start;
  193. const char *end;
  194. char *value;
  195. size_t len;
  196. /* Find the end of the header name */
  197. while(*header && (*header != ':'))
  198. ++header;
  199. if(*header)
  200. /* Skip over colon */
  201. ++header;
  202. /* Find the first non-space letter */
  203. start = header;
  204. while(*start && ISSPACE(*start))
  205. start++;
  206. /* data is in the host encoding so
  207. use '\r' and '\n' instead of 0x0d and 0x0a */
  208. end = strchr(start, '\r');
  209. if(!end)
  210. end = strchr(start, '\n');
  211. if(!end)
  212. end = strchr(start, '\0');
  213. if(!end)
  214. return NULL;
  215. /* skip all trailing space letters */
  216. while((end > start) && ISSPACE(*end))
  217. end--;
  218. /* get length of the type */
  219. len = end - start + 1;
  220. value = malloc(len + 1);
  221. if(!value)
  222. return NULL;
  223. memcpy(value, start, len);
  224. value[len] = 0; /* zero terminate */
  225. return value;
  226. }
  227. /*
  228. * http_output_basic() sets up an Authorization: header (or the proxy version)
  229. * for HTTP Basic authentication.
  230. *
  231. * Returns CURLcode.
  232. */
  233. static CURLcode http_output_basic(struct connectdata *conn, bool proxy)
  234. {
  235. size_t size = 0;
  236. char *authorization = NULL;
  237. struct Curl_easy *data = conn->data;
  238. char **userp;
  239. const char *user;
  240. const char *pwd;
  241. CURLcode result;
  242. char *out;
  243. if(proxy) {
  244. userp = &conn->allocptr.proxyuserpwd;
  245. user = conn->http_proxy.user;
  246. pwd = conn->http_proxy.passwd;
  247. }
  248. else {
  249. userp = &conn->allocptr.userpwd;
  250. user = conn->user;
  251. pwd = conn->passwd;
  252. }
  253. out = aprintf("%s:%s", user, pwd);
  254. if(!out)
  255. return CURLE_OUT_OF_MEMORY;
  256. result = Curl_base64_encode(data, out, strlen(out), &authorization, &size);
  257. if(result)
  258. goto fail;
  259. if(!authorization) {
  260. result = CURLE_REMOTE_ACCESS_DENIED;
  261. goto fail;
  262. }
  263. free(*userp);
  264. *userp = aprintf("%sAuthorization: Basic %s\r\n",
  265. proxy ? "Proxy-" : "",
  266. authorization);
  267. free(authorization);
  268. if(!*userp) {
  269. result = CURLE_OUT_OF_MEMORY;
  270. goto fail;
  271. }
  272. fail:
  273. free(out);
  274. return result;
  275. }
  276. /*
  277. * http_output_bearer() sets up an Authorization: header
  278. * for HTTP Bearer authentication.
  279. *
  280. * Returns CURLcode.
  281. */
  282. static CURLcode http_output_bearer(struct connectdata *conn)
  283. {
  284. char **userp;
  285. CURLcode result = CURLE_OK;
  286. userp = &conn->allocptr.userpwd;
  287. free(*userp);
  288. *userp = aprintf("Authorization: Bearer %s\r\n",
  289. conn->oauth_bearer);
  290. if(!*userp) {
  291. result = CURLE_OUT_OF_MEMORY;
  292. goto fail;
  293. }
  294. fail:
  295. return result;
  296. }
  297. /* pickoneauth() selects the most favourable authentication method from the
  298. * ones available and the ones we want.
  299. *
  300. * return TRUE if one was picked
  301. */
  302. static bool pickoneauth(struct auth *pick, unsigned long mask)
  303. {
  304. bool picked;
  305. /* only deal with authentication we want */
  306. unsigned long avail = pick->avail & pick->want & mask;
  307. picked = TRUE;
  308. /* The order of these checks is highly relevant, as this will be the order
  309. of preference in case of the existence of multiple accepted types. */
  310. if(avail & CURLAUTH_NEGOTIATE)
  311. pick->picked = CURLAUTH_NEGOTIATE;
  312. else if(avail & CURLAUTH_BEARER)
  313. pick->picked = CURLAUTH_BEARER;
  314. else if(avail & CURLAUTH_DIGEST)
  315. pick->picked = CURLAUTH_DIGEST;
  316. else if(avail & CURLAUTH_NTLM)
  317. pick->picked = CURLAUTH_NTLM;
  318. else if(avail & CURLAUTH_NTLM_WB)
  319. pick->picked = CURLAUTH_NTLM_WB;
  320. else if(avail & CURLAUTH_BASIC)
  321. pick->picked = CURLAUTH_BASIC;
  322. else {
  323. pick->picked = CURLAUTH_PICKNONE; /* we select to use nothing */
  324. picked = FALSE;
  325. }
  326. pick->avail = CURLAUTH_NONE; /* clear it here */
  327. return picked;
  328. }
  329. /*
  330. * Curl_http_perhapsrewind()
  331. *
  332. * If we are doing POST or PUT {
  333. * If we have more data to send {
  334. * If we are doing NTLM {
  335. * Keep sending since we must not disconnect
  336. * }
  337. * else {
  338. * If there is more than just a little data left to send, close
  339. * the current connection by force.
  340. * }
  341. * }
  342. * If we have sent any data {
  343. * If we don't have track of all the data {
  344. * call app to tell it to rewind
  345. * }
  346. * else {
  347. * rewind internally so that the operation can restart fine
  348. * }
  349. * }
  350. * }
  351. */
  352. static CURLcode http_perhapsrewind(struct connectdata *conn)
  353. {
  354. struct Curl_easy *data = conn->data;
  355. struct HTTP *http = data->req.protop;
  356. curl_off_t bytessent;
  357. curl_off_t expectsend = -1; /* default is unknown */
  358. if(!http)
  359. /* If this is still NULL, we have not reach very far and we can safely
  360. skip this rewinding stuff */
  361. return CURLE_OK;
  362. switch(data->set.httpreq) {
  363. case HTTPREQ_GET:
  364. case HTTPREQ_HEAD:
  365. return CURLE_OK;
  366. default:
  367. break;
  368. }
  369. bytessent = http->writebytecount;
  370. if(conn->bits.authneg) {
  371. /* This is a state where we are known to be negotiating and we don't send
  372. any data then. */
  373. expectsend = 0;
  374. }
  375. else if(!conn->bits.protoconnstart) {
  376. /* HTTP CONNECT in progress: there is no body */
  377. expectsend = 0;
  378. }
  379. else {
  380. /* figure out how much data we are expected to send */
  381. switch(data->set.httpreq) {
  382. case HTTPREQ_POST:
  383. if(data->state.infilesize != -1)
  384. expectsend = data->state.infilesize;
  385. break;
  386. case HTTPREQ_PUT:
  387. if(data->state.infilesize != -1)
  388. expectsend = data->state.infilesize;
  389. break;
  390. case HTTPREQ_POST_FORM:
  391. case HTTPREQ_POST_MIME:
  392. expectsend = http->postsize;
  393. break;
  394. default:
  395. break;
  396. }
  397. }
  398. conn->bits.rewindaftersend = FALSE; /* default */
  399. if((expectsend == -1) || (expectsend > bytessent)) {
  400. #if defined(USE_NTLM)
  401. /* There is still data left to send */
  402. if((data->state.authproxy.picked == CURLAUTH_NTLM) ||
  403. (data->state.authhost.picked == CURLAUTH_NTLM) ||
  404. (data->state.authproxy.picked == CURLAUTH_NTLM_WB) ||
  405. (data->state.authhost.picked == CURLAUTH_NTLM_WB)) {
  406. if(((expectsend - bytessent) < 2000) ||
  407. (conn->ntlm.state != NTLMSTATE_NONE) ||
  408. (conn->proxyntlm.state != NTLMSTATE_NONE)) {
  409. /* The NTLM-negotiation has started *OR* there is just a little (<2K)
  410. data left to send, keep on sending. */
  411. /* rewind data when completely done sending! */
  412. if(!conn->bits.authneg && (conn->writesockfd != CURL_SOCKET_BAD)) {
  413. conn->bits.rewindaftersend = TRUE;
  414. infof(data, "Rewind stream after send\n");
  415. }
  416. return CURLE_OK;
  417. }
  418. if(conn->bits.close)
  419. /* this is already marked to get closed */
  420. return CURLE_OK;
  421. infof(data, "NTLM send, close instead of sending %"
  422. CURL_FORMAT_CURL_OFF_T " bytes\n",
  423. (curl_off_t)(expectsend - bytessent));
  424. }
  425. #endif
  426. /* This is not NTLM or many bytes left to send: close */
  427. streamclose(conn, "Mid-auth HTTP and much data left to send");
  428. data->req.size = 0; /* don't download any more than 0 bytes */
  429. /* There still is data left to send, but this connection is marked for
  430. closure so we can safely do the rewind right now */
  431. }
  432. if(bytessent)
  433. /* we rewind now at once since if we already sent something */
  434. return Curl_readrewind(conn);
  435. return CURLE_OK;
  436. }
  437. /*
  438. * Curl_http_auth_act() gets called when all HTTP headers have been received
  439. * and it checks what authentication methods that are available and decides
  440. * which one (if any) to use. It will set 'newurl' if an auth method was
  441. * picked.
  442. */
  443. CURLcode Curl_http_auth_act(struct connectdata *conn)
  444. {
  445. struct Curl_easy *data = conn->data;
  446. bool pickhost = FALSE;
  447. bool pickproxy = FALSE;
  448. CURLcode result = CURLE_OK;
  449. unsigned long authmask = ~0ul;
  450. if(!conn->oauth_bearer)
  451. authmask &= (unsigned long)~CURLAUTH_BEARER;
  452. if(100 <= data->req.httpcode && 199 >= data->req.httpcode)
  453. /* this is a transient response code, ignore */
  454. return CURLE_OK;
  455. if(data->state.authproblem)
  456. return data->set.http_fail_on_error?CURLE_HTTP_RETURNED_ERROR:CURLE_OK;
  457. if((conn->bits.user_passwd || conn->oauth_bearer) &&
  458. ((data->req.httpcode == 401) ||
  459. (conn->bits.authneg && data->req.httpcode < 300))) {
  460. pickhost = pickoneauth(&data->state.authhost, authmask);
  461. if(!pickhost)
  462. data->state.authproblem = TRUE;
  463. }
  464. if(conn->bits.proxy_user_passwd &&
  465. ((data->req.httpcode == 407) ||
  466. (conn->bits.authneg && data->req.httpcode < 300))) {
  467. pickproxy = pickoneauth(&data->state.authproxy,
  468. authmask & ~CURLAUTH_BEARER);
  469. if(!pickproxy)
  470. data->state.authproblem = TRUE;
  471. }
  472. if(pickhost || pickproxy) {
  473. /* In case this is GSS auth, the newurl field is already allocated so
  474. we must make sure to free it before allocating a new one. As figured
  475. out in bug #2284386 */
  476. Curl_safefree(data->req.newurl);
  477. data->req.newurl = strdup(data->change.url); /* clone URL */
  478. if(!data->req.newurl)
  479. return CURLE_OUT_OF_MEMORY;
  480. if((data->set.httpreq != HTTPREQ_GET) &&
  481. (data->set.httpreq != HTTPREQ_HEAD) &&
  482. !conn->bits.rewindaftersend) {
  483. result = http_perhapsrewind(conn);
  484. if(result)
  485. return result;
  486. }
  487. }
  488. else if((data->req.httpcode < 300) &&
  489. (!data->state.authhost.done) &&
  490. conn->bits.authneg) {
  491. /* no (known) authentication available,
  492. authentication is not "done" yet and
  493. no authentication seems to be required and
  494. we didn't try HEAD or GET */
  495. if((data->set.httpreq != HTTPREQ_GET) &&
  496. (data->set.httpreq != HTTPREQ_HEAD)) {
  497. data->req.newurl = strdup(data->change.url); /* clone URL */
  498. if(!data->req.newurl)
  499. return CURLE_OUT_OF_MEMORY;
  500. data->state.authhost.done = TRUE;
  501. }
  502. }
  503. if(http_should_fail(conn)) {
  504. failf(data, "The requested URL returned error: %d",
  505. data->req.httpcode);
  506. result = CURLE_HTTP_RETURNED_ERROR;
  507. }
  508. return result;
  509. }
  510. /*
  511. * Output the correct authentication header depending on the auth type
  512. * and whether or not it is to a proxy.
  513. */
  514. static CURLcode
  515. output_auth_headers(struct connectdata *conn,
  516. struct auth *authstatus,
  517. const char *request,
  518. const char *path,
  519. bool proxy)
  520. {
  521. const char *auth = NULL;
  522. CURLcode result = CURLE_OK;
  523. #if !defined(CURL_DISABLE_VERBOSE_STRINGS) || defined(USE_SPNEGO)
  524. struct Curl_easy *data = conn->data;
  525. #endif
  526. #ifdef USE_SPNEGO
  527. struct negotiatedata *negdata = proxy ?
  528. &data->state.proxyneg : &data->state.negotiate;
  529. #endif
  530. #ifdef CURL_DISABLE_CRYPTO_AUTH
  531. (void)request;
  532. (void)path;
  533. #endif
  534. #ifdef USE_SPNEGO
  535. negdata->state = GSS_AUTHNONE;
  536. if((authstatus->picked == CURLAUTH_NEGOTIATE) &&
  537. negdata->context && !GSS_ERROR(negdata->status)) {
  538. auth = "Negotiate";
  539. result = Curl_output_negotiate(conn, proxy);
  540. if(result)
  541. return result;
  542. authstatus->done = TRUE;
  543. negdata->state = GSS_AUTHSENT;
  544. }
  545. else
  546. #endif
  547. #ifdef USE_NTLM
  548. if(authstatus->picked == CURLAUTH_NTLM) {
  549. auth = "NTLM";
  550. result = Curl_output_ntlm(conn, proxy);
  551. if(result)
  552. return result;
  553. }
  554. else
  555. #endif
  556. #if defined(USE_NTLM) && defined(NTLM_WB_ENABLED)
  557. if(authstatus->picked == CURLAUTH_NTLM_WB) {
  558. auth = "NTLM_WB";
  559. result = Curl_output_ntlm_wb(conn, proxy);
  560. if(result)
  561. return result;
  562. }
  563. else
  564. #endif
  565. #ifndef CURL_DISABLE_CRYPTO_AUTH
  566. if(authstatus->picked == CURLAUTH_DIGEST) {
  567. auth = "Digest";
  568. result = Curl_output_digest(conn,
  569. proxy,
  570. (const unsigned char *)request,
  571. (const unsigned char *)path);
  572. if(result)
  573. return result;
  574. }
  575. else
  576. #endif
  577. if(authstatus->picked == CURLAUTH_BASIC) {
  578. /* Basic */
  579. if((proxy && conn->bits.proxy_user_passwd &&
  580. !Curl_checkProxyheaders(conn, "Proxy-authorization")) ||
  581. (!proxy && conn->bits.user_passwd &&
  582. !Curl_checkheaders(conn, "Authorization"))) {
  583. auth = "Basic";
  584. result = http_output_basic(conn, proxy);
  585. if(result)
  586. return result;
  587. }
  588. /* NOTE: this function should set 'done' TRUE, as the other auth
  589. functions work that way */
  590. authstatus->done = TRUE;
  591. }
  592. if(authstatus->picked == CURLAUTH_BEARER) {
  593. /* Bearer */
  594. if((!proxy && conn->oauth_bearer &&
  595. !Curl_checkheaders(conn, "Authorization:"))) {
  596. auth = "Bearer";
  597. result = http_output_bearer(conn);
  598. if(result)
  599. return result;
  600. }
  601. /* NOTE: this function should set 'done' TRUE, as the other auth
  602. functions work that way */
  603. authstatus->done = TRUE;
  604. }
  605. if(auth) {
  606. infof(data, "%s auth using %s with user '%s'\n",
  607. proxy ? "Proxy" : "Server", auth,
  608. proxy ? (conn->http_proxy.user ? conn->http_proxy.user : "") :
  609. (conn->user ? conn->user : ""));
  610. authstatus->multipass = (!authstatus->done) ? TRUE : FALSE;
  611. }
  612. else
  613. authstatus->multipass = FALSE;
  614. return CURLE_OK;
  615. }
  616. /**
  617. * Curl_http_output_auth() setups the authentication headers for the
  618. * host/proxy and the correct authentication
  619. * method. conn->data->state.authdone is set to TRUE when authentication is
  620. * done.
  621. *
  622. * @param conn all information about the current connection
  623. * @param request pointer to the request keyword
  624. * @param path pointer to the requested path
  625. * @param proxytunnel boolean if this is the request setting up a "proxy
  626. * tunnel"
  627. *
  628. * @returns CURLcode
  629. */
  630. CURLcode
  631. Curl_http_output_auth(struct connectdata *conn,
  632. const char *request,
  633. const char *path,
  634. bool proxytunnel) /* TRUE if this is the request setting
  635. up the proxy tunnel */
  636. {
  637. CURLcode result = CURLE_OK;
  638. struct Curl_easy *data = conn->data;
  639. struct auth *authhost;
  640. struct auth *authproxy;
  641. DEBUGASSERT(data);
  642. authhost = &data->state.authhost;
  643. authproxy = &data->state.authproxy;
  644. if((conn->bits.httpproxy && conn->bits.proxy_user_passwd) ||
  645. conn->bits.user_passwd || conn->oauth_bearer)
  646. /* continue please */;
  647. else {
  648. authhost->done = TRUE;
  649. authproxy->done = TRUE;
  650. return CURLE_OK; /* no authentication with no user or password */
  651. }
  652. if(authhost->want && !authhost->picked)
  653. /* The app has selected one or more methods, but none has been picked
  654. so far by a server round-trip. Then we set the picked one to the
  655. want one, and if this is one single bit it'll be used instantly. */
  656. authhost->picked = authhost->want;
  657. if(authproxy->want && !authproxy->picked)
  658. /* The app has selected one or more methods, but none has been picked so
  659. far by a proxy round-trip. Then we set the picked one to the want one,
  660. and if this is one single bit it'll be used instantly. */
  661. authproxy->picked = authproxy->want;
  662. #ifndef CURL_DISABLE_PROXY
  663. /* Send proxy authentication header if needed */
  664. if(conn->bits.httpproxy &&
  665. (conn->bits.tunnel_proxy == proxytunnel)) {
  666. result = output_auth_headers(conn, authproxy, request, path, TRUE);
  667. if(result)
  668. return result;
  669. }
  670. else
  671. #else
  672. (void)proxytunnel;
  673. #endif /* CURL_DISABLE_PROXY */
  674. /* we have no proxy so let's pretend we're done authenticating
  675. with it */
  676. authproxy->done = TRUE;
  677. /* To prevent the user+password to get sent to other than the original
  678. host due to a location-follow, we do some weirdo checks here */
  679. if(!data->state.this_is_a_follow ||
  680. conn->bits.netrc ||
  681. !data->state.first_host ||
  682. data->set.allow_auth_to_other_hosts ||
  683. strcasecompare(data->state.first_host, conn->host.name)) {
  684. result = output_auth_headers(conn, authhost, request, path, FALSE);
  685. }
  686. else
  687. authhost->done = TRUE;
  688. return result;
  689. }
  690. /*
  691. * Curl_http_input_auth() deals with Proxy-Authenticate: and WWW-Authenticate:
  692. * headers. They are dealt with both in the transfer.c main loop and in the
  693. * proxy CONNECT loop.
  694. */
  695. CURLcode Curl_http_input_auth(struct connectdata *conn, bool proxy,
  696. const char *auth) /* the first non-space */
  697. {
  698. /*
  699. * This resource requires authentication
  700. */
  701. struct Curl_easy *data = conn->data;
  702. #ifdef USE_SPNEGO
  703. struct negotiatedata *negdata = proxy?
  704. &data->state.proxyneg:&data->state.negotiate;
  705. #endif
  706. unsigned long *availp;
  707. struct auth *authp;
  708. if(proxy) {
  709. availp = &data->info.proxyauthavail;
  710. authp = &data->state.authproxy;
  711. }
  712. else {
  713. availp = &data->info.httpauthavail;
  714. authp = &data->state.authhost;
  715. }
  716. /*
  717. * Here we check if we want the specific single authentication (using ==) and
  718. * if we do, we initiate usage of it.
  719. *
  720. * If the provided authentication is wanted as one out of several accepted
  721. * types (using &), we OR this authentication type to the authavail
  722. * variable.
  723. *
  724. * Note:
  725. *
  726. * ->picked is first set to the 'want' value (one or more bits) before the
  727. * request is sent, and then it is again set _after_ all response 401/407
  728. * headers have been received but then only to a single preferred method
  729. * (bit).
  730. */
  731. while(*auth) {
  732. #ifdef USE_SPNEGO
  733. if(checkprefix("Negotiate", auth)) {
  734. if((authp->avail & CURLAUTH_NEGOTIATE) ||
  735. Curl_auth_is_spnego_supported()) {
  736. *availp |= CURLAUTH_NEGOTIATE;
  737. authp->avail |= CURLAUTH_NEGOTIATE;
  738. if(authp->picked == CURLAUTH_NEGOTIATE) {
  739. if(negdata->state == GSS_AUTHSENT ||
  740. negdata->state == GSS_AUTHNONE) {
  741. CURLcode result = Curl_input_negotiate(conn, proxy, auth);
  742. if(!result) {
  743. DEBUGASSERT(!data->req.newurl);
  744. data->req.newurl = strdup(data->change.url);
  745. if(!data->req.newurl)
  746. return CURLE_OUT_OF_MEMORY;
  747. data->state.authproblem = FALSE;
  748. /* we received a GSS auth token and we dealt with it fine */
  749. negdata->state = GSS_AUTHRECV;
  750. }
  751. else
  752. data->state.authproblem = TRUE;
  753. }
  754. }
  755. }
  756. }
  757. else
  758. #endif
  759. #ifdef USE_NTLM
  760. /* NTLM support requires the SSL crypto libs */
  761. if(checkprefix("NTLM", auth)) {
  762. if((authp->avail & CURLAUTH_NTLM) ||
  763. (authp->avail & CURLAUTH_NTLM_WB) ||
  764. Curl_auth_is_ntlm_supported()) {
  765. *availp |= CURLAUTH_NTLM;
  766. authp->avail |= CURLAUTH_NTLM;
  767. if(authp->picked == CURLAUTH_NTLM ||
  768. authp->picked == CURLAUTH_NTLM_WB) {
  769. /* NTLM authentication is picked and activated */
  770. CURLcode result = Curl_input_ntlm(conn, proxy, auth);
  771. if(!result) {
  772. data->state.authproblem = FALSE;
  773. #ifdef NTLM_WB_ENABLED
  774. if(authp->picked == CURLAUTH_NTLM_WB) {
  775. *availp &= ~CURLAUTH_NTLM;
  776. authp->avail &= ~CURLAUTH_NTLM;
  777. *availp |= CURLAUTH_NTLM_WB;
  778. authp->avail |= CURLAUTH_NTLM_WB;
  779. /* Get the challenge-message which will be passed to
  780. * ntlm_auth for generating the type 3 message later */
  781. while(*auth && ISSPACE(*auth))
  782. auth++;
  783. if(checkprefix("NTLM", auth)) {
  784. auth += strlen("NTLM");
  785. while(*auth && ISSPACE(*auth))
  786. auth++;
  787. if(*auth) {
  788. conn->challenge_header = strdup(auth);
  789. if(!conn->challenge_header)
  790. return CURLE_OUT_OF_MEMORY;
  791. }
  792. }
  793. }
  794. #endif
  795. }
  796. else {
  797. infof(data, "Authentication problem. Ignoring this.\n");
  798. data->state.authproblem = TRUE;
  799. }
  800. }
  801. }
  802. }
  803. else
  804. #endif
  805. #ifndef CURL_DISABLE_CRYPTO_AUTH
  806. if(checkprefix("Digest", auth)) {
  807. if((authp->avail & CURLAUTH_DIGEST) != 0)
  808. infof(data, "Ignoring duplicate digest auth header.\n");
  809. else if(Curl_auth_is_digest_supported()) {
  810. CURLcode result;
  811. *availp |= CURLAUTH_DIGEST;
  812. authp->avail |= CURLAUTH_DIGEST;
  813. /* We call this function on input Digest headers even if Digest
  814. * authentication isn't activated yet, as we need to store the
  815. * incoming data from this header in case we are going to use
  816. * Digest */
  817. result = Curl_input_digest(conn, proxy, auth);
  818. if(result) {
  819. infof(data, "Authentication problem. Ignoring this.\n");
  820. data->state.authproblem = TRUE;
  821. }
  822. }
  823. }
  824. else
  825. #endif
  826. if(checkprefix("Basic", auth)) {
  827. *availp |= CURLAUTH_BASIC;
  828. authp->avail |= CURLAUTH_BASIC;
  829. if(authp->picked == CURLAUTH_BASIC) {
  830. /* We asked for Basic authentication but got a 40X back
  831. anyway, which basically means our name+password isn't
  832. valid. */
  833. authp->avail = CURLAUTH_NONE;
  834. infof(data, "Authentication problem. Ignoring this.\n");
  835. data->state.authproblem = TRUE;
  836. }
  837. }
  838. else
  839. if(checkprefix("Bearer", auth)) {
  840. *availp |= CURLAUTH_BEARER;
  841. authp->avail |= CURLAUTH_BEARER;
  842. if(authp->picked == CURLAUTH_BEARER) {
  843. /* We asked for Bearer authentication but got a 40X back
  844. anyway, which basically means our token isn't valid. */
  845. authp->avail = CURLAUTH_NONE;
  846. infof(data, "Authentication problem. Ignoring this.\n");
  847. data->state.authproblem = TRUE;
  848. }
  849. }
  850. /* there may be multiple methods on one line, so keep reading */
  851. while(*auth && *auth != ',') /* read up to the next comma */
  852. auth++;
  853. if(*auth == ',') /* if we're on a comma, skip it */
  854. auth++;
  855. while(*auth && ISSPACE(*auth))
  856. auth++;
  857. }
  858. return CURLE_OK;
  859. }
  860. /**
  861. * http_should_fail() determines whether an HTTP response has gotten us
  862. * into an error state or not.
  863. *
  864. * @param conn all information about the current connection
  865. *
  866. * @retval 0 communications should continue
  867. *
  868. * @retval 1 communications should not continue
  869. */
  870. static int http_should_fail(struct connectdata *conn)
  871. {
  872. struct Curl_easy *data;
  873. int httpcode;
  874. DEBUGASSERT(conn);
  875. data = conn->data;
  876. DEBUGASSERT(data);
  877. httpcode = data->req.httpcode;
  878. /*
  879. ** If we haven't been asked to fail on error,
  880. ** don't fail.
  881. */
  882. if(!data->set.http_fail_on_error)
  883. return 0;
  884. /*
  885. ** Any code < 400 is never terminal.
  886. */
  887. if(httpcode < 400)
  888. return 0;
  889. /*
  890. ** Any code >= 400 that's not 401 or 407 is always
  891. ** a terminal error
  892. */
  893. if((httpcode != 401) && (httpcode != 407))
  894. return 1;
  895. /*
  896. ** All we have left to deal with is 401 and 407
  897. */
  898. DEBUGASSERT((httpcode == 401) || (httpcode == 407));
  899. /*
  900. ** Examine the current authentication state to see if this
  901. ** is an error. The idea is for this function to get
  902. ** called after processing all the headers in a response
  903. ** message. So, if we've been to asked to authenticate a
  904. ** particular stage, and we've done it, we're OK. But, if
  905. ** we're already completely authenticated, it's not OK to
  906. ** get another 401 or 407.
  907. **
  908. ** It is possible for authentication to go stale such that
  909. ** the client needs to reauthenticate. Once that info is
  910. ** available, use it here.
  911. */
  912. /*
  913. ** Either we're not authenticating, or we're supposed to
  914. ** be authenticating something else. This is an error.
  915. */
  916. if((httpcode == 401) && !conn->bits.user_passwd)
  917. return TRUE;
  918. if((httpcode == 407) && !conn->bits.proxy_user_passwd)
  919. return TRUE;
  920. return data->state.authproblem;
  921. }
  922. /*
  923. * readmoredata() is a "fread() emulation" to provide POST and/or request
  924. * data. It is used when a huge POST is to be made and the entire chunk wasn't
  925. * sent in the first send(). This function will then be called from the
  926. * transfer.c loop when more data is to be sent to the peer.
  927. *
  928. * Returns the amount of bytes it filled the buffer with.
  929. */
  930. static size_t readmoredata(char *buffer,
  931. size_t size,
  932. size_t nitems,
  933. void *userp)
  934. {
  935. struct connectdata *conn = (struct connectdata *)userp;
  936. struct HTTP *http = conn->data->req.protop;
  937. size_t fullsize = size * nitems;
  938. if(!http->postsize)
  939. /* nothing to return */
  940. return 0;
  941. /* make sure that a HTTP request is never sent away chunked! */
  942. conn->data->req.forbidchunk = (http->sending == HTTPSEND_REQUEST)?TRUE:FALSE;
  943. if(http->postsize <= (curl_off_t)fullsize) {
  944. memcpy(buffer, http->postdata, (size_t)http->postsize);
  945. fullsize = (size_t)http->postsize;
  946. if(http->backup.postsize) {
  947. /* move backup data into focus and continue on that */
  948. http->postdata = http->backup.postdata;
  949. http->postsize = http->backup.postsize;
  950. conn->data->state.fread_func = http->backup.fread_func;
  951. conn->data->state.in = http->backup.fread_in;
  952. http->sending++; /* move one step up */
  953. http->backup.postsize = 0;
  954. }
  955. else
  956. http->postsize = 0;
  957. return fullsize;
  958. }
  959. memcpy(buffer, http->postdata, fullsize);
  960. http->postdata += fullsize;
  961. http->postsize -= fullsize;
  962. return fullsize;
  963. }
  964. /* ------------------------------------------------------------------------- */
  965. /* add_buffer functions */
  966. /*
  967. * Curl_add_buffer_init() sets up and returns a fine buffer struct
  968. */
  969. Curl_send_buffer *Curl_add_buffer_init(void)
  970. {
  971. return calloc(1, sizeof(Curl_send_buffer));
  972. }
  973. /*
  974. * Curl_add_buffer_free() frees all associated resources.
  975. */
  976. void Curl_add_buffer_free(Curl_send_buffer *buff)
  977. {
  978. if(buff) /* deal with NULL input */
  979. free(buff->buffer);
  980. free(buff);
  981. }
  982. /*
  983. * Curl_add_buffer_send() sends a header buffer and frees all associated
  984. * memory. Body data may be appended to the header data if desired.
  985. *
  986. * Returns CURLcode
  987. */
  988. CURLcode Curl_add_buffer_send(Curl_send_buffer *in,
  989. struct connectdata *conn,
  990. /* add the number of sent bytes to this
  991. counter */
  992. long *bytes_written,
  993. /* how much of the buffer contains body data */
  994. size_t included_body_bytes,
  995. int socketindex)
  996. {
  997. ssize_t amount;
  998. CURLcode result;
  999. char *ptr;
  1000. size_t size;
  1001. struct Curl_easy *data = conn->data;
  1002. struct HTTP *http = data->req.protop;
  1003. size_t sendsize;
  1004. curl_socket_t sockfd;
  1005. size_t headersize;
  1006. DEBUGASSERT(socketindex <= SECONDARYSOCKET);
  1007. sockfd = conn->sock[socketindex];
  1008. /* The looping below is required since we use non-blocking sockets, but due
  1009. to the circumstances we will just loop and try again and again etc */
  1010. ptr = in->buffer;
  1011. size = in->size_used;
  1012. headersize = size - included_body_bytes; /* the initial part that isn't body
  1013. is header */
  1014. DEBUGASSERT(size > included_body_bytes);
  1015. result = Curl_convert_to_network(data, ptr, headersize);
  1016. /* Curl_convert_to_network calls failf if unsuccessful */
  1017. if(result) {
  1018. /* conversion failed, free memory and return to the caller */
  1019. Curl_add_buffer_free(in);
  1020. return result;
  1021. }
  1022. if((conn->handler->flags & PROTOPT_SSL ||
  1023. conn->http_proxy.proxytype == CURLPROXY_HTTPS)
  1024. && conn->httpversion != 20) {
  1025. /* We never send more than CURL_MAX_WRITE_SIZE bytes in one single chunk
  1026. when we speak HTTPS, as if only a fraction of it is sent now, this data
  1027. needs to fit into the normal read-callback buffer later on and that
  1028. buffer is using this size.
  1029. */
  1030. sendsize = CURLMIN(size, CURL_MAX_WRITE_SIZE);
  1031. /* OpenSSL is very picky and we must send the SAME buffer pointer to the
  1032. library when we attempt to re-send this buffer. Sending the same data
  1033. is not enough, we must use the exact same address. For this reason, we
  1034. must copy the data to the uploadbuffer first, since that is the buffer
  1035. we will be using if this send is retried later.
  1036. */
  1037. result = Curl_get_upload_buffer(data);
  1038. if(result) {
  1039. /* malloc failed, free memory and return to the caller */
  1040. Curl_add_buffer_free(in);
  1041. return result;
  1042. }
  1043. memcpy(data->state.ulbuf, ptr, sendsize);
  1044. ptr = data->state.ulbuf;
  1045. }
  1046. else
  1047. sendsize = size;
  1048. result = Curl_write(conn, sockfd, ptr, sendsize, &amount);
  1049. if(!result) {
  1050. /*
  1051. * Note that we may not send the entire chunk at once, and we have a set
  1052. * number of data bytes at the end of the big buffer (out of which we may
  1053. * only send away a part).
  1054. */
  1055. /* how much of the header that was sent */
  1056. size_t headlen = (size_t)amount>headersize ? headersize : (size_t)amount;
  1057. size_t bodylen = amount - headlen;
  1058. if(data->set.verbose) {
  1059. /* this data _may_ contain binary stuff */
  1060. Curl_debug(data, CURLINFO_HEADER_OUT, ptr, headlen);
  1061. if(bodylen) {
  1062. /* there was body data sent beyond the initial header part, pass that
  1063. on to the debug callback too */
  1064. Curl_debug(data, CURLINFO_DATA_OUT,
  1065. ptr + headlen, bodylen);
  1066. }
  1067. }
  1068. /* 'amount' can never be a very large value here so typecasting it so a
  1069. signed 31 bit value should not cause problems even if ssize_t is
  1070. 64bit */
  1071. *bytes_written += (long)amount;
  1072. if(http) {
  1073. /* if we sent a piece of the body here, up the byte counter for it
  1074. accordingly */
  1075. http->writebytecount += bodylen;
  1076. if((size_t)amount != size) {
  1077. /* The whole request could not be sent in one system call. We must
  1078. queue it up and send it later when we get the chance. We must not
  1079. loop here and wait until it might work again. */
  1080. size -= amount;
  1081. ptr = in->buffer + amount;
  1082. /* backup the currently set pointers */
  1083. http->backup.fread_func = data->state.fread_func;
  1084. http->backup.fread_in = data->state.in;
  1085. http->backup.postdata = http->postdata;
  1086. http->backup.postsize = http->postsize;
  1087. /* set the new pointers for the request-sending */
  1088. data->state.fread_func = (curl_read_callback)readmoredata;
  1089. data->state.in = (void *)conn;
  1090. http->postdata = ptr;
  1091. http->postsize = (curl_off_t)size;
  1092. http->send_buffer = in;
  1093. http->sending = HTTPSEND_REQUEST;
  1094. return CURLE_OK;
  1095. }
  1096. http->sending = HTTPSEND_BODY;
  1097. /* the full buffer was sent, clean up and return */
  1098. }
  1099. else {
  1100. if((size_t)amount != size)
  1101. /* We have no continue-send mechanism now, fail. This can only happen
  1102. when this function is used from the CONNECT sending function. We
  1103. currently (stupidly) assume that the whole request is always sent
  1104. away in the first single chunk.
  1105. This needs FIXing.
  1106. */
  1107. return CURLE_SEND_ERROR;
  1108. Curl_pipeline_leave_write(conn);
  1109. }
  1110. }
  1111. Curl_add_buffer_free(in);
  1112. return result;
  1113. }
  1114. /*
  1115. * add_bufferf() add the formatted input to the buffer.
  1116. */
  1117. CURLcode Curl_add_bufferf(Curl_send_buffer *in, const char *fmt, ...)
  1118. {
  1119. char *s;
  1120. va_list ap;
  1121. va_start(ap, fmt);
  1122. s = vaprintf(fmt, ap); /* this allocs a new string to append */
  1123. va_end(ap);
  1124. if(s) {
  1125. CURLcode result = Curl_add_buffer(in, s, strlen(s));
  1126. free(s);
  1127. return result;
  1128. }
  1129. /* If we failed, we cleanup the whole buffer and return error */
  1130. free(in->buffer);
  1131. free(in);
  1132. return CURLE_OUT_OF_MEMORY;
  1133. }
  1134. /*
  1135. * add_buffer() appends a memory chunk to the existing buffer
  1136. */
  1137. CURLcode Curl_add_buffer(Curl_send_buffer *in, const void *inptr, size_t size)
  1138. {
  1139. char *new_rb;
  1140. if(~size < in->size_used) {
  1141. /* If resulting used size of send buffer would wrap size_t, cleanup
  1142. the whole buffer and return error. Otherwise the required buffer
  1143. size will fit into a single allocatable memory chunk */
  1144. Curl_safefree(in->buffer);
  1145. free(in);
  1146. return CURLE_OUT_OF_MEMORY;
  1147. }
  1148. if(!in->buffer ||
  1149. ((in->size_used + size) > (in->size_max - 1))) {
  1150. /* If current buffer size isn't enough to hold the result, use a
  1151. buffer size that doubles the required size. If this new size
  1152. would wrap size_t, then just use the largest possible one */
  1153. size_t new_size;
  1154. if((size > (size_t)-1 / 2) || (in->size_used > (size_t)-1 / 2) ||
  1155. (~(size * 2) < (in->size_used * 2)))
  1156. new_size = (size_t)-1;
  1157. else
  1158. new_size = (in->size_used + size) * 2;
  1159. if(in->buffer)
  1160. /* we have a buffer, enlarge the existing one */
  1161. new_rb = Curl_saferealloc(in->buffer, new_size);
  1162. else
  1163. /* create a new buffer */
  1164. new_rb = malloc(new_size);
  1165. if(!new_rb) {
  1166. /* If we failed, we cleanup the whole buffer and return error */
  1167. free(in);
  1168. return CURLE_OUT_OF_MEMORY;
  1169. }
  1170. in->buffer = new_rb;
  1171. in->size_max = new_size;
  1172. }
  1173. memcpy(&in->buffer[in->size_used], inptr, size);
  1174. in->size_used += size;
  1175. return CURLE_OK;
  1176. }
  1177. /* end of the add_buffer functions */
  1178. /* ------------------------------------------------------------------------- */
  1179. /*
  1180. * Curl_compareheader()
  1181. *
  1182. * Returns TRUE if 'headerline' contains the 'header' with given 'content'.
  1183. * Pass headers WITH the colon.
  1184. */
  1185. bool
  1186. Curl_compareheader(const char *headerline, /* line to check */
  1187. const char *header, /* header keyword _with_ colon */
  1188. const char *content) /* content string to find */
  1189. {
  1190. /* RFC2616, section 4.2 says: "Each header field consists of a name followed
  1191. * by a colon (":") and the field value. Field names are case-insensitive.
  1192. * The field value MAY be preceded by any amount of LWS, though a single SP
  1193. * is preferred." */
  1194. size_t hlen = strlen(header);
  1195. size_t clen;
  1196. size_t len;
  1197. const char *start;
  1198. const char *end;
  1199. if(!strncasecompare(headerline, header, hlen))
  1200. return FALSE; /* doesn't start with header */
  1201. /* pass the header */
  1202. start = &headerline[hlen];
  1203. /* pass all white spaces */
  1204. while(*start && ISSPACE(*start))
  1205. start++;
  1206. /* find the end of the header line */
  1207. end = strchr(start, '\r'); /* lines end with CRLF */
  1208. if(!end) {
  1209. /* in case there's a non-standard compliant line here */
  1210. end = strchr(start, '\n');
  1211. if(!end)
  1212. /* hm, there's no line ending here, use the zero byte! */
  1213. end = strchr(start, '\0');
  1214. }
  1215. len = end-start; /* length of the content part of the input line */
  1216. clen = strlen(content); /* length of the word to find */
  1217. /* find the content string in the rest of the line */
  1218. for(; len >= clen; len--, start++) {
  1219. if(strncasecompare(start, content, clen))
  1220. return TRUE; /* match! */
  1221. }
  1222. return FALSE; /* no match */
  1223. }
  1224. /*
  1225. * Curl_http_connect() performs HTTP stuff to do at connect-time, called from
  1226. * the generic Curl_connect().
  1227. */
  1228. CURLcode Curl_http_connect(struct connectdata *conn, bool *done)
  1229. {
  1230. CURLcode result;
  1231. /* We default to persistent connections. We set this already in this connect
  1232. function to make the re-use checks properly be able to check this bit. */
  1233. connkeep(conn, "HTTP default");
  1234. /* the CONNECT procedure might not have been completed */
  1235. result = Curl_proxy_connect(conn, FIRSTSOCKET);
  1236. if(result)
  1237. return result;
  1238. if(conn->bits.proxy_connect_closed)
  1239. /* this is not an error, just part of the connection negotiation */
  1240. return CURLE_OK;
  1241. if(CONNECT_FIRSTSOCKET_PROXY_SSL())
  1242. return CURLE_OK; /* wait for HTTPS proxy SSL initialization to complete */
  1243. if(Curl_connect_ongoing(conn))
  1244. /* nothing else to do except wait right now - we're not done here. */
  1245. return CURLE_OK;
  1246. if(conn->data->set.haproxyprotocol) {
  1247. /* add HAProxy PROXY protocol header */
  1248. result = add_haproxy_protocol_header(conn);
  1249. if(result)
  1250. return result;
  1251. }
  1252. if(conn->given->protocol & CURLPROTO_HTTPS) {
  1253. /* perform SSL initialization */
  1254. result = https_connecting(conn, done);
  1255. if(result)
  1256. return result;
  1257. }
  1258. else
  1259. *done = TRUE;
  1260. return CURLE_OK;
  1261. }
  1262. /* this returns the socket to wait for in the DO and DOING state for the multi
  1263. interface and then we're always _sending_ a request and thus we wait for
  1264. the single socket to become writable only */
  1265. static int http_getsock_do(struct connectdata *conn,
  1266. curl_socket_t *socks,
  1267. int numsocks)
  1268. {
  1269. /* write mode */
  1270. (void)numsocks; /* unused, we trust it to be at least 1 */
  1271. socks[0] = conn->sock[FIRSTSOCKET];
  1272. return GETSOCK_WRITESOCK(0);
  1273. }
  1274. static CURLcode add_haproxy_protocol_header(struct connectdata *conn)
  1275. {
  1276. char proxy_header[128];
  1277. Curl_send_buffer *req_buffer;
  1278. CURLcode result;
  1279. char tcp_version[5];
  1280. /* Emit the correct prefix for IPv6 */
  1281. if(conn->bits.ipv6) {
  1282. strcpy(tcp_version, "TCP6");
  1283. }
  1284. else {
  1285. strcpy(tcp_version, "TCP4");
  1286. }
  1287. snprintf(proxy_header,
  1288. sizeof(proxy_header),
  1289. "PROXY %s %s %s %li %li\r\n",
  1290. tcp_version,
  1291. conn->data->info.conn_local_ip,
  1292. conn->data->info.conn_primary_ip,
  1293. conn->data->info.conn_local_port,
  1294. conn->data->info.conn_primary_port);
  1295. req_buffer = Curl_add_buffer_init();
  1296. if(!req_buffer)
  1297. return CURLE_OUT_OF_MEMORY;
  1298. result = Curl_add_bufferf(req_buffer, proxy_header);
  1299. if(result)
  1300. return result;
  1301. result = Curl_add_buffer_send(req_buffer,
  1302. conn,
  1303. &conn->data->info.request_size,
  1304. 0,
  1305. FIRSTSOCKET);
  1306. return result;
  1307. }
  1308. #ifdef USE_SSL
  1309. static CURLcode https_connecting(struct connectdata *conn, bool *done)
  1310. {
  1311. CURLcode result;
  1312. DEBUGASSERT((conn) && (conn->handler->flags & PROTOPT_SSL));
  1313. /* perform SSL initialization for this socket */
  1314. result = Curl_ssl_connect_nonblocking(conn, FIRSTSOCKET, done);
  1315. if(result)
  1316. connclose(conn, "Failed HTTPS connection");
  1317. return result;
  1318. }
  1319. static int https_getsock(struct connectdata *conn,
  1320. curl_socket_t *socks,
  1321. int numsocks)
  1322. {
  1323. if(conn->handler->flags & PROTOPT_SSL)
  1324. return Curl_ssl_getsock(conn, socks, numsocks);
  1325. return GETSOCK_BLANK;
  1326. }
  1327. #endif /* USE_SSL */
  1328. /*
  1329. * Curl_http_done() gets called after a single HTTP request has been
  1330. * performed.
  1331. */
  1332. CURLcode Curl_http_done(struct connectdata *conn,
  1333. CURLcode status, bool premature)
  1334. {
  1335. struct Curl_easy *data = conn->data;
  1336. struct HTTP *http = data->req.protop;
  1337. /* Clear multipass flag. If authentication isn't done yet, then it will get
  1338. * a chance to be set back to true when we output the next auth header */
  1339. data->state.authhost.multipass = FALSE;
  1340. data->state.authproxy.multipass = FALSE;
  1341. Curl_unencode_cleanup(conn);
  1342. #ifdef USE_SPNEGO
  1343. if(data->state.proxyneg.state == GSS_AUTHSENT ||
  1344. data->state.negotiate.state == GSS_AUTHSENT) {
  1345. /* add forbid re-use if http-code != 401/407 as a WA only needed for
  1346. * 401/407 that signal auth failure (empty) otherwise state will be RECV
  1347. * with current code.
  1348. * Do not close CONNECT_ONLY connections. */
  1349. if((data->req.httpcode != 401) && (data->req.httpcode != 407) &&
  1350. !data->set.connect_only)
  1351. streamclose(conn, "Negotiate transfer completed");
  1352. Curl_cleanup_negotiate(data);
  1353. }
  1354. #endif
  1355. /* set the proper values (possibly modified on POST) */
  1356. conn->seek_func = data->set.seek_func; /* restore */
  1357. conn->seek_client = data->set.seek_client; /* restore */
  1358. if(!http)
  1359. return CURLE_OK;
  1360. if(http->send_buffer) {
  1361. Curl_add_buffer_free(http->send_buffer);
  1362. http->send_buffer = NULL; /* clear the pointer */
  1363. }
  1364. Curl_http2_done(conn, premature);
  1365. Curl_mime_cleanpart(&http->form);
  1366. switch(data->set.httpreq) {
  1367. case HTTPREQ_PUT:
  1368. case HTTPREQ_POST_FORM:
  1369. case HTTPREQ_POST_MIME:
  1370. data->req.bytecount = http->readbytecount + http->writebytecount;
  1371. break;
  1372. default:
  1373. break;
  1374. }
  1375. if(status)
  1376. return status;
  1377. if(!premature && /* this check is pointless when DONE is called before the
  1378. entire operation is complete */
  1379. !conn->bits.retry &&
  1380. !data->set.connect_only &&
  1381. (http->readbytecount +
  1382. data->req.headerbytecount -
  1383. data->req.deductheadercount) <= 0) {
  1384. /* If this connection isn't simply closed to be retried, AND nothing was
  1385. read from the HTTP server (that counts), this can't be right so we
  1386. return an error here */
  1387. failf(data, "Empty reply from server");
  1388. return CURLE_GOT_NOTHING;
  1389. }
  1390. return CURLE_OK;
  1391. }
  1392. /*
  1393. * Determine if we should use HTTP 1.1 (OR BETTER) for this request. Reasons
  1394. * to avoid it include:
  1395. *
  1396. * - if the user specifically requested HTTP 1.0
  1397. * - if the server we are connected to only supports 1.0
  1398. * - if any server previously contacted to handle this request only supports
  1399. * 1.0.
  1400. */
  1401. static bool use_http_1_1plus(const struct Curl_easy *data,
  1402. const struct connectdata *conn)
  1403. {
  1404. if((data->state.httpversion == 10) || (conn->httpversion == 10))
  1405. return FALSE;
  1406. if((data->set.httpversion == CURL_HTTP_VERSION_1_0) &&
  1407. (conn->httpversion <= 10))
  1408. return FALSE;
  1409. return ((data->set.httpversion == CURL_HTTP_VERSION_NONE) ||
  1410. (data->set.httpversion >= CURL_HTTP_VERSION_1_1));
  1411. }
  1412. static const char *get_http_string(const struct Curl_easy *data,
  1413. const struct connectdata *conn)
  1414. {
  1415. #ifdef USE_NGHTTP2
  1416. if(conn->proto.httpc.h2)
  1417. return "2";
  1418. #endif
  1419. if(use_http_1_1plus(data, conn))
  1420. return "1.1";
  1421. return "1.0";
  1422. }
  1423. /* check and possibly add an Expect: header */
  1424. static CURLcode expect100(struct Curl_easy *data,
  1425. struct connectdata *conn,
  1426. Curl_send_buffer *req_buffer)
  1427. {
  1428. CURLcode result = CURLE_OK;
  1429. data->state.expect100header = FALSE; /* default to false unless it is set
  1430. to TRUE below */
  1431. if(use_http_1_1plus(data, conn) &&
  1432. (conn->httpversion != 20)) {
  1433. /* if not doing HTTP 1.0 or version 2, or disabled explicitly, we add an
  1434. Expect: 100-continue to the headers which actually speeds up post
  1435. operations (as there is one packet coming back from the web server) */
  1436. const char *ptr = Curl_checkheaders(conn, "Expect");
  1437. if(ptr) {
  1438. data->state.expect100header =
  1439. Curl_compareheader(ptr, "Expect:", "100-continue");
  1440. }
  1441. else {
  1442. result = Curl_add_bufferf(req_buffer,
  1443. "Expect: 100-continue\r\n");
  1444. if(!result)
  1445. data->state.expect100header = TRUE;
  1446. }
  1447. }
  1448. return result;
  1449. }
  1450. enum proxy_use {
  1451. HEADER_SERVER, /* direct to server */
  1452. HEADER_PROXY, /* regular request to proxy */
  1453. HEADER_CONNECT /* sending CONNECT to a proxy */
  1454. };
  1455. CURLcode Curl_add_custom_headers(struct connectdata *conn,
  1456. bool is_connect,
  1457. Curl_send_buffer *req_buffer)
  1458. {
  1459. char *ptr;
  1460. struct curl_slist *h[2];
  1461. struct curl_slist *headers;
  1462. int numlists = 1; /* by default */
  1463. struct Curl_easy *data = conn->data;
  1464. int i;
  1465. enum proxy_use proxy;
  1466. if(is_connect)
  1467. proxy = HEADER_CONNECT;
  1468. else
  1469. proxy = conn->bits.httpproxy && !conn->bits.tunnel_proxy?
  1470. HEADER_PROXY:HEADER_SERVER;
  1471. switch(proxy) {
  1472. case HEADER_SERVER:
  1473. h[0] = data->set.headers;
  1474. break;
  1475. case HEADER_PROXY:
  1476. h[0] = data->set.headers;
  1477. if(data->set.sep_headers) {
  1478. h[1] = data->set.proxyheaders;
  1479. numlists++;
  1480. }
  1481. break;
  1482. case HEADER_CONNECT:
  1483. if(data->set.sep_headers)
  1484. h[0] = data->set.proxyheaders;
  1485. else
  1486. h[0] = data->set.headers;
  1487. break;
  1488. }
  1489. /* loop through one or two lists */
  1490. for(i = 0; i < numlists; i++) {
  1491. headers = h[i];
  1492. while(headers) {
  1493. char *semicolonp = NULL;
  1494. ptr = strchr(headers->data, ':');
  1495. if(!ptr) {
  1496. char *optr;
  1497. /* no colon, semicolon? */
  1498. ptr = strchr(headers->data, ';');
  1499. if(ptr) {
  1500. optr = ptr;
  1501. ptr++; /* pass the semicolon */
  1502. while(*ptr && ISSPACE(*ptr))
  1503. ptr++;
  1504. if(*ptr) {
  1505. /* this may be used for something else in the future */
  1506. optr = NULL;
  1507. }
  1508. else {
  1509. if(*(--ptr) == ';') {
  1510. /* send no-value custom header if terminated by semicolon */
  1511. *ptr = ':';
  1512. semicolonp = ptr;
  1513. }
  1514. }
  1515. ptr = optr;
  1516. }
  1517. }
  1518. if(ptr) {
  1519. /* we require a colon for this to be a true header */
  1520. ptr++; /* pass the colon */
  1521. while(*ptr && ISSPACE(*ptr))
  1522. ptr++;
  1523. if(*ptr || semicolonp) {
  1524. /* only send this if the contents was non-blank or done special */
  1525. CURLcode result = CURLE_OK;
  1526. if(conn->allocptr.host &&
  1527. /* a Host: header was sent already, don't pass on any custom Host:
  1528. header as that will produce *two* in the same request! */
  1529. checkprefix("Host:", headers->data))
  1530. ;
  1531. else if(data->set.httpreq == HTTPREQ_POST_FORM &&
  1532. /* this header (extended by formdata.c) is sent later */
  1533. checkprefix("Content-Type:", headers->data))
  1534. ;
  1535. else if(data->set.httpreq == HTTPREQ_POST_MIME &&
  1536. /* this header is sent later */
  1537. checkprefix("Content-Type:", headers->data))
  1538. ;
  1539. else if(conn->bits.authneg &&
  1540. /* while doing auth neg, don't allow the custom length since
  1541. we will force length zero then */
  1542. checkprefix("Content-Length:", headers->data))
  1543. ;
  1544. else if(conn->allocptr.te &&
  1545. /* when asking for Transfer-Encoding, don't pass on a custom
  1546. Connection: */
  1547. checkprefix("Connection:", headers->data))
  1548. ;
  1549. else if((conn->httpversion == 20) &&
  1550. checkprefix("Transfer-Encoding:", headers->data))
  1551. /* HTTP/2 doesn't support chunked requests */
  1552. ;
  1553. else if(checkprefix("Authorization:", headers->data) &&
  1554. /* be careful of sending this potentially sensitive header to
  1555. other hosts */
  1556. (data->state.this_is_a_follow &&
  1557. data->state.first_host &&
  1558. !data->set.allow_auth_to_other_hosts &&
  1559. !strcasecompare(data->state.first_host, conn->host.name)))
  1560. ;
  1561. else {
  1562. result = Curl_add_bufferf(req_buffer, "%s\r\n", headers->data);
  1563. }
  1564. if(semicolonp)
  1565. *semicolonp = ';'; /* put back the semicolon */
  1566. if(result)
  1567. return result;
  1568. }
  1569. }
  1570. headers = headers->next;
  1571. }
  1572. }
  1573. return CURLE_OK;
  1574. }
  1575. CURLcode Curl_add_timecondition(struct Curl_easy *data,
  1576. Curl_send_buffer *req_buffer)
  1577. {
  1578. const struct tm *tm;
  1579. struct tm keeptime;
  1580. CURLcode result;
  1581. char datestr[80];
  1582. const char *condp;
  1583. if(data->set.timecondition == CURL_TIMECOND_NONE)
  1584. /* no condition was asked for */
  1585. return CURLE_OK;
  1586. result = Curl_gmtime(data->set.timevalue, &keeptime);
  1587. if(result) {
  1588. failf(data, "Invalid TIMEVALUE");
  1589. return result;
  1590. }
  1591. tm = &keeptime;
  1592. switch(data->set.timecondition) {
  1593. default:
  1594. return CURLE_BAD_FUNCTION_ARGUMENT;
  1595. case CURL_TIMECOND_IFMODSINCE:
  1596. condp = "If-Modified-Since";
  1597. break;
  1598. case CURL_TIMECOND_IFUNMODSINCE:
  1599. condp = "If-Unmodified-Since";
  1600. break;
  1601. case CURL_TIMECOND_LASTMOD:
  1602. condp = "Last-Modified";
  1603. break;
  1604. }
  1605. /* The If-Modified-Since header family should have their times set in
  1606. * GMT as RFC2616 defines: "All HTTP date/time stamps MUST be
  1607. * represented in Greenwich Mean Time (GMT), without exception. For the
  1608. * purposes of HTTP, GMT is exactly equal to UTC (Coordinated Universal
  1609. * Time)." (see page 20 of RFC2616).
  1610. */
  1611. /* format: "Tue, 15 Nov 1994 12:45:26 GMT" */
  1612. snprintf(datestr, sizeof(datestr),
  1613. "%s: %s, %02d %s %4d %02d:%02d:%02d GMT\r\n",
  1614. condp,
  1615. Curl_wkday[tm->tm_wday?tm->tm_wday-1:6],
  1616. tm->tm_mday,
  1617. Curl_month[tm->tm_mon],
  1618. tm->tm_year + 1900,
  1619. tm->tm_hour,
  1620. tm->tm_min,
  1621. tm->tm_sec);
  1622. result = Curl_add_buffer(req_buffer, datestr, strlen(datestr));
  1623. return result;
  1624. }
  1625. /*
  1626. * Curl_http() gets called from the generic multi_do() function when a HTTP
  1627. * request is to be performed. This creates and sends a properly constructed
  1628. * HTTP request.
  1629. */
  1630. CURLcode Curl_http(struct connectdata *conn, bool *done)
  1631. {
  1632. struct Curl_easy *data = conn->data;
  1633. CURLcode result = CURLE_OK;
  1634. struct HTTP *http;
  1635. const char *ppath = data->state.path;
  1636. bool paste_ftp_userpwd = FALSE;
  1637. char ftp_typecode[sizeof("/;type=?")] = "";
  1638. const char *host = conn->host.name;
  1639. const char *te = ""; /* transfer-encoding */
  1640. const char *ptr;
  1641. const char *request;
  1642. Curl_HttpReq httpreq = data->set.httpreq;
  1643. #if !defined(CURL_DISABLE_COOKIES)
  1644. char *addcookies = NULL;
  1645. #endif
  1646. curl_off_t included_body = 0;
  1647. const char *httpstring;
  1648. Curl_send_buffer *req_buffer;
  1649. curl_off_t postsize = 0; /* curl_off_t to handle large file sizes */
  1650. /* Always consider the DO phase done after this function call, even if there
  1651. may be parts of the request that is not yet sent, since we can deal with
  1652. the rest of the request in the PERFORM phase. */
  1653. *done = TRUE;
  1654. if(conn->httpversion < 20) { /* unless the connection is re-used and already
  1655. http2 */
  1656. switch(conn->negnpn) {
  1657. case CURL_HTTP_VERSION_2:
  1658. conn->httpversion = 20; /* we know we're on HTTP/2 now */
  1659. result = Curl_http2_switched(conn, NULL, 0);
  1660. if(result)
  1661. return result;
  1662. break;
  1663. case CURL_HTTP_VERSION_1_1:
  1664. /* continue with HTTP/1.1 when explicitly requested */
  1665. break;
  1666. default:
  1667. /* Check if user wants to use HTTP/2 with clear TCP*/
  1668. #ifdef USE_NGHTTP2
  1669. if(conn->data->set.httpversion ==
  1670. CURL_HTTP_VERSION_2_PRIOR_KNOWLEDGE) {
  1671. DEBUGF(infof(data, "HTTP/2 over clean TCP\n"));
  1672. conn->httpversion = 20;
  1673. result = Curl_http2_switched(conn, NULL, 0);
  1674. if(result)
  1675. return result;
  1676. }
  1677. #endif
  1678. break;
  1679. }
  1680. }
  1681. else {
  1682. /* prepare for a http2 request */
  1683. result = Curl_http2_setup(conn);
  1684. if(result)
  1685. return result;
  1686. }
  1687. http = data->req.protop;
  1688. DEBUGASSERT(http);
  1689. if(!data->state.this_is_a_follow) {
  1690. /* Free to avoid leaking memory on multiple requests*/
  1691. free(data->state.first_host);
  1692. data->state.first_host = strdup(conn->host.name);
  1693. if(!data->state.first_host)
  1694. return CURLE_OUT_OF_MEMORY;
  1695. data->state.first_remote_port = conn->remote_port;
  1696. }
  1697. http->writebytecount = http->readbytecount = 0;
  1698. if((conn->handler->protocol&(PROTO_FAMILY_HTTP|CURLPROTO_FTP)) &&
  1699. data->set.upload) {
  1700. httpreq = HTTPREQ_PUT;
  1701. }
  1702. /* Now set the 'request' pointer to the proper request string */
  1703. if(data->set.str[STRING_CUSTOMREQUEST])
  1704. request = data->set.str[STRING_CUSTOMREQUEST];
  1705. else {
  1706. if(data->set.opt_no_body)
  1707. request = "HEAD";
  1708. else {
  1709. DEBUGASSERT((httpreq > HTTPREQ_NONE) && (httpreq < HTTPREQ_LAST));
  1710. switch(httpreq) {
  1711. case HTTPREQ_POST:
  1712. case HTTPREQ_POST_FORM:
  1713. case HTTPREQ_POST_MIME:
  1714. request = "POST";
  1715. break;
  1716. case HTTPREQ_PUT:
  1717. request = "PUT";
  1718. break;
  1719. case HTTPREQ_OPTIONS:
  1720. request = "OPTIONS";
  1721. break;
  1722. default: /* this should never happen */
  1723. case HTTPREQ_GET:
  1724. request = "GET";
  1725. break;
  1726. case HTTPREQ_HEAD:
  1727. request = "HEAD";
  1728. break;
  1729. }
  1730. }
  1731. }
  1732. /* The User-Agent string might have been allocated in url.c already, because
  1733. it might have been used in the proxy connect, but if we have got a header
  1734. with the user-agent string specified, we erase the previously made string
  1735. here. */
  1736. if(Curl_checkheaders(conn, "User-Agent")) {
  1737. free(conn->allocptr.uagent);
  1738. conn->allocptr.uagent = NULL;
  1739. }
  1740. /* setup the authentication headers */
  1741. result = Curl_http_output_auth(conn, request, ppath, FALSE);
  1742. if(result)
  1743. return result;
  1744. if((data->state.authhost.multipass || data->state.authproxy.multipass) &&
  1745. (httpreq != HTTPREQ_GET) &&
  1746. (httpreq != HTTPREQ_HEAD)) {
  1747. /* Auth is required and we are not authenticated yet. Make a PUT or POST
  1748. with content-length zero as a "probe". */
  1749. conn->bits.authneg = TRUE;
  1750. }
  1751. else
  1752. conn->bits.authneg = FALSE;
  1753. Curl_safefree(conn->allocptr.ref);
  1754. if(data->change.referer && !Curl_checkheaders(conn, "Referer")) {
  1755. conn->allocptr.ref = aprintf("Referer: %s\r\n", data->change.referer);
  1756. if(!conn->allocptr.ref)
  1757. return CURLE_OUT_OF_MEMORY;
  1758. }
  1759. else
  1760. conn->allocptr.ref = NULL;
  1761. #if !defined(CURL_DISABLE_COOKIES)
  1762. if(data->set.str[STRING_COOKIE] && !Curl_checkheaders(conn, "Cookie"))
  1763. addcookies = data->set.str[STRING_COOKIE];
  1764. #endif
  1765. if(!Curl_checkheaders(conn, "Accept-Encoding") &&
  1766. data->set.str[STRING_ENCODING]) {
  1767. Curl_safefree(conn->allocptr.accept_encoding);
  1768. conn->allocptr.accept_encoding =
  1769. aprintf("Accept-Encoding: %s\r\n", data->set.str[STRING_ENCODING]);
  1770. if(!conn->allocptr.accept_encoding)
  1771. return CURLE_OUT_OF_MEMORY;
  1772. }
  1773. else {
  1774. Curl_safefree(conn->allocptr.accept_encoding);
  1775. conn->allocptr.accept_encoding = NULL;
  1776. }
  1777. #ifdef HAVE_LIBZ
  1778. /* we only consider transfer-encoding magic if libz support is built-in */
  1779. if(!Curl_checkheaders(conn, "TE") &&
  1780. data->set.http_transfer_encoding) {
  1781. /* When we are to insert a TE: header in the request, we must also insert
  1782. TE in a Connection: header, so we need to merge the custom provided
  1783. Connection: header and prevent the original to get sent. Note that if
  1784. the user has inserted his/hers own TE: header we don't do this magic
  1785. but then assume that the user will handle it all! */
  1786. char *cptr = Curl_checkheaders(conn, "Connection");
  1787. #define TE_HEADER "TE: gzip\r\n"
  1788. Curl_safefree(conn->allocptr.te);
  1789. if(cptr) {
  1790. cptr = Curl_copy_header_value(cptr);
  1791. if(!cptr)
  1792. return CURLE_OUT_OF_MEMORY;
  1793. }
  1794. /* Create the (updated) Connection: header */
  1795. conn->allocptr.te = aprintf("Connection: %s%sTE\r\n" TE_HEADER,
  1796. cptr ? cptr : "", (cptr && *cptr) ? ", ":"");
  1797. free(cptr);
  1798. if(!conn->allocptr.te)
  1799. return CURLE_OUT_OF_MEMORY;
  1800. }
  1801. #endif
  1802. switch(httpreq) {
  1803. case HTTPREQ_POST_MIME:
  1804. http->sendit = &data->set.mimepost;
  1805. break;
  1806. case HTTPREQ_POST_FORM:
  1807. /* Convert the form structure into a mime structure. */
  1808. Curl_mime_cleanpart(&http->form);
  1809. result = Curl_getformdata(data, &http->form, data->set.httppost,
  1810. data->state.fread_func);
  1811. if(result)
  1812. return result;
  1813. http->sendit = &http->form;
  1814. break;
  1815. default:
  1816. http->sendit = NULL;
  1817. }
  1818. if(http->sendit) {
  1819. const char *cthdr = Curl_checkheaders(conn, "Content-Type");
  1820. /* Read and seek body only. */
  1821. http->sendit->flags |= MIME_BODY_ONLY;
  1822. /* Prepare the mime structure headers & set content type. */
  1823. if(cthdr)
  1824. for(cthdr += 13; *cthdr == ' '; cthdr++)
  1825. ;
  1826. else if(http->sendit->kind == MIMEKIND_MULTIPART)
  1827. cthdr = "multipart/form-data";
  1828. curl_mime_headers(http->sendit, data->set.headers, 0);
  1829. result = Curl_mime_prepare_headers(http->sendit, cthdr,
  1830. NULL, MIMESTRATEGY_FORM);
  1831. curl_mime_headers(http->sendit, NULL, 0);
  1832. if(!result)
  1833. result = Curl_mime_rewind(http->sendit);
  1834. if(result)
  1835. return result;
  1836. http->postsize = Curl_mime_size(http->sendit);
  1837. }
  1838. ptr = Curl_checkheaders(conn, "Transfer-Encoding");
  1839. if(ptr) {
  1840. /* Some kind of TE is requested, check if 'chunked' is chosen */
  1841. data->req.upload_chunky =
  1842. Curl_compareheader(ptr, "Transfer-Encoding:", "chunked");
  1843. }
  1844. else {
  1845. if((conn->handler->protocol & PROTO_FAMILY_HTTP) &&
  1846. (((httpreq == HTTPREQ_POST_MIME || httpreq == HTTPREQ_POST_FORM) &&
  1847. http->postsize < 0) ||
  1848. (data->set.upload && data->state.infilesize == -1))) {
  1849. if(conn->bits.authneg)
  1850. /* don't enable chunked during auth neg */
  1851. ;
  1852. else if(use_http_1_1plus(data, conn)) {
  1853. /* HTTP, upload, unknown file size and not HTTP 1.0 */
  1854. data->req.upload_chunky = TRUE;
  1855. }
  1856. else {
  1857. failf(data, "Chunky upload is not supported by HTTP 1.0");
  1858. return CURLE_UPLOAD_FAILED;
  1859. }
  1860. }
  1861. else {
  1862. /* else, no chunky upload */
  1863. data->req.upload_chunky = FALSE;
  1864. }
  1865. if(data->req.upload_chunky)
  1866. te = "Transfer-Encoding: chunked\r\n";
  1867. }
  1868. Curl_safefree(conn->allocptr.host);
  1869. ptr = Curl_checkheaders(conn, "Host");
  1870. if(ptr && (!data->state.this_is_a_follow ||
  1871. strcasecompare(data->state.first_host, conn->host.name))) {
  1872. #if !defined(CURL_DISABLE_COOKIES)
  1873. /* If we have a given custom Host: header, we extract the host name in
  1874. order to possibly use it for cookie reasons later on. We only allow the
  1875. custom Host: header if this is NOT a redirect, as setting Host: in the
  1876. redirected request is being out on thin ice. Except if the host name
  1877. is the same as the first one! */
  1878. char *cookiehost = Curl_copy_header_value(ptr);
  1879. if(!cookiehost)
  1880. return CURLE_OUT_OF_MEMORY;
  1881. if(!*cookiehost)
  1882. /* ignore empty data */
  1883. free(cookiehost);
  1884. else {
  1885. /* If the host begins with '[', we start searching for the port after
  1886. the bracket has been closed */
  1887. if(*cookiehost == '[') {
  1888. char *closingbracket;
  1889. /* since the 'cookiehost' is an allocated memory area that will be
  1890. freed later we cannot simply increment the pointer */
  1891. memmove(cookiehost, cookiehost + 1, strlen(cookiehost) - 1);
  1892. closingbracket = strchr(cookiehost, ']');
  1893. if(closingbracket)
  1894. *closingbracket = 0;
  1895. }
  1896. else {
  1897. int startsearch = 0;
  1898. char *colon = strchr(cookiehost + startsearch, ':');
  1899. if(colon)
  1900. *colon = 0; /* The host must not include an embedded port number */
  1901. }
  1902. Curl_safefree(conn->allocptr.cookiehost);
  1903. conn->allocptr.cookiehost = cookiehost;
  1904. }
  1905. #endif
  1906. if(strcmp("Host:", ptr)) {
  1907. conn->allocptr.host = aprintf("Host:%s\r\n", &ptr[5]);
  1908. if(!conn->allocptr.host)
  1909. return CURLE_OUT_OF_MEMORY;
  1910. }
  1911. else
  1912. /* when clearing the header */
  1913. conn->allocptr.host = NULL;
  1914. }
  1915. else {
  1916. /* When building Host: headers, we must put the host name within
  1917. [brackets] if the host name is a plain IPv6-address. RFC2732-style. */
  1918. if(((conn->given->protocol&CURLPROTO_HTTPS) &&
  1919. (conn->remote_port == PORT_HTTPS)) ||
  1920. ((conn->given->protocol&CURLPROTO_HTTP) &&
  1921. (conn->remote_port == PORT_HTTP)) )
  1922. /* if(HTTPS on port 443) OR (HTTP on port 80) then don't include
  1923. the port number in the host string */
  1924. conn->allocptr.host = aprintf("Host: %s%s%s\r\n",
  1925. conn->bits.ipv6_ip?"[":"",
  1926. host,
  1927. conn->bits.ipv6_ip?"]":"");
  1928. else
  1929. conn->allocptr.host = aprintf("Host: %s%s%s:%d\r\n",
  1930. conn->bits.ipv6_ip?"[":"",
  1931. host,
  1932. conn->bits.ipv6_ip?"]":"",
  1933. conn->remote_port);
  1934. if(!conn->allocptr.host)
  1935. /* without Host: we can't make a nice request */
  1936. return CURLE_OUT_OF_MEMORY;
  1937. }
  1938. #ifndef CURL_DISABLE_PROXY
  1939. if(conn->bits.httpproxy && !conn->bits.tunnel_proxy) {
  1940. /* Using a proxy but does not tunnel through it */
  1941. /* The path sent to the proxy is in fact the entire URL. But if the remote
  1942. host is a IDN-name, we must make sure that the request we produce only
  1943. uses the encoded host name! */
  1944. if(conn->host.dispname != conn->host.name) {
  1945. char *url = data->change.url;
  1946. ptr = strstr(url, conn->host.dispname);
  1947. if(ptr) {
  1948. /* This is where the display name starts in the URL, now replace this
  1949. part with the encoded name. TODO: This method of replacing the host
  1950. name is rather crude as I believe there's a slight risk that the
  1951. user has entered a user name or password that contain the host name
  1952. string. */
  1953. size_t currlen = strlen(conn->host.dispname);
  1954. size_t newlen = strlen(conn->host.name);
  1955. size_t urllen = strlen(url);
  1956. char *newurl;
  1957. newurl = malloc(urllen + newlen - currlen + 1);
  1958. if(newurl) {
  1959. /* copy the part before the host name */
  1960. memcpy(newurl, url, ptr - url);
  1961. /* append the new host name instead of the old */
  1962. memcpy(newurl + (ptr - url), conn->host.name, newlen);
  1963. /* append the piece after the host name */
  1964. memcpy(newurl + newlen + (ptr - url),
  1965. ptr + currlen, /* copy the trailing zero byte too */
  1966. urllen - (ptr-url) - currlen + 1);
  1967. if(data->change.url_alloc) {
  1968. Curl_safefree(data->change.url);
  1969. data->change.url_alloc = FALSE;
  1970. }
  1971. data->change.url = newurl;
  1972. data->change.url_alloc = TRUE;
  1973. }
  1974. else
  1975. return CURLE_OUT_OF_MEMORY;
  1976. }
  1977. }
  1978. ppath = data->change.url;
  1979. if(checkprefix("ftp://", ppath)) {
  1980. if(data->set.proxy_transfer_mode) {
  1981. /* when doing ftp, append ;type=<a|i> if not present */
  1982. char *type = strstr(ppath, ";type=");
  1983. if(type && type[6] && type[7] == 0) {
  1984. switch(Curl_raw_toupper(type[6])) {
  1985. case 'A':
  1986. case 'D':
  1987. case 'I':
  1988. break;
  1989. default:
  1990. type = NULL;
  1991. }
  1992. }
  1993. if(!type) {
  1994. char *p = ftp_typecode;
  1995. /* avoid sending invalid URLs like ftp://example.com;type=i if the
  1996. * user specified ftp://example.com without the slash */
  1997. if(!*data->state.path && ppath[strlen(ppath) - 1] != '/') {
  1998. *p++ = '/';
  1999. }
  2000. snprintf(p, sizeof(ftp_typecode) - 1, ";type=%c",
  2001. data->set.prefer_ascii ? 'a' : 'i');
  2002. }
  2003. }
  2004. if(conn->bits.user_passwd && !conn->bits.userpwd_in_url)
  2005. paste_ftp_userpwd = TRUE;
  2006. }
  2007. }
  2008. #endif /* CURL_DISABLE_PROXY */
  2009. http->p_accept = Curl_checkheaders(conn, "Accept")?NULL:"Accept: */*\r\n";
  2010. if((HTTPREQ_POST == httpreq || HTTPREQ_PUT == httpreq) &&
  2011. data->state.resume_from) {
  2012. /**********************************************************************
  2013. * Resuming upload in HTTP means that we PUT or POST and that we have
  2014. * got a resume_from value set. The resume value has already created
  2015. * a Range: header that will be passed along. We need to "fast forward"
  2016. * the file the given number of bytes and decrease the assume upload
  2017. * file size before we continue this venture in the dark lands of HTTP.
  2018. * Resuming mime/form posting at an offset > 0 has no sense and is ignored.
  2019. *********************************************************************/
  2020. if(data->state.resume_from < 0) {
  2021. /*
  2022. * This is meant to get the size of the present remote-file by itself.
  2023. * We don't support this now. Bail out!
  2024. */
  2025. data->state.resume_from = 0;
  2026. }
  2027. if(data->state.resume_from && !data->state.this_is_a_follow) {
  2028. /* do we still game? */
  2029. /* Now, let's read off the proper amount of bytes from the
  2030. input. */
  2031. int seekerr = CURL_SEEKFUNC_CANTSEEK;
  2032. if(conn->seek_func) {
  2033. Curl_set_in_callback(data, true);
  2034. seekerr = conn->seek_func(conn->seek_client, data->state.resume_from,
  2035. SEEK_SET);
  2036. Curl_set_in_callback(data, false);
  2037. }
  2038. if(seekerr != CURL_SEEKFUNC_OK) {
  2039. curl_off_t passed = 0;
  2040. if(seekerr != CURL_SEEKFUNC_CANTSEEK) {
  2041. failf(data, "Could not seek stream");
  2042. return CURLE_READ_ERROR;
  2043. }
  2044. /* when seekerr == CURL_SEEKFUNC_CANTSEEK (can't seek to offset) */
  2045. do {
  2046. size_t readthisamountnow =
  2047. (data->state.resume_from - passed > data->set.buffer_size) ?
  2048. (size_t)data->set.buffer_size :
  2049. curlx_sotouz(data->state.resume_from - passed);
  2050. size_t actuallyread =
  2051. data->state.fread_func(data->state.buffer, 1, readthisamountnow,
  2052. data->state.in);
  2053. passed += actuallyread;
  2054. if((actuallyread == 0) || (actuallyread > readthisamountnow)) {
  2055. /* this checks for greater-than only to make sure that the
  2056. CURL_READFUNC_ABORT return code still aborts */
  2057. failf(data, "Could only read %" CURL_FORMAT_CURL_OFF_T
  2058. " bytes from the input", passed);
  2059. return CURLE_READ_ERROR;
  2060. }
  2061. } while(passed < data->state.resume_from);
  2062. }
  2063. /* now, decrease the size of the read */
  2064. if(data->state.infilesize>0) {
  2065. data->state.infilesize -= data->state.resume_from;
  2066. if(data->state.infilesize <= 0) {
  2067. failf(data, "File already completely uploaded");
  2068. return CURLE_PARTIAL_FILE;
  2069. }
  2070. }
  2071. /* we've passed, proceed as normal */
  2072. }
  2073. }
  2074. if(data->state.use_range) {
  2075. /*
  2076. * A range is selected. We use different headers whether we're downloading
  2077. * or uploading and we always let customized headers override our internal
  2078. * ones if any such are specified.
  2079. */
  2080. if(((httpreq == HTTPREQ_GET) || (httpreq == HTTPREQ_HEAD)) &&
  2081. !Curl_checkheaders(conn, "Range")) {
  2082. /* if a line like this was already allocated, free the previous one */
  2083. free(conn->allocptr.rangeline);
  2084. conn->allocptr.rangeline = aprintf("Range: bytes=%s\r\n",
  2085. data->state.range);
  2086. }
  2087. else if((httpreq == HTTPREQ_POST || httpreq == HTTPREQ_PUT) &&
  2088. !Curl_checkheaders(conn, "Content-Range")) {
  2089. /* if a line like this was already allocated, free the previous one */
  2090. free(conn->allocptr.rangeline);
  2091. if(data->set.set_resume_from < 0) {
  2092. /* Upload resume was asked for, but we don't know the size of the
  2093. remote part so we tell the server (and act accordingly) that we
  2094. upload the whole file (again) */
  2095. conn->allocptr.rangeline =
  2096. aprintf("Content-Range: bytes 0-%" CURL_FORMAT_CURL_OFF_T
  2097. "/%" CURL_FORMAT_CURL_OFF_T "\r\n",
  2098. data->state.infilesize - 1, data->state.infilesize);
  2099. }
  2100. else if(data->state.resume_from) {
  2101. /* This is because "resume" was selected */
  2102. curl_off_t total_expected_size =
  2103. data->state.resume_from + data->state.infilesize;
  2104. conn->allocptr.rangeline =
  2105. aprintf("Content-Range: bytes %s%" CURL_FORMAT_CURL_OFF_T
  2106. "/%" CURL_FORMAT_CURL_OFF_T "\r\n",
  2107. data->state.range, total_expected_size-1,
  2108. total_expected_size);
  2109. }
  2110. else {
  2111. /* Range was selected and then we just pass the incoming range and
  2112. append total size */
  2113. conn->allocptr.rangeline =
  2114. aprintf("Content-Range: bytes %s/%" CURL_FORMAT_CURL_OFF_T "\r\n",
  2115. data->state.range, data->state.infilesize);
  2116. }
  2117. if(!conn->allocptr.rangeline)
  2118. return CURLE_OUT_OF_MEMORY;
  2119. }
  2120. }
  2121. httpstring = get_http_string(data, conn);
  2122. /* initialize a dynamic send-buffer */
  2123. req_buffer = Curl_add_buffer_init();
  2124. if(!req_buffer)
  2125. return CURLE_OUT_OF_MEMORY;
  2126. /* add the main request stuff */
  2127. /* GET/HEAD/POST/PUT */
  2128. result = Curl_add_bufferf(req_buffer, "%s ", request);
  2129. if(result)
  2130. return result;
  2131. if(data->set.str[STRING_TARGET])
  2132. ppath = data->set.str[STRING_TARGET];
  2133. /* url */
  2134. if(paste_ftp_userpwd)
  2135. result = Curl_add_bufferf(req_buffer, "ftp://%s:%s@%s",
  2136. conn->user, conn->passwd,
  2137. ppath + sizeof("ftp://") - 1);
  2138. else
  2139. result = Curl_add_buffer(req_buffer, ppath, strlen(ppath));
  2140. if(result)
  2141. return result;
  2142. result =
  2143. Curl_add_bufferf(req_buffer,
  2144. "%s" /* ftp typecode (;type=x) */
  2145. " HTTP/%s\r\n" /* HTTP version */
  2146. "%s" /* host */
  2147. "%s" /* proxyuserpwd */
  2148. "%s" /* userpwd */
  2149. "%s" /* range */
  2150. "%s" /* user agent */
  2151. "%s" /* accept */
  2152. "%s" /* TE: */
  2153. "%s" /* accept-encoding */
  2154. "%s" /* referer */
  2155. "%s" /* Proxy-Connection */
  2156. "%s",/* transfer-encoding */
  2157. ftp_typecode,
  2158. httpstring,
  2159. (conn->allocptr.host?conn->allocptr.host:""),
  2160. conn->allocptr.proxyuserpwd?
  2161. conn->allocptr.proxyuserpwd:"",
  2162. conn->allocptr.userpwd?conn->allocptr.userpwd:"",
  2163. (data->state.use_range && conn->allocptr.rangeline)?
  2164. conn->allocptr.rangeline:"",
  2165. (data->set.str[STRING_USERAGENT] &&
  2166. *data->set.str[STRING_USERAGENT] &&
  2167. conn->allocptr.uagent)?
  2168. conn->allocptr.uagent:"",
  2169. http->p_accept?http->p_accept:"",
  2170. conn->allocptr.te?conn->allocptr.te:"",
  2171. (data->set.str[STRING_ENCODING] &&
  2172. *data->set.str[STRING_ENCODING] &&
  2173. conn->allocptr.accept_encoding)?
  2174. conn->allocptr.accept_encoding:"",
  2175. (data->change.referer && conn->allocptr.ref)?
  2176. conn->allocptr.ref:"" /* Referer: <data> */,
  2177. (conn->bits.httpproxy &&
  2178. !conn->bits.tunnel_proxy &&
  2179. !Curl_checkProxyheaders(conn, "Proxy-Connection"))?
  2180. "Proxy-Connection: Keep-Alive\r\n":"",
  2181. te
  2182. );
  2183. /* clear userpwd and proxyuserpwd to avoid re-using old credentials
  2184. * from re-used connections */
  2185. Curl_safefree(conn->allocptr.userpwd);
  2186. Curl_safefree(conn->allocptr.proxyuserpwd);
  2187. if(result)
  2188. return result;
  2189. if(!(conn->handler->flags&PROTOPT_SSL) &&
  2190. conn->httpversion != 20 &&
  2191. (data->set.httpversion == CURL_HTTP_VERSION_2)) {
  2192. /* append HTTP2 upgrade magic stuff to the HTTP request if it isn't done
  2193. over SSL */
  2194. result = Curl_http2_request_upgrade(req_buffer, conn);
  2195. if(result)
  2196. return result;
  2197. }
  2198. #if !defined(CURL_DISABLE_COOKIES)
  2199. if(data->cookies || addcookies) {
  2200. struct Cookie *co = NULL; /* no cookies from start */
  2201. int count = 0;
  2202. if(data->cookies) {
  2203. Curl_share_lock(data, CURL_LOCK_DATA_COOKIE, CURL_LOCK_ACCESS_SINGLE);
  2204. co = Curl_cookie_getlist(data->cookies,
  2205. conn->allocptr.cookiehost?
  2206. conn->allocptr.cookiehost:host,
  2207. data->state.path,
  2208. (conn->handler->protocol&CURLPROTO_HTTPS)?
  2209. TRUE:FALSE);
  2210. Curl_share_unlock(data, CURL_LOCK_DATA_COOKIE);
  2211. }
  2212. if(co) {
  2213. struct Cookie *store = co;
  2214. /* now loop through all cookies that matched */
  2215. while(co) {
  2216. if(co->value) {
  2217. if(0 == count) {
  2218. result = Curl_add_bufferf(req_buffer, "Cookie: ");
  2219. if(result)
  2220. break;
  2221. }
  2222. result = Curl_add_bufferf(req_buffer,
  2223. "%s%s=%s", count?"; ":"",
  2224. co->name, co->value);
  2225. if(result)
  2226. break;
  2227. count++;
  2228. }
  2229. co = co->next; /* next cookie please */
  2230. }
  2231. Curl_cookie_freelist(store);
  2232. }
  2233. if(addcookies && !result) {
  2234. if(!count)
  2235. result = Curl_add_bufferf(req_buffer, "Cookie: ");
  2236. if(!result) {
  2237. result = Curl_add_bufferf(req_buffer, "%s%s", count?"; ":"",
  2238. addcookies);
  2239. count++;
  2240. }
  2241. }
  2242. if(count && !result)
  2243. result = Curl_add_buffer(req_buffer, "\r\n", 2);
  2244. if(result)
  2245. return result;
  2246. }
  2247. #endif
  2248. result = Curl_add_timecondition(data, req_buffer);
  2249. if(result)
  2250. return result;
  2251. result = Curl_add_custom_headers(conn, FALSE, req_buffer);
  2252. if(result)
  2253. return result;
  2254. http->postdata = NULL; /* nothing to post at this point */
  2255. Curl_pgrsSetUploadSize(data, -1); /* upload size is unknown atm */
  2256. /* If 'authdone' is FALSE, we must not set the write socket index to the
  2257. Curl_transfer() call below, as we're not ready to actually upload any
  2258. data yet. */
  2259. switch(httpreq) {
  2260. case HTTPREQ_PUT: /* Let's PUT the data to the server! */
  2261. if(conn->bits.authneg)
  2262. postsize = 0;
  2263. else
  2264. postsize = data->state.infilesize;
  2265. if((postsize != -1) && !data->req.upload_chunky &&
  2266. (conn->bits.authneg || !Curl_checkheaders(conn, "Content-Length"))) {
  2267. /* only add Content-Length if not uploading chunked */
  2268. result = Curl_add_bufferf(req_buffer,
  2269. "Content-Length: %" CURL_FORMAT_CURL_OFF_T
  2270. "\r\n", postsize);
  2271. if(result)
  2272. return result;
  2273. }
  2274. if(postsize != 0) {
  2275. result = expect100(data, conn, req_buffer);
  2276. if(result)
  2277. return result;
  2278. }
  2279. result = Curl_add_buffer(req_buffer, "\r\n", 2); /* end of headers */
  2280. if(result)
  2281. return result;
  2282. /* set the upload size to the progress meter */
  2283. Curl_pgrsSetUploadSize(data, postsize);
  2284. /* this sends the buffer and frees all the buffer resources */
  2285. result = Curl_add_buffer_send(req_buffer, conn,
  2286. &data->info.request_size, 0, FIRSTSOCKET);
  2287. if(result)
  2288. failf(data, "Failed sending PUT request");
  2289. else
  2290. /* prepare for transfer */
  2291. Curl_setup_transfer(conn, FIRSTSOCKET, -1, TRUE,
  2292. &http->readbytecount, postsize?FIRSTSOCKET:-1,
  2293. postsize?&http->writebytecount:NULL);
  2294. if(result)
  2295. return result;
  2296. break;
  2297. case HTTPREQ_POST_FORM:
  2298. case HTTPREQ_POST_MIME:
  2299. /* This is form posting using mime data. */
  2300. if(conn->bits.authneg) {
  2301. /* nothing to post! */
  2302. result = Curl_add_bufferf(req_buffer, "Content-Length: 0\r\n\r\n");
  2303. if(result)
  2304. return result;
  2305. result = Curl_add_buffer_send(req_buffer, conn,
  2306. &data->info.request_size, 0, FIRSTSOCKET);
  2307. if(result)
  2308. failf(data, "Failed sending POST request");
  2309. else
  2310. /* setup variables for the upcoming transfer */
  2311. Curl_setup_transfer(conn, FIRSTSOCKET, -1, TRUE, &http->readbytecount,
  2312. -1, NULL);
  2313. break;
  2314. }
  2315. postsize = http->postsize;
  2316. /* We only set Content-Length and allow a custom Content-Length if
  2317. we don't upload data chunked, as RFC2616 forbids us to set both
  2318. kinds of headers (Transfer-Encoding: chunked and Content-Length) */
  2319. if(postsize != -1 && !data->req.upload_chunky &&
  2320. (conn->bits.authneg || !Curl_checkheaders(conn, "Content-Length"))) {
  2321. /* we allow replacing this header if not during auth negotiation,
  2322. although it isn't very wise to actually set your own */
  2323. result = Curl_add_bufferf(req_buffer,
  2324. "Content-Length: %" CURL_FORMAT_CURL_OFF_T
  2325. "\r\n", postsize);
  2326. if(result)
  2327. return result;
  2328. }
  2329. /* Output mime-generated headers. */
  2330. {
  2331. struct curl_slist *hdr;
  2332. for(hdr = http->sendit->curlheaders; hdr; hdr = hdr->next) {
  2333. result = Curl_add_bufferf(req_buffer, "%s\r\n", hdr->data);
  2334. if(result)
  2335. return result;
  2336. }
  2337. }
  2338. /* For really small posts we don't use Expect: headers at all, and for
  2339. the somewhat bigger ones we allow the app to disable it. Just make
  2340. sure that the expect100header is always set to the preferred value
  2341. here. */
  2342. ptr = Curl_checkheaders(conn, "Expect");
  2343. if(ptr) {
  2344. data->state.expect100header =
  2345. Curl_compareheader(ptr, "Expect:", "100-continue");
  2346. }
  2347. else if(postsize > EXPECT_100_THRESHOLD || postsize < 0) {
  2348. result = expect100(data, conn, req_buffer);
  2349. if(result)
  2350. return result;
  2351. }
  2352. else
  2353. data->state.expect100header = FALSE;
  2354. /* make the request end in a true CRLF */
  2355. result = Curl_add_buffer(req_buffer, "\r\n", 2);
  2356. if(result)
  2357. return result;
  2358. /* set the upload size to the progress meter */
  2359. Curl_pgrsSetUploadSize(data, postsize);
  2360. /* Read from mime structure. */
  2361. data->state.fread_func = (curl_read_callback) Curl_mime_read;
  2362. data->state.in = (void *) http->sendit;
  2363. http->sending = HTTPSEND_BODY;
  2364. /* this sends the buffer and frees all the buffer resources */
  2365. result = Curl_add_buffer_send(req_buffer, conn,
  2366. &data->info.request_size, 0, FIRSTSOCKET);
  2367. if(result)
  2368. failf(data, "Failed sending POST request");
  2369. else
  2370. /* prepare for transfer */
  2371. Curl_setup_transfer(conn, FIRSTSOCKET, -1, TRUE,
  2372. &http->readbytecount, postsize?FIRSTSOCKET:-1,
  2373. postsize?&http->writebytecount:NULL);
  2374. if(result)
  2375. return result;
  2376. break;
  2377. case HTTPREQ_POST:
  2378. /* this is the simple POST, using x-www-form-urlencoded style */
  2379. if(conn->bits.authneg)
  2380. postsize = 0;
  2381. else
  2382. /* the size of the post body */
  2383. postsize = data->state.infilesize;
  2384. /* We only set Content-Length and allow a custom Content-Length if
  2385. we don't upload data chunked, as RFC2616 forbids us to set both
  2386. kinds of headers (Transfer-Encoding: chunked and Content-Length) */
  2387. if((postsize != -1) && !data->req.upload_chunky &&
  2388. (conn->bits.authneg || !Curl_checkheaders(conn, "Content-Length"))) {
  2389. /* we allow replacing this header if not during auth negotiation,
  2390. although it isn't very wise to actually set your own */
  2391. result = Curl_add_bufferf(req_buffer,
  2392. "Content-Length: %" CURL_FORMAT_CURL_OFF_T
  2393. "\r\n", postsize);
  2394. if(result)
  2395. return result;
  2396. }
  2397. if(!Curl_checkheaders(conn, "Content-Type")) {
  2398. result = Curl_add_bufferf(req_buffer,
  2399. "Content-Type: application/"
  2400. "x-www-form-urlencoded\r\n");
  2401. if(result)
  2402. return result;
  2403. }
  2404. /* For really small posts we don't use Expect: headers at all, and for
  2405. the somewhat bigger ones we allow the app to disable it. Just make
  2406. sure that the expect100header is always set to the preferred value
  2407. here. */
  2408. ptr = Curl_checkheaders(conn, "Expect");
  2409. if(ptr) {
  2410. data->state.expect100header =
  2411. Curl_compareheader(ptr, "Expect:", "100-continue");
  2412. }
  2413. else if(postsize > EXPECT_100_THRESHOLD || postsize < 0) {
  2414. result = expect100(data, conn, req_buffer);
  2415. if(result)
  2416. return result;
  2417. }
  2418. else
  2419. data->state.expect100header = FALSE;
  2420. if(data->set.postfields) {
  2421. /* In HTTP2, we send request body in DATA frame regardless of
  2422. its size. */
  2423. if(conn->httpversion != 20 &&
  2424. !data->state.expect100header &&
  2425. (postsize < MAX_INITIAL_POST_SIZE)) {
  2426. /* if we don't use expect: 100 AND
  2427. postsize is less than MAX_INITIAL_POST_SIZE
  2428. then append the post data to the HTTP request header. This limit
  2429. is no magic limit but only set to prevent really huge POSTs to
  2430. get the data duplicated with malloc() and family. */
  2431. result = Curl_add_buffer(req_buffer, "\r\n", 2); /* end of headers! */
  2432. if(result)
  2433. return result;
  2434. if(!data->req.upload_chunky) {
  2435. /* We're not sending it 'chunked', append it to the request
  2436. already now to reduce the number if send() calls */
  2437. result = Curl_add_buffer(req_buffer, data->set.postfields,
  2438. (size_t)postsize);
  2439. included_body = postsize;
  2440. }
  2441. else {
  2442. if(postsize) {
  2443. /* Append the POST data chunky-style */
  2444. result = Curl_add_bufferf(req_buffer, "%x\r\n", (int)postsize);
  2445. if(!result) {
  2446. result = Curl_add_buffer(req_buffer, data->set.postfields,
  2447. (size_t)postsize);
  2448. if(!result)
  2449. result = Curl_add_buffer(req_buffer, "\r\n", 2);
  2450. included_body = postsize + 2;
  2451. }
  2452. }
  2453. if(!result)
  2454. result = Curl_add_buffer(req_buffer, "\x30\x0d\x0a\x0d\x0a", 5);
  2455. /* 0 CR LF CR LF */
  2456. included_body += 5;
  2457. }
  2458. if(result)
  2459. return result;
  2460. /* Make sure the progress information is accurate */
  2461. Curl_pgrsSetUploadSize(data, postsize);
  2462. }
  2463. else {
  2464. /* A huge POST coming up, do data separate from the request */
  2465. http->postsize = postsize;
  2466. http->postdata = data->set.postfields;
  2467. http->sending = HTTPSEND_BODY;
  2468. data->state.fread_func = (curl_read_callback)readmoredata;
  2469. data->state.in = (void *)conn;
  2470. /* set the upload size to the progress meter */
  2471. Curl_pgrsSetUploadSize(data, http->postsize);
  2472. result = Curl_add_buffer(req_buffer, "\r\n", 2); /* end of headers! */
  2473. if(result)
  2474. return result;
  2475. }
  2476. }
  2477. else {
  2478. result = Curl_add_buffer(req_buffer, "\r\n", 2); /* end of headers! */
  2479. if(result)
  2480. return result;
  2481. if(data->req.upload_chunky && conn->bits.authneg) {
  2482. /* Chunky upload is selected and we're negotiating auth still, send
  2483. end-of-data only */
  2484. result = Curl_add_buffer(req_buffer,
  2485. "\x30\x0d\x0a\x0d\x0a", 5);
  2486. /* 0 CR LF CR LF */
  2487. if(result)
  2488. return result;
  2489. }
  2490. else if(data->state.infilesize) {
  2491. /* set the upload size to the progress meter */
  2492. Curl_pgrsSetUploadSize(data, postsize?postsize:-1);
  2493. /* set the pointer to mark that we will send the post body using the
  2494. read callback, but only if we're not in authenticate
  2495. negotiation */
  2496. if(!conn->bits.authneg) {
  2497. http->postdata = (char *)&http->postdata;
  2498. http->postsize = postsize;
  2499. }
  2500. }
  2501. }
  2502. /* issue the request */
  2503. result = Curl_add_buffer_send(req_buffer, conn, &data->info.request_size,
  2504. (size_t)included_body, FIRSTSOCKET);
  2505. if(result)
  2506. failf(data, "Failed sending HTTP POST request");
  2507. else
  2508. Curl_setup_transfer(conn, FIRSTSOCKET, -1, TRUE,
  2509. &http->readbytecount, http->postdata?FIRSTSOCKET:-1,
  2510. http->postdata?&http->writebytecount:NULL);
  2511. break;
  2512. default:
  2513. result = Curl_add_buffer(req_buffer, "\r\n", 2);
  2514. if(result)
  2515. return result;
  2516. /* issue the request */
  2517. result = Curl_add_buffer_send(req_buffer, conn,
  2518. &data->info.request_size, 0, FIRSTSOCKET);
  2519. if(result)
  2520. failf(data, "Failed sending HTTP request");
  2521. else
  2522. /* HTTP GET/HEAD download: */
  2523. Curl_setup_transfer(conn, FIRSTSOCKET, -1, TRUE, &http->readbytecount,
  2524. http->postdata?FIRSTSOCKET:-1,
  2525. http->postdata?&http->writebytecount:NULL);
  2526. }
  2527. if(result)
  2528. return result;
  2529. if(http->writebytecount) {
  2530. /* if a request-body has been sent off, we make sure this progress is noted
  2531. properly */
  2532. Curl_pgrsSetUploadCounter(data, http->writebytecount);
  2533. if(Curl_pgrsUpdate(conn))
  2534. result = CURLE_ABORTED_BY_CALLBACK;
  2535. if(http->writebytecount >= postsize) {
  2536. /* already sent the entire request body, mark the "upload" as
  2537. complete */
  2538. infof(data, "upload completely sent off: %" CURL_FORMAT_CURL_OFF_T
  2539. " out of %" CURL_FORMAT_CURL_OFF_T " bytes\n",
  2540. http->writebytecount, postsize);
  2541. data->req.upload_done = TRUE;
  2542. data->req.keepon &= ~KEEP_SEND; /* we're done writing */
  2543. data->req.exp100 = EXP100_SEND_DATA; /* already sent */
  2544. Curl_expire_done(data, EXPIRE_100_TIMEOUT);
  2545. }
  2546. else
  2547. data->req.writebytecount = http->writebytecount;
  2548. }
  2549. if((conn->httpversion == 20) && data->req.upload_chunky)
  2550. /* upload_chunky was set above to set up the request in a chunky fashion,
  2551. but is disabled here again to avoid that the chunked encoded version is
  2552. actually used when sending the request body over h2 */
  2553. data->req.upload_chunky = FALSE;
  2554. return result;
  2555. }
  2556. typedef enum {
  2557. STATUS_UNKNOWN, /* not enough data to tell yet */
  2558. STATUS_DONE, /* a status line was read */
  2559. STATUS_BAD /* not a status line */
  2560. } statusline;
  2561. /* Check a string for a prefix. Check no more than 'len' bytes */
  2562. static bool checkprefixmax(const char *prefix, const char *buffer, size_t len)
  2563. {
  2564. size_t ch = CURLMIN(strlen(prefix), len);
  2565. return curl_strnequal(prefix, buffer, ch);
  2566. }
  2567. /*
  2568. * checkhttpprefix()
  2569. *
  2570. * Returns TRUE if member of the list matches prefix of string
  2571. */
  2572. static statusline
  2573. checkhttpprefix(struct Curl_easy *data,
  2574. const char *s, size_t len)
  2575. {
  2576. struct curl_slist *head = data->set.http200aliases;
  2577. statusline rc = STATUS_BAD;
  2578. statusline onmatch = len >= 5? STATUS_DONE : STATUS_UNKNOWN;
  2579. #ifdef CURL_DOES_CONVERSIONS
  2580. /* convert from the network encoding using a scratch area */
  2581. char *scratch = strdup(s);
  2582. if(NULL == scratch) {
  2583. failf(data, "Failed to allocate memory for conversion!");
  2584. return FALSE; /* can't return CURLE_OUT_OF_MEMORY so return FALSE */
  2585. }
  2586. if(CURLE_OK != Curl_convert_from_network(data, scratch, strlen(s) + 1)) {
  2587. /* Curl_convert_from_network calls failf if unsuccessful */
  2588. free(scratch);
  2589. return FALSE; /* can't return CURLE_foobar so return FALSE */
  2590. }
  2591. s = scratch;
  2592. #endif /* CURL_DOES_CONVERSIONS */
  2593. while(head) {
  2594. if(checkprefixmax(head->data, s, len)) {
  2595. rc = onmatch;
  2596. break;
  2597. }
  2598. head = head->next;
  2599. }
  2600. if((rc != STATUS_DONE) && (checkprefixmax("HTTP/", s, len)))
  2601. rc = onmatch;
  2602. #ifdef CURL_DOES_CONVERSIONS
  2603. free(scratch);
  2604. #endif /* CURL_DOES_CONVERSIONS */
  2605. return rc;
  2606. }
  2607. #ifndef CURL_DISABLE_RTSP
  2608. static statusline
  2609. checkrtspprefix(struct Curl_easy *data,
  2610. const char *s, size_t len)
  2611. {
  2612. statusline result = STATUS_BAD;
  2613. statusline onmatch = len >= 5? STATUS_DONE : STATUS_UNKNOWN;
  2614. #ifdef CURL_DOES_CONVERSIONS
  2615. /* convert from the network encoding using a scratch area */
  2616. char *scratch = strdup(s);
  2617. if(NULL == scratch) {
  2618. failf(data, "Failed to allocate memory for conversion!");
  2619. return FALSE; /* can't return CURLE_OUT_OF_MEMORY so return FALSE */
  2620. }
  2621. if(CURLE_OK != Curl_convert_from_network(data, scratch, strlen(s) + 1)) {
  2622. /* Curl_convert_from_network calls failf if unsuccessful */
  2623. result = FALSE; /* can't return CURLE_foobar so return FALSE */
  2624. }
  2625. else if(checkprefixmax("RTSP/", scratch, len))
  2626. result = onmatch;
  2627. free(scratch);
  2628. #else
  2629. (void)data; /* unused */
  2630. if(checkprefixmax("RTSP/", s, len))
  2631. result = onmatch;
  2632. #endif /* CURL_DOES_CONVERSIONS */
  2633. return result;
  2634. }
  2635. #endif /* CURL_DISABLE_RTSP */
  2636. static statusline
  2637. checkprotoprefix(struct Curl_easy *data, struct connectdata *conn,
  2638. const char *s, size_t len)
  2639. {
  2640. #ifndef CURL_DISABLE_RTSP
  2641. if(conn->handler->protocol & CURLPROTO_RTSP)
  2642. return checkrtspprefix(data, s, len);
  2643. #else
  2644. (void)conn;
  2645. #endif /* CURL_DISABLE_RTSP */
  2646. return checkhttpprefix(data, s, len);
  2647. }
  2648. /*
  2649. * header_append() copies a chunk of data to the end of the already received
  2650. * header. We make sure that the full string fit in the allocated header
  2651. * buffer, or else we enlarge it.
  2652. */
  2653. static CURLcode header_append(struct Curl_easy *data,
  2654. struct SingleRequest *k,
  2655. size_t length)
  2656. {
  2657. size_t newsize = k->hbuflen + length;
  2658. if(newsize > CURL_MAX_HTTP_HEADER) {
  2659. /* The reason to have a max limit for this is to avoid the risk of a bad
  2660. server feeding libcurl with a never-ending header that will cause
  2661. reallocs infinitely */
  2662. failf(data, "Rejected %zu bytes header (max is %d)!", newsize,
  2663. CURL_MAX_HTTP_HEADER);
  2664. return CURLE_OUT_OF_MEMORY;
  2665. }
  2666. if(newsize >= data->state.headersize) {
  2667. /* We enlarge the header buffer as it is too small */
  2668. char *newbuff;
  2669. size_t hbufp_index;
  2670. newsize = CURLMAX((k->hbuflen + length) * 3 / 2, data->state.headersize*2);
  2671. hbufp_index = k->hbufp - data->state.headerbuff;
  2672. newbuff = realloc(data->state.headerbuff, newsize);
  2673. if(!newbuff) {
  2674. failf(data, "Failed to alloc memory for big header!");
  2675. return CURLE_OUT_OF_MEMORY;
  2676. }
  2677. data->state.headersize = newsize;
  2678. data->state.headerbuff = newbuff;
  2679. k->hbufp = data->state.headerbuff + hbufp_index;
  2680. }
  2681. memcpy(k->hbufp, k->str_start, length);
  2682. k->hbufp += length;
  2683. k->hbuflen += length;
  2684. *k->hbufp = 0;
  2685. return CURLE_OK;
  2686. }
  2687. static void print_http_error(struct Curl_easy *data)
  2688. {
  2689. struct SingleRequest *k = &data->req;
  2690. char *beg = k->p;
  2691. /* make sure that data->req.p points to the HTTP status line */
  2692. if(!strncmp(beg, "HTTP", 4)) {
  2693. /* skip to HTTP status code */
  2694. beg = strchr(beg, ' ');
  2695. if(beg && *++beg) {
  2696. /* find trailing CR */
  2697. char end_char = '\r';
  2698. char *end = strchr(beg, end_char);
  2699. if(!end) {
  2700. /* try to find LF (workaround for non-compliant HTTP servers) */
  2701. end_char = '\n';
  2702. end = strchr(beg, end_char);
  2703. }
  2704. if(end) {
  2705. /* temporarily replace CR or LF by NUL and print the error message */
  2706. *end = '\0';
  2707. failf(data, "The requested URL returned error: %s", beg);
  2708. /* restore the previously replaced CR or LF */
  2709. *end = end_char;
  2710. return;
  2711. }
  2712. }
  2713. }
  2714. /* fall-back to printing the HTTP status code only */
  2715. failf(data, "The requested URL returned error: %d", k->httpcode);
  2716. }
  2717. /*
  2718. * Read any HTTP header lines from the server and pass them to the client app.
  2719. */
  2720. CURLcode Curl_http_readwrite_headers(struct Curl_easy *data,
  2721. struct connectdata *conn,
  2722. ssize_t *nread,
  2723. bool *stop_reading)
  2724. {
  2725. CURLcode result;
  2726. struct SingleRequest *k = &data->req;
  2727. ssize_t onread = *nread;
  2728. char *ostr = k->str;
  2729. /* header line within buffer loop */
  2730. do {
  2731. size_t rest_length;
  2732. size_t full_length;
  2733. int writetype;
  2734. /* str_start is start of line within buf */
  2735. k->str_start = k->str;
  2736. /* data is in network encoding so use 0x0a instead of '\n' */
  2737. k->end_ptr = memchr(k->str_start, 0x0a, *nread);
  2738. if(!k->end_ptr) {
  2739. /* Not a complete header line within buffer, append the data to
  2740. the end of the headerbuff. */
  2741. result = header_append(data, k, *nread);
  2742. if(result)
  2743. return result;
  2744. if(!k->headerline) {
  2745. /* check if this looks like a protocol header */
  2746. statusline st = checkprotoprefix(data, conn, data->state.headerbuff,
  2747. k->hbuflen);
  2748. if(st == STATUS_BAD) {
  2749. /* this is not the beginning of a protocol first header line */
  2750. k->header = FALSE;
  2751. k->badheader = HEADER_ALLBAD;
  2752. streamclose(conn, "bad HTTP: No end-of-message indicator");
  2753. break;
  2754. }
  2755. }
  2756. break; /* read more and try again */
  2757. }
  2758. /* decrease the size of the remaining (supposed) header line */
  2759. rest_length = (k->end_ptr - k->str) + 1;
  2760. *nread -= (ssize_t)rest_length;
  2761. k->str = k->end_ptr + 1; /* move past new line */
  2762. full_length = k->str - k->str_start;
  2763. result = header_append(data, k, full_length);
  2764. if(result)
  2765. return result;
  2766. k->end_ptr = k->hbufp;
  2767. k->p = data->state.headerbuff;
  2768. /****
  2769. * We now have a FULL header line that p points to
  2770. *****/
  2771. if(!k->headerline) {
  2772. /* the first read header */
  2773. statusline st = checkprotoprefix(data, conn, data->state.headerbuff,
  2774. k->hbuflen);
  2775. if(st == STATUS_BAD) {
  2776. streamclose(conn, "bad HTTP: No end-of-message indicator");
  2777. /* this is not the beginning of a protocol first header line */
  2778. k->header = FALSE;
  2779. if(*nread)
  2780. /* since there's more, this is a partial bad header */
  2781. k->badheader = HEADER_PARTHEADER;
  2782. else {
  2783. /* this was all we read so it's all a bad header */
  2784. k->badheader = HEADER_ALLBAD;
  2785. *nread = onread;
  2786. k->str = ostr;
  2787. return CURLE_OK;
  2788. }
  2789. break;
  2790. }
  2791. }
  2792. /* headers are in network encoding so
  2793. use 0x0a and 0x0d instead of '\n' and '\r' */
  2794. if((0x0a == *k->p) || (0x0d == *k->p)) {
  2795. size_t headerlen;
  2796. /* Zero-length header line means end of headers! */
  2797. #ifdef CURL_DOES_CONVERSIONS
  2798. if(0x0d == *k->p) {
  2799. *k->p = '\r'; /* replace with CR in host encoding */
  2800. k->p++; /* pass the CR byte */
  2801. }
  2802. if(0x0a == *k->p) {
  2803. *k->p = '\n'; /* replace with LF in host encoding */
  2804. k->p++; /* pass the LF byte */
  2805. }
  2806. #else
  2807. if('\r' == *k->p)
  2808. k->p++; /* pass the \r byte */
  2809. if('\n' == *k->p)
  2810. k->p++; /* pass the \n byte */
  2811. #endif /* CURL_DOES_CONVERSIONS */
  2812. if(100 <= k->httpcode && 199 >= k->httpcode) {
  2813. /* "A user agent MAY ignore unexpected 1xx status responses." */
  2814. switch(k->httpcode) {
  2815. case 100:
  2816. /*
  2817. * We have made a HTTP PUT or POST and this is 1.1-lingo
  2818. * that tells us that the server is OK with this and ready
  2819. * to receive the data.
  2820. * However, we'll get more headers now so we must get
  2821. * back into the header-parsing state!
  2822. */
  2823. k->header = TRUE;
  2824. k->headerline = 0; /* restart the header line counter */
  2825. /* if we did wait for this do enable write now! */
  2826. if(k->exp100 > EXP100_SEND_DATA) {
  2827. k->exp100 = EXP100_SEND_DATA;
  2828. k->keepon |= KEEP_SEND;
  2829. Curl_expire_done(data, EXPIRE_100_TIMEOUT);
  2830. }
  2831. break;
  2832. case 101:
  2833. /* Switching Protocols */
  2834. if(k->upgr101 == UPGR101_REQUESTED) {
  2835. /* Switching to HTTP/2 */
  2836. infof(data, "Received 101\n");
  2837. k->upgr101 = UPGR101_RECEIVED;
  2838. /* we'll get more headers (HTTP/2 response) */
  2839. k->header = TRUE;
  2840. k->headerline = 0; /* restart the header line counter */
  2841. /* switch to http2 now. The bytes after response headers
  2842. are also processed here, otherwise they are lost. */
  2843. result = Curl_http2_switched(conn, k->str, *nread);
  2844. if(result)
  2845. return result;
  2846. *nread = 0;
  2847. }
  2848. else {
  2849. /* Switching to another protocol (e.g. WebSocket) */
  2850. k->header = FALSE; /* no more header to parse! */
  2851. }
  2852. break;
  2853. default:
  2854. /* the status code 1xx indicates a provisional response, so
  2855. we'll get another set of headers */
  2856. k->header = TRUE;
  2857. k->headerline = 0; /* restart the header line counter */
  2858. break;
  2859. }
  2860. }
  2861. else {
  2862. k->header = FALSE; /* no more header to parse! */
  2863. if((k->size == -1) && !k->chunk && !conn->bits.close &&
  2864. (conn->httpversion == 11) &&
  2865. !(conn->handler->protocol & CURLPROTO_RTSP) &&
  2866. data->set.httpreq != HTTPREQ_HEAD) {
  2867. /* On HTTP 1.1, when connection is not to get closed, but no
  2868. Content-Length nor Transfer-Encoding chunked have been
  2869. received, according to RFC2616 section 4.4 point 5, we
  2870. assume that the server will close the connection to
  2871. signal the end of the document. */
  2872. infof(data, "no chunk, no close, no size. Assume close to "
  2873. "signal end\n");
  2874. streamclose(conn, "HTTP: No end-of-message indicator");
  2875. }
  2876. }
  2877. /* At this point we have some idea about the fate of the connection.
  2878. If we are closing the connection it may result auth failure. */
  2879. #if defined(USE_NTLM)
  2880. if(conn->bits.close &&
  2881. (((data->req.httpcode == 401) &&
  2882. (conn->ntlm.state == NTLMSTATE_TYPE2)) ||
  2883. ((data->req.httpcode == 407) &&
  2884. (conn->proxyntlm.state == NTLMSTATE_TYPE2)))) {
  2885. infof(data, "Connection closure while negotiating auth (HTTP 1.0?)\n");
  2886. data->state.authproblem = TRUE;
  2887. }
  2888. #endif
  2889. /*
  2890. * When all the headers have been parsed, see if we should give
  2891. * up and return an error.
  2892. */
  2893. if(http_should_fail(conn)) {
  2894. failf(data, "The requested URL returned error: %d",
  2895. k->httpcode);
  2896. return CURLE_HTTP_RETURNED_ERROR;
  2897. }
  2898. /* now, only output this if the header AND body are requested:
  2899. */
  2900. writetype = CLIENTWRITE_HEADER;
  2901. if(data->set.include_header)
  2902. writetype |= CLIENTWRITE_BODY;
  2903. headerlen = k->p - data->state.headerbuff;
  2904. result = Curl_client_write(conn, writetype,
  2905. data->state.headerbuff,
  2906. headerlen);
  2907. if(result)
  2908. return result;
  2909. data->info.header_size += (long)headerlen;
  2910. data->req.headerbytecount += (long)headerlen;
  2911. data->req.deductheadercount =
  2912. (100 <= k->httpcode && 199 >= k->httpcode)?data->req.headerbytecount:0;
  2913. /* Curl_http_auth_act() checks what authentication methods
  2914. * that are available and decides which one (if any) to
  2915. * use. It will set 'newurl' if an auth method was picked. */
  2916. result = Curl_http_auth_act(conn);
  2917. if(result)
  2918. return result;
  2919. if(k->httpcode >= 300) {
  2920. if((!conn->bits.authneg) && !conn->bits.close &&
  2921. !conn->bits.rewindaftersend) {
  2922. /*
  2923. * General treatment of errors when about to send data. Including :
  2924. * "417 Expectation Failed", while waiting for 100-continue.
  2925. *
  2926. * The check for close above is done simply because of something
  2927. * else has already deemed the connection to get closed then
  2928. * something else should've considered the big picture and we
  2929. * avoid this check.
  2930. *
  2931. * rewindaftersend indicates that something has told libcurl to
  2932. * continue sending even if it gets discarded
  2933. */
  2934. switch(data->set.httpreq) {
  2935. case HTTPREQ_PUT:
  2936. case HTTPREQ_POST:
  2937. case HTTPREQ_POST_FORM:
  2938. case HTTPREQ_POST_MIME:
  2939. /* We got an error response. If this happened before the whole
  2940. * request body has been sent we stop sending and mark the
  2941. * connection for closure after we've read the entire response.
  2942. */
  2943. Curl_expire_done(data, EXPIRE_100_TIMEOUT);
  2944. if(!k->upload_done) {
  2945. if(data->set.http_keep_sending_on_error) {
  2946. infof(data, "HTTP error before end of send, keep sending\n");
  2947. if(k->exp100 > EXP100_SEND_DATA) {
  2948. k->exp100 = EXP100_SEND_DATA;
  2949. k->keepon |= KEEP_SEND;
  2950. }
  2951. }
  2952. else {
  2953. infof(data, "HTTP error before end of send, stop sending\n");
  2954. streamclose(conn, "Stop sending data before everything sent");
  2955. k->upload_done = TRUE;
  2956. k->keepon &= ~KEEP_SEND; /* don't send */
  2957. if(data->state.expect100header)
  2958. k->exp100 = EXP100_FAILED;
  2959. }
  2960. }
  2961. break;
  2962. default: /* default label present to avoid compiler warnings */
  2963. break;
  2964. }
  2965. }
  2966. if(conn->bits.rewindaftersend) {
  2967. /* We rewind after a complete send, so thus we continue
  2968. sending now */
  2969. infof(data, "Keep sending data to get tossed away!\n");
  2970. k->keepon |= KEEP_SEND;
  2971. }
  2972. }
  2973. if(!k->header) {
  2974. /*
  2975. * really end-of-headers.
  2976. *
  2977. * If we requested a "no body", this is a good time to get
  2978. * out and return home.
  2979. */
  2980. if(data->set.opt_no_body)
  2981. *stop_reading = TRUE;
  2982. #ifndef CURL_DISABLE_RTSP
  2983. else if((conn->handler->protocol & CURLPROTO_RTSP) &&
  2984. (data->set.rtspreq == RTSPREQ_DESCRIBE) &&
  2985. (k->size <= -1))
  2986. /* Respect section 4.4 of rfc2326: If the Content-Length header is
  2987. absent, a length 0 must be assumed. It will prevent libcurl from
  2988. hanging on DESCRIBE request that got refused for whatever
  2989. reason */
  2990. *stop_reading = TRUE;
  2991. #endif
  2992. else {
  2993. /* If we know the expected size of this document, we set the
  2994. maximum download size to the size of the expected
  2995. document or else, we won't know when to stop reading!
  2996. Note that we set the download maximum even if we read a
  2997. "Connection: close" header, to make sure that
  2998. "Content-Length: 0" still prevents us from attempting to
  2999. read the (missing) response-body.
  3000. */
  3001. /* According to RFC2616 section 4.4, we MUST ignore
  3002. Content-Length: headers if we are now receiving data
  3003. using chunked Transfer-Encoding.
  3004. */
  3005. if(k->chunk)
  3006. k->maxdownload = k->size = -1;
  3007. }
  3008. if(-1 != k->size) {
  3009. /* We do this operation even if no_body is true, since this
  3010. data might be retrieved later with curl_easy_getinfo()
  3011. and its CURLINFO_CONTENT_LENGTH_DOWNLOAD option. */
  3012. Curl_pgrsSetDownloadSize(data, k->size);
  3013. k->maxdownload = k->size;
  3014. }
  3015. /* If max download size is *zero* (nothing) we already have
  3016. nothing and can safely return ok now! But for HTTP/2, we'd
  3017. like to call http2_handle_stream_close to properly close a
  3018. stream. In order to do this, we keep reading until we
  3019. close the stream. */
  3020. if(0 == k->maxdownload
  3021. #if defined(USE_NGHTTP2)
  3022. && !((conn->handler->protocol & PROTO_FAMILY_HTTP) &&
  3023. conn->httpversion == 20)
  3024. #endif
  3025. )
  3026. *stop_reading = TRUE;
  3027. if(*stop_reading) {
  3028. /* we make sure that this socket isn't read more now */
  3029. k->keepon &= ~KEEP_RECV;
  3030. }
  3031. if(data->set.verbose)
  3032. Curl_debug(data, CURLINFO_HEADER_IN,
  3033. k->str_start, headerlen);
  3034. break; /* exit header line loop */
  3035. }
  3036. /* We continue reading headers, so reset the line-based
  3037. header parsing variables hbufp && hbuflen */
  3038. k->hbufp = data->state.headerbuff;
  3039. k->hbuflen = 0;
  3040. continue;
  3041. }
  3042. /*
  3043. * Checks for special headers coming up.
  3044. */
  3045. if(!k->headerline++) {
  3046. /* This is the first header, it MUST be the error code line
  3047. or else we consider this to be the body right away! */
  3048. int httpversion_major;
  3049. int rtspversion_major;
  3050. int nc = 0;
  3051. #ifdef CURL_DOES_CONVERSIONS
  3052. #define HEADER1 scratch
  3053. #define SCRATCHSIZE 21
  3054. CURLcode res;
  3055. char scratch[SCRATCHSIZE + 1]; /* "HTTP/major.minor 123" */
  3056. /* We can't really convert this yet because we
  3057. don't know if it's the 1st header line or the body.
  3058. So we do a partial conversion into a scratch area,
  3059. leaving the data at k->p as-is.
  3060. */
  3061. strncpy(&scratch[0], k->p, SCRATCHSIZE);
  3062. scratch[SCRATCHSIZE] = 0; /* null terminate */
  3063. res = Curl_convert_from_network(data,
  3064. &scratch[0],
  3065. SCRATCHSIZE);
  3066. if(res)
  3067. /* Curl_convert_from_network calls failf if unsuccessful */
  3068. return res;
  3069. #else
  3070. #define HEADER1 k->p /* no conversion needed, just use k->p */
  3071. #endif /* CURL_DOES_CONVERSIONS */
  3072. if(conn->handler->protocol & PROTO_FAMILY_HTTP) {
  3073. /*
  3074. * https://tools.ietf.org/html/rfc7230#section-3.1.2
  3075. *
  3076. * The response code is always a three-digit number in HTTP as the spec
  3077. * says. We try to allow any number here, but we cannot make
  3078. * guarantees on future behaviors since it isn't within the protocol.
  3079. */
  3080. char separator;
  3081. nc = sscanf(HEADER1,
  3082. " HTTP/%1d.%1d%c%3d",
  3083. &httpversion_major,
  3084. &conn->httpversion,
  3085. &separator,
  3086. &k->httpcode);
  3087. if(nc == 1 && httpversion_major == 2 &&
  3088. 1 == sscanf(HEADER1, " HTTP/2 %d", &k->httpcode)) {
  3089. conn->httpversion = 0;
  3090. nc = 4;
  3091. separator = ' ';
  3092. }
  3093. if((nc == 4) && (' ' == separator)) {
  3094. conn->httpversion += 10 * httpversion_major;
  3095. if(k->upgr101 == UPGR101_RECEIVED) {
  3096. /* supposedly upgraded to http2 now */
  3097. if(conn->httpversion != 20)
  3098. infof(data, "Lying server, not serving HTTP/2\n");
  3099. }
  3100. }
  3101. else if(!nc) {
  3102. /* this is the real world, not a Nirvana
  3103. NCSA 1.5.x returns this crap when asked for HTTP/1.1
  3104. */
  3105. nc = sscanf(HEADER1, " HTTP %3d", &k->httpcode);
  3106. conn->httpversion = 10;
  3107. /* If user has set option HTTP200ALIASES,
  3108. compare header line against list of aliases
  3109. */
  3110. if(!nc) {
  3111. if(checkhttpprefix(data, k->p, k->hbuflen) == STATUS_DONE) {
  3112. nc = 1;
  3113. k->httpcode = 200;
  3114. conn->httpversion = 10;
  3115. }
  3116. }
  3117. }
  3118. else {
  3119. failf(data, "Unsupported HTTP version in response\n");
  3120. return CURLE_UNSUPPORTED_PROTOCOL;
  3121. }
  3122. }
  3123. else if(conn->handler->protocol & CURLPROTO_RTSP) {
  3124. char separator;
  3125. nc = sscanf(HEADER1,
  3126. " RTSP/%1d.%1d%c%3d",
  3127. &rtspversion_major,
  3128. &conn->rtspversion,
  3129. &separator,
  3130. &k->httpcode);
  3131. if((nc == 4) && (' ' == separator)) {
  3132. conn->rtspversion += 10 * rtspversion_major;
  3133. conn->httpversion = 11; /* For us, RTSP acts like HTTP 1.1 */
  3134. }
  3135. else {
  3136. /* TODO: do we care about the other cases here? */
  3137. nc = 0;
  3138. }
  3139. }
  3140. if(nc) {
  3141. data->info.httpcode = k->httpcode;
  3142. data->info.httpversion = conn->httpversion;
  3143. if(!data->state.httpversion ||
  3144. data->state.httpversion > conn->httpversion)
  3145. /* store the lowest server version we encounter */
  3146. data->state.httpversion = conn->httpversion;
  3147. /*
  3148. * This code executes as part of processing the header. As a
  3149. * result, it's not totally clear how to interpret the
  3150. * response code yet as that depends on what other headers may
  3151. * be present. 401 and 407 may be errors, but may be OK
  3152. * depending on how authentication is working. Other codes
  3153. * are definitely errors, so give up here.
  3154. */
  3155. if(data->state.resume_from && data->set.httpreq == HTTPREQ_GET &&
  3156. k->httpcode == 416) {
  3157. /* "Requested Range Not Satisfiable", just proceed and
  3158. pretend this is no error */
  3159. k->ignorebody = TRUE; /* Avoid appending error msg to good data. */
  3160. }
  3161. else if(data->set.http_fail_on_error && (k->httpcode >= 400) &&
  3162. ((k->httpcode != 401) || !conn->bits.user_passwd) &&
  3163. ((k->httpcode != 407) || !conn->bits.proxy_user_passwd) ) {
  3164. /* serious error, go home! */
  3165. print_http_error(data);
  3166. return CURLE_HTTP_RETURNED_ERROR;
  3167. }
  3168. if(conn->httpversion == 10) {
  3169. /* Default action for HTTP/1.0 must be to close, unless
  3170. we get one of those fancy headers that tell us the
  3171. server keeps it open for us! */
  3172. infof(data, "HTTP 1.0, assume close after body\n");
  3173. connclose(conn, "HTTP/1.0 close after body");
  3174. }
  3175. else if(conn->httpversion == 20 ||
  3176. (k->upgr101 == UPGR101_REQUESTED && k->httpcode == 101)) {
  3177. DEBUGF(infof(data, "HTTP/2 found, allow multiplexing\n"));
  3178. /* HTTP/2 cannot blacklist multiplexing since it is a core
  3179. functionality of the protocol */
  3180. conn->bundle->multiuse = BUNDLE_MULTIPLEX;
  3181. }
  3182. else if(conn->httpversion >= 11 &&
  3183. !conn->bits.close) {
  3184. /* If HTTP version is >= 1.1 and connection is persistent
  3185. server supports pipelining. */
  3186. DEBUGF(infof(data,
  3187. "HTTP 1.1 or later with persistent connection, "
  3188. "pipelining supported\n"));
  3189. /* Activate pipelining if needed */
  3190. if(conn->bundle) {
  3191. if(!Curl_pipeline_site_blacklisted(data, conn))
  3192. conn->bundle->multiuse = BUNDLE_PIPELINING;
  3193. }
  3194. }
  3195. switch(k->httpcode) {
  3196. case 204:
  3197. /* (quote from RFC2616, section 10.2.5): The server has
  3198. * fulfilled the request but does not need to return an
  3199. * entity-body ... The 204 response MUST NOT include a
  3200. * message-body, and thus is always terminated by the first
  3201. * empty line after the header fields. */
  3202. /* FALLTHROUGH */
  3203. case 304:
  3204. /* (quote from RFC2616, section 10.3.5): The 304 response
  3205. * MUST NOT contain a message-body, and thus is always
  3206. * terminated by the first empty line after the header
  3207. * fields. */
  3208. if(data->set.timecondition)
  3209. data->info.timecond = TRUE;
  3210. k->size = 0;
  3211. k->maxdownload = 0;
  3212. k->ignorecl = TRUE; /* ignore Content-Length headers */
  3213. break;
  3214. default:
  3215. /* nothing */
  3216. break;
  3217. }
  3218. }
  3219. else {
  3220. k->header = FALSE; /* this is not a header line */
  3221. break;
  3222. }
  3223. }
  3224. result = Curl_convert_from_network(data, k->p, strlen(k->p));
  3225. /* Curl_convert_from_network calls failf if unsuccessful */
  3226. if(result)
  3227. return result;
  3228. /* Check for Content-Length: header lines to get size */
  3229. if(!k->ignorecl && !data->set.ignorecl &&
  3230. checkprefix("Content-Length:", k->p)) {
  3231. curl_off_t contentlength;
  3232. CURLofft offt = curlx_strtoofft(k->p + 15, NULL, 10, &contentlength);
  3233. if(offt == CURL_OFFT_OK) {
  3234. if(data->set.max_filesize &&
  3235. contentlength > data->set.max_filesize) {
  3236. failf(data, "Maximum file size exceeded");
  3237. return CURLE_FILESIZE_EXCEEDED;
  3238. }
  3239. k->size = contentlength;
  3240. k->maxdownload = k->size;
  3241. /* we set the progress download size already at this point
  3242. just to make it easier for apps/callbacks to extract this
  3243. info as soon as possible */
  3244. Curl_pgrsSetDownloadSize(data, k->size);
  3245. }
  3246. else if(offt == CURL_OFFT_FLOW) {
  3247. /* out of range */
  3248. if(data->set.max_filesize) {
  3249. failf(data, "Maximum file size exceeded");
  3250. return CURLE_FILESIZE_EXCEEDED;
  3251. }
  3252. streamclose(conn, "overflow content-length");
  3253. infof(data, "Overflow Content-Length: value!\n");
  3254. }
  3255. else {
  3256. /* negative or just rubbish - bad HTTP */
  3257. failf(data, "Invalid Content-Length: value");
  3258. return CURLE_WEIRD_SERVER_REPLY;
  3259. }
  3260. }
  3261. /* check for Content-Type: header lines to get the MIME-type */
  3262. else if(checkprefix("Content-Type:", k->p)) {
  3263. char *contenttype = Curl_copy_header_value(k->p);
  3264. if(!contenttype)
  3265. return CURLE_OUT_OF_MEMORY;
  3266. if(!*contenttype)
  3267. /* ignore empty data */
  3268. free(contenttype);
  3269. else {
  3270. Curl_safefree(data->info.contenttype);
  3271. data->info.contenttype = contenttype;
  3272. }
  3273. }
  3274. else if(checkprefix("Server:", k->p)) {
  3275. if(conn->httpversion < 20) {
  3276. /* only do this for non-h2 servers */
  3277. char *server_name = Curl_copy_header_value(k->p);
  3278. /* Turn off pipelining if the server version is blacklisted */
  3279. if(conn->bundle && (conn->bundle->multiuse == BUNDLE_PIPELINING)) {
  3280. if(Curl_pipeline_server_blacklisted(data, server_name))
  3281. conn->bundle->multiuse = BUNDLE_NO_MULTIUSE;
  3282. }
  3283. free(server_name);
  3284. }
  3285. }
  3286. else if((conn->httpversion == 10) &&
  3287. conn->bits.httpproxy &&
  3288. Curl_compareheader(k->p,
  3289. "Proxy-Connection:", "keep-alive")) {
  3290. /*
  3291. * When a HTTP/1.0 reply comes when using a proxy, the
  3292. * 'Proxy-Connection: keep-alive' line tells us the
  3293. * connection will be kept alive for our pleasure.
  3294. * Default action for 1.0 is to close.
  3295. */
  3296. connkeep(conn, "Proxy-Connection keep-alive"); /* don't close */
  3297. infof(data, "HTTP/1.0 proxy connection set to keep alive!\n");
  3298. }
  3299. else if((conn->httpversion == 11) &&
  3300. conn->bits.httpproxy &&
  3301. Curl_compareheader(k->p,
  3302. "Proxy-Connection:", "close")) {
  3303. /*
  3304. * We get a HTTP/1.1 response from a proxy and it says it'll
  3305. * close down after this transfer.
  3306. */
  3307. connclose(conn, "Proxy-Connection: asked to close after done");
  3308. infof(data, "HTTP/1.1 proxy connection set close!\n");
  3309. }
  3310. else if((conn->httpversion == 10) &&
  3311. Curl_compareheader(k->p, "Connection:", "keep-alive")) {
  3312. /*
  3313. * A HTTP/1.0 reply with the 'Connection: keep-alive' line
  3314. * tells us the connection will be kept alive for our
  3315. * pleasure. Default action for 1.0 is to close.
  3316. *
  3317. * [RFC2068, section 19.7.1] */
  3318. connkeep(conn, "Connection keep-alive");
  3319. infof(data, "HTTP/1.0 connection set to keep alive!\n");
  3320. }
  3321. else if(Curl_compareheader(k->p, "Connection:", "close")) {
  3322. /*
  3323. * [RFC 2616, section 8.1.2.1]
  3324. * "Connection: close" is HTTP/1.1 language and means that
  3325. * the connection will close when this request has been
  3326. * served.
  3327. */
  3328. streamclose(conn, "Connection: close used");
  3329. }
  3330. else if(checkprefix("Transfer-Encoding:", k->p)) {
  3331. /* One or more encodings. We check for chunked and/or a compression
  3332. algorithm. */
  3333. /*
  3334. * [RFC 2616, section 3.6.1] A 'chunked' transfer encoding
  3335. * means that the server will send a series of "chunks". Each
  3336. * chunk starts with line with info (including size of the
  3337. * coming block) (terminated with CRLF), then a block of data
  3338. * with the previously mentioned size. There can be any amount
  3339. * of chunks, and a chunk-data set to zero signals the
  3340. * end-of-chunks. */
  3341. result = Curl_build_unencoding_stack(conn, k->p + 18, TRUE);
  3342. if(result)
  3343. return result;
  3344. }
  3345. else if(checkprefix("Content-Encoding:", k->p) &&
  3346. data->set.str[STRING_ENCODING]) {
  3347. /*
  3348. * Process Content-Encoding. Look for the values: identity,
  3349. * gzip, deflate, compress, x-gzip and x-compress. x-gzip and
  3350. * x-compress are the same as gzip and compress. (Sec 3.5 RFC
  3351. * 2616). zlib cannot handle compress. However, errors are
  3352. * handled further down when the response body is processed
  3353. */
  3354. result = Curl_build_unencoding_stack(conn, k->p + 17, FALSE);
  3355. if(result)
  3356. return result;
  3357. }
  3358. else if(checkprefix("Content-Range:", k->p)) {
  3359. /* Content-Range: bytes [num]-
  3360. Content-Range: bytes: [num]-
  3361. Content-Range: [num]-
  3362. Content-Range: [asterisk]/[total]
  3363. The second format was added since Sun's webserver
  3364. JavaWebServer/1.1.1 obviously sends the header this way!
  3365. The third added since some servers use that!
  3366. The forth means the requested range was unsatisfied.
  3367. */
  3368. char *ptr = k->p + 14;
  3369. /* Move forward until first digit or asterisk */
  3370. while(*ptr && !ISDIGIT(*ptr) && *ptr != '*')
  3371. ptr++;
  3372. /* if it truly stopped on a digit */
  3373. if(ISDIGIT(*ptr)) {
  3374. if(!curlx_strtoofft(ptr, NULL, 10, &k->offset)) {
  3375. if(data->state.resume_from == k->offset)
  3376. /* we asked for a resume and we got it */
  3377. k->content_range = TRUE;
  3378. }
  3379. }
  3380. else
  3381. data->state.resume_from = 0; /* get everything */
  3382. }
  3383. #if !defined(CURL_DISABLE_COOKIES)
  3384. else if(data->cookies &&
  3385. checkprefix("Set-Cookie:", k->p)) {
  3386. Curl_share_lock(data, CURL_LOCK_DATA_COOKIE,
  3387. CURL_LOCK_ACCESS_SINGLE);
  3388. Curl_cookie_add(data,
  3389. data->cookies, TRUE, FALSE, k->p + 11,
  3390. /* If there is a custom-set Host: name, use it
  3391. here, or else use real peer host name. */
  3392. conn->allocptr.cookiehost?
  3393. conn->allocptr.cookiehost:conn->host.name,
  3394. data->state.path);
  3395. Curl_share_unlock(data, CURL_LOCK_DATA_COOKIE);
  3396. }
  3397. #endif
  3398. else if(checkprefix("Last-Modified:", k->p) &&
  3399. (data->set.timecondition || data->set.get_filetime) ) {
  3400. time_t secs = time(NULL);
  3401. k->timeofdoc = curl_getdate(k->p + strlen("Last-Modified:"),
  3402. &secs);
  3403. if(data->set.get_filetime)
  3404. data->info.filetime = k->timeofdoc;
  3405. }
  3406. else if((checkprefix("WWW-Authenticate:", k->p) &&
  3407. (401 == k->httpcode)) ||
  3408. (checkprefix("Proxy-authenticate:", k->p) &&
  3409. (407 == k->httpcode))) {
  3410. bool proxy = (k->httpcode == 407) ? TRUE : FALSE;
  3411. char *auth = Curl_copy_header_value(k->p);
  3412. if(!auth)
  3413. return CURLE_OUT_OF_MEMORY;
  3414. result = Curl_http_input_auth(conn, proxy, auth);
  3415. free(auth);
  3416. if(result)
  3417. return result;
  3418. }
  3419. else if((k->httpcode >= 300 && k->httpcode < 400) &&
  3420. checkprefix("Location:", k->p) &&
  3421. !data->req.location) {
  3422. /* this is the URL that the server advises us to use instead */
  3423. char *location = Curl_copy_header_value(k->p);
  3424. if(!location)
  3425. return CURLE_OUT_OF_MEMORY;
  3426. if(!*location)
  3427. /* ignore empty data */
  3428. free(location);
  3429. else {
  3430. data->req.location = location;
  3431. if(data->set.http_follow_location) {
  3432. DEBUGASSERT(!data->req.newurl);
  3433. data->req.newurl = strdup(data->req.location); /* clone */
  3434. if(!data->req.newurl)
  3435. return CURLE_OUT_OF_MEMORY;
  3436. /* some cases of POST and PUT etc needs to rewind the data
  3437. stream at this point */
  3438. result = http_perhapsrewind(conn);
  3439. if(result)
  3440. return result;
  3441. }
  3442. }
  3443. }
  3444. else if(conn->handler->protocol & CURLPROTO_RTSP) {
  3445. result = Curl_rtsp_parseheader(conn, k->p);
  3446. if(result)
  3447. return result;
  3448. }
  3449. /*
  3450. * End of header-checks. Write them to the client.
  3451. */
  3452. writetype = CLIENTWRITE_HEADER;
  3453. if(data->set.include_header)
  3454. writetype |= CLIENTWRITE_BODY;
  3455. if(data->set.verbose)
  3456. Curl_debug(data, CURLINFO_HEADER_IN, k->p, (size_t)k->hbuflen);
  3457. result = Curl_client_write(conn, writetype, k->p, k->hbuflen);
  3458. if(result)
  3459. return result;
  3460. data->info.header_size += (long)k->hbuflen;
  3461. data->req.headerbytecount += (long)k->hbuflen;
  3462. /* reset hbufp pointer && hbuflen */
  3463. k->hbufp = data->state.headerbuff;
  3464. k->hbuflen = 0;
  3465. }
  3466. while(*k->str); /* header line within buffer */
  3467. /* We might have reached the end of the header part here, but
  3468. there might be a non-header part left in the end of the read
  3469. buffer. */
  3470. return CURLE_OK;
  3471. }
  3472. #endif /* CURL_DISABLE_HTTP */