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