FtpControlSocket.cpp 181 KB

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