FtpControlSocket.cpp 172 KB

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