url.c 128 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252
  1. /***************************************************************************
  2. * _ _ ____ _
  3. * Project ___| | | | _ \| |
  4. * / __| | | | |_) | |
  5. * | (__| |_| | _ <| |___
  6. * \___|\___/|_| \_\_____|
  7. *
  8. * Copyright (C) 1998 - 2007, Daniel Stenberg, <[email protected]>, et al.
  9. *
  10. * This software is licensed as described in the file COPYING, which
  11. * you should have received as part of this distribution. The terms
  12. * are also available at http://curl.haxx.se/docs/copyright.html.
  13. *
  14. * You may opt to use, copy, modify, merge, publish, distribute and/or sell
  15. * copies of the Software, and permit persons to whom the Software is
  16. * furnished to do so, under the terms of the COPYING file.
  17. *
  18. * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
  19. * KIND, either express or implied.
  20. *
  21. * $Id$
  22. ***************************************************************************/
  23. /* -- WIN32 approved -- */
  24. #include "setup.h"
  25. #include <stdio.h>
  26. #include <string.h>
  27. #include <stdarg.h>
  28. #include <stdlib.h>
  29. #include <ctype.h>
  30. #ifdef HAVE_SYS_TYPES_H
  31. #include <sys/types.h>
  32. #endif
  33. #ifdef HAVE_SYS_STAT_H
  34. #include <sys/stat.h>
  35. #endif
  36. #include <errno.h>
  37. #ifdef WIN32
  38. #include <time.h>
  39. #include <io.h>
  40. #else
  41. #ifdef HAVE_SYS_SOCKET_H
  42. #include <sys/socket.h>
  43. #endif
  44. #include <netinet/in.h>
  45. #ifdef HAVE_SYS_TIME_H
  46. #include <sys/time.h>
  47. #endif
  48. #ifdef HAVE_UNISTD_H
  49. #include <unistd.h>
  50. #endif
  51. #include <netdb.h>
  52. #ifdef HAVE_ARPA_INET_H
  53. #include <arpa/inet.h>
  54. #endif
  55. #ifdef HAVE_NET_IF_H
  56. #include <net/if.h>
  57. #endif
  58. #include <sys/ioctl.h>
  59. #include <signal.h>
  60. #ifdef HAVE_SYS_PARAM_H
  61. #include <sys/param.h>
  62. #endif
  63. #ifdef VMS
  64. #include <in.h>
  65. #include <inet.h>
  66. #endif
  67. #ifdef HAVE_SETJMP_H
  68. #include <setjmp.h>
  69. #endif
  70. #ifndef HAVE_SOCKET
  71. #error "We can't compile without socket() support!"
  72. #endif
  73. #endif
  74. #ifdef USE_LIBIDN
  75. #include <idna.h>
  76. #include <tld.h>
  77. #include <stringprep.h>
  78. #ifdef HAVE_IDN_FREE_H
  79. #include <idn-free.h>
  80. #else
  81. void idn_free (void *ptr); /* prototype from idn-free.h, not provided by
  82. libidn 0.4.5's make install! */
  83. #endif
  84. #ifndef HAVE_IDN_FREE
  85. /* if idn_free() was not found in this version of libidn, use plain free()
  86. instead */
  87. #define idn_free(x) (free)(x)
  88. #endif
  89. #endif /* USE_LIBIDN */
  90. #include "urldata.h"
  91. #include "netrc.h"
  92. #include "formdata.h"
  93. #include "base64.h"
  94. #include "sslgen.h"
  95. #include "hostip.h"
  96. #include "transfer.h"
  97. #include "sendf.h"
  98. #include "progress.h"
  99. #include "cookie.h"
  100. #include "strequal.h"
  101. #include "strerror.h"
  102. #include "escape.h"
  103. #include "strtok.h"
  104. #include "share.h"
  105. #include "content_encoding.h"
  106. #include "http_digest.h"
  107. #include "http_negotiate.h"
  108. #include "select.h"
  109. #include "multiif.h"
  110. #include "easyif.h"
  111. /* And now for the protocols */
  112. #include "ftp.h"
  113. #include "dict.h"
  114. #include "telnet.h"
  115. #include "tftp.h"
  116. #include "http.h"
  117. #include "file.h"
  118. #include "ldap.h"
  119. #include "ssh.h"
  120. #include "url.h"
  121. #include "connect.h"
  122. #include "inet_ntop.h"
  123. #include "http_ntlm.h"
  124. #include "socks.h"
  125. #include <ca-bundle.h>
  126. #if defined(HAVE_INET_NTOA_R) && !defined(HAVE_INET_NTOA_R_DECL)
  127. #include "inet_ntoa_r.h"
  128. #endif
  129. #define _MPRINTF_REPLACE /* use our functions only */
  130. #include <curl/mprintf.h>
  131. #ifdef HAVE_KRB4
  132. #include "krb4.h"
  133. #endif
  134. #include "memory.h"
  135. /* The last #include file should be: */
  136. #include "memdebug.h"
  137. /* Local static prototypes */
  138. static long ConnectionKillOne(struct SessionHandle *data);
  139. static bool ConnectionExists(struct SessionHandle *data,
  140. struct connectdata *needle,
  141. struct connectdata **usethis);
  142. static long ConnectionStore(struct SessionHandle *data,
  143. struct connectdata *conn);
  144. static bool IsPipeliningPossible(struct SessionHandle *handle);
  145. static bool IsPipeliningEnabled(struct SessionHandle *handle);
  146. static void conn_free(struct connectdata *conn);
  147. static void signalPipeClose(struct curl_llist *pipe);
  148. #define MAX_PIPELINE_LENGTH 5
  149. /*
  150. * We use this ZERO_NULL to avoid picky compiler warnings,
  151. * when assigning a NULL pointer to a function pointer var.
  152. */
  153. #define ZERO_NULL 0
  154. #ifndef USE_ARES
  155. /* not for ares builds */
  156. #ifndef WIN32
  157. /* not for WIN32 builds */
  158. #ifdef HAVE_SIGSETJMP
  159. extern sigjmp_buf curl_jmpenv;
  160. #endif
  161. #ifdef SIGALRM
  162. static
  163. RETSIGTYPE alarmfunc(int sig)
  164. {
  165. /* this is for "-ansi -Wall -pedantic" to stop complaining! (rabe) */
  166. (void)sig;
  167. #ifdef HAVE_SIGSETJMP
  168. siglongjmp(curl_jmpenv, 1);
  169. #endif
  170. /*return;*/ /* not reahed, and has no effect anyway */
  171. }
  172. #endif /* SIGALRM */
  173. #endif /* WIN32 */
  174. #endif /* USE_ARES */
  175. void Curl_safefree(void *ptr)
  176. {
  177. if(ptr)
  178. free(ptr);
  179. }
  180. static void close_connections(struct SessionHandle *data)
  181. {
  182. /* Loop through all open connections and kill them one by one */
  183. while(-1 != ConnectionKillOne(data))
  184. ; /* empty loop */
  185. }
  186. /*
  187. * This is the internal function curl_easy_cleanup() calls. This should
  188. * cleanup and free all resources associated with this sessionhandle.
  189. *
  190. * NOTE: if we ever add something that attempts to write to a socket or
  191. * similar here, we must ignore SIGPIPE first. It is currently only done
  192. * when curl_easy_perform() is invoked.
  193. */
  194. CURLcode Curl_close(struct SessionHandle *data)
  195. {
  196. struct Curl_multi *m = data->multi;
  197. #ifdef CURLDEBUG
  198. /* only for debugging, scan through all connections and see if there's a
  199. pipe reference still identifying this handle */
  200. if(data->state.is_in_pipeline)
  201. fprintf(stderr, "CLOSED when in pipeline!\n");
  202. if(data->state.connc && data->state.connc->type == CONNCACHE_MULTI) {
  203. struct conncache *c = data->state.connc;
  204. int i;
  205. struct curl_llist *pipe;
  206. struct curl_llist_element *curr;
  207. struct connectdata *connptr;
  208. for(i=0; i< c->num; i++) {
  209. connptr = c->connects[i];
  210. if(!connptr)
  211. continue;
  212. pipe = connptr->send_pipe;
  213. if(pipe) {
  214. for (curr = pipe->head; curr; curr=curr->next) {
  215. if(data == (struct SessionHandle *) curr->ptr) {
  216. fprintf(stderr,
  217. "MAJOR problem we %p are still in send pipe for %p done %d\n",
  218. data, connptr, connptr->bits.done);
  219. }
  220. }
  221. }
  222. pipe = connptr->recv_pipe;
  223. if(pipe) {
  224. for (curr = pipe->head; curr; curr=curr->next) {
  225. if(data == (struct SessionHandle *) curr->ptr) {
  226. fprintf(stderr,
  227. "MAJOR problem we %p are still in recv pipe for %p done %d\n",
  228. data, connptr, connptr->bits.done);
  229. }
  230. }
  231. }
  232. }
  233. }
  234. #endif
  235. if(m)
  236. /* This handle is still part of a multi handle, take care of this first
  237. and detach this handle from there. */
  238. Curl_multi_rmeasy(data->multi, data);
  239. data->magic = 0; /* force a clear AFTER the possibly enforced removal from
  240. the multi handle, since that function uses the magic
  241. field! */
  242. if(data->state.connc) {
  243. if(data->state.connc->type == CONNCACHE_PRIVATE) {
  244. /* close all connections still alive that are in the private connection
  245. cache, as we no longer have the pointer left to the shared one. */
  246. close_connections(data);
  247. /* free the connection cache if allocated privately */
  248. Curl_rm_connc(data->state.connc);
  249. }
  250. }
  251. if(data->state.shared_conn) {
  252. /* marked to be used by a pending connection so we can't kill this handle
  253. just yet */
  254. data->state.closed = TRUE;
  255. return CURLE_OK;
  256. }
  257. if ( ! (data->share && data->share->hostcache) ) {
  258. if ( !Curl_global_host_cache_use(data)) {
  259. Curl_hash_destroy(data->dns.hostcache);
  260. }
  261. }
  262. /* Free the pathbuffer */
  263. Curl_safefree(data->reqdata.pathbuffer);
  264. Curl_safefree(data->reqdata.proto.generic);
  265. /* Close down all open SSL info and sessions */
  266. Curl_ssl_close_all(data);
  267. Curl_safefree(data->state.first_host);
  268. Curl_safefree(data->state.scratch);
  269. if(data->change.referer_alloc)
  270. free(data->change.referer);
  271. if(data->change.url_alloc)
  272. free(data->change.url);
  273. Curl_safefree(data->state.headerbuff);
  274. #if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_COOKIES)
  275. Curl_share_lock(data, CURL_LOCK_DATA_COOKIE, CURL_LOCK_ACCESS_SINGLE);
  276. if(data->set.cookiejar) {
  277. if(data->change.cookielist) {
  278. /* If there is a list of cookie files to read, do it first so that
  279. we have all the told files read before we write the new jar */
  280. Curl_cookie_loadfiles(data);
  281. }
  282. /* we have a "destination" for all the cookies to get dumped to */
  283. if(Curl_cookie_output(data->cookies, data->set.cookiejar))
  284. infof(data, "WARNING: failed to save cookies in %s\n",
  285. data->set.cookiejar);
  286. }
  287. else {
  288. if(data->change.cookielist)
  289. /* since nothing is written, we can just free the list of cookie file
  290. names */
  291. curl_slist_free_all(data->change.cookielist); /* clean up list */
  292. }
  293. if( !data->share || (data->cookies != data->share->cookies) ) {
  294. Curl_cookie_cleanup(data->cookies);
  295. }
  296. Curl_share_unlock(data, CURL_LOCK_DATA_COOKIE);
  297. #endif
  298. Curl_digest_cleanup(data);
  299. Curl_safefree(data->info.contenttype);
  300. /* this destroys the channel and we cannot use it anymore after this */
  301. ares_destroy(data->state.areschannel);
  302. #if defined(CURL_DOES_CONVERSIONS) && defined(HAVE_ICONV)
  303. /* close iconv conversion descriptors */
  304. if (data->inbound_cd != (iconv_t)-1) {
  305. iconv_close(data->inbound_cd);
  306. }
  307. if (data->outbound_cd != (iconv_t)-1) {
  308. iconv_close(data->outbound_cd);
  309. }
  310. if (data->utf8_cd != (iconv_t)-1) {
  311. iconv_close(data->utf8_cd);
  312. }
  313. #endif /* CURL_DOES_CONVERSIONS && HAVE_ICONV */
  314. /* No longer a dirty share, if it exists */
  315. if (data->share)
  316. data->share->dirty--;
  317. free(data);
  318. return CURLE_OK;
  319. }
  320. /* create a connection cache of a private or multi type */
  321. struct conncache *Curl_mk_connc(int type,
  322. int amount) /* set -1 to use default */
  323. {
  324. /* It is subject for debate how many default connections to have for a multi
  325. connection cache... */
  326. int default_amount = amount == -1?
  327. ((type == CONNCACHE_PRIVATE)?5:10):amount;
  328. struct conncache *c;
  329. c= calloc(sizeof(struct conncache), 1);
  330. if(!c)
  331. return NULL;
  332. c->connects = calloc(sizeof(struct connectdata *), default_amount);
  333. if(!c->connects) {
  334. free(c);
  335. return NULL;
  336. }
  337. c->num = default_amount;
  338. return c;
  339. }
  340. /* Change number of entries of a connection cache */
  341. CURLcode Curl_ch_connc(struct SessionHandle *data,
  342. struct conncache *c,
  343. long newamount)
  344. {
  345. long i;
  346. struct connectdata **newptr;
  347. if(newamount < 1)
  348. newamount = 1; /* we better have at least one entry */
  349. if(!c) {
  350. /* we get a NULL pointer passed in as connection cache, which means that
  351. there is no cache created for this SessionHandle just yet, we create a
  352. brand new with the requested size.
  353. */
  354. data->state.connc = Curl_mk_connc(CONNCACHE_PRIVATE, newamount);
  355. if(!data->state.connc)
  356. return CURLE_OUT_OF_MEMORY;
  357. return CURLE_OK;
  358. }
  359. if(newamount < c->num) {
  360. /* Since this number is *decreased* from the existing number, we must
  361. close the possibly open connections that live on the indexes that
  362. are being removed!
  363. NOTE: for conncache_multi cases we must make sure that we only
  364. close handles not in use.
  365. */
  366. for(i=newamount; i< c->num; i++)
  367. Curl_disconnect(c->connects[i]);
  368. /* If the most recent connection is no longer valid, mark it
  369. invalid. */
  370. if(data->state.lastconnect <= newamount)
  371. data->state.lastconnect = -1;
  372. }
  373. if(newamount > 0) {
  374. newptr= (struct connectdata **)
  375. realloc(c->connects, sizeof(struct connectdata *) * newamount);
  376. if(!newptr)
  377. /* we closed a few connections in vain, but so what? */
  378. return CURLE_OUT_OF_MEMORY;
  379. /* nullify the newly added pointers */
  380. for(i=c->num; i<newamount; i++)
  381. newptr[i] = NULL;
  382. c->connects = newptr;
  383. c->num = newamount;
  384. }
  385. /* we no longer support less than 1 as size for the connection cache, and
  386. I'm not sure it ever worked to set it to zero */
  387. return CURLE_OK;
  388. }
  389. /* Free a connection cache. This is called from Curl_close() and
  390. curl_multi_cleanup(). */
  391. void Curl_rm_connc(struct conncache *c)
  392. {
  393. if(c->connects) {
  394. int i;
  395. for(i = 0; i < c->num; ++i)
  396. conn_free(c->connects[i]);
  397. free(c->connects);
  398. }
  399. free(c);
  400. }
  401. /**
  402. * Curl_open()
  403. *
  404. * @param curl is a pointer to a sessionhandle pointer that gets set by this
  405. * function.
  406. * @return CURLcode
  407. */
  408. CURLcode Curl_open(struct SessionHandle **curl)
  409. {
  410. CURLcode res = CURLE_OK;
  411. struct SessionHandle *data;
  412. /* Very simple start-up: alloc the struct, init it with zeroes and return */
  413. data = (struct SessionHandle *)calloc(1, sizeof(struct SessionHandle));
  414. if(!data)
  415. /* this is a very serious error */
  416. return CURLE_OUT_OF_MEMORY;
  417. data->magic = CURLEASY_MAGIC_NUMBER;
  418. #ifdef USE_ARES
  419. if(ARES_SUCCESS != ares_init(&data->state.areschannel)) {
  420. free(data);
  421. return CURLE_FAILED_INIT;
  422. }
  423. /* make sure that all other returns from this function should destroy the
  424. ares channel before returning error! */
  425. #endif
  426. /* We do some initial setup here, all those fields that can't be just 0 */
  427. data->state.headerbuff=(char*)malloc(HEADERSIZE);
  428. if(!data->state.headerbuff)
  429. res = CURLE_OUT_OF_MEMORY;
  430. else {
  431. data->state.headersize=HEADERSIZE;
  432. data->set.out = stdout; /* default output to stdout */
  433. data->set.in = stdin; /* default input from stdin */
  434. data->set.err = stderr; /* default stderr to stderr */
  435. /* use fwrite as default function to store output */
  436. data->set.fwrite = (curl_write_callback)fwrite;
  437. /* use fread as default function to read input */
  438. data->set.fread = (curl_read_callback)fread;
  439. /* conversion callbacks for non-ASCII hosts */
  440. data->set.convfromnetwork = (curl_conv_callback)ZERO_NULL;
  441. data->set.convtonetwork = (curl_conv_callback)ZERO_NULL;
  442. data->set.convfromutf8 = (curl_conv_callback)ZERO_NULL;
  443. #if defined(CURL_DOES_CONVERSIONS) && defined(HAVE_ICONV)
  444. /* conversion descriptors for iconv calls */
  445. data->outbound_cd = (iconv_t)-1;
  446. data->inbound_cd = (iconv_t)-1;
  447. data->utf8_cd = (iconv_t)-1;
  448. #endif /* CURL_DOES_CONVERSIONS && HAVE_ICONV */
  449. data->set.infilesize = -1; /* we don't know any size */
  450. data->set.postfieldsize = -1;
  451. data->set.maxredirs = -1; /* allow any amount by default */
  452. data->state.current_speed = -1; /* init to negative == impossible */
  453. data->set.httpreq = HTTPREQ_GET; /* Default HTTP request */
  454. data->set.ftp_use_epsv = TRUE; /* FTP defaults to EPSV operations */
  455. data->set.ftp_use_eprt = TRUE; /* FTP defaults to EPRT operations */
  456. data->set.ftp_filemethod = FTPFILE_MULTICWD;
  457. data->set.dns_cache_timeout = 60; /* Timeout every 60 seconds by default */
  458. /* make libcurl quiet by default: */
  459. data->set.hide_progress = TRUE; /* CURLOPT_NOPROGRESS changes these */
  460. data->progress.flags |= PGRS_HIDE;
  461. /* Set the default size of the SSL session ID cache */
  462. data->set.ssl.numsessions = 5;
  463. data->set.proxyport = 1080;
  464. data->set.proxytype = CURLPROXY_HTTP; /* defaults to HTTP proxy */
  465. data->set.httpauth = CURLAUTH_BASIC; /* defaults to basic */
  466. data->set.proxyauth = CURLAUTH_BASIC; /* defaults to basic */
  467. /* This no longer creates a connection cache here. It is instead made on
  468. the first call to curl_easy_perform() or when the handle is added to a
  469. multi stack. */
  470. data->set.ssh_auth_types = CURLSSH_AUTH_DEFAULT; /* defaults to any auth
  471. type */
  472. /* most recent connection is not yet defined */
  473. data->state.lastconnect = -1;
  474. Curl_easy_initHandleData(data);
  475. /*
  476. * libcurl 7.10 introduced SSL verification *by default*! This needs to be
  477. * switched off unless wanted.
  478. */
  479. data->set.ssl.verifypeer = TRUE;
  480. data->set.ssl.verifyhost = 2;
  481. data->set.ssl.sessionid = TRUE; /* session ID caching enabled by default */
  482. #ifdef CURL_CA_BUNDLE
  483. /* This is our preferred CA cert bundle since install time */
  484. data->set.ssl.CAfile = (char *)CURL_CA_BUNDLE;
  485. #endif
  486. }
  487. if(res) {
  488. ares_destroy(data->state.areschannel);
  489. if(data->state.headerbuff)
  490. free(data->state.headerbuff);
  491. free(data);
  492. data = NULL;
  493. }
  494. else
  495. *curl = data;
  496. return res;
  497. }
  498. CURLcode Curl_setopt(struct SessionHandle *data, CURLoption option,
  499. va_list param)
  500. {
  501. char *argptr;
  502. CURLcode result = CURLE_OK;
  503. switch(option) {
  504. case CURLOPT_DNS_CACHE_TIMEOUT:
  505. data->set.dns_cache_timeout = va_arg(param, int);
  506. break;
  507. case CURLOPT_DNS_USE_GLOBAL_CACHE:
  508. {
  509. int use_cache = va_arg(param, int);
  510. if (use_cache) {
  511. Curl_global_host_cache_init();
  512. }
  513. data->set.global_dns_cache = (bool)(0 != use_cache);
  514. }
  515. break;
  516. case CURLOPT_SSL_CIPHER_LIST:
  517. /* set a list of cipher we want to use in the SSL connection */
  518. data->set.ssl.cipher_list = va_arg(param, char *);
  519. break;
  520. case CURLOPT_RANDOM_FILE:
  521. /*
  522. * This is the path name to a file that contains random data to seed
  523. * the random SSL stuff with. The file is only used for reading.
  524. */
  525. data->set.ssl.random_file = va_arg(param, char *);
  526. break;
  527. case CURLOPT_EGDSOCKET:
  528. /*
  529. * The Entropy Gathering Daemon socket pathname
  530. */
  531. data->set.ssl.egdsocket = va_arg(param, char *);
  532. break;
  533. case CURLOPT_MAXCONNECTS:
  534. /*
  535. * Set the absolute number of maximum simultaneous alive connection that
  536. * libcurl is allowed to have.
  537. */
  538. result = Curl_ch_connc(data, data->state.connc, va_arg(param, long));
  539. break;
  540. case CURLOPT_FORBID_REUSE:
  541. /*
  542. * When this transfer is done, it must not be left to be reused by a
  543. * subsequent transfer but shall be closed immediately.
  544. */
  545. data->set.reuse_forbid = (bool)(0 != va_arg(param, long));
  546. break;
  547. case CURLOPT_FRESH_CONNECT:
  548. /*
  549. * This transfer shall not use a previously cached connection but
  550. * should be made with a fresh new connect!
  551. */
  552. data->set.reuse_fresh = (bool)(0 != va_arg(param, long));
  553. break;
  554. case CURLOPT_VERBOSE:
  555. /*
  556. * Verbose means infof() calls that give a lot of information about
  557. * the connection and transfer procedures as well as internal choices.
  558. */
  559. data->set.verbose = (bool)(0 != va_arg(param, long));
  560. break;
  561. case CURLOPT_HEADER:
  562. /*
  563. * Set to include the header in the general data output stream.
  564. */
  565. data->set.include_header = (bool)(0 != va_arg(param, long));
  566. break;
  567. case CURLOPT_NOPROGRESS:
  568. /*
  569. * Shut off the internal supported progress meter
  570. */
  571. data->set.hide_progress = (bool)(0 != va_arg(param, long));
  572. if(data->set.hide_progress)
  573. data->progress.flags |= PGRS_HIDE;
  574. else
  575. data->progress.flags &= ~PGRS_HIDE;
  576. break;
  577. case CURLOPT_NOBODY:
  578. /*
  579. * Do not include the body part in the output data stream.
  580. */
  581. data->set.opt_no_body = (bool)(0 != va_arg(param, long));
  582. if(data->set.opt_no_body)
  583. /* in HTTP lingo, this means using the HEAD request */
  584. data->set.httpreq = HTTPREQ_HEAD;
  585. break;
  586. case CURLOPT_FAILONERROR:
  587. /*
  588. * Don't output the >=300 error code HTML-page, but instead only
  589. * return error.
  590. */
  591. data->set.http_fail_on_error = (bool)(0 != va_arg(param, long));
  592. break;
  593. case CURLOPT_UPLOAD:
  594. case CURLOPT_PUT:
  595. /*
  596. * We want to sent data to the remote host. If this is HTTP, that equals
  597. * using the PUT request.
  598. */
  599. data->set.upload = (bool)(0 != va_arg(param, long));
  600. if(data->set.upload)
  601. /* If this is HTTP, PUT is what's needed to "upload" */
  602. data->set.httpreq = HTTPREQ_PUT;
  603. break;
  604. case CURLOPT_FILETIME:
  605. /*
  606. * Try to get the file time of the remote document. The time will
  607. * later (possibly) become available using curl_easy_getinfo().
  608. */
  609. data->set.get_filetime = (bool)(0 != va_arg(param, long));
  610. break;
  611. case CURLOPT_FTP_CREATE_MISSING_DIRS:
  612. /*
  613. * An FTP option that modifies an upload to create missing directories on
  614. * the server.
  615. */
  616. data->set.ftp_create_missing_dirs = (bool)(0 != va_arg(param, long));
  617. break;
  618. case CURLOPT_FTP_RESPONSE_TIMEOUT:
  619. /*
  620. * An FTP option that specifies how quickly an FTP response must be
  621. * obtained before it is considered failure.
  622. */
  623. data->set.ftp_response_timeout = va_arg( param , long );
  624. break;
  625. case CURLOPT_FTPLISTONLY:
  626. /*
  627. * An FTP option that changes the command to one that asks for a list
  628. * only, no file info details.
  629. */
  630. data->set.ftp_list_only = (bool)(0 != va_arg(param, long));
  631. break;
  632. case CURLOPT_FTPAPPEND:
  633. /*
  634. * We want to upload and append to an existing (FTP) file.
  635. */
  636. data->set.ftp_append = (bool)(0 != va_arg(param, long));
  637. break;
  638. case CURLOPT_FTP_FILEMETHOD:
  639. /*
  640. * How do access files over FTP.
  641. */
  642. data->set.ftp_filemethod = (curl_ftpfile)va_arg(param, long);
  643. break;
  644. case CURLOPT_NETRC:
  645. /*
  646. * Parse the $HOME/.netrc file
  647. */
  648. data->set.use_netrc = (enum CURL_NETRC_OPTION)va_arg(param, long);
  649. break;
  650. case CURLOPT_NETRC_FILE:
  651. /*
  652. * Use this file instead of the $HOME/.netrc file
  653. */
  654. data->set.netrc_file = va_arg(param, char *);
  655. break;
  656. case CURLOPT_TRANSFERTEXT:
  657. /*
  658. * This option was previously named 'FTPASCII'. Renamed to work with
  659. * more protocols than merely FTP.
  660. *
  661. * Transfer using ASCII (instead of BINARY).
  662. */
  663. data->set.prefer_ascii = (bool)(0 != va_arg(param, long));
  664. break;
  665. case CURLOPT_TIMECONDITION:
  666. /*
  667. * Set HTTP time condition. This must be one of the defines in the
  668. * curl/curl.h header file.
  669. */
  670. data->set.timecondition = (curl_TimeCond)va_arg(param, long);
  671. break;
  672. case CURLOPT_TIMEVALUE:
  673. /*
  674. * This is the value to compare with the remote document with the
  675. * method set with CURLOPT_TIMECONDITION
  676. */
  677. data->set.timevalue = (time_t)va_arg(param, long);
  678. break;
  679. case CURLOPT_SSLVERSION:
  680. /*
  681. * Set explicit SSL version to try to connect with, as some SSL
  682. * implementations are lame.
  683. */
  684. data->set.ssl.version = va_arg(param, long);
  685. break;
  686. #ifndef CURL_DISABLE_HTTP
  687. case CURLOPT_AUTOREFERER:
  688. /*
  689. * Switch on automatic referer that gets set if curl follows locations.
  690. */
  691. data->set.http_auto_referer = (bool)(0 != va_arg(param, long));
  692. break;
  693. case CURLOPT_ENCODING:
  694. /*
  695. * String to use at the value of Accept-Encoding header.
  696. *
  697. * If the encoding is set to "" we use an Accept-Encoding header that
  698. * encompasses all the encodings we support.
  699. * If the encoding is set to NULL we don't send an Accept-Encoding header
  700. * and ignore an received Content-Encoding header.
  701. *
  702. */
  703. data->set.encoding = va_arg(param, char *);
  704. if(data->set.encoding && !*data->set.encoding)
  705. data->set.encoding = (char*)ALL_CONTENT_ENCODINGS;
  706. break;
  707. case CURLOPT_FOLLOWLOCATION:
  708. /*
  709. * Follow Location: header hints on a HTTP-server.
  710. */
  711. data->set.http_follow_location = (bool)(0 != va_arg(param, long));
  712. break;
  713. case CURLOPT_UNRESTRICTED_AUTH:
  714. /*
  715. * Send authentication (user+password) when following locations, even when
  716. * hostname changed.
  717. */
  718. data->set.http_disable_hostname_check_before_authentication =
  719. (bool)(0 != va_arg(param, long));
  720. break;
  721. case CURLOPT_MAXREDIRS:
  722. /*
  723. * The maximum amount of hops you allow curl to follow Location:
  724. * headers. This should mostly be used to detect never-ending loops.
  725. */
  726. data->set.maxredirs = va_arg(param, long);
  727. break;
  728. case CURLOPT_POST:
  729. /* Does this option serve a purpose anymore? Yes it does, when
  730. CURLOPT_POSTFIELDS isn't used and the POST data is read off the
  731. callback! */
  732. if(va_arg(param, long)) {
  733. data->set.httpreq = HTTPREQ_POST;
  734. data->set.opt_no_body = FALSE; /* this is implied */
  735. }
  736. else
  737. data->set.httpreq = HTTPREQ_GET;
  738. break;
  739. case CURLOPT_POSTFIELDS:
  740. /*
  741. * A string with POST data. Makes curl HTTP POST. Even if it is NULL.
  742. */
  743. data->set.postfields = va_arg(param, char *);
  744. data->set.httpreq = HTTPREQ_POST;
  745. break;
  746. case CURLOPT_POSTFIELDSIZE:
  747. /*
  748. * The size of the POSTFIELD data to prevent libcurl to do strlen() to
  749. * figure it out. Enables binary posts.
  750. */
  751. data->set.postfieldsize = va_arg(param, long);
  752. break;
  753. case CURLOPT_POSTFIELDSIZE_LARGE:
  754. /*
  755. * The size of the POSTFIELD data to prevent libcurl to do strlen() to
  756. * figure it out. Enables binary posts.
  757. */
  758. data->set.postfieldsize = va_arg(param, curl_off_t);
  759. break;
  760. case CURLOPT_HTTPPOST:
  761. /*
  762. * Set to make us do HTTP POST
  763. */
  764. data->set.httppost = va_arg(param, struct curl_httppost *);
  765. data->set.httpreq = HTTPREQ_POST_FORM;
  766. data->set.opt_no_body = FALSE; /* this is implied */
  767. break;
  768. case CURLOPT_REFERER:
  769. /*
  770. * String to set in the HTTP Referer: field.
  771. */
  772. if(data->change.referer_alloc) {
  773. free(data->change.referer);
  774. data->change.referer_alloc = FALSE;
  775. }
  776. data->set.set_referer = va_arg(param, char *);
  777. data->change.referer = data->set.set_referer;
  778. break;
  779. case CURLOPT_USERAGENT:
  780. /*
  781. * String to use in the HTTP User-Agent field
  782. */
  783. data->set.useragent = va_arg(param, char *);
  784. break;
  785. case CURLOPT_HTTPHEADER:
  786. /*
  787. * Set a list with HTTP headers to use (or replace internals with)
  788. */
  789. data->set.headers = va_arg(param, struct curl_slist *);
  790. break;
  791. case CURLOPT_HTTP200ALIASES:
  792. /*
  793. * Set a list of aliases for HTTP 200 in response header
  794. */
  795. data->set.http200aliases = va_arg(param, struct curl_slist *);
  796. break;
  797. #if !defined(CURL_DISABLE_COOKIES)
  798. case CURLOPT_COOKIE:
  799. /*
  800. * Cookie string to send to the remote server in the request.
  801. */
  802. data->set.cookie = va_arg(param, char *);
  803. break;
  804. case CURLOPT_COOKIEFILE:
  805. /*
  806. * Set cookie file to read and parse. Can be used multiple times.
  807. */
  808. argptr = (char *)va_arg(param, void *);
  809. if(argptr) {
  810. struct curl_slist *cl;
  811. /* append the cookie file name to the list of file names, and deal with
  812. them later */
  813. cl = curl_slist_append(data->change.cookielist, argptr);
  814. if(!cl)
  815. return CURLE_OUT_OF_MEMORY;
  816. data->change.cookielist = cl;
  817. }
  818. break;
  819. case CURLOPT_COOKIEJAR:
  820. /*
  821. * Set cookie file name to dump all cookies to when we're done.
  822. */
  823. data->set.cookiejar = (char *)va_arg(param, void *);
  824. /*
  825. * Activate the cookie parser. This may or may not already
  826. * have been made.
  827. */
  828. data->cookies = Curl_cookie_init(data, NULL, data->cookies,
  829. data->set.cookiesession);
  830. break;
  831. case CURLOPT_COOKIESESSION:
  832. /*
  833. * Set this option to TRUE to start a new "cookie session". It will
  834. * prevent the forthcoming read-cookies-from-file actions to accept
  835. * cookies that are marked as being session cookies, as they belong to a
  836. * previous session.
  837. *
  838. * In the original Netscape cookie spec, "session cookies" are cookies
  839. * with no expire date set. RFC2109 describes the same action if no
  840. * 'Max-Age' is set and RFC2965 includes the RFC2109 description and adds
  841. * a 'Discard' action that can enforce the discard even for cookies that
  842. * have a Max-Age.
  843. *
  844. * We run mostly with the original cookie spec, as hardly anyone implements
  845. * anything else.
  846. */
  847. data->set.cookiesession = (bool)(0 != va_arg(param, long));
  848. break;
  849. case CURLOPT_COOKIELIST:
  850. argptr = va_arg(param, char *);
  851. if(argptr == NULL)
  852. break;
  853. if(strequal(argptr, "ALL")) {
  854. /* clear all cookies */
  855. Curl_cookie_clearall(data->cookies);
  856. break;
  857. }
  858. else if(strequal(argptr, "SESS")) {
  859. /* clear session cookies */
  860. Curl_cookie_clearsess(data->cookies);
  861. break;
  862. }
  863. if(!data->cookies)
  864. /* if cookie engine was not running, activate it */
  865. data->cookies = Curl_cookie_init(data, NULL, NULL, TRUE);
  866. argptr = strdup(argptr);
  867. if(!argptr) {
  868. result = CURLE_OUT_OF_MEMORY;
  869. break;
  870. }
  871. if(checkprefix("Set-Cookie:", argptr))
  872. /* HTTP Header format line */
  873. Curl_cookie_add(data, data->cookies, TRUE, argptr + 11, NULL, NULL);
  874. else
  875. /* Netscape format line */
  876. Curl_cookie_add(data, data->cookies, FALSE, argptr, NULL, NULL);
  877. free(argptr);
  878. break;
  879. #endif /* CURL_DISABLE_COOKIES */
  880. case CURLOPT_HTTPGET:
  881. /*
  882. * Set to force us do HTTP GET
  883. */
  884. if(va_arg(param, long)) {
  885. data->set.httpreq = HTTPREQ_GET;
  886. data->set.upload = FALSE; /* switch off upload */
  887. data->set.opt_no_body = FALSE; /* this is implied */
  888. }
  889. break;
  890. case CURLOPT_HTTP_VERSION:
  891. /*
  892. * This sets a requested HTTP version to be used. The value is one of
  893. * the listed enums in curl/curl.h.
  894. */
  895. data->set.httpversion = va_arg(param, long);
  896. break;
  897. case CURLOPT_HTTPPROXYTUNNEL:
  898. /*
  899. * Tunnel operations through the proxy instead of normal proxy use
  900. */
  901. data->set.tunnel_thru_httpproxy = (bool)(0 != va_arg(param, long));
  902. break;
  903. case CURLOPT_CUSTOMREQUEST:
  904. /*
  905. * Set a custom string to use as request
  906. */
  907. data->set.customrequest = va_arg(param, char *);
  908. /* we don't set
  909. data->set.httpreq = HTTPREQ_CUSTOM;
  910. here, we continue as if we were using the already set type
  911. and this just changes the actual request keyword */
  912. break;
  913. case CURLOPT_PROXYPORT:
  914. /*
  915. * Explicitly set HTTP proxy port number.
  916. */
  917. data->set.proxyport = va_arg(param, long);
  918. break;
  919. case CURLOPT_HTTPAUTH:
  920. /*
  921. * Set HTTP Authentication type BITMASK.
  922. */
  923. {
  924. long auth = va_arg(param, long);
  925. /* switch off bits we can't support */
  926. #ifndef USE_NTLM
  927. auth &= ~CURLAUTH_NTLM; /* no NTLM without SSL */
  928. #endif
  929. #ifndef HAVE_GSSAPI
  930. auth &= ~CURLAUTH_GSSNEGOTIATE; /* no GSS-Negotiate without GSSAPI */
  931. #endif
  932. if(!auth)
  933. return CURLE_FAILED_INIT; /* no supported types left! */
  934. data->set.httpauth = auth;
  935. }
  936. break;
  937. case CURLOPT_PROXYAUTH:
  938. /*
  939. * Set HTTP Authentication type BITMASK.
  940. */
  941. {
  942. long auth = va_arg(param, long);
  943. /* switch off bits we can't support */
  944. #ifndef USE_NTLM
  945. auth &= ~CURLAUTH_NTLM; /* no NTLM without SSL */
  946. #endif
  947. #ifndef HAVE_GSSAPI
  948. auth &= ~CURLAUTH_GSSNEGOTIATE; /* no GSS-Negotiate without GSSAPI */
  949. #endif
  950. if(!auth)
  951. return CURLE_FAILED_INIT; /* no supported types left! */
  952. data->set.proxyauth = auth;
  953. }
  954. break;
  955. #endif /* CURL_DISABLE_HTTP */
  956. case CURLOPT_PROXY:
  957. /*
  958. * Set proxy server:port to use as HTTP proxy.
  959. *
  960. * If the proxy is set to "" we explicitly say that we don't want to use a
  961. * proxy (even though there might be environment variables saying so).
  962. *
  963. * Setting it to NULL, means no proxy but allows the environment variables
  964. * to decide for us.
  965. */
  966. data->set.proxy = va_arg(param, char *);
  967. break;
  968. case CURLOPT_WRITEHEADER:
  969. /*
  970. * Custom pointer to pass the header write callback function
  971. */
  972. data->set.writeheader = (void *)va_arg(param, void *);
  973. break;
  974. case CURLOPT_ERRORBUFFER:
  975. /*
  976. * Error buffer provided by the caller to get the human readable
  977. * error string in.
  978. */
  979. data->set.errorbuffer = va_arg(param, char *);
  980. break;
  981. case CURLOPT_FILE:
  982. /*
  983. * FILE pointer to write to or include in the data write callback
  984. */
  985. data->set.out = va_arg(param, FILE *);
  986. break;
  987. case CURLOPT_FTPPORT:
  988. /*
  989. * Use FTP PORT, this also specifies which IP address to use
  990. */
  991. data->set.ftpport = va_arg(param, char *);
  992. data->set.ftp_use_port = (bool)(NULL != data->set.ftpport);
  993. break;
  994. case CURLOPT_FTP_USE_EPRT:
  995. data->set.ftp_use_eprt = (bool)(0 != va_arg(param, long));
  996. break;
  997. case CURLOPT_FTP_USE_EPSV:
  998. data->set.ftp_use_epsv = (bool)(0 != va_arg(param, long));
  999. break;
  1000. case CURLOPT_FTP_SSL_CCC:
  1001. data->set.ftp_use_ccc = (bool)(0 != va_arg(param, long));
  1002. break;
  1003. case CURLOPT_FTP_SKIP_PASV_IP:
  1004. /*
  1005. * Enable or disable FTP_SKIP_PASV_IP, which will disable/enable the
  1006. * bypass of the IP address in PASV responses.
  1007. */
  1008. data->set.ftp_skip_ip = (bool)(0 != va_arg(param, long));
  1009. break;
  1010. case CURLOPT_INFILE:
  1011. /*
  1012. * FILE pointer to read the file to be uploaded from. Or possibly
  1013. * used as argument to the read callback.
  1014. */
  1015. data->set.in = va_arg(param, FILE *);
  1016. break;
  1017. case CURLOPT_INFILESIZE:
  1018. /*
  1019. * If known, this should inform curl about the file size of the
  1020. * to-be-uploaded file.
  1021. */
  1022. data->set.infilesize = va_arg(param, long);
  1023. break;
  1024. case CURLOPT_INFILESIZE_LARGE:
  1025. /*
  1026. * If known, this should inform curl about the file size of the
  1027. * to-be-uploaded file.
  1028. */
  1029. data->set.infilesize = va_arg(param, curl_off_t);
  1030. break;
  1031. case CURLOPT_LOW_SPEED_LIMIT:
  1032. /*
  1033. * The low speed limit that if transfers are below this for
  1034. * CURLOPT_LOW_SPEED_TIME, the transfer is aborted.
  1035. */
  1036. data->set.low_speed_limit=va_arg(param, long);
  1037. break;
  1038. case CURLOPT_MAX_SEND_SPEED_LARGE:
  1039. /*
  1040. * The max speed limit that sends transfer more than
  1041. * CURLOPT_MAX_SEND_PER_SECOND bytes per second the transfer is
  1042. * throttled..
  1043. */
  1044. data->set.max_send_speed=va_arg(param, curl_off_t);
  1045. break;
  1046. case CURLOPT_MAX_RECV_SPEED_LARGE:
  1047. /*
  1048. * The max speed limit that sends transfer more than
  1049. * CURLOPT_MAX_RECV_PER_SECOND bytes per second the transfer is
  1050. * throttled..
  1051. */
  1052. data->set.max_recv_speed=va_arg(param, curl_off_t);
  1053. break;
  1054. case CURLOPT_LOW_SPEED_TIME:
  1055. /*
  1056. * The low speed time that if transfers are below the set
  1057. * CURLOPT_LOW_SPEED_LIMIT during this time, the transfer is aborted.
  1058. */
  1059. data->set.low_speed_time=va_arg(param, long);
  1060. break;
  1061. case CURLOPT_URL:
  1062. /*
  1063. * The URL to fetch.
  1064. */
  1065. if(data->change.url_alloc) {
  1066. /* the already set URL is allocated, free it first! */
  1067. free(data->change.url);
  1068. data->change.url_alloc=FALSE;
  1069. }
  1070. data->set.set_url = va_arg(param, char *);
  1071. data->change.url = data->set.set_url;
  1072. data->change.url_changed = TRUE;
  1073. break;
  1074. case CURLOPT_PORT:
  1075. /*
  1076. * The port number to use when getting the URL
  1077. */
  1078. data->set.use_port = va_arg(param, long);
  1079. break;
  1080. case CURLOPT_TIMEOUT:
  1081. /*
  1082. * The maximum time you allow curl to use for a single transfer
  1083. * operation.
  1084. */
  1085. data->set.timeout = va_arg(param, long);
  1086. break;
  1087. case CURLOPT_CONNECTTIMEOUT:
  1088. /*
  1089. * The maximum time you allow curl to use to connect.
  1090. */
  1091. data->set.connecttimeout = va_arg(param, long);
  1092. break;
  1093. case CURLOPT_USERPWD:
  1094. /*
  1095. * user:password to use in the operation
  1096. */
  1097. data->set.userpwd = va_arg(param, char *);
  1098. break;
  1099. case CURLOPT_POSTQUOTE:
  1100. /*
  1101. * List of RAW FTP commands to use after a transfer
  1102. */
  1103. data->set.postquote = va_arg(param, struct curl_slist *);
  1104. break;
  1105. case CURLOPT_PREQUOTE:
  1106. /*
  1107. * List of RAW FTP commands to use prior to RETR (Wesley Laxton)
  1108. */
  1109. data->set.prequote = va_arg(param, struct curl_slist *);
  1110. break;
  1111. case CURLOPT_QUOTE:
  1112. /*
  1113. * List of RAW FTP commands to use before a transfer
  1114. */
  1115. data->set.quote = va_arg(param, struct curl_slist *);
  1116. break;
  1117. case CURLOPT_PROGRESSFUNCTION:
  1118. /*
  1119. * Progress callback function
  1120. */
  1121. data->set.fprogress = va_arg(param, curl_progress_callback);
  1122. if(data->set.fprogress)
  1123. data->progress.callback = TRUE; /* no longer internal */
  1124. else
  1125. data->progress.callback = FALSE; /* NULL enforces internal */
  1126. break;
  1127. case CURLOPT_PROGRESSDATA:
  1128. /*
  1129. * Custom client data to pass to the progress callback
  1130. */
  1131. data->set.progress_client = va_arg(param, void *);
  1132. break;
  1133. case CURLOPT_PROXYUSERPWD:
  1134. /*
  1135. * user:password needed to use the proxy
  1136. */
  1137. data->set.proxyuserpwd = va_arg(param, char *);
  1138. break;
  1139. case CURLOPT_RANGE:
  1140. /*
  1141. * What range of the file you want to transfer
  1142. */
  1143. data->set.set_range = va_arg(param, char *);
  1144. break;
  1145. case CURLOPT_RESUME_FROM:
  1146. /*
  1147. * Resume transfer at the give file position
  1148. */
  1149. data->set.set_resume_from = va_arg(param, long);
  1150. break;
  1151. case CURLOPT_RESUME_FROM_LARGE:
  1152. /*
  1153. * Resume transfer at the give file position
  1154. */
  1155. data->set.set_resume_from = va_arg(param, curl_off_t);
  1156. break;
  1157. case CURLOPT_DEBUGFUNCTION:
  1158. /*
  1159. * stderr write callback.
  1160. */
  1161. data->set.fdebug = va_arg(param, curl_debug_callback);
  1162. /*
  1163. * if the callback provided is NULL, it'll use the default callback
  1164. */
  1165. break;
  1166. case CURLOPT_DEBUGDATA:
  1167. /*
  1168. * Set to a void * that should receive all error writes. This
  1169. * defaults to CURLOPT_STDERR for normal operations.
  1170. */
  1171. data->set.debugdata = va_arg(param, void *);
  1172. break;
  1173. case CURLOPT_STDERR:
  1174. /*
  1175. * Set to a FILE * that should receive all error writes. This
  1176. * defaults to stderr for normal operations.
  1177. */
  1178. data->set.err = va_arg(param, FILE *);
  1179. if(!data->set.err)
  1180. data->set.err = stderr;
  1181. break;
  1182. case CURLOPT_HEADERFUNCTION:
  1183. /*
  1184. * Set header write callback
  1185. */
  1186. data->set.fwrite_header = va_arg(param, curl_write_callback);
  1187. break;
  1188. case CURLOPT_WRITEFUNCTION:
  1189. /*
  1190. * Set data write callback
  1191. */
  1192. data->set.fwrite = va_arg(param, curl_write_callback);
  1193. if(!data->set.fwrite)
  1194. /* When set to NULL, reset to our internal default function */
  1195. data->set.fwrite = (curl_write_callback)fwrite;
  1196. break;
  1197. case CURLOPT_READFUNCTION:
  1198. /*
  1199. * Read data callback
  1200. */
  1201. data->set.fread = va_arg(param, curl_read_callback);
  1202. if(!data->set.fread)
  1203. /* When set to NULL, reset to our internal default function */
  1204. data->set.fread = (curl_read_callback)fread;
  1205. break;
  1206. case CURLOPT_CONV_FROM_NETWORK_FUNCTION:
  1207. /*
  1208. * "Convert from network encoding" callback
  1209. */
  1210. data->set.convfromnetwork = va_arg(param, curl_conv_callback);
  1211. break;
  1212. case CURLOPT_CONV_TO_NETWORK_FUNCTION:
  1213. /*
  1214. * "Convert to network encoding" callback
  1215. */
  1216. data->set.convtonetwork = va_arg(param, curl_conv_callback);
  1217. break;
  1218. case CURLOPT_CONV_FROM_UTF8_FUNCTION:
  1219. /*
  1220. * "Convert from UTF-8 encoding" callback
  1221. */
  1222. data->set.convfromutf8 = va_arg(param, curl_conv_callback);
  1223. break;
  1224. case CURLOPT_IOCTLFUNCTION:
  1225. /*
  1226. * I/O control callback. Might be NULL.
  1227. */
  1228. data->set.ioctl = va_arg(param, curl_ioctl_callback);
  1229. break;
  1230. case CURLOPT_IOCTLDATA:
  1231. /*
  1232. * I/O control data pointer. Might be NULL.
  1233. */
  1234. data->set.ioctl_client = va_arg(param, void *);
  1235. break;
  1236. case CURLOPT_SSLCERT:
  1237. /*
  1238. * String that holds file name of the SSL certificate to use
  1239. */
  1240. data->set.cert = va_arg(param, char *);
  1241. break;
  1242. case CURLOPT_SSLCERTTYPE:
  1243. /*
  1244. * String that holds file type of the SSL certificate to use
  1245. */
  1246. data->set.cert_type = va_arg(param, char *);
  1247. break;
  1248. case CURLOPT_SSLKEY:
  1249. /*
  1250. * String that holds file name of the SSL certificate to use
  1251. */
  1252. data->set.key = va_arg(param, char *);
  1253. break;
  1254. case CURLOPT_SSLKEYTYPE:
  1255. /*
  1256. * String that holds file type of the SSL certificate to use
  1257. */
  1258. data->set.key_type = va_arg(param, char *);
  1259. break;
  1260. case CURLOPT_SSLKEYPASSWD:
  1261. /*
  1262. * String that holds the SSL private key password.
  1263. */
  1264. data->set.key_passwd = va_arg(param, char *);
  1265. break;
  1266. case CURLOPT_SSLENGINE:
  1267. /*
  1268. * String that holds the SSL crypto engine.
  1269. */
  1270. argptr = va_arg(param, char *);
  1271. if (argptr && argptr[0])
  1272. result = Curl_ssl_set_engine(data, argptr);
  1273. break;
  1274. case CURLOPT_SSLENGINE_DEFAULT:
  1275. /*
  1276. * flag to set engine as default.
  1277. */
  1278. result = Curl_ssl_set_engine_default(data);
  1279. break;
  1280. case CURLOPT_CRLF:
  1281. /*
  1282. * Kludgy option to enable CRLF conversions. Subject for removal.
  1283. */
  1284. data->set.crlf = (bool)(0 != va_arg(param, long));
  1285. break;
  1286. case CURLOPT_INTERFACE:
  1287. /*
  1288. * Set what interface or address/hostname to bind the socket to when
  1289. * performing an operation and thus what from-IP your connection will use.
  1290. */
  1291. data->set.device = va_arg(param, char *);
  1292. break;
  1293. case CURLOPT_LOCALPORT:
  1294. /*
  1295. * Set what local port to bind the socket to when performing an operation.
  1296. */
  1297. data->set.localport = (unsigned short) va_arg(param, long);
  1298. break;
  1299. case CURLOPT_LOCALPORTRANGE:
  1300. /*
  1301. * Set number of local ports to try, starting with CURLOPT_LOCALPORT.
  1302. */
  1303. data->set.localportrange = (int) va_arg(param, long);
  1304. break;
  1305. case CURLOPT_KRB4LEVEL:
  1306. /*
  1307. * A string that defines the krb4 security level.
  1308. */
  1309. data->set.krb4_level = va_arg(param, char *);
  1310. data->set.krb4 = (bool)(NULL != data->set.krb4_level);
  1311. break;
  1312. case CURLOPT_SSL_VERIFYPEER:
  1313. /*
  1314. * Enable peer SSL verifying.
  1315. */
  1316. data->set.ssl.verifypeer = va_arg(param, long);
  1317. break;
  1318. case CURLOPT_SSL_VERIFYHOST:
  1319. /*
  1320. * Enable verification of the CN contained in the peer certificate
  1321. */
  1322. data->set.ssl.verifyhost = va_arg(param, long);
  1323. break;
  1324. case CURLOPT_SSL_CTX_FUNCTION:
  1325. /*
  1326. * Set a SSL_CTX callback
  1327. */
  1328. data->set.ssl.fsslctx = va_arg(param, curl_ssl_ctx_callback);
  1329. break;
  1330. case CURLOPT_SSL_CTX_DATA:
  1331. /*
  1332. * Set a SSL_CTX callback parameter pointer
  1333. */
  1334. data->set.ssl.fsslctxp = va_arg(param, void *);
  1335. break;
  1336. case CURLOPT_CAINFO:
  1337. /*
  1338. * Set CA info for SSL connection. Specify file name of the CA certificate
  1339. */
  1340. data->set.ssl.CAfile = va_arg(param, char *);
  1341. break;
  1342. case CURLOPT_CAPATH:
  1343. /*
  1344. * Set CA path info for SSL connection. Specify directory name of the CA
  1345. * certificates which have been prepared using openssl c_rehash utility.
  1346. */
  1347. /* This does not work on windows. */
  1348. data->set.ssl.CApath = va_arg(param, char *);
  1349. break;
  1350. case CURLOPT_TELNETOPTIONS:
  1351. /*
  1352. * Set a linked list of telnet options
  1353. */
  1354. data->set.telnet_options = va_arg(param, struct curl_slist *);
  1355. break;
  1356. case CURLOPT_BUFFERSIZE:
  1357. /*
  1358. * The application kindly asks for a differently sized receive buffer.
  1359. * If it seems reasonable, we'll use it.
  1360. */
  1361. data->set.buffer_size = va_arg(param, long);
  1362. if((data->set.buffer_size> (BUFSIZE -1 )) ||
  1363. (data->set.buffer_size < 1))
  1364. data->set.buffer_size = 0; /* huge internal default */
  1365. break;
  1366. case CURLOPT_NOSIGNAL:
  1367. /*
  1368. * The application asks not to set any signal() or alarm() handlers,
  1369. * even when using a timeout.
  1370. */
  1371. data->set.no_signal = (bool)(0 != va_arg(param, long));
  1372. break;
  1373. case CURLOPT_SHARE:
  1374. {
  1375. struct Curl_share *set;
  1376. set = va_arg(param, struct Curl_share *);
  1377. /* disconnect from old share, if any */
  1378. if(data->share) {
  1379. Curl_share_lock(data, CURL_LOCK_DATA_SHARE, CURL_LOCK_ACCESS_SINGLE);
  1380. if(data->dns.hostcachetype == HCACHE_SHARED) {
  1381. data->dns.hostcache = NULL;
  1382. data->dns.hostcachetype = HCACHE_NONE;
  1383. }
  1384. if(data->share->cookies == data->cookies)
  1385. data->cookies = NULL;
  1386. data->share->dirty--;
  1387. Curl_share_unlock(data, CURL_LOCK_DATA_SHARE);
  1388. data->share = NULL;
  1389. }
  1390. /* use new share if it set */
  1391. data->share = set;
  1392. if(data->share) {
  1393. Curl_share_lock(data, CURL_LOCK_DATA_SHARE, CURL_LOCK_ACCESS_SINGLE);
  1394. data->share->dirty++;
  1395. if(data->share->hostcache) {
  1396. /* use shared host cache, first free the private one if any */
  1397. if(data->dns.hostcachetype == HCACHE_PRIVATE)
  1398. Curl_hash_destroy(data->dns.hostcache);
  1399. data->dns.hostcache = data->share->hostcache;
  1400. data->dns.hostcachetype = HCACHE_SHARED;
  1401. }
  1402. #if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_COOKIES)
  1403. if(data->share->cookies) {
  1404. /* use shared cookie list, first free own one if any */
  1405. if (data->cookies)
  1406. Curl_cookie_cleanup(data->cookies);
  1407. data->cookies = data->share->cookies;
  1408. }
  1409. #endif /* CURL_DISABLE_HTTP */
  1410. Curl_share_unlock(data, CURL_LOCK_DATA_SHARE);
  1411. }
  1412. #if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_COOKIES)
  1413. /* check cookie list is set */
  1414. if(!data->cookies)
  1415. data->cookies = Curl_cookie_init(data, NULL, NULL, TRUE );
  1416. #endif /* CURL_DISABLE_HTTP */
  1417. /* check for host cache not needed,
  1418. * it will be done by curl_easy_perform */
  1419. }
  1420. break;
  1421. case CURLOPT_PROXYTYPE:
  1422. /*
  1423. * Set proxy type. HTTP/SOCKS4/SOCKS5
  1424. */
  1425. data->set.proxytype = (curl_proxytype)va_arg(param, long);
  1426. break;
  1427. case CURLOPT_PRIVATE:
  1428. /*
  1429. * Set private data pointer.
  1430. */
  1431. data->set.private_data = va_arg(param, char *);
  1432. break;
  1433. case CURLOPT_MAXFILESIZE:
  1434. /*
  1435. * Set the maximum size of a file to download.
  1436. */
  1437. data->set.max_filesize = va_arg(param, long);
  1438. break;
  1439. case CURLOPT_FTP_SSL:
  1440. /*
  1441. * Make FTP transfers attempt to use SSL/TLS.
  1442. */
  1443. data->set.ftp_ssl = (curl_ftpssl)va_arg(param, long);
  1444. break;
  1445. case CURLOPT_FTPSSLAUTH:
  1446. /*
  1447. * Set a specific auth for FTP-SSL transfers.
  1448. */
  1449. data->set.ftpsslauth = (curl_ftpauth)va_arg(param, long);
  1450. break;
  1451. case CURLOPT_IPRESOLVE:
  1452. data->set.ip_version = va_arg(param, long);
  1453. break;
  1454. case CURLOPT_MAXFILESIZE_LARGE:
  1455. /*
  1456. * Set the maximum size of a file to download.
  1457. */
  1458. data->set.max_filesize = va_arg(param, curl_off_t);
  1459. break;
  1460. case CURLOPT_TCP_NODELAY:
  1461. /*
  1462. * Enable or disable TCP_NODELAY, which will disable/enable the Nagle
  1463. * algorithm
  1464. */
  1465. data->set.tcp_nodelay = (bool)(0 != va_arg(param, long));
  1466. break;
  1467. /*
  1468. case CURLOPT_SOURCE_URL:
  1469. case CURLOPT_SOURCE_USERPWD:
  1470. case CURLOPT_SOURCE_QUOTE:
  1471. case CURLOPT_SOURCE_PREQUOTE:
  1472. case CURLOPT_SOURCE_POSTQUOTE:
  1473. These former 3rd party transfer options are deprecated */
  1474. case CURLOPT_FTP_ACCOUNT:
  1475. data->set.ftp_account = va_arg(param, char *);
  1476. break;
  1477. case CURLOPT_IGNORE_CONTENT_LENGTH:
  1478. data->set.ignorecl = (bool)(0 != va_arg(param, long));
  1479. break;
  1480. case CURLOPT_CONNECT_ONLY:
  1481. /*
  1482. * No data transfer, set up connection and let application use the socket
  1483. */
  1484. data->set.connect_only = (bool)(0 != va_arg(param, long));
  1485. break;
  1486. case CURLOPT_FTP_ALTERNATIVE_TO_USER:
  1487. data->set.ftp_alternative_to_user = va_arg(param, char *);
  1488. break;
  1489. case CURLOPT_SOCKOPTFUNCTION:
  1490. /*
  1491. * socket callback function: called after socket() but before connect()
  1492. */
  1493. data->set.fsockopt = va_arg(param, curl_sockopt_callback);
  1494. break;
  1495. case CURLOPT_SOCKOPTDATA:
  1496. /*
  1497. * socket callback data pointer. Might be NULL.
  1498. */
  1499. data->set.sockopt_client = va_arg(param, void *);
  1500. break;
  1501. case CURLOPT_SSL_SESSIONID_CACHE:
  1502. data->set.ssl.sessionid = (bool)(0 != va_arg(param, long));
  1503. break;
  1504. case CURLOPT_SSH_AUTH_TYPES:
  1505. data->set.ssh_auth_types = va_arg(param, long);
  1506. break;
  1507. case CURLOPT_SSH_PUBLIC_KEYFILE:
  1508. /*
  1509. * Use this file instead of the $HOME/.ssh/id_dsa.pub file
  1510. */
  1511. data->set.ssh_public_key = va_arg(param, char *);
  1512. break;
  1513. case CURLOPT_SSH_PRIVATE_KEYFILE:
  1514. /*
  1515. * Use this file instead of the $HOME/.ssh/id_dsa file
  1516. */
  1517. data->set.ssh_private_key = va_arg(param, char *);
  1518. break;
  1519. default:
  1520. /* unknown tag and its companion, just ignore: */
  1521. result = CURLE_FAILED_INIT; /* correct this */
  1522. break;
  1523. }
  1524. return result;
  1525. }
  1526. static void conn_free(struct connectdata *conn)
  1527. {
  1528. if (!conn)
  1529. return;
  1530. /* close possibly still open sockets */
  1531. if(CURL_SOCKET_BAD != conn->sock[SECONDARYSOCKET])
  1532. sclose(conn->sock[SECONDARYSOCKET]);
  1533. if(CURL_SOCKET_BAD != conn->sock[FIRSTSOCKET])
  1534. sclose(conn->sock[FIRSTSOCKET]);
  1535. Curl_safefree(conn->user);
  1536. Curl_safefree(conn->passwd);
  1537. Curl_safefree(conn->proxyuser);
  1538. Curl_safefree(conn->proxypasswd);
  1539. Curl_safefree(conn->allocptr.proxyuserpwd);
  1540. Curl_safefree(conn->allocptr.uagent);
  1541. Curl_safefree(conn->allocptr.userpwd);
  1542. Curl_safefree(conn->allocptr.accept_encoding);
  1543. Curl_safefree(conn->allocptr.rangeline);
  1544. Curl_safefree(conn->allocptr.ref);
  1545. Curl_safefree(conn->allocptr.host);
  1546. Curl_safefree(conn->allocptr.cookiehost);
  1547. Curl_safefree(conn->ip_addr_str);
  1548. Curl_safefree(conn->trailer);
  1549. Curl_safefree(conn->host.rawalloc); /* host name buffer */
  1550. Curl_safefree(conn->proxy.rawalloc); /* proxy name buffer */
  1551. Curl_llist_destroy(conn->send_pipe, NULL);
  1552. Curl_llist_destroy(conn->recv_pipe, NULL);
  1553. /* possible left-overs from the async name resolvers */
  1554. #if defined(USE_ARES)
  1555. Curl_safefree(conn->async.hostname);
  1556. Curl_safefree(conn->async.os_specific);
  1557. #elif defined(CURLRES_THREADED)
  1558. Curl_destroy_thread_data(&conn->async);
  1559. #endif
  1560. Curl_free_ssl_config(&conn->ssl_config);
  1561. free(conn); /* free all the connection oriented data */
  1562. }
  1563. CURLcode Curl_disconnect(struct connectdata *conn)
  1564. {
  1565. struct SessionHandle *data;
  1566. if(!conn)
  1567. return CURLE_OK; /* this is closed and fine already */
  1568. data = conn->data;
  1569. if(!data) {
  1570. DEBUGF(infof(data, "DISCONNECT without easy handle, ignoring\n"));
  1571. return CURLE_OK;
  1572. }
  1573. #if defined(CURLDEBUG) && defined(AGGRESIVE_TEST)
  1574. /* scan for DNS cache entries still marked as in use */
  1575. Curl_hash_apply(data->hostcache,
  1576. NULL, Curl_scan_cache_used);
  1577. #endif
  1578. Curl_expire(data, 0); /* shut off timers */
  1579. Curl_hostcache_prune(data); /* kill old DNS cache entries */
  1580. /*
  1581. * The range string is usually freed in curl_done(), but we might
  1582. * get here *instead* if we fail prematurely. Thus we need to be able
  1583. * to free this resource here as well.
  1584. */
  1585. if(data->reqdata.rangestringalloc) {
  1586. free(data->reqdata.range);
  1587. data->reqdata.rangestringalloc = FALSE;
  1588. }
  1589. if((conn->ntlm.state != NTLMSTATE_NONE) ||
  1590. (conn->proxyntlm.state != NTLMSTATE_NONE)) {
  1591. /* Authentication data is a mix of connection-related and sessionhandle-
  1592. related stuff. NTLM is connection-related so when we close the shop
  1593. we shall forget. */
  1594. data->state.authhost.done = FALSE;
  1595. data->state.authhost.picked =
  1596. data->state.authhost.want;
  1597. data->state.authproxy.done = FALSE;
  1598. data->state.authproxy.picked =
  1599. data->state.authproxy.want;
  1600. data->state.authproblem = FALSE;
  1601. Curl_ntlm_cleanup(conn);
  1602. }
  1603. if(conn->curl_disconnect)
  1604. /* This is set if protocol-specific cleanups should be made */
  1605. conn->curl_disconnect(conn);
  1606. if(-1 != conn->connectindex) {
  1607. /* unlink ourselves! */
  1608. infof(data, "Closing connection #%ld\n", conn->connectindex);
  1609. if(data->state.connc)
  1610. /* only clear the table entry if we still know in which cache we
  1611. used to be in */
  1612. data->state.connc->connects[conn->connectindex] = NULL;
  1613. }
  1614. #ifdef USE_LIBIDN
  1615. if(conn->host.encalloc)
  1616. idn_free(conn->host.encalloc); /* encoded host name buffer, must be freed
  1617. with idn_free() since this was allocated
  1618. by libidn */
  1619. if(conn->proxy.encalloc)
  1620. idn_free(conn->proxy.encalloc); /* encoded proxy name buffer, must be
  1621. freed with idn_free() since this was
  1622. allocated by libidn */
  1623. #endif
  1624. Curl_ssl_close(conn);
  1625. /* Indicate to all handles on the pipe that we're dead */
  1626. if (IsPipeliningEnabled(data)) {
  1627. signalPipeClose(conn->send_pipe);
  1628. signalPipeClose(conn->recv_pipe);
  1629. }
  1630. conn_free(conn);
  1631. return CURLE_OK;
  1632. }
  1633. /*
  1634. * This function should return TRUE if the socket is to be assumed to
  1635. * be dead. Most commonly this happens when the server has closed the
  1636. * connection due to inactivity.
  1637. */
  1638. static bool SocketIsDead(curl_socket_t sock)
  1639. {
  1640. int sval;
  1641. bool ret_val = TRUE;
  1642. sval = Curl_select(sock, CURL_SOCKET_BAD, 0);
  1643. if(sval == 0)
  1644. /* timeout */
  1645. ret_val = FALSE;
  1646. return ret_val;
  1647. }
  1648. static bool IsPipeliningPossible(struct SessionHandle *handle)
  1649. {
  1650. if (handle->multi && Curl_multi_canPipeline(handle->multi) &&
  1651. (handle->set.httpreq == HTTPREQ_GET ||
  1652. handle->set.httpreq == HTTPREQ_HEAD) &&
  1653. handle->set.httpversion != CURL_HTTP_VERSION_1_0)
  1654. return TRUE;
  1655. return FALSE;
  1656. }
  1657. static bool IsPipeliningEnabled(struct SessionHandle *handle)
  1658. {
  1659. if (handle->multi && Curl_multi_canPipeline(handle->multi))
  1660. return TRUE;
  1661. return FALSE;
  1662. }
  1663. void Curl_addHandleToPipeline(struct SessionHandle *data,
  1664. struct curl_llist *pipe)
  1665. {
  1666. #ifdef CURLDEBUG
  1667. if(!IsPipeliningPossible(data)) {
  1668. /* when not pipelined, there MUST be no handle in the list already */
  1669. if(pipe->head)
  1670. infof(data, "PIPE when no PIPE supposed!\n");
  1671. }
  1672. #endif
  1673. Curl_llist_insert_next(pipe, pipe->tail, data);
  1674. }
  1675. int Curl_removeHandleFromPipeline(struct SessionHandle *handle,
  1676. struct curl_llist *pipe)
  1677. {
  1678. struct curl_llist_element *curr;
  1679. curr = pipe->head;
  1680. while (curr) {
  1681. if (curr->ptr == handle) {
  1682. Curl_llist_remove(pipe, curr, NULL);
  1683. return 1; /* we removed a handle */
  1684. }
  1685. curr = curr->next;
  1686. }
  1687. return 0;
  1688. }
  1689. #if 0 /* this code is saved here as it is useful for debugging purposes */
  1690. static void Curl_printPipeline(struct curl_llist *pipe)
  1691. {
  1692. struct curl_llist_element *curr;
  1693. curr = pipe->head;
  1694. while (curr) {
  1695. struct SessionHandle *data = (struct SessionHandle *) curr->ptr;
  1696. infof(data, "Handle in pipeline: %s\n",
  1697. data->reqdata.path);
  1698. curr = curr->next;
  1699. }
  1700. }
  1701. #endif
  1702. bool Curl_isHandleAtHead(struct SessionHandle *handle,
  1703. struct curl_llist *pipe)
  1704. {
  1705. struct curl_llist_element *curr = pipe->head;
  1706. if (curr) {
  1707. return (bool)(curr->ptr == handle);
  1708. }
  1709. return FALSE;
  1710. }
  1711. static void signalPipeClose(struct curl_llist *pipe)
  1712. {
  1713. struct curl_llist_element *curr;
  1714. curr = pipe->head;
  1715. while (curr) {
  1716. struct curl_llist_element *next = curr->next;
  1717. struct SessionHandle *data = (struct SessionHandle *) curr->ptr;
  1718. #ifdef CURLDEBUG /* debug-only code */
  1719. if(data->magic != CURLEASY_MAGIC_NUMBER) {
  1720. /* MAJOR BADNESS */
  1721. fprintf(stderr, "signalPipeClose() found BAAD easy handle\n");
  1722. }
  1723. else
  1724. #endif
  1725. data->state.pipe_broke = TRUE;
  1726. Curl_llist_remove(pipe, curr, NULL);
  1727. curr = next;
  1728. }
  1729. }
  1730. /*
  1731. * Given one filled in connection struct (named needle), this function should
  1732. * detect if there already is one that has all the significant details
  1733. * exactly the same and thus should be used instead.
  1734. *
  1735. * If there is a match, this function returns TRUE - and has marked the
  1736. * connection as 'in-use'. It must later be called with ConnectionDone() to
  1737. * return back to 'idle' (unused) state.
  1738. */
  1739. static bool
  1740. ConnectionExists(struct SessionHandle *data,
  1741. struct connectdata *needle,
  1742. struct connectdata **usethis)
  1743. {
  1744. long i;
  1745. struct connectdata *check;
  1746. bool canPipeline = IsPipeliningPossible(data);
  1747. for(i=0; i< data->state.connc->num; i++) {
  1748. bool match = FALSE;
  1749. /*
  1750. * Note that if we use a HTTP proxy, we check connections to that
  1751. * proxy and not to the actual remote server.
  1752. */
  1753. check = data->state.connc->connects[i];
  1754. if(!check)
  1755. /* NULL pointer means not filled-in entry */
  1756. continue;
  1757. if (check->connectindex == -1) {
  1758. check->connectindex = i; /* Set this appropriately since it might have
  1759. been set to -1 when the easy was removed
  1760. from the multi */
  1761. }
  1762. infof(data, "Examining connection #%ld for reuse\n", check->connectindex);
  1763. if(check->inuse && !canPipeline) {
  1764. /* can only happen within multi handles, and means that another easy
  1765. handle is using this connection */
  1766. continue;
  1767. }
  1768. #ifdef CURLRES_ASYNCH
  1769. /* ip_addr_str is NULL only if the resolving of the name hasn't completed
  1770. yet and until then we don't re-use this connection */
  1771. if (!check->ip_addr_str) {
  1772. infof(data,
  1773. "Connection #%ld has not finished name resolve, can't reuse\n",
  1774. check->connectindex);
  1775. continue;
  1776. }
  1777. #endif
  1778. if (check->send_pipe->size +
  1779. check->recv_pipe->size >= MAX_PIPELINE_LENGTH) {
  1780. infof(data, "Connection #%ld has its pipeline full, can't reuse\n",
  1781. check->connectindex);
  1782. continue;
  1783. }
  1784. if (data->state.is_in_pipeline && check->bits.close) {
  1785. /* Don't pick a connection that is going to be closed */
  1786. infof(data, "Connection #%ld has been marked for close, can't reuse\n",
  1787. check->connectindex);
  1788. continue;
  1789. }
  1790. if((needle->protocol&PROT_SSL) != (check->protocol&PROT_SSL))
  1791. /* don't do mixed SSL and non-SSL connections */
  1792. continue;
  1793. if(!needle->bits.httpproxy || needle->protocol&PROT_SSL) {
  1794. /* The requested connection does not use a HTTP proxy or it
  1795. uses SSL. */
  1796. if(!(needle->protocol&PROT_SSL) && check->bits.httpproxy)
  1797. /* we don't do SSL but the cached connection has a proxy,
  1798. then don't match this */
  1799. continue;
  1800. if(strequal(needle->protostr, check->protostr) &&
  1801. strequal(needle->host.name, check->host.name) &&
  1802. (needle->remote_port == check->remote_port) ) {
  1803. if(needle->protocol & PROT_SSL) {
  1804. /* This is SSL, verify that we're using the same
  1805. ssl options as well */
  1806. if(!Curl_ssl_config_matches(&needle->ssl_config,
  1807. &check->ssl_config)) {
  1808. infof(data,
  1809. "Connection #%ld has different SSL parameters, "
  1810. "can't reuse\n",
  1811. check->connectindex );
  1812. continue;
  1813. }
  1814. }
  1815. if((needle->protocol & PROT_FTP) ||
  1816. ((needle->protocol & PROT_HTTP) &&
  1817. (data->state.authhost.want==CURLAUTH_NTLM))) {
  1818. /* This is FTP or HTTP+NTLM, verify that we're using the same name
  1819. and password as well */
  1820. if(!strequal(needle->user, check->user) ||
  1821. !strequal(needle->passwd, check->passwd)) {
  1822. /* one of them was different */
  1823. continue;
  1824. }
  1825. }
  1826. match = TRUE;
  1827. }
  1828. }
  1829. else { /* The requested needle connection is using a proxy,
  1830. is the checked one using the same? */
  1831. if(check->bits.httpproxy &&
  1832. strequal(needle->proxy.name, check->proxy.name) &&
  1833. needle->port == check->port) {
  1834. /* This is the same proxy connection, use it! */
  1835. match = TRUE;
  1836. }
  1837. }
  1838. if(match) {
  1839. if (!IsPipeliningEnabled(data)) {
  1840. /* The check for a dead socket makes sense only in the
  1841. non-pipelining case */
  1842. bool dead = SocketIsDead(check->sock[FIRSTSOCKET]);
  1843. if(dead) {
  1844. check->data = data;
  1845. infof(data, "Connection #%d seems to be dead!\n", i);
  1846. Curl_disconnect(check); /* disconnect resources */
  1847. data->state.connc->connects[i]=NULL; /* nothing here */
  1848. return FALSE;
  1849. }
  1850. }
  1851. check->inuse = TRUE; /* mark this as being in use so that no other
  1852. handle in a multi stack may nick it */
  1853. if (canPipeline) {
  1854. /* Mark the connection as being in a pipeline */
  1855. check->is_in_pipeline = TRUE;
  1856. }
  1857. check->connectindex = i; /* Set this appropriately since it might have
  1858. been set to -1 when the easy was removed
  1859. from the multi */
  1860. *usethis = check;
  1861. return TRUE; /* yes, we found one to use! */
  1862. }
  1863. }
  1864. return FALSE; /* no matching connecting exists */
  1865. }
  1866. /*
  1867. * This function frees/closes a connection in the connection cache. This
  1868. * should take the previously set policy into account when deciding which
  1869. * of the connections to kill.
  1870. */
  1871. static long
  1872. ConnectionKillOne(struct SessionHandle *data)
  1873. {
  1874. long i;
  1875. struct connectdata *conn;
  1876. long highscore=-1;
  1877. long connindex=-1;
  1878. long score;
  1879. struct timeval now;
  1880. now = Curl_tvnow();
  1881. for(i=0; data->state.connc && (i< data->state.connc->num); i++) {
  1882. conn = data->state.connc->connects[i];
  1883. if(!conn || conn->inuse)
  1884. continue;
  1885. /* Set higher score for the age passed since the connection was used */
  1886. score = Curl_tvdiff(now, conn->now);
  1887. if(score > highscore) {
  1888. highscore = score;
  1889. connindex = i;
  1890. }
  1891. }
  1892. if(connindex >= 0) {
  1893. /* Set the connection's owner correctly */
  1894. conn = data->state.connc->connects[connindex];
  1895. conn->data = data;
  1896. /* the winner gets the honour of being disconnected */
  1897. (void)Curl_disconnect(conn);
  1898. /* clean the array entry */
  1899. data->state.connc->connects[connindex] = NULL;
  1900. }
  1901. return connindex; /* return the available index or -1 */
  1902. }
  1903. /* this connection can now be marked 'idle' */
  1904. static void
  1905. ConnectionDone(struct connectdata *conn)
  1906. {
  1907. conn->inuse = FALSE;
  1908. if (!conn->send_pipe && !conn->recv_pipe)
  1909. conn->is_in_pipeline = FALSE;
  1910. }
  1911. /*
  1912. * The given input connection struct pointer is to be stored. If the "cache"
  1913. * is already full, we must clean out the most suitable using the previously
  1914. * set policy.
  1915. *
  1916. * The given connection should be unique. That must've been checked prior to
  1917. * this call.
  1918. */
  1919. static long
  1920. ConnectionStore(struct SessionHandle *data,
  1921. struct connectdata *conn)
  1922. {
  1923. long i;
  1924. for(i=0; i< data->state.connc->num; i++) {
  1925. if(!data->state.connc->connects[i])
  1926. break;
  1927. }
  1928. if(i == data->state.connc->num) {
  1929. /* there was no room available, kill one */
  1930. i = ConnectionKillOne(data);
  1931. if(-1 != i)
  1932. infof(data, "Connection (#%d) was killed to make room (holds %d)\n",
  1933. i, data->state.connc->num);
  1934. else
  1935. infof(data, "This connection did not fit in the connection cache\n");
  1936. }
  1937. conn->connectindex = i; /* Make the child know where the pointer to this
  1938. particular data is stored. But note that this -1
  1939. if this is not within the cache and this is
  1940. probably not checked for everywhere (yet). */
  1941. conn->inuse = TRUE;
  1942. if(-1 != i) {
  1943. /* Only do this if a true index was returned, if -1 was returned there
  1944. is no room in the cache for an unknown reason and we cannot store
  1945. this there.
  1946. TODO: make sure we really can work with more handles than positions in
  1947. the cache, or possibly we should (allow to automatically) resize the
  1948. connection cache when we add more easy handles to a multi handle!
  1949. */
  1950. data->state.connc->connects[i] = conn; /* fill in this */
  1951. conn->data = data;
  1952. }
  1953. return i;
  1954. }
  1955. static CURLcode ConnectPlease(struct SessionHandle *data,
  1956. struct connectdata *conn,
  1957. struct Curl_dns_entry *hostaddr,
  1958. bool *connected)
  1959. {
  1960. CURLcode result;
  1961. Curl_addrinfo *addr;
  1962. char *hostname = conn->bits.httpproxy?conn->proxy.name:conn->host.name;
  1963. infof(data, "About to connect() to %s%s port %d (#%d)\n",
  1964. conn->bits.httpproxy?"proxy ":"",
  1965. hostname, conn->port, conn->connectindex);
  1966. /*************************************************************
  1967. * Connect to server/proxy
  1968. *************************************************************/
  1969. result= Curl_connecthost(conn,
  1970. hostaddr,
  1971. &conn->sock[FIRSTSOCKET],
  1972. &addr,
  1973. connected);
  1974. if(CURLE_OK == result) {
  1975. /* All is cool, then we store the current information */
  1976. conn->dns_entry = hostaddr;
  1977. conn->ip_addr = addr;
  1978. Curl_store_ip_addr(conn);
  1979. switch(data->set.proxytype) {
  1980. case CURLPROXY_SOCKS5:
  1981. result = Curl_SOCKS5(conn->proxyuser, conn->proxypasswd, conn);
  1982. break;
  1983. case CURLPROXY_HTTP:
  1984. /* do nothing here. handled later. */
  1985. break;
  1986. case CURLPROXY_SOCKS4:
  1987. result = Curl_SOCKS4(conn->proxyuser, conn);
  1988. break;
  1989. default:
  1990. failf(data, "unknown proxytype option given");
  1991. result = CURLE_COULDNT_CONNECT;
  1992. break;
  1993. }
  1994. }
  1995. return result;
  1996. }
  1997. /*
  1998. * verboseconnect() displays verbose information after a connect
  1999. */
  2000. static void verboseconnect(struct connectdata *conn)
  2001. {
  2002. infof(conn->data, "Connected to %s (%s) port %d (#%d)\n",
  2003. conn->bits.httpproxy ? conn->proxy.dispname : conn->host.dispname,
  2004. conn->ip_addr_str, conn->port, conn->connectindex);
  2005. }
  2006. int Curl_protocol_getsock(struct connectdata *conn,
  2007. curl_socket_t *socks,
  2008. int numsocks)
  2009. {
  2010. if(conn->curl_proto_getsock)
  2011. return conn->curl_proto_getsock(conn, socks, numsocks);
  2012. return GETSOCK_BLANK;
  2013. }
  2014. int Curl_doing_getsock(struct connectdata *conn,
  2015. curl_socket_t *socks,
  2016. int numsocks)
  2017. {
  2018. if(conn && conn->curl_doing_getsock)
  2019. return conn->curl_doing_getsock(conn, socks, numsocks);
  2020. return GETSOCK_BLANK;
  2021. }
  2022. /*
  2023. * We are doing protocol-specific connecting and this is being called over and
  2024. * over from the multi interface until the connection phase is done on
  2025. * protocol layer.
  2026. */
  2027. CURLcode Curl_protocol_connecting(struct connectdata *conn,
  2028. bool *done)
  2029. {
  2030. CURLcode result=CURLE_OK;
  2031. if(conn && conn->curl_connecting) {
  2032. *done = FALSE;
  2033. result = conn->curl_connecting(conn, done);
  2034. }
  2035. else
  2036. *done = TRUE;
  2037. return result;
  2038. }
  2039. /*
  2040. * We are DOING this is being called over and over from the multi interface
  2041. * until the DOING phase is done on protocol layer.
  2042. */
  2043. CURLcode Curl_protocol_doing(struct connectdata *conn, bool *done)
  2044. {
  2045. CURLcode result=CURLE_OK;
  2046. if(conn && conn->curl_doing) {
  2047. *done = FALSE;
  2048. result = conn->curl_doing(conn, done);
  2049. }
  2050. else
  2051. *done = TRUE;
  2052. return result;
  2053. }
  2054. /*
  2055. * We have discovered that the TCP connection has been successful, we can now
  2056. * proceed with some action.
  2057. *
  2058. */
  2059. CURLcode Curl_protocol_connect(struct connectdata *conn,
  2060. bool *protocol_done)
  2061. {
  2062. CURLcode result=CURLE_OK;
  2063. struct SessionHandle *data = conn->data;
  2064. *protocol_done = FALSE;
  2065. if(conn->bits.tcpconnect && conn->bits.protoconnstart) {
  2066. /* We already are connected, get back. This may happen when the connect
  2067. worked fine in the first call, like when we connect to a local server
  2068. or proxy. Note that we don't know if the protocol is actually done.
  2069. Unless this protocol doesn't have any protocol-connect callback, as
  2070. then we know we're done. */
  2071. if(!conn->curl_connecting)
  2072. *protocol_done = TRUE;
  2073. return CURLE_OK;
  2074. }
  2075. if(!conn->bits.tcpconnect) {
  2076. Curl_pgrsTime(data, TIMER_CONNECT); /* connect done */
  2077. if(data->set.verbose)
  2078. verboseconnect(conn);
  2079. }
  2080. if(!conn->bits.protoconnstart) {
  2081. if(conn->curl_connect) {
  2082. /* is there a protocol-specific connect() procedure? */
  2083. /* Set start time here for timeout purposes in the connect procedure, it
  2084. is later set again for the progress meter purpose */
  2085. conn->now = Curl_tvnow();
  2086. /* Call the protocol-specific connect function */
  2087. result = conn->curl_connect(conn, protocol_done);
  2088. }
  2089. else
  2090. *protocol_done = TRUE;
  2091. /* it has started, possibly even completed but that knowledge isn't stored
  2092. in this bit! */
  2093. if (!result)
  2094. conn->bits.protoconnstart = TRUE;
  2095. }
  2096. return result; /* pass back status */
  2097. }
  2098. /*
  2099. * Helpers for IDNA convertions.
  2100. */
  2101. #ifdef USE_LIBIDN
  2102. static bool is_ASCII_name(const char *hostname)
  2103. {
  2104. const unsigned char *ch = (const unsigned char*)hostname;
  2105. while (*ch) {
  2106. if (*ch++ & 0x80)
  2107. return FALSE;
  2108. }
  2109. return TRUE;
  2110. }
  2111. /*
  2112. * Check if characters in hostname is allowed in Top Level Domain.
  2113. */
  2114. static bool tld_check_name(struct SessionHandle *data,
  2115. const char *ace_hostname)
  2116. {
  2117. size_t err_pos;
  2118. char *uc_name = NULL;
  2119. int rc;
  2120. /* Convert (and downcase) ACE-name back into locale's character set */
  2121. rc = idna_to_unicode_lzlz(ace_hostname, &uc_name, 0);
  2122. if (rc != IDNA_SUCCESS)
  2123. return (FALSE);
  2124. rc = tld_check_lz(uc_name, &err_pos, NULL);
  2125. if (rc == TLD_INVALID)
  2126. infof(data, "WARNING: %s; pos %u = `%c'/0x%02X\n",
  2127. #ifdef HAVE_TLD_STRERROR
  2128. tld_strerror((Tld_rc)rc),
  2129. #else
  2130. "<no msg>",
  2131. #endif
  2132. err_pos, uc_name[err_pos],
  2133. uc_name[err_pos] & 255);
  2134. else if (rc != TLD_SUCCESS)
  2135. infof(data, "WARNING: TLD check for %s failed; %s\n",
  2136. uc_name,
  2137. #ifdef HAVE_TLD_STRERROR
  2138. tld_strerror((Tld_rc)rc)
  2139. #else
  2140. "<no msg>"
  2141. #endif
  2142. );
  2143. if (uc_name)
  2144. idn_free(uc_name);
  2145. return (bool)(rc == TLD_SUCCESS);
  2146. }
  2147. #endif
  2148. static void fix_hostname(struct SessionHandle *data,
  2149. struct connectdata *conn, struct hostname *host)
  2150. {
  2151. /* set the name we use to display the host name */
  2152. host->dispname = host->name;
  2153. #ifdef USE_LIBIDN
  2154. /*************************************************************
  2155. * Check name for non-ASCII and convert hostname to ACE form.
  2156. *************************************************************/
  2157. if (!is_ASCII_name(host->name) &&
  2158. stringprep_check_version(LIBIDN_REQUIRED_VERSION)) {
  2159. char *ace_hostname = NULL;
  2160. int rc = idna_to_ascii_lz(host->name, &ace_hostname, 0);
  2161. infof (data, "Input domain encoded as `%s'\n",
  2162. stringprep_locale_charset ());
  2163. if (rc != IDNA_SUCCESS)
  2164. infof(data, "Failed to convert %s to ACE; %s\n",
  2165. host->name, Curl_idn_strerror(conn,rc));
  2166. else {
  2167. /* tld_check_name() displays a warning if the host name contains
  2168. "illegal" characters for this TLD */
  2169. (void)tld_check_name(data, ace_hostname);
  2170. host->encalloc = ace_hostname;
  2171. /* change the name pointer to point to the encoded hostname */
  2172. host->name = host->encalloc;
  2173. }
  2174. }
  2175. #else
  2176. (void)data; /* never used */
  2177. (void)conn; /* never used */
  2178. #endif
  2179. }
  2180. /*
  2181. * Parse URL and fill in the relevant members of the connection struct.
  2182. */
  2183. static CURLcode ParseURLAndFillConnection(struct SessionHandle *data,
  2184. struct connectdata *conn)
  2185. {
  2186. char *at;
  2187. char *tmp;
  2188. char *path = data->reqdata.path;
  2189. /*************************************************************
  2190. * Parse the URL.
  2191. *
  2192. * We need to parse the url even when using the proxy, because we will need
  2193. * the hostname and port in case we are trying to SSL connect through the
  2194. * proxy -- and we don't know if we will need to use SSL until we parse the
  2195. * url ...
  2196. ************************************************************/
  2197. if((2 == sscanf(data->change.url, "%15[^:]:%[^\n]",
  2198. conn->protostr,
  2199. path)) && strequal(conn->protostr, "file")) {
  2200. if(path[0] == '/' && path[1] == '/') {
  2201. /* Allow omitted hostname (e.g. file:/<path>). This is not strictly
  2202. * speaking a valid file: URL by RFC 1738, but treating file:/<path> as
  2203. * file://localhost/<path> is similar to how other schemes treat missing
  2204. * hostnames. See RFC 1808. */
  2205. /* This cannot be done with strcpy() in a portable manner, since the
  2206. memory areas overlap! */
  2207. memmove(path, path + 2, strlen(path + 2)+1);
  2208. }
  2209. /*
  2210. * we deal with file://<host>/<path> differently since it supports no
  2211. * hostname other than "localhost" and "127.0.0.1", which is unique among
  2212. * the URL protocols specified in RFC 1738
  2213. */
  2214. if(path[0] != '/') {
  2215. /* the URL included a host name, we ignore host names in file:// URLs
  2216. as the standards don't define what to do with them */
  2217. char *ptr=strchr(path, '/');
  2218. if(ptr) {
  2219. /* there was a slash present
  2220. RFC1738 (section 3.1, page 5) says:
  2221. The rest of the locator consists of data specific to the scheme,
  2222. and is known as the "url-path". It supplies the details of how the
  2223. specified resource can be accessed. Note that the "/" between the
  2224. host (or port) and the url-path is NOT part of the url-path.
  2225. As most agents use file://localhost/foo to get '/foo' although the
  2226. slash preceding foo is a separator and not a slash for the path,
  2227. a URL as file://localhost//foo must be valid as well, to refer to
  2228. the same file with an absolute path.
  2229. */
  2230. if(ptr[1] && ('/' == ptr[1]))
  2231. /* if there was two slashes, we skip the first one as that is then
  2232. used truly as a separator */
  2233. ptr++;
  2234. /* This cannot be made with strcpy, as the memory chunks overlap! */
  2235. memmove(path, ptr, strlen(ptr)+1);
  2236. }
  2237. }
  2238. strcpy(conn->protostr, "file"); /* store protocol string lowercase */
  2239. }
  2240. else {
  2241. /* clear path */
  2242. path[0]=0;
  2243. if (2 > sscanf(data->change.url,
  2244. "%15[^\n:]://%[^\n/]%[^\n]",
  2245. conn->protostr,
  2246. conn->host.name, path)) {
  2247. /*
  2248. * The URL was badly formatted, let's try the browser-style _without_
  2249. * protocol specified like 'http://'.
  2250. */
  2251. if((1 > sscanf(data->change.url, "%[^\n/]%[^\n]",
  2252. conn->host.name, path)) ) {
  2253. /*
  2254. * We couldn't even get this format.
  2255. */
  2256. failf(data, "<url> malformed");
  2257. return CURLE_URL_MALFORMAT;
  2258. }
  2259. /*
  2260. * Since there was no protocol part specified, we guess what protocol it
  2261. * is based on the first letters of the server name.
  2262. */
  2263. /* Note: if you add a new protocol, please update the list in
  2264. * lib/version.c too! */
  2265. if(checkprefix("FTP.", conn->host.name))
  2266. strcpy(conn->protostr, "ftp");
  2267. else if (checkprefix("DICT.", conn->host.name))
  2268. strcpy(conn->protostr, "DICT");
  2269. else if (checkprefix("LDAP.", conn->host.name))
  2270. strcpy(conn->protostr, "LDAP");
  2271. else {
  2272. strcpy(conn->protostr, "http");
  2273. }
  2274. conn->protocol |= PROT_MISSING; /* not given in URL */
  2275. }
  2276. }
  2277. /* We search for '?' in the host name (but only on the right side of a
  2278. * @-letter to allow ?-letters in username and password) to handle things
  2279. * like http://example.com?param= (notice the missing '/').
  2280. */
  2281. at = strchr(conn->host.name, '@');
  2282. if(at)
  2283. tmp = strchr(at+1, '?');
  2284. else
  2285. tmp = strchr(conn->host.name, '?');
  2286. if(tmp) {
  2287. /* We must insert a slash before the '?'-letter in the URL. If the URL had
  2288. a slash after the '?', that is where the path currently begins and the
  2289. '?string' is still part of the host name.
  2290. We must move the trailing part from the host name and put it first in
  2291. the path. And have it all prefixed with a slash.
  2292. */
  2293. size_t hostlen = strlen(tmp);
  2294. size_t pathlen = strlen(path);
  2295. /* move the existing path plus the zero byte forward, to make room for
  2296. the host-name part */
  2297. memmove(path+hostlen+1, path, pathlen+1);
  2298. /* now copy the trailing host part in front of the existing path */
  2299. memcpy(path+1, tmp, hostlen);
  2300. path[0]='/'; /* prepend the missing slash */
  2301. *tmp=0; /* now cut off the hostname at the ? */
  2302. }
  2303. else if(!path[0]) {
  2304. /* if there's no path set, use a single slash */
  2305. strcpy(path, "/");
  2306. }
  2307. /* If the URL is malformatted (missing a '/' after hostname before path) we
  2308. * insert a slash here. The only letter except '/' we accept to start a path
  2309. * is '?'.
  2310. */
  2311. if(path[0] == '?') {
  2312. /* We need this function to deal with overlapping memory areas. We know
  2313. that the memory area 'path' points to is 'urllen' bytes big and that
  2314. is bigger than the path. Use +1 to move the zero byte too. */
  2315. memmove(&path[1], path, strlen(path)+1);
  2316. path[0] = '/';
  2317. }
  2318. /*
  2319. * So if the URL was A://B/C,
  2320. * conn->protostr is A
  2321. * conn->host.name is B
  2322. * data->reqdata.path is /C
  2323. */
  2324. return CURLE_OK;
  2325. }
  2326. static void llist_dtor(void *user, void *element)
  2327. {
  2328. (void)user;
  2329. (void)element;
  2330. /* Do nothing */
  2331. }
  2332. /**
  2333. * CreateConnection() sets up a new connectdata struct, or re-uses an already
  2334. * existing one, and resolves host name.
  2335. *
  2336. * if this function returns CURLE_OK and *async is set to TRUE, the resolve
  2337. * response will be coming asynchronously. If *async is FALSE, the name is
  2338. * already resolved.
  2339. *
  2340. * @param data The sessionhandle pointer
  2341. * @param in_connect is set to the next connection data pointer
  2342. * @param addr is set to the new dns entry for this connection. If this
  2343. * connection is re-used it will be NULL.
  2344. * @param async is set TRUE/FALSE depending on the nature of this lookup
  2345. * @return CURLcode
  2346. * @see SetupConnection()
  2347. *
  2348. * *NOTE* this function assigns the conn->data pointer!
  2349. */
  2350. static CURLcode CreateConnection(struct SessionHandle *data,
  2351. struct connectdata **in_connect,
  2352. struct Curl_dns_entry **addr,
  2353. bool *async)
  2354. {
  2355. char *tmp;
  2356. CURLcode result=CURLE_OK;
  2357. struct connectdata *conn;
  2358. struct connectdata *conn_temp = NULL;
  2359. size_t urllen;
  2360. struct Curl_dns_entry *hostaddr;
  2361. #if defined(HAVE_ALARM) && !defined(USE_ARES)
  2362. unsigned int prev_alarm=0;
  2363. #endif
  2364. char endbracket;
  2365. char user[MAX_CURL_USER_LENGTH];
  2366. char passwd[MAX_CURL_PASSWORD_LENGTH];
  2367. int rc;
  2368. bool reuse;
  2369. char *proxy;
  2370. bool proxy_alloc = FALSE;
  2371. #ifndef USE_ARES
  2372. #ifdef SIGALRM
  2373. #ifdef HAVE_SIGACTION
  2374. struct sigaction keep_sigact; /* store the old struct here */
  2375. bool keep_copysig=FALSE; /* did copy it? */
  2376. #else
  2377. #ifdef HAVE_SIGNAL
  2378. void (*keep_sigact)(int); /* store the old handler here */
  2379. #endif /* HAVE_SIGNAL */
  2380. #endif /* HAVE_SIGACTION */
  2381. #endif /* SIGALRM */
  2382. #endif /* USE_ARES */
  2383. *addr = NULL; /* nothing yet */
  2384. *async = FALSE;
  2385. /*************************************************************
  2386. * Check input data
  2387. *************************************************************/
  2388. if(!data->change.url)
  2389. return CURLE_URL_MALFORMAT;
  2390. /* First, split up the current URL in parts so that we can use the
  2391. parts for checking against the already present connections. In order
  2392. to not have to modify everything at once, we allocate a temporary
  2393. connection data struct and fill in for comparison purposes. */
  2394. conn = (struct connectdata *)calloc(sizeof(struct connectdata), 1);
  2395. if(!conn) {
  2396. *in_connect = NULL; /* clear the pointer */
  2397. return CURLE_OUT_OF_MEMORY;
  2398. }
  2399. /* We must set the return variable as soon as possible, so that our
  2400. parent can cleanup any possible allocs we may have done before
  2401. any failure */
  2402. *in_connect = conn;
  2403. /* and we setup a few fields in case we end up actually using this struct */
  2404. conn->data = data; /* Setup the association between this connection
  2405. and the SessionHandle */
  2406. conn->sock[FIRSTSOCKET] = CURL_SOCKET_BAD; /* no file descriptor */
  2407. conn->sock[SECONDARYSOCKET] = CURL_SOCKET_BAD; /* no file descriptor */
  2408. conn->connectindex = -1; /* no index */
  2409. conn->bits.httpproxy = (bool)(data->set.proxy /* http proxy or not */
  2410. && *data->set.proxy
  2411. && (data->set.proxytype == CURLPROXY_HTTP));
  2412. proxy = data->set.proxy; /* if global proxy is set, this is it */
  2413. /* Default protocol-independent behavior doesn't support persistent
  2414. connections, so we set this to force-close. Protocols that support
  2415. this need to set this to FALSE in their "curl_do" functions. */
  2416. conn->bits.close = TRUE;
  2417. conn->readchannel_inuse = FALSE;
  2418. conn->writechannel_inuse = FALSE;
  2419. conn->read_pos = 0;
  2420. conn->buf_len = 0;
  2421. /* Initialize the pipeline lists */
  2422. conn->send_pipe = Curl_llist_alloc((curl_llist_dtor) llist_dtor);
  2423. conn->recv_pipe = Curl_llist_alloc((curl_llist_dtor) llist_dtor);
  2424. /* Store creation time to help future close decision making */
  2425. conn->created = Curl_tvnow();
  2426. /* range status */
  2427. data->reqdata.use_range = (bool)(NULL != data->set.set_range);
  2428. data->reqdata.range = data->set.set_range; /* clone the range setting */
  2429. data->reqdata.resume_from = data->set.set_resume_from;
  2430. conn->bits.user_passwd = (bool)(NULL != data->set.userpwd);
  2431. conn->bits.proxy_user_passwd = (bool)(NULL != data->set.proxyuserpwd);
  2432. conn->bits.no_body = data->set.opt_no_body;
  2433. conn->bits.tunnel_proxy = data->set.tunnel_thru_httpproxy;
  2434. conn->bits.ftp_use_epsv = data->set.ftp_use_epsv;
  2435. conn->bits.ftp_use_eprt = data->set.ftp_use_eprt;
  2436. /* This initing continues below, see the comment "Continue connectdata
  2437. * initialization here" */
  2438. /***********************************************************
  2439. * We need to allocate memory to store the path in. We get the size of the
  2440. * full URL to be sure, and we need to make it at least 256 bytes since
  2441. * other parts of the code will rely on this fact
  2442. ***********************************************************/
  2443. #define LEAST_PATH_ALLOC 256
  2444. urllen=strlen(data->change.url);
  2445. if(urllen < LEAST_PATH_ALLOC)
  2446. urllen=LEAST_PATH_ALLOC;
  2447. if (!data->set.source_url /* 3rd party FTP */
  2448. && data->reqdata.pathbuffer) {
  2449. /* Free the old buffer */
  2450. free(data->reqdata.pathbuffer);
  2451. }
  2452. /*
  2453. * We malloc() the buffers below urllen+2 to make room for to possibilities:
  2454. * 1 - an extra terminating zero
  2455. * 2 - an extra slash (in case a syntax like "www.host.com?moo" is used)
  2456. */
  2457. data->reqdata.pathbuffer=(char *)malloc(urllen+2);
  2458. if(NULL == data->reqdata.pathbuffer)
  2459. return CURLE_OUT_OF_MEMORY; /* really bad error */
  2460. data->reqdata.path = data->reqdata.pathbuffer;
  2461. conn->host.rawalloc=(char *)malloc(urllen+2);
  2462. if(NULL == conn->host.rawalloc)
  2463. return CURLE_OUT_OF_MEMORY;
  2464. conn->host.name = conn->host.rawalloc;
  2465. conn->host.name[0] = 0;
  2466. result = ParseURLAndFillConnection(data, conn);
  2467. if (result != CURLE_OK) {
  2468. return result;
  2469. }
  2470. /*************************************************************
  2471. * Take care of proxy authentication stuff
  2472. *************************************************************/
  2473. if(conn->bits.proxy_user_passwd) {
  2474. char proxyuser[MAX_CURL_USER_LENGTH]="";
  2475. char proxypasswd[MAX_CURL_PASSWORD_LENGTH]="";
  2476. sscanf(data->set.proxyuserpwd,
  2477. "%" MAX_CURL_USER_LENGTH_TXT "[^:]:"
  2478. "%" MAX_CURL_PASSWORD_LENGTH_TXT "[^\n]",
  2479. proxyuser, proxypasswd);
  2480. conn->proxyuser = curl_easy_unescape(data, proxyuser, 0, NULL);
  2481. if(!conn->proxyuser)
  2482. return CURLE_OUT_OF_MEMORY;
  2483. conn->proxypasswd = curl_easy_unescape(data, proxypasswd, 0, NULL);
  2484. if(!conn->proxypasswd)
  2485. return CURLE_OUT_OF_MEMORY;
  2486. }
  2487. #ifndef CURL_DISABLE_HTTP
  2488. /*************************************************************
  2489. * Detect what (if any) proxy to use
  2490. *************************************************************/
  2491. if(!conn->bits.httpproxy) {
  2492. /* If proxy was not specified, we check for default proxy environment
  2493. * variables, to enable i.e Lynx compliance:
  2494. *
  2495. * http_proxy=http://some.server.dom:port/
  2496. * https_proxy=http://some.server.dom:port/
  2497. * ftp_proxy=http://some.server.dom:port/
  2498. * no_proxy=domain1.dom,host.domain2.dom
  2499. * (a comma-separated list of hosts which should
  2500. * not be proxied, or an asterisk to override
  2501. * all proxy variables)
  2502. * all_proxy=http://some.server.dom:port/
  2503. * (seems to exist for the CERN www lib. Probably
  2504. * the first to check for.)
  2505. *
  2506. * For compatibility, the all-uppercase versions of these variables are
  2507. * checked if the lowercase versions don't exist.
  2508. */
  2509. char *no_proxy=NULL;
  2510. char *no_proxy_tok_buf;
  2511. char proxy_env[128];
  2512. no_proxy=curl_getenv("no_proxy");
  2513. if(!no_proxy)
  2514. no_proxy=curl_getenv("NO_PROXY");
  2515. if(!no_proxy || !strequal("*", no_proxy)) {
  2516. /* NO_PROXY wasn't specified or it wasn't just an asterisk */
  2517. char *nope;
  2518. nope=no_proxy?strtok_r(no_proxy, ", ", &no_proxy_tok_buf):NULL;
  2519. while(nope) {
  2520. size_t namelen;
  2521. char *endptr = strchr(conn->host.name, ':');
  2522. if(endptr)
  2523. namelen=endptr-conn->host.name;
  2524. else
  2525. namelen=strlen(conn->host.name);
  2526. if(strlen(nope) <= namelen) {
  2527. char *checkn=
  2528. conn->host.name + namelen - strlen(nope);
  2529. if(checkprefix(nope, checkn)) {
  2530. /* no proxy for this host! */
  2531. break;
  2532. }
  2533. }
  2534. nope=strtok_r(NULL, ", ", &no_proxy_tok_buf);
  2535. }
  2536. if(!nope) {
  2537. /* It was not listed as without proxy */
  2538. char *protop = conn->protostr;
  2539. char *envp = proxy_env;
  2540. char *prox;
  2541. /* Now, build <protocol>_proxy and check for such a one to use */
  2542. while(*protop)
  2543. *envp++ = (char)tolower((int)*protop++);
  2544. /* append _proxy */
  2545. strcpy(envp, "_proxy");
  2546. /* read the protocol proxy: */
  2547. prox=curl_getenv(proxy_env);
  2548. /*
  2549. * We don't try the uppercase version of HTTP_PROXY because of
  2550. * security reasons:
  2551. *
  2552. * When curl is used in a webserver application
  2553. * environment (cgi or php), this environment variable can
  2554. * be controlled by the web server user by setting the
  2555. * http header 'Proxy:' to some value.
  2556. *
  2557. * This can cause 'internal' http/ftp requests to be
  2558. * arbitrarily redirected by any external attacker.
  2559. */
  2560. if(!prox && !strequal("http_proxy", proxy_env)) {
  2561. /* There was no lowercase variable, try the uppercase version: */
  2562. for(envp = proxy_env; *envp; envp++)
  2563. *envp = (char)toupper((int)*envp);
  2564. prox=curl_getenv(proxy_env);
  2565. }
  2566. if(prox && *prox) { /* don't count "" strings */
  2567. proxy = prox; /* use this */
  2568. }
  2569. else {
  2570. proxy = curl_getenv("all_proxy"); /* default proxy to use */
  2571. if(!proxy)
  2572. proxy=curl_getenv("ALL_PROXY");
  2573. }
  2574. if(proxy && *proxy) {
  2575. long bits = conn->protocol & (PROT_HTTPS|PROT_SSL|PROT_MISSING);
  2576. /* force this to become HTTP */
  2577. conn->protocol = PROT_HTTP | bits;
  2578. proxy_alloc=TRUE; /* this needs to be freed later */
  2579. conn->bits.httpproxy = TRUE;
  2580. }
  2581. } /* if (!nope) - it wasn't specified non-proxy */
  2582. } /* NO_PROXY wasn't specified or '*' */
  2583. if(no_proxy)
  2584. free(no_proxy);
  2585. } /* if not using proxy */
  2586. #endif /* CURL_DISABLE_HTTP */
  2587. /*************************************************************
  2588. * No protocol part in URL was used, add it!
  2589. *************************************************************/
  2590. if(conn->protocol&PROT_MISSING) {
  2591. /* We're guessing prefixes here and if we're told to use a proxy or if
  2592. we're gonna follow a Location: later or... then we need the protocol
  2593. part added so that we have a valid URL. */
  2594. char *reurl;
  2595. reurl = aprintf("%s://%s", conn->protostr, data->change.url);
  2596. if(!reurl)
  2597. return CURLE_OUT_OF_MEMORY;
  2598. data->change.url = reurl;
  2599. data->change.url_alloc = TRUE; /* free this later */
  2600. conn->protocol &= ~PROT_MISSING; /* switch that one off again */
  2601. }
  2602. #ifndef CURL_DISABLE_HTTP
  2603. /************************************************************
  2604. * RESUME on a HTTP page is a tricky business. First, let's just check that
  2605. * 'range' isn't used, then set the range parameter and leave the resume as
  2606. * it is to inform about this situation for later use. We will then
  2607. * "attempt" to resume, and if we're talking to a HTTP/1.1 (or later)
  2608. * server, we will get the document resumed. If we talk to a HTTP/1.0
  2609. * server, we just fail since we can't rewind the file writing from within
  2610. * this function.
  2611. ***********************************************************/
  2612. if(data->reqdata.resume_from) {
  2613. if(!data->reqdata.use_range) {
  2614. /* if it already was in use, we just skip this */
  2615. data->reqdata.range = aprintf("%" FORMAT_OFF_T "-", data->reqdata.resume_from);
  2616. if(!data->reqdata.range)
  2617. return CURLE_OUT_OF_MEMORY;
  2618. data->reqdata.rangestringalloc = TRUE; /* mark as allocated */
  2619. data->reqdata.use_range = 1; /* switch on range usage */
  2620. }
  2621. }
  2622. #endif
  2623. /*************************************************************
  2624. * Setup internals depending on protocol
  2625. *************************************************************/
  2626. conn->socktype = SOCK_STREAM; /* most of them are TCP streams */
  2627. if (strequal(conn->protostr, "HTTP")) {
  2628. #ifndef CURL_DISABLE_HTTP
  2629. conn->port = PORT_HTTP;
  2630. conn->remote_port = PORT_HTTP;
  2631. conn->protocol |= PROT_HTTP;
  2632. conn->curl_do = Curl_http;
  2633. conn->curl_do_more = (Curl_do_more_func)ZERO_NULL;
  2634. conn->curl_done = Curl_http_done;
  2635. conn->curl_connect = Curl_http_connect;
  2636. #else
  2637. failf(data, LIBCURL_NAME
  2638. " was built with HTTP disabled, http: not supported!");
  2639. return CURLE_UNSUPPORTED_PROTOCOL;
  2640. #endif
  2641. }
  2642. else if (strequal(conn->protostr, "HTTPS")) {
  2643. #if defined(USE_SSL) && !defined(CURL_DISABLE_HTTP)
  2644. conn->port = PORT_HTTPS;
  2645. conn->remote_port = PORT_HTTPS;
  2646. conn->protocol |= PROT_HTTP|PROT_HTTPS|PROT_SSL;
  2647. conn->curl_do = Curl_http;
  2648. conn->curl_do_more = (Curl_do_more_func)ZERO_NULL;
  2649. conn->curl_done = Curl_http_done;
  2650. conn->curl_connect = Curl_http_connect;
  2651. conn->curl_connecting = Curl_https_connecting;
  2652. conn->curl_proto_getsock = Curl_https_getsock;
  2653. #else /* USE_SSL */
  2654. failf(data, LIBCURL_NAME
  2655. " was built with SSL disabled, https: not supported!");
  2656. return CURLE_UNSUPPORTED_PROTOCOL;
  2657. #endif /* !USE_SSL */
  2658. }
  2659. else if(strequal(conn->protostr, "FTP") ||
  2660. strequal(conn->protostr, "FTPS")) {
  2661. #ifndef CURL_DISABLE_FTP
  2662. char *type;
  2663. int port = PORT_FTP;
  2664. if(strequal(conn->protostr, "FTPS")) {
  2665. #ifdef USE_SSL
  2666. conn->protocol |= PROT_FTPS|PROT_SSL;
  2667. conn->ssl[SECONDARYSOCKET].use = TRUE; /* send data securely */
  2668. port = PORT_FTPS;
  2669. #else
  2670. failf(data, LIBCURL_NAME
  2671. " was built with SSL disabled, ftps: not supported!");
  2672. return CURLE_UNSUPPORTED_PROTOCOL;
  2673. #endif /* !USE_SSL */
  2674. }
  2675. conn->port = port;
  2676. conn->remote_port = (unsigned short)port;
  2677. conn->protocol |= PROT_FTP;
  2678. if(proxy && *proxy && !data->set.tunnel_thru_httpproxy) {
  2679. /* Unless we have asked to tunnel ftp operations through the proxy, we
  2680. switch and use HTTP operations only */
  2681. #ifndef CURL_DISABLE_HTTP
  2682. conn->curl_do = Curl_http;
  2683. conn->curl_done = Curl_http_done;
  2684. conn->protocol = PROT_HTTP; /* switch to HTTP */
  2685. #else
  2686. failf(data, "FTP over http proxy requires HTTP support built-in!");
  2687. return CURLE_UNSUPPORTED_PROTOCOL;
  2688. #endif
  2689. }
  2690. else {
  2691. conn->curl_do = Curl_ftp;
  2692. conn->curl_do_more = Curl_ftp_nextconnect;
  2693. conn->curl_done = Curl_ftp_done;
  2694. conn->curl_connect = Curl_ftp_connect;
  2695. conn->curl_connecting = Curl_ftp_multi_statemach;
  2696. conn->curl_doing = Curl_ftp_doing;
  2697. conn->curl_proto_getsock = Curl_ftp_getsock;
  2698. conn->curl_doing_getsock = Curl_ftp_getsock;
  2699. conn->curl_disconnect = Curl_ftp_disconnect;
  2700. }
  2701. data->reqdata.path++; /* don't include the initial slash */
  2702. /* FTP URLs support an extension like ";type=<typecode>" that
  2703. * we'll try to get now! */
  2704. type=strstr(data->reqdata.path, ";type=");
  2705. if(!type) {
  2706. type=strstr(conn->host.rawalloc, ";type=");
  2707. }
  2708. if(type) {
  2709. char command;
  2710. *type=0; /* it was in the middle of the hostname */
  2711. command = (char)toupper((int)type[6]);
  2712. switch(command) {
  2713. case 'A': /* ASCII mode */
  2714. data->set.prefer_ascii = TRUE;
  2715. break;
  2716. case 'D': /* directory mode */
  2717. data->set.ftp_list_only = TRUE;
  2718. break;
  2719. case 'I': /* binary mode */
  2720. default:
  2721. /* switch off ASCII */
  2722. data->set.prefer_ascii = FALSE;
  2723. break;
  2724. }
  2725. }
  2726. #else /* CURL_DISABLE_FTP */
  2727. failf(data, LIBCURL_NAME
  2728. " was built with FTP disabled, ftp/ftps: not supported!");
  2729. return CURLE_UNSUPPORTED_PROTOCOL;
  2730. #endif
  2731. }
  2732. else if(strequal(conn->protostr, "TELNET")) {
  2733. #ifndef CURL_DISABLE_TELNET
  2734. /* telnet testing factory */
  2735. conn->protocol |= PROT_TELNET;
  2736. conn->port = PORT_TELNET;
  2737. conn->remote_port = PORT_TELNET;
  2738. conn->curl_do = Curl_telnet;
  2739. conn->curl_done = Curl_telnet_done;
  2740. #else
  2741. failf(data, LIBCURL_NAME
  2742. " was built with TELNET disabled!");
  2743. #endif
  2744. }
  2745. else if (strequal(conn->protostr, "DICT")) {
  2746. #ifndef CURL_DISABLE_DICT
  2747. conn->protocol |= PROT_DICT;
  2748. conn->port = PORT_DICT;
  2749. conn->remote_port = PORT_DICT;
  2750. conn->curl_do = Curl_dict;
  2751. /* no DICT-specific done */
  2752. conn->curl_done = (Curl_done_func)ZERO_NULL;
  2753. #else
  2754. failf(data, LIBCURL_NAME
  2755. " was built with DICT disabled!");
  2756. #endif
  2757. }
  2758. else if (strequal(conn->protostr, "LDAP")) {
  2759. #ifndef CURL_DISABLE_LDAP
  2760. conn->protocol |= PROT_LDAP;
  2761. conn->port = PORT_LDAP;
  2762. conn->remote_port = PORT_LDAP;
  2763. conn->curl_do = Curl_ldap;
  2764. /* no LDAP-specific done */
  2765. conn->curl_done = (Curl_done_func)ZERO_NULL;
  2766. #else
  2767. failf(data, LIBCURL_NAME
  2768. " was built with LDAP disabled!");
  2769. #endif
  2770. }
  2771. else if (strequal(conn->protostr, "FILE")) {
  2772. #ifndef CURL_DISABLE_FILE
  2773. conn->protocol |= PROT_FILE;
  2774. conn->curl_do = Curl_file;
  2775. conn->curl_done = Curl_file_done;
  2776. /* anyway, this is supposed to be the connect function so we better
  2777. at least check that the file is present here! */
  2778. result = Curl_file_connect(conn);
  2779. /* Setup a "faked" transfer that'll do nothing */
  2780. if(CURLE_OK == result) {
  2781. conn->data = data;
  2782. conn->bits.tcpconnect = TRUE; /* we are "connected */
  2783. ConnectionStore(data, conn);
  2784. result = Curl_setup_transfer(conn, -1, -1, FALSE, NULL, /* no download */
  2785. -1, NULL); /* no upload */
  2786. }
  2787. return result;
  2788. #else
  2789. failf(data, LIBCURL_NAME
  2790. " was built with FILE disabled!");
  2791. #endif
  2792. }
  2793. else if (strequal(conn->protostr, "TFTP")) {
  2794. #ifndef CURL_DISABLE_TFTP
  2795. char *type;
  2796. conn->socktype = SOCK_DGRAM; /* UDP datagram based */
  2797. conn->protocol |= PROT_TFTP;
  2798. conn->port = PORT_TFTP;
  2799. conn->remote_port = PORT_TFTP;
  2800. conn->curl_connect = Curl_tftp_connect;
  2801. conn->curl_do = Curl_tftp;
  2802. conn->curl_done = Curl_tftp_done;
  2803. /* TFTP URLs support an extension like ";mode=<typecode>" that
  2804. * we'll try to get now! */
  2805. type=strstr(data->reqdata.path, ";mode=");
  2806. if(!type) {
  2807. type=strstr(conn->host.rawalloc, ";mode=");
  2808. }
  2809. if(type) {
  2810. char command;
  2811. *type=0; /* it was in the middle of the hostname */
  2812. command = (char)toupper((int)type[6]);
  2813. switch(command) {
  2814. case 'A': /* ASCII mode */
  2815. case 'N': /* NETASCII mode */
  2816. data->set.prefer_ascii = TRUE;
  2817. break;
  2818. case 'O': /* octet mode */
  2819. case 'I': /* binary mode */
  2820. default:
  2821. /* switch off ASCII */
  2822. data->set.prefer_ascii = FALSE;
  2823. break;
  2824. }
  2825. }
  2826. #else
  2827. failf(data, LIBCURL_NAME
  2828. " was built with TFTP disabled!");
  2829. #endif
  2830. }
  2831. else if (strequal(conn->protostr, "SCP")) {
  2832. #ifdef USE_LIBSSH2
  2833. conn->port = PORT_SSH;
  2834. conn->remote_port = PORT_SSH;
  2835. conn->protocol = PROT_SCP;
  2836. conn->curl_connect = Curl_ssh_connect; /* ssh_connect? */
  2837. conn->curl_do = Curl_scp_do;
  2838. conn->curl_done = Curl_scp_done;
  2839. conn->curl_do_more = (Curl_do_more_func)ZERO_NULL;
  2840. #else
  2841. failf(data, LIBCURL_NAME
  2842. " was built without LIBSSH2, scp: not supported!");
  2843. return CURLE_UNSUPPORTED_PROTOCOL;
  2844. #endif
  2845. }
  2846. else if (strequal(conn->protostr, "SFTP")) {
  2847. #ifdef USE_LIBSSH2
  2848. conn->port = PORT_SSH;
  2849. conn->remote_port = PORT_SSH;
  2850. conn->protocol = PROT_SFTP;
  2851. conn->curl_connect = Curl_ssh_connect; /* ssh_connect? */
  2852. conn->curl_do = Curl_sftp_do;
  2853. conn->curl_done = Curl_sftp_done;
  2854. conn->curl_do_more = (Curl_do_more_func)NULL;
  2855. #else
  2856. failf(data, LIBCURL_NAME
  2857. " was built without LIBSSH2, scp: not supported!");
  2858. return CURLE_UNSUPPORTED_PROTOCOL;
  2859. #endif
  2860. }
  2861. else {
  2862. /* We fell through all checks and thus we don't support the specified
  2863. protocol */
  2864. failf(data, "Unsupported protocol: %s", conn->protostr);
  2865. return CURLE_UNSUPPORTED_PROTOCOL;
  2866. }
  2867. if(proxy && *proxy) {
  2868. /* If this is supposed to use a proxy, we need to figure out the proxy
  2869. host name name, so that we can re-use an existing connection
  2870. that may exist registered to the same proxy host. */
  2871. char *prox_portno;
  2872. char *endofprot;
  2873. /* We need to make a duplicate of the proxy so that we can modify the
  2874. string safely. If 'proxy_alloc' is TRUE, the string is already
  2875. allocated and we can treat it as duplicated. */
  2876. char *proxydup=proxy_alloc?proxy:strdup(proxy);
  2877. /* We use 'proxyptr' to point to the proxy name from now on... */
  2878. char *proxyptr=proxydup;
  2879. char *portptr;
  2880. char *atsign;
  2881. if(NULL == proxydup) {
  2882. failf(data, "memory shortage");
  2883. return CURLE_OUT_OF_MEMORY;
  2884. }
  2885. /* We do the proxy host string parsing here. We want the host name and the
  2886. * port name. Accept a protocol:// prefix, even though it should just be
  2887. * ignored.
  2888. */
  2889. /* Skip the protocol part if present */
  2890. endofprot=strstr(proxyptr, "://");
  2891. if(endofprot)
  2892. proxyptr = endofprot+3;
  2893. /* Is there a username and password given in this proxy url? */
  2894. atsign = strchr(proxyptr, '@');
  2895. if(atsign) {
  2896. char proxyuser[MAX_CURL_USER_LENGTH];
  2897. char proxypasswd[MAX_CURL_PASSWORD_LENGTH];
  2898. proxypasswd[0] = 0;
  2899. if(1 <= sscanf(proxyptr,
  2900. "%" MAX_CURL_USER_LENGTH_TXT"[^:]:"
  2901. "%" MAX_CURL_PASSWORD_LENGTH_TXT "[^@]",
  2902. proxyuser, proxypasswd)) {
  2903. CURLcode res = CURLE_OK;
  2904. /* found user and password, rip them out. note that we are
  2905. unescaping them, as there is otherwise no way to have a
  2906. username or password with reserved characters like ':' in
  2907. them. */
  2908. Curl_safefree(conn->proxyuser);
  2909. conn->proxyuser = curl_easy_unescape(data, proxyuser, 0, NULL);
  2910. if(!conn->proxyuser)
  2911. res = CURLE_OUT_OF_MEMORY;
  2912. else {
  2913. Curl_safefree(conn->proxypasswd);
  2914. conn->proxypasswd = curl_easy_unescape(data, proxypasswd, 0, NULL);
  2915. if(!conn->proxypasswd)
  2916. res = CURLE_OUT_OF_MEMORY;
  2917. }
  2918. if(CURLE_OK == res) {
  2919. conn->bits.proxy_user_passwd = TRUE; /* enable it */
  2920. atsign = strdup(atsign+1); /* the right side of the @-letter */
  2921. if(atsign) {
  2922. free(proxydup); /* free the former proxy string */
  2923. proxydup = proxyptr = atsign; /* now use this instead */
  2924. }
  2925. else
  2926. res = CURLE_OUT_OF_MEMORY;
  2927. }
  2928. if(res) {
  2929. free(proxydup); /* free the allocated proxy string */
  2930. return res;
  2931. }
  2932. }
  2933. }
  2934. /* start scanning for port number at this point */
  2935. portptr = proxyptr;
  2936. /* detect and extract RFC2732-style IPv6-addresses */
  2937. if(*proxyptr == '[') {
  2938. char *ptr = ++proxyptr; /* advance beyond the initial bracket */
  2939. while(*ptr && (ISXDIGIT(*ptr) || (*ptr == ':')))
  2940. ptr++;
  2941. if(*ptr == ']') {
  2942. /* yeps, it ended nicely with a bracket as well */
  2943. *ptr = 0;
  2944. portptr = ptr+1;
  2945. }
  2946. /* Note that if this didn't end with a bracket, we still advanced the
  2947. * proxyptr first, but I can't see anything wrong with that as no host
  2948. * name nor a numeric can legally start with a bracket.
  2949. */
  2950. }
  2951. /* Get port number off proxy.server.com:1080 */
  2952. prox_portno = strchr(portptr, ':');
  2953. if (prox_portno) {
  2954. *prox_portno = 0x0; /* cut off number from host name */
  2955. prox_portno ++;
  2956. /* now set the local port number */
  2957. conn->port = atoi(prox_portno);
  2958. }
  2959. else if(data->set.proxyport) {
  2960. /* None given in the proxy string, then get the default one if it is
  2961. given */
  2962. conn->port = data->set.proxyport;
  2963. }
  2964. /* now, clone the cleaned proxy host name */
  2965. conn->proxy.rawalloc = strdup(proxyptr);
  2966. conn->proxy.name = conn->proxy.rawalloc;
  2967. free(proxydup); /* free the duplicate pointer and not the modified */
  2968. proxy = NULL; /* this may have just been freed */
  2969. if(!conn->proxy.rawalloc)
  2970. return CURLE_OUT_OF_MEMORY;
  2971. }
  2972. /*************************************************************
  2973. * If the protocol is using SSL and HTTP proxy is used, we set
  2974. * the tunnel_proxy bit.
  2975. *************************************************************/
  2976. if((conn->protocol&PROT_SSL) && conn->bits.httpproxy)
  2977. conn->bits.tunnel_proxy = TRUE;
  2978. /*************************************************************
  2979. * Take care of user and password authentication stuff
  2980. *************************************************************/
  2981. /*
  2982. * Inputs: data->set.userpwd (CURLOPT_USERPWD)
  2983. * data->set.fpasswd (CURLOPT_PASSWDFUNCTION)
  2984. * data->set.use_netrc (CURLOPT_NETRC)
  2985. * conn->host.name
  2986. * netrc file
  2987. * hard-coded defaults
  2988. *
  2989. * Outputs: (almost :- all currently undefined)
  2990. * conn->bits.user_passwd - non-zero if non-default passwords exist
  2991. * conn->user - non-zero length if defined
  2992. * conn->passwd - ditto
  2993. * conn->host.name - remove user name and password
  2994. */
  2995. /* At this point, we're hoping all the other special cases have
  2996. * been taken care of, so conn->host.name is at most
  2997. * [user[:password]]@]hostname
  2998. *
  2999. * We need somewhere to put the embedded details, so do that first.
  3000. */
  3001. user[0] =0; /* to make everything well-defined */
  3002. passwd[0]=0;
  3003. if (conn->protocol & (PROT_FTP|PROT_HTTP|PROT_SCP|PROT_SFTP)) {
  3004. /* This is a FTP, HTTP, SCP or SFTP URL, we will now try to extract the
  3005. * possible user+password pair in a string like:
  3006. * ftp://user:[email protected]:8021/README */
  3007. char *ptr=strchr(conn->host.name, '@');
  3008. char *userpass = conn->host.name;
  3009. if(ptr != NULL) {
  3010. /* there's a user+password given here, to the left of the @ */
  3011. conn->host.name = ++ptr;
  3012. /* So the hostname is sane. Only bother interpreting the
  3013. * results if we could care. It could still be wasted
  3014. * work because it might be overtaken by the programmatically
  3015. * set user/passwd, but doing that first adds more cases here :-(
  3016. */
  3017. if (data->set.use_netrc != CURL_NETRC_REQUIRED) {
  3018. /* We could use the one in the URL */
  3019. conn->bits.user_passwd = 1; /* enable user+password */
  3020. if(*userpass != ':') {
  3021. /* the name is given, get user+password */
  3022. sscanf(userpass, "%" MAX_CURL_USER_LENGTH_TXT "[^:@]:"
  3023. "%" MAX_CURL_PASSWORD_LENGTH_TXT "[^@]",
  3024. user, passwd);
  3025. }
  3026. else
  3027. /* no name given, get the password only */
  3028. sscanf(userpass, ":%" MAX_CURL_PASSWORD_LENGTH_TXT "[^@]", passwd);
  3029. if(user[0]) {
  3030. char *newname=curl_easy_unescape(data, user, 0, NULL);
  3031. if(!newname)
  3032. return CURLE_OUT_OF_MEMORY;
  3033. if(strlen(newname) < sizeof(user))
  3034. strcpy(user, newname);
  3035. /* if the new name is longer than accepted, then just use
  3036. the unconverted name, it'll be wrong but what the heck */
  3037. free(newname);
  3038. }
  3039. if (passwd[0]) {
  3040. /* we have a password found in the URL, decode it! */
  3041. char *newpasswd=curl_easy_unescape(data, passwd, 0, NULL);
  3042. if(!newpasswd)
  3043. return CURLE_OUT_OF_MEMORY;
  3044. if(strlen(newpasswd) < sizeof(passwd))
  3045. strcpy(passwd, newpasswd);
  3046. free(newpasswd);
  3047. }
  3048. }
  3049. }
  3050. }
  3051. /*************************************************************
  3052. * Figure out the remote port number
  3053. *
  3054. * No matter if we use a proxy or not, we have to figure out the remote
  3055. * port number of various reasons.
  3056. *
  3057. * To be able to detect port number flawlessly, we must not confuse them
  3058. * IPv6-specified addresses in the [0::1] style. (RFC2732)
  3059. *
  3060. * The conn->host.name is currently [user:passwd@]host[:port] where host
  3061. * could be a hostname, IPv4 address or IPv6 address.
  3062. *************************************************************/
  3063. if((1 == sscanf(conn->host.name, "[%*39[0-9a-fA-F:.]%c", &endbracket)) &&
  3064. (']' == endbracket)) {
  3065. /* this is a RFC2732-style specified IP-address */
  3066. conn->bits.ipv6_ip = TRUE;
  3067. conn->host.name++; /* pass the starting bracket */
  3068. tmp = strchr(conn->host.name, ']');
  3069. *tmp = 0; /* zero terminate */
  3070. tmp++; /* pass the ending bracket */
  3071. if(':' != *tmp)
  3072. tmp = NULL; /* no port number available */
  3073. }
  3074. else
  3075. tmp = strrchr(conn->host.name, ':');
  3076. if(data->set.use_port && data->state.allow_port) {
  3077. /* if set, we use this and ignore the port possibly given in the URL */
  3078. conn->remote_port = (unsigned short)data->set.use_port;
  3079. if(tmp)
  3080. *tmp = '\0'; /* cut off the name there anyway - if there was a port
  3081. number - since the port number is to be ignored! */
  3082. if(conn->bits.httpproxy) {
  3083. /* we need to create new URL with the new port number */
  3084. char *url;
  3085. url = aprintf("http://%s:%d%s", conn->host.name, conn->remote_port,
  3086. data->reqdata.path);
  3087. if(!url)
  3088. return CURLE_OUT_OF_MEMORY;
  3089. if(data->change.url_alloc)
  3090. free(data->change.url);
  3091. data->change.url = url;
  3092. data->change.url_alloc = TRUE;
  3093. }
  3094. }
  3095. else if (tmp) {
  3096. /* no CURLOPT_PORT given, extract the one from the URL */
  3097. char *rest;
  3098. unsigned long port;
  3099. port=strtoul(tmp+1, &rest, 10); /* Port number must be decimal */
  3100. if (rest != (tmp+1) && *rest == '\0') {
  3101. /* The colon really did have only digits after it,
  3102. * so it is either a port number or a mistake */
  3103. if (port > 0xffff) { /* Single unix standard says port numbers are
  3104. * 16 bits long */
  3105. failf(data, "Port number too large: %lu", port);
  3106. return CURLE_URL_MALFORMAT;
  3107. }
  3108. *tmp = '\0'; /* cut off the name there */
  3109. conn->remote_port = (unsigned short)port;
  3110. }
  3111. }
  3112. /* Programmatically set password:
  3113. * - always applies, if available
  3114. * - takes precedence over the values we just set above
  3115. * so scribble it over the top.
  3116. * User-supplied passwords are assumed not to need unescaping.
  3117. *
  3118. * user_password is set in "inherit initial knowledge' above,
  3119. * so it doesn't have to be set in this block
  3120. */
  3121. if (data->set.userpwd != NULL) {
  3122. /* the name is given, get user+password */
  3123. sscanf(data->set.userpwd,
  3124. "%" MAX_CURL_USER_LENGTH_TXT "[^:]:"
  3125. "%" MAX_CURL_PASSWORD_LENGTH_TXT "[^\n]",
  3126. user, passwd);
  3127. }
  3128. conn->bits.netrc = FALSE;
  3129. if (data->set.use_netrc != CURL_NETRC_IGNORED) {
  3130. if(Curl_parsenetrc(conn->host.name,
  3131. user, passwd,
  3132. data->set.netrc_file)) {
  3133. infof(data, "Couldn't find host %s in the " DOT_CHAR
  3134. "netrc file, using defaults\n",
  3135. conn->host.name);
  3136. }
  3137. else {
  3138. /* set bits.netrc TRUE to remember that we got the name from a .netrc
  3139. file, so that it is safe to use even if we followed a Location: to a
  3140. different host or similar. */
  3141. conn->bits.netrc = TRUE;
  3142. conn->bits.user_passwd = 1; /* enable user+password */
  3143. }
  3144. }
  3145. /* If our protocol needs a password and we have none, use the defaults */
  3146. if ( (conn->protocol & PROT_FTP) &&
  3147. !conn->bits.user_passwd) {
  3148. conn->user = strdup(CURL_DEFAULT_USER);
  3149. conn->passwd = strdup(CURL_DEFAULT_PASSWORD);
  3150. /* This is the default password, so DON'T set conn->bits.user_passwd */
  3151. }
  3152. else {
  3153. /* store user + password, zero-length if not set */
  3154. conn->user = strdup(user);
  3155. conn->passwd = strdup(passwd);
  3156. }
  3157. if(!conn->user || !conn->passwd)
  3158. return CURLE_OUT_OF_MEMORY;
  3159. /*************************************************************
  3160. * Check the current list of connections to see if we can
  3161. * re-use an already existing one or if we have to create a
  3162. * new one.
  3163. *************************************************************/
  3164. /* get a cloned copy of the SSL config situation stored in the
  3165. connection struct */
  3166. if(!Curl_clone_ssl_config(&data->set.ssl, &conn->ssl_config))
  3167. return CURLE_OUT_OF_MEMORY;
  3168. /* reuse_fresh is TRUE if we are told to use a new connection by force, but
  3169. we only acknowledge this option if this is not a re-used connection
  3170. already (which happens due to follow-location or during a HTTP
  3171. authentication phase). */
  3172. if(data->set.reuse_fresh && !data->state.this_is_a_follow)
  3173. reuse = FALSE;
  3174. else
  3175. reuse = ConnectionExists(data, conn, &conn_temp);
  3176. if(reuse) {
  3177. /*
  3178. * We already have a connection for this, we got the former connection
  3179. * in the conn_temp variable and thus we need to cleanup the one we
  3180. * just allocated before we can move along and use the previously
  3181. * existing one.
  3182. */
  3183. struct connectdata *old_conn = conn;
  3184. if(old_conn->proxy.rawalloc)
  3185. free(old_conn->proxy.rawalloc);
  3186. /* free the SSL config struct from this connection struct as this was
  3187. allocated in vain and is targeted for destruction */
  3188. Curl_free_ssl_config(&conn->ssl_config);
  3189. conn = conn_temp; /* use this connection from now on */
  3190. conn->data = old_conn->data;
  3191. /* get the user+password information from the old_conn struct since it may
  3192. * be new for this request even when we re-use an existing connection */
  3193. conn->bits.user_passwd = old_conn->bits.user_passwd;
  3194. if (conn->bits.user_passwd) {
  3195. /* use the new user namd and password though */
  3196. Curl_safefree(conn->user);
  3197. Curl_safefree(conn->passwd);
  3198. conn->user = old_conn->user;
  3199. conn->passwd = old_conn->passwd;
  3200. old_conn->user = NULL;
  3201. old_conn->passwd = NULL;
  3202. }
  3203. conn->bits.proxy_user_passwd = old_conn->bits.proxy_user_passwd;
  3204. if (conn->bits.proxy_user_passwd) {
  3205. /* use the new proxy user name and proxy password though */
  3206. Curl_safefree(conn->proxyuser);
  3207. Curl_safefree(conn->proxypasswd);
  3208. conn->proxyuser = old_conn->proxyuser;
  3209. conn->proxypasswd = old_conn->proxypasswd;
  3210. old_conn->proxyuser = NULL;
  3211. old_conn->proxypasswd = NULL;
  3212. }
  3213. /* host can change, when doing keepalive with a proxy ! */
  3214. if (conn->bits.httpproxy) {
  3215. free(conn->host.rawalloc);
  3216. conn->host=old_conn->host;
  3217. }
  3218. /* get the newly set value, not the old one */
  3219. conn->bits.no_body = old_conn->bits.no_body;
  3220. if (!conn->bits.httpproxy)
  3221. free(old_conn->host.rawalloc); /* free the newly allocated name buffer */
  3222. /* re-use init */
  3223. conn->bits.reuse = TRUE; /* yes, we're re-using here */
  3224. conn->bits.chunk = FALSE; /* always assume not chunked unless told
  3225. otherwise */
  3226. Curl_safefree(old_conn->user);
  3227. Curl_safefree(old_conn->passwd);
  3228. Curl_safefree(old_conn->proxyuser);
  3229. Curl_safefree(old_conn->proxypasswd);
  3230. Curl_llist_destroy(old_conn->send_pipe, NULL);
  3231. Curl_llist_destroy(old_conn->recv_pipe, NULL);
  3232. free(old_conn); /* we don't need this anymore */
  3233. /*
  3234. * If we're doing a resumed transfer, we need to setup our stuff
  3235. * properly.
  3236. */
  3237. data->reqdata.resume_from = data->set.set_resume_from;
  3238. if (data->reqdata.resume_from) {
  3239. if (data->reqdata.rangestringalloc == TRUE)
  3240. free(data->reqdata.range);
  3241. data->reqdata.range = aprintf("%" FORMAT_OFF_T "-",
  3242. data->reqdata.resume_from);
  3243. if(!data->reqdata.range)
  3244. return CURLE_OUT_OF_MEMORY;
  3245. /* tell ourselves to fetch this range */
  3246. data->reqdata.use_range = TRUE; /* enable range download */
  3247. data->reqdata.rangestringalloc = TRUE; /* mark range string allocated */
  3248. }
  3249. else if (data->set.set_range) {
  3250. /* There is a range, but is not a resume, useful for random ftp access */
  3251. data->reqdata.range = strdup(data->set.set_range);
  3252. if(!data->reqdata.range)
  3253. return CURLE_OUT_OF_MEMORY;
  3254. data->reqdata.rangestringalloc = TRUE; /* mark range string allocated */
  3255. data->reqdata.use_range = TRUE; /* enable range download */
  3256. }
  3257. else
  3258. data->reqdata.use_range = FALSE; /* disable range download */
  3259. *in_connect = conn; /* return this instead! */
  3260. infof(data, "Re-using existing connection! (#%ld) with host %s\n",
  3261. conn->connectindex,
  3262. conn->bits.httpproxy?conn->proxy.dispname:conn->host.dispname);
  3263. }
  3264. else {
  3265. /*
  3266. * This is a brand new connection, so let's store it in the connection
  3267. * cache of ours!
  3268. */
  3269. ConnectionStore(data, conn);
  3270. }
  3271. /* Continue connectdata initialization here. */
  3272. /*
  3273. *
  3274. * Inherit the proper values from the urldata struct AFTER we have arranged
  3275. * the persistent connection stuff */
  3276. conn->fread = data->set.fread;
  3277. conn->fread_in = data->set.in;
  3278. if ((conn->protocol&PROT_HTTP) &&
  3279. data->set.upload &&
  3280. (data->set.infilesize == -1) &&
  3281. (data->set.httpversion != CURL_HTTP_VERSION_1_0)) {
  3282. /* HTTP, upload, unknown file size and not HTTP 1.0 */
  3283. conn->bits.upload_chunky = TRUE;
  3284. }
  3285. else {
  3286. /* else, no chunky upload */
  3287. conn->bits.upload_chunky = FALSE;
  3288. }
  3289. #ifndef USE_ARES
  3290. /*************************************************************
  3291. * Set timeout if that is being used, and we're not using an asynchronous
  3292. * name resolve.
  3293. *************************************************************/
  3294. if((data->set.timeout || data->set.connecttimeout) && !data->set.no_signal) {
  3295. /*************************************************************
  3296. * Set signal handler to catch SIGALRM
  3297. * Store the old value to be able to set it back later!
  3298. *************************************************************/
  3299. #ifdef SIGALRM
  3300. #ifdef HAVE_ALARM
  3301. long shortest;
  3302. #endif
  3303. #ifdef HAVE_SIGACTION
  3304. struct sigaction sigact;
  3305. sigaction(SIGALRM, NULL, &sigact);
  3306. keep_sigact = sigact;
  3307. keep_copysig = TRUE; /* yes, we have a copy */
  3308. sigact.sa_handler = alarmfunc;
  3309. #ifdef SA_RESTART
  3310. /* HPUX doesn't have SA_RESTART but defaults to that behaviour! */
  3311. sigact.sa_flags &= ~SA_RESTART;
  3312. #endif
  3313. /* now set the new struct */
  3314. sigaction(SIGALRM, &sigact, NULL);
  3315. #else /* HAVE_SIGACTION */
  3316. /* no sigaction(), revert to the much lamer signal() */
  3317. #ifdef HAVE_SIGNAL
  3318. keep_sigact = signal(SIGALRM, alarmfunc);
  3319. #endif
  3320. #endif /* HAVE_SIGACTION */
  3321. /* We set the timeout on the name resolving phase first, separately from
  3322. * the download/upload part to allow a maximum time on everything. This is
  3323. * a signal-based timeout, why it won't work and shouldn't be used in
  3324. * multi-threaded environments. */
  3325. #ifdef HAVE_ALARM
  3326. shortest = data->set.timeout; /* default to this timeout value */
  3327. if(shortest && data->set.connecttimeout &&
  3328. (data->set.connecttimeout < shortest))
  3329. /* if both are set, pick the shortest */
  3330. shortest = data->set.connecttimeout;
  3331. else if(!shortest)
  3332. /* if timeout is not set, use the connect timeout */
  3333. shortest = data->set.connecttimeout;
  3334. /* alarm() makes a signal get sent when the timeout fires off, and that
  3335. will abort system calls */
  3336. prev_alarm = alarm((unsigned int) shortest);
  3337. /* We can expect the conn->created time to be "now", as that was just
  3338. recently set in the beginning of this function and nothing slow
  3339. has been done since then until now. */
  3340. #endif
  3341. #endif /* SIGALRM */
  3342. }
  3343. #endif /* USE_ARES */
  3344. /*************************************************************
  3345. * Resolve the name of the server or proxy
  3346. *************************************************************/
  3347. if(conn->bits.reuse) {
  3348. /* re-used connection, no resolving is necessary */
  3349. hostaddr = NULL;
  3350. /* we'll need to clear conn->dns_entry later in Curl_disconnect() */
  3351. if (conn->bits.httpproxy)
  3352. fix_hostname(data, conn, &conn->host);
  3353. }
  3354. else {
  3355. /* this is a fresh connect */
  3356. /* set a pointer to the hostname we display */
  3357. fix_hostname(data, conn, &conn->host);
  3358. if(!conn->proxy.name || !*conn->proxy.name) {
  3359. /* If not connecting via a proxy, extract the port from the URL, if it is
  3360. * there, thus overriding any defaults that might have been set above. */
  3361. conn->port = conn->remote_port; /* it is the same port */
  3362. /* Resolve target host right on */
  3363. rc = Curl_resolv(conn, conn->host.name, (int)conn->port, &hostaddr);
  3364. if(rc == CURLRESOLV_PENDING)
  3365. *async = TRUE;
  3366. else if(!hostaddr) {
  3367. failf(data, "Couldn't resolve host '%s'", conn->host.dispname);
  3368. result = CURLE_COULDNT_RESOLVE_HOST;
  3369. /* don't return yet, we need to clean up the timeout first */
  3370. }
  3371. }
  3372. else {
  3373. /* This is a proxy that hasn't been resolved yet. */
  3374. /* IDN-fix the proxy name */
  3375. fix_hostname(data, conn, &conn->proxy);
  3376. /* resolve proxy */
  3377. rc = Curl_resolv(conn, conn->proxy.name, (int)conn->port, &hostaddr);
  3378. if(rc == CURLRESOLV_PENDING)
  3379. *async = TRUE;
  3380. else if(!hostaddr) {
  3381. failf(data, "Couldn't resolve proxy '%s'", conn->proxy.dispname);
  3382. result = CURLE_COULDNT_RESOLVE_PROXY;
  3383. /* don't return yet, we need to clean up the timeout first */
  3384. }
  3385. }
  3386. }
  3387. *addr = hostaddr;
  3388. #if defined(HAVE_ALARM) && defined(SIGALRM) && !defined(USE_ARES)
  3389. if((data->set.timeout || data->set.connecttimeout) && !data->set.no_signal) {
  3390. #ifdef HAVE_SIGACTION
  3391. if(keep_copysig) {
  3392. /* we got a struct as it looked before, now put that one back nice
  3393. and clean */
  3394. sigaction(SIGALRM, &keep_sigact, NULL); /* put it back */
  3395. }
  3396. #else
  3397. #ifdef HAVE_SIGNAL
  3398. /* restore the previous SIGALRM handler */
  3399. signal(SIGALRM, keep_sigact);
  3400. #endif
  3401. #endif /* HAVE_SIGACTION */
  3402. /* switch back the alarm() to either zero or to what it was before minus
  3403. the time we spent until now! */
  3404. if(prev_alarm) {
  3405. /* there was an alarm() set before us, now put it back */
  3406. unsigned long elapsed_ms = Curl_tvdiff(Curl_tvnow(), conn->created);
  3407. unsigned long alarm_set;
  3408. /* the alarm period is counted in even number of seconds */
  3409. alarm_set = prev_alarm - elapsed_ms/1000;
  3410. if(!alarm_set ||
  3411. ((alarm_set >= 0x80000000) && (prev_alarm < 0x80000000)) ) {
  3412. /* if the alarm time-left reached zero or turned "negative" (counted
  3413. with unsigned values), we should fire off a SIGALRM here, but we
  3414. won't, and zero would be to switch it off so we never set it to
  3415. less than 1! */
  3416. alarm(1);
  3417. result = CURLE_OPERATION_TIMEOUTED;
  3418. failf(data, "Previous alarm fired off!");
  3419. }
  3420. else
  3421. alarm((unsigned int)alarm_set);
  3422. }
  3423. else
  3424. alarm(0); /* just shut it off */
  3425. }
  3426. #endif
  3427. return result;
  3428. }
  3429. /* SetupConnection() is called after the name resolve initiated in
  3430. * CreateConnection() is all done.
  3431. *
  3432. * NOTE: the argument 'hostaddr' is NULL when this function is called for a
  3433. * re-used connection.
  3434. *
  3435. * conn->data MUST already have been setup fine (in CreateConnection)
  3436. */
  3437. static CURLcode SetupConnection(struct connectdata *conn,
  3438. struct Curl_dns_entry *hostaddr,
  3439. bool *protocol_done)
  3440. {
  3441. CURLcode result=CURLE_OK;
  3442. struct SessionHandle *data = conn->data;
  3443. Curl_pgrsTime(data, TIMER_NAMELOOKUP);
  3444. if(conn->protocol & PROT_FILE) {
  3445. /* There's nothing in this function to setup if we're only doing
  3446. a file:// transfer */
  3447. *protocol_done = TRUE;
  3448. return result;
  3449. }
  3450. *protocol_done = FALSE; /* default to not done */
  3451. /*************************************************************
  3452. * Send user-agent to HTTP proxies even if the target protocol
  3453. * isn't HTTP.
  3454. *************************************************************/
  3455. if((conn->protocol&PROT_HTTP) || conn->bits.httpproxy) {
  3456. if(data->set.useragent) {
  3457. Curl_safefree(conn->allocptr.uagent);
  3458. conn->allocptr.uagent =
  3459. aprintf("User-Agent: %s\r\n", data->set.useragent);
  3460. if(!conn->allocptr.uagent)
  3461. return CURLE_OUT_OF_MEMORY;
  3462. }
  3463. }
  3464. conn->headerbytecount = 0;
  3465. #ifdef CURL_DO_LINEEND_CONV
  3466. data->state.crlf_conversions = 0; /* reset CRLF conversion counter */
  3467. #endif /* CURL_DO_LINEEND_CONV */
  3468. for(;;) {
  3469. /* loop for CURL_SERVER_CLOSED_CONNECTION */
  3470. if(CURL_SOCKET_BAD == conn->sock[FIRSTSOCKET]) {
  3471. bool connected = FALSE;
  3472. /* Connect only if not already connected! */
  3473. result = ConnectPlease(data, conn, hostaddr, &connected);
  3474. if(connected) {
  3475. result = Curl_protocol_connect(conn, protocol_done);
  3476. if(CURLE_OK == result)
  3477. conn->bits.tcpconnect = TRUE;
  3478. }
  3479. else
  3480. conn->bits.tcpconnect = FALSE;
  3481. /* if the connection was closed by the server while exchanging
  3482. authentication informations, retry with the new set
  3483. authentication information */
  3484. if(conn->bits.proxy_connect_closed) {
  3485. /* reset the error buffer */
  3486. if (data->set.errorbuffer)
  3487. data->set.errorbuffer[0] = '\0';
  3488. data->state.errorbuf = FALSE;
  3489. continue;
  3490. }
  3491. if(CURLE_OK != result)
  3492. return result;
  3493. }
  3494. else {
  3495. Curl_pgrsTime(data, TIMER_CONNECT); /* we're connected already */
  3496. conn->bits.tcpconnect = TRUE;
  3497. *protocol_done = TRUE;
  3498. if(data->set.verbose)
  3499. verboseconnect(conn);
  3500. }
  3501. /* Stop the loop now */
  3502. break;
  3503. }
  3504. conn->now = Curl_tvnow(); /* time this *after* the connect is done, we
  3505. set this here perhaps a second time */
  3506. #ifdef __EMX__
  3507. /* 20000330 mgs
  3508. * the check is quite a hack...
  3509. * we're calling _fsetmode to fix the problem with fwrite converting newline
  3510. * characters (you get mangled text files, and corrupted binary files when
  3511. * you download to stdout and redirect it to a file). */
  3512. if ((data->set.out)->_handle == NULL) {
  3513. _fsetmode(stdout, "b");
  3514. }
  3515. #endif
  3516. return CURLE_OK;
  3517. }
  3518. CURLcode Curl_connect(struct SessionHandle *data,
  3519. struct connectdata **in_connect,
  3520. bool *asyncp,
  3521. bool *protocol_done)
  3522. {
  3523. CURLcode code;
  3524. struct Curl_dns_entry *dns;
  3525. *asyncp = FALSE; /* assume synchronous resolves by default */
  3526. /* call the stuff that needs to be called */
  3527. code = CreateConnection(data, in_connect, &dns, asyncp);
  3528. if(CURLE_OK == code) {
  3529. /* no error */
  3530. if(dns || !*asyncp)
  3531. /* If an address is available it means that we already have the name
  3532. resolved, OR it isn't async. if this is a re-used connection 'dns'
  3533. will be NULL here. Continue connecting from here */
  3534. code = SetupConnection(*in_connect, dns, protocol_done);
  3535. /* else
  3536. response will be received and treated async wise */
  3537. }
  3538. if(CURLE_OK != code) {
  3539. /* We're not allowed to return failure with memory left allocated
  3540. in the connectdata struct, free those here */
  3541. if(*in_connect) {
  3542. Curl_disconnect(*in_connect); /* close the connection */
  3543. *in_connect = NULL; /* return a NULL */
  3544. }
  3545. }
  3546. else {
  3547. if ((*in_connect)->is_in_pipeline)
  3548. data->state.is_in_pipeline = TRUE;
  3549. }
  3550. return code;
  3551. }
  3552. /* Call this function after Curl_connect() has returned async=TRUE and
  3553. then a successful name resolve has been received.
  3554. Note: this function disconnects and frees the conn data in case of
  3555. resolve failure */
  3556. CURLcode Curl_async_resolved(struct connectdata *conn,
  3557. bool *protocol_done)
  3558. {
  3559. #if defined(USE_ARES) || defined(USE_THREADING_GETHOSTBYNAME) || \
  3560. defined(USE_THREADING_GETADDRINFO)
  3561. CURLcode code = SetupConnection(conn, conn->async.dns, protocol_done);
  3562. if(code)
  3563. /* We're not allowed to return failure with memory left allocated
  3564. in the connectdata struct, free those here */
  3565. Curl_disconnect(conn); /* close the connection */
  3566. return code;
  3567. #else
  3568. (void)conn;
  3569. (void)protocol_done;
  3570. return CURLE_OK;
  3571. #endif
  3572. }
  3573. CURLcode Curl_done(struct connectdata **connp,
  3574. CURLcode status, bool premature) /* an error if this is called after an
  3575. error was detected */
  3576. {
  3577. CURLcode result;
  3578. struct connectdata *conn = *connp;
  3579. struct SessionHandle *data = conn->data;
  3580. Curl_expire(data, 0); /* stop timer */
  3581. if(conn->bits.done)
  3582. return CURLE_OK; /* Curl_done() has already been called */
  3583. conn->bits.done = TRUE; /* called just now! */
  3584. if(Curl_removeHandleFromPipeline(data, conn->recv_pipe) &&
  3585. conn->readchannel_inuse)
  3586. conn->readchannel_inuse = FALSE;
  3587. if(Curl_removeHandleFromPipeline(data, conn->send_pipe) &&
  3588. conn->writechannel_inuse)
  3589. conn->writechannel_inuse = FALSE;
  3590. /* cleanups done even if the connection is re-used */
  3591. if(data->reqdata.rangestringalloc) {
  3592. free(data->reqdata.range);
  3593. data->reqdata.rangestringalloc = FALSE;
  3594. }
  3595. /* Cleanup possible redirect junk */
  3596. if(data->reqdata.newurl) {
  3597. free(data->reqdata.newurl);
  3598. data->reqdata.newurl = NULL;
  3599. }
  3600. if(conn->dns_entry) {
  3601. Curl_resolv_unlock(data, conn->dns_entry); /* done with this */
  3602. conn->dns_entry = NULL;
  3603. }
  3604. /* this calls the protocol-specific function pointer previously set */
  3605. if(conn->curl_done)
  3606. result = conn->curl_done(conn, status, premature);
  3607. else
  3608. result = CURLE_OK;
  3609. Curl_pgrsDone(conn); /* done with the operation */
  3610. /* for ares-using, make sure all possible outstanding requests are properly
  3611. cancelled before we proceed */
  3612. ares_cancel(data->state.areschannel);
  3613. /* if data->set.reuse_forbid is TRUE, it means the libcurl client has
  3614. forced us to close this no matter what we think.
  3615. if conn->bits.close is TRUE, it means that the connection should be
  3616. closed in spite of all our efforts to be nice, due to protocol
  3617. restrictions in our or the server's end */
  3618. if(data->set.reuse_forbid || conn->bits.close) {
  3619. CURLcode res2 = Curl_disconnect(conn); /* close the connection */
  3620. *connp = NULL; /* to make the caller of this function better detect that
  3621. this was actually killed here */
  3622. /* If we had an error already, make sure we return that one. But
  3623. if we got a new error, return that. */
  3624. if(!result && res2)
  3625. result = res2;
  3626. }
  3627. else {
  3628. ConnectionDone(conn); /* the connection is no longer in use */
  3629. /* remember the most recently used connection */
  3630. data->state.lastconnect = conn->connectindex;
  3631. infof(data, "Connection #%ld to host %s left intact\n",
  3632. conn->connectindex,
  3633. conn->bits.httpproxy?conn->proxy.dispname:conn->host.dispname);
  3634. }
  3635. return result;
  3636. }
  3637. CURLcode Curl_do(struct connectdata **connp, bool *done)
  3638. {
  3639. CURLcode result=CURLE_OK;
  3640. struct connectdata *conn = *connp;
  3641. struct SessionHandle *data = conn->data;
  3642. conn->bits.done = FALSE; /* Curl_done() is not called yet */
  3643. conn->bits.do_more = FALSE; /* by default there's no curl_do_more() to use */
  3644. if(conn->curl_do) {
  3645. /* generic protocol-specific function pointer set in curl_connect() */
  3646. result = conn->curl_do(conn, done);
  3647. /* This was formerly done in transfer.c, but we better do it here */
  3648. if((CURLE_SEND_ERROR == result) && conn->bits.reuse) {
  3649. /* This was a re-use of a connection and we got a write error in the
  3650. * DO-phase. Then we DISCONNECT this connection and have another attempt
  3651. * to CONNECT and then DO again! The retry cannot possibly find another
  3652. * connection to re-use, since we only keep one possible connection for
  3653. * each. */
  3654. infof(data, "Re-used connection seems dead, get a new one\n");
  3655. conn->bits.close = TRUE; /* enforce close of this connection */
  3656. result = Curl_done(&conn, result, FALSE); /* we are so done with this */
  3657. /* conn may no longer be a good pointer */
  3658. /*
  3659. * According to bug report #1330310. We need to check for
  3660. * CURLE_SEND_ERROR here as well. I figure this could happen when the
  3661. * request failed on a FTP connection and thus Curl_done() itself tried
  3662. * to use the connection (again). Slight Lack of feedback in the report,
  3663. * but I don't think this extra check can do much harm.
  3664. */
  3665. if((CURLE_OK == result) || (CURLE_SEND_ERROR == result)) {
  3666. bool async;
  3667. bool protocol_done = TRUE;
  3668. /* Now, redo the connect and get a new connection */
  3669. result = Curl_connect(data, connp, &async, &protocol_done);
  3670. if(CURLE_OK == result) {
  3671. /* We have connected or sent away a name resolve query fine */
  3672. conn = *connp; /* setup conn to again point to something nice */
  3673. if(async) {
  3674. /* Now, if async is TRUE here, we need to wait for the name
  3675. to resolve */
  3676. result = Curl_wait_for_resolv(conn, NULL);
  3677. if(result)
  3678. return result;
  3679. /* Resolved, continue with the connection */
  3680. result = Curl_async_resolved(conn, &protocol_done);
  3681. if(result)
  3682. return result;
  3683. }
  3684. /* ... finally back to actually retry the DO phase */
  3685. result = conn->curl_do(conn, done);
  3686. }
  3687. }
  3688. }
  3689. }
  3690. return result;
  3691. }
  3692. CURLcode Curl_do_more(struct connectdata *conn)
  3693. {
  3694. CURLcode result=CURLE_OK;
  3695. if(conn->curl_do_more)
  3696. result = conn->curl_do_more(conn);
  3697. return result;
  3698. }