FtpControlSocket.cpp 182 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391
  1. //---------------------------------------------------------------------------
  2. #include "stdafx.h"
  3. #include "FtpControlSocket.h"
  4. #include "mainthread.h"
  5. #include "transfersocket.h"
  6. #include "asyncproxysocketlayer.h"
  7. #include "AsyncSslSocketLayer.h"
  8. #ifndef MPEXT_NO_GSS
  9. #include "AsyncGssSocketLayer.h"
  10. #endif
  11. #include "filezillaapi.h"
  12. #include <WideStrUtils.hpp>
  13. class CFtpControlSocket::CFileTransferData : public CFtpControlSocket::t_operation::COpData
  14. {
  15. public:
  16. CFileTransferData()
  17. {
  18. pDirectoryListing=0;
  19. nGotTransferEndReply=0;
  20. nWaitNextOpState=0;
  21. nMKDOpState=-1;
  22. hasRemoteDate = false;
  23. pFileSize=0;
  24. bUseAbsolutePaths = FALSE;
  25. bTriedPortPasvOnce = FALSE;
  26. askOnResumeFail = false;
  27. };
  28. ~CFileTransferData()
  29. {
  30. if (pDirectoryListing)
  31. delete pDirectoryListing;
  32. pDirectoryListing=0;
  33. delete pFileSize;
  34. };
  35. CString rawpwd;
  36. t_transferfile transferfile;
  37. t_transferdata transferdata;
  38. CString host;
  39. int port;
  40. BOOL bPasv;
  41. int nGotTransferEndReply;
  42. t_directory *pDirectoryListing;
  43. int nWaitNextOpState;
  44. CServerPath MKDCurrent;
  45. std::list<CString> MKDSegments;
  46. int nMKDOpState;
  47. bool hasRemoteDate;
  48. t_directory::t_direntry::t_date remoteDate;
  49. //CTime *pFileTime; //Used when downloading and OPTION_PRESERVEDOWNLOADFILETIME is set or when LIST fails
  50. _int64 *pFileSize; //Used when LIST failes
  51. BOOL bUseAbsolutePaths;
  52. BOOL bTriedPortPasvOnce;
  53. #ifndef MPEXT_NO_ZLIB
  54. int newZlibLevel;
  55. #endif
  56. bool askOnResumeFail;
  57. };
  58. class CFtpControlSocket::CLogonData:public CFtpControlSocket::t_operation::COpData
  59. {
  60. public:
  61. CLogonData()
  62. {
  63. waitForAsyncRequest = false;
  64. gotPassword = false;
  65. }
  66. virtual ~CLogonData()
  67. {
  68. }
  69. bool waitForAsyncRequest;
  70. bool gotPassword;
  71. };
  72. class CFtpControlSocket::CListData:public CFtpControlSocket::t_operation::COpData
  73. {
  74. public:
  75. CListData()
  76. {
  77. pDirectoryListing = 0;
  78. bTriedPortPasvOnce = FALSE;
  79. lastCmdSentCDUP = false;
  80. }
  81. virtual ~CListData()
  82. {
  83. if (pDirectoryListing)
  84. delete pDirectoryListing;
  85. }
  86. CString rawpwd;
  87. CServerPath path;
  88. CString fileName;
  89. CString subdir;
  90. BOOL bPasv;
  91. CString host;
  92. UINT port;
  93. int nFinish;
  94. t_directory *pDirectoryListing;
  95. BOOL bTriedPortPasvOnce;
  96. #ifndef MPEXT_NO_ZLIB
  97. int newZlibLevel;
  98. #endif
  99. bool lastCmdSentCDUP;
  100. };
  101. class CFtpControlSocket::CListFileData:public CFtpControlSocket::t_operation::COpData
  102. {
  103. public:
  104. CListFileData()
  105. {
  106. direntry = NULL;
  107. }
  108. ~CListFileData()
  109. {
  110. delete [] direntry;
  111. }
  112. CString fileName;
  113. CString dir;
  114. CString path;
  115. CServerPath pwd;
  116. t_directory::t_direntry * direntry;
  117. };
  118. class CFtpControlSocket::CMakeDirData : public CFtpControlSocket::t_operation::COpData
  119. {
  120. public:
  121. CMakeDirData() {}
  122. virtual ~CMakeDirData() {}
  123. CServerPath path;
  124. CServerPath Current;
  125. std::list<CString> Segments;
  126. };
  127. #define MKD_INIT -1
  128. #define MKD_FINDPARENT 0
  129. #define MKD_MAKESUBDIRS 1
  130. #define MKD_CHANGETOSUBDIR 2
  131. /////////////////////////////////////////////////////////////////////////////
  132. // CFtpControlSocket
  133. std::list<CFtpControlSocket::t_ActiveList> CFtpControlSocket::m_InstanceList[2];
  134. CTime CFtpControlSocket::m_CurrentTransferTime[2] = { CTime::GetCurrentTime(), CTime::GetCurrentTime() };
  135. _int64 CFtpControlSocket::m_CurrentTransferLimit[2] = {0, 0};
  136. CCriticalSection CFtpControlSocket::m_SpeedLimitSync;
  137. #define BUFSIZE 16384
  138. CFtpControlSocket::CFtpControlSocket(CMainThread *pMainThread, CFileZillaTools * pTools)
  139. {
  140. DebugAssert(pMainThread);
  141. m_pOwner=pMainThread;
  142. m_pTools=pTools;
  143. m_Operation.nOpMode=0;
  144. m_Operation.nOpState=-1;
  145. m_Operation.pData=0;
  146. m_pProxyLayer = NULL;
  147. m_pSslLayer = NULL;
  148. #ifndef MPEXT_NO_GSS
  149. m_pGssLayer = NULL;
  150. #endif
  151. m_pDirectoryListing=0;
  152. m_pTransferSocket=0;
  153. m_pDataFile=0;
  154. srand( (unsigned)time( NULL ) );
  155. m_bKeepAliveActive=FALSE;
  156. m_bCheckForTimeout=TRUE;
  157. m_bDidRejectCertificate = FALSE;
  158. #ifndef MPEXT_NO_ZLIB
  159. m_useZlib = false;
  160. m_zlibSupported = false;
  161. m_zlibLevel = 8;
  162. #endif
  163. m_bUTF8 = true;
  164. m_hasClntCmd = false;
  165. m_serverCapabilities.Clear();
  166. m_ListFile = "";
  167. m_awaitsReply = false;
  168. m_skipReply = false;
  169. m_sendBuffer = 0;
  170. m_sendBufferLen = 0;
  171. m_bProtP = false;
  172. m_mayBeMvsFilesystem = false;
  173. m_mayBeBS2000Filesystem = false;
  174. }
  175. CFtpControlSocket::~CFtpControlSocket()
  176. {
  177. DoClose();
  178. if (m_pTransferSocket)
  179. {
  180. m_pTransferSocket->Close();
  181. delete m_pTransferSocket;
  182. m_pTransferSocket=0;
  183. }
  184. if (m_pDataFile)
  185. {
  186. delete m_pDataFile;
  187. m_pDataFile=0;
  188. }
  189. Close();
  190. }
  191. void CFtpControlSocket::ShowStatus(UINT nID, int type) const
  192. {
  193. CString str;
  194. str.LoadString(nID);
  195. ShowStatus(str, type);
  196. }
  197. void CFtpControlSocket::ShowStatus(CString status, int type) const
  198. {
  199. if (!GetOptionVal(OPTION_MPEXT_LOG_SENSITIVE))
  200. {
  201. if ( status.Left(5)==L"PASS " )
  202. {
  203. int len=status.GetLength()-5;
  204. status=L"PASS ";
  205. for (int i=0;i<len;i++)
  206. status+=L"*";
  207. }
  208. else if ( status.Left(5)==L"ACCT " )
  209. {
  210. int len=status.GetLength()-5;
  211. status=L"ACCT ";
  212. for (int i=0;i<len;i++)
  213. status+=L"*";
  214. }
  215. }
  216. LogMessageRaw(type, (LPCTSTR)status);
  217. }
  218. void CFtpControlSocket::ShowTimeoutError(UINT nID) const
  219. {
  220. CString str1;
  221. str1.LoadString(IDS_ERRORMSG_TIMEOUT);
  222. CString str2;
  223. str2.LoadString(nID);
  224. CString message;
  225. message.Format(L"%s (%s)", str1, str2);
  226. ShowStatus(message, FZ_LOG_ERROR);
  227. }
  228. t_server CFtpControlSocket::GetCurrentServer()
  229. {
  230. return m_CurrentServer;
  231. }
  232. void CFtpControlSocket::Close()
  233. {
  234. if (m_pDirectoryListing)
  235. {
  236. delete m_pDirectoryListing;
  237. }
  238. m_pDirectoryListing=0;
  239. CAsyncSocketEx::Close();
  240. delete m_pProxyLayer;
  241. m_pProxyLayer = NULL;
  242. delete m_pSslLayer;
  243. m_pSslLayer = NULL;
  244. #ifndef MPEXT_NO_GSS
  245. delete m_pGssLayer;
  246. m_pGssLayer = NULL;
  247. #endif
  248. RemoveActiveTransfer();
  249. }
  250. BOOL CFtpControlSocket::Connect(CString hostAddress, UINT nHostPort)
  251. {
  252. hostAddress = ConvertDomainName(hostAddress);
  253. //Don't resolve host asynchronously when using proxies
  254. if (m_pProxyLayer)
  255. {
  256. return CAsyncSocketEx::Connect(hostAddress, nHostPort);
  257. }
  258. BOOL res = CAsyncSocketEx::Connect(hostAddress, nHostPort);
  259. int nLastError = WSAGetLastError();
  260. if (res || nLastError==WSAEWOULDBLOCK)
  261. {
  262. WSASetLastError(nLastError);
  263. }
  264. return res;
  265. }
  266. void CFtpControlSocket::SetDirectoryListing(t_directory *pDirectory, bool bSetWorkingDir /*=true*/)
  267. {
  268. if (m_pDirectoryListing)
  269. delete m_pDirectoryListing;
  270. m_CurrentServer=pDirectory->server;
  271. m_pDirectoryListing=new t_directory;
  272. *m_pDirectoryListing=*pDirectory;
  273. if (bSetWorkingDir)
  274. m_pOwner->SetWorkingDir(pDirectory);
  275. }
  276. /////////////////////////////////////////////////////////////////////////////
  277. // Member-Funktion CFtpControlSocket
  278. #define CONNECT_INIT -1
  279. #ifndef MPEXT_NO_GSS
  280. #define CONNECT_GSS_INIT -2
  281. #define CONNECT_GSS_AUTHDONE -3
  282. #define CONNECT_GSS_CWD -4
  283. #define CONNECT_GSS_FAILED -5
  284. #define CONNECT_GSS_NEEDPASS -6
  285. #define CONNECT_GSS_NEEDUSER -7
  286. #endif
  287. #define CONNECT_SSL_INIT -8
  288. #define CONNECT_SSL_NEGOTIATE -9
  289. #define CONNECT_TLS_NEGOTIATE -10
  290. #define CONNECT_SSL_WAITDONE -11
  291. #define CONNECT_SSL_PBSZ -12
  292. #define CONNECT_SSL_PROT -13
  293. #define CONNECT_FEAT -14
  294. #define CONNECT_SYST -15
  295. #define CONNECT_OPTSUTF8 -16
  296. #define CONNECT_CLNT -17
  297. #define CONNECT_OPTSMLST -18
  298. #define CONNECT_NEEDPASS -19
  299. #define CONNECT_HOST -20
  300. bool CFtpControlSocket::InitConnect()
  301. {
  302. USES_CONVERSION;
  303. // Reset detected capabilities
  304. m_bAnnouncesUTF8 = false;
  305. m_hasClntCmd = false;
  306. m_serverCapabilities.Clear();
  307. m_ListFile = "";
  308. m_isFileZilla = false;
  309. if (m_CurrentServer.nUTF8 == 2)
  310. m_bUTF8 = false;
  311. else
  312. m_bUTF8 = true;
  313. // Some sanity checks
  314. if (m_pOwner->IsConnected())
  315. {
  316. ShowStatus(L"Internal error: Connect called while still connected", FZ_LOG_ERROR);
  317. if (!m_Operation.nOpMode)
  318. m_Operation.nOpMode = CSMODE_CONNECT;
  319. DoClose(FZ_REPLY_CRITICALERROR);
  320. return false;
  321. }
  322. if (m_pSslLayer)
  323. {
  324. ShowStatus(L"Internal error: m_pSslLayer not zero in Connect", FZ_LOG_ERROR);
  325. DoClose(FZ_REPLY_CRITICALERROR);
  326. return false;
  327. }
  328. if (m_pProxyLayer)
  329. {
  330. ShowStatus(L"Internal error: m_pProxyLayer not zero in Connect", FZ_LOG_ERROR);
  331. DoClose(FZ_REPLY_CRITICALERROR);
  332. return false;
  333. }
  334. if (m_CurrentServer.nServerType & FZ_SERVERTYPE_LAYER_SSL_IMPLICIT ||
  335. m_CurrentServer.nServerType & FZ_SERVERTYPE_LAYER_SSL_EXPLICIT ||
  336. m_CurrentServer.nServerType & FZ_SERVERTYPE_LAYER_TLS_EXPLICIT)
  337. {
  338. m_pSslLayer = new CAsyncSslSocketLayer;
  339. AddLayer(m_pSslLayer);
  340. m_pSslLayer->SetClientCertificate(m_CurrentServer.Certificate, m_CurrentServer.PrivateKey);
  341. TCHAR buffer[1000];
  342. GetModuleFileName(NULL, buffer, 1000);
  343. CString filename = buffer;
  344. int pos = filename.ReverseFind(L'\\');
  345. if (pos != -1)
  346. {
  347. filename = filename.Left(pos + 1);
  348. filename += L"cacert.pem";
  349. }
  350. else
  351. filename = L"cacert.pem";
  352. m_pSslLayer->SetCertStorage(filename);
  353. }
  354. int nProxyType = GetOptionVal(OPTION_PROXYTYPE);
  355. if (nProxyType != PROXYTYPE_NOPROXY)
  356. {
  357. m_pProxyLayer = new CAsyncProxySocketLayer;
  358. m_pProxyLayer->SetProxy(
  359. nProxyType, T2CA(GetOption(OPTION_PROXYHOST)), GetOptionVal(OPTION_PROXYPORT),
  360. GetOptionVal(OPTION_PROXYUSELOGON), T2CA(GetOption(OPTION_PROXYUSER)), T2CA(GetOption(OPTION_PROXYPASS)));
  361. AddLayer(m_pProxyLayer);
  362. }
  363. #ifndef MPEXT_NO_GSS
  364. BOOL bUseGSS = FALSE;
  365. if (GetOptionVal(OPTION_USEGSS) && !m_pSslLayer)
  366. {
  367. CString GssServers=GetOption(OPTION_GSSSERVERS);
  368. LPCSTR lpszAscii=T2CA(m_CurrentServer.host);
  369. hostent *fullname=gethostbyname(lpszAscii);
  370. CString host;
  371. if (fullname)
  372. host=fullname->h_name;
  373. else
  374. host=m_CurrentServer.host;
  375. host.MakeLower();
  376. int i;
  377. while ((i=GssServers.Find(L";"))!=-1)
  378. {
  379. if ((L"."+GssServers.Left(i))==host.Right(GssServers.Left(i).GetLength()+1) || GssServers.Left(i)==host)
  380. {
  381. bUseGSS=TRUE;
  382. break;
  383. }
  384. GssServers=GssServers.Mid(i+1);
  385. }
  386. }
  387. if (bUseGSS)
  388. {
  389. m_pGssLayer = new CAsyncGssSocketLayer;
  390. AddLayer(m_pGssLayer);
  391. if (!m_pGssLayer->InitGSS())
  392. {
  393. ShowStatus(L"Unable to initialize GSS api", FZ_LOG_ERROR);
  394. DoClose(FZ_REPLY_CRITICALERROR);
  395. return false;
  396. }
  397. }
  398. #endif
  399. return true;
  400. }
  401. int CFtpControlSocket::InitConnectState()
  402. {
  403. if ((m_CurrentServer.nServerType & FZ_SERVERTYPE_LAYERMASK) & (FZ_SERVERTYPE_LAYER_SSL_EXPLICIT | FZ_SERVERTYPE_LAYER_TLS_EXPLICIT))
  404. return CONNECT_SSL_INIT;
  405. else
  406. #ifndef MPEXT_NO_GSS
  407. if (m_pGssLayer)
  408. return CONNECT_GSS_INIT;
  409. else
  410. #endif
  411. return CONNECT_INIT;
  412. }
  413. void CFtpControlSocket::Connect(t_server &server)
  414. {
  415. USES_CONVERSION;
  416. if (m_Operation.nOpMode)
  417. {
  418. ShowStatus(L"Internal error: m_Operation.nOpMode not zero in Connect", FZ_LOG_ERROR);
  419. m_Operation.nOpMode = CSMODE_CONNECT;
  420. DoClose(FZ_REPLY_CRITICALERROR);
  421. return;
  422. }
  423. m_Operation.nOpMode = CSMODE_CONNECT;
  424. m_CurrentServer = server;
  425. if (!InitConnect())
  426. return;
  427. if (!Create())
  428. {
  429. DoClose();
  430. return;
  431. }
  432. AsyncSelect();
  433. if (GetOptionVal(OPTION_MPEXT_HOST))
  434. {
  435. m_Operation.nOpState = CONNECT_HOST;
  436. }
  437. else
  438. {
  439. m_Operation.nOpState = InitConnectState();
  440. }
  441. if (server.nServerType & FZ_SERVERTYPE_LAYER_SSL_IMPLICIT)
  442. {
  443. if (!m_pSslLayer)
  444. {
  445. ShowStatus(L"Internal error: m_pSslLayer not initialized", FZ_LOG_ERROR);
  446. DoClose(FZ_REPLY_CRITICALERROR);
  447. return;
  448. }
  449. int res = m_pSslLayer->InitSSLConnection(true, NULL,
  450. GetOptionVal(OPTION_MPEXT_SSLSESSIONREUSE),
  451. m_pTools);
  452. if (res == SSL_FAILURE_INITSSL)
  453. ShowStatus(IDS_ERRORMSG_CANTINITSSL, FZ_LOG_ERROR);
  454. if (res)
  455. {
  456. DoClose();
  457. return;
  458. }
  459. }
  460. int logontype = GetOptionVal(OPTION_LOGONTYPE);
  461. int port;
  462. CString buf,temp;
  463. // are we connecting directly to the host (logon type 0) or via a firewall? (logon type>0)
  464. CString fwhost;
  465. int fwport;
  466. if(!logontype)
  467. {
  468. temp=server.host;
  469. port=server.port;
  470. }
  471. else
  472. {
  473. fwhost=GetOption(OPTION_FWHOST);
  474. fwport=GetOptionVal(OPTION_FWPORT);
  475. temp=fwhost;
  476. port=fwport;
  477. if(fwport!=21)
  478. fwhost.Format( L"%s:%d", fwhost, fwport); // add port to fwhost (only if port is not 21)
  479. }
  480. CString hostname = server.host;
  481. if(server.port!=21)
  482. hostname.Format( L"%s:%d", hostname, server.port); // add port to hostname (only if port is not 21)
  483. CString str;
  484. str.Format(IDS_STATUSMSG_CONNECTING, hostname);
  485. ShowStatus(str, FZ_LOG_STATUS);
  486. if (!Connect(temp, port))
  487. {
  488. if (WSAGetLastError() != WSAEWOULDBLOCK)
  489. {
  490. DoClose();
  491. return;
  492. }
  493. }
  494. m_ServerName = logontype?fwhost:hostname;
  495. m_LastRecvTime = m_LastSendTime = CTime::GetCurrentTime();
  496. m_Operation.pData = new CLogonData();
  497. }
  498. static CString NormalizePass(const CString & pass)
  499. {
  500. return CString(NormalizeString(UnicodeString(T2CW(pass))).c_str());
  501. }
  502. void CFtpControlSocket::LogOnToServer(BOOL bSkipReply /*=FALSE*/)
  503. {
  504. int logontype =
  505. #ifndef MPEXT_NO_GSS
  506. m_pGssLayer ? 0 :
  507. #endif
  508. GetOptionVal(OPTION_LOGONTYPE);
  509. const int LO = -2, ER = -1;
  510. CString buf, temp;
  511. const int NUMLOGIN = 9; // currently supports 9 different login sequences
  512. int logonseq[NUMLOGIN][20] = {
  513. // this array stores all of the logon sequences for the various firewalls
  514. // in blocks of 3 nums. 1st num is command to send, 2nd num is next point in logon sequence array
  515. // if 200 series response is rec'd from server as the result of the command, 3rd num is next
  516. // point in logon sequence if 300 series rec'd
  517. {0,LO,3, 1,LO,6, 12,LO,ER}, // no firewall
  518. {3,6,3, 4,6,ER, 5,9,9, 0,LO,12, 1,LO,15, 12,LO,ER}, // SITE hostname
  519. {3,6,3, 4,6,ER, 6,LO,9, 1,LO,12, 12,LO,ER}, // USER after logon
  520. {7,3,3, 0,LO,6, 1,LO,9, 12,LO,ER}, //proxy OPEN
  521. {3,6,3, 4,6,ER, 0,LO,9, 1,LO,12, 12,LO,ER}, // Transparent
  522. {6,LO,3, 1,LO,6, 12,LO,ER}, // USER remoteID@remotehost
  523. {8,6,3, 4,6,ER, 0,LO,9, 1,LO,12, 12,LO,ER}, //USER fireID@remotehost
  524. {9,ER,3, 1,LO,6, 2,LO,ER}, //USER remoteID@remotehost fireID
  525. {10,LO,3,11,LO,6,2,LO,ER} // USER remoteID@fireID@remotehost
  526. };
  527. if (m_Operation.nOpState == CONNECT_SSL_INIT)
  528. {
  529. if (m_CurrentServer.nServerType & FZ_SERVERTYPE_LAYER_SSL_EXPLICIT)
  530. {
  531. if (!SendAuthSsl())
  532. {
  533. return;
  534. }
  535. }
  536. else
  537. {
  538. if (!Send("AUTH TLS"))
  539. return;
  540. m_Operation.nOpState = CONNECT_TLS_NEGOTIATE;
  541. }
  542. return;
  543. }
  544. else if ((m_Operation.nOpState == CONNECT_SSL_NEGOTIATE) ||
  545. (m_Operation.nOpState == CONNECT_TLS_NEGOTIATE))
  546. {
  547. int res = GetReplyCode();
  548. if (res!=2 && res!=3)
  549. {
  550. if (m_Operation.nOpState == CONNECT_TLS_NEGOTIATE)
  551. {
  552. // Try to fall back to AUTH SSL
  553. if (!SendAuthSsl())
  554. {
  555. return;
  556. }
  557. }
  558. else
  559. {
  560. DoClose();
  561. }
  562. return;
  563. }
  564. else
  565. {
  566. if (!m_pSslLayer)
  567. {
  568. ShowStatus(L"Internal error: m_pSslLayer not initialized", FZ_LOG_ERROR);
  569. DoClose(FZ_REPLY_CRITICALERROR);
  570. return;
  571. }
  572. int res = m_pSslLayer->InitSSLConnection(true, NULL,
  573. GetOptionVal(OPTION_MPEXT_SSLSESSIONREUSE),
  574. m_pTools);
  575. if (res == SSL_FAILURE_INITSSL)
  576. ShowStatus(IDS_ERRORMSG_CANTINITSSL, FZ_LOG_ERROR);
  577. if (res)
  578. {
  579. DoClose();
  580. return;
  581. }
  582. }
  583. m_Operation.nOpState = CONNECT_SSL_WAITDONE;
  584. return;
  585. }
  586. else if (m_Operation.nOpState == CONNECT_SSL_WAITDONE)
  587. {
  588. m_Operation.nOpState = CONNECT_INIT;
  589. }
  590. else if (m_Operation.nOpState == CONNECT_SSL_PBSZ)
  591. {
  592. if (!Send(L"PROT P"))
  593. return;
  594. m_Operation.nOpState = CONNECT_SSL_PROT;
  595. return;
  596. }
  597. else if (m_Operation.nOpState == CONNECT_SSL_PROT)
  598. {
  599. int code = GetReplyCode();
  600. if (code == 2 || code == 3)
  601. m_bProtP = true;
  602. ShowStatus(IDS_STATUSMSG_CONNECTED, FZ_LOG_STATUS);
  603. m_pOwner->SetConnected(TRUE);
  604. ResetOperation(FZ_REPLY_OK);
  605. return;
  606. }
  607. #ifndef MPEXT_NO_GSS
  608. else
  609. if (m_Operation.nOpState==CONNECT_GSS_FAILED ||
  610. m_Operation.nOpState == CONNECT_GSS_NEEDPASS ||
  611. m_Operation.nOpState == CONNECT_GSS_NEEDUSER)
  612. {
  613. if (!m_RecvBuffer.empty() && m_RecvBuffer.front() != "")
  614. {
  615. //Incoming reply from server during async is not allowed
  616. DoClose();
  617. return;
  618. }
  619. }
  620. #endif
  621. else if (m_Operation.nOpState == CONNECT_HOST)
  622. {
  623. if (Send(L"HOST " + m_CurrentServer.host))
  624. {
  625. m_Operation.nOpState = InitConnectState();
  626. return;
  627. }
  628. }
  629. else if (m_Operation.nOpState == CONNECT_OPTSMLST)
  630. {
  631. int code = GetReplyCode();
  632. if (code != 2 && code != 3)
  633. m_serverCapabilities.SetCapability(mlsd_command, no);
  634. ShowStatus(IDS_STATUSMSG_CONNECTED, FZ_LOG_STATUS);
  635. m_pOwner->SetConnected(TRUE);
  636. ResetOperation(FZ_REPLY_OK);
  637. return;
  638. }
  639. else if (m_Operation.nOpState == CONNECT_FEAT)
  640. {
  641. std::string facts;
  642. if (m_serverCapabilities.GetCapabilityString(mlsd_command, &facts) == yes)
  643. {
  644. ftp_capabilities_t cap = m_serverCapabilities.GetCapabilityString(opts_mlst_command);
  645. if (cap == unknown)
  646. {
  647. std::transform(facts.begin(), facts.end(), facts.begin(), ::tolower);
  648. bool had_unset = false;
  649. std::string opts_facts;
  650. // Create a list of all facts understood by both FZ and the server.
  651. // Check if there's any supported fact not enabled by default, should that
  652. // be the case we need to send OPTS MLST
  653. while (!facts.empty())
  654. {
  655. size_t delim = facts.find_first_of(';');
  656. if (delim == -1)
  657. break;
  658. if (!delim)
  659. {
  660. facts = facts.substr(1, std::string::npos);
  661. continue;
  662. }
  663. bool enabled = false;
  664. std::string fact;
  665. if (facts[delim - 1] == '*')
  666. {
  667. if (delim == 1)
  668. {
  669. facts = facts.substr(delim + 1, std::string::npos);
  670. continue;
  671. }
  672. enabled = true;
  673. fact = facts.substr(0, delim - 1);
  674. }
  675. else
  676. {
  677. enabled = false;
  678. fact = facts.substr(0, delim);
  679. }
  680. facts = facts.substr(delim + 1, std::string::npos);
  681. if (!strcmp(fact.c_str(), "type") ||
  682. !strcmp(fact.c_str(), "size") ||
  683. !strcmp(fact.c_str(), "modify") ||
  684. !strcmp(fact.c_str(), "create") ||
  685. !strcmp(fact.c_str(), "perm") ||
  686. !strcmp(fact.c_str(), "unix.mode") ||
  687. !strcmp(fact.c_str(), "unix.owner") ||
  688. !strcmp(fact.c_str(), "unix.user") ||
  689. !strcmp(fact.c_str(), "unix.group") ||
  690. !strcmp(fact.c_str(), "unix.uid") ||
  691. !strcmp(fact.c_str(), "unix.gid"))
  692. {
  693. had_unset |= !enabled;
  694. opts_facts += fact.c_str();
  695. opts_facts += ";";
  696. }
  697. }
  698. if (had_unset)
  699. {
  700. m_serverCapabilities.SetCapability(opts_mlst_command, yes, opts_facts);
  701. }
  702. else
  703. {
  704. m_serverCapabilities.SetCapability(opts_mlst_command, no);
  705. }
  706. }
  707. }
  708. GetIntern()->PostMessage(FZ_MSG_MAKEMSG(FZ_MSG_CAPABILITIES, 0), (LPARAM)&m_serverCapabilities);
  709. if (!m_bAnnouncesUTF8 && !m_CurrentServer.nUTF8)
  710. m_bUTF8 = false;
  711. if (m_hasClntCmd)
  712. {
  713. // Some servers refuse to enable UTF8 if client does not send CLNT command
  714. // to fix compatibility with Internet Explorer, but in the process breaking
  715. // compatibility with other clients.
  716. // Rather than forcing MS to fix Internet Explorer, letting other clients
  717. // suffer is a questionable decision in my opinion.
  718. if (Send(CString(L"CLNT ") + m_pTools->GetClientString().c_str()))
  719. m_Operation.nOpState = CONNECT_CLNT;
  720. return;
  721. }
  722. if (m_bUTF8 && !m_isFileZilla)
  723. {
  724. // Handle servers that disobey RFC 2640 that have UTF8 in the FEAT
  725. // response but do not use UTF8 unless OPTS UTF8 ON gets send.
  726. // However these servers obey a conflicting ietf draft:
  727. // https://tools.ietf.org/html/draft-ietf-ftpext-utf-8-option-00
  728. // servers are, amongst others, G6 FTP Server and RaidenFTPd.
  729. if (Send(L"OPTS UTF8 ON"))
  730. m_Operation.nOpState = CONNECT_OPTSUTF8;
  731. return;
  732. }
  733. if ((m_CurrentServer.nServerType & FZ_SERVERTYPE_LAYERMASK) & (FZ_SERVERTYPE_LAYER_SSL_IMPLICIT | FZ_SERVERTYPE_LAYER_SSL_EXPLICIT | FZ_SERVERTYPE_LAYER_TLS_EXPLICIT))
  734. {
  735. m_Operation.nOpState = CONNECT_SSL_PBSZ;
  736. Send(L"PBSZ 0");
  737. return;
  738. }
  739. if (m_serverCapabilities.GetCapability(mlsd_command) == yes)
  740. {
  741. std::string args;
  742. // this is never true, see comment is DiscardLine
  743. if (m_serverCapabilities.GetCapabilityString(opts_mlst_command, &args) == yes &&
  744. !args.empty())
  745. {
  746. m_Operation.nOpState = CONNECT_OPTSMLST;
  747. Send("OPTS MLST " + CString(args.c_str()));
  748. return;
  749. }
  750. }
  751. ShowStatus(IDS_STATUSMSG_CONNECTED, FZ_LOG_STATUS);
  752. m_pOwner->SetConnected(TRUE);
  753. ResetOperation(FZ_REPLY_OK);
  754. return;
  755. }
  756. else if (m_Operation.nOpState == CONNECT_CLNT)
  757. {
  758. // See above why we send this command
  759. if (Send(L"OPTS UTF8 ON"))
  760. m_Operation.nOpState = CONNECT_OPTSUTF8;
  761. return;
  762. }
  763. else if (m_Operation.nOpState == CONNECT_OPTSUTF8)
  764. {
  765. if ((m_CurrentServer.nServerType & FZ_SERVERTYPE_LAYERMASK) & (FZ_SERVERTYPE_LAYER_SSL_IMPLICIT | FZ_SERVERTYPE_LAYER_SSL_EXPLICIT | FZ_SERVERTYPE_LAYER_TLS_EXPLICIT))
  766. {
  767. m_Operation.nOpState = CONNECT_SSL_PBSZ;
  768. Send(L"PBSZ 0");
  769. return;
  770. }
  771. ShowStatus(IDS_STATUSMSG_CONNECTED, FZ_LOG_STATUS);
  772. m_pOwner->SetConnected(TRUE);
  773. ResetOperation(FZ_REPLY_OK);
  774. return;
  775. }
  776. else if (m_Operation.nOpState == CONNECT_SYST)
  777. {
  778. if (GetReplyCode() == 2)
  779. {
  780. const CStringA reply = m_RecvBuffer.front();
  781. if (reply.GetLength() > 7 && reply.Mid(3, 4) == " MVS")
  782. m_mayBeMvsFilesystem = true;
  783. else if (reply.GetLength() >= 11 && reply.Mid(3, 8) == " BS-2000")
  784. m_mayBeBS2000Filesystem = true;
  785. if (reply.Find("FileZilla") != -1)
  786. m_isFileZilla = true;
  787. }
  788. if (Send(L"FEAT"))
  789. m_Operation.nOpState = CONNECT_FEAT;
  790. return;
  791. }
  792. else if (!bSkipReply)
  793. {
  794. int res = GetReplyCode();
  795. if (res != 2 && res != 3 && m_Operation.nOpState >= 0) // get initial connect msg off server
  796. {
  797. int nError = 0;
  798. if (m_bUTF8 && m_CurrentServer.nUTF8 != 1)
  799. {
  800. // Fall back to local charset for the case that the server might not
  801. // support UTF8 and the login data contains non-ascii characters.
  802. bool asciiOnly = true;
  803. for (int i = 0; i < m_CurrentServer.user.GetLength(); i++)
  804. if (m_CurrentServer.user.GetAt(i) > 127)
  805. asciiOnly = false;
  806. CString pass = NormalizePass(m_CurrentServer.pass);
  807. for (int i = 0; i < pass.GetLength(); i++)
  808. if (pass.GetAt(i) > 127)
  809. asciiOnly = false;
  810. for (int i = 0; i < m_CurrentServer.account.GetLength(); i++)
  811. if (m_CurrentServer.account.GetAt(i) > 127)
  812. asciiOnly = false;
  813. if (!asciiOnly)
  814. {
  815. ShowStatus(L"Login data contains non-ascii characters and server might not be UTF-8 aware. Trying local charset.", FZ_LOG_STATUS);
  816. m_bUTF8 = false;
  817. m_Operation.nOpState = CONNECT_INIT;
  818. }
  819. else
  820. nError = FZ_REPLY_ERROR;
  821. }
  822. else
  823. nError = FZ_REPLY_ERROR;
  824. if (nError)
  825. {
  826. if (res==5 && logonseq[logontype][m_Operation.nOpState]==1)
  827. nError|=FZ_REPLY_CRITICALERROR;
  828. DoClose(nError);
  829. return;
  830. }
  831. }
  832. }
  833. CString hostname = m_CurrentServer.host;
  834. if (m_CurrentServer.port != 21)
  835. hostname.Format(hostname+ L":%d", m_CurrentServer.port); // add port to hostname (only if port is not 21)
  836. USES_CONVERSION;
  837. #ifndef MPEXT_NO_GSS
  838. //**** GSS Authentication ****
  839. if (m_Operation.nOpState==CONNECT_GSS_INIT) //authenticate
  840. {
  841. int i = m_pGssLayer->GetClientAuth(T2CA(m_CurrentServer.host));
  842. if (i==-1)
  843. m_Operation.nOpState = CONNECT_GSS_AUTHDONE;
  844. else if (i != GSSAPI_AUTHENTICATION_SUCCEEDED)
  845. {
  846. m_Operation.nOpState = CONNECT_GSS_FAILED;
  847. CAsyncRequestData *pData=new CAsyncRequestData;
  848. pData->nRequestType=FZ_ASYNCREQUEST_GSS_AUTHFAILED;
  849. pData->nRequestID=m_pOwner->GetNextAsyncRequestID();
  850. if (!GetIntern()->PostMessage(FZ_MSG_MAKEMSG(FZ_MSG_ASYNCREQUEST, FZ_ASYNCREQUEST_GSS_AUTHFAILED), (LPARAM)pData))
  851. {
  852. delete pData;
  853. }
  854. else
  855. {
  856. m_bCheckForTimeout = FALSE;
  857. }
  858. }
  859. else
  860. {
  861. // we got authentication, we need to check whether we have forwardable tickets
  862. if (Send(L"CWD ."))
  863. m_Operation.nOpState = CONNECT_GSS_CWD;
  864. }
  865. return;
  866. }
  867. else if (m_Operation.nOpState == CONNECT_GSS_AUTHDONE)
  868. {
  869. if (!m_pGssLayer->AuthSuccessful())
  870. {
  871. m_Operation.nOpState = CONNECT_GSS_FAILED;
  872. CAsyncRequestData *pData=new CAsyncRequestData;
  873. pData->nRequestType = FZ_ASYNCREQUEST_GSS_AUTHFAILED;
  874. pData->nRequestID = m_pOwner->GetNextAsyncRequestID();
  875. if (!GetIntern()->PostMessage(FZ_MSG_MAKEMSG(FZ_MSG_ASYNCREQUEST, FZ_ASYNCREQUEST_GSS_AUTHFAILED), (LPARAM)pData))
  876. {
  877. delete pData;
  878. }
  879. else
  880. {
  881. m_bCheckForTimeout = FALSE;
  882. }
  883. return;
  884. }
  885. else
  886. {
  887. // we got authentication, we need to check whether we have forwardable tickets
  888. if (Send(L"CWD ."))
  889. m_Operation.nOpState = CONNECT_GSS_CWD;
  890. return;
  891. }
  892. }
  893. else if (m_Operation.nOpState == CONNECT_GSS_CWD)
  894. { // authentication succeeded, we're now get the response to the CWD command
  895. if (GetReplyCode() == 2) // we're logged on
  896. {
  897. if (Send(L"SYST"))
  898. m_Operation.nOpState = CONNECT_SYST;
  899. return;
  900. }
  901. else
  902. {
  903. //GSS authentication complete but we still have to go through the standard logon procedure
  904. m_Operation.nOpState = CONNECT_INIT;
  905. }
  906. }
  907. #endif
  908. if (m_Operation.nOpState==CONNECT_INIT)
  909. {
  910. if (logontype)
  911. {
  912. CString str;
  913. str.Format(IDS_STATUSMSG_FWCONNECT,hostname);
  914. ShowStatus(str,FZ_LOG_STATUS);
  915. }
  916. m_Operation.nOpState++;
  917. }
  918. else if (m_Operation.nOpState >= 0 && !bSkipReply)
  919. {
  920. m_Operation.nOpState=logonseq[logontype][m_Operation.nOpState+GetReplyCode()-1]; //get next command from array
  921. switch(m_Operation.nOpState)
  922. {
  923. case ER: // ER means summat has gone wrong
  924. DoClose();
  925. return;
  926. case LO: //LO means we are logged on
  927. if (Send(L"SYST"))
  928. m_Operation.nOpState = CONNECT_SYST;
  929. return;
  930. }
  931. }
  932. // go through appropriate logon procedure
  933. #ifndef MPEXT_NO_GSS
  934. int i = logonseq[logontype][m_Operation.nOpState];
  935. if (m_pGssLayer)
  936. {
  937. if ((i == 0 || i == 6 || i == 9 || i == 10) &&
  938. (m_CurrentServer.user == L"anonymous" || m_CurrentServer.user == L""))
  939. {
  940. //Extract user from kerberos ticket
  941. char str[256];
  942. if (m_pGssLayer->GetUserFromKrbTicket(str))
  943. m_CurrentServer.user = str;
  944. if (m_CurrentServer.user == L"")
  945. {
  946. CGssNeedUserRequestData *pData = new CGssNeedUserRequestData;
  947. pData->nRequestID = m_pOwner->GetNextAsyncRequestID();
  948. pData->nOldOpState = m_Operation.nOpState;
  949. m_Operation.nOpState = CONNECT_GSS_NEEDUSER;
  950. if (!GetIntern()->PostMessage(FZ_MSG_MAKEMSG(FZ_MSG_ASYNCREQUEST, FZ_ASYNCREQUEST_GSS_NEEDUSER), (LPARAM)pData))
  951. {
  952. delete pData;
  953. }
  954. else
  955. {
  956. m_bCheckForTimeout = FALSE;
  957. }
  958. return;
  959. }
  960. }
  961. else if ((i == 1 || i == 11) && (m_CurrentServer.pass == GetOption(OPTION_ANONPWD) || m_CurrentServer.pass == ""))
  962. {
  963. CGssNeedPassRequestData *pData=new CGssNeedPassRequestData;
  964. pData->nRequestID=m_pOwner->GetNextAsyncRequestID();
  965. pData->nOldOpState = m_Operation.nOpState;
  966. m_Operation.nOpState = CONNECT_GSS_NEEDPASS;
  967. if (!GetIntern()->PostMessage(FZ_MSG_MAKEMSG(FZ_MSG_ASYNCREQUEST, FZ_ASYNCREQUEST_GSS_NEEDPASS), (LPARAM)pData))
  968. {
  969. delete pData;
  970. }
  971. else
  972. {
  973. m_bCheckForTimeout = FALSE;
  974. }
  975. return;
  976. }
  977. }
  978. #endif
  979. CLogonData *pData = static_cast<CLogonData *>(m_Operation.pData);
  980. bool needpass = (m_CurrentServer.pass == GetOption(OPTION_ANONPWD)) || (m_CurrentServer.pass == L"");
  981. switch(logonseq[logontype][m_Operation.nOpState])
  982. {
  983. case 0:
  984. temp=L"USER "+m_CurrentServer.user;
  985. break;
  986. case 1:
  987. if (needpass && !pData->waitForAsyncRequest && !pData->gotPassword)
  988. {
  989. CNeedPassRequestData *pNeedPassRequestData = new CNeedPassRequestData();
  990. pNeedPassRequestData->nRequestID = m_pOwner->GetNextAsyncRequestID();
  991. pNeedPassRequestData->nOldOpState = m_Operation.nOpState;
  992. m_Operation.nOpState = CONNECT_NEEDPASS;
  993. if (!GetIntern()->PostMessage(FZ_MSG_MAKEMSG(FZ_MSG_ASYNCREQUEST, FZ_ASYNCREQUEST_NEEDPASS), (LPARAM)pNeedPassRequestData))
  994. {
  995. delete pNeedPassRequestData;
  996. ResetOperation(FZ_REPLY_ERROR);
  997. }
  998. else
  999. {
  1000. m_bCheckForTimeout = FALSE;
  1001. }
  1002. pData->waitForAsyncRequest = true;
  1003. return;
  1004. }
  1005. else if (!needpass || pData->gotPassword)
  1006. {
  1007. temp=L"PASS "+NormalizePass(m_CurrentServer.pass);
  1008. }
  1009. else
  1010. {
  1011. return;
  1012. }
  1013. break;
  1014. case 2:
  1015. temp=L"ACCT "+GetOption(OPTION_FWPASS);
  1016. break;
  1017. case 3:
  1018. temp=L"USER "+GetOption(OPTION_FWUSER);
  1019. break;
  1020. case 4:
  1021. temp=L"PASS "+GetOption(OPTION_FWPASS);
  1022. break;
  1023. case 5:
  1024. temp=L"SITE "+hostname;
  1025. break;
  1026. case 6:
  1027. temp=L"USER "+m_CurrentServer.user+L"@"+hostname;
  1028. break;
  1029. case 7:
  1030. temp=L"OPEN "+hostname;
  1031. break;
  1032. case 8:
  1033. temp=L"USER "+GetOption(OPTION_FWUSER)+L"@"+hostname;
  1034. break;
  1035. case 9:
  1036. temp=L"USER "+m_CurrentServer.user+L"@"+hostname+L" "+GetOption(OPTION_FWUSER);
  1037. break;
  1038. case 10:
  1039. temp=L"USER "+m_CurrentServer.user+L"@"+GetOption(OPTION_FWUSER)+L"@"+hostname;
  1040. break;
  1041. case 11:
  1042. if (needpass && !pData->waitForAsyncRequest && !pData->gotPassword)
  1043. {
  1044. CNeedPassRequestData *pNeedPassRequestData = new CNeedPassRequestData();
  1045. pNeedPassRequestData->nRequestID = m_pOwner->GetNextAsyncRequestID();
  1046. pNeedPassRequestData->nOldOpState = m_Operation.nOpState;
  1047. m_Operation.nOpState = CONNECT_NEEDPASS;
  1048. if (!GetIntern()->PostMessage(FZ_MSG_MAKEMSG(FZ_MSG_ASYNCREQUEST, FZ_ASYNCREQUEST_NEEDPASS), (LPARAM)pNeedPassRequestData))
  1049. {
  1050. delete pNeedPassRequestData;
  1051. ResetOperation(FZ_REPLY_ERROR);
  1052. }
  1053. else
  1054. {
  1055. m_bCheckForTimeout = FALSE;
  1056. }
  1057. pData->waitForAsyncRequest = true;
  1058. return;
  1059. }
  1060. else if (!needpass || pData->gotPassword)
  1061. {
  1062. temp=L"PASS "+NormalizePass(m_CurrentServer.pass)+L"@"+GetOption(OPTION_FWPASS);
  1063. }
  1064. else
  1065. {
  1066. return;
  1067. }
  1068. break;
  1069. case 12:
  1070. if (m_CurrentServer.account == L"")
  1071. temp = L"ACCT default";
  1072. else
  1073. temp = L"ACCT " + m_CurrentServer.account;
  1074. break;
  1075. }
  1076. // send command, get response
  1077. if(!Send(temp))
  1078. return;
  1079. }
  1080. BOOL CFtpControlSocket::SendAuthSsl()
  1081. {
  1082. if (!Send("AUTH SSL"))
  1083. return false;
  1084. m_Operation.nOpState = CONNECT_SSL_NEGOTIATE;
  1085. return true;
  1086. }
  1087. #define BUFFERSIZE 4096
  1088. void CFtpControlSocket::OnReceive(int nErrorCode)
  1089. {
  1090. m_LastRecvTime = CTime::GetCurrentTime();
  1091. if (!m_pOwner->IsConnected())
  1092. {
  1093. if (!m_Operation.nOpMode)
  1094. {
  1095. LogMessage(FZ_LOG_INFO, L"Socket has been closed, don't process receive" );
  1096. return;
  1097. }
  1098. m_MultiLine = "";
  1099. CString str;
  1100. str.Format(IDS_STATUSMSG_CONNECTEDWITH, m_ServerName);
  1101. ShowStatus(str, FZ_LOG_PROGRESS);
  1102. m_pOwner->SetConnected(TRUE);
  1103. }
  1104. char *buffer = new char[BUFFERSIZE];
  1105. int numread = Receive(buffer, BUFFERSIZE);
  1106. if (numread == SOCKET_ERROR)
  1107. {
  1108. delete [] buffer;
  1109. buffer = NULL;
  1110. int Error = GetLastError();
  1111. if (Error != WSAEWOULDBLOCK)
  1112. {
  1113. LogError(Error);
  1114. ShowStatus(IDS_STATUSMSG_DISCONNECTED, FZ_LOG_ERROR);
  1115. DoClose();
  1116. }
  1117. return;
  1118. }
  1119. if (!numread)
  1120. {
  1121. delete [] buffer;
  1122. buffer = NULL;
  1123. ShowStatus(IDS_STATUSMSG_DISCONNECTED, FZ_LOG_ERROR);
  1124. DoClose();
  1125. }
  1126. for (int i=0; i < numread; i++)
  1127. {
  1128. if ((buffer[i] == '\r') || (buffer[i] == '\n') || (buffer[i] == 0))
  1129. {
  1130. if (!m_RecvBuffer.empty() && m_RecvBuffer.back() != "")
  1131. {
  1132. USES_CONVERSION;
  1133. if (m_bUTF8)
  1134. {
  1135. // convert from UTF-8 to ANSI
  1136. LPCSTR utf8 = (LPCSTR)m_RecvBuffer.back();
  1137. if (DetectUTF8Encoding(RawByteString(utf8)) == etANSI)
  1138. {
  1139. if (m_CurrentServer.nUTF8 != 1)
  1140. {
  1141. LogMessage(FZ_LOG_WARNING, L"Server does not send proper UTF-8, falling back to local charset");
  1142. m_bUTF8 = false;
  1143. }
  1144. ShowStatus(A2CT(utf8), FZ_LOG_REPLY);
  1145. }
  1146. else
  1147. {
  1148. int len = MultiByteToWideChar(CP_UTF8, 0, utf8, -1, NULL, 0);
  1149. if (!len)
  1150. m_RecvBuffer.back() = "";
  1151. else
  1152. {
  1153. LPWSTR p1 = new WCHAR[len + 1];
  1154. MultiByteToWideChar(CP_UTF8, 0, utf8, -1 , (LPWSTR)p1, len + 1);
  1155. ShowStatus(W2CT(p1), FZ_LOG_REPLY);
  1156. delete [] p1;
  1157. }
  1158. }
  1159. }
  1160. else
  1161. {
  1162. ShowStatus(A2CT(m_RecvBuffer.back()), FZ_LOG_REPLY);
  1163. }
  1164. // Check for multi-line responses
  1165. // Partially duplicated in TFTPFileSystem::HandleReplyStatus
  1166. if (m_RecvBuffer.back().GetLength() > 3)
  1167. {
  1168. if (m_MultiLine != "")
  1169. {
  1170. if (m_RecvBuffer.back().Left(4) != m_MultiLine)
  1171. {
  1172. CStringA line = m_RecvBuffer.back();
  1173. if (line.Left(4) == m_MultiLine.Left(3) + '-')
  1174. {
  1175. line = line.Mid(4, line.GetLength() - 4);
  1176. }
  1177. DiscardLine(line);
  1178. m_RecvBuffer.pop_back();
  1179. }
  1180. else // end of multi-line found
  1181. {
  1182. m_MultiLine = "";
  1183. LPARAM lParam = 0;
  1184. #ifdef _DEBUG
  1185. lParam = GetTickCount();
  1186. #endif
  1187. m_pOwner->PostThreadMessage(m_pOwner->m_nInternalMessageID, FZAPI_THREADMSG_PROCESSREPLY, lParam);
  1188. }
  1189. }
  1190. // start of new multi-line
  1191. else if (m_RecvBuffer.back()[3] == '-')
  1192. {
  1193. // DDD<SP> is the end of a multi-line response
  1194. m_MultiLine = m_RecvBuffer.back().Left(3) + ' ';
  1195. m_RecvBuffer.pop_back();
  1196. }
  1197. else
  1198. {
  1199. LPARAM lParam = 0;
  1200. #ifdef _DEBUG
  1201. lParam = GetTickCount();
  1202. #endif
  1203. m_pOwner->PostThreadMessage(m_pOwner->m_nInternalMessageID, FZAPI_THREADMSG_PROCESSREPLY, lParam);
  1204. }
  1205. }
  1206. else
  1207. {
  1208. m_RecvBuffer.pop_back();
  1209. }
  1210. m_RecvBuffer.push_back("");
  1211. }
  1212. }
  1213. else
  1214. {
  1215. //The command may only be 2000 chars long. This ensures that a malicious user can't
  1216. //send extremely large commands to fill the memory of the server
  1217. if (m_RecvBuffer.empty())
  1218. m_RecvBuffer.push_back("");
  1219. if (m_RecvBuffer.back().GetLength() < 2000)
  1220. m_RecvBuffer.back() += buffer[i];
  1221. }
  1222. }
  1223. delete [] buffer;
  1224. }
  1225. void CFtpControlSocket::ProcessReply()
  1226. {
  1227. if (m_RecvBuffer.empty())
  1228. return;
  1229. if (m_awaitsReply)
  1230. {
  1231. if (m_sendBuffer)
  1232. TriggerEvent(FD_WRITE);
  1233. m_awaitsReply = false;
  1234. }
  1235. CString reply = GetReply();
  1236. if ( reply == L"" )
  1237. return;
  1238. // After Cancel, we might have to skip a reply
  1239. if (m_skipReply)
  1240. {
  1241. m_skipReply = false;
  1242. m_RecvBuffer.pop_front();
  1243. return;
  1244. }
  1245. if (m_bKeepAliveActive)
  1246. {
  1247. m_bKeepAliveActive = FALSE;
  1248. m_pOwner->PostThreadMessage(m_pOwner->m_nInternalMessageID,FZAPI_THREADMSG_POSTKEEPALIVE,0);
  1249. }
  1250. else if (m_Operation.nOpMode&CSMODE_CONNECT)
  1251. LogOnToServer();
  1252. else if (m_Operation.nOpMode& (CSMODE_COMMAND|CSMODE_CHMOD) )
  1253. {
  1254. if (GetReplyCode()== 2 || GetReplyCode()== 3)
  1255. ResetOperation(FZ_REPLY_OK);
  1256. else
  1257. ResetOperation(FZ_REPLY_ERROR);
  1258. }
  1259. else if (m_Operation.nOpMode&CSMODE_TRANSFER)
  1260. {
  1261. FileTransfer(0);
  1262. }
  1263. else if (m_Operation.nOpMode&CSMODE_LIST)
  1264. List(FALSE);
  1265. else if (m_Operation.nOpMode&CSMODE_LISTFILE)
  1266. ListFile(L"", CServerPath());
  1267. else if (m_Operation.nOpMode&CSMODE_DELETE)
  1268. Delete( L"",CServerPath(), false);
  1269. else if (m_Operation.nOpMode&CSMODE_RMDIR)
  1270. RemoveDir( L"",CServerPath());
  1271. else if (m_Operation.nOpMode&CSMODE_MKDIR)
  1272. MakeDir(CServerPath());
  1273. else if (m_Operation.nOpMode&CSMODE_RENAME)
  1274. Rename(L"", L"", CServerPath(), CServerPath());
  1275. if (!m_RecvBuffer.empty())
  1276. m_RecvBuffer.pop_front();
  1277. }
  1278. void CFtpControlSocket::OnConnect(int nErrorCode)
  1279. {
  1280. if (!m_Operation.nOpMode)
  1281. {
  1282. if (!m_pOwner->IsConnected())
  1283. DoClose();
  1284. return;
  1285. }
  1286. if (!nErrorCode)
  1287. {
  1288. if (!m_pOwner->IsConnected())
  1289. {
  1290. m_MultiLine = "";
  1291. m_pOwner->SetConnected(TRUE);
  1292. CString str;
  1293. str.Format(
  1294. m_pSslLayer ? IDS_STATUSMSG_CONNECTEDWITHSSL : IDS_STATUSMSG_CONNECTEDWITH,
  1295. m_ServerName);
  1296. ShowStatus(str,FZ_LOG_PROGRESS);
  1297. }
  1298. }
  1299. else
  1300. {
  1301. if (nErrorCode == WSAHOST_NOT_FOUND)
  1302. {
  1303. CString str;
  1304. str.Format(IDS_ERRORMSG_CANTRESOLVEHOST2, m_ServerName);
  1305. ShowStatus(str, FZ_LOG_ERROR);
  1306. }
  1307. else
  1308. {
  1309. TCHAR Buffer[255];
  1310. int Len = FormatMessage(
  1311. FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ARGUMENT_ARRAY,
  1312. NULL, nErrorCode, 0, Buffer, LENOF(Buffer), NULL);
  1313. while ((Len > 0) && ((Buffer[Len - 1] >= 0) && (Buffer[Len - 1] <= 32)))
  1314. {
  1315. --Len;
  1316. }
  1317. ShowStatus(CString(Buffer, Len), FZ_LOG_ERROR);
  1318. }
  1319. DoClose();
  1320. }
  1321. }
  1322. BOOL CFtpControlSocket::Send(CString str)
  1323. {
  1324. USES_CONVERSION;
  1325. ShowStatus(str, FZ_LOG_COMMAND);
  1326. str += L"\r\n";
  1327. int res = 0;
  1328. if (m_bUTF8)
  1329. {
  1330. LPCWSTR unicode = T2CW(str);
  1331. int len = WideCharToMultiByte(CP_UTF8, 0, unicode, -1, 0, 0, 0, 0);
  1332. if (!len)
  1333. {
  1334. ShowStatus(IDS_ERRORMSG_CANTSENDCOMMAND, FZ_LOG_ERROR);
  1335. DoClose();
  1336. return FALSE;
  1337. }
  1338. char* utf8 = new char[len + 1];
  1339. WideCharToMultiByte(CP_UTF8, 0, unicode, -1, utf8, len + 1, 0, 0);
  1340. int sendLen = strlen(utf8);
  1341. if (!m_awaitsReply && !m_sendBuffer)
  1342. res = CAsyncSocketEx::Send(utf8, strlen(utf8));
  1343. else
  1344. res = -2;
  1345. if ((res == SOCKET_ERROR && GetLastError() != WSAEWOULDBLOCK) || !res)
  1346. {
  1347. delete [] utf8;
  1348. ShowStatus(IDS_ERRORMSG_CANTSENDCOMMAND, FZ_LOG_ERROR);
  1349. DoClose();
  1350. return FALSE;
  1351. }
  1352. if (res != sendLen)
  1353. {
  1354. if (res < 0)
  1355. res = 0;
  1356. if (!m_sendBuffer)
  1357. {
  1358. m_sendBuffer = new char[sendLen - res];
  1359. memcpy(m_sendBuffer, utf8 + res, sendLen - res);
  1360. m_sendBufferLen = sendLen - res;
  1361. }
  1362. else
  1363. {
  1364. char* tmp = new char[m_sendBufferLen + sendLen - res];
  1365. memcpy(tmp, m_sendBuffer, m_sendBufferLen);
  1366. memcpy(tmp + m_sendBufferLen, utf8 + res, sendLen - res);
  1367. delete [] m_sendBuffer;
  1368. m_sendBuffer = tmp;
  1369. m_sendBufferLen += sendLen - res;
  1370. }
  1371. }
  1372. delete [] utf8;
  1373. }
  1374. else
  1375. {
  1376. LPCSTR lpszAsciiSend = T2CA(str);
  1377. int sendLen = strlen(lpszAsciiSend);
  1378. if (!m_awaitsReply && !m_sendBuffer)
  1379. res = CAsyncSocketEx::Send(lpszAsciiSend, strlen(lpszAsciiSend));
  1380. else
  1381. res = -2;
  1382. if ((res == SOCKET_ERROR && GetLastError() != WSAEWOULDBLOCK) || !res)
  1383. {
  1384. ShowStatus(IDS_ERRORMSG_CANTSENDCOMMAND, FZ_LOG_ERROR);
  1385. DoClose();
  1386. return FALSE;
  1387. }
  1388. if (res != sendLen)
  1389. {
  1390. if (res < 0)
  1391. res = 0;
  1392. if (!m_sendBuffer)
  1393. {
  1394. m_sendBuffer = new char[sendLen - res];
  1395. memcpy(m_sendBuffer, lpszAsciiSend, sendLen - res);
  1396. m_sendBufferLen = sendLen - res;
  1397. }
  1398. else
  1399. {
  1400. char* tmp = new char[m_sendBufferLen + sendLen - res];
  1401. memcpy(tmp, m_sendBuffer, m_sendBufferLen);
  1402. memcpy(tmp + m_sendBufferLen, lpszAsciiSend + res, sendLen - res);
  1403. delete [] m_sendBuffer;
  1404. m_sendBuffer = tmp;
  1405. m_sendBufferLen += sendLen - res;
  1406. }
  1407. }
  1408. }
  1409. if (res > 0)
  1410. {
  1411. m_awaitsReply = true;
  1412. m_LastSendTime = CTime::GetCurrentTime();
  1413. // Count timeout since the last request, not only since the last received data
  1414. // otherwise we may happen to timeout immediately after sending request if
  1415. // CheckForTimeout occurs in between and we haven't received any data for a while
  1416. m_LastRecvTime = m_LastSendTime;
  1417. }
  1418. return TRUE;
  1419. }
  1420. int CFtpControlSocket::GetReplyCode()
  1421. {
  1422. if (m_RecvBuffer.empty())
  1423. return 0;
  1424. CStringA str = m_RecvBuffer.front();
  1425. if (str == "")
  1426. return 0;
  1427. else
  1428. return str[0]-'0';
  1429. }
  1430. void CFtpControlSocket::DoClose(int nError /*=0*/)
  1431. {
  1432. LogMessage(FZ_LOG_INFO, L"Connection closed");
  1433. m_bCheckForTimeout=TRUE;
  1434. m_pOwner->SetConnected(FALSE);
  1435. m_bKeepAliveActive=FALSE;
  1436. if (nError & FZ_REPLY_CRITICALERROR)
  1437. nError |= FZ_REPLY_ERROR;
  1438. ResetOperation(FZ_REPLY_ERROR|FZ_REPLY_DISCONNECTED|nError);
  1439. m_RecvBuffer.clear();
  1440. m_MultiLine = "";
  1441. m_bDidRejectCertificate = FALSE;
  1442. #ifndef MPEXT_NO_ZLIB
  1443. m_useZlib = false;
  1444. m_zlibSupported = false;
  1445. m_zlibLevel = 0;
  1446. #endif
  1447. m_bUTF8 = false;
  1448. m_hasClntCmd = false;
  1449. m_serverCapabilities.Clear();
  1450. m_ListFile = "";
  1451. m_awaitsReply = false;
  1452. m_skipReply = false;
  1453. delete [] m_sendBuffer;
  1454. m_sendBuffer = 0;
  1455. m_sendBufferLen = 0;
  1456. m_bProtP = false;
  1457. m_mayBeMvsFilesystem = false;
  1458. m_mayBeBS2000Filesystem = false;
  1459. Close();
  1460. }
  1461. void CFtpControlSocket::Disconnect()
  1462. {
  1463. DebugAssert(!m_Operation.nOpMode);
  1464. m_Operation.nOpMode=CSMODE_DISCONNECT;
  1465. DoClose();
  1466. ShowStatus(IDS_STATUSMSG_DISCONNECTED,FZ_LOG_STATUS); //Send the disconnected message to the message log
  1467. }
  1468. void CFtpControlSocket::CheckForTimeout()
  1469. {
  1470. if (!m_Operation.nOpMode && !m_bKeepAliveActive)
  1471. return;
  1472. if (!m_bCheckForTimeout)
  1473. return;
  1474. int delay=GetOptionVal(OPTION_TIMEOUTLENGTH);
  1475. if (m_pTransferSocket)
  1476. {
  1477. int res=m_pTransferSocket->CheckForTimeout(delay);
  1478. if (res)
  1479. return;
  1480. }
  1481. CTimeSpan span=CTime::GetCurrentTime()-m_LastRecvTime;
  1482. if (span.GetTotalSeconds()>=delay)
  1483. {
  1484. ShowTimeoutError(IDS_CONTROL_CONNECTION);
  1485. DoClose();
  1486. }
  1487. }
  1488. void CFtpControlSocket::FtpCommand(LPCTSTR pCommand)
  1489. {
  1490. m_Operation.nOpMode=CSMODE_COMMAND;
  1491. Send(pCommand);
  1492. }
  1493. bool CFtpControlSocket::UsingMlsd()
  1494. {
  1495. return
  1496. // 0 = on, 1 = off, 2 = auto
  1497. (m_CurrentServer.iUseMlsd == 0) ||
  1498. ((m_CurrentServer.iUseMlsd != 1) &&
  1499. (m_serverCapabilities.GetCapability(mlsd_command) == yes));
  1500. }
  1501. bool CFtpControlSocket::UsingUtf8()
  1502. {
  1503. return m_bUTF8;
  1504. }
  1505. std::string CFtpControlSocket::GetTlsVersionStr()
  1506. {
  1507. if (m_pSslLayer != NULL)
  1508. {
  1509. return m_pSslLayer->GetTlsVersionStr();
  1510. }
  1511. else
  1512. {
  1513. return std::string();
  1514. }
  1515. }
  1516. std::string CFtpControlSocket::GetCipherName()
  1517. {
  1518. if (m_pSslLayer != NULL)
  1519. {
  1520. return m_pSslLayer->GetCipherName();
  1521. }
  1522. else
  1523. {
  1524. return std::string();
  1525. }
  1526. }
  1527. CString CFtpControlSocket::GetListingCmd()
  1528. {
  1529. CString cmd;
  1530. if (UsingMlsd())
  1531. {
  1532. cmd = L"MLSD";
  1533. }
  1534. else
  1535. {
  1536. cmd = L"LIST";
  1537. if (GetOptionVal(OPTION_MPEXT_SHOWHIDDEN) && !(m_CurrentServer.nServerType & (FZ_SERVERTYPE_SUB_FTP_MVS | FZ_SERVERTYPE_SUB_FTP_VMS | FZ_SERVERTYPE_SUB_FTP_BS2000)))
  1538. cmd += L" -a";
  1539. }
  1540. return cmd;
  1541. }
  1542. void CFtpControlSocket::List(BOOL bFinish, int nError /*=FALSE*/, CServerPath path /*=CServerPath()*/, CString subdir /*=L""*/)
  1543. {
  1544. USES_CONVERSION;
  1545. #define LIST_INIT -1
  1546. #define LIST_PWD 0
  1547. #define LIST_CWD 1
  1548. #define LIST_PWD2 2
  1549. #define LIST_CWD2 3
  1550. #define LIST_PWD3 4
  1551. #define LIST_MODE 5
  1552. #define LIST_OPTS 6
  1553. #define LIST_PORT_PASV 7
  1554. #define LIST_TYPE 8
  1555. #define LIST_LIST 9
  1556. #define LIST_WAITFINISH 10
  1557. DebugAssert(!m_Operation.nOpMode || m_Operation.nOpMode&CSMODE_LIST);
  1558. m_Operation.nOpMode|=CSMODE_LIST;
  1559. if (!m_pOwner->IsConnected())
  1560. {
  1561. ResetOperation(FZ_REPLY_ERROR|FZ_REPLY_NOTCONNECTED);
  1562. return;
  1563. }
  1564. if (bFinish || nError)
  1565. if (m_Operation.nOpMode!=CSMODE_LIST)
  1566. return; //Old message coming in
  1567. if (nError)
  1568. {
  1569. delete m_pTransferSocket;
  1570. m_pTransferSocket=0;
  1571. if (nError&CSMODE_TRANSFERTIMEOUT)
  1572. DoClose();
  1573. else
  1574. ResetOperation(FZ_REPLY_ERROR);
  1575. return;
  1576. }
  1577. CListData *pData = static_cast<CListData *>(m_Operation.pData);
  1578. if (bFinish)
  1579. {
  1580. if (!m_pTransferSocket || m_pTransferSocket->m_bListening)
  1581. {
  1582. delete m_pDirectoryListing;
  1583. m_pDirectoryListing = 0;
  1584. delete m_pTransferSocket;
  1585. m_pTransferSocket = 0;
  1586. ResetOperation(FZ_REPLY_ERROR);
  1587. return;
  1588. }
  1589. int num = 0;
  1590. pData->pDirectoryListing = new t_directory;
  1591. if (GetOptionVal(OPTION_DEBUGSHOWLISTING))
  1592. m_pTransferSocket->m_pListResult->SendToMessageLog();
  1593. pData->pDirectoryListing->direntry = m_pTransferSocket->m_pListResult->getList(num, false);
  1594. pData->pDirectoryListing->num = num;
  1595. if (m_pTransferSocket->m_pListResult->m_server.nServerType & FZ_SERVERTYPE_SUB_FTP_VMS && m_CurrentServer.nServerType & FZ_SERVERTYPE_FTP)
  1596. m_CurrentServer.nServerType |= FZ_SERVERTYPE_SUB_FTP_VMS;
  1597. pData->pDirectoryListing->server = m_CurrentServer;
  1598. pData->pDirectoryListing->path.SetServer(pData->pDirectoryListing->server);
  1599. if (pData->rawpwd != L"")
  1600. {
  1601. if (!pData->pDirectoryListing->path.SetPath(pData->rawpwd))
  1602. {
  1603. delete m_pDirectoryListing;
  1604. m_pDirectoryListing=0;
  1605. delete m_pTransferSocket;
  1606. m_pTransferSocket=0;
  1607. ResetOperation(FZ_REPLY_ERROR);
  1608. return;
  1609. }
  1610. m_pOwner->SetCurrentPath(pData->pDirectoryListing->path);
  1611. }
  1612. else
  1613. pData->pDirectoryListing->path = m_pOwner->GetCurrentPath();
  1614. if (m_Operation.nOpState!=LIST_WAITFINISH)
  1615. {
  1616. return;
  1617. }
  1618. else
  1619. {
  1620. delete m_pTransferSocket;
  1621. m_pTransferSocket=0;
  1622. }
  1623. }
  1624. if (m_Operation.nOpState==LIST_WAITFINISH)
  1625. {
  1626. if (!bFinish)
  1627. {
  1628. if (pData->nFinish==-1)
  1629. {
  1630. int code=GetReplyCode();
  1631. if (code== 2)
  1632. {
  1633. pData->nFinish=1;
  1634. }
  1635. else
  1636. pData->nFinish=0;
  1637. }
  1638. }
  1639. else
  1640. {
  1641. if (m_pTransferSocket)
  1642. delete m_pTransferSocket;
  1643. m_pTransferSocket=0;
  1644. }
  1645. if (pData->nFinish==0)
  1646. {
  1647. ResetOperation(FZ_REPLY_ERROR);
  1648. return;
  1649. }
  1650. else if (pData->pDirectoryListing && pData->nFinish==1)
  1651. {
  1652. ShowStatus(IDS_STATUSMSG_DIRLISTSUCCESSFUL,FZ_LOG_PROGRESS);
  1653. SetDirectoryListing(pData->pDirectoryListing);
  1654. ResetOperation(FZ_REPLY_OK);
  1655. return;
  1656. }
  1657. return;
  1658. }
  1659. else if (m_Operation.nOpState != LIST_INIT)
  1660. {
  1661. CString retmsg = GetReply();
  1662. BOOL error = FALSE;
  1663. int code = GetReplyCode();
  1664. switch (m_Operation.nOpState)
  1665. {
  1666. case LIST_PWD: //Reply to PWD command
  1667. if (code != 2 && code !=3 )
  1668. {
  1669. error = TRUE;
  1670. break;
  1671. }
  1672. pData->rawpwd = retmsg;
  1673. if ((m_mayBeMvsFilesystem || m_mayBeBS2000Filesystem) && m_CurrentServer.nServerType & FZ_SERVERTYPE_FTP &&
  1674. pData->rawpwd[0] != L'/')
  1675. {
  1676. m_mayBeMvsFilesystem = false;
  1677. m_mayBeBS2000Filesystem = false;
  1678. if (m_mayBeBS2000Filesystem)
  1679. m_CurrentServer.nServerType |= FZ_SERVERTYPE_SUB_FTP_BS2000;
  1680. else
  1681. m_CurrentServer.nServerType |= FZ_SERVERTYPE_SUB_FTP_MVS;
  1682. if (!pData->path.IsEmpty())
  1683. pData->path.SetServer(m_CurrentServer);
  1684. }
  1685. if (!ParsePwdReply(pData->rawpwd))
  1686. return;
  1687. if (pData->path.IsEmpty() || pData->path == m_pOwner->GetCurrentPath())
  1688. {
  1689. m_Operation.nOpState = NeedModeCommand() ? LIST_MODE : (NeedOptsCommand() ? LIST_OPTS : LIST_TYPE);
  1690. }
  1691. else
  1692. m_Operation.nOpState = LIST_CWD;
  1693. break;
  1694. case LIST_CWD:
  1695. if (code != 2 && code != 3)
  1696. error = TRUE;
  1697. m_Operation.nOpState = LIST_PWD2;
  1698. break;
  1699. case LIST_PWD2: //Reply to PWD command
  1700. if (code !=2 && code != 3)
  1701. error = TRUE;
  1702. else
  1703. {
  1704. pData->rawpwd = retmsg;
  1705. if (!ParsePwdReply(pData->rawpwd))
  1706. return;
  1707. }
  1708. if (pData->subdir != L"")
  1709. {
  1710. if (pData->path != m_pOwner->GetCurrentPath())
  1711. {
  1712. ResetOperation(FZ_REPLY_ERROR);
  1713. return;
  1714. }
  1715. m_Operation.nOpState = LIST_CWD2;
  1716. }
  1717. else
  1718. {
  1719. m_Operation.nOpState = NeedModeCommand() ? LIST_MODE : (NeedOptsCommand() ? LIST_OPTS : LIST_TYPE);
  1720. }
  1721. break;
  1722. case LIST_CWD2:
  1723. if (pData->lastCmdSentCDUP)
  1724. {
  1725. CString reply = GetReply().Left(3);
  1726. int replycode = _ttoi(reply);
  1727. if (replycode >= 500 && replycode < 505)
  1728. break;
  1729. pData->lastCmdSentCDUP = false;
  1730. }
  1731. if (code != 2 && code != 3)
  1732. error = TRUE;
  1733. m_Operation.nOpState = LIST_PWD3;
  1734. break;
  1735. case LIST_PWD3: //Reply to PWD command
  1736. if (code != 2 && code != 3)
  1737. error = TRUE;
  1738. else
  1739. {
  1740. pData->rawpwd = retmsg;
  1741. if (!ParsePwdReply(pData->rawpwd))
  1742. return;
  1743. }
  1744. m_Operation.nOpState = NeedModeCommand() ? LIST_MODE : (NeedOptsCommand() ? LIST_OPTS : LIST_TYPE);
  1745. break;
  1746. case LIST_MODE:
  1747. #ifndef MPEXT_NO_ZLIB
  1748. if (code == 2 || code == 3)
  1749. m_useZlib = !m_useZlib;
  1750. #endif
  1751. m_Operation.nOpState = NeedOptsCommand() ? LIST_OPTS : LIST_TYPE;
  1752. break;
  1753. case LIST_OPTS:
  1754. #ifndef MPEXT_NO_ZLIB
  1755. if (code == 2 || code == 3)
  1756. m_zlibLevel = pData->newZlibLevel;
  1757. #endif
  1758. m_Operation.nOpState = LIST_TYPE;
  1759. break;
  1760. case LIST_TYPE:
  1761. if (code!=2 && code!=3)
  1762. error=TRUE;
  1763. m_Operation.nOpState = LIST_PORT_PASV;
  1764. break;
  1765. case LIST_PORT_PASV:
  1766. if (code!=2 && code!=3)
  1767. {
  1768. error=TRUE;
  1769. break;
  1770. }
  1771. if (pData->bPasv)
  1772. {
  1773. CString temp;
  1774. int i,j;
  1775. // MP EXT
  1776. if((i=retmsg.Find(L"("))>=0&&(j=retmsg.Find(L")"))>=0)
  1777. {
  1778. i++;
  1779. j--;
  1780. }
  1781. else
  1782. {
  1783. // MP EXT
  1784. if ((i=retmsg.Mid(4).FindOneOf(L"0123456789"))>=0)
  1785. {
  1786. i += 4;
  1787. j = retmsg.GetLength() - 1;
  1788. }
  1789. else
  1790. {
  1791. if (!pData->bTriedPortPasvOnce)
  1792. {
  1793. pData->bTriedPortPasvOnce = TRUE;
  1794. pData->bPasv = !pData->bPasv;
  1795. }
  1796. else
  1797. error=TRUE;
  1798. break;
  1799. }
  1800. }
  1801. temp = retmsg.Mid(i,(j-i)+1);
  1802. if (GetFamily() == AF_INET)
  1803. {
  1804. i=temp.ReverseFind(L',');
  1805. pData->port=atol( T2CA( temp.Right(temp.GetLength()-(i+1)) ) ); //get ls byte of server socket
  1806. temp=temp.Left(i);
  1807. i=temp.ReverseFind(L',');
  1808. pData->port+=256*atol( T2CA( temp.Right(temp.GetLength()-(i+1)) ) ); // add ms byte to server socket
  1809. pData->host = temp.Left(i);
  1810. pData->host.Replace(L',', L'.');
  1811. if (!CheckForcePasvIp(pData->host))
  1812. {
  1813. error = TRUE;
  1814. break;
  1815. }
  1816. }
  1817. else if (GetFamily() == AF_INET6)
  1818. {
  1819. temp = temp.Mid(3);
  1820. pData->port = atol( T2CA(temp.Left(temp.GetLength() - 1) ) );
  1821. if (pData->port < 0 || pData->port > 65535)
  1822. {
  1823. LogMessage(FZ_LOG_WARNING, L"Port %u not valid", pData->port);
  1824. error = TRUE;
  1825. break;
  1826. }
  1827. pData->host = m_CurrentServer.host;
  1828. }
  1829. else
  1830. {
  1831. LogMessage(FZ_LOG_WARNING, L"Protocol %d not supported", GetFamily());
  1832. error = TRUE;
  1833. break;
  1834. }
  1835. }
  1836. m_Operation.nOpState = LIST_LIST;
  1837. break;
  1838. case LIST_LIST:
  1839. if (IsMisleadingListResponse())
  1840. {
  1841. ShowStatus(IDS_STATUSMSG_DIRLISTSUCCESSFUL, FZ_LOG_PROGRESS);
  1842. t_directory listing;
  1843. listing.server = m_CurrentServer;
  1844. listing.path = m_pOwner->GetCurrentPath();
  1845. SetDirectoryListing(&listing);
  1846. ResetOperation(FZ_REPLY_OK);
  1847. return;
  1848. }
  1849. else if (code != 1)
  1850. error = TRUE;
  1851. else
  1852. m_Operation.nOpState = LIST_WAITFINISH;
  1853. break;
  1854. default:
  1855. error = TRUE;
  1856. }
  1857. if (error)
  1858. {
  1859. ResetOperation(FZ_REPLY_ERROR);
  1860. return;
  1861. }
  1862. }
  1863. if (m_Operation.nOpState==LIST_INIT)
  1864. { //Initialize some variables
  1865. pData=new CListData;
  1866. pData->path=path;
  1867. pData->subdir=subdir;
  1868. m_Operation.pData=pData;
  1869. ShowStatus(IDS_STATUSMSG_RETRIEVINGDIRLIST, FZ_LOG_PROGRESS);
  1870. pData->nFinish=-1;
  1871. if (m_pDirectoryListing)
  1872. {
  1873. delete m_pDirectoryListing;
  1874. m_pDirectoryListing=0;
  1875. }
  1876. if (GetOptionVal(OPTION_PROXYTYPE)!=PROXYTYPE_NOPROXY)
  1877. pData->bPasv = TRUE;
  1878. else if (m_CurrentServer.nPasv == 1)
  1879. pData->bPasv = TRUE;
  1880. else if (m_CurrentServer.nPasv == 2)
  1881. pData->bPasv = FALSE;
  1882. else
  1883. pData->bPasv = GetOptionVal(OPTION_PASV);
  1884. CServerPath path = pData->path;
  1885. CServerPath realpath = m_pOwner->GetCurrentPath();
  1886. if (!realpath.IsEmpty())
  1887. {
  1888. if (!pData->path.IsEmpty() && pData->path != realpath)
  1889. m_Operation.nOpState=LIST_CWD;
  1890. else if (!pData->path.IsEmpty() && pData->subdir!=L"")
  1891. m_Operation.nOpState=LIST_CWD2;
  1892. else
  1893. {
  1894. m_Operation.nOpState = NeedModeCommand() ? LIST_MODE : (NeedOptsCommand() ? LIST_OPTS : LIST_TYPE);;
  1895. }
  1896. }
  1897. else
  1898. m_Operation.nOpState = LIST_PWD;
  1899. }
  1900. CString cmd;
  1901. if (m_Operation.nOpState == LIST_PWD)
  1902. cmd=L"PWD";
  1903. else if (m_Operation.nOpState==LIST_CWD)
  1904. cmd=L"CWD " + pData->path.GetPathUnterminated(); //Command to retrieve the current directory
  1905. else if (m_Operation.nOpState==LIST_PWD2)
  1906. cmd=L"PWD";
  1907. else if (m_Operation.nOpState==LIST_CWD2)
  1908. {
  1909. if (!pData->subdir)
  1910. {
  1911. ResetOperation(FZ_REPLY_ERROR);
  1912. return;
  1913. }
  1914. if (pData->subdir != L".." )
  1915. {
  1916. if (m_CurrentServer.nServerType & FZ_SERVERTYPE_SUB_FTP_VMS)
  1917. {
  1918. CServerPath path = m_pOwner->GetCurrentPath();
  1919. path.AddSubdir(pData->subdir);
  1920. cmd = L"CWD " + path.GetPathUnterminated();
  1921. }
  1922. else
  1923. cmd = L"CWD " + pData->subdir;
  1924. }
  1925. else
  1926. {
  1927. if (pData->lastCmdSentCDUP)
  1928. {
  1929. pData->lastCmdSentCDUP = false;
  1930. cmd = L"CWD ..";
  1931. }
  1932. else
  1933. {
  1934. pData->lastCmdSentCDUP = true;
  1935. cmd = L"CDUP";
  1936. }
  1937. }
  1938. }
  1939. else if (m_Operation.nOpState == LIST_PWD3)
  1940. cmd=L"PWD";
  1941. else if (m_Operation.nOpState == LIST_MODE)
  1942. {
  1943. #ifdef MPEXT_NO_ZLIB
  1944. DebugFail();
  1945. #else
  1946. if (m_useZlib)
  1947. #endif
  1948. cmd = L"MODE S";
  1949. #ifndef MPEXT_NO_ZLIB
  1950. else
  1951. cmd = L"MODE Z";
  1952. #endif
  1953. }
  1954. else if (m_Operation.nOpState == LIST_OPTS)
  1955. {
  1956. #ifdef MPEXT_NO_ZLIB
  1957. DebugFail();
  1958. #else
  1959. pData->newZlibLevel = GetOptionVal(OPTION_MODEZ_LEVEL);
  1960. cmd.Format(L"OPTS MODE Z LEVEL %d", pData->newZlibLevel);
  1961. #endif
  1962. }
  1963. else if (m_Operation.nOpState == LIST_PORT_PASV)
  1964. {
  1965. m_pTransferSocket = new CTransferSocket(this, m_Operation.nOpMode);
  1966. #ifndef MPEXT_NO_ZLIB
  1967. if (m_useZlib)
  1968. {
  1969. if (!m_pTransferSocket->InitZlib(m_zlibLevel))
  1970. {
  1971. ShowStatus(L"Failed to initialize zlib", FZ_LOG_ERROR);
  1972. ResetOperation(FZ_REPLY_ERROR);
  1973. return;
  1974. }
  1975. }
  1976. #endif
  1977. m_pTransferSocket->m_nInternalMessageID = m_pOwner->m_nInternalMessageID;
  1978. #ifndef MPEXT_NO_GSS
  1979. if (m_pGssLayer && m_pGssLayer->AuthSuccessful())
  1980. m_pTransferSocket->UseGSS(m_pGssLayer);
  1981. #endif
  1982. m_pTransferSocket->SetFamily(GetFamily());
  1983. if (!m_pTransferSocket->Create(m_pSslLayer && m_bProtP) ||
  1984. !m_pTransferSocket->AsyncSelect())
  1985. {
  1986. ShowStatus(L"Failed to create socket", FZ_LOG_ERROR);
  1987. ResetOperation(FZ_REPLY_ERROR);
  1988. return;
  1989. }
  1990. if (pData->bPasv)
  1991. switch (GetFamily())
  1992. {
  1993. case AF_INET:
  1994. cmd = L"PASV";
  1995. break;
  1996. case AF_INET6:
  1997. cmd = L"EPSV";
  1998. break;
  1999. default:
  2000. LogMessage(FZ_LOG_WARNING, L"Protocol %d not supported", GetFamily());
  2001. ResetOperation(FZ_REPLY_ERROR);
  2002. return;
  2003. }
  2004. else
  2005. {
  2006. m_pTransferSocket->m_bListening=TRUE;
  2007. if (m_pProxyLayer)
  2008. {
  2009. SOCKADDR_IN addr;
  2010. int len=sizeof(addr);
  2011. if (!m_pProxyLayer->GetPeerName((SOCKADDR *)&addr,&len))
  2012. {
  2013. ResetOperation(FZ_REPLY_ERROR);
  2014. return;
  2015. }
  2016. else if (!m_pTransferSocket->Listen(addr.sin_addr.S_un.S_addr))
  2017. {
  2018. ResetOperation(FZ_REPLY_ERROR);
  2019. return;
  2020. }
  2021. }
  2022. else
  2023. {
  2024. //Set up an active file transfer
  2025. CString tempHostname;
  2026. UINT nPort;
  2027. if (// create listen socket (let MFC choose the port) & start the socket listening
  2028. !m_pTransferSocket->Listen() ||
  2029. !m_pTransferSocket->GetSockName(tempHostname, nPort))
  2030. {
  2031. ShowStatus(L"Failed to create listen socket", FZ_LOG_ERROR);
  2032. ResetOperation(FZ_REPLY_ERROR);
  2033. return;
  2034. }
  2035. CString host;
  2036. bool bError = false;
  2037. if (GetFamily() == AF_INET)
  2038. {
  2039. host = GetOption(OPTION_TRANSFERIP);
  2040. if (host != L"")
  2041. {
  2042. DWORD ip = inet_addr(T2CA(host));
  2043. if (ip != INADDR_NONE)
  2044. host.Format(L"%d,%d,%d,%d", ip%256, (ip>>8)%256, (ip>>16)%256, ip>>24);
  2045. else
  2046. {
  2047. hostent *fullname = gethostbyname(T2CA(host));
  2048. if (!fullname)
  2049. host = L"";
  2050. else
  2051. {
  2052. DWORD ip = ((LPIN_ADDR)fullname->h_addr)->s_addr;
  2053. if (ip != INADDR_NONE)
  2054. host.Format(L"%d,%d,%d,%d", ip%256, (ip>>8)%256, (ip>>16)%256, ip>>24);
  2055. else
  2056. host = L"";
  2057. }
  2058. }
  2059. }
  2060. if (host == L"")
  2061. {
  2062. UINT temp;
  2063. if (!GetSockName(host, temp))
  2064. {
  2065. ShowStatus(L"Failed to get socket address ", FZ_LOG_ERROR);
  2066. bError = true;
  2067. }
  2068. host.Replace(L'.', L',');
  2069. }
  2070. if (!bError)
  2071. {
  2072. host.Format(host+L",%d,%d", nPort/256, nPort%256);
  2073. cmd = L"PORT " + host; // send PORT cmd to server
  2074. }
  2075. }
  2076. else if (GetFamily() == AF_INET6)
  2077. {
  2078. host = GetOption(OPTION_TRANSFERIP6);
  2079. if (host != L"")
  2080. {
  2081. USES_CONVERSION;
  2082. addrinfo hints, *res;
  2083. memset(&hints, 0, sizeof(addrinfo));
  2084. hints.ai_family = AF_INET6;
  2085. hints.ai_socktype = SOCK_STREAM;
  2086. if (!getaddrinfo(T2CA(host), "1024", &hints, &res))
  2087. {
  2088. host = Inet6AddrToString(((SOCKADDR_IN6 *)res->ai_addr)->sin6_addr);
  2089. freeaddrinfo(res);
  2090. }
  2091. else
  2092. host = L"";
  2093. }
  2094. if (host == L"")
  2095. {
  2096. UINT temp;
  2097. if(!GetSockName(host, temp))
  2098. bError = true;
  2099. }
  2100. if (!bError)
  2101. {
  2102. // assamble EPRT command
  2103. cmd.Format(L"EPRT |2|" + host + L"|%d|", nPort);
  2104. }
  2105. }
  2106. else
  2107. {
  2108. LogMessage(FZ_LOG_WARNING, L"Protocol %d not supported", GetFamily());
  2109. bError = true;
  2110. }
  2111. if (bError)
  2112. {
  2113. ResetOperation(FZ_REPLY_ERROR);
  2114. return;
  2115. }
  2116. }
  2117. }
  2118. }
  2119. else if (m_Operation.nOpState==LIST_TYPE)
  2120. cmd=L"TYPE A";
  2121. else if (m_Operation.nOpState==LIST_LIST)
  2122. {
  2123. if (!m_pTransferSocket)
  2124. {
  2125. LogMessage(FZ_LOG_APIERROR, L"Error: m_pTransferSocket==NULL" );
  2126. ResetOperation(FZ_REPLY_ERROR);
  2127. return;
  2128. }
  2129. m_pTransferSocket->SetActive();
  2130. cmd = GetListingCmd();
  2131. if (!Send(cmd))
  2132. return;
  2133. if (pData->bPasv)
  2134. {
  2135. // if PASV create the socket & initiate outbound data channel connection
  2136. if (!ConnectTransferSocket(pData->host, pData->port))
  2137. {
  2138. ResetOperation(FZ_REPLY_ERROR);
  2139. return;
  2140. }
  2141. }
  2142. return;
  2143. }
  2144. if (cmd != L"")
  2145. Send(cmd);
  2146. }
  2147. bool CFtpControlSocket::ConnectTransferSocket(const CString & host, UINT port)
  2148. {
  2149. CString hostname;
  2150. hostname.Format(L"%s:%d", host, port);
  2151. CString str;
  2152. str.Format(IDS_STATUSMSG_CONNECTING, hostname);
  2153. ShowStatus(str, FZ_LOG_PROGRESS);
  2154. bool result = true;
  2155. if (!m_pTransferSocket->Connect(host, port))
  2156. {
  2157. if (GetLastError() != WSAEWOULDBLOCK)
  2158. {
  2159. result = false;
  2160. }
  2161. }
  2162. return result;
  2163. }
  2164. void CFtpControlSocket::ListFile(CString filename, const CServerPath &path)
  2165. {
  2166. USES_CONVERSION;
  2167. #define LISTFILE_INIT -1
  2168. #define LISTFILE_MLST 1
  2169. #define LISTFILE_TYPE 2
  2170. #define LISTFILE_SIZE 3
  2171. #define LISTFILE_MDTM 4
  2172. #define LISTFILE_PWD 5
  2173. #define LISTFILE_CWD 6
  2174. #define LISTFILE_CWD2 7
  2175. DebugAssert(!m_Operation.nOpMode || m_Operation.nOpMode&CSMODE_LISTFILE);
  2176. m_Operation.nOpMode|=CSMODE_LISTFILE;
  2177. if (!m_pOwner->IsConnected())
  2178. {
  2179. ResetOperation(FZ_REPLY_ERROR|FZ_REPLY_NOTCONNECTED);
  2180. return;
  2181. }
  2182. CListFileData * pData = static_cast<CListFileData *>(m_Operation.pData);
  2183. BOOL error = FALSE;
  2184. CString cmd;
  2185. CString retmsg;
  2186. int code = -1;
  2187. int num = -1;
  2188. switch (m_Operation.nOpState)
  2189. {
  2190. case LISTFILE_INIT:
  2191. //Initialize some variables
  2192. pData = new CListFileData;
  2193. pData->fileName = filename;
  2194. pData->dir = path.GetPath();
  2195. // special case for listing a root folder
  2196. pData->path = (filename == L"/") ? pData->dir : path.FormatFilename(filename);
  2197. m_Operation.pData = pData;
  2198. ShowStatus(IDS_STATUSMSG_RETRIEVINGLISTFILE, FZ_LOG_PROGRESS);
  2199. if (UsingMlsd())
  2200. {
  2201. m_Operation.nOpState = LISTFILE_MLST;
  2202. cmd = L"MLST " + pData->path;
  2203. }
  2204. else
  2205. {
  2206. m_Operation.nOpState = LISTFILE_PWD;
  2207. cmd = L"PWD";
  2208. }
  2209. if (!Send(cmd))
  2210. {
  2211. error = TRUE;
  2212. }
  2213. break;
  2214. case LISTFILE_MLST:
  2215. retmsg = GetReply();
  2216. code = GetReplyCode();
  2217. if (IsMisleadingListResponse())
  2218. {
  2219. ShowStatus(IDS_STATUSMSG_LISTFILESUCCESSFUL, FZ_LOG_PROGRESS);
  2220. num = 0;
  2221. }
  2222. else if (code != 2)
  2223. {
  2224. error = TRUE;
  2225. }
  2226. else
  2227. {
  2228. USES_CONVERSION;
  2229. int size = m_ListFile.GetLength();
  2230. char *buffer = new char[size + 1];
  2231. memmove(buffer, (LPCSTR)m_ListFile, m_ListFile.GetLength());
  2232. CFtpListResult * pListResult = new CFtpListResult(m_CurrentServer, &m_bUTF8);
  2233. pListResult->InitIntern(GetIntern());
  2234. pListResult->AddData(buffer, size);
  2235. if (GetOptionVal(OPTION_DEBUGSHOWLISTING))
  2236. pListResult->SendToMessageLog();
  2237. pData->direntry = pListResult->getList(num, true);
  2238. if (pListResult->m_server.nServerType & FZ_SERVERTYPE_SUB_FTP_VMS && m_CurrentServer.nServerType & FZ_SERVERTYPE_FTP)
  2239. m_CurrentServer.nServerType |= FZ_SERVERTYPE_SUB_FTP_VMS;
  2240. delete pListResult;
  2241. }
  2242. break;
  2243. case LISTFILE_PWD:
  2244. code = GetReplyCode();
  2245. retmsg = GetReply();
  2246. if ((code == 2) &&
  2247. ParsePwdReply(retmsg, pData->pwd) &&
  2248. Send(L"CWD " + pData->path))
  2249. {
  2250. m_Operation.nOpState = LISTFILE_CWD;
  2251. }
  2252. else
  2253. {
  2254. error = TRUE;
  2255. }
  2256. break;
  2257. case LISTFILE_CWD:
  2258. code = GetReplyCode();
  2259. pData->direntry = new t_directory::t_direntry[1];
  2260. pData->direntry->name = pData->fileName;
  2261. if (code == 2)
  2262. {
  2263. pData->direntry->dir = TRUE;
  2264. if (Send(L"CWD " + pData->pwd.GetPathUnterminated()))
  2265. {
  2266. m_Operation.nOpState = LISTFILE_CWD2;
  2267. }
  2268. else
  2269. {
  2270. error = TRUE;
  2271. }
  2272. }
  2273. else
  2274. {
  2275. // CWD failed, file is not a directory, we should not need to restore PWD.
  2276. // Force binary mode, as according to RFC 6359,
  2277. // SIZE command returns size as transferred over the stream.
  2278. // Moreover ProFTPD does not even support SIZE command in ASCII mode
  2279. if (Send(L"TYPE I"))
  2280. {
  2281. m_Operation.nOpState = LISTFILE_TYPE;
  2282. }
  2283. else
  2284. {
  2285. error = TRUE;
  2286. }
  2287. }
  2288. break;
  2289. case LISTFILE_CWD2:
  2290. code = GetReplyCode();
  2291. if (code == 2)
  2292. {
  2293. // No point trying SIZE on directories.
  2294. // (More over IIS returns a multi-line response for SIZE /dir and we cannot handle that).
  2295. // IIS fails even for MDTM, so skipping even that.
  2296. num = 1;
  2297. }
  2298. // this should never really happen
  2299. else
  2300. {
  2301. error = TRUE;
  2302. }
  2303. break;
  2304. case LISTFILE_TYPE:
  2305. // Do not really care if TYPE succeeded or not
  2306. if (Send(L"SIZE " + pData->path))
  2307. {
  2308. m_Operation.nOpState = LISTFILE_SIZE;
  2309. }
  2310. else
  2311. {
  2312. error = TRUE;
  2313. }
  2314. break;
  2315. case LISTFILE_SIZE:
  2316. code = GetReplyCode();
  2317. // Ignore SIZE errors for directories
  2318. if ((HandleSize(code, pData->direntry->size) || pData->direntry->dir) &&
  2319. Send(L"MDTM " + pData->path))
  2320. {
  2321. m_Operation.nOpState = LISTFILE_MDTM;
  2322. }
  2323. else
  2324. {
  2325. error = TRUE;
  2326. }
  2327. break;
  2328. case LISTFILE_MDTM:
  2329. code = GetReplyCode();
  2330. if (HandleMdtm(code, pData->direntry->date))
  2331. {
  2332. num = 1;
  2333. }
  2334. else
  2335. {
  2336. error = TRUE;
  2337. }
  2338. break;
  2339. default:
  2340. error = TRUE;
  2341. break;
  2342. }
  2343. if (error)
  2344. {
  2345. ResetOperation(FZ_REPLY_ERROR);
  2346. }
  2347. else if (num >= 0)
  2348. {
  2349. t_directory * pDirectoryListing = new t_directory;
  2350. pDirectoryListing->direntry = pData->direntry;
  2351. pData->direntry = NULL;
  2352. pDirectoryListing->num = num;
  2353. pDirectoryListing->server = m_CurrentServer;
  2354. pDirectoryListing->path.SetServer(pDirectoryListing->server);
  2355. pDirectoryListing->path = pData->dir;
  2356. ShowStatus(IDS_STATUSMSG_LISTFILESUCCESSFUL,FZ_LOG_PROGRESS);
  2357. // do not use SetDirectoryListing as that would make
  2358. // later operations believe that there's only this one file in the folder
  2359. m_pOwner->SendDirectoryListing(pDirectoryListing);
  2360. ResetOperation(FZ_REPLY_OK);
  2361. }
  2362. }
  2363. void CFtpControlSocket::TransferEnd(int nMode)
  2364. {
  2365. if (!m_Operation.nOpMode)
  2366. {
  2367. LogMessage(FZ_LOG_INFO, L"Ignoring old TransferEnd message");
  2368. return;
  2369. }
  2370. m_LastRecvTime=CTime::GetCurrentTime();
  2371. if (m_Operation.nOpMode&CSMODE_TRANSFER)
  2372. FileTransfer(0,TRUE,nMode&(CSMODE_TRANSFERERROR|CSMODE_TRANSFERTIMEOUT));
  2373. else if (m_Operation.nOpMode&CSMODE_LIST)
  2374. List(TRUE,nMode&(CSMODE_TRANSFERERROR|CSMODE_TRANSFERTIMEOUT));
  2375. }
  2376. void CFtpControlSocket::OnClose(int nErrorCode)
  2377. {
  2378. ShowStatus(IDS_STATUSMSG_DISCONNECTED, FZ_LOG_ERROR);
  2379. if (m_pTransferSocket)
  2380. {
  2381. m_pTransferSocket->OnClose(0);
  2382. m_pTransferSocket->Close();
  2383. delete m_pTransferSocket;
  2384. m_pTransferSocket=0;
  2385. DoClose();
  2386. return;
  2387. }
  2388. if (m_bDidRejectCertificate)
  2389. DoClose(FZ_REPLY_CANCEL);
  2390. else
  2391. DoClose();
  2392. }
  2393. void CFtpControlSocket::ResetTransferSocket(bool Error)
  2394. {
  2395. if (Error)
  2396. {
  2397. LogMessage(FZ_LOG_INFO, L"Destroying data socket on error");
  2398. }
  2399. else
  2400. {
  2401. LogMessage(FZ_LOG_INFO, L"Destroying data socket after transfer completed");
  2402. }
  2403. delete m_pTransferSocket;
  2404. m_pTransferSocket = NULL;
  2405. }
  2406. void CFtpControlSocket::FileTransfer(t_transferfile *transferfile/*=0*/,BOOL bFinish/*=FALSE*/,int nError/*=0*/)
  2407. {
  2408. USES_CONVERSION;
  2409. #define FILETRANSFER_INIT -1
  2410. #define FILETRANSFER_PWD 0
  2411. #define FILETRANSFER_CWD 1
  2412. #define FILETRANSFER_MKD 2
  2413. #define FILETRANSFER_CWD2 3
  2414. #define FILETRANSFER_PWD2 4
  2415. #define FILETRANSFER_LIST_MODE 5
  2416. #define FILETRANSFER_LIST_OPTS 6
  2417. #define FILETRANSFER_LIST_PORTPASV 7
  2418. #define FILETRANSFER_LIST_TYPE 8
  2419. #define FILETRANSFER_LIST_LIST 9
  2420. #define FILETRANSFER_LIST_WAITFINISH 10
  2421. #define FILETRANSFER_NOLIST_SIZE 11
  2422. #define FILETRANSFER_NOLIST_MDTM 12
  2423. #define FILETRANSFER_TYPE 13
  2424. #define FILETRANSFER_REST 14
  2425. #define FILETRANSFER_MODE 15
  2426. #define FILETRANSFER_OPTS 16
  2427. #define FILETRANSFER_PORTPASV 17
  2428. #define FILETRANSFER_RETRSTOR 18
  2429. #define FILETRANSFER_WAITFINISH 19
  2430. #define FILETRANSFER_WAIT 20
  2431. #define FILETRANSFER_MFMT 21
  2432. //Partial flowchart of FileTransfer
  2433. //
  2434. // +----+
  2435. // /------|Init|--------\
  2436. // | +----+ |
  2437. // | | |
  2438. // | /---+ |
  2439. // | | | |
  2440. // | | +---+ |
  2441. // | | |PWD| |
  2442. // | | +---+ |
  2443. // | | | |
  2444. // | \---+ |
  2445. // | | |
  2446. // | +---+ |
  2447. // | |CWD|--\ |
  2448. // | +---+ | |
  2449. // | | | |
  2450. // | | | |
  2451. // | | +---+ |
  2452. // | | |MKD| |
  2453. // | | +---+ |
  2454. // | | | |
  2455. // | | | |
  2456. // | | +----+ |
  2457. // | | |CWD2| |
  2458. // | | +----+ |
  2459. // | | | |
  2460. // | +----/ |
  2461. // | | |
  2462. // | +---+ |
  2463. // +-------|PWD| |
  2464. // | +---+ |
  2465. // | | |
  2466. // | +----------/
  2467. // | |
  2468. // | +---------+
  2469. // | |LIST_TYPE|
  2470. // | +---------+
  2471. // | |
  2472. // | |
  2473. // | +-------------+
  2474. // | |LIST_PORTPASV|
  2475. // | +-------------+
  2476. // | |
  2477. // | |
  2478. // | +---------+
  2479. // | |LIST_LIST|-----\ //List fails, maybe folder is list protected
  2480. // | +---------+ | //Use SIZE and MDTM to get file information
  2481. // | | +----+
  2482. // | | |SIZE|
  2483. // | | +----+
  2484. // | | |
  2485. // | | +----+
  2486. // | | |MDTM|
  2487. // | | +----+
  2488. // | | |
  2489. // | | |
  2490. // | +---------------+ |
  2491. // | |LIST_WAITFINISH| |
  2492. // | +---------------+ |
  2493. // | | |
  2494. // | | |
  2495. // | +----------/
  2496. // | |
  2497. // \---------+
  2498. // |
  2499. // +----+
  2500. // |TYPE|
  2501. // +----+
  2502. // |
  2503. // |
  2504. // +--------+
  2505. // |PORTPASV|--\
  2506. // +--------+ |
  2507. // | |
  2508. // | |
  2509. // | +----+
  2510. // | |REST|
  2511. // | +----+
  2512. // | |
  2513. // +------/
  2514. // |
  2515. // +--------+
  2516. // |RETRSTOR|
  2517. // +--------+
  2518. // |
  2519. // |
  2520. // +----------+
  2521. // |WAITFINISH|
  2522. // +----------+
  2523. DebugAssert(!m_Operation.nOpMode || m_Operation.nOpMode&CSMODE_TRANSFER);
  2524. if (!m_pOwner->IsConnected())
  2525. {
  2526. m_Operation.nOpMode=CSMODE_TRANSFER|(transferfile->get?CSMODE_DOWNLOAD:CSMODE_UPLOAD);
  2527. ResetOperation(FZ_REPLY_ERROR|FZ_REPLY_DISCONNECTED);
  2528. return;
  2529. }
  2530. CFileTransferData *pData=static_cast<CFileTransferData *>(m_Operation.pData);
  2531. //Process finish and error messages
  2532. if (bFinish || nError)
  2533. {
  2534. DebugAssert(m_Operation.nOpMode&CSMODE_TRANSFER);
  2535. // APPE failed, ignore this reply
  2536. if (m_Operation.nOpMode == FILETRANSFER_WAIT && bFinish)
  2537. return;
  2538. if (!(m_Operation.nOpMode&CSMODE_TRANSFER))
  2539. return;
  2540. if (nError)
  2541. {
  2542. if (m_Operation.nOpState == FILETRANSFER_LIST_LIST && nError & CSMODE_TRANSFERERROR)
  2543. { //Don't abort operation, use fallback to SIZE and MDTM (when actual LIST reply comes in)
  2544. if (m_pTransferSocket)
  2545. m_pTransferSocket=0;
  2546. delete m_pDirectoryListing;
  2547. m_pDirectoryListing=0;
  2548. }
  2549. else if (nError&CSMODE_TRANSFERTIMEOUT)
  2550. DoClose();
  2551. else
  2552. {
  2553. // we may get here when connection was closed, when the closure
  2554. // was first detected while reading/writing,
  2555. // when we abort file transfer with regular error,
  2556. // possibly preventing automatic reconnect
  2557. LogMessage(FZ_LOG_INFO, L"Transfer error (%x)", nError);
  2558. ResetOperation(FZ_REPLY_ERROR);
  2559. }
  2560. return;
  2561. }
  2562. if (m_Operation.nOpState <= FILETRANSFER_LIST_PORTPASV)
  2563. {
  2564. ResetOperation(FZ_REPLY_ERROR);
  2565. return;
  2566. }
  2567. else if (m_Operation.nOpState<=FILETRANSFER_LIST_WAITFINISH)
  2568. {
  2569. if (!m_pTransferSocket || m_pTransferSocket->m_bListening)
  2570. {
  2571. delete m_pDirectoryListing;
  2572. m_pDirectoryListing=0;
  2573. ResetOperation(FZ_REPLY_ERROR);
  2574. return;
  2575. }
  2576. int num=0;
  2577. pData->pDirectoryListing=new t_directory;
  2578. if (GetOptionVal(OPTION_DEBUGSHOWLISTING))
  2579. m_pTransferSocket->m_pListResult->SendToMessageLog();
  2580. pData->pDirectoryListing->direntry=m_pTransferSocket->m_pListResult->getList(num, false);
  2581. pData->pDirectoryListing->num=num;
  2582. if (m_pTransferSocket->m_pListResult->m_server.nServerType&FZ_SERVERTYPE_SUB_FTP_VMS && m_CurrentServer.nServerType&FZ_SERVERTYPE_FTP)
  2583. m_CurrentServer.nServerType |= FZ_SERVERTYPE_SUB_FTP_VMS;
  2584. pData->pDirectoryListing->server = m_CurrentServer;
  2585. pData->pDirectoryListing->path.SetServer(m_CurrentServer);
  2586. pData->pDirectoryListing->path = pData->transferfile.remotepath;
  2587. if (pData->rawpwd!=L"")
  2588. {
  2589. if (!pData->pDirectoryListing->path.SetPath(pData->rawpwd))
  2590. {
  2591. delete m_pDirectoryListing;
  2592. m_pDirectoryListing=0;
  2593. delete m_pTransferSocket;
  2594. m_pTransferSocket=0;
  2595. ResetOperation(FZ_REPLY_ERROR);
  2596. return;
  2597. }
  2598. }
  2599. else
  2600. pData->pDirectoryListing->path=pData->transferfile.remotepath;
  2601. if (m_Operation.nOpState!=FILETRANSFER_LIST_WAITFINISH)
  2602. return;
  2603. }
  2604. else if (m_Operation.nOpState <= FILETRANSFER_PORTPASV)
  2605. {
  2606. ResetOperation(FZ_REPLY_ERROR);
  2607. return;
  2608. }
  2609. else if (m_Operation.nOpState<=FILETRANSFER_WAITFINISH)
  2610. {
  2611. if (m_pTransferSocket->m_bListening)
  2612. {
  2613. ResetOperation(FZ_REPLY_ERROR);
  2614. return;
  2615. }
  2616. pData->nGotTransferEndReply |= 2;
  2617. if (m_Operation.nOpState!=FILETRANSFER_WAITFINISH)
  2618. return;
  2619. else
  2620. {
  2621. ResetTransferSocket(nError);
  2622. }
  2623. }
  2624. }
  2625. //////////////////
  2626. //Initialization//
  2627. //////////////////
  2628. int nReplyError = 0;
  2629. if (m_Operation.nOpState == FILETRANSFER_INIT)
  2630. {
  2631. DebugAssert(transferfile);
  2632. DebugAssert(!m_Operation.nOpMode);
  2633. DebugAssert(!m_Operation.pData);
  2634. CString str;
  2635. str.Format(transferfile->get?IDS_STATUSMSG_DOWNLOADSTART:IDS_STATUSMSG_UPLOADSTART,
  2636. transferfile->get ? transferfile->remotepath.FormatFilename(transferfile->remotefile) : transferfile->localfile);
  2637. ShowStatus(str,FZ_LOG_STATUS);
  2638. m_Operation.nOpMode=CSMODE_TRANSFER|(transferfile->get?CSMODE_DOWNLOAD:CSMODE_UPLOAD);
  2639. m_Operation.pData=new CFileTransferData;
  2640. pData=static_cast<CFileTransferData *>(m_Operation.pData);
  2641. if (GetOptionVal(OPTION_PROXYTYPE)!=PROXYTYPE_NOPROXY)
  2642. pData->bPasv = TRUE;
  2643. else if (m_CurrentServer.nPasv == 1)
  2644. pData->bPasv = TRUE;
  2645. else if (m_CurrentServer.nPasv == 2)
  2646. pData->bPasv = FALSE;
  2647. else
  2648. pData->bPasv = GetOptionVal(OPTION_PASV);
  2649. //Replace invalid characters in the local filename
  2650. int pos=transferfile->localfile.ReverseFind(L'\\');
  2651. for (int i=(pos+1);i<transferfile->localfile.GetLength();i++)
  2652. if (transferfile->localfile[i]==L':')
  2653. transferfile->localfile.SetAt(i, L'_');
  2654. pData->transferfile=*transferfile;
  2655. pData->transferdata.transfersize=pData->transferfile.size;
  2656. pData->transferdata.transferleft=pData->transferfile.size;
  2657. pData->transferdata.bResume = FALSE;
  2658. pData->transferdata.bResumeAppend = FALSE;
  2659. pData->transferdata.bType = (pData->transferfile.nType == 1) ? TRUE : FALSE;
  2660. CServerPath path;
  2661. DebugCheck(m_pOwner->GetCurrentPath(path));
  2662. if (path == pData->transferfile.remotepath)
  2663. {
  2664. if (m_pDirectoryListing)
  2665. {
  2666. m_Operation.nOpState=FILETRANSFER_TYPE;
  2667. CString remotefile=pData->transferfile.remotefile;
  2668. int i;
  2669. for (i=0; i<m_pDirectoryListing->num; i++)
  2670. {
  2671. if (m_pDirectoryListing->direntry[i].name==remotefile &&
  2672. ( m_pDirectoryListing->direntry[i].bUnsure || m_pDirectoryListing->direntry[i].size==-1 ))
  2673. {
  2674. delete m_pDirectoryListing;
  2675. m_pDirectoryListing=0;
  2676. m_Operation.nOpState = FileTransferListState(transferfile->get);
  2677. break;
  2678. }
  2679. }
  2680. if (m_pDirectoryListing && i==m_pDirectoryListing->num)
  2681. {
  2682. nReplyError = CheckOverwriteFile();
  2683. if (!nReplyError)
  2684. {
  2685. if (pData->transferfile.get)
  2686. {
  2687. CString path=pData->transferfile.localfile;
  2688. if (path.ReverseFind(L'\\')!=-1)
  2689. {
  2690. path=path.Left(path.ReverseFind(L'\\')+1);
  2691. CString path2;
  2692. while (path!=L"")
  2693. {
  2694. path2+=path.Left(path.Find( L"\\" )+1);
  2695. path=path.Mid(path.Find( L"\\" )+1);
  2696. CreateDirectory(path2, 0);
  2697. }
  2698. }
  2699. }
  2700. }
  2701. }
  2702. }
  2703. else
  2704. {
  2705. m_Operation.nOpState = FileTransferListState(transferfile->get);
  2706. }
  2707. }
  2708. else
  2709. {
  2710. if (path.IsEmpty())
  2711. m_Operation.nOpState = FILETRANSFER_PWD;
  2712. else
  2713. m_Operation.nOpState = FILETRANSFER_CWD;
  2714. }
  2715. }
  2716. else
  2717. {
  2718. ///////////
  2719. //Replies//
  2720. ///////////
  2721. int code = GetReplyCode();
  2722. switch(m_Operation.nOpState)
  2723. {
  2724. case FILETRANSFER_PWD:
  2725. if (code != 2 && code != 3)
  2726. {
  2727. nReplyError = FZ_REPLY_ERROR;
  2728. break;
  2729. }
  2730. pData->rawpwd = GetReply();
  2731. if ((m_mayBeMvsFilesystem || m_mayBeBS2000Filesystem) && m_CurrentServer.nServerType & FZ_SERVERTYPE_FTP &&
  2732. pData->rawpwd[0] != L'/')
  2733. {
  2734. m_mayBeMvsFilesystem = false;
  2735. m_mayBeBS2000Filesystem = false;
  2736. if (m_mayBeBS2000Filesystem)
  2737. m_CurrentServer.nServerType |= FZ_SERVERTYPE_SUB_FTP_BS2000;
  2738. else
  2739. m_CurrentServer.nServerType |= FZ_SERVERTYPE_SUB_FTP_MVS;
  2740. pData->transferfile.remotepath.SetServer(m_CurrentServer);
  2741. }
  2742. if (!ParsePwdReply(pData->rawpwd))
  2743. return;
  2744. if (m_pOwner->GetCurrentPath() == pData->transferfile.remotepath)
  2745. {
  2746. m_Operation.nOpState = FileTransferListState(pData->transferfile.get);
  2747. }
  2748. else
  2749. m_Operation.nOpState = LIST_CWD;
  2750. break;
  2751. case FILETRANSFER_CWD:
  2752. if (code != 2 && code != 3)
  2753. if (pData->transferfile.get)
  2754. {
  2755. pData->bUseAbsolutePaths = TRUE;
  2756. m_Operation.nOpState = FILETRANSFER_NOLIST_SIZE;
  2757. }
  2758. else
  2759. m_Operation.nOpState = FILETRANSFER_MKD;
  2760. else
  2761. m_Operation.nOpState = FILETRANSFER_PWD2;
  2762. break;
  2763. case FILETRANSFER_MKD:
  2764. switch(pData->nMKDOpState)
  2765. {
  2766. case MKD_FINDPARENT:
  2767. {
  2768. if (code == 2 || code == 3)
  2769. {
  2770. m_pOwner->SetCurrentPath(pData->MKDCurrent);
  2771. pData->nMKDOpState=MKD_CHANGETOSUBDIR;
  2772. pData->MKDCurrent.AddSubdir(pData->MKDSegments.front());
  2773. CString Segment=pData->MKDSegments.front();
  2774. pData->MKDSegments.pop_front();
  2775. if (!Send( L"MKD " + Segment))
  2776. return;
  2777. }
  2778. else
  2779. {
  2780. if (!pData->MKDCurrent.HasParent())
  2781. nReplyError = FZ_REPLY_ERROR | ((code == 5) ? FZ_REPLY_CRITICALERROR : 0);
  2782. else
  2783. {
  2784. pData->MKDSegments.push_front(pData->MKDCurrent.GetLastSegment());
  2785. pData->MKDCurrent=pData->MKDCurrent.GetParent();
  2786. if (!Send(L"CWD "+pData->MKDCurrent.GetPathUnterminated()))
  2787. return;
  2788. }
  2789. }
  2790. }
  2791. break;
  2792. case MKD_MAKESUBDIRS:
  2793. {
  2794. if (code == 2 || code == 3)
  2795. { //Create dir entry in parent dir
  2796. DebugAssert(!pData->MKDSegments.empty());
  2797. pData->MKDCurrent.AddSubdir(pData->MKDSegments.front());
  2798. CString Segment=pData->MKDSegments.front();
  2799. pData->MKDSegments.pop_front();
  2800. if (Send( L"MKD " + Segment))
  2801. pData->nMKDOpState=MKD_CHANGETOSUBDIR;
  2802. else
  2803. return;
  2804. }
  2805. else
  2806. nReplyError=FZ_REPLY_ERROR;
  2807. }
  2808. break;
  2809. case MKD_CHANGETOSUBDIR:
  2810. {
  2811. if (code == 2 || code == 3 || //Creation successful
  2812. m_RecvBuffer.front() == "550 Directory already exists") //Creation was successful, although someone else did the work for us
  2813. {
  2814. CServerPath path2 = pData->MKDCurrent;
  2815. if (path2.HasParent())
  2816. {
  2817. CString name=path2.GetLastSegment();
  2818. path2=path2.GetParent();
  2819. t_directory dir;
  2820. BOOL res=FALSE;
  2821. if (m_pDirectoryListing)
  2822. {
  2823. if (m_pDirectoryListing->path==path2)
  2824. {
  2825. dir=*m_pDirectoryListing;
  2826. res=TRUE;
  2827. }
  2828. }
  2829. t_directory WorkingDir;
  2830. BOOL bFound=m_pOwner->GetWorkingDir(&WorkingDir);
  2831. if (!res && bFound)
  2832. if (WorkingDir.path==path2)
  2833. {
  2834. dir=WorkingDir;
  2835. res=TRUE;
  2836. }
  2837. if (!res)
  2838. {
  2839. dir.path=path2;
  2840. dir.server=m_CurrentServer;
  2841. }
  2842. int i;
  2843. for (i=0; i<dir.num; i++)
  2844. if (dir.direntry[i].name == name)
  2845. {
  2846. LogMessage(FZ_LOG_WARNING, L"Dir already exists in cache!");
  2847. break;
  2848. }
  2849. if (i==dir.num)
  2850. {
  2851. t_directory::t_direntry *entries = new t_directory::t_direntry[dir.num+1];
  2852. for (i=0;i<dir.num;i++)
  2853. entries[i]=dir.direntry[i];
  2854. entries[i].name=name;
  2855. entries[i].dir=TRUE;
  2856. entries[i].date.hasdate=FALSE;
  2857. entries[i].size=-1;
  2858. entries[i].bUnsure=FALSE;
  2859. delete [] dir.direntry;
  2860. dir.direntry=entries;
  2861. dir.num++;
  2862. BOOL updated=FALSE;
  2863. if (m_pDirectoryListing && m_pDirectoryListing->path==dir.path)
  2864. {
  2865. updated=TRUE;
  2866. SetDirectoryListing(&dir);
  2867. }
  2868. if (!updated)
  2869. if (WorkingDir.path==dir.path)
  2870. {
  2871. updated=TRUE;
  2872. m_pOwner->SetWorkingDir(&dir);
  2873. }
  2874. }
  2875. }
  2876. }
  2877. //Continue operation even if MKD failed, maybe another thread did create this directory for us
  2878. if (pData->MKDSegments.empty())
  2879. m_Operation.nOpState=FILETRANSFER_CWD2;
  2880. else
  2881. {
  2882. if (Send( L"CWD " + pData->MKDCurrent.GetPathUnterminated()))
  2883. pData->nMKDOpState=MKD_MAKESUBDIRS;
  2884. else
  2885. return;
  2886. }
  2887. }
  2888. break;
  2889. default:
  2890. DebugFail();
  2891. }
  2892. break;
  2893. case FILETRANSFER_CWD2:
  2894. if (code != 2 && code != 3)
  2895. if (code == 4)
  2896. nReplyError=FZ_REPLY_ERROR;
  2897. else
  2898. nReplyError=FZ_REPLY_CRITICALERROR;
  2899. else
  2900. m_Operation.nOpState=FILETRANSFER_PWD2;
  2901. break;
  2902. case FILETRANSFER_PWD2:
  2903. if (code != 2 && code != 3)
  2904. nReplyError = FZ_REPLY_ERROR;
  2905. else
  2906. {
  2907. pData->rawpwd = GetReply();
  2908. if (!ParsePwdReply(pData->rawpwd))
  2909. return;
  2910. m_Operation.nOpState = FileTransferListState(pData->transferfile.get);
  2911. }
  2912. break;
  2913. case FILETRANSFER_LIST_MODE:
  2914. #ifdef MPEXT_NO_ZLIB
  2915. DebugFail();
  2916. m_Operation.nOpState = FILETRANSFER_LIST_TYPE;
  2917. #else
  2918. if (code == 2 || code == 3)
  2919. m_useZlib = !m_useZlib;
  2920. m_Operation.nOpState = NeedOptsCommand() ? FILETRANSFER_LIST_OPTS : FILETRANSFER_LIST_TYPE;
  2921. #endif
  2922. break;
  2923. case FILETRANSFER_LIST_OPTS:
  2924. #ifdef MPEXT_NO_ZLIB
  2925. DebugFail();
  2926. #else
  2927. if (code == 2 || code == 3)
  2928. m_zlibLevel = pData->newZlibLevel;
  2929. m_Operation.nOpState = FILETRANSFER_LIST_TYPE;
  2930. #endif
  2931. break;
  2932. case FILETRANSFER_LIST_TYPE:
  2933. if (code != 2 && code != 3)
  2934. nReplyError = FZ_REPLY_ERROR;
  2935. else
  2936. m_Operation.nOpState = FILETRANSFER_LIST_PORTPASV;
  2937. break;
  2938. case FILETRANSFER_LIST_PORTPASV:
  2939. if (code!=3 && code!=2)
  2940. {
  2941. if (!pData->bTriedPortPasvOnce)
  2942. {
  2943. pData->bTriedPortPasvOnce = TRUE;
  2944. pData->bPasv = !pData->bPasv;
  2945. }
  2946. else
  2947. nReplyError=FZ_REPLY_ERROR;
  2948. break;
  2949. }
  2950. if (pData->bPasv)
  2951. {
  2952. CString reply = GetReply();
  2953. int i,j;
  2954. // MP EXT
  2955. if((i=reply.Find(L"("))>=0&&(j=reply.Find(L")"))>=0)
  2956. {
  2957. i++;
  2958. j--;
  2959. }
  2960. else
  2961. {
  2962. // MP EXT
  2963. if ((i=reply.Mid(4).FindOneOf(L"0123456789"))>=0)
  2964. {
  2965. i += 4;
  2966. j = reply.GetLength() - 1;
  2967. }
  2968. else
  2969. {
  2970. if (!pData->bTriedPortPasvOnce)
  2971. {
  2972. pData->bTriedPortPasvOnce = TRUE;
  2973. pData->bPasv = !pData->bPasv;
  2974. }
  2975. else
  2976. nReplyError = FZ_REPLY_ERROR;
  2977. break;
  2978. }
  2979. }
  2980. CString temp = reply.Mid(i,(j-i)+1);
  2981. if (GetFamily() == AF_INET)
  2982. {
  2983. int count=0;
  2984. int pos=0;
  2985. //Convert commas to dots
  2986. temp.Replace( L",", L"." );
  2987. while(1)
  2988. {
  2989. pos=temp.Find(L".",pos);
  2990. if (pos!=-1)
  2991. count++;
  2992. else
  2993. break;
  2994. pos++;
  2995. }
  2996. if (count!=5)
  2997. {
  2998. if (!pData->bTriedPortPasvOnce)
  2999. {
  3000. pData->bTriedPortPasvOnce = TRUE;
  3001. pData->bPasv = !pData->bPasv;
  3002. }
  3003. else
  3004. nReplyError = FZ_REPLY_ERROR;
  3005. break;
  3006. }
  3007. i=temp.ReverseFind(L'.');
  3008. pData->port=atol( T2CA( temp.Right(temp.GetLength()-(i+1)) ) ); //get ls byte of server socket
  3009. temp=temp.Left(i);
  3010. i=temp.ReverseFind(L'.');
  3011. pData->port+=256*atol( T2CA( temp.Right(temp.GetLength()-(i+1)) ) ); // add ms byte to server socket
  3012. pData->host=temp.Left(i);
  3013. if (!CheckForcePasvIp(pData->host))
  3014. {
  3015. nReplyError = FZ_REPLY_ERROR;
  3016. break;
  3017. }
  3018. }
  3019. else if (GetFamily() == AF_INET6)
  3020. {
  3021. temp = temp.Mid(3);
  3022. pData->port = atol( T2CA(temp.Left(temp.GetLength() - 1) ) );
  3023. if (pData->port < 0 || pData->port > 65535)
  3024. {
  3025. LogMessage(FZ_LOG_WARNING, L"Port %u not valid", pData->port);
  3026. nReplyError = FZ_REPLY_ERROR;
  3027. break;
  3028. }
  3029. pData->host = m_CurrentServer.host;
  3030. }
  3031. m_pTransferSocket = new CTransferSocket(this, CSMODE_LIST);
  3032. #ifndef MPEXT_NO_ZLIB
  3033. if (m_useZlib)
  3034. {
  3035. if (!m_pTransferSocket->InitZlib(m_zlibLevel))
  3036. {
  3037. ShowStatus(L"Failed to initialize zlib", FZ_LOG_ERROR);
  3038. ResetOperation(FZ_REPLY_ERROR);
  3039. return;
  3040. }
  3041. }
  3042. #endif
  3043. #ifndef MPEXT_NO_GSS
  3044. if (m_pGssLayer && m_pGssLayer->AuthSuccessful())
  3045. m_pTransferSocket->UseGSS(m_pGssLayer);
  3046. #endif
  3047. m_pTransferSocket->m_nInternalMessageID = m_pOwner->m_nInternalMessageID;
  3048. m_pTransferSocket->SetFamily(GetFamily());
  3049. if (!m_pTransferSocket->Create(m_pSslLayer && m_bProtP))
  3050. {
  3051. nReplyError = FZ_REPLY_ERROR;
  3052. break;
  3053. }
  3054. DebugCheck(m_pTransferSocket->AsyncSelect());
  3055. }
  3056. m_Operation.nOpState=FILETRANSFER_LIST_LIST;
  3057. break;
  3058. case FILETRANSFER_LIST_LIST:
  3059. if (IsMisleadingListResponse())
  3060. {
  3061. ShowStatus(IDS_STATUSMSG_DIRLISTSUCCESSFUL, FZ_LOG_PROGRESS);
  3062. t_directory listing;
  3063. listing.server = m_CurrentServer;
  3064. listing.path.SetServer(m_CurrentServer);
  3065. if (pData->rawpwd != L"")
  3066. {
  3067. if (!listing.path.SetPath(pData->rawpwd))
  3068. {
  3069. delete m_pDirectoryListing;
  3070. m_pDirectoryListing = 0;
  3071. delete m_pTransferSocket;
  3072. m_pTransferSocket = 0;
  3073. ResetOperation(FZ_REPLY_ERROR);
  3074. return;
  3075. }
  3076. }
  3077. else
  3078. listing.path = pData->transferfile.remotepath;
  3079. SetDirectoryListing(&listing);
  3080. m_Operation.nOpState = FILETRANSFER_TYPE;
  3081. delete m_pTransferSocket;
  3082. m_pTransferSocket = 0;
  3083. nReplyError = CheckOverwriteFile();
  3084. if (!nReplyError)
  3085. {
  3086. if (pData->transferfile.get)
  3087. {
  3088. CString path=pData->transferfile.localfile;
  3089. if (path.ReverseFind(L'\\')!=-1)
  3090. {
  3091. path=path.Left(path.ReverseFind(L'\\')+1);
  3092. CString path2;
  3093. while (path!=L"")
  3094. {
  3095. path2+=path.Left(path.Find( L"\\" )+1);
  3096. path=path.Mid(path.Find( L"\\" )+1);
  3097. CreateDirectory(path2, 0);
  3098. }
  3099. }
  3100. }
  3101. }
  3102. }
  3103. else if (code==4 || code==5) //LIST failed, try getting file information using SIZE and MDTM
  3104. {
  3105. TransferHandleListError();
  3106. }
  3107. else if (code!=1)
  3108. nReplyError=FZ_REPLY_ERROR;
  3109. else
  3110. m_Operation.nOpState=FILETRANSFER_LIST_WAITFINISH;
  3111. break;
  3112. case FILETRANSFER_LIST_WAITFINISH:
  3113. if (!bFinish)
  3114. {
  3115. if (code!=2 && code!=3)
  3116. {
  3117. if (code==4 || code==5)
  3118. {
  3119. TransferHandleListError();
  3120. }
  3121. else
  3122. {
  3123. nReplyError=FZ_REPLY_ERROR;
  3124. }
  3125. }
  3126. else
  3127. pData->nGotTransferEndReply = 1;
  3128. }
  3129. if (pData->nGotTransferEndReply && pData->pDirectoryListing)
  3130. {
  3131. SetDirectoryListing(pData->pDirectoryListing);
  3132. delete m_pTransferSocket;
  3133. m_pTransferSocket=0;
  3134. m_Operation.nOpState=FILETRANSFER_TYPE;
  3135. nReplyError = CheckOverwriteFile();
  3136. if (!nReplyError)
  3137. {
  3138. if (pData->transferfile.get)
  3139. {
  3140. CString path=pData->transferfile.localfile;
  3141. if (path.ReverseFind(L'\\')!=-1)
  3142. {
  3143. path=path.Left(path.ReverseFind(L'\\')+1);
  3144. CString path2;
  3145. while (path!=L"")
  3146. {
  3147. path2+=path.Left(path.Find( L"\\" )+1);
  3148. path=path.Mid(path.Find( L"\\" )+1);
  3149. CreateDirectory(path2, 0);
  3150. }
  3151. }
  3152. }
  3153. }
  3154. pData->nGotTransferEndReply=0;
  3155. }
  3156. break;
  3157. case FILETRANSFER_NOLIST_SIZE:
  3158. {
  3159. __int64 size;
  3160. if (HandleSize(code, size))
  3161. {
  3162. DebugAssert(!pData->pFileSize);
  3163. pData->pFileSize=new _int64;
  3164. *pData->pFileSize=size;
  3165. }
  3166. }
  3167. m_Operation.nOpState=FILETRANSFER_NOLIST_MDTM;
  3168. break;
  3169. case FILETRANSFER_NOLIST_MDTM:
  3170. if (HandleMdtm(code, pData->remoteDate))
  3171. {
  3172. pData->hasRemoteDate = true;
  3173. }
  3174. m_Operation.nOpState=FILETRANSFER_TYPE;
  3175. nReplyError=CheckOverwriteFile();
  3176. break;
  3177. case FILETRANSFER_TYPE:
  3178. if (code!=2 && code!=3)
  3179. nReplyError = FZ_REPLY_ERROR;
  3180. m_Operation.nOpState = NeedModeCommand() ? FILETRANSFER_MODE : (NeedOptsCommand() ? FILETRANSFER_OPTS : FILETRANSFER_PORTPASV);
  3181. break;
  3182. case FILETRANSFER_WAIT:
  3183. if (!pData->nWaitNextOpState)
  3184. nReplyError=FZ_REPLY_ERROR;
  3185. else
  3186. m_Operation.nOpState=pData->nWaitNextOpState;
  3187. break;
  3188. case FILETRANSFER_MODE:
  3189. #ifdef MPEXT_NO_ZLIB
  3190. DebugFail();
  3191. m_Operation.nOpState = FILETRANSFER_PORTPASV;
  3192. #else
  3193. if (code == 2 || code == 3)
  3194. m_useZlib = !m_useZlib;
  3195. m_Operation.nOpState = NeedOptsCommand() ? FILETRANSFER_OPTS : FILETRANSFER_PORTPASV;
  3196. #endif
  3197. break;
  3198. case FILETRANSFER_OPTS:
  3199. #ifdef MPEXT_NO_ZLIB
  3200. DebugFail();
  3201. #else
  3202. if (code == 2 || code == 3)
  3203. m_zlibLevel = pData->newZlibLevel;
  3204. #endif
  3205. m_Operation.nOpState = FILETRANSFER_PORTPASV;
  3206. break;
  3207. case FILETRANSFER_PORTPASV:
  3208. if (code == 3 || code == 2)
  3209. {
  3210. if (pData->bPasv)
  3211. {
  3212. CString reply = GetReply();
  3213. int i,j;
  3214. // MP EXT
  3215. if((i=reply.Find(L"("))>=0&&(j=reply.Find(L")"))>=0)
  3216. {
  3217. i++;
  3218. j--;
  3219. }
  3220. else
  3221. {
  3222. // MP EXT
  3223. if ((i=reply.Mid(4).FindOneOf(L"0123456789"))>=0)
  3224. {
  3225. i += 4;
  3226. j = reply.GetLength() - 1;
  3227. }
  3228. else
  3229. {
  3230. if (!pData->bTriedPortPasvOnce)
  3231. {
  3232. pData->bTriedPortPasvOnce = TRUE;
  3233. pData->bPasv = !pData->bPasv;
  3234. }
  3235. else
  3236. nReplyError = FZ_REPLY_ERROR;
  3237. break;
  3238. }
  3239. }
  3240. CString temp = reply.Mid(i,(j-i)+1);
  3241. if (GetFamily() == AF_INET)
  3242. {
  3243. int count=0;
  3244. int pos=0;
  3245. //Convert commas to dots
  3246. temp.Replace( L",", L"." );
  3247. while(1)
  3248. {
  3249. pos=temp.Find( L".", pos);
  3250. if (pos!=-1)
  3251. count++;
  3252. else
  3253. break;
  3254. pos++;
  3255. }
  3256. if (count!=5)
  3257. {
  3258. if (!pData->bTriedPortPasvOnce)
  3259. {
  3260. pData->bTriedPortPasvOnce = TRUE;
  3261. pData->bPasv = !pData->bPasv;
  3262. }
  3263. else
  3264. nReplyError = FZ_REPLY_ERROR;
  3265. break;
  3266. }
  3267. i=temp.ReverseFind(L'.');
  3268. pData->port=atol( T2CA( temp.Right(temp.GetLength()-(i+1)) ) ); //get ls byte of server socket
  3269. temp=temp.Left(i);
  3270. i=temp.ReverseFind(L'.');
  3271. pData->port+=256*atol( T2CA( temp.Right(temp.GetLength()-(i+1)) ) ); // add ms byte to server socket
  3272. pData->host=temp.Left(i);
  3273. if (!CheckForcePasvIp(pData->host))
  3274. {
  3275. nReplyError = FZ_REPLY_ERROR;
  3276. break;
  3277. }
  3278. }
  3279. else if (GetFamily() == AF_INET6)
  3280. {
  3281. temp = temp.Mid(3);
  3282. pData->port = atol( T2CA(temp.Left(temp.GetLength() - 1) ) );
  3283. if (pData->port < 0 || pData->port > 65535)
  3284. {
  3285. LogMessage(FZ_LOG_WARNING, L"Port %u not valid", pData->port);
  3286. nReplyError = FZ_REPLY_ERROR;
  3287. break;
  3288. }
  3289. pData->host = m_CurrentServer.host;
  3290. }
  3291. else
  3292. {
  3293. nReplyError = FZ_REPLY_ERROR;
  3294. break;
  3295. }
  3296. m_pTransferSocket = new CTransferSocket(this, m_Operation.nOpMode);
  3297. #ifndef MPEXT_NO_ZLIB
  3298. if (m_useZlib)
  3299. {
  3300. if (!m_pTransferSocket->InitZlib(m_zlibLevel))
  3301. {
  3302. ShowStatus(L"Failed to initialize zlib", FZ_LOG_ERROR);
  3303. ResetOperation(FZ_REPLY_ERROR);
  3304. return;
  3305. }
  3306. }
  3307. #endif
  3308. #ifndef MPEXT_NO_GSS
  3309. if (m_pGssLayer && m_pGssLayer->AuthSuccessful())
  3310. m_pTransferSocket->UseGSS(m_pGssLayer);
  3311. #endif
  3312. m_pTransferSocket->m_nInternalMessageID = m_pOwner->m_nInternalMessageID;
  3313. m_pTransferSocket->SetFamily(GetFamily());
  3314. if (!m_pTransferSocket->Create(m_pSslLayer && m_bProtP))
  3315. {
  3316. nReplyError = FZ_REPLY_ERROR;
  3317. break;
  3318. }
  3319. DebugCheck(m_pTransferSocket->AsyncSelect());
  3320. }
  3321. if (pData->transferdata.bResume)
  3322. m_Operation.nOpState = FILETRANSFER_REST;
  3323. else
  3324. m_Operation.nOpState = FILETRANSFER_RETRSTOR;
  3325. BOOL res = FALSE;
  3326. if (!m_pDataFile)
  3327. m_pDataFile = new CFile;
  3328. if (pData->transferfile.get)
  3329. {
  3330. if (pData->transferdata.bResume)
  3331. res = m_pDataFile->Open(pData->transferfile.localfile,CFile::modeCreate|CFile::modeWrite|CFile::modeNoTruncate|CFile::shareDenyWrite);
  3332. else
  3333. res = m_pDataFile->Open(pData->transferfile.localfile,CFile::modeWrite|CFile::modeCreate|CFile::shareDenyWrite);
  3334. }
  3335. else
  3336. res = m_pDataFile->Open(pData->transferfile.localfile,CFile::modeRead|CFile::shareDenyNone);
  3337. if (!res)
  3338. {
  3339. wchar_t * Error = m_pTools->LastSysErrorMessage();
  3340. //Error opening the file
  3341. CString str;
  3342. str.Format(IDS_ERRORMSG_FILEOPENFAILED,pData->transferfile.localfile);
  3343. str += L"\n";
  3344. str += Error;
  3345. free(Error);
  3346. ShowStatus(str,FZ_LOG_ERROR);
  3347. nReplyError = FZ_REPLY_ERROR;
  3348. break;
  3349. }
  3350. if (!m_pTransferSocket)
  3351. {
  3352. nReplyError=FZ_REPLY_ERROR;
  3353. break;
  3354. }
  3355. m_pTransferSocket->m_pFile = m_pDataFile;
  3356. if (!pData->transferfile.get)
  3357. {
  3358. // See comment in !get branch below
  3359. pData->transferdata.transfersize=GetLength64(*m_pDataFile);
  3360. pData->transferdata.transferleft=pData->transferdata.transfersize;
  3361. if (pData->transferdata.bResume)
  3362. {
  3363. CString remotefile=pData->transferfile.remotefile;
  3364. if (m_pDirectoryListing)
  3365. for (int i = 0; i < m_pDirectoryListing->num; i++)
  3366. {
  3367. if (m_pDirectoryListing->direntry[i].name == remotefile)
  3368. {
  3369. pData->transferdata.transferleft -= m_pDirectoryListing->direntry[i].size;
  3370. break;
  3371. }
  3372. }
  3373. _int64 size = pData->transferdata.transfersize-pData->transferdata.transferleft;
  3374. LONG low = static_cast<LONG>(size&0xFFFFFFFF);
  3375. LONG high = static_cast<LONG>(size>>32);
  3376. if (SetFilePointer((HANDLE)m_pDataFile->m_hFile, low, &high, FILE_BEGIN)==0xFFFFFFFF && GetLastError()!=NO_ERROR)
  3377. {
  3378. ShowStatus(IDS_ERRORMSG_SETFILEPOINTER, FZ_LOG_ERROR);
  3379. nReplyError = FZ_REPLY_ERROR;
  3380. }
  3381. }
  3382. }
  3383. else
  3384. {
  3385. // Resetting transfersize here is pointless as we
  3386. // always provide valid size in call to FileTransfer.
  3387. // We unnecessary reply on the file being in the directory listing.
  3388. pData->transferdata.transfersize=-1;
  3389. CString remotefile=pData->transferfile.remotefile;
  3390. if (m_pDirectoryListing)
  3391. for (int i=0; i<m_pDirectoryListing->num; i++)
  3392. {
  3393. if (m_pDirectoryListing->direntry[i].name==remotefile)
  3394. {
  3395. pData->hasRemoteDate = true;
  3396. pData->remoteDate = m_pDirectoryListing->direntry[i].date;
  3397. pData->transferdata.transfersize=m_pDirectoryListing->direntry[i].size;
  3398. }
  3399. }
  3400. else if (pData->pFileSize)
  3401. pData->transferdata.transfersize=*pData->pFileSize;
  3402. pData->transferdata.transferleft=pData->transferdata.transfersize;
  3403. }
  3404. }
  3405. else
  3406. if (!pData->bTriedPortPasvOnce)
  3407. {
  3408. pData->bTriedPortPasvOnce = TRUE;
  3409. pData->bPasv = !pData->bPasv;
  3410. }
  3411. else
  3412. nReplyError = FZ_REPLY_ERROR;
  3413. break;
  3414. case FILETRANSFER_REST:
  3415. { //Resume
  3416. if (code==3 || code==2)
  3417. {
  3418. LONG high = 0;
  3419. if (pData->transferfile.get)
  3420. {
  3421. pData->transferdata.transferleft = pData->transferdata.transfersize - GetLength64(*m_pDataFile);
  3422. if (SetFilePointer((HANDLE)m_pDataFile->m_hFile, 0, &high, FILE_END)==0xFFFFFFFF && GetLastError()!=NO_ERROR)
  3423. {
  3424. ShowStatus(IDS_ERRORMSG_SETFILEPOINTER, FZ_LOG_ERROR);
  3425. nReplyError = FZ_REPLY_ERROR;
  3426. }
  3427. else
  3428. m_Operation.nOpState = FILETRANSFER_RETRSTOR;
  3429. }
  3430. else
  3431. {
  3432. m_Operation.nOpState = FILETRANSFER_RETRSTOR;
  3433. }
  3434. }
  3435. else
  3436. {
  3437. if (code==5 && GetReply()[1]==L'0')
  3438. {
  3439. if (pData->transferfile.get)
  3440. {
  3441. if (pData->transferdata.transfersize!=-1)
  3442. {
  3443. DebugAssert(m_pDataFile);
  3444. if (GetLength64(*m_pDataFile) == pData->transferdata.transfersize)
  3445. {
  3446. ShowStatus(IDS_ERRORMSG_CANTRESUME_FINISH, FZ_LOG_STATUS);
  3447. ResetOperation(FZ_REPLY_OK);
  3448. return;
  3449. }
  3450. }
  3451. ShowStatus(IDS_ERRORMSG_CANTRESUME, FZ_LOG_ERROR);
  3452. pData->transferdata.transferleft=pData->transferdata.transfersize;
  3453. pData->transferdata.bResume=FALSE;
  3454. m_Operation.nOpState=FILETRANSFER_RETRSTOR;
  3455. }
  3456. else
  3457. {
  3458. ShowStatus(L"Resume command not supported by server, trying append.", FZ_LOG_PROGRESS);
  3459. pData->transferdata.bResumeAppend=TRUE;
  3460. m_Operation.nOpState=FILETRANSFER_RETRSTOR;
  3461. }
  3462. }
  3463. else
  3464. nReplyError=FZ_REPLY_ERROR;
  3465. }
  3466. }
  3467. break;
  3468. case FILETRANSFER_RETRSTOR:
  3469. // A '1xy opening data connection' reply is expected if RETR/STOR/APPE
  3470. // is successful.
  3471. // On failure, it's a 4xy or 5xy reply.
  3472. // However, some servers send a 2xy transfer complete reply without opening a data
  3473. // connection if there's no data to send.
  3474. if (code==2)
  3475. {
  3476. //Transfer successful, however server did not open data connection
  3477. ResetOperation(FZ_REPLY_OK);
  3478. return;
  3479. }
  3480. else if (code!=1)
  3481. {
  3482. if (!pData->transferfile.get && pData->transferdata.bResume && pData->askOnResumeFail)
  3483. {
  3484. pData->askOnResumeFail = false;
  3485. delete m_pTransferSocket;
  3486. m_pTransferSocket = 0;
  3487. delete m_pDataFile;
  3488. m_pDataFile = 0;
  3489. pData->nGotTransferEndReply = 0;
  3490. nReplyError = CheckOverwriteFile();
  3491. }
  3492. else
  3493. {
  3494. nReplyError = FZ_REPLY_ERROR;
  3495. if (code == 5)
  3496. nReplyError |= FZ_REPLY_CRITICALERROR;
  3497. }
  3498. }
  3499. else
  3500. {
  3501. m_Operation.nOpState=FILETRANSFER_WAITFINISH;
  3502. //Look if we can find any information about the resume offset
  3503. if (!pData->transferfile.get && pData->transferdata.bResumeAppend)
  3504. {
  3505. _int64 nOffset = -1;
  3506. CString reply = GetReply();
  3507. reply.MakeLower();
  3508. int pos = reply.Find(L"restarting at offset ");
  3509. if (pos != -1)
  3510. pos += _tcslen(L"restarting at offset ");
  3511. reply = reply.Mid(pos);
  3512. int i;
  3513. for (i=0; i<reply.GetLength(); i++)
  3514. {
  3515. if (reply[i] < L'0' || reply[i] > L'9')
  3516. break;
  3517. }
  3518. if (i == reply.GetLength())
  3519. nOffset = _ttoi64(reply);
  3520. if (nOffset != -1 && m_pDataFile)
  3521. {
  3522. LONG low = 0;
  3523. LONG high = 0;
  3524. if (nOffset >= GetLength64(*m_pDataFile))
  3525. {
  3526. if (SetFilePointer((HANDLE)m_pDataFile->m_hFile, 0, &high, FILE_END)==0xFFFFFFFF && GetLastError()!=NO_ERROR)
  3527. {
  3528. ShowStatus(IDS_ERRORMSG_SETFILEPOINTER, FZ_LOG_ERROR);
  3529. nReplyError = FZ_REPLY_ERROR;
  3530. }
  3531. }
  3532. else
  3533. {
  3534. low=static_cast<LONG>(nOffset&0xFFFFFFFF);
  3535. high=static_cast<LONG>(nOffset>>32);
  3536. if (SetFilePointer((HANDLE)m_pDataFile->m_hFile, low, &high, FILE_BEGIN)==0xFFFFFFFF && GetLastError()!=NO_ERROR)
  3537. {
  3538. ShowStatus(IDS_ERRORMSG_SETFILEPOINTER, FZ_LOG_ERROR);
  3539. nReplyError = FZ_REPLY_ERROR;
  3540. }
  3541. }
  3542. }
  3543. if (!nReplyError && !GetOptionVal(OPTION_MPEXT_TRANSFER_ACTIVE_IMMEDIATELY))
  3544. {
  3545. m_pTransferSocket->SetActive();
  3546. }
  3547. }
  3548. else if (pData->bPasv && !GetOptionVal(OPTION_MPEXT_TRANSFER_ACTIVE_IMMEDIATELY))
  3549. {
  3550. m_pTransferSocket->SetActive();
  3551. }
  3552. }
  3553. break;
  3554. case FILETRANSFER_WAITFINISH:
  3555. if (bFinish)
  3556. {
  3557. if (nError)
  3558. {
  3559. LogMessage(FZ_LOG_INFO, L"Transfer completed");
  3560. }
  3561. else
  3562. {
  3563. LogMessage(FZ_LOG_INFO, L"Transfer failed");
  3564. }
  3565. }
  3566. if (!bFinish)
  3567. {
  3568. if (code == 1)
  3569. {
  3570. /* Some non-rfc959 compatible servers send more than one code 1yz reply, especially if using APPE.
  3571. * Just ignore the additional ones.
  3572. */
  3573. LogMessage(FZ_LOG_WARNING, L"Server sent more than one code 1yz reply, ignoring additional reply");
  3574. break;
  3575. }
  3576. else if (code!=2 && code!=3)
  3577. nReplyError = FZ_REPLY_ERROR;
  3578. else
  3579. {
  3580. pData->nGotTransferEndReply |= 1;
  3581. }
  3582. }
  3583. if (pData->nGotTransferEndReply==3)
  3584. {
  3585. // Not really sure about a reason for the m_pDataFile condition here
  3586. TransferFinished(m_pDataFile != NULL);
  3587. return;
  3588. }
  3589. break;
  3590. case FILETRANSFER_MFMT:
  3591. //Transfer successful
  3592. ResetOperation(FZ_REPLY_OK);
  3593. break;
  3594. }
  3595. if (nReplyError)
  3596. { //Error transferring the file
  3597. LogMessage(FZ_LOG_INFO, L"Transfer response error (%x)", nReplyError);
  3598. ResetOperation(nReplyError);
  3599. return;
  3600. }
  3601. }
  3602. /////////////////
  3603. //Send commands//
  3604. /////////////////
  3605. BOOL bError=FALSE;
  3606. switch(m_Operation.nOpState)
  3607. {
  3608. case FILETRANSFER_PWD:
  3609. if (!Send(L"PWD"))
  3610. bError = TRUE;
  3611. break;
  3612. case FILETRANSFER_CWD:
  3613. if (!Send(L"CWD "+pData->transferfile.remotepath.GetPathUnterminated()))
  3614. bError=TRUE;
  3615. break;
  3616. case FILETRANSFER_MKD:
  3617. if (pData->nMKDOpState==MKD_INIT)
  3618. {
  3619. if (!pData->transferfile.remotepath.HasParent())
  3620. {
  3621. LogMessage(FZ_LOG_WARNING, L"Can't create root dir");
  3622. ResetOperation(FZ_REPLY_CRITICALERROR);
  3623. return;
  3624. }
  3625. if (!Send(L"CWD "+pData->transferfile.remotepath.GetParent().GetPathUnterminated()))
  3626. bError=TRUE;
  3627. pData->MKDCurrent=pData->transferfile.remotepath.GetParent();
  3628. pData->MKDSegments.push_front(pData->transferfile.remotepath.GetLastSegment());
  3629. pData->nMKDOpState=MKD_FINDPARENT;
  3630. }
  3631. break;
  3632. case FILETRANSFER_CWD2:
  3633. if (!Send(L"CWD "+pData->transferfile.remotepath.GetPathUnterminated()))
  3634. bError=TRUE;
  3635. break;
  3636. case FILETRANSFER_PWD2:
  3637. if (!Send(L"PWD"))
  3638. bError=TRUE;
  3639. break;
  3640. case FILETRANSFER_LIST_MODE:
  3641. #ifdef MPEXT_NO_ZLIB
  3642. DebugFail();
  3643. #else
  3644. if (m_useZlib)
  3645. {
  3646. if (!Send(L"MODE S"))
  3647. bError = TRUE;
  3648. }
  3649. else
  3650. if (!Send(L"MODE Z"))
  3651. bError = TRUE;
  3652. #endif
  3653. break;
  3654. case FILETRANSFER_LIST_OPTS:
  3655. #ifdef MPEXT_NO_ZLIB
  3656. DebugFail();
  3657. #else
  3658. {
  3659. pData->newZlibLevel = GetOptionVal(OPTION_MODEZ_LEVEL);
  3660. CString str;
  3661. str.Format(L"OPTS MODE Z LEVEL %d", pData->newZlibLevel);
  3662. if (!Send(str))
  3663. bError = TRUE;
  3664. }
  3665. #endif
  3666. break;
  3667. case FILETRANSFER_LIST_PORTPASV:
  3668. delete m_pDirectoryListing;
  3669. m_pDirectoryListing=0;
  3670. if (pData->bPasv)
  3671. {
  3672. if (!Send((GetFamily() == AF_INET) ? L"PASV" : L"EPSV"))
  3673. bError=TRUE;
  3674. }
  3675. else
  3676. {
  3677. if (m_pTransferSocket)
  3678. {
  3679. delete m_pTransferSocket;
  3680. }
  3681. m_pTransferSocket = new CTransferSocket(this, CSMODE_LIST);
  3682. #ifndef MPEXT_NO_ZLIB
  3683. if (m_useZlib)
  3684. {
  3685. if (!m_pTransferSocket->InitZlib(m_zlibLevel))
  3686. {
  3687. ShowStatus(L"Failed to initialize zlib", FZ_LOG_ERROR);
  3688. ResetOperation(FZ_REPLY_ERROR);
  3689. return;
  3690. }
  3691. }
  3692. #endif
  3693. #ifndef MPEXT_NO_GSS
  3694. if (m_pGssLayer && m_pGssLayer->AuthSuccessful())
  3695. m_pTransferSocket->UseGSS(m_pGssLayer);
  3696. #endif
  3697. m_pTransferSocket->m_nInternalMessageID = m_pOwner->m_nInternalMessageID;
  3698. m_pTransferSocket->m_bListening = TRUE;
  3699. m_pTransferSocket->SetFamily(GetFamily());
  3700. if(!m_pTransferSocket->Create(m_pSslLayer && m_bProtP) || !m_pTransferSocket->AsyncSelect())
  3701. bError=TRUE;
  3702. else if (m_pProxyLayer)
  3703. {
  3704. SOCKADDR_IN addr;
  3705. int len=sizeof(addr);
  3706. if (!m_pProxyLayer->GetPeerName((SOCKADDR *)&addr,&len))
  3707. {
  3708. ShowStatus(IDS_ERRORMSG_CANTGETLIST,FZ_LOG_ERROR);
  3709. bError=TRUE;
  3710. }
  3711. else if (!m_pTransferSocket->Listen(addr.sin_addr.S_un.S_addr))
  3712. {
  3713. ShowStatus(IDS_ERRORMSG_CANTGETLIST,FZ_LOG_ERROR);
  3714. bError=TRUE;
  3715. }
  3716. //Don't send PORT command yet, params are unknown.
  3717. //will be sent in TransfersocketListenFinished
  3718. }
  3719. else
  3720. {
  3721. //Set up an active file transfer
  3722. CString temp;
  3723. UINT nPort;
  3724. if (//create listen socket (let Windows choose the port) & start listening
  3725. !m_pTransferSocket->Listen() ||
  3726. !m_pTransferSocket->GetSockName(temp, nPort))
  3727. {
  3728. bError = TRUE;
  3729. break;
  3730. }
  3731. CString host;
  3732. if (GetFamily() == AF_INET)
  3733. {
  3734. host = GetOption(OPTION_TRANSFERIP);
  3735. if (host != L"")
  3736. {
  3737. DWORD ip = inet_addr(T2CA(host));
  3738. if (ip != INADDR_NONE)
  3739. host.Format(L"%d,%d,%d,%d", ip%256, (ip>>8)%256, (ip>>16)%256, ip>>24);
  3740. else
  3741. {
  3742. hostent *fullname = gethostbyname(T2CA(host));
  3743. if (!fullname)
  3744. host = L"";
  3745. else
  3746. {
  3747. DWORD ip = ((LPIN_ADDR)fullname->h_addr)->s_addr;
  3748. if (ip != INADDR_NONE)
  3749. host.Format(L"%d,%d,%d,%d", ip%256, (ip>>8)%256, (ip>>16)%256, ip>>24);
  3750. else
  3751. host = L"";
  3752. }
  3753. }
  3754. }
  3755. if (host == L"")
  3756. {
  3757. UINT temp;
  3758. if (!GetSockName(host, temp))
  3759. {
  3760. bError = true;
  3761. break;
  3762. }
  3763. host.Replace(L'.', L',');
  3764. }
  3765. if (!bError)
  3766. {
  3767. host.Format(host+L",%d,%d", nPort/256, nPort%256);
  3768. if (!Send(L"PORT " + host)) // send PORT cmd to server
  3769. bError = TRUE;
  3770. }
  3771. }
  3772. else if (GetFamily() == AF_INET6)
  3773. {
  3774. host = GetOption(OPTION_TRANSFERIP6);
  3775. if (host != L"")
  3776. {
  3777. USES_CONVERSION;
  3778. addrinfo hints, *res;
  3779. memset(&hints, 0, sizeof(addrinfo));
  3780. hints.ai_family = AF_INET6;
  3781. hints.ai_socktype = SOCK_STREAM;
  3782. if (!getaddrinfo(T2CA(host), "1024", &hints, &res))
  3783. {
  3784. host = Inet6AddrToString(((SOCKADDR_IN6 *)res->ai_addr)->sin6_addr);
  3785. freeaddrinfo(res);
  3786. }
  3787. else
  3788. host = L"";
  3789. }
  3790. if (host == L"")
  3791. {
  3792. UINT temp;
  3793. if(!GetSockName(host, temp))
  3794. bError = true;
  3795. }
  3796. if (!bError)
  3797. {
  3798. // assamble EPRT command
  3799. CString cmd;
  3800. cmd.Format(L"EPRT |2|" + host + L"|%d|", nPort);
  3801. if (!Send(cmd))
  3802. bError = TRUE;
  3803. }
  3804. }
  3805. else
  3806. {
  3807. LogMessage(FZ_LOG_WARNING, L"Protocol %d not supported", GetFamily());
  3808. bError = true;
  3809. }
  3810. }
  3811. }
  3812. break;
  3813. case FILETRANSFER_LIST_TYPE:
  3814. if (!Send(L"TYPE A"))
  3815. bError=TRUE;
  3816. break;
  3817. case FILETRANSFER_LIST_LIST:
  3818. {
  3819. if (!m_pTransferSocket)
  3820. {
  3821. ResetOperation(FZ_REPLY_ERROR);
  3822. return;
  3823. }
  3824. m_pTransferSocket->SetActive();
  3825. CString cmd = GetListingCmd();
  3826. if(!Send(cmd))
  3827. bError=TRUE;
  3828. else if(pData->bPasv)
  3829. {
  3830. if (!ConnectTransferSocket(pData->host, pData->port))
  3831. {
  3832. bError=TRUE;
  3833. ShowStatus(IDS_ERRORMSG_CANTGETLIST,FZ_LOG_ERROR);
  3834. }
  3835. }
  3836. }
  3837. break;
  3838. case FILETRANSFER_NOLIST_SIZE:
  3839. {
  3840. CString command = L"SIZE ";
  3841. command += pData->transferfile.remotepath.FormatFilename(pData->transferfile.remotefile, !pData->bUseAbsolutePaths);
  3842. if (!Send(command))
  3843. bError=TRUE;
  3844. }
  3845. break;
  3846. case FILETRANSFER_NOLIST_MDTM:
  3847. {
  3848. CString command = L"MDTM ";
  3849. command += pData->transferfile.remotepath.FormatFilename(pData->transferfile.remotefile, !pData->bUseAbsolutePaths);
  3850. if (!Send(command))
  3851. bError=TRUE;
  3852. }
  3853. break;
  3854. case FILETRANSFER_TYPE:
  3855. if (pData->transferfile.nType==1)
  3856. {
  3857. if (!Send(L"TYPE A"))
  3858. bError=TRUE;
  3859. }
  3860. else
  3861. if (!Send(L"TYPE I"))
  3862. bError=TRUE;
  3863. break;
  3864. case FILETRANSFER_MODE:
  3865. #ifdef MPEXT_NO_ZLIB
  3866. DebugFail();
  3867. #else
  3868. if (m_useZlib)
  3869. {
  3870. if (!Send(L"MODE S"))
  3871. bError = TRUE;
  3872. }
  3873. else
  3874. if (!Send(L"MODE Z"))
  3875. bError = TRUE;
  3876. #endif
  3877. break;
  3878. case FILETRANSFER_OPTS:
  3879. #ifdef MPEXT_NO_ZLIB
  3880. DebugFail();
  3881. #else
  3882. {
  3883. pData->newZlibLevel = GetOptionVal(OPTION_MODEZ_LEVEL);
  3884. CString str;
  3885. str.Format(L"OPTS MODE Z LEVEL %d", pData->newZlibLevel);
  3886. if (!Send(str))
  3887. bError = TRUE;
  3888. }
  3889. #endif
  3890. break;
  3891. case FILETRANSFER_PORTPASV:
  3892. if (pData->bPasv)
  3893. {
  3894. if (!Send((GetFamily() == AF_INET) ? L"PASV" : L"EPSV"))
  3895. bError=TRUE;
  3896. }
  3897. else
  3898. {
  3899. if (m_pTransferSocket)
  3900. {
  3901. delete m_pTransferSocket;
  3902. }
  3903. m_pTransferSocket=new CTransferSocket(this, m_Operation.nOpMode);
  3904. #ifndef MPEXT_NO_ZLIB
  3905. if (m_useZlib)
  3906. {
  3907. if (!m_pTransferSocket->InitZlib(m_zlibLevel))
  3908. {
  3909. ShowStatus(L"Failed to initialize zlib", FZ_LOG_ERROR);
  3910. ResetOperation(FZ_REPLY_ERROR);
  3911. return;
  3912. }
  3913. }
  3914. #endif
  3915. #ifndef MPEXT_NO_GSS
  3916. if (m_pGssLayer && m_pGssLayer->AuthSuccessful())
  3917. m_pTransferSocket->UseGSS(m_pGssLayer);
  3918. #endif
  3919. m_pTransferSocket->m_nInternalMessageID=m_pOwner->m_nInternalMessageID;
  3920. m_pTransferSocket->m_bListening = TRUE;
  3921. m_pTransferSocket->SetFamily(GetFamily());
  3922. if(!m_pTransferSocket->Create(m_pSslLayer && m_bProtP) || !m_pTransferSocket->AsyncSelect())
  3923. bError = TRUE;
  3924. else if (m_pProxyLayer)
  3925. {
  3926. SOCKADDR_IN addr;
  3927. int len=sizeof(addr);
  3928. if (!m_pProxyLayer->GetPeerName((SOCKADDR *)&addr,&len))
  3929. {
  3930. ShowStatus(IDS_ERRORMSG_CANTGETLIST,FZ_LOG_ERROR);
  3931. bError=TRUE;
  3932. }
  3933. else if (!m_pTransferSocket->Listen(addr.sin_addr.S_un.S_addr))
  3934. {
  3935. ShowStatus(IDS_ERRORMSG_CANTGETLIST,FZ_LOG_ERROR);
  3936. bError=TRUE;
  3937. }
  3938. //Don't send PORT command yet, params are unknown.
  3939. //will be sent in TransfersocketListenFinished
  3940. }
  3941. else
  3942. {
  3943. //Set up an active file transfer
  3944. CString temp;
  3945. UINT nPort;
  3946. if (//create listen socket (let Windows choose the port) & start listening
  3947. !m_pTransferSocket->Listen() ||
  3948. !m_pTransferSocket->GetSockName(temp, nPort))
  3949. {
  3950. bError = TRUE;
  3951. break;
  3952. }
  3953. CString host;
  3954. if (GetFamily() == AF_INET)
  3955. {
  3956. host = GetOption(OPTION_TRANSFERIP);
  3957. if (host != L"")
  3958. {
  3959. DWORD ip = inet_addr(T2CA(host));
  3960. if (ip != INADDR_NONE)
  3961. host.Format(L"%d,%d,%d,%d", ip%256, (ip>>8)%256, (ip>>16)%256, ip>>24);
  3962. else
  3963. {
  3964. hostent *fullname = gethostbyname(T2CA(host));
  3965. if (!fullname)
  3966. host = L"";
  3967. else
  3968. {
  3969. DWORD ip = ((LPIN_ADDR)fullname->h_addr)->s_addr;
  3970. if (ip != INADDR_NONE)
  3971. host.Format(L"%d,%d,%d,%d", ip%256, (ip>>8)%256, (ip>>16)%256, ip>>24);
  3972. else
  3973. host = L"";
  3974. }
  3975. }
  3976. }
  3977. if (host == L"")
  3978. {
  3979. UINT temp;
  3980. if (!GetSockName(host, temp))
  3981. bError = true;
  3982. host.Replace(L'.', L',');
  3983. }
  3984. if (!bError)
  3985. {
  3986. host.Format(host+L",%d,%d", nPort/256, nPort%256);
  3987. if (!Send(L"PORT " + host)) // send PORT cmd to server
  3988. bError = TRUE;
  3989. }
  3990. }
  3991. else if (GetFamily() == AF_INET6)
  3992. {
  3993. host = GetOption(OPTION_TRANSFERIP6);
  3994. if (host != L"")
  3995. {
  3996. USES_CONVERSION;
  3997. addrinfo hints, *res;
  3998. memset(&hints, 0, sizeof(addrinfo));
  3999. hints.ai_family = AF_INET6;
  4000. hints.ai_socktype = SOCK_STREAM;
  4001. if (!getaddrinfo(T2CA(host), "1024", &hints, &res))
  4002. {
  4003. host = Inet6AddrToString(((SOCKADDR_IN6 *)res->ai_addr)->sin6_addr);
  4004. freeaddrinfo(res);
  4005. }
  4006. else
  4007. host = L"";
  4008. }
  4009. if (host == L"")
  4010. {
  4011. UINT temp;
  4012. if(!GetSockName(host, temp))
  4013. bError = true;
  4014. }
  4015. if (!bError)
  4016. {
  4017. // assamble EPRT command
  4018. CString cmd;
  4019. cmd.Format(L"EPRT |2|" + host + L"|%d|", nPort);
  4020. if (!Send(cmd))
  4021. bError = TRUE;
  4022. }
  4023. }
  4024. else
  4025. {
  4026. LogMessage(FZ_LOG_WARNING, L"Protocol %d not supported", GetFamily());
  4027. bError = true;
  4028. }
  4029. if (bError)
  4030. {
  4031. ResetOperation(FZ_REPLY_ERROR);
  4032. return;
  4033. }
  4034. }
  4035. }
  4036. break;
  4037. case FILETRANSFER_REST:
  4038. DebugAssert(m_pDataFile);
  4039. {
  4040. CString command;
  4041. __int64 transferoffset =
  4042. pData->transferfile.get ?
  4043. GetLength64(*m_pDataFile) :
  4044. pData->transferdata.transfersize-pData->transferdata.transferleft;
  4045. command.Format(L"REST %I64d", transferoffset);
  4046. if (!Send(command))
  4047. bError=TRUE;
  4048. }
  4049. break;
  4050. case FILETRANSFER_RETRSTOR:
  4051. // send RETR/STOR command to server
  4052. if (!m_pTransferSocket)
  4053. {
  4054. ResetOperation(FZ_REPLY_ERROR);
  4055. return;
  4056. }
  4057. m_pTransferSocket->m_transferdata=pData->transferdata;
  4058. if (GetOptionVal(OPTION_MPEXT_TRANSFER_ACTIVE_IMMEDIATELY) || !pData->bPasv)
  4059. {
  4060. m_pTransferSocket->SetActive();
  4061. }
  4062. CString filename;
  4063. filename = pData->transferfile.remotepath.FormatFilename(pData->transferfile.remotefile, !pData->bUseAbsolutePaths);
  4064. if(!Send((pData->transferfile.get?L"RETR ":(pData->transferdata.bResumeAppend)?L"APPE ":L"STOR ")+ filename))
  4065. bError = TRUE;
  4066. else
  4067. {
  4068. if (pData->bPasv)
  4069. {
  4070. // if PASV create the socket & initiate outbound data channel connection
  4071. if (!ConnectTransferSocket(pData->host, pData->port))
  4072. {
  4073. bError=TRUE;
  4074. }
  4075. }
  4076. }
  4077. break;
  4078. }
  4079. if (bError)
  4080. { //Error transferring the file
  4081. LogMessage(FZ_LOG_INFO, L"Transfer error");
  4082. ResetOperation(FZ_REPLY_ERROR);
  4083. return;
  4084. }
  4085. }
  4086. void CFtpControlSocket::TransferHandleListError()
  4087. {
  4088. if (m_pTransferSocket)
  4089. delete m_pTransferSocket;
  4090. m_pTransferSocket=0;
  4091. m_Operation.nOpState = FILETRANSFER_NOLIST_SIZE;
  4092. }
  4093. static int atoui(const wchar_t * s)
  4094. {
  4095. wchar_t * endptr;
  4096. int result = wcstol(s, &endptr, 10);
  4097. if ((*s == L'\0') || (*endptr != L'\0'))
  4098. {
  4099. result = -1;
  4100. }
  4101. return result;
  4102. }
  4103. bool CFtpControlSocket::HandleMdtm(int code, t_directory::t_direntry::t_date & date)
  4104. {
  4105. bool result = false;
  4106. if (code==2)
  4107. {
  4108. CString line = GetReply();
  4109. if ( line.GetLength()>4 && line.Left(4) == L"213 " )
  4110. {
  4111. int y=0, M=0, d=0, h=0, m=0, s=0;
  4112. bool hasseconds = false;
  4113. line=line.Mid(4);
  4114. y=atoui(line.Left(4));
  4115. if ((y >= 0) && (line.GetLength() > 4))
  4116. {
  4117. line=line.Mid(4);
  4118. M=atoui(line.Left(2));
  4119. if ((M >= 0) && (line.GetLength() > 2))
  4120. {
  4121. line=line.Mid(2);
  4122. d=atoui(line.Left(2));
  4123. if ((d >= 0) && (line.GetLength() > 2))
  4124. {
  4125. line=line.Mid(2);
  4126. h=atoui(line.Left(2));
  4127. if ((h >= 0) && (line.GetLength() > 2))
  4128. {
  4129. line=line.Mid(2);
  4130. m=atoui(line.Left(2));
  4131. if ((m >= 0) && (line.GetLength() > 2))
  4132. {
  4133. line=line.Mid(2);
  4134. s=_ttoi(line.Left(2));
  4135. hasseconds = true;
  4136. }
  4137. }
  4138. }
  4139. if (M>0 && M<=12 && d>0 && d<=31 && h>=0 && h<24 && m>=0 && m<60 && s>=0 && s<60)
  4140. {
  4141. result = true;
  4142. date.year = y;
  4143. date.month = M;
  4144. date.day = d;
  4145. date.hour = h;
  4146. date.minute = m;
  4147. date.second = s;
  4148. date.hastime = true;
  4149. date.hasseconds = hasseconds;
  4150. date.hasdate = true;
  4151. date.utc = true;
  4152. }
  4153. }
  4154. }
  4155. }
  4156. }
  4157. return result;
  4158. }
  4159. bool CFtpControlSocket::HandleSize(int code, __int64 & size)
  4160. {
  4161. bool result = false;
  4162. if (code == 2)
  4163. {
  4164. CString line = GetReply();
  4165. if ((line.GetLength() > 4) && (line.Left(4) == L"213 "))
  4166. {
  4167. size = _ttoi64(line.Mid(4));
  4168. result = true;
  4169. }
  4170. }
  4171. return result;
  4172. }
  4173. void CFtpControlSocket::TransferFinished(bool preserveFileTimeForUploads)
  4174. {
  4175. CFileTransferData *pData=static_cast<CFileTransferData *>(m_Operation.pData);
  4176. if (GetOptionVal(OPTION_PRESERVEDOWNLOADFILETIME) && m_pDataFile &&
  4177. pData->transferfile.get)
  4178. {
  4179. m_pTools->PreserveDownloadFileTime(
  4180. (HANDLE)m_pDataFile->m_hFile, reinterpret_cast<void *>(pData->transferfile.nUserData));
  4181. }
  4182. if (!pData->transferfile.get &&
  4183. GetOptionVal(OPTION_MPEXT_PRESERVEUPLOADFILETIME) && preserveFileTimeForUploads &&
  4184. ((m_serverCapabilities.GetCapability(mfmt_command) == yes) ||
  4185. (m_serverCapabilities.GetCapability(mdtm_command) == yes)))
  4186. {
  4187. CString filename =
  4188. pData->transferfile.remotepath.FormatFilename(pData->transferfile.remotefile, !pData->bUseAbsolutePaths);
  4189. struct tm tm;
  4190. if (m_pTools->GetFileModificationTimeInUtc((LPCTSTR)pData->transferfile.localfile, tm))
  4191. {
  4192. CString timestr;
  4193. timestr.Format(L"%02d%02d%02d%02d%02d%02d",
  4194. 1900 + tm.tm_year, 1 + tm.tm_mon, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);
  4195. CString command;
  4196. if (m_serverCapabilities.GetCapability(mfmt_command) == yes)
  4197. {
  4198. command = L"MFMT";
  4199. }
  4200. else
  4201. {
  4202. // Support for MDTM does not necessarily mean
  4203. // that the server supports non-standard hack
  4204. // of setting timestamp using
  4205. // MFMT-like (two argument) call to MDTM.
  4206. // IIS definitelly does.
  4207. command = L"MDTM";
  4208. }
  4209. if (Send( command + L" " + timestr + L" " + filename))
  4210. {
  4211. m_Operation.nOpState = FILETRANSFER_MFMT;
  4212. return;
  4213. }
  4214. }
  4215. }
  4216. //Transfer successful
  4217. ResetOperation(FZ_REPLY_OK);
  4218. }
  4219. void CFtpControlSocket::Cancel(BOOL bQuit/*=FALSE*/)
  4220. {
  4221. const int nOpMode = m_Operation.nOpMode;
  4222. if (nOpMode==CSMODE_CONNECT)
  4223. DoClose(FZ_REPLY_CANCEL);
  4224. else if (nOpMode & CSMODE_LIST)
  4225. {
  4226. if (m_Operation.nOpState == LIST_WAITFINISH)
  4227. m_skipReply = true;
  4228. ResetOperation(FZ_REPLY_ERROR | FZ_REPLY_CANCEL);
  4229. }
  4230. else if (nOpMode & CSMODE_TRANSFER)
  4231. {
  4232. if (m_Operation.nOpState == FILETRANSFER_WAITFINISH || m_Operation.nOpState == FILETRANSFER_LIST_WAITFINISH)
  4233. m_skipReply = true;
  4234. ResetOperation(FZ_REPLY_ERROR | FZ_REPLY_CANCEL | FZ_REPLY_ABORTED);
  4235. }
  4236. else if (nOpMode != CSMODE_NONE)
  4237. ResetOperation(FZ_REPLY_ERROR | FZ_REPLY_CANCEL);
  4238. if (nOpMode != CSMODE_NONE && !bQuit)
  4239. ShowStatus(IDS_ERRORMSG_INTERRUPTED, FZ_LOG_ERROR);
  4240. if (m_awaitsReply)
  4241. m_skipReply = true;
  4242. }
  4243. void CFtpControlSocket::TransfersocketListenFinished(unsigned int ip, unsigned short port)
  4244. {
  4245. if (m_Operation.nOpMode&CSMODE_TRANSFER || m_Operation.nOpMode&CSMODE_LIST)
  4246. {
  4247. CString host;
  4248. host.Format(L"%d,%d,%d,%d,%d,%d",ip%256,(ip>>8)%256,(ip>>16)%256,(ip>>24)%256,port%256,port>>8);
  4249. Send(L"PORT "+host);
  4250. }
  4251. }
  4252. void CFtpControlSocket::ResumeTransfer()
  4253. {
  4254. if (m_pTransferSocket && (m_Operation.nOpMode&CSMODE_TRANSFER || m_Operation.nOpMode&CSMODE_LIST))
  4255. {
  4256. m_pTransferSocket->OnSend(0);
  4257. m_pTransferSocket->OnReceive(0);
  4258. }
  4259. }
  4260. BOOL CFtpControlSocket::Create()
  4261. {
  4262. if (!GetOptionVal(OPTION_LIMITPORTRANGE))
  4263. return CAsyncSocketEx::Create(0, SOCK_STREAM, FD_READ | FD_WRITE | FD_OOB | FD_ACCEPT | FD_CONNECT | FD_CLOSE, 0, GetOptionVal(OPTION_ENABLE_IPV6) ? AF_UNSPEC : AF_INET);
  4264. else
  4265. {
  4266. int min=GetOptionVal(OPTION_PORTRANGELOW);
  4267. int max=GetOptionVal(OPTION_PORTRANGEHIGH);
  4268. if (min>=max)
  4269. {
  4270. ShowStatus(IDS_ERRORMSG_CANTCREATEDUETOPORTRANGE,FZ_LOG_ERROR);
  4271. return FALSE;
  4272. }
  4273. int startport = static_cast<int>(min+((double)rand()*(max-min))/(RAND_MAX+1));
  4274. int port = startport;
  4275. while (!CAsyncSocketEx::Create(port, SOCK_STREAM, FD_READ | FD_WRITE | FD_OOB | FD_ACCEPT | FD_CONNECT | FD_CLOSE, 0, GetOptionVal(OPTION_ENABLE_IPV6) ? AF_UNSPEC : AF_INET))
  4276. {
  4277. port++;
  4278. if (port>max)
  4279. port=min;
  4280. if (port==startport)
  4281. {
  4282. ShowStatus(IDS_ERRORMSG_CANTCREATEDUETOPORTRANGE,FZ_LOG_ERROR);
  4283. return FALSE;
  4284. }
  4285. if (!InitConnect())
  4286. return FALSE;
  4287. }
  4288. }
  4289. return TRUE;
  4290. }
  4291. void CFtpControlSocket::ResetOperation(int nSuccessful /*=FALSE*/)
  4292. {
  4293. if (nSuccessful & FZ_REPLY_CRITICALERROR)
  4294. nSuccessful |= FZ_REPLY_ERROR;
  4295. if (m_pTransferSocket)
  4296. {
  4297. ResetTransferSocket(!(nSuccessful & FZ_REPLY_ERROR));
  4298. delete m_pTransferSocket;
  4299. m_pTransferSocket=0;
  4300. }
  4301. if (m_pDataFile)
  4302. delete m_pDataFile;
  4303. m_pDataFile=0;
  4304. if (m_Operation.nOpMode)
  4305. {
  4306. //Unset busy attribute so that new commands can be executed
  4307. m_pOwner->SetBusy(FALSE);
  4308. if (m_Operation.nOpMode&CSMODE_CONNECT && nSuccessful&FZ_REPLY_ERROR)
  4309. {
  4310. nSuccessful|=FZ_REPLY_DISCONNECTED;
  4311. ShowStatus(IDS_ERRORMSG_CANTCONNECT, FZ_LOG_ERROR);
  4312. }
  4313. if (m_Operation.nOpMode & (CSMODE_LIST|CSMODE_LISTFILE|CSMODE_TRANSFER) && nSuccessful==FZ_REPLY_OK)
  4314. m_LastSendTime=CTime::GetCurrentTime();
  4315. //Update remote file entry
  4316. if (m_Operation.pData &&
  4317. m_Operation.nOpMode&CSMODE_TRANSFER &&
  4318. (!((CFileTransferData*)m_Operation.pData)->transferfile.get) &&
  4319. m_pDirectoryListing &&
  4320. m_Operation.nOpState>=FILETRANSFER_RETRSTOR)
  4321. {
  4322. CString filename=((CFileTransferData*)m_Operation.pData)->transferfile.remotefile;
  4323. CServerPath path=((CFileTransferData*)m_Operation.pData)->transferfile.remotepath;
  4324. t_directory dir;
  4325. BOOL res=FALSE;
  4326. if (m_pDirectoryListing)
  4327. {
  4328. if (m_pDirectoryListing->path==path)
  4329. {
  4330. dir=*m_pDirectoryListing;
  4331. res=TRUE;
  4332. }
  4333. }
  4334. t_directory WorkingDir;
  4335. BOOL bFound=m_pOwner->GetWorkingDir(&WorkingDir);
  4336. if (!res && bFound)
  4337. if (WorkingDir.path==path)
  4338. {
  4339. dir=WorkingDir;
  4340. res=TRUE;
  4341. }
  4342. if (res)
  4343. {
  4344. int i;
  4345. for (i=0; i<dir.num; i++)
  4346. if (dir.direntry[i].name==filename)
  4347. {
  4348. dir.direntry[i].bUnsure = TRUE;
  4349. if (nSuccessful & FZ_REPLY_ERROR)
  4350. {
  4351. dir.direntry[i].bUnsure = TRUE;
  4352. if (!((CFileTransferData *)m_Operation.pData)->transferfile.get)
  4353. dir.direntry[i].size = -1;
  4354. if (!GetLength64(((CFileTransferData *)m_Operation.pData)->transferfile.localfile, dir.direntry[i].size))
  4355. dir.direntry[i].size = -1;
  4356. }
  4357. dir.direntry[i].date.hasdate = false;
  4358. break;
  4359. }
  4360. if (i==dir.num)
  4361. {
  4362. t_directory::t_direntry *entries=new t_directory::t_direntry[dir.num+1];
  4363. int i;
  4364. for (i=0; i<dir.num; i++)
  4365. entries[i]=dir.direntry[i];
  4366. entries[i].name=filename;
  4367. entries[i].dir=FALSE;
  4368. entries[i].date.hasdate=FALSE;
  4369. entries[i].size=-1;
  4370. if (nSuccessful&FZ_REPLY_OK)
  4371. entries[i].bUnsure=FALSE;
  4372. else
  4373. entries[i].bUnsure=TRUE;
  4374. delete [] dir.direntry;
  4375. dir.direntry=entries;
  4376. dir.num++;
  4377. }
  4378. BOOL updated=FALSE;
  4379. if (m_pDirectoryListing && m_pDirectoryListing->path==dir.path)
  4380. {
  4381. updated=TRUE;
  4382. SetDirectoryListing(&dir, bFound && WorkingDir.path == dir.path);
  4383. }
  4384. if (!updated)
  4385. if (bFound && WorkingDir.path==dir.path)
  4386. {
  4387. updated = TRUE;
  4388. m_pOwner->SetWorkingDir(&dir);
  4389. }
  4390. }
  4391. }
  4392. if (m_Operation.pData && nSuccessful&FZ_REPLY_ERROR)
  4393. {
  4394. if (m_Operation.nOpMode&CSMODE_TRANSFER)
  4395. if (nSuccessful&FZ_REPLY_ABORTED)
  4396. //Transfer aborted by user
  4397. ShowStatus((m_Operation.nOpMode&CSMODE_DOWNLOAD)?IDS_ERRORMSG_DOWNLOADABORTED:IDS_ERRORMSG_UPLOADABORTED,FZ_LOG_ERROR);
  4398. else
  4399. ShowStatus(((CFileTransferData*)m_Operation.pData)->transferfile.get?IDS_ERRORMSG_DOWNLOADFAILED:IDS_ERRORMSG_UPLOADFAILED,FZ_LOG_ERROR);
  4400. else if (m_Operation.nOpMode&CSMODE_LIST)
  4401. ShowStatus(IDS_ERRORMSG_CANTGETLIST,FZ_LOG_ERROR);
  4402. else if (m_Operation.nOpMode&CSMODE_LISTFILE)
  4403. ShowStatus(IDS_ERRORMSG_CANTGETLISTFILE,FZ_LOG_ERROR);
  4404. }
  4405. else if (m_Operation.pData && m_Operation.nOpMode&CSMODE_TRANSFER && nSuccessful==FZ_REPLY_OK)
  4406. ShowStatus(((CFileTransferData*)m_Operation.pData)->transferfile.get?IDS_STATUSMSG_DOWNLOADSUCCESSFUL:IDS_STATUSMSG_UPLOADSUCCESSFUL,FZ_LOG_STATUS);
  4407. }
  4408. else
  4409. {
  4410. // When control socket is waiting for reply
  4411. // to keepalive (!IsReady), while new command comes,
  4412. // its execution is postponed
  4413. // (CMainThread::m_pPostKeepAliveCommand),
  4414. // but the main thread
  4415. // is set to busy state already (CMainThread::Command).
  4416. // if connection is closed before without receiving reply,
  4417. // main thread would stay busy forever.
  4418. m_pOwner->SetBusy(FALSE);
  4419. //No operation in progress
  4420. nSuccessful&=FZ_REPLY_DISCONNECTED|FZ_REPLY_CANCEL;
  4421. if (!nSuccessful)
  4422. DebugFail();
  4423. }
  4424. if (nSuccessful&FZ_REPLY_DISCONNECTED)
  4425. m_pOwner->SetWorkingDir(0); //Disconnected, reset working dir
  4426. if (m_Operation.nOpMode)
  4427. GetIntern()->PostMessage(FZ_MSG_MAKEMSG(FZ_MSG_REPLY, m_pOwner->m_LastCommand.id), nSuccessful);
  4428. else
  4429. GetIntern()->PostMessage(FZ_MSG_MAKEMSG(FZ_MSG_REPLY, 0), nSuccessful);
  4430. m_Operation.nOpMode=0;
  4431. m_Operation.nOpState=-1;
  4432. if (m_Operation.pData)
  4433. delete m_Operation.pData;
  4434. m_Operation.pData=0;
  4435. }
  4436. void CFtpControlSocket::Delete(CString filename, const CServerPath &path, bool filenameOnly)
  4437. {
  4438. class CDeleteData : public CFtpControlSocket::t_operation::COpData
  4439. {
  4440. public:
  4441. CDeleteData() {}
  4442. virtual ~CDeleteData() {}
  4443. CString m_FileName;
  4444. CServerPath path;
  4445. };
  4446. if (filename!=L"")
  4447. {
  4448. DebugAssert(!path.IsEmpty());
  4449. DebugAssert(m_Operation.nOpMode==CSMODE_NONE);
  4450. DebugAssert(m_Operation.nOpState==-1);
  4451. DebugAssert(!m_Operation.pData);
  4452. m_Operation.nOpMode=CSMODE_DELETE;
  4453. CString command = L"DELE ";
  4454. if (!filenameOnly)
  4455. {
  4456. command += path.FormatFilename(filename);
  4457. }
  4458. else
  4459. {
  4460. command += filename;
  4461. }
  4462. if (!Send(command))
  4463. return;
  4464. CDeleteData *data=new CDeleteData;
  4465. data->m_FileName=filename;
  4466. data->path=path;
  4467. m_Operation.pData=data;
  4468. }
  4469. else
  4470. {
  4471. DebugAssert(path.IsEmpty());
  4472. DebugAssert(m_Operation.nOpMode==CSMODE_DELETE);
  4473. DebugAssert(m_Operation.nOpState==-1);
  4474. DebugAssert(m_Operation.pData);
  4475. int res=GetReplyCode();
  4476. if (res==2 || res==3)
  4477. { //Remove file from cached dirs
  4478. CDeleteData *pData=(CDeleteData *)m_Operation.pData;
  4479. t_directory dir;
  4480. BOOL res=FALSE;
  4481. if (m_pDirectoryListing)
  4482. {
  4483. if (m_pDirectoryListing->path==pData->path)
  4484. {
  4485. dir=*m_pDirectoryListing;
  4486. res=TRUE;
  4487. }
  4488. }
  4489. t_directory WorkingDir;
  4490. BOOL bFound=m_pOwner->GetWorkingDir(&WorkingDir);
  4491. if (!res && bFound)
  4492. if (WorkingDir.path==pData->path)
  4493. {
  4494. dir=WorkingDir;
  4495. res=TRUE;
  4496. }
  4497. if (res)
  4498. {
  4499. BOOL found=FALSE;
  4500. for (int i=0;i<dir.num;i++)
  4501. {
  4502. if (dir.direntry[i].name==pData->m_FileName)
  4503. {
  4504. DebugAssert(!dir.direntry[i].dir || dir.direntry[i].bLink);
  4505. found=TRUE;
  4506. break;
  4507. }
  4508. }
  4509. if (found)
  4510. {
  4511. t_directory::t_direntry *direntry=new t_directory::t_direntry[dir.num-1];
  4512. int j=0;
  4513. int i;
  4514. for (i=0; i<dir.num; i++)
  4515. {
  4516. if (dir.direntry[i].name==pData->m_FileName)
  4517. continue;
  4518. direntry[j]=dir.direntry[i];
  4519. j++;
  4520. }
  4521. delete [] dir.direntry;
  4522. dir.direntry=direntry;
  4523. dir.num--;
  4524. BOOL updated=FALSE;
  4525. if (m_pDirectoryListing)
  4526. if (m_pDirectoryListing->path==dir.path)
  4527. {
  4528. updated=TRUE;
  4529. SetDirectoryListing(&dir);
  4530. }
  4531. if (!updated)
  4532. if (WorkingDir.path==dir.path)
  4533. {
  4534. updated=TRUE;
  4535. m_pOwner->SetWorkingDir(&dir);
  4536. }
  4537. }
  4538. }
  4539. }
  4540. ResetOperation(FZ_REPLY_OK);
  4541. }
  4542. }
  4543. void CFtpControlSocket::RemoveDir(CString dirname, const CServerPath &path)
  4544. {
  4545. class CRemoveDirData : public CFtpControlSocket::t_operation::COpData
  4546. {
  4547. public:
  4548. CRemoveDirData() {}
  4549. virtual ~CRemoveDirData() {}
  4550. CString m_DirName;
  4551. CServerPath path;
  4552. };
  4553. if (dirname != L"")
  4554. {
  4555. DebugAssert(!path.IsEmpty());
  4556. DebugAssert(m_Operation.nOpMode == CSMODE_NONE);
  4557. DebugAssert(m_Operation.nOpState == -1);
  4558. DebugAssert(!m_Operation.pData);
  4559. m_Operation.nOpMode = CSMODE_RMDIR;
  4560. CServerPath newPath = path;
  4561. if (!newPath.AddSubdir(dirname))
  4562. {
  4563. ShowStatus(L"Unable to concatenate path", FZ_LOG_ERROR);
  4564. return;
  4565. }
  4566. if (!Send(L"RMD "+ newPath.GetPathUnterminated()))
  4567. return;
  4568. CRemoveDirData *data = new CRemoveDirData;
  4569. data->m_DirName = dirname;
  4570. data->path = path;
  4571. m_Operation.pData = data;
  4572. }
  4573. else
  4574. {
  4575. DebugAssert(path.IsEmpty());
  4576. DebugAssert(m_Operation.nOpMode == CSMODE_RMDIR);
  4577. DebugAssert(m_Operation.nOpState == -1);
  4578. DebugAssert(m_Operation.pData);
  4579. int res = GetReplyCode();
  4580. if (res == 2 || res == 3)
  4581. { //Remove dir from cached dirs
  4582. CRemoveDirData *pData= (CRemoveDirData *)m_Operation.pData;
  4583. t_directory dir;
  4584. BOOL res = FALSE;
  4585. if (m_pDirectoryListing)
  4586. {
  4587. if (m_pDirectoryListing->path == pData->path)
  4588. {
  4589. dir = *m_pDirectoryListing;
  4590. res = TRUE;
  4591. }
  4592. }
  4593. t_directory WorkingDir;
  4594. BOOL bFound = m_pOwner->GetWorkingDir(&WorkingDir);
  4595. if (!res && bFound)
  4596. if (WorkingDir.path == pData->path)
  4597. {
  4598. dir = WorkingDir;
  4599. res = TRUE;
  4600. }
  4601. if (res)
  4602. {
  4603. BOOL found = FALSE;
  4604. for (int i = 0; i < dir.num; i++)
  4605. {
  4606. if (dir.direntry[i].name == pData->m_DirName)
  4607. {
  4608. DebugAssert(dir.direntry[i].dir);
  4609. found = TRUE;
  4610. break;
  4611. }
  4612. }
  4613. if (found)
  4614. {
  4615. t_directory::t_direntry *direntry = new t_directory::t_direntry[dir.num-1];
  4616. int j = 0;
  4617. int i;
  4618. for (i = 0; i < dir.num; i++)
  4619. {
  4620. if (dir.direntry[i].name == pData->m_DirName)
  4621. continue;
  4622. direntry[j] = dir.direntry[i];
  4623. j++;
  4624. }
  4625. delete [] dir.direntry;
  4626. dir.direntry = direntry;
  4627. dir.num--;
  4628. BOOL updated = FALSE;
  4629. if (m_pDirectoryListing)
  4630. if (m_pDirectoryListing->path == dir.path)
  4631. {
  4632. updated = TRUE;
  4633. SetDirectoryListing(&dir);
  4634. }
  4635. if (!updated)
  4636. if (WorkingDir.path == dir.path)
  4637. {
  4638. updated = TRUE;
  4639. m_pOwner->SetWorkingDir(&dir);
  4640. }
  4641. }
  4642. }
  4643. ResetOperation(FZ_REPLY_OK);
  4644. }
  4645. else
  4646. ResetOperation(FZ_REPLY_ERROR);
  4647. }
  4648. }
  4649. int CFtpControlSocket::CheckOverwriteFile()
  4650. {
  4651. if (!m_Operation.pData)
  4652. {
  4653. return FZ_REPLY_ERROR;
  4654. }
  4655. CFileTransferData *pData = reinterpret_cast<CFileTransferData *>(m_Operation.pData);
  4656. int nReplyError = 0;
  4657. CFileStatus64 status;
  4658. BOOL res = GetStatus64(pData->transferfile.localfile, status);
  4659. if (!res)
  4660. {
  4661. if (!pData->transferfile.get)
  4662. {
  4663. ShowStatus(IDS_ERRORMSG_CANTGETLISTFILE,FZ_LOG_ERROR);
  4664. nReplyError = FZ_REPLY_CRITICALERROR; //File has to exist when uploading
  4665. }
  4666. else
  4667. {
  4668. m_Operation.nOpState = FILETRANSFER_TYPE;
  4669. }
  4670. }
  4671. else
  4672. {
  4673. if (status.m_attribute & 0x10)
  4674. {
  4675. nReplyError = FZ_REPLY_CRITICALERROR; //Can't transfer to/from dirs
  4676. }
  4677. else
  4678. {
  4679. _int64 localsize;
  4680. if (!GetLength64(pData->transferfile.localfile, localsize))
  4681. if (!pData->transferfile.get)
  4682. nReplyError = FZ_REPLY_CRITICALERROR;
  4683. else
  4684. m_Operation.nOpState = FILETRANSFER_TYPE;
  4685. CTime *localtime = NULL;
  4686. TRY
  4687. {
  4688. if (status.m_has_mtime && status.m_mtime != -1)
  4689. localtime = new CTime(status.m_mtime);
  4690. }
  4691. CATCH_ALL(e)
  4692. {
  4693. TCHAR buffer[1024];
  4694. CString str =L"Exception creating CTime object: ";
  4695. if (e->GetErrorMessage(buffer, 1024, NULL))
  4696. str += buffer;
  4697. else
  4698. str += L"Unknown exception";
  4699. LogMessageRaw(FZ_LOG_WARNING, str);
  4700. localtime = NULL;
  4701. }
  4702. END_CATCH_ALL;
  4703. BOOL bRemoteFileExists = FALSE;
  4704. __int64 remotesize = -1;
  4705. t_directory::t_direntry::t_date remotetime;
  4706. if (m_pDirectoryListing)
  4707. {
  4708. for (int i=0; i<m_pDirectoryListing->num; i++)
  4709. {
  4710. CString remotefile = pData->transferfile.remotefile;
  4711. if (m_pDirectoryListing->direntry[i].name == remotefile)
  4712. {
  4713. remotesize = m_pDirectoryListing->direntry[i].size;
  4714. remotetime = m_pDirectoryListing->direntry[i].date;
  4715. bRemoteFileExists = TRUE;
  4716. break;
  4717. }
  4718. }
  4719. }
  4720. if (!bRemoteFileExists && pData->hasRemoteDate)
  4721. {
  4722. remotetime = pData->remoteDate;
  4723. bRemoteFileExists = TRUE;
  4724. }
  4725. if (remotesize == -1 && pData->pFileSize)
  4726. {
  4727. remotesize = *pData->pFileSize;
  4728. bRemoteFileExists = TRUE;
  4729. }
  4730. if (bRemoteFileExists || pData->transferfile.get )
  4731. {
  4732. COverwriteRequestData *pOverwriteData = new COverwriteRequestData;
  4733. t_transferfile *pTransferFile = new t_transferfile;
  4734. *pTransferFile = pData->transferfile;
  4735. pOverwriteData->pTransferFile = pTransferFile;
  4736. if (pData->transferfile.get)
  4737. {
  4738. int pos = pData->transferfile.localfile.ReverseFind(L'\\');
  4739. // pos can be -1 here, e.g. in scripting, the code below still works then
  4740. pOverwriteData->FileName1 = pData->transferfile.localfile.Mid(pos+1);
  4741. pOverwriteData->FileName2 = pData->transferfile.remotefile;
  4742. pOverwriteData->path1 = pData->transferfile.localfile.Left(pos+1);
  4743. pOverwriteData->path2 = pData->transferfile.remotepath.GetPath();
  4744. pOverwriteData->size1 = localsize;
  4745. pOverwriteData->size2 = remotesize;
  4746. }
  4747. else
  4748. {
  4749. int pos = pData->transferfile.localfile.ReverseFind(L'\\');
  4750. // pos can be -1 here, e.g. in scripting, the code below still works then
  4751. pOverwriteData->FileName1 = pData->transferfile.remotefile;
  4752. pOverwriteData->FileName2 = pData->transferfile.localfile.Mid(pos+1);
  4753. pOverwriteData->path1 = pData->transferfile.remotepath.GetPath();
  4754. pOverwriteData->path2 = pData->transferfile.localfile.Left(pos+1);
  4755. pOverwriteData->size1 = remotesize;
  4756. pOverwriteData->size2 = localsize;
  4757. }
  4758. pOverwriteData->localtime = localtime;
  4759. pOverwriteData->remotetime = remotetime;
  4760. pOverwriteData->nRequestID = m_pOwner->GetNextAsyncRequestID();
  4761. if (!GetIntern()->PostMessage(FZ_MSG_MAKEMSG(FZ_MSG_ASYNCREQUEST, FZ_ASYNCREQUEST_OVERWRITE), (LPARAM)pOverwriteData))
  4762. {
  4763. delete pOverwriteData;
  4764. nReplyError = FZ_REPLY_ERROR;
  4765. }
  4766. else
  4767. {
  4768. m_bCheckForTimeout = FALSE;
  4769. m_Operation.nOpState = FILETRANSFER_WAIT;
  4770. }
  4771. }
  4772. else
  4773. {
  4774. m_Operation.nOpState = FILETRANSFER_TYPE;
  4775. delete localtime;
  4776. }
  4777. }
  4778. }
  4779. return nReplyError;
  4780. }
  4781. void CFtpControlSocket::SetFileExistsAction(int nAction, COverwriteRequestData *pData)
  4782. {
  4783. if (!pData)
  4784. return;
  4785. if (!(m_Operation.nOpMode & CSMODE_TRANSFER))
  4786. return;
  4787. if (m_Operation.nOpState != FILETRANSFER_WAIT)
  4788. return;
  4789. CFileTransferData* pTransferData = reinterpret_cast<CFileTransferData*>(m_Operation.pData);
  4790. if (!pTransferData)
  4791. return;
  4792. pTransferData->transferdata.bResume = false;
  4793. m_bCheckForTimeout = TRUE;
  4794. int nReplyError = 0;
  4795. switch (nAction)
  4796. {
  4797. case FILEEXISTS_SKIP:
  4798. nReplyError = FZ_REPLY_OK;
  4799. break;
  4800. case FILEEXISTS_OVERWRITE:
  4801. pTransferData->nWaitNextOpState = FILETRANSFER_TYPE;
  4802. break;
  4803. case FILEEXISTS_RENAME:
  4804. if (pTransferData->transferfile.get)
  4805. {
  4806. CFileStatus64 status;
  4807. if (GetStatus64(pData->FileName1, status))
  4808. {
  4809. ShowStatus(IDS_ERRORMSG_NAMEINUSE, FZ_LOG_ERROR);
  4810. nReplyError= FZ_REPLY_CRITICALERROR;
  4811. }
  4812. else
  4813. {
  4814. pTransferData->transferfile.localfile = pData->path1+pData->FileName1;
  4815. //Replace invalid characters in the local filename
  4816. int pos = pTransferData->transferfile.localfile.ReverseFind(L'\\');
  4817. for (int i = (pos+1); i < pTransferData->transferfile.localfile.GetLength(); i++)
  4818. if (pTransferData->transferfile.localfile[i] == L':')
  4819. pTransferData->transferfile.localfile.SetAt(i, L'_');
  4820. pTransferData->nWaitNextOpState= FILETRANSFER_TYPE;
  4821. }
  4822. }
  4823. else
  4824. {
  4825. DebugAssert(m_pDirectoryListing);
  4826. int i;
  4827. for (i = 0; i < m_pDirectoryListing->num; i++)
  4828. {
  4829. if (m_pDirectoryListing->direntry[i].name == pData->FileName1)
  4830. {
  4831. ShowStatus(IDS_ERRORMSG_NAMEINUSE, FZ_LOG_ERROR);
  4832. nReplyError = FZ_REPLY_CRITICALERROR;
  4833. break;
  4834. }
  4835. }
  4836. if (i==m_pDirectoryListing->num)
  4837. {
  4838. pTransferData->transferfile.remotefile = pData->FileName1;
  4839. pTransferData->nWaitNextOpState = FILETRANSFER_TYPE;
  4840. }
  4841. }
  4842. break;
  4843. case FILEEXISTS_RESUME:
  4844. if (pData->size1 >= 0)
  4845. {
  4846. pTransferData->transferdata.bResume = TRUE;
  4847. }
  4848. pTransferData->nWaitNextOpState = FILETRANSFER_TYPE;
  4849. break;
  4850. case FILEEXISTS_COMPLETE:
  4851. // Simulating transfer finish
  4852. m_Operation.nOpState=FILETRANSFER_WAITFINISH;
  4853. TransferFinished(true);
  4854. return; // Avoid call to FileTransfer below
  4855. }
  4856. if (nReplyError == FZ_REPLY_OK)
  4857. ResetOperation(FZ_REPLY_OK);
  4858. else if (nReplyError)
  4859. ResetOperation(FZ_REPLY_ERROR | nReplyError); //Error transferring the file
  4860. else
  4861. FileTransfer();
  4862. }
  4863. void CFtpControlSocket::SendKeepAliveCommand()
  4864. {
  4865. ShowStatus(L"Sending dummy command to keep session alive.", FZ_LOG_PROGRESS);
  4866. m_bKeepAliveActive=TRUE;
  4867. //Choose a random command from the list
  4868. TCHAR commands[4][7]={L"PWD",L"REST 0",L"TYPE A",L"TYPE I"};
  4869. int choice=(rand()*4)/(RAND_MAX+1);
  4870. Send(commands[choice]);
  4871. }
  4872. void CFtpControlSocket::MakeDir(const CServerPath &path)
  4873. {
  4874. //Directory creation works like this:
  4875. //Find existing parent and create subdirs one by one
  4876. if (m_Operation.nOpState == MKD_INIT)
  4877. {
  4878. DebugAssert(!path.IsEmpty());
  4879. DebugAssert(m_Operation.nOpMode==CSMODE_NONE);
  4880. DebugAssert(!m_Operation.pData);
  4881. m_Operation.nOpMode = CSMODE_MKDIR;
  4882. if (!Send(L"CWD "+path.GetParent().GetPathUnterminated()))
  4883. return;
  4884. CMakeDirData *data = new CMakeDirData;
  4885. data->path = path;
  4886. data->Current = path.GetParent();
  4887. data->Segments.push_front(path.GetLastSegment());
  4888. m_Operation.pData = data;
  4889. m_Operation.nOpState = MKD_FINDPARENT;
  4890. }
  4891. else if (m_Operation.nOpState==MKD_FINDPARENT)
  4892. {
  4893. DebugAssert(m_Operation.nOpMode==CSMODE_MKDIR);
  4894. DebugAssert(path.IsEmpty());
  4895. DebugAssert(m_Operation.pData);
  4896. CMakeDirData *pData=(CMakeDirData *)m_Operation.pData;
  4897. int res=GetReplyCode();
  4898. if (res==2 || res==3)
  4899. {
  4900. m_pOwner->SetCurrentPath(pData->Current);
  4901. m_Operation.nOpState=MKD_MAKESUBDIRS;
  4902. pData->Current.AddSubdir(pData->Segments.front());
  4903. CString Segment=pData->Segments.front();
  4904. pData->Segments.pop_front();
  4905. if (Send( L"MKD " + Segment))
  4906. m_Operation.nOpState = MKD_CHANGETOSUBDIR;
  4907. else
  4908. return;
  4909. }
  4910. else
  4911. {
  4912. if (!pData->Current.HasParent())
  4913. ResetOperation(FZ_REPLY_ERROR);
  4914. else
  4915. {
  4916. pData->Segments.push_front(pData->Current.GetLastSegment());
  4917. pData->Current=pData->Current.GetParent();
  4918. if (!Send(L"CWD "+pData->Current.GetPathUnterminated()))
  4919. return;
  4920. }
  4921. }
  4922. }
  4923. else if (m_Operation.nOpState==MKD_MAKESUBDIRS)
  4924. {
  4925. int res=GetReplyCode();
  4926. if (res==2 || res==3)
  4927. { //Create dir entry in parent dir
  4928. CMakeDirData *pData=(CMakeDirData *)m_Operation.pData;
  4929. DebugAssert(!pData->Segments.empty());
  4930. m_pOwner->SetCurrentPath(pData->Current);
  4931. pData->Current.AddSubdir(pData->Segments.front());
  4932. CString Segment=pData->Segments.front();
  4933. pData->Segments.pop_front();
  4934. if (Send( L"MKD " + Segment))
  4935. m_Operation.nOpState=MKD_CHANGETOSUBDIR;
  4936. else
  4937. return;
  4938. }
  4939. else
  4940. ResetOperation(FZ_REPLY_ERROR);
  4941. }
  4942. else if (m_Operation.nOpState==MKD_CHANGETOSUBDIR)
  4943. {
  4944. CMakeDirData *pData=(CMakeDirData *)m_Operation.pData;
  4945. int res=GetReplyCode();
  4946. if (res==2 || res==3 || //Creation successful
  4947. GetReply() == L"550 Directory already exists")//Creation was successful, although someone else did the work for us
  4948. { //Create dir entry in parent dir
  4949. CServerPath path2=pData->Current;
  4950. if (path2.HasParent())
  4951. {
  4952. CString name=path2.GetLastSegment();
  4953. path2=path2.GetParent();
  4954. t_directory dir;
  4955. BOOL res = FALSE;
  4956. if (m_pDirectoryListing)
  4957. {
  4958. if (m_pDirectoryListing->path == path2)
  4959. {
  4960. dir = *m_pDirectoryListing;
  4961. res = TRUE;
  4962. }
  4963. }
  4964. t_directory WorkingDir;
  4965. BOOL bFound = m_pOwner->GetWorkingDir(&WorkingDir);
  4966. if (!res && bFound)
  4967. if (WorkingDir.path == path2)
  4968. {
  4969. dir = WorkingDir;
  4970. res = TRUE;
  4971. }
  4972. if (!res)
  4973. {
  4974. dir.path = path2;
  4975. dir.server = m_CurrentServer;
  4976. }
  4977. int i;
  4978. for (i=0; i<dir.num; i++)
  4979. if (dir.direntry[i].name==name)
  4980. {
  4981. LogMessage(FZ_LOG_WARNING, L"Dir already exists in cache!");
  4982. break;
  4983. }
  4984. if (i==dir.num)
  4985. {
  4986. t_directory::t_direntry *entries=new t_directory::t_direntry[dir.num+1];
  4987. for (i=0;i<dir.num;i++)
  4988. entries[i]=dir.direntry[i];
  4989. entries[i].name=name;
  4990. entries[i].dir=TRUE;
  4991. entries[i].date.hasdate=FALSE;
  4992. entries[i].size=-1;
  4993. entries[i].bUnsure=FALSE;
  4994. delete [] dir.direntry;
  4995. dir.direntry=entries;
  4996. dir.num++;
  4997. BOOL updated = FALSE;
  4998. if (m_pDirectoryListing && m_pDirectoryListing->path == dir.path)
  4999. {
  5000. updated = TRUE;
  5001. SetDirectoryListing(&dir, bFound && WorkingDir.path == dir.path);
  5002. }
  5003. if (!updated)
  5004. if (bFound && WorkingDir.path == dir.path)
  5005. {
  5006. updated = TRUE;
  5007. m_pOwner->SetWorkingDir(&dir);
  5008. }
  5009. }
  5010. }
  5011. }
  5012. //Continue operation even if MKD failed, maybe another thread did create this directory for us
  5013. if (pData->Segments.empty())
  5014. ResetOperation(FZ_REPLY_OK);
  5015. else
  5016. {
  5017. if (Send( L"CWD " + pData->Current.GetPathUnterminated()))
  5018. m_Operation.nOpState=MKD_MAKESUBDIRS;
  5019. else
  5020. return;
  5021. }
  5022. }
  5023. else
  5024. DebugFail();
  5025. }
  5026. void CFtpControlSocket::Rename(CString oldName, CString newName, const CServerPath &path, const CServerPath &newPath)
  5027. {
  5028. class CRenameData : public CFtpControlSocket::t_operation::COpData
  5029. {
  5030. public:
  5031. CRenameData() {}
  5032. virtual ~CRenameData() {}
  5033. CString oldName, newName;
  5034. CServerPath path;
  5035. CServerPath newPath;
  5036. };
  5037. if (oldName != L"")
  5038. {
  5039. DebugAssert(newName != L"");
  5040. DebugAssert(!path.IsEmpty());
  5041. DebugAssert(m_Operation.nOpMode == CSMODE_NONE);
  5042. DebugAssert(m_Operation.nOpState == -1);
  5043. DebugAssert(!m_Operation.pData);
  5044. m_Operation.nOpMode = CSMODE_RENAME;
  5045. if (!Send(L"RNFR " + path.FormatFilename(oldName)))
  5046. return;
  5047. CRenameData *data = new CRenameData;
  5048. data->oldName = oldName;
  5049. data->newName = newName;
  5050. data->path = path;
  5051. data->newPath = newPath;
  5052. m_Operation.pData = data;
  5053. }
  5054. else
  5055. {
  5056. DebugAssert(oldName == L"");
  5057. DebugAssert(path.IsEmpty());
  5058. DebugAssert(m_Operation.nOpMode == CSMODE_RENAME);
  5059. DebugAssert(m_Operation.pData);
  5060. CRenameData *pData = reinterpret_cast<CRenameData *>(m_Operation.pData);
  5061. if (m_Operation.nOpState == -1)
  5062. {
  5063. int res = GetReplyCode();
  5064. if (res == 2 || res == 3)
  5065. {
  5066. m_Operation.nOpState++;
  5067. if (pData->newPath.IsEmpty())
  5068. {
  5069. if (!Send(L"RNTO " + pData->path.FormatFilename(((CRenameData *)m_Operation.pData)->newName)))
  5070. return;
  5071. }
  5072. else
  5073. if (!Send(L"RNTO " + pData->newPath.FormatFilename(((CRenameData *)m_Operation.pData)->newName)))
  5074. return;
  5075. }
  5076. else
  5077. ResetOperation(FZ_REPLY_ERROR);
  5078. }
  5079. else
  5080. {
  5081. int res = GetReplyCode();
  5082. if (res == 2 || res == 3)
  5083. { //Rename entry in cached directory
  5084. CRenameData *pData = reinterpret_cast<CRenameData *>(m_Operation.pData);
  5085. t_directory dir;
  5086. BOOL res = FALSE;
  5087. if (m_pDirectoryListing)
  5088. {
  5089. if (m_pDirectoryListing->path == pData->path)
  5090. {
  5091. dir = *m_pDirectoryListing;
  5092. res = TRUE;
  5093. }
  5094. }
  5095. t_directory WorkingDir;
  5096. BOOL bFound = m_pOwner->GetWorkingDir(&WorkingDir);
  5097. if (!res && bFound)
  5098. if (WorkingDir.path == pData->path)
  5099. {
  5100. dir = WorkingDir;
  5101. res = TRUE;
  5102. }
  5103. if (res)
  5104. {
  5105. for (int i=0; i<dir.num; i++)
  5106. if (dir.direntry[i].name == pData->oldName)
  5107. {
  5108. if (pData->newPath.IsEmpty())
  5109. {
  5110. dir.direntry[i].name = pData->newName;
  5111. BOOL updated = FALSE;
  5112. if (m_pDirectoryListing && m_pDirectoryListing->path == dir.path)
  5113. {
  5114. updated = TRUE;
  5115. SetDirectoryListing(&dir, WorkingDir.path == dir.path);
  5116. }
  5117. if (!updated)
  5118. if (WorkingDir.path == dir.path)
  5119. {
  5120. updated = TRUE;
  5121. m_pOwner->SetWorkingDir(&dir);
  5122. }
  5123. }
  5124. else
  5125. {
  5126. t_directory::t_direntry oldentry = dir.direntry[i];
  5127. for (int j = i+1; j < dir.num; j++)
  5128. {
  5129. dir.direntry[j-1] = dir.direntry[j];
  5130. }
  5131. dir.num--;
  5132. BOOL updated = FALSE;
  5133. if (m_pDirectoryListing && m_pDirectoryListing->path == dir.path)
  5134. {
  5135. updated = TRUE;
  5136. SetDirectoryListing(&dir, WorkingDir.path == dir.path);
  5137. }
  5138. if (!updated)
  5139. if (WorkingDir.path == dir.path)
  5140. {
  5141. updated = TRUE;
  5142. m_pOwner->SetWorkingDir(&dir);
  5143. }
  5144. BOOL res = FALSE;
  5145. if (m_pDirectoryListing)
  5146. {
  5147. if (m_pDirectoryListing->path == pData->newPath)
  5148. {
  5149. dir = *m_pDirectoryListing;
  5150. res = TRUE;
  5151. }
  5152. }
  5153. t_directory WorkingDir;
  5154. BOOL bFound = m_pOwner->GetWorkingDir(&WorkingDir);
  5155. if (!res && bFound)
  5156. if (WorkingDir.path == pData->newPath)
  5157. {
  5158. dir = WorkingDir;
  5159. res = TRUE;
  5160. }
  5161. if (res)
  5162. {
  5163. t_directory::t_direntry *direntry = new t_directory::t_direntry[dir.num + 1];
  5164. for (int i = 0; i < dir.num; i++)
  5165. direntry[i] = dir.direntry[i];
  5166. direntry[dir.num] = oldentry;
  5167. direntry[dir.num].name = pData->newName;
  5168. dir.num++;
  5169. delete [] dir.direntry;
  5170. dir.direntry = direntry;
  5171. BOOL updated = FALSE;
  5172. if (m_pDirectoryListing && m_pDirectoryListing->path == dir.path)
  5173. {
  5174. updated = TRUE;
  5175. SetDirectoryListing(&dir, bFound && WorkingDir.path == dir.path);
  5176. }
  5177. if (!updated)
  5178. if (bFound && WorkingDir.path == dir.path)
  5179. {
  5180. updated = TRUE;
  5181. m_pOwner->SetWorkingDir(&dir);
  5182. }
  5183. }
  5184. }
  5185. break;
  5186. }
  5187. }
  5188. ResetOperation(FZ_REPLY_OK);
  5189. }
  5190. else
  5191. ResetOperation(FZ_REPLY_ERROR);
  5192. }
  5193. }
  5194. }
  5195. void CFtpControlSocket::SetVerifyCertResult(int nResult, t_SslCertData *pData)
  5196. {
  5197. DebugAssert(pData);
  5198. if (!m_pSslLayer)
  5199. return;
  5200. if (!m_Operation.nOpMode == CSMODE_CONNECT)
  5201. return;
  5202. m_bCheckForTimeout = TRUE;
  5203. m_pSslLayer->SetNotifyReply(pData->priv_data, SSL_VERIFY_CERT, nResult);
  5204. m_LastRecvTime = CTime::GetCurrentTime();
  5205. }
  5206. void CFtpControlSocket::OnTimer()
  5207. {
  5208. CheckForTimeout();
  5209. ResumeTransfer();
  5210. if (GetOptionVal(OPTION_KEEPALIVE))
  5211. {
  5212. if (!m_pOwner->IsBusy() && m_pOwner->IsConnected() && !m_bKeepAliveActive)
  5213. {
  5214. //Getting intervals for the Keep Alive feature
  5215. int low=GetOptionVal(OPTION_INTERVALLOW);
  5216. int diff=GetOptionVal(OPTION_INTERVALHIGH)-low;
  5217. //Choose a new delay
  5218. int delay=low+(rand()*diff)/RAND_MAX;
  5219. CTimeSpan span=CTime::GetCurrentTime()-m_LastSendTime;
  5220. if (span.GetTotalSeconds()>=delay)
  5221. SendKeepAliveCommand();
  5222. }
  5223. }
  5224. }
  5225. BOOL CFtpControlSocket::IsReady()
  5226. {
  5227. return !m_bKeepAliveActive;
  5228. }
  5229. void CFtpControlSocket::Chmod(CString filename, const CServerPath &path, int nValue)
  5230. {
  5231. m_Operation.nOpMode=CSMODE_CHMOD;
  5232. CString str;
  5233. str.Format( L"SITE CHMOD %03d %s", nValue, path.FormatFilename(filename));
  5234. Send(str);
  5235. }
  5236. void CFtpControlSocket::SetAsyncRequestResult(int nAction, CAsyncRequestData *pData)
  5237. {
  5238. switch (pData->nRequestType)
  5239. {
  5240. case FZ_ASYNCREQUEST_OVERWRITE:
  5241. SetFileExistsAction(nAction, (COverwriteRequestData *)pData);
  5242. break;
  5243. case FZ_ASYNCREQUEST_VERIFYCERT:
  5244. SetVerifyCertResult(nAction, ((CVerifyCertRequestData *)pData)->pCertData );
  5245. break;
  5246. case FZ_ASYNCREQUEST_NEEDPASS:
  5247. if (m_Operation.nOpMode!=CSMODE_CONNECT ||
  5248. m_Operation.nOpState != CONNECT_NEEDPASS)
  5249. break;
  5250. if (!m_RecvBuffer.empty() && m_RecvBuffer.front() != "")
  5251. {
  5252. DoClose();
  5253. break;
  5254. }
  5255. if (!nAction)
  5256. {
  5257. DoClose(FZ_REPLY_CRITICALERROR|FZ_REPLY_CANCEL);
  5258. ShowStatus(IDS_ERRORMSG_INTERRUPTED,FZ_LOG_ERROR);
  5259. break;
  5260. }
  5261. else
  5262. {
  5263. m_bCheckForTimeout = TRUE;
  5264. m_CurrentServer.pass=((CNeedPassRequestData *)pData)->Password;
  5265. m_Operation.nOpState=((CNeedPassRequestData *)pData)->nOldOpState;
  5266. CLogonData *pLogonData = static_cast<CLogonData *>(m_Operation.pData);
  5267. pLogonData->waitForAsyncRequest = false;
  5268. pLogonData->gotPassword = true;
  5269. LogOnToServer(TRUE);
  5270. }
  5271. break;
  5272. #ifndef MPEXT_NO_GSS
  5273. case FZ_ASYNCREQUEST_GSS_AUTHFAILED:
  5274. if (m_Operation.nOpMode!=CSMODE_CONNECT || m_Operation.nOpState!=CONNECT_GSS_FAILED)
  5275. break;
  5276. if (!m_RecvBuffer.empty() && m_RecvBuffer.front() != "")
  5277. {
  5278. DoClose();
  5279. break;
  5280. }
  5281. if (!nAction)
  5282. {
  5283. DoClose(FZ_REPLY_CRITICALERROR|FZ_REPLY_CANCEL);
  5284. ShowStatus(IDS_ERRORMSG_INTERRUPTED,FZ_LOG_ERROR);
  5285. break;
  5286. }
  5287. m_bCheckForTimeout = TRUE;
  5288. m_Operation.nOpState=-1;
  5289. LogOnToServer(TRUE);
  5290. break;
  5291. case FZ_ASYNCREQUEST_GSS_NEEDPASS:
  5292. if (m_Operation.nOpMode!=CSMODE_CONNECT ||
  5293. m_Operation.nOpState != CONNECT_GSS_NEEDPASS)
  5294. break;
  5295. if (!m_RecvBuffer.empty() && m_RecvBuffer.front() != "")
  5296. {
  5297. DoClose();
  5298. break;
  5299. }
  5300. if (!nAction)
  5301. {
  5302. DoClose(FZ_REPLY_CRITICALERROR|FZ_REPLY_CANCEL);
  5303. ShowStatus(IDS_ERRORMSG_INTERRUPTED,FZ_LOG_ERROR);
  5304. break;
  5305. }
  5306. else
  5307. {
  5308. m_bCheckForTimeout = TRUE;
  5309. m_CurrentServer.pass=((CGssNeedPassRequestData *)pData)->pass;
  5310. m_Operation.nOpState=((CGssNeedPassRequestData *)pData)->nOldOpState;
  5311. LogOnToServer(TRUE);
  5312. }
  5313. break;
  5314. case FZ_ASYNCREQUEST_GSS_NEEDUSER:
  5315. if (m_Operation.nOpMode != CSMODE_CONNECT ||
  5316. m_Operation.nOpState != CONNECT_GSS_NEEDUSER)
  5317. break;
  5318. if (!m_RecvBuffer.empty() && m_RecvBuffer.front() != "")
  5319. {
  5320. DoClose();
  5321. break;
  5322. }
  5323. if (!nAction)
  5324. {
  5325. DoClose(FZ_REPLY_CRITICALERROR | FZ_REPLY_CANCEL);
  5326. ShowStatus(IDS_ERRORMSG_INTERRUPTED, FZ_LOG_ERROR);
  5327. break;
  5328. }
  5329. else
  5330. {
  5331. m_bCheckForTimeout = TRUE;
  5332. m_CurrentServer.user = ((CGssNeedUserRequestData *)pData)->user;
  5333. m_Operation.nOpState=((CGssNeedUserRequestData *)pData)->nOldOpState;
  5334. LogOnToServer(TRUE);
  5335. }
  5336. break;
  5337. #endif
  5338. default:
  5339. LogMessage(FZ_LOG_WARNING, L"Unknown request reply %d", pData->nRequestType);
  5340. break;
  5341. }
  5342. }
  5343. int CFtpControlSocket::OnLayerCallback(std::list<t_callbackMsg>& callbacks)
  5344. {
  5345. for (std::list<t_callbackMsg>::iterator iter = callbacks.begin(); iter != callbacks.end(); iter++)
  5346. {
  5347. if (iter->nType == LAYERCALLBACK_STATECHANGE)
  5348. {
  5349. if (CAsyncSocketEx::LogStateChange(iter->nParam1, iter->nParam2))
  5350. {
  5351. const TCHAR * state2Desc = CAsyncSocketEx::GetStateDesc(iter->nParam2);
  5352. const TCHAR * state1Desc = CAsyncSocketEx::GetStateDesc(iter->nParam1);
  5353. if (iter->pLayer == m_pProxyLayer)
  5354. LogMessage(FZ_LOG_INFO, L"Proxy layer changed state from %s to %s", state2Desc, state1Desc);
  5355. #ifndef MPEXT_NO_GSS
  5356. else if (iter->pLayer == m_pGssLayer)
  5357. LogMessage(FZ_LOG_INFO, L"m_pGssLayer changed state from %s to %s", state2Desc, state1Desc);
  5358. #endif
  5359. else if (iter->pLayer == m_pSslLayer)
  5360. {
  5361. delete [] iter->str;
  5362. LogMessage(FZ_LOG_INFO, L"TLS layer changed state from %s to %s", state2Desc, state1Desc);
  5363. }
  5364. else
  5365. LogMessage(FZ_LOG_INFO, L"Layer @ %d changed state from %s to %s", iter->pLayer, state2Desc, state1Desc);
  5366. }
  5367. }
  5368. else if (iter->nType == LAYERCALLBACK_LAYERSPECIFIC)
  5369. {
  5370. USES_CONVERSION;
  5371. if (iter->pLayer == m_pProxyLayer)
  5372. {
  5373. switch (iter->nParam1)
  5374. {
  5375. case PROXYERROR_NOERROR:
  5376. ShowStatus(IDS_PROXY_CONNECTED, FZ_LOG_STATUS);
  5377. break;
  5378. case PROXYERROR_NOCONN:
  5379. ShowStatus(IDS_ERRORMSG_PROXY_NOCONN, FZ_LOG_ERROR);
  5380. break;
  5381. case PROXYERROR_REQUESTFAILED:
  5382. ShowStatus(IDS_ERRORMSG_PROXY_REQUESTFAILED, FZ_LOG_ERROR);
  5383. if (iter->str)
  5384. ShowStatus(A2T(iter->str), FZ_LOG_ERROR);
  5385. break;
  5386. case PROXYERROR_AUTHTYPEUNKNOWN:
  5387. ShowStatus(IDS_ERRORMSG_PROXY_AUTHTYPEUNKNOWN, FZ_LOG_ERROR);
  5388. break;
  5389. case PROXYERROR_AUTHFAILED:
  5390. ShowStatus(IDS_ERRORMSG_PROXY_AUTHFAILED, FZ_LOG_ERROR);
  5391. break;
  5392. case PROXYERROR_AUTHNOLOGON:
  5393. ShowStatus(IDS_ERRORMSG_PROXY_AUTHNOLOGON, FZ_LOG_ERROR);
  5394. break;
  5395. case PROXYERROR_CANTRESOLVEHOST:
  5396. ShowStatus(IDS_ERRORMSG_PROXY_CANTRESOLVEHOST, FZ_LOG_ERROR);
  5397. break;
  5398. default:
  5399. LogMessage(FZ_LOG_WARNING, L"Unknown proxy error" );
  5400. }
  5401. }
  5402. #ifndef MPEXT_NO_GSS
  5403. else if (iter->pLayer == m_pGssLayer)
  5404. {
  5405. switch (iter->nParam1)
  5406. {
  5407. case GSS_INFO:
  5408. LogMessageRaw(FZ_LOG_INFO, A2CT(iter->str));
  5409. break;
  5410. case GSS_ERROR:
  5411. LogMessageRaw(FZ_LOG_APIERROR, A2CT(iter->str));
  5412. break;
  5413. case GSS_COMMAND:
  5414. ShowStatus(A2CT(iter->str), FZ_LOG_COMMAND);
  5415. break;
  5416. case GSS_REPLY:
  5417. ShowStatus(A2CT(iter->str), FZ_LOG_REPLY);
  5418. break;
  5419. }
  5420. }
  5421. #endif
  5422. else if (iter->pLayer == m_pSslLayer)
  5423. {
  5424. USES_CONVERSION;
  5425. switch (iter->nParam1)
  5426. {
  5427. case SSL_INFO:
  5428. switch (iter->nParam2)
  5429. {
  5430. case SSL_INFO_ESTABLISHED:
  5431. ShowStatus(IDS_STATUSMSG_SSLESTABLISHED, FZ_LOG_STATUS);
  5432. if (m_Operation.nOpState == CONNECT_SSL_WAITDONE)
  5433. {
  5434. LogOnToServer();
  5435. }
  5436. break;
  5437. }
  5438. break;
  5439. case SSL_FAILURE:
  5440. switch (iter->nParam2)
  5441. {
  5442. case SSL_FAILURE_UNKNOWN:
  5443. ShowStatus(IDS_ERRORMSG_UNKNOWNSSLERROR, FZ_LOG_ERROR);
  5444. break;
  5445. case SSL_FAILURE_ESTABLISH:
  5446. ShowStatus(IDS_ERRORMSG_CANTESTABLISHSSLCONNECTION, FZ_LOG_ERROR);
  5447. break;
  5448. case SSL_FAILURE_INITSSL:
  5449. ShowStatus(IDS_ERRORMSG_CANTINITSSL, FZ_LOG_ERROR);
  5450. break;
  5451. case SSL_FAILURE_VERIFYCERT:
  5452. ShowStatus(IDS_ERRORMSG_SSLCERTIFICATEERROR, FZ_LOG_ERROR);
  5453. break;
  5454. case SSL_FAILURE_CERTREJECTED:
  5455. ShowStatus(IDS_ERRORMSG_CERTREJECTED, FZ_LOG_ERROR);
  5456. m_bDidRejectCertificate = TRUE;
  5457. break;
  5458. }
  5459. TriggerEvent(FD_CLOSE);
  5460. break;
  5461. case SSL_VERIFY_CERT:
  5462. t_SslCertData *pData = new t_SslCertData;
  5463. LPTSTR CertError = NULL;
  5464. if (m_pSslLayer->GetPeerCertificateData(*pData, CertError))
  5465. {
  5466. CVerifyCertRequestData *pRequestData = new CVerifyCertRequestData;
  5467. pRequestData->nRequestID=m_pOwner->GetNextAsyncRequestID();
  5468. pRequestData->pCertData = pData;
  5469. if (!GetIntern()->PostMessage(FZ_MSG_MAKEMSG(FZ_MSG_ASYNCREQUEST, FZ_ASYNCREQUEST_VERIFYCERT), (LPARAM)pRequestData))
  5470. {
  5471. delete pRequestData->pCertData;
  5472. delete pRequestData;
  5473. ResetOperation(FZ_REPLY_ERROR);
  5474. }
  5475. else
  5476. {
  5477. m_bCheckForTimeout = FALSE;
  5478. }
  5479. delete [] iter->str;
  5480. continue;
  5481. }
  5482. else
  5483. {
  5484. delete pData;
  5485. delete [] iter->str;
  5486. CString str;
  5487. str.Format(TLS_CERT_DECODE_ERROR, CertError);
  5488. ShowStatus(str, FZ_LOG_ERROR);
  5489. ResetOperation(FZ_REPLY_ERROR);
  5490. continue;
  5491. }
  5492. break;
  5493. }
  5494. delete [] iter->str;
  5495. continue;
  5496. }
  5497. #ifndef MPEXT_NO_GSS
  5498. else
  5499. if (iter->pLayer == m_pGssLayer)
  5500. {
  5501. if (iter->nParam1 == GSS_AUTHCOMPLETE ||
  5502. iter->nParam1 == GSS_AUTHFAILED)
  5503. {
  5504. LogOnToServer(TRUE);
  5505. delete [] iter->str;
  5506. continue;
  5507. }
  5508. }
  5509. #endif
  5510. }
  5511. delete [] iter->str;
  5512. }
  5513. return 0;
  5514. }
  5515. _int64 CFtpControlSocket::GetSpeedLimit(CTime &time, int valType, int valValue)
  5516. {
  5517. int type = GetOptionVal(valType);
  5518. if ( type == 1)
  5519. return ( _int64)GetOptionVal(valValue) * 1024;
  5520. return ( _int64)1000000000000; // I hope that when there will be something with 1000GB/s then I'll change it :)
  5521. }
  5522. _int64 CFtpControlSocket::GetSpeedLimit(enum transferDirection direction, CTime &time)
  5523. {
  5524. if (direction == download)
  5525. return GetSpeedLimit(time, OPTION_SPEEDLIMIT_DOWNLOAD_TYPE, OPTION_SPEEDLIMIT_DOWNLOAD_VALUE);
  5526. else
  5527. return GetSpeedLimit(time, OPTION_SPEEDLIMIT_UPLOAD_TYPE, OPTION_SPEEDLIMIT_UPLOAD_VALUE);
  5528. return ( _int64)1000000000000;
  5529. }
  5530. _int64 CFtpControlSocket::GetAbleToUDSize( bool &beenWaiting, CTime &curTime, _int64 &curLimit, std::list<CFtpControlSocket::t_ActiveList>::iterator &iter, enum transferDirection direction, int nBufSize)
  5531. {
  5532. beenWaiting = false;
  5533. CTime nowTime = CTime::GetCurrentTime();
  5534. _int64 ableToRead = BUFSIZE;
  5535. if ( nowTime == curTime)
  5536. {
  5537. ableToRead = iter->nBytesAvailable;
  5538. if (ableToRead <= 0)
  5539. {
  5540. // we should wait till next second
  5541. nowTime = CTime::GetCurrentTime();
  5542. while (nowTime == curTime && !iter->nBytesAvailable)
  5543. {
  5544. if (beenWaiting)
  5545. {
  5546. //Check if there are other commands in the command queue.
  5547. MSG msg;
  5548. if (PeekMessage(&msg, 0, m_pOwner->m_nInternalMessageID, m_pOwner->m_nInternalMessageID, PM_NOREMOVE))
  5549. {
  5550. LogMessage(FZ_LOG_INFO, L"Message waiting in queue, resuming later");
  5551. return 0;
  5552. }
  5553. }
  5554. m_SpeedLimitSync.Unlock();
  5555. Sleep(100);
  5556. m_SpeedLimitSync.Lock();
  5557. nowTime = CTime::GetCurrentTime();
  5558. beenWaiting = true;
  5559. // Since we didn't hold the critical section for some time, we have to renew the iterator
  5560. for (iter = m_InstanceList[direction].begin(); iter != m_InstanceList[direction].end(); iter++)
  5561. if (iter->pOwner == this)
  5562. break;
  5563. if (iter == m_InstanceList[direction].end())
  5564. return 0;
  5565. }
  5566. }
  5567. ableToRead = iter->nBytesAvailable;
  5568. }
  5569. if (nowTime != curTime)
  5570. {
  5571. if (ableToRead > 0)
  5572. ableToRead = 0;
  5573. curLimit = GetSpeedLimit(direction, curTime);
  5574. __int64 nMax = curLimit / m_InstanceList[direction].size();
  5575. _int64 nLeft = 0;
  5576. int nCount = 0;
  5577. std::list<t_ActiveList>::iterator iter2;
  5578. for (iter2 = m_InstanceList[direction].begin(); iter2 != m_InstanceList[direction].end(); iter2++)
  5579. {
  5580. if (iter2->nBytesAvailable>0)
  5581. {
  5582. nLeft += iter2->nBytesAvailable;
  5583. iter2->nBytesTransferred = 1;
  5584. }
  5585. else
  5586. {
  5587. nCount++;
  5588. iter2->nBytesTransferred = 0;
  5589. }
  5590. iter2->nBytesAvailable = nMax;
  5591. }
  5592. if (nLeft && nCount)
  5593. {
  5594. nMax = nLeft / nCount;
  5595. for (iter2 = m_InstanceList[direction].begin(); iter2 != m_InstanceList[direction].end(); iter2++)
  5596. {
  5597. if (!iter2->nBytesTransferred)
  5598. iter2->nBytesAvailable += nMax;
  5599. else
  5600. iter2->nBytesTransferred = 0;
  5601. }
  5602. }
  5603. ableToRead = iter->nBytesAvailable;
  5604. }
  5605. curTime = nowTime;
  5606. if (!nBufSize)
  5607. nBufSize = BUFSIZE;
  5608. if (ableToRead > nBufSize)
  5609. ableToRead = nBufSize;
  5610. return ableToRead;
  5611. }
  5612. _int64 CFtpControlSocket::GetAbleToTransferSize(enum transferDirection direction, bool &beenWaiting, int nBufSize)
  5613. {
  5614. m_SpeedLimitSync.Lock();
  5615. std::list<t_ActiveList>::iterator iter;
  5616. for (iter = m_InstanceList[direction].begin(); iter != m_InstanceList[direction].end(); iter++)
  5617. if (iter->pOwner == this)
  5618. break;
  5619. if (iter == m_InstanceList[direction].end())
  5620. {
  5621. t_ActiveList item;
  5622. CTime time = CTime::GetCurrentTime();
  5623. item.nBytesAvailable = GetSpeedLimit(direction, time) / (m_InstanceList[direction].size() + 1);
  5624. item.nBytesTransferred = 0;
  5625. item.pOwner = this;
  5626. m_InstanceList[direction].push_back(item);
  5627. iter = m_InstanceList[direction].end();
  5628. iter--;
  5629. }
  5630. _int64 limit = GetAbleToUDSize(beenWaiting, m_CurrentTransferTime[direction], m_CurrentTransferLimit[direction], iter, direction, nBufSize);
  5631. m_SpeedLimitSync.Unlock();
  5632. return limit;
  5633. }
  5634. BOOL CFtpControlSocket::RemoveActiveTransfer()
  5635. {
  5636. BOOL bFound = FALSE;
  5637. m_SpeedLimitSync.Lock();
  5638. std::list<t_ActiveList>::iterator iter;
  5639. for (int i = 0; i < 2; i++)
  5640. {
  5641. for (iter = m_InstanceList[i].begin(); iter != m_InstanceList[i].end(); iter++)
  5642. if (iter->pOwner == this)
  5643. {
  5644. m_InstanceList[i].erase(iter);
  5645. bFound = TRUE;
  5646. break;
  5647. }
  5648. }
  5649. m_SpeedLimitSync.Unlock();
  5650. return bFound;
  5651. }
  5652. BOOL CFtpControlSocket::SpeedLimitAddTransferredBytes(enum transferDirection direction, _int64 nBytesTransferred)
  5653. {
  5654. m_SpeedLimitSync.Lock();
  5655. std::list<t_ActiveList>::iterator iter;
  5656. for (iter = m_InstanceList[direction].begin(); iter != m_InstanceList[direction].end(); iter++)
  5657. if (iter->pOwner == this)
  5658. {
  5659. if (iter->nBytesAvailable > nBytesTransferred)
  5660. iter->nBytesAvailable -= nBytesTransferred;
  5661. else
  5662. iter->nBytesAvailable = 0;
  5663. iter->nBytesTransferred += nBytesTransferred;
  5664. m_SpeedLimitSync.Unlock();
  5665. return TRUE;
  5666. }
  5667. m_SpeedLimitSync.Unlock();
  5668. return FALSE;
  5669. }
  5670. CString CFtpControlSocket::ConvertDomainName(CString domain)
  5671. {
  5672. USES_CONVERSION;
  5673. LPCWSTR buffer = T2CW(domain);
  5674. char *utf8 = new char[wcslen(buffer) * 2 + 2];
  5675. if (!WideCharToMultiByte(CP_UTF8, 0, buffer, -1, utf8, wcslen(buffer) * 2 + 2, 0, 0))
  5676. {
  5677. delete [] utf8;
  5678. LogMessage(FZ_LOG_WARNING, L"Could not convert domain name");
  5679. return domain;
  5680. }
  5681. char *output = 0;
  5682. output = strdup(utf8);
  5683. delete [] utf8;
  5684. CString result = A2T(output);
  5685. free(output);
  5686. return result;
  5687. }
  5688. void CFtpControlSocket::LogSocketMessageRaw(int nMessageType, LPCTSTR pMsg)
  5689. {
  5690. LogMessageRaw(nMessageType, pMsg);
  5691. }
  5692. bool CFtpControlSocket::LoggingSocketMessage(int nMessageType)
  5693. {
  5694. return LoggingMessageType(nMessageType);
  5695. }
  5696. BOOL CFtpControlSocket::ParsePwdReply(CString& rawpwd)
  5697. {
  5698. CServerPath realPath;
  5699. BOOL Result = ParsePwdReply(rawpwd, realPath);
  5700. if (Result)
  5701. {
  5702. m_pOwner->SetCurrentPath(realPath);
  5703. }
  5704. return Result;
  5705. }
  5706. BOOL CFtpControlSocket::ParsePwdReply(CString& rawpwd, CServerPath & realPath)
  5707. {
  5708. CListData *pData = static_cast<CListData *>(m_Operation.pData);
  5709. DebugAssert(pData);
  5710. int pos1 = rawpwd.Find(L'"');
  5711. int pos2 = rawpwd.ReverseFind(L'"');
  5712. if (pos1 == -1 || pos2 == -1 || pos1 >= pos2)
  5713. {
  5714. LogMessage(FZ_LOG_WARNING, L"No quoted path found, try using first token as path");
  5715. pos1 = rawpwd.Find(L' ');
  5716. if (pos1 != -1)
  5717. {
  5718. pos2 = rawpwd.Find(L' ', pos1 + 1);
  5719. if (pos2 == -1)
  5720. pos2 = rawpwd.GetLength();
  5721. }
  5722. if (pos1 == -1)
  5723. {
  5724. LogMessage(FZ_LOG_WARNING, L"Can't parse path!");
  5725. ResetOperation(FZ_REPLY_ERROR);
  5726. return FALSE;
  5727. }
  5728. }
  5729. rawpwd = rawpwd.Mid(pos1 + 1, pos2 - pos1 - 1);
  5730. realPath = m_pOwner->GetCurrentPath();
  5731. realPath.SetServer(m_CurrentServer);
  5732. if (!realPath.SetPath(rawpwd))
  5733. {
  5734. LogMessage(FZ_LOG_WARNING, L"Can't parse path!");
  5735. ResetOperation(FZ_REPLY_ERROR);
  5736. return FALSE;
  5737. }
  5738. return TRUE;
  5739. }
  5740. void CFtpControlSocket::DiscardLine(CStringA line)
  5741. {
  5742. if (m_Operation.nOpMode == CSMODE_CONNECT && m_Operation.nOpState == CONNECT_FEAT)
  5743. {
  5744. line.MakeUpper();
  5745. while (line.Left(1) == " ")
  5746. {
  5747. line = line.Mid(1, line.GetLength() - 1);
  5748. }
  5749. #ifndef MPEXT_NO_ZLIB
  5750. if (line == "MODE Z" || line.Left(7) == "MODE Z ")
  5751. m_zlibSupported = true;
  5752. else
  5753. #endif
  5754. if (line == "UTF8" && m_CurrentServer.nUTF8 != 2)
  5755. m_bAnnouncesUTF8 = true;
  5756. else if (line == "CLNT" || line.Left(5) == "CLNT ")
  5757. m_hasClntCmd = true;
  5758. else if (line == "MLSD")
  5759. {
  5760. m_serverCapabilities.SetCapability(mlsd_command, yes);
  5761. }
  5762. else if (line == "MDTM")
  5763. {
  5764. m_serverCapabilities.SetCapability(mdtm_command, yes);
  5765. }
  5766. else if (line == "SIZE")
  5767. {
  5768. m_serverCapabilities.SetCapability(size_command, yes);
  5769. }
  5770. else if (line.Left(4) == "MLST")
  5771. {
  5772. USES_CONVERSION;
  5773. std::string facts;
  5774. if (line.GetLength() > 5)
  5775. {
  5776. facts = (LPCSTR)line.Mid(5, line.GetLength() - 5);
  5777. }
  5778. m_serverCapabilities.SetCapability(mlsd_command, yes, facts);
  5779. }
  5780. else if (line == "MFMT")
  5781. {
  5782. m_serverCapabilities.SetCapability(mfmt_command, yes);
  5783. }
  5784. }
  5785. else if (m_Operation.nOpMode == CSMODE_LISTFILE)
  5786. {
  5787. m_ListFile = line;
  5788. }
  5789. }
  5790. int CFtpControlSocket::FileTransferListState(bool get)
  5791. {
  5792. int Result;
  5793. if (GetOptionVal(OPTION_MPEXT_NOLIST) && !get)
  5794. {
  5795. Result = FILETRANSFER_TYPE;
  5796. }
  5797. else
  5798. {
  5799. Result = NeedModeCommand() ? FILETRANSFER_LIST_MODE : (NeedOptsCommand() ? FILETRANSFER_LIST_OPTS : FILETRANSFER_LIST_TYPE);
  5800. }
  5801. return Result;
  5802. }
  5803. bool CFtpControlSocket::NeedModeCommand()
  5804. {
  5805. #ifdef MPEXT_NO_ZLIB
  5806. return false;
  5807. #else
  5808. bool useZlib;
  5809. if (m_Operation.nOpMode == CSMODE_LIST || (m_Operation.nOpMode == CSMODE_TRANSFER && m_Operation.nOpMode <= FILETRANSFER_TYPE))
  5810. useZlib = GetOptionVal(OPTION_MODEZ_USE) != 0;
  5811. else
  5812. useZlib = GetOptionVal(OPTION_MODEZ_USE) > 1;
  5813. if (!m_useZlib && !m_zlibSupported)
  5814. return false;
  5815. return m_useZlib != useZlib;
  5816. #endif
  5817. }
  5818. bool CFtpControlSocket::NeedOptsCommand()
  5819. {
  5820. #ifndef MPEXT_NO_ZLIB
  5821. if (!m_useZlib)
  5822. #endif
  5823. return false;
  5824. #ifndef MPEXT_NO_ZLIB
  5825. return m_zlibLevel != GetOptionVal(OPTION_MODEZ_LEVEL);
  5826. #endif
  5827. }
  5828. CString CFtpControlSocket::GetReply()
  5829. {
  5830. if (m_RecvBuffer.empty())
  5831. return L"";
  5832. USES_CONVERSION;
  5833. LPCSTR line;
  5834. if ((m_Operation.nOpMode&CSMODE_LISTFILE) && (m_Operation.nOpState==LISTFILE_MLST) &&
  5835. (GetReplyCode() == 2))
  5836. {
  5837. // this is probably never used anyway
  5838. line = (LPCSTR)m_ListFile;
  5839. }
  5840. else
  5841. {
  5842. line = (LPCSTR)m_RecvBuffer.front();
  5843. }
  5844. if (m_bUTF8)
  5845. {
  5846. // convert from UTF-8 to ANSI
  5847. if (DetectUTF8Encoding(RawByteString(line)) == etANSI)
  5848. {
  5849. if (m_CurrentServer.nUTF8 != 1)
  5850. {
  5851. LogMessage(FZ_LOG_WARNING, L"Server does not send proper UTF-8, falling back to local charset");
  5852. m_bUTF8 = false;
  5853. }
  5854. return A2CT(line);
  5855. }
  5856. // convert from UTF-8 to ANSI
  5857. int len = MultiByteToWideChar(CP_UTF8, 0, line, -1, NULL, 0);
  5858. if (!len)
  5859. {
  5860. m_RecvBuffer.pop_front();
  5861. if (m_RecvBuffer.empty())
  5862. m_RecvBuffer.push_back("");
  5863. return L"";
  5864. }
  5865. else
  5866. {
  5867. LPWSTR p1 = new WCHAR[len + 1];
  5868. MultiByteToWideChar(CP_UTF8, 0, line, -1 , (LPWSTR)p1, len + 1);
  5869. CString reply = W2CT(p1);
  5870. delete [] p1;
  5871. return reply;
  5872. }
  5873. }
  5874. else
  5875. return A2CT(line);
  5876. }
  5877. void CFtpControlSocket::OnSend(int nErrorCode)
  5878. {
  5879. if (!m_sendBufferLen || !m_sendBuffer || m_awaitsReply)
  5880. return;
  5881. int res = CAsyncSocketEx::Send(m_sendBuffer, m_sendBufferLen);
  5882. if (res == -1)
  5883. {
  5884. int Error = GetLastError();
  5885. if (Error != WSAEWOULDBLOCK)
  5886. {
  5887. LogError(Error);
  5888. ShowStatus(IDS_ERRORMSG_CANTSENDCOMMAND, FZ_LOG_ERROR);
  5889. DoClose();
  5890. }
  5891. return;
  5892. }
  5893. if (!res)
  5894. {
  5895. ShowStatus(IDS_ERRORMSG_CANTSENDCOMMAND, FZ_LOG_ERROR);
  5896. DoClose();
  5897. }
  5898. m_awaitsReply = true;
  5899. m_LastSendTime = CTime::GetCurrentTime();
  5900. if (res == m_sendBufferLen)
  5901. {
  5902. delete [] m_sendBuffer;
  5903. m_sendBuffer = 0;
  5904. m_sendBufferLen = 0;
  5905. }
  5906. else
  5907. {
  5908. char* tmp = new char[m_sendBufferLen - res];
  5909. memcpy(tmp, m_sendBuffer + res, m_sendBufferLen - res);
  5910. delete [] m_sendBuffer;
  5911. m_sendBuffer = tmp;
  5912. m_sendBufferLen -= res;
  5913. }
  5914. }
  5915. bool CFtpControlSocket::IsMisleadingListResponse()
  5916. {
  5917. // Some servers are broken. Instead of an empty listing, some MVS servers
  5918. // for example they return something "550 no members found"
  5919. // Other servers return "550 No files found."
  5920. CString retmsg = GetReply();
  5921. if (!retmsg.CompareNoCase(L"550 No members found."))
  5922. return true;
  5923. if (!retmsg.CompareNoCase(L"550 No data sets found."))
  5924. return true;
  5925. if (!retmsg.CompareNoCase(L"550 No files found."))
  5926. return true;
  5927. return false;
  5928. }
  5929. bool CFtpControlSocket::IsRoutableAddress(const CString & host)
  5930. {
  5931. USES_CONVERSION;
  5932. if (host.Left(3) == L"127" ||
  5933. host.Left(3) == L"10." ||
  5934. host.Left(7) == L"192.168" ||
  5935. host.Left(7) == L"169.254")
  5936. {
  5937. return false;
  5938. }
  5939. else if (host.Left(3) == L"172")
  5940. {
  5941. CString middle = host.Mid(4);
  5942. int pos = middle.Find(L".");
  5943. long part = atol(T2CA(middle.Left(pos)));
  5944. if ((part >= 16) && (part <= 31))
  5945. {
  5946. return false;
  5947. }
  5948. }
  5949. return true;
  5950. }
  5951. bool CFtpControlSocket::CheckForcePasvIp(CString & host)
  5952. {
  5953. bool result = true;
  5954. unsigned int tmpPort;
  5955. CString ahost;
  5956. switch (m_CurrentServer.iForcePasvIp)
  5957. {
  5958. case 0: // on
  5959. if (!GetPeerName(ahost, tmpPort))
  5960. {
  5961. // this should happen with proxy server only
  5962. int logontype = GetOptionVal(OPTION_LOGONTYPE);
  5963. // do not know what to do, if there's FTP proxy
  5964. if (!logontype)
  5965. {
  5966. // this is a host name, not an IP, but it should not be a problem
  5967. ahost = m_CurrentServer.host;
  5968. }
  5969. }
  5970. if (ahost != host)
  5971. {
  5972. LogMessage(FZ_LOG_WARNING, L"Using host address %s instead of the one suggested by the server: %s", ahost, host);
  5973. host = ahost;
  5974. }
  5975. break;
  5976. case 1: // off
  5977. // noop
  5978. break;
  5979. default: // auto
  5980. if (!GetPeerName(ahost, tmpPort))
  5981. {
  5982. LogMessage(FZ_LOG_PROGRESS, L"Error retrieving server address, cannot test if address is routable");
  5983. }
  5984. else if (!IsRoutableAddress(host) && IsRoutableAddress(ahost))
  5985. {
  5986. LogMessage(FZ_LOG_WARNING, L"Server sent passive reply with unroutable address %s, using host address instead.", host, ahost);
  5987. host = ahost;
  5988. }
  5989. break;
  5990. }
  5991. return result;
  5992. }
  5993. //---------------------------------------------------------------------------
  5994. ftp_capabilities_t TFTPServerCapabilities::GetCapability(ftp_capability_names_t Name)
  5995. {
  5996. t_cap tcap = FCapabilityMap[Name];
  5997. return tcap.cap;
  5998. }
  5999. ftp_capabilities_t TFTPServerCapabilities::GetCapabilityString(ftp_capability_names_t Name, std::string * Option)
  6000. {
  6001. t_cap tcap = FCapabilityMap[Name];
  6002. if (Option)
  6003. *Option = tcap.option;
  6004. return tcap.cap;
  6005. }
  6006. void TFTPServerCapabilities::SetCapability(ftp_capability_names_t Name, ftp_capabilities_t Cap)
  6007. {
  6008. t_cap tcap = FCapabilityMap[Name];
  6009. tcap.cap = Cap;
  6010. tcap.number = 1;
  6011. FCapabilityMap[Name] = tcap;
  6012. }
  6013. void TFTPServerCapabilities::SetCapability(ftp_capability_names_t Name, ftp_capabilities_t Cap, const std::string & Option)
  6014. {
  6015. t_cap tcap = FCapabilityMap[Name];
  6016. tcap.cap = Cap;
  6017. tcap.option = Option;
  6018. tcap.number = 0;
  6019. FCapabilityMap[Name] = tcap;
  6020. }