http.c 130 KB

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