http.c 75 KB

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