FtpControlSocket.cpp 182 KB

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