http.c 132 KB

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