http.c 93 KB

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