http.c 92 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900
  1. /***************************************************************************
  2. * _ _ ____ _
  3. * Project ___| | | | _ \| |
  4. * / __| | | | |_) | |
  5. * | (__| |_| | _ <| |___
  6. * \___|\___/|_| \_\_____|
  7. *
  8. * Copyright (C) 1998 - 2008, Daniel Stenberg, <[email protected]>, et al.
  9. *
  10. * This software is licensed as described in the file COPYING, which
  11. * you should have received as part of this distribution. The terms
  12. * are also available at http://curl.haxx.se/docs/copyright.html.
  13. *
  14. * You may opt to use, copy, modify, merge, publish, distribute and/or sell
  15. * copies of the Software, and permit persons to whom the Software is
  16. * furnished to do so, under the terms of the COPYING file.
  17. *
  18. * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
  19. * KIND, either express or implied.
  20. *
  21. * $Id$
  22. ***************************************************************************/
  23. #include "setup.h"
  24. #ifndef CURL_DISABLE_HTTP
  25. /* -- WIN32 approved -- */
  26. #include <stdio.h>
  27. #include <string.h>
  28. #include <stdarg.h>
  29. #include <stdlib.h>
  30. #include <ctype.h>
  31. #ifdef WIN32
  32. #include <time.h>
  33. #include <io.h>
  34. #else
  35. #ifdef HAVE_SYS_SOCKET_H
  36. #include <sys/socket.h>
  37. #endif
  38. #ifdef HAVE_NETINET_IN_H
  39. #include <netinet/in.h>
  40. #endif
  41. #ifdef HAVE_SYS_TIME_H
  42. #include <sys/time.h>
  43. #endif
  44. #ifdef HAVE_TIME_H
  45. #ifdef TIME_WITH_SYS_TIME
  46. #include <time.h>
  47. #endif
  48. #endif
  49. #ifdef HAVE_UNISTD_H
  50. #include <unistd.h>
  51. #endif
  52. #ifdef HAVE_NETDB_H
  53. #include <netdb.h>
  54. #endif
  55. #ifdef HAVE_ARPA_INET_H
  56. #include <arpa/inet.h>
  57. #endif
  58. #ifdef HAVE_NET_IF_H
  59. #include <net/if.h>
  60. #endif
  61. #ifdef HAVE_SYS_IOCTL_H
  62. #include <sys/ioctl.h>
  63. #endif
  64. #include <signal.h>
  65. #ifdef HAVE_SYS_PARAM_H
  66. #include <sys/param.h>
  67. #endif
  68. #endif
  69. #include "urldata.h"
  70. #include <curl/curl.h>
  71. #include "transfer.h"
  72. #include "sendf.h"
  73. #include "easyif.h" /* for Curl_convert_... prototypes */
  74. #include "formdata.h"
  75. #include "progress.h"
  76. #include "curl_base64.h"
  77. #include "cookie.h"
  78. #include "strequal.h"
  79. #include "sslgen.h"
  80. #include "http_digest.h"
  81. #include "http_ntlm.h"
  82. #include "http_negotiate.h"
  83. #include "url.h"
  84. #include "share.h"
  85. #include "hostip.h"
  86. #include "http.h"
  87. #include "memory.h"
  88. #include "select.h"
  89. #include "parsedate.h" /* for the week day and month names */
  90. #include "strtoofft.h"
  91. #include "multiif.h"
  92. #define _MPRINTF_REPLACE /* use our functions only */
  93. #include <curl/mprintf.h>
  94. /* The last #include file should be: */
  95. #include "memdebug.h"
  96. /* Default proxy timeout in milliseconds */
  97. #define PROXY_TIMEOUT (3600*1000)
  98. /*
  99. * Forward declarations.
  100. */
  101. static int http_getsock_do(struct connectdata *conn,
  102. curl_socket_t *socks,
  103. int numsocks);
  104. static CURLcode https_connecting(struct connectdata *conn, bool *done);
  105. #ifdef USE_SSL
  106. static int https_getsock(struct connectdata *conn,
  107. curl_socket_t *socks,
  108. int numsocks);
  109. #endif
  110. /*
  111. * HTTP handler interface.
  112. */
  113. const struct Curl_handler Curl_handler_http = {
  114. "HTTP", /* scheme */
  115. ZERO_NULL, /* setup_connection */
  116. Curl_http, /* do_it */
  117. Curl_http_done, /* done */
  118. ZERO_NULL, /* do_more */
  119. Curl_http_connect, /* connect_it */
  120. ZERO_NULL, /* connecting */
  121. ZERO_NULL, /* doing */
  122. ZERO_NULL, /* proto_getsock */
  123. http_getsock_do, /* doing_getsock */
  124. ZERO_NULL, /* disconnect */
  125. PORT_HTTP, /* defport */
  126. PROT_HTTP, /* protocol */
  127. };
  128. #ifdef USE_SSL
  129. /*
  130. * HTTPS handler interface.
  131. */
  132. const struct Curl_handler Curl_handler_https = {
  133. "HTTPS", /* scheme */
  134. ZERO_NULL, /* setup_connection */
  135. Curl_http, /* do_it */
  136. Curl_http_done, /* done */
  137. ZERO_NULL, /* do_more */
  138. Curl_http_connect, /* connect_it */
  139. https_connecting, /* connecting */
  140. ZERO_NULL, /* doing */
  141. https_getsock, /* proto_getsock */
  142. http_getsock_do, /* doing_getsock */
  143. ZERO_NULL, /* disconnect */
  144. PORT_HTTPS, /* defport */
  145. PROT_HTTP | PROT_HTTPS | PROT_SSL /* protocol */
  146. };
  147. #endif
  148. /*
  149. * checkheaders() checks the linked list of custom HTTP headers for a
  150. * particular header (prefix).
  151. *
  152. * Returns a pointer to the first matching header or NULL if none matched.
  153. */
  154. static char *checkheaders(struct SessionHandle *data, const char *thisheader)
  155. {
  156. struct curl_slist *head;
  157. size_t thislen = strlen(thisheader);
  158. for(head = data->set.headers; head; head=head->next) {
  159. if(strnequal(head->data, thisheader, thislen))
  160. return head->data;
  161. }
  162. return NULL;
  163. }
  164. /*
  165. * Strip off leading and trailing whitespace from the value in the
  166. * given HTTP header line and return a strdupped copy. Returns NULL in
  167. * case of allocation failure. Returns an empty string if the header value
  168. * consists entirely of whitespace.
  169. */
  170. char *Curl_copy_header_value(const char *h)
  171. {
  172. const char *start;
  173. const char *end;
  174. char *value;
  175. size_t len;
  176. DEBUGASSERT(h);
  177. /* Find the end of the header name */
  178. while (*h && (*h != ':'))
  179. ++h;
  180. if (*h)
  181. /* Skip over colon */
  182. ++h;
  183. /* Find the first non-space letter */
  184. for(start=h;
  185. *start && ISSPACE(*start);
  186. start++)
  187. ; /* empty loop */
  188. /* data is in the host encoding so
  189. use '\r' and '\n' instead of 0x0d and 0x0a */
  190. end = strchr(start, '\r');
  191. if(!end)
  192. end = strchr(start, '\n');
  193. if(!end)
  194. end = strchr(start, '\0');
  195. /* skip all trailing space letters */
  196. for(; ISSPACE(*end) && (end > start); end--)
  197. ; /* empty loop */
  198. /* get length of the type */
  199. len = end-start+1;
  200. value = malloc(len + 1);
  201. if(!value)
  202. return NULL;
  203. memcpy(value, start, len);
  204. value[len] = 0; /* zero terminate */
  205. return value;
  206. }
  207. /*
  208. * http_output_basic() sets up an Authorization: header (or the proxy version)
  209. * for HTTP Basic authentication.
  210. *
  211. * Returns CURLcode.
  212. */
  213. static CURLcode http_output_basic(struct connectdata *conn, bool proxy)
  214. {
  215. char *authorization;
  216. struct SessionHandle *data=conn->data;
  217. char **userp;
  218. char *user;
  219. char *pwd;
  220. if(proxy) {
  221. userp = &conn->allocptr.proxyuserpwd;
  222. user = conn->proxyuser;
  223. pwd = conn->proxypasswd;
  224. }
  225. else {
  226. userp = &conn->allocptr.userpwd;
  227. user = conn->user;
  228. pwd = conn->passwd;
  229. }
  230. snprintf(data->state.buffer, sizeof(data->state.buffer), "%s:%s", user, pwd);
  231. if(Curl_base64_encode(data, data->state.buffer,
  232. strlen(data->state.buffer),
  233. &authorization) > 0) {
  234. if(*userp)
  235. free(*userp);
  236. *userp = aprintf( "%sAuthorization: Basic %s\r\n",
  237. proxy?"Proxy-":"",
  238. authorization);
  239. free(authorization);
  240. if(!*userp)
  241. return CURLE_OUT_OF_MEMORY;
  242. }
  243. else
  244. return CURLE_OUT_OF_MEMORY;
  245. return CURLE_OK;
  246. }
  247. /* pickoneauth() selects the most favourable authentication method from the
  248. * ones available and the ones we want.
  249. *
  250. * return TRUE if one was picked
  251. */
  252. static bool pickoneauth(struct auth *pick)
  253. {
  254. bool picked;
  255. /* only deal with authentication we want */
  256. long avail = pick->avail & pick->want;
  257. picked = TRUE;
  258. /* The order of these checks is highly relevant, as this will be the order
  259. of preference in case of the existance of multiple accepted types. */
  260. if(avail & CURLAUTH_GSSNEGOTIATE)
  261. pick->picked = CURLAUTH_GSSNEGOTIATE;
  262. else if(avail & CURLAUTH_DIGEST)
  263. pick->picked = CURLAUTH_DIGEST;
  264. else if(avail & CURLAUTH_NTLM)
  265. pick->picked = CURLAUTH_NTLM;
  266. else if(avail & CURLAUTH_BASIC)
  267. pick->picked = CURLAUTH_BASIC;
  268. else {
  269. pick->picked = CURLAUTH_PICKNONE; /* we select to use nothing */
  270. picked = FALSE;
  271. }
  272. pick->avail = CURLAUTH_NONE; /* clear it here */
  273. return picked;
  274. }
  275. /*
  276. * Curl_http_perhapsrewind()
  277. *
  278. * If we are doing POST or PUT {
  279. * If we have more data to send {
  280. * If we are doing NTLM {
  281. * Keep sending since we must not disconnect
  282. * }
  283. * else {
  284. * If there is more than just a little data left to send, close
  285. * the current connection by force.
  286. * }
  287. * }
  288. * If we have sent any data {
  289. * If we don't have track of all the data {
  290. * call app to tell it to rewind
  291. * }
  292. * else {
  293. * rewind internally so that the operation can restart fine
  294. * }
  295. * }
  296. * }
  297. */
  298. CURLcode Curl_http_perhapsrewind(struct connectdata *conn)
  299. {
  300. struct SessionHandle *data = conn->data;
  301. struct HTTP *http = data->state.proto.http;
  302. curl_off_t bytessent;
  303. curl_off_t expectsend = -1; /* default is unknown */
  304. if(!http || !(conn->protocol & PROT_HTTP))
  305. /* If this is still NULL, we have not reach very far and we can
  306. safely skip this rewinding stuff, or this is attempted to get used
  307. when HTTP isn't activated */
  308. return CURLE_OK;
  309. switch(data->set.httpreq) {
  310. case HTTPREQ_GET:
  311. case HTTPREQ_HEAD:
  312. return CURLE_OK;
  313. default:
  314. break;
  315. }
  316. bytessent = http->writebytecount;
  317. if(conn->bits.authneg)
  318. /* This is a state where we are known to be negotiating and we don't send
  319. any data then. */
  320. expectsend = 0;
  321. else {
  322. /* figure out how much data we are expected to send */
  323. switch(data->set.httpreq) {
  324. case HTTPREQ_POST:
  325. if(data->set.postfieldsize != -1)
  326. expectsend = data->set.postfieldsize;
  327. break;
  328. case HTTPREQ_PUT:
  329. if(data->set.infilesize != -1)
  330. expectsend = data->set.infilesize;
  331. break;
  332. case HTTPREQ_POST_FORM:
  333. expectsend = http->postsize;
  334. break;
  335. default:
  336. break;
  337. }
  338. }
  339. conn->bits.rewindaftersend = FALSE; /* default */
  340. if((expectsend == -1) || (expectsend > bytessent)) {
  341. /* There is still data left to send */
  342. if((data->state.authproxy.picked == CURLAUTH_NTLM) ||
  343. (data->state.authhost.picked == CURLAUTH_NTLM)) {
  344. if(((expectsend - bytessent) < 2000) ||
  345. (conn->ntlm.state != NTLMSTATE_NONE)) {
  346. /* The NTLM-negotiation has started *OR* there is just a little (<2K)
  347. data left to send, keep on sending. */
  348. /* rewind data when completely done sending! */
  349. if(!conn->bits.authneg)
  350. conn->bits.rewindaftersend = TRUE;
  351. return CURLE_OK;
  352. }
  353. if(conn->bits.close)
  354. /* this is already marked to get closed */
  355. return CURLE_OK;
  356. infof(data, "NTLM send, close instead of sending %" FORMAT_OFF_T
  357. " bytes\n", (curl_off_t)(expectsend - bytessent));
  358. }
  359. /* This is not NTLM or NTLM with many bytes left to send: close
  360. */
  361. conn->bits.close = TRUE;
  362. data->req.size = 0; /* don't download any more than 0 bytes */
  363. /* There still is data left to send, but this connection is marked for
  364. closure so we can safely do the rewind right now */
  365. }
  366. if(bytessent)
  367. /* we rewind now at once since if we already sent something */
  368. return Curl_readrewind(conn);
  369. return CURLE_OK;
  370. }
  371. /*
  372. * Curl_http_auth_act() gets called when a all HTTP headers have been received
  373. * and it checks what authentication methods that are available and decides
  374. * which one (if any) to use. It will set 'newurl' if an auth metod was
  375. * picked.
  376. */
  377. CURLcode Curl_http_auth_act(struct connectdata *conn)
  378. {
  379. struct SessionHandle *data = conn->data;
  380. bool pickhost = FALSE;
  381. bool pickproxy = FALSE;
  382. CURLcode code = CURLE_OK;
  383. if(100 <= data->req.httpcode && 199 >= data->req.httpcode)
  384. /* this is a transient response code, ignore */
  385. return CURLE_OK;
  386. if(data->state.authproblem)
  387. return data->set.http_fail_on_error?CURLE_HTTP_RETURNED_ERROR:CURLE_OK;
  388. if(conn->bits.user_passwd &&
  389. ((data->req.httpcode == 401) ||
  390. (conn->bits.authneg && data->req.httpcode < 300))) {
  391. pickhost = pickoneauth(&data->state.authhost);
  392. if(!pickhost)
  393. data->state.authproblem = TRUE;
  394. }
  395. if(conn->bits.proxy_user_passwd &&
  396. ((data->req.httpcode == 407) ||
  397. (conn->bits.authneg && data->req.httpcode < 300))) {
  398. pickproxy = pickoneauth(&data->state.authproxy);
  399. if(!pickproxy)
  400. data->state.authproblem = TRUE;
  401. }
  402. if(pickhost || pickproxy) {
  403. data->req.newurl = strdup(data->change.url); /* clone URL */
  404. if(!data->req.newurl)
  405. return CURLE_OUT_OF_MEMORY;
  406. if((data->set.httpreq != HTTPREQ_GET) &&
  407. (data->set.httpreq != HTTPREQ_HEAD) &&
  408. !conn->bits.rewindaftersend) {
  409. code = Curl_http_perhapsrewind(conn);
  410. if(code)
  411. return code;
  412. }
  413. }
  414. else if((data->req.httpcode < 300) &&
  415. (!data->state.authhost.done) &&
  416. conn->bits.authneg) {
  417. /* no (known) authentication available,
  418. authentication is not "done" yet and
  419. no authentication seems to be required and
  420. we didn't try HEAD or GET */
  421. if((data->set.httpreq != HTTPREQ_GET) &&
  422. (data->set.httpreq != HTTPREQ_HEAD)) {
  423. data->req.newurl = strdup(data->change.url); /* clone URL */
  424. if(!data->req.newurl)
  425. return CURLE_OUT_OF_MEMORY;
  426. data->state.authhost.done = TRUE;
  427. }
  428. }
  429. if(Curl_http_should_fail(conn)) {
  430. failf (data, "The requested URL returned error: %d",
  431. data->req.httpcode);
  432. code = CURLE_HTTP_RETURNED_ERROR;
  433. }
  434. return code;
  435. }
  436. /**
  437. * Curl_http_output_auth() setups the authentication headers for the
  438. * host/proxy and the correct authentication
  439. * method. conn->data->state.authdone is set to TRUE when authentication is
  440. * done.
  441. *
  442. * @param conn all information about the current connection
  443. * @param request pointer to the request keyword
  444. * @param path pointer to the requested path
  445. * @param proxytunnel boolean if this is the request setting up a "proxy
  446. * tunnel"
  447. *
  448. * @returns CURLcode
  449. */
  450. static CURLcode
  451. http_output_auth(struct connectdata *conn,
  452. const char *request,
  453. const char *path,
  454. bool proxytunnel) /* TRUE if this is the request setting
  455. up the proxy tunnel */
  456. {
  457. CURLcode result = CURLE_OK;
  458. struct SessionHandle *data = conn->data;
  459. const char *auth=NULL;
  460. struct auth *authhost;
  461. struct auth *authproxy;
  462. DEBUGASSERT(data);
  463. authhost = &data->state.authhost;
  464. authproxy = &data->state.authproxy;
  465. if((conn->bits.httpproxy && conn->bits.proxy_user_passwd) ||
  466. conn->bits.user_passwd)
  467. /* continue please */ ;
  468. else {
  469. authhost->done = TRUE;
  470. authproxy->done = TRUE;
  471. return CURLE_OK; /* no authentication with no user or password */
  472. }
  473. if(authhost->want && !authhost->picked)
  474. /* The app has selected one or more methods, but none has been picked
  475. so far by a server round-trip. Then we set the picked one to the
  476. want one, and if this is one single bit it'll be used instantly. */
  477. authhost->picked = authhost->want;
  478. if(authproxy->want && !authproxy->picked)
  479. /* The app has selected one or more methods, but none has been picked so
  480. far by a proxy round-trip. Then we set the picked one to the want one,
  481. and if this is one single bit it'll be used instantly. */
  482. authproxy->picked = authproxy->want;
  483. /* Send proxy authentication header if needed */
  484. if(conn->bits.httpproxy &&
  485. (conn->bits.tunnel_proxy == proxytunnel)) {
  486. #ifdef HAVE_GSSAPI
  487. if((authproxy->picked == CURLAUTH_GSSNEGOTIATE) &&
  488. data->state.negotiate.context &&
  489. !GSS_ERROR(data->state.negotiate.status)) {
  490. auth="GSS-Negotiate";
  491. result = Curl_output_negotiate(conn, TRUE);
  492. if(result)
  493. return result;
  494. authproxy->done = TRUE;
  495. }
  496. else
  497. #endif
  498. #ifdef USE_NTLM
  499. if(authproxy->picked == CURLAUTH_NTLM) {
  500. auth="NTLM";
  501. result = Curl_output_ntlm(conn, TRUE);
  502. if(result)
  503. return result;
  504. }
  505. else
  506. #endif
  507. if(authproxy->picked == CURLAUTH_BASIC) {
  508. /* Basic */
  509. if(conn->bits.proxy_user_passwd &&
  510. !checkheaders(data, "Proxy-authorization:")) {
  511. auth="Basic";
  512. result = http_output_basic(conn, TRUE);
  513. if(result)
  514. return result;
  515. }
  516. /* NOTE: http_output_basic() should set 'done' TRUE, as the other auth
  517. functions work that way */
  518. authproxy->done = TRUE;
  519. }
  520. #ifndef CURL_DISABLE_CRYPTO_AUTH
  521. else if(authproxy->picked == CURLAUTH_DIGEST) {
  522. auth="Digest";
  523. result = Curl_output_digest(conn,
  524. TRUE, /* proxy */
  525. (const unsigned char *)request,
  526. (const unsigned char *)path);
  527. if(result)
  528. return result;
  529. }
  530. #endif
  531. if(auth) {
  532. infof(data, "Proxy auth using %s with user '%s'\n",
  533. auth, conn->proxyuser?conn->proxyuser:"");
  534. authproxy->multi = (bool)(!authproxy->done);
  535. }
  536. else
  537. authproxy->multi = FALSE;
  538. }
  539. else
  540. /* we have no proxy so let's pretend we're done authenticating
  541. with it */
  542. authproxy->done = TRUE;
  543. /* To prevent the user+password to get sent to other than the original
  544. host due to a location-follow, we do some weirdo checks here */
  545. if(!data->state.this_is_a_follow ||
  546. conn->bits.netrc ||
  547. !data->state.first_host ||
  548. curl_strequal(data->state.first_host, conn->host.name) ||
  549. data->set.http_disable_hostname_check_before_authentication) {
  550. /* Send web authentication header if needed */
  551. {
  552. auth = NULL;
  553. #ifdef HAVE_GSSAPI
  554. if((authhost->picked == CURLAUTH_GSSNEGOTIATE) &&
  555. data->state.negotiate.context &&
  556. !GSS_ERROR(data->state.negotiate.status)) {
  557. auth="GSS-Negotiate";
  558. result = Curl_output_negotiate(conn, FALSE);
  559. if(result)
  560. return result;
  561. authhost->done = TRUE;
  562. }
  563. else
  564. #endif
  565. #ifdef USE_NTLM
  566. if(authhost->picked == CURLAUTH_NTLM) {
  567. auth="NTLM";
  568. result = Curl_output_ntlm(conn, FALSE);
  569. if(result)
  570. return result;
  571. }
  572. else
  573. #endif
  574. {
  575. #ifndef CURL_DISABLE_CRYPTO_AUTH
  576. if(authhost->picked == CURLAUTH_DIGEST) {
  577. auth="Digest";
  578. result = Curl_output_digest(conn,
  579. FALSE, /* not a proxy */
  580. (const unsigned char *)request,
  581. (const unsigned char *)path);
  582. if(result)
  583. return result;
  584. } else
  585. #endif
  586. if(authhost->picked == CURLAUTH_BASIC) {
  587. if(conn->bits.user_passwd &&
  588. !checkheaders(data, "Authorization:")) {
  589. auth="Basic";
  590. result = http_output_basic(conn, FALSE);
  591. if(result)
  592. return result;
  593. }
  594. /* basic is always ready */
  595. authhost->done = TRUE;
  596. }
  597. }
  598. if(auth) {
  599. infof(data, "Server auth using %s with user '%s'\n",
  600. auth, conn->user);
  601. authhost->multi = (bool)(!authhost->done);
  602. }
  603. else
  604. authhost->multi = FALSE;
  605. }
  606. }
  607. else
  608. authhost->done = TRUE;
  609. return result;
  610. }
  611. /*
  612. * Curl_http_input_auth() deals with Proxy-Authenticate: and WWW-Authenticate:
  613. * headers. They are dealt with both in the transfer.c main loop and in the
  614. * proxy CONNECT loop.
  615. */
  616. CURLcode Curl_http_input_auth(struct connectdata *conn,
  617. int httpcode,
  618. const char *header) /* the first non-space */
  619. {
  620. /*
  621. * This resource requires authentication
  622. */
  623. struct SessionHandle *data = conn->data;
  624. long *availp;
  625. const char *start;
  626. struct auth *authp;
  627. if(httpcode == 407) {
  628. start = header+strlen("Proxy-authenticate:");
  629. availp = &data->info.proxyauthavail;
  630. authp = &data->state.authproxy;
  631. }
  632. else {
  633. start = header+strlen("WWW-Authenticate:");
  634. availp = &data->info.httpauthavail;
  635. authp = &data->state.authhost;
  636. }
  637. /* pass all white spaces */
  638. while(*start && ISSPACE(*start))
  639. start++;
  640. /*
  641. * Here we check if we want the specific single authentication (using ==) and
  642. * if we do, we initiate usage of it.
  643. *
  644. * If the provided authentication is wanted as one out of several accepted
  645. * types (using &), we OR this authentication type to the authavail
  646. * variable.
  647. */
  648. #ifdef HAVE_GSSAPI
  649. if(checkprefix("GSS-Negotiate", start) ||
  650. checkprefix("Negotiate", start)) {
  651. *availp |= CURLAUTH_GSSNEGOTIATE;
  652. authp->avail |= CURLAUTH_GSSNEGOTIATE;
  653. if(authp->picked == CURLAUTH_GSSNEGOTIATE) {
  654. /* if exactly this is wanted, go */
  655. int neg = Curl_input_negotiate(conn, (bool)(httpcode == 407), start);
  656. if(neg == 0) {
  657. DEBUGASSERT(!data->req.newurl);
  658. data->req.newurl = strdup(data->change.url);
  659. data->state.authproblem = (data->req.newurl == NULL);
  660. }
  661. else {
  662. infof(data, "Authentication problem. Ignoring this.\n");
  663. data->state.authproblem = TRUE;
  664. }
  665. }
  666. }
  667. else
  668. #endif
  669. #ifdef USE_NTLM
  670. /* NTLM support requires the SSL crypto libs */
  671. if(checkprefix("NTLM", start)) {
  672. *availp |= CURLAUTH_NTLM;
  673. authp->avail |= CURLAUTH_NTLM;
  674. if(authp->picked == CURLAUTH_NTLM) {
  675. /* NTLM authentication is picked and activated */
  676. CURLntlm ntlm =
  677. Curl_input_ntlm(conn, (bool)(httpcode == 407), start);
  678. if(CURLNTLM_BAD != ntlm)
  679. data->state.authproblem = FALSE;
  680. else {
  681. infof(data, "Authentication problem. Ignoring this.\n");
  682. data->state.authproblem = TRUE;
  683. }
  684. }
  685. }
  686. else
  687. #endif
  688. #ifndef CURL_DISABLE_CRYPTO_AUTH
  689. if(checkprefix("Digest", start)) {
  690. if((authp->avail & CURLAUTH_DIGEST) != 0) {
  691. infof(data, "Ignoring duplicate digest auth header.\n");
  692. }
  693. else {
  694. CURLdigest dig;
  695. *availp |= CURLAUTH_DIGEST;
  696. authp->avail |= CURLAUTH_DIGEST;
  697. /* We call this function on input Digest headers even if Digest
  698. * authentication isn't activated yet, as we need to store the
  699. * incoming data from this header in case we are gonna use Digest. */
  700. dig = Curl_input_digest(conn, (bool)(httpcode == 407), start);
  701. if(CURLDIGEST_FINE != dig) {
  702. infof(data, "Authentication problem. Ignoring this.\n");
  703. data->state.authproblem = TRUE;
  704. }
  705. }
  706. }
  707. else
  708. #endif
  709. if(checkprefix("Basic", start)) {
  710. *availp |= CURLAUTH_BASIC;
  711. authp->avail |= CURLAUTH_BASIC;
  712. if(authp->picked == CURLAUTH_BASIC) {
  713. /* We asked for Basic authentication but got a 40X back
  714. anyway, which basicly means our name+password isn't
  715. valid. */
  716. authp->avail = CURLAUTH_NONE;
  717. infof(data, "Authentication problem. Ignoring this.\n");
  718. data->state.authproblem = TRUE;
  719. }
  720. }
  721. return CURLE_OK;
  722. }
  723. /**
  724. * Curl_http_should_fail() determines whether an HTTP response has gotten us
  725. * into an error state or not.
  726. *
  727. * @param conn all information about the current connection
  728. *
  729. * @retval 0 communications should continue
  730. *
  731. * @retval 1 communications should not continue
  732. */
  733. int Curl_http_should_fail(struct connectdata *conn)
  734. {
  735. struct SessionHandle *data;
  736. int httpcode;
  737. DEBUGASSERT(conn);
  738. data = conn->data;
  739. DEBUGASSERT(data);
  740. httpcode = data->req.httpcode;
  741. /*
  742. ** If we haven't been asked to fail on error,
  743. ** don't fail.
  744. */
  745. if(!data->set.http_fail_on_error)
  746. return 0;
  747. /*
  748. ** Any code < 400 is never terminal.
  749. */
  750. if(httpcode < 400)
  751. return 0;
  752. if(data->state.resume_from &&
  753. (data->set.httpreq==HTTPREQ_GET) &&
  754. (httpcode == 416)) {
  755. /* "Requested Range Not Satisfiable", just proceed and
  756. pretend this is no error */
  757. return 0;
  758. }
  759. /*
  760. ** Any code >= 400 that's not 401 or 407 is always
  761. ** a terminal error
  762. */
  763. if((httpcode != 401) &&
  764. (httpcode != 407))
  765. return 1;
  766. /*
  767. ** All we have left to deal with is 401 and 407
  768. */
  769. DEBUGASSERT((httpcode == 401) || (httpcode == 407));
  770. /*
  771. ** Examine the current authentication state to see if this
  772. ** is an error. The idea is for this function to get
  773. ** called after processing all the headers in a response
  774. ** message. So, if we've been to asked to authenticate a
  775. ** particular stage, and we've done it, we're OK. But, if
  776. ** we're already completely authenticated, it's not OK to
  777. ** get another 401 or 407.
  778. **
  779. ** It is possible for authentication to go stale such that
  780. ** the client needs to reauthenticate. Once that info is
  781. ** available, use it here.
  782. */
  783. #if 0 /* set to 1 when debugging this functionality */
  784. infof(data,"%s: authstage = %d\n",__FUNCTION__,data->state.authstage);
  785. infof(data,"%s: authwant = 0x%08x\n",__FUNCTION__,data->state.authwant);
  786. infof(data,"%s: authavail = 0x%08x\n",__FUNCTION__,data->state.authavail);
  787. infof(data,"%s: httpcode = %d\n",__FUNCTION__,k->httpcode);
  788. infof(data,"%s: authdone = %d\n",__FUNCTION__,data->state.authdone);
  789. infof(data,"%s: newurl = %s\n",__FUNCTION__,data->req.newurl ?
  790. data->req.newurl : "(null)");
  791. infof(data,"%s: authproblem = %d\n",__FUNCTION__,data->state.authproblem);
  792. #endif
  793. /*
  794. ** Either we're not authenticating, or we're supposed to
  795. ** be authenticating something else. This is an error.
  796. */
  797. if((httpcode == 401) && !conn->bits.user_passwd)
  798. return TRUE;
  799. if((httpcode == 407) && !conn->bits.proxy_user_passwd)
  800. return TRUE;
  801. return data->state.authproblem;
  802. }
  803. /*
  804. * readmoredata() is a "fread() emulation" to provide POST and/or request
  805. * data. It is used when a huge POST is to be made and the entire chunk wasn't
  806. * sent in the first send(). This function will then be called from the
  807. * transfer.c loop when more data is to be sent to the peer.
  808. *
  809. * Returns the amount of bytes it filled the buffer with.
  810. */
  811. static size_t readmoredata(char *buffer,
  812. size_t size,
  813. size_t nitems,
  814. void *userp)
  815. {
  816. struct connectdata *conn = (struct connectdata *)userp;
  817. struct HTTP *http = conn->data->state.proto.http;
  818. size_t fullsize = size * nitems;
  819. if(0 == http->postsize)
  820. /* nothing to return */
  821. return 0;
  822. /* make sure that a HTTP request is never sent away chunked! */
  823. conn->data->req.forbidchunk = (bool)(http->sending == HTTPSEND_REQUEST);
  824. if(http->postsize <= (curl_off_t)fullsize) {
  825. memcpy(buffer, http->postdata, (size_t)http->postsize);
  826. fullsize = (size_t)http->postsize;
  827. if(http->backup.postsize) {
  828. /* move backup data into focus and continue on that */
  829. http->postdata = http->backup.postdata;
  830. http->postsize = http->backup.postsize;
  831. conn->fread_func = http->backup.fread_func;
  832. conn->fread_in = http->backup.fread_in;
  833. http->sending++; /* move one step up */
  834. http->backup.postsize=0;
  835. }
  836. else
  837. http->postsize = 0;
  838. return fullsize;
  839. }
  840. memcpy(buffer, http->postdata, fullsize);
  841. http->postdata += fullsize;
  842. http->postsize -= fullsize;
  843. return fullsize;
  844. }
  845. /* ------------------------------------------------------------------------- */
  846. /*
  847. * The add_buffer series of functions are used to build one large memory chunk
  848. * from repeated function invokes. Used so that the entire HTTP request can
  849. * be sent in one go.
  850. */
  851. struct send_buffer {
  852. char *buffer;
  853. size_t size_max;
  854. size_t size_used;
  855. };
  856. typedef struct send_buffer send_buffer;
  857. static CURLcode add_custom_headers(struct connectdata *conn,
  858. send_buffer *req_buffer);
  859. static CURLcode
  860. add_buffer(send_buffer *in, const void *inptr, size_t size);
  861. /*
  862. * add_buffer_init() sets up and returns a fine buffer struct
  863. */
  864. static
  865. send_buffer *add_buffer_init(void)
  866. {
  867. send_buffer *blonk;
  868. blonk=(send_buffer *)malloc(sizeof(send_buffer));
  869. if(blonk) {
  870. memset(blonk, 0, sizeof(send_buffer));
  871. return blonk;
  872. }
  873. return NULL; /* failed, go home */
  874. }
  875. /*
  876. * add_buffer_send() sends a header buffer and frees all associated memory.
  877. * Body data may be appended to the header data if desired.
  878. *
  879. * Returns CURLcode
  880. */
  881. static
  882. CURLcode add_buffer_send(send_buffer *in,
  883. struct connectdata *conn,
  884. long *bytes_written, /* add the number of sent bytes
  885. to this counter */
  886. size_t included_body_bytes, /* how much of the buffer
  887. contains body data */
  888. int socketindex)
  889. {
  890. ssize_t amount;
  891. CURLcode res;
  892. char *ptr;
  893. size_t size;
  894. struct HTTP *http = conn->data->state.proto.http;
  895. size_t sendsize;
  896. curl_socket_t sockfd;
  897. size_t headersize;
  898. DEBUGASSERT(socketindex <= SECONDARYSOCKET);
  899. sockfd = conn->sock[socketindex];
  900. /* The looping below is required since we use non-blocking sockets, but due
  901. to the circumstances we will just loop and try again and again etc */
  902. ptr = in->buffer;
  903. size = in->size_used;
  904. headersize = size - included_body_bytes; /* the initial part that isn't body
  905. is header */
  906. DEBUGASSERT(size > included_body_bytes);
  907. #ifdef CURL_DOES_CONVERSIONS
  908. res = Curl_convert_to_network(conn->data, ptr, headersize);
  909. /* Curl_convert_to_network calls failf if unsuccessful */
  910. if(res != CURLE_OK) {
  911. /* conversion failed, free memory and return to the caller */
  912. if(in->buffer)
  913. free(in->buffer);
  914. free(in);
  915. return res;
  916. }
  917. #endif /* CURL_DOES_CONVERSIONS */
  918. if(conn->protocol & PROT_HTTPS) {
  919. /* We never send more than CURL_MAX_WRITE_SIZE bytes in one single chunk
  920. when we speak HTTPS, as if only a fraction of it is sent now, this data
  921. needs to fit into the normal read-callback buffer later on and that
  922. buffer is using this size.
  923. */
  924. sendsize= (size > CURL_MAX_WRITE_SIZE)?CURL_MAX_WRITE_SIZE:size;
  925. /* OpenSSL is very picky and we must send the SAME buffer pointer to the
  926. library when we attempt to re-send this buffer. Sending the same data
  927. is not enough, we must use the exact same address. For this reason, we
  928. must copy the data to the uploadbuffer first, since that is the buffer
  929. we will be using if this send is retried later.
  930. */
  931. memcpy(conn->data->state.uploadbuffer, ptr, sendsize);
  932. ptr = conn->data->state.uploadbuffer;
  933. }
  934. else
  935. sendsize = size;
  936. res = Curl_write(conn, sockfd, ptr, sendsize, &amount);
  937. if(CURLE_OK == res) {
  938. /*
  939. * Note that we may not send the entire chunk at once, and we have a set
  940. * number of data bytes at the end of the big buffer (out of which we may
  941. * only send away a part).
  942. */
  943. /* how much of the header that was sent */
  944. size_t headlen = (size_t)amount>headersize?headersize:(size_t)amount;
  945. size_t bodylen = amount - headlen;
  946. if(conn->data->set.verbose) {
  947. /* this data _may_ contain binary stuff */
  948. Curl_debug(conn->data, CURLINFO_HEADER_OUT, ptr, headlen, conn);
  949. if((size_t)amount > headlen) {
  950. /* there was body data sent beyond the initial header part, pass that
  951. on to the debug callback too */
  952. Curl_debug(conn->data, CURLINFO_DATA_OUT,
  953. ptr+headlen, bodylen, conn);
  954. }
  955. }
  956. if(bodylen)
  957. /* since we sent a piece of the body here, up the byte counter for it
  958. accordingly */
  959. http->writebytecount += bodylen;
  960. *bytes_written += amount;
  961. if(http) {
  962. if((size_t)amount != size) {
  963. /* The whole request could not be sent in one system call. We must
  964. queue it up and send it later when we get the chance. We must not
  965. loop here and wait until it might work again. */
  966. size -= amount;
  967. ptr = in->buffer + amount;
  968. /* backup the currently set pointers */
  969. http->backup.fread_func = conn->fread_func;
  970. http->backup.fread_in = conn->fread_in;
  971. http->backup.postdata = http->postdata;
  972. http->backup.postsize = http->postsize;
  973. /* set the new pointers for the request-sending */
  974. conn->fread_func = (curl_read_callback)readmoredata;
  975. conn->fread_in = (void *)conn;
  976. http->postdata = ptr;
  977. http->postsize = (curl_off_t)size;
  978. http->send_buffer = in;
  979. http->sending = HTTPSEND_REQUEST;
  980. return CURLE_OK;
  981. }
  982. http->sending = HTTPSEND_BODY;
  983. /* the full buffer was sent, clean up and return */
  984. }
  985. else {
  986. if((size_t)amount != size)
  987. /* We have no continue-send mechanism now, fail. This can only happen
  988. when this function is used from the CONNECT sending function. We
  989. currently (stupidly) assume that the whole request is always sent
  990. away in the first single chunk.
  991. This needs FIXing.
  992. */
  993. return CURLE_SEND_ERROR;
  994. else
  995. conn->writechannel_inuse = FALSE;
  996. }
  997. }
  998. if(in->buffer)
  999. free(in->buffer);
  1000. free(in);
  1001. return res;
  1002. }
  1003. /*
  1004. * add_bufferf() add the formatted input to the buffer.
  1005. */
  1006. static
  1007. CURLcode add_bufferf(send_buffer *in, const char *fmt, ...)
  1008. {
  1009. char *s;
  1010. va_list ap;
  1011. va_start(ap, fmt);
  1012. s = vaprintf(fmt, ap); /* this allocs a new string to append */
  1013. va_end(ap);
  1014. if(s) {
  1015. CURLcode result = add_buffer(in, s, strlen(s));
  1016. free(s);
  1017. return result;
  1018. }
  1019. /* If we failed, we cleanup the whole buffer and return error */
  1020. if(in->buffer)
  1021. free(in->buffer);
  1022. free(in);
  1023. return CURLE_OUT_OF_MEMORY;
  1024. }
  1025. /*
  1026. * add_buffer() appends a memory chunk to the existing buffer
  1027. */
  1028. static
  1029. CURLcode add_buffer(send_buffer *in, const void *inptr, size_t size)
  1030. {
  1031. char *new_rb;
  1032. size_t new_size;
  1033. if(~size < in->size_used) {
  1034. /* If resulting used size of send buffer would wrap size_t, cleanup
  1035. the whole buffer and return error. Otherwise the required buffer
  1036. size will fit into a single allocatable memory chunk */
  1037. Curl_safefree(in->buffer);
  1038. free(in);
  1039. return CURLE_OUT_OF_MEMORY;
  1040. }
  1041. if(!in->buffer ||
  1042. ((in->size_used + size) > (in->size_max - 1))) {
  1043. /* If current buffer size isn't enough to hold the result, use a
  1044. buffer size that doubles the required size. If this new size
  1045. would wrap size_t, then just use the largest possible one */
  1046. if((size > (size_t)-1/2) || (in->size_used > (size_t)-1/2) ||
  1047. (~(size*2) < (in->size_used*2)))
  1048. new_size = (size_t)-1;
  1049. else
  1050. new_size = (in->size_used+size)*2;
  1051. if(in->buffer)
  1052. /* we have a buffer, enlarge the existing one */
  1053. new_rb = (char *)realloc(in->buffer, new_size);
  1054. else
  1055. /* create a new buffer */
  1056. new_rb = (char *)malloc(new_size);
  1057. if(!new_rb) {
  1058. /* If we failed, we cleanup the whole buffer and return error */
  1059. Curl_safefree(in->buffer);
  1060. free(in);
  1061. return CURLE_OUT_OF_MEMORY;
  1062. }
  1063. in->buffer = new_rb;
  1064. in->size_max = new_size;
  1065. }
  1066. memcpy(&in->buffer[in->size_used], inptr, size);
  1067. in->size_used += size;
  1068. return CURLE_OK;
  1069. }
  1070. /* end of the add_buffer functions */
  1071. /* ------------------------------------------------------------------------- */
  1072. /*
  1073. * Curl_compareheader()
  1074. *
  1075. * Returns TRUE if 'headerline' contains the 'header' with given 'content'.
  1076. * Pass headers WITH the colon.
  1077. */
  1078. bool
  1079. Curl_compareheader(const char *headerline, /* line to check */
  1080. const char *header, /* header keyword _with_ colon */
  1081. const char *content) /* content string to find */
  1082. {
  1083. /* RFC2616, section 4.2 says: "Each header field consists of a name followed
  1084. * by a colon (":") and the field value. Field names are case-insensitive.
  1085. * The field value MAY be preceded by any amount of LWS, though a single SP
  1086. * is preferred." */
  1087. size_t hlen = strlen(header);
  1088. size_t clen;
  1089. size_t len;
  1090. const char *start;
  1091. const char *end;
  1092. if(!strnequal(headerline, header, hlen))
  1093. return FALSE; /* doesn't start with header */
  1094. /* pass the header */
  1095. start = &headerline[hlen];
  1096. /* pass all white spaces */
  1097. while(*start && ISSPACE(*start))
  1098. start++;
  1099. /* find the end of the header line */
  1100. end = strchr(start, '\r'); /* lines end with CRLF */
  1101. if(!end) {
  1102. /* in case there's a non-standard compliant line here */
  1103. end = strchr(start, '\n');
  1104. if(!end)
  1105. /* hm, there's no line ending here, use the zero byte! */
  1106. end = strchr(start, '\0');
  1107. }
  1108. len = end-start; /* length of the content part of the input line */
  1109. clen = strlen(content); /* length of the word to find */
  1110. /* find the content string in the rest of the line */
  1111. for(;len>=clen;len--, start++) {
  1112. if(strnequal(start, content, clen))
  1113. return TRUE; /* match! */
  1114. }
  1115. return FALSE; /* no match */
  1116. }
  1117. /*
  1118. * Curl_proxyCONNECT() requires that we're connected to a HTTP proxy. This
  1119. * function will issue the necessary commands to get a seamless tunnel through
  1120. * this proxy. After that, the socket can be used just as a normal socket.
  1121. *
  1122. * This badly needs to be rewritten. CONNECT should be sent and dealt with
  1123. * like any ordinary HTTP request, and not specially crafted like this. This
  1124. * function only remains here like this for now since the rewrite is a bit too
  1125. * much work to do at the moment.
  1126. *
  1127. * This function is BLOCKING which is nasty for all multi interface using apps.
  1128. */
  1129. CURLcode Curl_proxyCONNECT(struct connectdata *conn,
  1130. int sockindex,
  1131. const char *hostname,
  1132. unsigned short remote_port)
  1133. {
  1134. int subversion=0;
  1135. struct SessionHandle *data=conn->data;
  1136. struct SingleRequest *k = &data->req;
  1137. CURLcode result;
  1138. int res;
  1139. long timeout =
  1140. data->set.timeout?data->set.timeout:PROXY_TIMEOUT; /* in milliseconds */
  1141. curl_socket_t tunnelsocket = conn->sock[sockindex];
  1142. curl_off_t cl=0;
  1143. bool closeConnection = FALSE;
  1144. bool chunked_encoding = FALSE;
  1145. long check;
  1146. #define SELECT_OK 0
  1147. #define SELECT_ERROR 1
  1148. #define SELECT_TIMEOUT 2
  1149. int error = SELECT_OK;
  1150. conn->bits.proxy_connect_closed = FALSE;
  1151. do {
  1152. if(!conn->bits.tunnel_connecting) { /* BEGIN CONNECT PHASE */
  1153. char *host_port;
  1154. send_buffer *req_buffer;
  1155. infof(data, "Establish HTTP proxy tunnel to %s:%d\n",
  1156. hostname, remote_port);
  1157. if(data->req.newurl) {
  1158. /* This only happens if we've looped here due to authentication
  1159. reasons, and we don't really use the newly cloned URL here
  1160. then. Just free() it. */
  1161. free(data->req.newurl);
  1162. data->req.newurl = NULL;
  1163. }
  1164. /* initialize a dynamic send-buffer */
  1165. req_buffer = add_buffer_init();
  1166. if(!req_buffer)
  1167. return CURLE_OUT_OF_MEMORY;
  1168. host_port = aprintf("%s:%d", hostname, remote_port);
  1169. if(!host_port) {
  1170. free(req_buffer);
  1171. return CURLE_OUT_OF_MEMORY;
  1172. }
  1173. /* Setup the proxy-authorization header, if any */
  1174. result = http_output_auth(conn, (char *)"CONNECT", host_port, TRUE);
  1175. if(CURLE_OK == result) {
  1176. char *host=(char *)"";
  1177. const char *proxyconn="";
  1178. const char *useragent="";
  1179. if(!checkheaders(data, "Host:")) {
  1180. host = aprintf("Host: %s\r\n", host_port);
  1181. if(!host) {
  1182. free(req_buffer);
  1183. free(host_port);
  1184. return CURLE_OUT_OF_MEMORY;
  1185. }
  1186. }
  1187. if(!checkheaders(data, "Proxy-Connection:"))
  1188. proxyconn = "Proxy-Connection: Keep-Alive\r\n";
  1189. if(!checkheaders(data, "User-Agent:") &&
  1190. data->set.str[STRING_USERAGENT])
  1191. useragent = conn->allocptr.uagent;
  1192. /* Send the connect request to the proxy */
  1193. /* BLOCKING */
  1194. result =
  1195. add_bufferf(req_buffer,
  1196. "CONNECT %s:%d HTTP/1.0\r\n"
  1197. "%s" /* Host: */
  1198. "%s" /* Proxy-Authorization */
  1199. "%s" /* User-Agent */
  1200. "%s", /* Proxy-Connection */
  1201. hostname, remote_port,
  1202. host,
  1203. conn->allocptr.proxyuserpwd?
  1204. conn->allocptr.proxyuserpwd:"",
  1205. useragent,
  1206. proxyconn);
  1207. if(host && *host)
  1208. free(host);
  1209. if(CURLE_OK == result)
  1210. result = add_custom_headers(conn, req_buffer);
  1211. if(CURLE_OK == result)
  1212. /* CRLF terminate the request */
  1213. result = add_bufferf(req_buffer, "\r\n");
  1214. if(CURLE_OK == result) {
  1215. /* Now send off the request */
  1216. result = add_buffer_send(req_buffer, conn,
  1217. &data->info.request_size, 0, sockindex);
  1218. }
  1219. req_buffer = NULL;
  1220. if(result)
  1221. failf(data, "Failed sending CONNECT to proxy");
  1222. }
  1223. free(host_port);
  1224. Curl_safefree(req_buffer);
  1225. if(result)
  1226. return result;
  1227. conn->bits.tunnel_connecting = TRUE;
  1228. } /* END CONNECT PHASE */
  1229. /* now we've issued the CONNECT and we're waiting to hear back -
  1230. we try not to block here in multi-mode because that might be a LONG
  1231. wait if the proxy cannot connect-through to the remote host. */
  1232. /* if timeout is requested, find out how much remaining time we have */
  1233. check = timeout - /* timeout time */
  1234. Curl_tvdiff(Curl_tvnow(), conn->now); /* spent time */
  1235. if(check <=0 ) {
  1236. failf(data, "Proxy CONNECT aborted due to timeout");
  1237. error = SELECT_TIMEOUT; /* already too little time */
  1238. break;
  1239. }
  1240. /* if we're in multi-mode and we would block, return instead for a retry */
  1241. if(Curl_if_multi == data->state.used_interface) {
  1242. if(0 == Curl_socket_ready(tunnelsocket, CURL_SOCKET_BAD, 0))
  1243. /* return so we'll be called again polling-style */
  1244. return CURLE_OK;
  1245. else {
  1246. DEBUGF(infof(data,
  1247. "Multi mode finished polling for response from "
  1248. "proxy CONNECT."));
  1249. }
  1250. }
  1251. else {
  1252. DEBUGF(infof(data, "Easy mode waiting for response from proxy CONNECT."));
  1253. }
  1254. /* at this point, either:
  1255. 1) we're in easy-mode and so it's okay to block waiting for a CONNECT
  1256. response
  1257. 2) we're in multi-mode and we didn't block - it's either an error or we
  1258. now have some data waiting.
  1259. In any case, the tunnel_connecting phase is over. */
  1260. conn->bits.tunnel_connecting = FALSE;
  1261. { /* BEGIN NEGOTIATION PHASE */
  1262. size_t nread; /* total size read */
  1263. int perline; /* count bytes per line */
  1264. int keepon=TRUE;
  1265. ssize_t gotbytes;
  1266. char *ptr;
  1267. char *line_start;
  1268. ptr=data->state.buffer;
  1269. line_start = ptr;
  1270. nread=0;
  1271. perline=0;
  1272. keepon=TRUE;
  1273. while((nread<BUFSIZE) && (keepon && !error)) {
  1274. /* if timeout is requested, find out how much remaining time we have */
  1275. check = timeout - /* timeout time */
  1276. Curl_tvdiff(Curl_tvnow(), conn->now); /* spent time */
  1277. if(check <= 0) {
  1278. failf(data, "Proxy CONNECT aborted due to timeout");
  1279. error = SELECT_TIMEOUT; /* already too little time */
  1280. break;
  1281. }
  1282. /* loop every second at least, less if the timeout is near */
  1283. switch (Curl_socket_ready(tunnelsocket, CURL_SOCKET_BAD,
  1284. check<1000L?(int)check:1000)) {
  1285. case -1: /* select() error, stop reading */
  1286. error = SELECT_ERROR;
  1287. failf(data, "Proxy CONNECT aborted due to select/poll error");
  1288. break;
  1289. case 0: /* timeout */
  1290. break;
  1291. default:
  1292. DEBUGASSERT(ptr+BUFSIZE-nread <= data->state.buffer+BUFSIZE+1);
  1293. res = Curl_read(conn, tunnelsocket, ptr, BUFSIZE-nread, &gotbytes);
  1294. if(res< 0)
  1295. /* EWOULDBLOCK */
  1296. continue; /* go loop yourself */
  1297. else if(res)
  1298. keepon = FALSE;
  1299. else if(gotbytes <= 0) {
  1300. keepon = FALSE;
  1301. if(data->set.proxyauth && data->state.authproxy.avail) {
  1302. /* proxy auth was requested and there was proxy auth available,
  1303. then deem this as "mere" proxy disconnect */
  1304. conn->bits.proxy_connect_closed = TRUE;
  1305. }
  1306. else {
  1307. error = SELECT_ERROR;
  1308. failf(data, "Proxy CONNECT aborted");
  1309. }
  1310. }
  1311. else {
  1312. /*
  1313. * We got a whole chunk of data, which can be anything from one
  1314. * byte to a set of lines and possibly just a piece of the last
  1315. * line.
  1316. */
  1317. int i;
  1318. nread += gotbytes;
  1319. if(keepon > TRUE) {
  1320. /* This means we are currently ignoring a response-body */
  1321. nread = 0; /* make next read start over in the read buffer */
  1322. ptr=data->state.buffer;
  1323. if(cl) {
  1324. /* A Content-Length based body: simply count down the counter
  1325. and make sure to break out of the loop when we're done! */
  1326. cl -= gotbytes;
  1327. if(cl<=0) {
  1328. keepon = FALSE;
  1329. break;
  1330. }
  1331. }
  1332. else {
  1333. /* chunked-encoded body, so we need to do the chunked dance
  1334. properly to know when the end of the body is reached */
  1335. CHUNKcode r;
  1336. ssize_t tookcareof=0;
  1337. /* now parse the chunked piece of data so that we can
  1338. properly tell when the stream ends */
  1339. r = Curl_httpchunk_read(conn, ptr, gotbytes, &tookcareof);
  1340. if(r == CHUNKE_STOP) {
  1341. /* we're done reading chunks! */
  1342. infof(data, "chunk reading DONE\n");
  1343. keepon = FALSE;
  1344. }
  1345. else
  1346. infof(data, "Read %d bytes of chunk, continue\n",
  1347. tookcareof);
  1348. }
  1349. }
  1350. else
  1351. for(i = 0; i < gotbytes; ptr++, i++) {
  1352. perline++; /* amount of bytes in this line so far */
  1353. if(*ptr=='\n') {
  1354. char letter;
  1355. int writetype;
  1356. /* output debug if that is requested */
  1357. if(data->set.verbose)
  1358. Curl_debug(data, CURLINFO_HEADER_IN,
  1359. line_start, (size_t)perline, conn);
  1360. /* send the header to the callback */
  1361. writetype = CLIENTWRITE_HEADER;
  1362. if(data->set.include_header)
  1363. writetype |= CLIENTWRITE_BODY;
  1364. result = Curl_client_write(conn, writetype, line_start,
  1365. perline);
  1366. if(result)
  1367. return result;
  1368. /* Newlines are CRLF, so the CR is ignored as the line isn't
  1369. really terminated until the LF comes. Treat a following CR
  1370. as end-of-headers as well.*/
  1371. if(('\r' == line_start[0]) ||
  1372. ('\n' == line_start[0])) {
  1373. /* end of response-headers from the proxy */
  1374. nread = 0; /* make next read start over in the read
  1375. buffer */
  1376. ptr=data->state.buffer;
  1377. if((407 == k->httpcode) && !data->state.authproblem) {
  1378. /* If we get a 407 response code with content length
  1379. when we have no auth problem, we must ignore the
  1380. whole response-body */
  1381. keepon = 2;
  1382. if(cl) {
  1383. infof(data, "Ignore %" FORMAT_OFF_T
  1384. " bytes of response-body\n", cl);
  1385. /* remove the remaining chunk of what we already
  1386. read */
  1387. cl -= (gotbytes - i);
  1388. if(cl<=0)
  1389. /* if the whole thing was already read, we are done!
  1390. */
  1391. keepon=FALSE;
  1392. }
  1393. else if(chunked_encoding) {
  1394. CHUNKcode r;
  1395. /* We set ignorebody true here since the chunked
  1396. decoder function will acknowledge that. Pay
  1397. attention so that this is cleared again when this
  1398. function returns! */
  1399. k->ignorebody = TRUE;
  1400. infof(data, "%d bytes of chunk left\n", gotbytes-i);
  1401. if(line_start[1] == '\n') {
  1402. /* this can only be a LF if the letter at index 0
  1403. was a CR */
  1404. line_start++;
  1405. i++;
  1406. }
  1407. /* now parse the chunked piece of data so that we can
  1408. properly tell when the stream ends */
  1409. r = Curl_httpchunk_read(conn, line_start+1,
  1410. gotbytes -i, &gotbytes);
  1411. if(r == CHUNKE_STOP) {
  1412. /* we're done reading chunks! */
  1413. infof(data, "chunk reading DONE\n");
  1414. keepon = FALSE;
  1415. }
  1416. else
  1417. infof(data, "Read %d bytes of chunk, continue\n",
  1418. gotbytes);
  1419. }
  1420. else {
  1421. /* without content-length or chunked encoding, we
  1422. can't keep the connection alive since the close is
  1423. the end signal so we bail out at once instead */
  1424. keepon=FALSE;
  1425. }
  1426. }
  1427. else
  1428. keepon = FALSE;
  1429. break; /* breaks out of for-loop, not switch() */
  1430. }
  1431. /* keep a backup of the position we are about to blank */
  1432. letter = line_start[perline];
  1433. line_start[perline]=0; /* zero terminate the buffer */
  1434. if((checkprefix("WWW-Authenticate:", line_start) &&
  1435. (401 == k->httpcode)) ||
  1436. (checkprefix("Proxy-authenticate:", line_start) &&
  1437. (407 == k->httpcode))) {
  1438. result = Curl_http_input_auth(conn, k->httpcode,
  1439. line_start);
  1440. if(result)
  1441. return result;
  1442. }
  1443. else if(checkprefix("Content-Length:", line_start)) {
  1444. cl = curlx_strtoofft(line_start + strlen("Content-Length:"),
  1445. NULL, 10);
  1446. }
  1447. else if(Curl_compareheader(line_start,
  1448. "Connection:", "close"))
  1449. closeConnection = TRUE;
  1450. else if(Curl_compareheader(line_start,
  1451. "Transfer-Encoding:", "chunked")) {
  1452. infof(data, "CONNECT responded chunked\n");
  1453. chunked_encoding = TRUE;
  1454. /* init our chunky engine */
  1455. Curl_httpchunk_init(conn);
  1456. }
  1457. else if(Curl_compareheader(line_start,
  1458. "Proxy-Connection:", "close"))
  1459. closeConnection = TRUE;
  1460. else if(2 == sscanf(line_start, "HTTP/1.%d %d",
  1461. &subversion,
  1462. &k->httpcode)) {
  1463. /* store the HTTP code from the proxy */
  1464. data->info.httpproxycode = k->httpcode;
  1465. }
  1466. /* put back the letter we blanked out before */
  1467. line_start[perline]= letter;
  1468. perline=0; /* line starts over here */
  1469. line_start = ptr+1; /* this skips the zero byte we wrote */
  1470. }
  1471. }
  1472. }
  1473. break;
  1474. } /* switch */
  1475. if(Curl_pgrsUpdate(conn))
  1476. return CURLE_ABORTED_BY_CALLBACK;
  1477. } /* while there's buffer left and loop is requested */
  1478. if(error)
  1479. return CURLE_RECV_ERROR;
  1480. if(data->info.httpproxycode != 200) {
  1481. /* Deal with the possibly already received authenticate
  1482. headers. 'newurl' is set to a new URL if we must loop. */
  1483. result = Curl_http_auth_act(conn);
  1484. if(result)
  1485. return result;
  1486. if(conn->bits.close)
  1487. /* the connection has been marked for closure, most likely in the
  1488. Curl_http_auth_act() function and thus we can kill it at once
  1489. below
  1490. */
  1491. closeConnection = TRUE;
  1492. }
  1493. if(closeConnection && data->req.newurl) {
  1494. /* Connection closed by server. Don't use it anymore */
  1495. sclose(conn->sock[sockindex]);
  1496. conn->sock[sockindex] = CURL_SOCKET_BAD;
  1497. break;
  1498. }
  1499. } /* END NEGOTIATION PHASE */
  1500. } while(data->req.newurl);
  1501. if(200 != data->req.httpcode) {
  1502. failf(data, "Received HTTP code %d from proxy after CONNECT",
  1503. data->req.httpcode);
  1504. if(closeConnection && data->req.newurl)
  1505. conn->bits.proxy_connect_closed = TRUE;
  1506. return CURLE_RECV_ERROR;
  1507. }
  1508. /* If a proxy-authorization header was used for the proxy, then we should
  1509. make sure that it isn't accidentally used for the document request
  1510. after we've connected. So let's free and clear it here. */
  1511. Curl_safefree(conn->allocptr.proxyuserpwd);
  1512. conn->allocptr.proxyuserpwd = NULL;
  1513. data->state.authproxy.done = TRUE;
  1514. infof (data, "Proxy replied OK to CONNECT request\n");
  1515. data->req.ignorebody = FALSE; /* put it (back) to non-ignore state */
  1516. return CURLE_OK;
  1517. }
  1518. /*
  1519. * Curl_http_connect() performs HTTP stuff to do at connect-time, called from
  1520. * the generic Curl_connect().
  1521. */
  1522. CURLcode Curl_http_connect(struct connectdata *conn, bool *done)
  1523. {
  1524. struct SessionHandle *data;
  1525. CURLcode result;
  1526. data=conn->data;
  1527. /* We default to persistent connections. We set this already in this connect
  1528. function to make the re-use checks properly be able to check this bit. */
  1529. conn->bits.close = FALSE;
  1530. /* If we are not using a proxy and we want a secure connection, perform SSL
  1531. * initialization & connection now. If using a proxy with https, then we
  1532. * must tell the proxy to CONNECT to the host we want to talk to. Only
  1533. * after the connect has occurred, can we start talking SSL
  1534. */
  1535. if(conn->bits.tunnel_proxy && conn->bits.httpproxy) {
  1536. /* either SSL over proxy, or explicitly asked for */
  1537. result = Curl_proxyCONNECT(conn, FIRSTSOCKET,
  1538. conn->host.name,
  1539. conn->remote_port);
  1540. if(CURLE_OK != result)
  1541. return result;
  1542. }
  1543. if(conn->bits.tunnel_connecting) {
  1544. /* nothing else to do except wait right now - we're not done here. */
  1545. return CURLE_OK;
  1546. }
  1547. if(!data->state.this_is_a_follow) {
  1548. /* this is not a followed location, get the original host name */
  1549. if(data->state.first_host)
  1550. /* Free to avoid leaking memory on multiple requests*/
  1551. free(data->state.first_host);
  1552. data->state.first_host = strdup(conn->host.name);
  1553. if(!data->state.first_host)
  1554. return CURLE_OUT_OF_MEMORY;
  1555. }
  1556. if(conn->protocol & PROT_HTTPS) {
  1557. /* perform SSL initialization */
  1558. if(data->state.used_interface == Curl_if_multi) {
  1559. result = https_connecting(conn, done);
  1560. if(result)
  1561. return result;
  1562. }
  1563. else {
  1564. /* BLOCKING */
  1565. result = Curl_ssl_connect(conn, FIRSTSOCKET);
  1566. if(result)
  1567. return result;
  1568. *done = TRUE;
  1569. }
  1570. }
  1571. else {
  1572. *done = TRUE;
  1573. }
  1574. return CURLE_OK;
  1575. }
  1576. /* this returns the socket to wait for in the DO and DOING state for the multi
  1577. interface and then we're always _sending_ a request and thus we wait for
  1578. the single socket to become writable only */
  1579. static int http_getsock_do(struct connectdata *conn,
  1580. curl_socket_t *socks,
  1581. int numsocks)
  1582. {
  1583. /* write mode */
  1584. (void)numsocks; /* unused, we trust it to be at least 1 */
  1585. socks[0] = conn->sock[FIRSTSOCKET];
  1586. return GETSOCK_WRITESOCK(0);
  1587. }
  1588. static CURLcode https_connecting(struct connectdata *conn, bool *done)
  1589. {
  1590. CURLcode result;
  1591. DEBUGASSERT((conn) && (conn->protocol & PROT_HTTPS));
  1592. /* perform SSL initialization for this socket */
  1593. result = Curl_ssl_connect_nonblocking(conn, FIRSTSOCKET, done);
  1594. if(result) {
  1595. conn->bits.close = TRUE; /* a failed connection is marked for closure
  1596. to prevent (bad) re-use or similar */
  1597. return result;
  1598. }
  1599. return CURLE_OK;
  1600. }
  1601. #ifdef USE_SSLEAY
  1602. /* This function is OpenSSL-specific. It should be made to query the generic
  1603. SSL layer instead. */
  1604. static int https_getsock(struct connectdata *conn,
  1605. curl_socket_t *socks,
  1606. int numsocks)
  1607. {
  1608. if(conn->protocol & PROT_HTTPS) {
  1609. struct ssl_connect_data *connssl = &conn->ssl[FIRSTSOCKET];
  1610. if(!numsocks)
  1611. return GETSOCK_BLANK;
  1612. if(connssl->connecting_state == ssl_connect_2_writing) {
  1613. /* write mode */
  1614. socks[0] = conn->sock[FIRSTSOCKET];
  1615. return GETSOCK_WRITESOCK(0);
  1616. }
  1617. else if(connssl->connecting_state == ssl_connect_2_reading) {
  1618. /* read mode */
  1619. socks[0] = conn->sock[FIRSTSOCKET];
  1620. return GETSOCK_READSOCK(0);
  1621. }
  1622. }
  1623. return CURLE_OK;
  1624. }
  1625. #else
  1626. #ifdef USE_GNUTLS
  1627. static int https_getsock(struct connectdata *conn,
  1628. curl_socket_t *socks,
  1629. int numsocks)
  1630. {
  1631. (void)conn;
  1632. (void)socks;
  1633. (void)numsocks;
  1634. return GETSOCK_BLANK;
  1635. }
  1636. #else
  1637. #ifdef USE_NSS
  1638. static int https_getsock(struct connectdata *conn,
  1639. curl_socket_t *socks,
  1640. int numsocks)
  1641. {
  1642. (void)conn;
  1643. (void)socks;
  1644. (void)numsocks;
  1645. return GETSOCK_BLANK;
  1646. }
  1647. #else
  1648. #ifdef USE_QSOSSL
  1649. static int https_getsock(struct connectdata *conn,
  1650. curl_socket_t *socks,
  1651. int numsocks)
  1652. {
  1653. (void)conn;
  1654. (void)socks;
  1655. (void)numsocks;
  1656. return GETSOCK_BLANK;
  1657. }
  1658. #endif
  1659. #endif
  1660. #endif
  1661. #endif
  1662. /*
  1663. * Curl_http_done() gets called from Curl_done() after a single HTTP request
  1664. * has been performed.
  1665. */
  1666. CURLcode Curl_http_done(struct connectdata *conn,
  1667. CURLcode status, bool premature)
  1668. {
  1669. struct SessionHandle *data = conn->data;
  1670. struct HTTP *http =data->state.proto.http;
  1671. (void)premature; /* not used */
  1672. /* set the proper values (possibly modified on POST) */
  1673. conn->fread_func = data->set.fread_func; /* restore */
  1674. conn->fread_in = data->set.in; /* restore */
  1675. conn->seek_func = data->set.seek_func; /* restore */
  1676. conn->seek_client = data->set.seek_client; /* restore */
  1677. if(http == NULL)
  1678. return CURLE_OK;
  1679. if(http->send_buffer) {
  1680. send_buffer *buff = http->send_buffer;
  1681. free(buff->buffer);
  1682. free(buff);
  1683. http->send_buffer = NULL; /* clear the pointer */
  1684. }
  1685. if(HTTPREQ_POST_FORM == data->set.httpreq) {
  1686. data->req.bytecount = http->readbytecount + http->writebytecount;
  1687. Curl_formclean(&http->sendit); /* Now free that whole lot */
  1688. if(http->form.fp) {
  1689. /* a file being uploaded was left opened, close it! */
  1690. fclose(http->form.fp);
  1691. http->form.fp = NULL;
  1692. }
  1693. }
  1694. else if(HTTPREQ_PUT == data->set.httpreq)
  1695. data->req.bytecount = http->readbytecount + http->writebytecount;
  1696. if(status != CURLE_OK)
  1697. return (status);
  1698. if(!premature && /* this check is pointless when DONE is called before the
  1699. entire operation is complete */
  1700. !conn->bits.retry &&
  1701. ((http->readbytecount +
  1702. data->req.headerbytecount -
  1703. data->req.deductheadercount)) <= 0) {
  1704. /* If this connection isn't simply closed to be retried, AND nothing was
  1705. read from the HTTP server (that counts), this can't be right so we
  1706. return an error here */
  1707. failf(data, "Empty reply from server");
  1708. return CURLE_GOT_NOTHING;
  1709. }
  1710. return CURLE_OK;
  1711. }
  1712. /* check and possibly add an Expect: header */
  1713. static CURLcode expect100(struct SessionHandle *data,
  1714. send_buffer *req_buffer)
  1715. {
  1716. CURLcode result = CURLE_OK;
  1717. data->state.expect100header = FALSE; /* default to false unless it is set
  1718. to TRUE below */
  1719. if((data->set.httpversion != CURL_HTTP_VERSION_1_0) &&
  1720. !checkheaders(data, "Expect:")) {
  1721. /* if not doing HTTP 1.0 or disabled explicitly, we add a Expect:
  1722. 100-continue to the headers which actually speeds up post
  1723. operations (as there is one packet coming back from the web
  1724. server) */
  1725. result = add_bufferf(req_buffer,
  1726. "Expect: 100-continue\r\n");
  1727. if(result == CURLE_OK)
  1728. data->state.expect100header = TRUE;
  1729. }
  1730. return result;
  1731. }
  1732. static CURLcode add_custom_headers(struct connectdata *conn,
  1733. send_buffer *req_buffer)
  1734. {
  1735. char *ptr;
  1736. struct curl_slist *headers=conn->data->set.headers;
  1737. while(headers) {
  1738. ptr = strchr(headers->data, ':');
  1739. if(ptr) {
  1740. /* we require a colon for this to be a true header */
  1741. ptr++; /* pass the colon */
  1742. while(*ptr && ISSPACE(*ptr))
  1743. ptr++;
  1744. if(*ptr) {
  1745. /* only send this if the contents was non-blank */
  1746. if(conn->allocptr.host &&
  1747. /* a Host: header was sent already, don't pass on any custom Host:
  1748. header as that will produce *two* in the same request! */
  1749. curl_strnequal("Host:", headers->data, 5))
  1750. ;
  1751. else if(conn->data->set.httpreq == HTTPREQ_POST_FORM &&
  1752. /* this header (extended by formdata.c) is sent later */
  1753. curl_strnequal("Content-Type:", headers->data,
  1754. strlen("Content-Type:")))
  1755. ;
  1756. else {
  1757. CURLcode result = add_bufferf(req_buffer, "%s\r\n", headers->data);
  1758. if(result)
  1759. return result;
  1760. }
  1761. }
  1762. }
  1763. headers = headers->next;
  1764. }
  1765. return CURLE_OK;
  1766. }
  1767. /*
  1768. * Curl_http() gets called from the generic Curl_do() function when a HTTP
  1769. * request is to be performed. This creates and sends a properly constructed
  1770. * HTTP request.
  1771. */
  1772. CURLcode Curl_http(struct connectdata *conn, bool *done)
  1773. {
  1774. struct SessionHandle *data=conn->data;
  1775. char *buf = data->state.buffer; /* this is a short cut to the buffer */
  1776. CURLcode result=CURLE_OK;
  1777. struct HTTP *http;
  1778. char *ppath = data->state.path;
  1779. char ftp_typecode[sizeof(";type=?")] = "";
  1780. char *host = conn->host.name;
  1781. const char *te = ""; /* transfer-encoding */
  1782. char *ptr;
  1783. char *request;
  1784. Curl_HttpReq httpreq = data->set.httpreq;
  1785. char *addcookies = NULL;
  1786. curl_off_t included_body = 0;
  1787. const char *httpstring;
  1788. send_buffer *req_buffer;
  1789. curl_off_t postsize; /* off_t type to be able to hold a large file size */
  1790. /* Always consider the DO phase done after this function call, even if there
  1791. may be parts of the request that is not yet sent, since we can deal with
  1792. the rest of the request in the PERFORM phase. */
  1793. *done = TRUE;
  1794. /* If there already is a protocol-specific struct allocated for this
  1795. sessionhandle, deal with it */
  1796. Curl_reset_reqproto(conn);
  1797. if(!data->state.proto.http) {
  1798. /* Only allocate this struct if we don't already have it! */
  1799. http = (struct HTTP *)calloc(sizeof(struct HTTP), 1);
  1800. if(!http)
  1801. return CURLE_OUT_OF_MEMORY;
  1802. data->state.proto.http = http;
  1803. }
  1804. else
  1805. http = data->state.proto.http;
  1806. if( (conn->protocol&(PROT_HTTP|PROT_FTP)) &&
  1807. data->set.upload) {
  1808. httpreq = HTTPREQ_PUT;
  1809. }
  1810. /* Now set the 'request' pointer to the proper request string */
  1811. if(data->set.str[STRING_CUSTOMREQUEST])
  1812. request = data->set.str[STRING_CUSTOMREQUEST];
  1813. else {
  1814. if(data->set.opt_no_body)
  1815. request = (char *)"HEAD";
  1816. else {
  1817. DEBUGASSERT((httpreq > HTTPREQ_NONE) && (httpreq < HTTPREQ_LAST));
  1818. switch(httpreq) {
  1819. case HTTPREQ_POST:
  1820. case HTTPREQ_POST_FORM:
  1821. request = (char *)"POST";
  1822. break;
  1823. case HTTPREQ_PUT:
  1824. request = (char *)"PUT";
  1825. break;
  1826. default: /* this should never happen */
  1827. case HTTPREQ_GET:
  1828. request = (char *)"GET";
  1829. break;
  1830. case HTTPREQ_HEAD:
  1831. request = (char *)"HEAD";
  1832. break;
  1833. }
  1834. }
  1835. }
  1836. /* The User-Agent string might have been allocated in url.c already, because
  1837. it might have been used in the proxy connect, but if we have got a header
  1838. with the user-agent string specified, we erase the previously made string
  1839. here. */
  1840. if(checkheaders(data, "User-Agent:") && conn->allocptr.uagent) {
  1841. free(conn->allocptr.uagent);
  1842. conn->allocptr.uagent=NULL;
  1843. }
  1844. /* setup the authentication headers */
  1845. result = http_output_auth(conn, request, ppath, FALSE);
  1846. if(result)
  1847. return result;
  1848. if((data->state.authhost.multi || data->state.authproxy.multi) &&
  1849. (httpreq != HTTPREQ_GET) &&
  1850. (httpreq != HTTPREQ_HEAD)) {
  1851. /* Auth is required and we are not authenticated yet. Make a PUT or POST
  1852. with content-length zero as a "probe". */
  1853. conn->bits.authneg = TRUE;
  1854. }
  1855. else
  1856. conn->bits.authneg = FALSE;
  1857. Curl_safefree(conn->allocptr.ref);
  1858. if(data->change.referer && !checkheaders(data, "Referer:"))
  1859. conn->allocptr.ref = aprintf("Referer: %s\r\n", data->change.referer);
  1860. else
  1861. conn->allocptr.ref = NULL;
  1862. if(data->set.str[STRING_COOKIE] && !checkheaders(data, "Cookie:"))
  1863. addcookies = data->set.str[STRING_COOKIE];
  1864. if(!checkheaders(data, "Accept-Encoding:") &&
  1865. data->set.str[STRING_ENCODING]) {
  1866. Curl_safefree(conn->allocptr.accept_encoding);
  1867. conn->allocptr.accept_encoding =
  1868. aprintf("Accept-Encoding: %s\r\n", data->set.str[STRING_ENCODING]);
  1869. if(!conn->allocptr.accept_encoding)
  1870. return CURLE_OUT_OF_MEMORY;
  1871. }
  1872. ptr = checkheaders(data, "Transfer-Encoding:");
  1873. if(ptr) {
  1874. /* Some kind of TE is requested, check if 'chunked' is chosen */
  1875. data->req.upload_chunky =
  1876. Curl_compareheader(ptr, "Transfer-Encoding:", "chunked");
  1877. }
  1878. else {
  1879. if((conn->protocol&PROT_HTTP) &&
  1880. data->set.upload &&
  1881. (data->set.infilesize == -1) &&
  1882. (data->set.httpversion != CURL_HTTP_VERSION_1_0)) {
  1883. /* HTTP, upload, unknown file size and not HTTP 1.0 */
  1884. data->req.upload_chunky = TRUE;
  1885. }
  1886. else {
  1887. /* else, no chunky upload */
  1888. data->req.upload_chunky = FALSE;
  1889. }
  1890. if(data->req.upload_chunky)
  1891. te = "Transfer-Encoding: chunked\r\n";
  1892. }
  1893. Curl_safefree(conn->allocptr.host);
  1894. ptr = checkheaders(data, "Host:");
  1895. if(ptr && (!data->state.this_is_a_follow ||
  1896. curl_strequal(data->state.first_host, conn->host.name))) {
  1897. #if !defined(CURL_DISABLE_COOKIES)
  1898. /* If we have a given custom Host: header, we extract the host name in
  1899. order to possibly use it for cookie reasons later on. We only allow the
  1900. custom Host: header if this is NOT a redirect, as setting Host: in the
  1901. redirected request is being out on thin ice. Except if the host name
  1902. is the same as the first one! */
  1903. char *cookiehost = Curl_copy_header_value(ptr);
  1904. if (!cookiehost)
  1905. return CURLE_OUT_OF_MEMORY;
  1906. if (!*cookiehost)
  1907. /* ignore empty data */
  1908. free(cookiehost);
  1909. else {
  1910. char *colon = strchr(cookiehost, ':');
  1911. if (colon)
  1912. *colon = 0; /* The host must not include an embedded port number */
  1913. Curl_safefree(conn->allocptr.cookiehost);
  1914. conn->allocptr.cookiehost = cookiehost;
  1915. }
  1916. #endif
  1917. conn->allocptr.host = NULL;
  1918. }
  1919. else {
  1920. /* When building Host: headers, we must put the host name within
  1921. [brackets] if the host name is a plain IPv6-address. RFC2732-style. */
  1922. if(((conn->protocol&PROT_HTTPS) && (conn->remote_port == PORT_HTTPS)) ||
  1923. (!(conn->protocol&PROT_HTTPS) && (conn->remote_port == PORT_HTTP)) )
  1924. /* if(HTTPS on port 443) OR (non-HTTPS on port 80) then don't include
  1925. the port number in the host string */
  1926. conn->allocptr.host = aprintf("Host: %s%s%s\r\n",
  1927. conn->bits.ipv6_ip?"[":"",
  1928. host,
  1929. conn->bits.ipv6_ip?"]":"");
  1930. else
  1931. conn->allocptr.host = aprintf("Host: %s%s%s:%d\r\n",
  1932. conn->bits.ipv6_ip?"[":"",
  1933. host,
  1934. conn->bits.ipv6_ip?"]":"",
  1935. conn->remote_port);
  1936. if(!conn->allocptr.host)
  1937. /* without Host: we can't make a nice request */
  1938. return CURLE_OUT_OF_MEMORY;
  1939. }
  1940. if(conn->bits.httpproxy && !conn->bits.tunnel_proxy) {
  1941. /* Using a proxy but does not tunnel through it */
  1942. /* The path sent to the proxy is in fact the entire URL. But if the remote
  1943. host is a IDN-name, we must make sure that the request we produce only
  1944. uses the encoded host name! */
  1945. if(conn->host.dispname != conn->host.name) {
  1946. char *url = data->change.url;
  1947. ptr = strstr(url, conn->host.dispname);
  1948. if(ptr) {
  1949. /* This is where the display name starts in the URL, now replace this
  1950. part with the encoded name. TODO: This method of replacing the host
  1951. name is rather crude as I believe there's a slight risk that the
  1952. user has entered a user name or password that contain the host name
  1953. string. */
  1954. size_t currlen = strlen(conn->host.dispname);
  1955. size_t newlen = strlen(conn->host.name);
  1956. size_t urllen = strlen(url);
  1957. char *newurl;
  1958. newurl = malloc(urllen + newlen - currlen + 1);
  1959. if(newurl) {
  1960. /* copy the part before the host name */
  1961. memcpy(newurl, url, ptr - url);
  1962. /* append the new host name instead of the old */
  1963. memcpy(newurl + (ptr - url), conn->host.name, newlen);
  1964. /* append the piece after the host name */
  1965. memcpy(newurl + newlen + (ptr - url),
  1966. ptr + currlen, /* copy the trailing zero byte too */
  1967. urllen - (ptr-url) - currlen + 1);
  1968. if(data->change.url_alloc)
  1969. free(data->change.url);
  1970. data->change.url = newurl;
  1971. data->change.url_alloc = TRUE;
  1972. }
  1973. else
  1974. return CURLE_OUT_OF_MEMORY;
  1975. }
  1976. }
  1977. ppath = data->change.url;
  1978. if (data->set.proxy_transfer_mode) {
  1979. /* when doing ftp, append ;type=<a|i> if not present */
  1980. if(checkprefix("ftp://", ppath) || checkprefix("ftps://", ppath)) {
  1981. char *p = strstr(ppath, ";type=");
  1982. if(p && p[6] && p[7] == 0) {
  1983. switch (toupper((int)((unsigned char)p[6]))) {
  1984. case 'A':
  1985. case 'D':
  1986. case 'I':
  1987. break;
  1988. default:
  1989. p = NULL;
  1990. }
  1991. }
  1992. if(!p)
  1993. snprintf(ftp_typecode, sizeof(ftp_typecode), ";type=%c",
  1994. data->set.prefer_ascii ? 'a' : 'i');
  1995. }
  1996. }
  1997. }
  1998. if(HTTPREQ_POST_FORM == httpreq) {
  1999. /* we must build the whole darned post sequence first, so that we have
  2000. a size of the whole shebang before we start to send it */
  2001. result = Curl_getFormData(&http->sendit, data->set.httppost,
  2002. checkheaders(data, "Content-Type:"),
  2003. &http->postsize);
  2004. if(CURLE_OK != result) {
  2005. /* Curl_getFormData() doesn't use failf() */
  2006. failf(data, "failed creating formpost data");
  2007. return result;
  2008. }
  2009. }
  2010. http->p_pragma =
  2011. (!checkheaders(data, "Pragma:") &&
  2012. (conn->bits.httpproxy && !conn->bits.tunnel_proxy) )?
  2013. "Pragma: no-cache\r\n":NULL;
  2014. http->p_accept = checkheaders(data, "Accept:")?NULL:"Accept: */*\r\n";
  2015. if(( (HTTPREQ_POST == httpreq) ||
  2016. (HTTPREQ_POST_FORM == httpreq) ||
  2017. (HTTPREQ_PUT == httpreq) ) &&
  2018. data->state.resume_from) {
  2019. /**********************************************************************
  2020. * Resuming upload in HTTP means that we PUT or POST and that we have
  2021. * got a resume_from value set. The resume value has already created
  2022. * a Range: header that will be passed along. We need to "fast forward"
  2023. * the file the given number of bytes and decrease the assume upload
  2024. * file size before we continue this venture in the dark lands of HTTP.
  2025. *********************************************************************/
  2026. if(data->state.resume_from < 0 ) {
  2027. /*
  2028. * This is meant to get the size of the present remote-file by itself.
  2029. * We don't support this now. Bail out!
  2030. */
  2031. data->state.resume_from = 0;
  2032. }
  2033. if(data->state.resume_from && !data->state.this_is_a_follow) {
  2034. /* do we still game? */
  2035. /* Now, let's read off the proper amount of bytes from the
  2036. input. */
  2037. if(conn->seek_func) {
  2038. curl_off_t readthisamountnow = data->state.resume_from;
  2039. if(conn->seek_func(conn->seek_client,
  2040. readthisamountnow, SEEK_SET) != 0) {
  2041. failf(data, "Could not seek stream");
  2042. return CURLE_READ_ERROR;
  2043. }
  2044. }
  2045. else {
  2046. curl_off_t passed=0;
  2047. do {
  2048. size_t readthisamountnow = (size_t)(data->state.resume_from - passed);
  2049. size_t actuallyread;
  2050. if(readthisamountnow > BUFSIZE)
  2051. readthisamountnow = BUFSIZE;
  2052. actuallyread = data->set.fread_func(data->state.buffer, 1,
  2053. (size_t)readthisamountnow,
  2054. data->set.in);
  2055. passed += actuallyread;
  2056. if(actuallyread != readthisamountnow) {
  2057. failf(data, "Could only read %" FORMAT_OFF_T
  2058. " bytes from the input",
  2059. passed);
  2060. return CURLE_READ_ERROR;
  2061. }
  2062. } while(passed != data->state.resume_from); /* loop until done */
  2063. }
  2064. /* now, decrease the size of the read */
  2065. if(data->set.infilesize>0) {
  2066. data->set.infilesize -= data->state.resume_from;
  2067. if(data->set.infilesize <= 0) {
  2068. failf(data, "File already completely uploaded");
  2069. return CURLE_PARTIAL_FILE;
  2070. }
  2071. }
  2072. /* we've passed, proceed as normal */
  2073. }
  2074. }
  2075. if(data->state.use_range) {
  2076. /*
  2077. * A range is selected. We use different headers whether we're downloading
  2078. * or uploading and we always let customized headers override our internal
  2079. * ones if any such are specified.
  2080. */
  2081. if(((httpreq == HTTPREQ_GET) || (httpreq == HTTPREQ_HEAD)) &&
  2082. !checkheaders(data, "Range:")) {
  2083. /* if a line like this was already allocated, free the previous one */
  2084. if(conn->allocptr.rangeline)
  2085. free(conn->allocptr.rangeline);
  2086. conn->allocptr.rangeline = aprintf("Range: bytes=%s\r\n",
  2087. data->state.range);
  2088. }
  2089. else if((httpreq != HTTPREQ_GET) &&
  2090. !checkheaders(data, "Content-Range:")) {
  2091. /* if a line like this was already allocated, free the previous one */
  2092. if(conn->allocptr.rangeline)
  2093. free(conn->allocptr.rangeline);
  2094. if(data->set.set_resume_from < 0) {
  2095. /* Upload resume was asked for, but we don't know the size of the
  2096. remote part so we tell the server (and act accordingly) that we
  2097. upload the whole file (again) */
  2098. conn->allocptr.rangeline =
  2099. aprintf("Content-Range: bytes 0-%" FORMAT_OFF_T
  2100. "/%" FORMAT_OFF_T "\r\n",
  2101. data->set.infilesize - 1, data->set.infilesize);
  2102. }
  2103. else if(data->state.resume_from) {
  2104. /* This is because "resume" was selected */
  2105. curl_off_t total_expected_size=
  2106. data->state.resume_from + data->set.infilesize;
  2107. conn->allocptr.rangeline =
  2108. aprintf("Content-Range: bytes %s%" FORMAT_OFF_T
  2109. "/%" FORMAT_OFF_T "\r\n",
  2110. data->state.range, total_expected_size-1,
  2111. total_expected_size);
  2112. }
  2113. else {
  2114. /* Range was selected and then we just pass the incoming range and
  2115. append total size */
  2116. conn->allocptr.rangeline =
  2117. aprintf("Content-Range: bytes %s/%" FORMAT_OFF_T "\r\n",
  2118. data->state.range, data->set.infilesize);
  2119. }
  2120. if(!conn->allocptr.rangeline)
  2121. return CURLE_OUT_OF_MEMORY;
  2122. }
  2123. }
  2124. /* Use 1.1 unless the use specificly asked for 1.0 */
  2125. httpstring= data->set.httpversion==CURL_HTTP_VERSION_1_0?"1.0":"1.1";
  2126. /* initialize a dynamic send-buffer */
  2127. req_buffer = add_buffer_init();
  2128. if(!req_buffer)
  2129. return CURLE_OUT_OF_MEMORY;
  2130. /* add the main request stuff */
  2131. result =
  2132. add_bufferf(req_buffer,
  2133. "%s " /* GET/HEAD/POST/PUT */
  2134. "%s%s HTTP/%s\r\n" /* path + HTTP version */
  2135. "%s" /* proxyuserpwd */
  2136. "%s" /* userpwd */
  2137. "%s" /* range */
  2138. "%s" /* user agent */
  2139. "%s" /* host */
  2140. "%s" /* pragma */
  2141. "%s" /* accept */
  2142. "%s" /* accept-encoding */
  2143. "%s" /* referer */
  2144. "%s" /* Proxy-Connection */
  2145. "%s",/* transfer-encoding */
  2146. request,
  2147. ppath,
  2148. ftp_typecode,
  2149. httpstring,
  2150. conn->allocptr.proxyuserpwd?
  2151. conn->allocptr.proxyuserpwd:"",
  2152. conn->allocptr.userpwd?conn->allocptr.userpwd:"",
  2153. (data->state.use_range && conn->allocptr.rangeline)?
  2154. conn->allocptr.rangeline:"",
  2155. (data->set.str[STRING_USERAGENT] &&
  2156. *data->set.str[STRING_USERAGENT] && conn->allocptr.uagent)?
  2157. conn->allocptr.uagent:"",
  2158. (conn->allocptr.host?conn->allocptr.host:""), /* Host: host */
  2159. http->p_pragma?http->p_pragma:"",
  2160. http->p_accept?http->p_accept:"",
  2161. (data->set.str[STRING_ENCODING] &&
  2162. *data->set.str[STRING_ENCODING] &&
  2163. conn->allocptr.accept_encoding)?
  2164. conn->allocptr.accept_encoding:"",
  2165. (data->change.referer && conn->allocptr.ref)?
  2166. conn->allocptr.ref:"" /* Referer: <data> */,
  2167. (conn->bits.httpproxy &&
  2168. !conn->bits.tunnel_proxy &&
  2169. !checkheaders(data, "Proxy-Connection:"))?
  2170. "Proxy-Connection: Keep-Alive\r\n":"",
  2171. te
  2172. );
  2173. /*
  2174. * Free userpwd now --- cannot reuse this for Negotiate and possibly NTLM
  2175. * with basic and digest, it will be freed anyway by the next request
  2176. */
  2177. Curl_safefree (conn->allocptr.userpwd);
  2178. conn->allocptr.userpwd = NULL;
  2179. if(result)
  2180. return result;
  2181. #if !defined(CURL_DISABLE_COOKIES)
  2182. if(data->cookies || addcookies) {
  2183. struct Cookie *co=NULL; /* no cookies from start */
  2184. int count=0;
  2185. if(data->cookies) {
  2186. Curl_share_lock(data, CURL_LOCK_DATA_COOKIE, CURL_LOCK_ACCESS_SINGLE);
  2187. co = Curl_cookie_getlist(data->cookies,
  2188. conn->allocptr.cookiehost?
  2189. conn->allocptr.cookiehost:host,
  2190. data->state.path,
  2191. (bool)(conn->protocol&PROT_HTTPS?TRUE:FALSE));
  2192. Curl_share_unlock(data, CURL_LOCK_DATA_COOKIE);
  2193. }
  2194. if(co) {
  2195. struct Cookie *store=co;
  2196. /* now loop through all cookies that matched */
  2197. while(co) {
  2198. if(co->value) {
  2199. if(0 == count) {
  2200. result = add_bufferf(req_buffer, "Cookie: ");
  2201. if(result)
  2202. break;
  2203. }
  2204. result = add_bufferf(req_buffer,
  2205. "%s%s=%s", count?"; ":"",
  2206. co->name, co->value);
  2207. if(result)
  2208. break;
  2209. count++;
  2210. }
  2211. co = co->next; /* next cookie please */
  2212. }
  2213. Curl_cookie_freelist(store, FALSE); /* free the cookie list */
  2214. }
  2215. if(addcookies && (CURLE_OK == result)) {
  2216. if(!count)
  2217. result = add_bufferf(req_buffer, "Cookie: ");
  2218. if(CURLE_OK == result) {
  2219. result = add_bufferf(req_buffer, "%s%s",
  2220. count?"; ":"",
  2221. addcookies);
  2222. count++;
  2223. }
  2224. }
  2225. if(count && (CURLE_OK == result))
  2226. result = add_buffer(req_buffer, "\r\n", 2);
  2227. if(result)
  2228. return result;
  2229. }
  2230. #endif
  2231. if(data->set.timecondition) {
  2232. struct tm *tm;
  2233. /* The If-Modified-Since header family should have their times set in
  2234. * GMT as RFC2616 defines: "All HTTP date/time stamps MUST be
  2235. * represented in Greenwich Mean Time (GMT), without exception. For the
  2236. * purposes of HTTP, GMT is exactly equal to UTC (Coordinated Universal
  2237. * Time)." (see page 20 of RFC2616).
  2238. */
  2239. #ifdef HAVE_GMTIME_R
  2240. /* thread-safe version */
  2241. struct tm keeptime;
  2242. tm = (struct tm *)gmtime_r(&data->set.timevalue, &keeptime);
  2243. #else
  2244. tm = gmtime(&data->set.timevalue);
  2245. #endif
  2246. /* format: "Tue, 15 Nov 1994 12:45:26 GMT" */
  2247. snprintf(buf, BUFSIZE-1,
  2248. "%s, %02d %s %4d %02d:%02d:%02d GMT",
  2249. Curl_wkday[tm->tm_wday?tm->tm_wday-1:6],
  2250. tm->tm_mday,
  2251. Curl_month[tm->tm_mon],
  2252. tm->tm_year + 1900,
  2253. tm->tm_hour,
  2254. tm->tm_min,
  2255. tm->tm_sec);
  2256. switch(data->set.timecondition) {
  2257. case CURL_TIMECOND_IFMODSINCE:
  2258. default:
  2259. result = add_bufferf(req_buffer,
  2260. "If-Modified-Since: %s\r\n", buf);
  2261. break;
  2262. case CURL_TIMECOND_IFUNMODSINCE:
  2263. result = add_bufferf(req_buffer,
  2264. "If-Unmodified-Since: %s\r\n", buf);
  2265. break;
  2266. case CURL_TIMECOND_LASTMOD:
  2267. result = add_bufferf(req_buffer,
  2268. "Last-Modified: %s\r\n", buf);
  2269. break;
  2270. }
  2271. if(result)
  2272. return result;
  2273. }
  2274. result = add_custom_headers(conn, req_buffer);
  2275. if(result)
  2276. return result;
  2277. http->postdata = NULL; /* nothing to post at this point */
  2278. Curl_pgrsSetUploadSize(data, 0); /* upload size is 0 atm */
  2279. /* If 'authdone' is FALSE, we must not set the write socket index to the
  2280. Curl_transfer() call below, as we're not ready to actually upload any
  2281. data yet. */
  2282. switch(httpreq) {
  2283. case HTTPREQ_POST_FORM:
  2284. if(!http->sendit || conn->bits.authneg) {
  2285. /* nothing to post! */
  2286. result = add_bufferf(req_buffer, "Content-Length: 0\r\n\r\n");
  2287. if(result)
  2288. return result;
  2289. result = add_buffer_send(req_buffer, conn,
  2290. &data->info.request_size, 0, FIRSTSOCKET);
  2291. if(result)
  2292. failf(data, "Failed sending POST request");
  2293. else
  2294. /* setup variables for the upcoming transfer */
  2295. result = Curl_setup_transfer(conn, FIRSTSOCKET, -1, TRUE,
  2296. &http->readbytecount,
  2297. -1, NULL);
  2298. break;
  2299. }
  2300. if(Curl_FormInit(&http->form, http->sendit)) {
  2301. failf(data, "Internal HTTP POST error!");
  2302. return CURLE_HTTP_POST_ERROR;
  2303. }
  2304. /* Get the currently set callback function pointer and store that in the
  2305. form struct since we might want the actual user-provided callback later
  2306. on. The conn->fread_func pointer itself will be changed for the
  2307. multipart case to the function that returns a multipart formatted
  2308. stream. */
  2309. http->form.fread_func = conn->fread_func;
  2310. /* Set the read function to read from the generated form data */
  2311. conn->fread_func = (curl_read_callback)Curl_FormReader;
  2312. conn->fread_in = &http->form;
  2313. http->sending = HTTPSEND_BODY;
  2314. if(!data->req.upload_chunky) {
  2315. /* only add Content-Length if not uploading chunked */
  2316. result = add_bufferf(req_buffer,
  2317. "Content-Length: %" FORMAT_OFF_T "\r\n",
  2318. http->postsize);
  2319. if(result)
  2320. return result;
  2321. }
  2322. result = expect100(data, req_buffer);
  2323. if(result)
  2324. return result;
  2325. {
  2326. /* Get Content-Type: line from Curl_formpostheader.
  2327. */
  2328. char *contentType;
  2329. size_t linelength=0;
  2330. contentType = Curl_formpostheader((void *)&http->form,
  2331. &linelength);
  2332. if(!contentType) {
  2333. failf(data, "Could not get Content-Type header line!");
  2334. return CURLE_HTTP_POST_ERROR;
  2335. }
  2336. result = add_buffer(req_buffer, contentType, linelength);
  2337. if(result)
  2338. return result;
  2339. }
  2340. /* make the request end in a true CRLF */
  2341. result = add_buffer(req_buffer, "\r\n", 2);
  2342. if(result)
  2343. return result;
  2344. /* set upload size to the progress meter */
  2345. Curl_pgrsSetUploadSize(data, http->postsize);
  2346. /* fire away the whole request to the server */
  2347. result = add_buffer_send(req_buffer, conn,
  2348. &data->info.request_size, 0, FIRSTSOCKET);
  2349. if(result)
  2350. failf(data, "Failed sending POST request");
  2351. else
  2352. /* setup variables for the upcoming transfer */
  2353. result = Curl_setup_transfer(conn, FIRSTSOCKET, -1, TRUE,
  2354. &http->readbytecount,
  2355. FIRSTSOCKET,
  2356. &http->writebytecount);
  2357. if(result) {
  2358. Curl_formclean(&http->sendit); /* free that whole lot */
  2359. return result;
  2360. }
  2361. #ifdef CURL_DOES_CONVERSIONS
  2362. /* time to convert the form data... */
  2363. result = Curl_formconvert(data, http->sendit);
  2364. if(result) {
  2365. Curl_formclean(&http->sendit); /* free that whole lot */
  2366. return result;
  2367. }
  2368. #endif /* CURL_DOES_CONVERSIONS */
  2369. break;
  2370. case HTTPREQ_PUT: /* Let's PUT the data to the server! */
  2371. if(conn->bits.authneg)
  2372. postsize = 0;
  2373. else
  2374. postsize = data->set.infilesize;
  2375. if((postsize != -1) && !data->req.upload_chunky) {
  2376. /* only add Content-Length if not uploading chunked */
  2377. result = add_bufferf(req_buffer,
  2378. "Content-Length: %" FORMAT_OFF_T "\r\n",
  2379. postsize );
  2380. if(result)
  2381. return result;
  2382. }
  2383. result = expect100(data, req_buffer);
  2384. if(result)
  2385. return result;
  2386. result = add_buffer(req_buffer, "\r\n", 2); /* end of headers */
  2387. if(result)
  2388. return result;
  2389. /* set the upload size to the progress meter */
  2390. Curl_pgrsSetUploadSize(data, postsize);
  2391. /* this sends the buffer and frees all the buffer resources */
  2392. result = add_buffer_send(req_buffer, conn,
  2393. &data->info.request_size, 0, FIRSTSOCKET);
  2394. if(result)
  2395. failf(data, "Failed sending PUT request");
  2396. else
  2397. /* prepare for transfer */
  2398. result = Curl_setup_transfer(conn, FIRSTSOCKET, -1, TRUE,
  2399. &http->readbytecount,
  2400. postsize?FIRSTSOCKET:-1,
  2401. postsize?&http->writebytecount:NULL);
  2402. if(result)
  2403. return result;
  2404. break;
  2405. case HTTPREQ_POST:
  2406. /* this is the simple POST, using x-www-form-urlencoded style */
  2407. if(conn->bits.authneg)
  2408. postsize = 0;
  2409. else
  2410. /* figure out the size of the postfields */
  2411. postsize = (data->set.postfieldsize != -1)?
  2412. data->set.postfieldsize:
  2413. (data->set.postfields? (curl_off_t)strlen(data->set.postfields):0);
  2414. if(!data->req.upload_chunky) {
  2415. /* We only set Content-Length and allow a custom Content-Length if
  2416. we don't upload data chunked, as RFC2616 forbids us to set both
  2417. kinds of headers (Transfer-Encoding: chunked and Content-Length) */
  2418. if(!checkheaders(data, "Content-Length:")) {
  2419. /* we allow replacing this header, although it isn't very wise to
  2420. actually set your own */
  2421. result = add_bufferf(req_buffer,
  2422. "Content-Length: %" FORMAT_OFF_T"\r\n",
  2423. postsize);
  2424. if(result)
  2425. return result;
  2426. }
  2427. }
  2428. if(!checkheaders(data, "Content-Type:")) {
  2429. result = add_bufferf(req_buffer,
  2430. "Content-Type: application/x-www-form-urlencoded\r\n");
  2431. if(result)
  2432. return result;
  2433. }
  2434. /* For really small posts we don't use Expect: headers at all, and for
  2435. the somewhat bigger ones we allow the app to disable it. Just make
  2436. sure that the expect100header is always set to the preferred value
  2437. here. */
  2438. if(postsize > TINY_INITIAL_POST_SIZE) {
  2439. result = expect100(data, req_buffer);
  2440. if(result)
  2441. return result;
  2442. }
  2443. else
  2444. data->state.expect100header = FALSE;
  2445. if(data->set.postfields) {
  2446. if(!data->state.expect100header &&
  2447. (postsize < MAX_INITIAL_POST_SIZE)) {
  2448. /* if we don't use expect: 100 AND
  2449. postsize is less than MAX_INITIAL_POST_SIZE
  2450. then append the post data to the HTTP request header. This limit
  2451. is no magic limit but only set to prevent really huge POSTs to
  2452. get the data duplicated with malloc() and family. */
  2453. result = add_buffer(req_buffer, "\r\n", 2); /* end of headers! */
  2454. if(result)
  2455. return result;
  2456. if(!data->req.upload_chunky) {
  2457. /* We're not sending it 'chunked', append it to the request
  2458. already now to reduce the number if send() calls */
  2459. result = add_buffer(req_buffer, data->set.postfields,
  2460. (size_t)postsize);
  2461. included_body = postsize;
  2462. }
  2463. else {
  2464. /* Append the POST data chunky-style */
  2465. result = add_bufferf(req_buffer, "%x\r\n", (int)postsize);
  2466. if(CURLE_OK == result)
  2467. result = add_buffer(req_buffer, data->set.postfields,
  2468. (size_t)postsize);
  2469. if(CURLE_OK == result)
  2470. result = add_buffer(req_buffer,
  2471. "\x0d\x0a\x30\x0d\x0a\x0d\x0a", 7);
  2472. /* CR LF 0 CR LF CR LF */
  2473. included_body = postsize + 7;
  2474. }
  2475. if(result)
  2476. return result;
  2477. }
  2478. else {
  2479. /* A huge POST coming up, do data separate from the request */
  2480. http->postsize = postsize;
  2481. http->postdata = data->set.postfields;
  2482. http->sending = HTTPSEND_BODY;
  2483. conn->fread_func = (curl_read_callback)readmoredata;
  2484. conn->fread_in = (void *)conn;
  2485. /* set the upload size to the progress meter */
  2486. Curl_pgrsSetUploadSize(data, http->postsize);
  2487. result = add_buffer(req_buffer, "\r\n", 2); /* end of headers! */
  2488. if(result)
  2489. return result;
  2490. }
  2491. }
  2492. else {
  2493. result = add_buffer(req_buffer, "\r\n", 2); /* end of headers! */
  2494. if(result)
  2495. return result;
  2496. if(data->set.postfieldsize) {
  2497. /* set the upload size to the progress meter */
  2498. Curl_pgrsSetUploadSize(data, postsize?postsize:-1);
  2499. /* set the pointer to mark that we will send the post body using the
  2500. read callback, but only if we're not in authenticate
  2501. negotiation */
  2502. if(!conn->bits.authneg) {
  2503. http->postdata = (char *)&http->postdata;
  2504. http->postsize = postsize;
  2505. }
  2506. }
  2507. }
  2508. /* issue the request */
  2509. result = add_buffer_send(req_buffer, conn, &data->info.request_size,
  2510. (size_t)included_body, FIRSTSOCKET);
  2511. if(result)
  2512. failf(data, "Failed sending HTTP POST request");
  2513. else
  2514. result =
  2515. Curl_setup_transfer(conn, FIRSTSOCKET, -1, TRUE,
  2516. &http->readbytecount,
  2517. http->postdata?FIRSTSOCKET:-1,
  2518. http->postdata?&http->writebytecount:NULL);
  2519. break;
  2520. default:
  2521. result = add_buffer(req_buffer, "\r\n", 2);
  2522. if(result)
  2523. return result;
  2524. /* issue the request */
  2525. result = add_buffer_send(req_buffer, conn,
  2526. &data->info.request_size, 0, FIRSTSOCKET);
  2527. if(result)
  2528. failf(data, "Failed sending HTTP request");
  2529. else
  2530. /* HTTP GET/HEAD download: */
  2531. result = Curl_setup_transfer(conn, FIRSTSOCKET, -1, TRUE,
  2532. &http->readbytecount,
  2533. http->postdata?FIRSTSOCKET:-1,
  2534. http->postdata?&http->writebytecount:NULL);
  2535. }
  2536. if(result)
  2537. return result;
  2538. if(http->writebytecount) {
  2539. /* if a request-body has been sent off, we make sure this progress is noted
  2540. properly */
  2541. Curl_pgrsSetUploadCounter(data, http->writebytecount);
  2542. if(Curl_pgrsUpdate(conn))
  2543. result = CURLE_ABORTED_BY_CALLBACK;
  2544. }
  2545. return result;
  2546. }
  2547. #endif