FtpControlSocket.cpp 183 KB

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