FtpControlSocket.cpp 182 KB

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