FtpControlSocket.cpp 183 KB

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