http.c 109 KB

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