FtpControlSocket.cpp 182 KB

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