http.c 113 KB

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