http.c 122 KB

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