http.c 120 KB

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