FtpControlSocket.cpp 182 KB

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