http.c 118 KB

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