FtpControlSocket.cpp 182 KB

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