http.c 120 KB

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