1
0

FtpControlSocket.cpp 177 KB

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