FtpControlSocket.cpp 160 KB

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