FtpControlSocket.cpp 183 KB

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