FtpControlSocket.cpp 182 KB

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