FtpControlSocket.cpp 159 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874
  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);
  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);
  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, BOOL bUpdateRecvTime)
  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. if (bUpdateRecvTime)
  1138. {
  1139. // Count timeout since the last request, not only since the last received data
  1140. // otherwise we may happen to timeout immediatelly after sending request if
  1141. // CheckForTimeout occurs in between and we haven't received any data for a while
  1142. m_LastRecvTime = m_LastSendTime;
  1143. }
  1144. PostMessage(m_pOwner->m_hOwnerWnd, m_pOwner->m_nReplyMessageID, FZ_MSG_MAKEMSG(FZ_MSG_SOCKETSTATUS, FZ_SOCKETSTATUS_SEND), 0);
  1145. }
  1146. return TRUE;
  1147. }
  1148. int CFtpControlSocket::GetReplyCode()
  1149. {
  1150. if (m_RecvBuffer.empty())
  1151. return 0;
  1152. CStringA str = m_RecvBuffer.front();
  1153. if (str == "")
  1154. return 0;
  1155. else
  1156. return str[0]-'0';
  1157. }
  1158. void CFtpControlSocket::DoClose(int nError /*=0*/)
  1159. {
  1160. LogMessage(__FILE__, __LINE__, this,FZ_LOG_DEBUG, _T("DoClose(%d) OpMode=%d OpState=%d"), nError, m_Operation.nOpMode, m_Operation.nOpState);
  1161. m_bCheckForTimeout=TRUE;
  1162. m_pOwner->SetConnected(FALSE);
  1163. m_bKeepAliveActive=FALSE;
  1164. PostMessage(m_pOwner->m_hOwnerWnd, m_pOwner->m_nReplyMessageID, FZ_MSG_MAKEMSG(FZ_MSG_SECURESERVER, FALSE), 0);
  1165. if (nError & FZ_REPLY_CRITICALERROR)
  1166. nError |= FZ_REPLY_ERROR;
  1167. ResetOperation(FZ_REPLY_ERROR|FZ_REPLY_DISCONNECTED|nError);
  1168. m_RecvBuffer.clear();
  1169. m_MultiLine = "";
  1170. #ifndef MPEXT_NO_SSL
  1171. m_bDidRejectCertificate = FALSE;
  1172. #endif
  1173. #ifndef MPEXT_NO_ZLIB
  1174. m_useZlib = false;
  1175. m_zlibSupported = false;
  1176. m_zlibLevel = 0;
  1177. #endif
  1178. m_bUTF8 = false;
  1179. m_hasClntCmd = false;
  1180. #ifdef MPEXT
  1181. m_hasMfmtCmd = false;
  1182. #endif
  1183. m_awaitsReply = false;
  1184. m_skipReply = false;
  1185. delete [] m_sendBuffer;
  1186. m_sendBuffer = 0;
  1187. m_sendBufferLen = 0;
  1188. m_bProtP = false;
  1189. m_mayBeMvsFilesystem = false;
  1190. m_mayBeBS2000Filesystem = false;
  1191. CControlSocket::Close();
  1192. }
  1193. void CFtpControlSocket::Disconnect()
  1194. {
  1195. ASSERT(!m_Operation.nOpMode);
  1196. m_Operation.nOpMode=CSMODE_DISCONNECT;
  1197. DoClose();
  1198. ShowStatus(IDS_STATUSMSG_DISCONNECTED,0); //Send the disconnected message to the message log
  1199. }
  1200. void CFtpControlSocket::CheckForTimeout()
  1201. {
  1202. if (!m_Operation.nOpMode && !m_bKeepAliveActive)
  1203. return;
  1204. if (!m_bCheckForTimeout)
  1205. return;
  1206. int delay=COptions::GetOptionVal(OPTION_TIMEOUTLENGTH);
  1207. if (m_pTransferSocket)
  1208. {
  1209. int res=m_pTransferSocket->CheckForTimeout(delay);
  1210. if (res)
  1211. return;
  1212. }
  1213. CTimeSpan span=CTime::GetCurrentTime()-m_LastRecvTime;
  1214. if (span.GetTotalSeconds()>=delay)
  1215. {
  1216. ShowStatus(IDS_ERRORMSG_TIMEOUT, 1);
  1217. DoClose();
  1218. }
  1219. }
  1220. void CFtpControlSocket::FtpCommand(LPCTSTR pCommand)
  1221. {
  1222. LogMessage(__FILE__, __LINE__, this,FZ_LOG_DEBUG, _T("FtpCommand(%s) OpMode=%d OpState=%d"), pCommand, m_Operation.nOpMode, m_Operation.nOpState);
  1223. m_Operation.nOpMode=CSMODE_COMMAND;
  1224. Send(pCommand);
  1225. }
  1226. void CFtpControlSocket::List(BOOL bFinish, int nError /*=FALSE*/, CServerPath path /*=CServerPath()*/, CString subdir /*=""*/,int nListMode/*=0*/)
  1227. {
  1228. 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,
  1229. m_Operation.nOpMode, m_Operation.nOpState);
  1230. USES_CONVERSION;
  1231. #define LIST_INIT -1
  1232. #define LIST_PWD 0
  1233. #define LIST_CWD 1
  1234. #define LIST_PWD2 2
  1235. #define LIST_CWD2 3
  1236. #define LIST_PWD3 4
  1237. #define LIST_MODE 5
  1238. #define LIST_OPTS 6
  1239. #define LIST_PORT_PASV 7
  1240. #define LIST_TYPE 8
  1241. #define LIST_LIST 9
  1242. #define LIST_WAITFINISH 10
  1243. ASSERT(!m_Operation.nOpMode || m_Operation.nOpMode&CSMODE_LIST);
  1244. m_Operation.nOpMode|=CSMODE_LIST;
  1245. if (!m_pOwner->IsConnected())
  1246. {
  1247. ResetOperation(FZ_REPLY_ERROR|FZ_REPLY_NOTCONNECTED);
  1248. return;
  1249. }
  1250. if (bFinish || nError)
  1251. if (m_Operation.nOpMode!=CSMODE_LIST)
  1252. return; //Old message coming in
  1253. if (nError)
  1254. {
  1255. delete m_pTransferSocket;
  1256. m_pTransferSocket=0;
  1257. if (nError&CSMODE_TRANSFERTIMEOUT)
  1258. DoClose();
  1259. else
  1260. ResetOperation(FZ_REPLY_ERROR);
  1261. return;
  1262. }
  1263. CListData *pData = static_cast<CListData *>(m_Operation.pData);
  1264. if (bFinish)
  1265. {
  1266. if (!m_pTransferSocket || m_pTransferSocket->m_bListening)
  1267. {
  1268. delete m_pDirectoryListing;
  1269. m_pDirectoryListing = 0;
  1270. delete m_pTransferSocket;
  1271. m_pTransferSocket = 0;
  1272. ResetOperation(FZ_REPLY_ERROR);
  1273. return;
  1274. }
  1275. int num = 0;
  1276. pData->pDirectoryListing = new t_directory;
  1277. if (COptions::GetOptionVal(OPTION_DEBUGSHOWLISTING))
  1278. m_pTransferSocket->m_pListResult->SendToMessageLog(m_pOwner->m_hOwnerWnd, m_pOwner->m_nReplyMessageID);
  1279. pData->pDirectoryListing->direntry = m_pTransferSocket->m_pListResult->getList(num, pData->ListStartTime);
  1280. pData->pDirectoryListing->num = num;
  1281. if (m_pTransferSocket->m_pListResult->m_server.nServerType & FZ_SERVERTYPE_SUB_FTP_VMS && m_CurrentServer.nServerType & FZ_SERVERTYPE_FTP)
  1282. m_CurrentServer.nServerType |= FZ_SERVERTYPE_SUB_FTP_VMS;
  1283. pData->pDirectoryListing->server = m_CurrentServer;
  1284. pData->pDirectoryListing->path.SetServer(pData->pDirectoryListing->server);
  1285. if (pData->rawpwd != "")
  1286. {
  1287. if (!pData->pDirectoryListing->path.SetPath(pData->rawpwd))
  1288. {
  1289. delete m_pDirectoryListing;
  1290. m_pDirectoryListing=0;
  1291. delete m_pTransferSocket;
  1292. m_pTransferSocket=0;
  1293. ResetOperation(FZ_REPLY_ERROR);
  1294. return;
  1295. }
  1296. m_pOwner->SetCurrentPath(pData->pDirectoryListing->path);
  1297. }
  1298. else
  1299. pData->pDirectoryListing->path = m_pOwner->GetCurrentPath();
  1300. if (m_Operation.nOpState!=LIST_WAITFINISH)
  1301. {
  1302. return;
  1303. }
  1304. else
  1305. {
  1306. delete m_pTransferSocket;
  1307. m_pTransferSocket=0;
  1308. }
  1309. }
  1310. if (m_Operation.nOpState==LIST_WAITFINISH)
  1311. {
  1312. if (!bFinish)
  1313. {
  1314. if (pData->nFinish==-1)
  1315. {
  1316. int code=GetReplyCode();
  1317. if (code== 2)
  1318. {
  1319. pData->nFinish=1;
  1320. }
  1321. else
  1322. pData->nFinish=0;
  1323. }
  1324. }
  1325. else
  1326. {
  1327. if (m_pTransferSocket)
  1328. delete m_pTransferSocket;
  1329. m_pTransferSocket=0;
  1330. }
  1331. if (pData->nFinish==0)
  1332. {
  1333. ResetOperation(FZ_REPLY_ERROR);
  1334. return;
  1335. }
  1336. else if (pData->pDirectoryListing && pData->nFinish==1)
  1337. {
  1338. ShowStatus(IDS_STATUSMSG_DIRLISTSUCCESSFUL,0);
  1339. #ifndef MPEXT_NO_CACHE
  1340. CDirectoryCache cache;
  1341. cache.Lock();
  1342. t_directory dir;
  1343. if (!pData->path.IsEmpty() && pData->subdir!="")
  1344. {
  1345. if (cache.Lookup(pData->pDirectoryListing->path, pData->pDirectoryListing->server, dir))
  1346. pData->pDirectoryListing->Merge(dir, pData->ListStartTime);
  1347. cache.Store(*pData->pDirectoryListing,pData->path,pData->subdir);
  1348. }
  1349. else
  1350. {
  1351. if (cache.Lookup(pData->pDirectoryListing->path, pData->pDirectoryListing->server, dir))
  1352. pData->pDirectoryListing->Merge(dir, pData->ListStartTime);
  1353. cache.Store(*pData->pDirectoryListing);
  1354. }
  1355. cache.Unlock();
  1356. #endif
  1357. SetDirectoryListing(pData->pDirectoryListing);
  1358. ResetOperation(FZ_REPLY_OK);
  1359. return;
  1360. }
  1361. return;
  1362. }
  1363. else if (m_Operation.nOpState != LIST_INIT)
  1364. {
  1365. CString retmsg = GetReply();
  1366. BOOL error = FALSE;
  1367. int code = GetReplyCode();
  1368. switch (m_Operation.nOpState)
  1369. {
  1370. case LIST_PWD: //Reply to PWD command
  1371. if (code != 2 && code !=3 )
  1372. {
  1373. error = TRUE;
  1374. break;
  1375. }
  1376. pData->rawpwd = retmsg;
  1377. if ((m_mayBeMvsFilesystem || m_mayBeBS2000Filesystem) && m_CurrentServer.nServerType & FZ_SERVERTYPE_FTP &&
  1378. pData->rawpwd[0] != '/')
  1379. {
  1380. m_mayBeMvsFilesystem = false;
  1381. m_mayBeBS2000Filesystem = false;
  1382. if (m_mayBeBS2000Filesystem)
  1383. m_CurrentServer.nServerType |= FZ_SERVERTYPE_SUB_FTP_BS2000;
  1384. else
  1385. m_CurrentServer.nServerType |= FZ_SERVERTYPE_SUB_FTP_MVS;
  1386. if (!pData->path.IsEmpty())
  1387. pData->path.SetServer(m_CurrentServer);
  1388. }
  1389. if (!ParsePwdReply(pData->rawpwd))
  1390. return;
  1391. if (pData->path.IsEmpty() || pData->path == m_pOwner->GetCurrentPath())
  1392. {
  1393. #ifndef MPEXT_NO_CACHE
  1394. if (pData->nListMode & FZ_LIST_USECACHE)
  1395. {
  1396. t_directory dir;
  1397. CDirectoryCache cache;
  1398. BOOL res = cache.Lookup(m_pOwner->GetCurrentPath(), m_CurrentServer, dir);
  1399. if (res)
  1400. {
  1401. BOOL bExact = TRUE;
  1402. if (pData->nListMode & FZ_LIST_EXACT)
  1403. for (int i=0; i<dir.num; i++)
  1404. if (dir.direntry[i].bUnsure || (dir.direntry[i].size==-1 && !dir.direntry[i].dir))
  1405. {
  1406. bExact = FALSE;
  1407. break;
  1408. }
  1409. if (bExact)
  1410. {
  1411. ShowStatus(IDS_STATUSMSG_DIRLISTSUCCESSFUL, 0);
  1412. SetDirectoryListing(&dir);
  1413. ResetOperation(FZ_REPLY_OK);
  1414. return;
  1415. }
  1416. }
  1417. }
  1418. #endif
  1419. m_Operation.nOpState = NeedModeCommand() ? LIST_MODE : (NeedOptsCommand() ? LIST_OPTS : LIST_TYPE);
  1420. }
  1421. else
  1422. m_Operation.nOpState = LIST_CWD;
  1423. break;
  1424. case LIST_CWD:
  1425. if (code != 2 && code != 3)
  1426. error = TRUE;
  1427. m_Operation.nOpState = LIST_PWD2;
  1428. break;
  1429. case LIST_PWD2: //Reply to PWD command
  1430. if (code !=2 && code != 3)
  1431. error = TRUE;
  1432. else
  1433. {
  1434. pData->rawpwd = retmsg;
  1435. if (!ParsePwdReply(pData->rawpwd))
  1436. return;
  1437. }
  1438. if (pData->subdir != "")
  1439. {
  1440. if (pData->path != m_pOwner->GetCurrentPath())
  1441. {
  1442. ResetOperation(FZ_REPLY_ERROR);
  1443. return;
  1444. }
  1445. m_Operation.nOpState = LIST_CWD2;
  1446. }
  1447. else
  1448. {
  1449. #ifndef MPEXT_NO_CACHE
  1450. if (pData->nListMode & FZ_LIST_USECACHE)
  1451. {
  1452. t_directory dir;
  1453. CDirectoryCache cache;
  1454. BOOL res = cache.Lookup(m_pOwner->GetCurrentPath(), m_CurrentServer, dir);
  1455. if (res)
  1456. {
  1457. BOOL bExact = TRUE;
  1458. if (pData->nListMode & FZ_LIST_EXACT)
  1459. for (int i=0; i<dir.num; i++)
  1460. if (dir.direntry[i].bUnsure || (dir.direntry[i].size==-1 && !dir.direntry[i].dir))
  1461. {
  1462. bExact = FALSE;
  1463. break;
  1464. }
  1465. if (bExact)
  1466. {
  1467. ShowStatus(IDS_STATUSMSG_DIRLISTSUCCESSFUL, 0);
  1468. SetDirectoryListing(&dir);
  1469. ResetOperation(FZ_REPLY_OK);
  1470. return;
  1471. }
  1472. }
  1473. }
  1474. #endif
  1475. m_Operation.nOpState = NeedModeCommand() ? LIST_MODE : (NeedOptsCommand() ? LIST_OPTS : LIST_TYPE);
  1476. }
  1477. break;
  1478. case LIST_CWD2:
  1479. if (pData->lastCmdSentCDUP)
  1480. {
  1481. CString reply = GetReply().Left(3);
  1482. int replycode = _ttoi(reply);
  1483. if (replycode >= 500 && replycode < 505)
  1484. break;
  1485. pData->lastCmdSentCDUP = false;
  1486. }
  1487. if (code != 2 && code != 3)
  1488. error = TRUE;
  1489. m_Operation.nOpState = LIST_PWD3;
  1490. break;
  1491. case LIST_PWD3: //Reply to PWD command
  1492. if (code != 2 && code != 3)
  1493. error = TRUE;
  1494. else
  1495. {
  1496. pData->rawpwd = retmsg;
  1497. if (!ParsePwdReply(pData->rawpwd))
  1498. return;
  1499. #ifndef MPEXT_NO_CACHE
  1500. if (pData->nListMode & FZ_LIST_USECACHE)
  1501. {
  1502. t_directory dir;
  1503. CDirectoryCache cache;
  1504. BOOL res = cache.Lookup(m_pOwner->GetCurrentPath(), m_CurrentServer, dir);
  1505. if (res)
  1506. {
  1507. BOOL bExact = TRUE;
  1508. if (pData->nListMode & FZ_LIST_EXACT)
  1509. for (int i=0; i<dir.num; i++)
  1510. if (dir.direntry[i].bUnsure || (dir.direntry[i].size==-1 && !dir.direntry[i].dir))
  1511. {
  1512. bExact = FALSE;
  1513. break;
  1514. }
  1515. if (bExact)
  1516. {
  1517. ShowStatus(IDS_STATUSMSG_DIRLISTSUCCESSFUL, 0);
  1518. SetDirectoryListing(&dir);
  1519. ResetOperation(FZ_REPLY_OK);
  1520. return;
  1521. }
  1522. }
  1523. }
  1524. #endif
  1525. }
  1526. m_Operation.nOpState = NeedModeCommand() ? LIST_MODE : (NeedOptsCommand() ? LIST_OPTS : LIST_TYPE);
  1527. break;
  1528. case LIST_MODE:
  1529. #ifndef MPEXT_NO_ZLIB
  1530. if (code == 2 || code == 3)
  1531. m_useZlib = !m_useZlib;
  1532. #endif
  1533. m_Operation.nOpState = NeedOptsCommand() ? LIST_OPTS : LIST_TYPE;
  1534. break;
  1535. case LIST_OPTS:
  1536. #ifndef MPEXT_NO_ZLIB
  1537. if (code == 2 || code == 3)
  1538. m_zlibLevel = pData->newZlibLevel;
  1539. #endif
  1540. m_Operation.nOpState = LIST_TYPE;
  1541. break;
  1542. case LIST_TYPE:
  1543. if (code!=2 && code!=3)
  1544. error=TRUE;
  1545. m_Operation.nOpState = LIST_PORT_PASV;
  1546. break;
  1547. case LIST_PORT_PASV:
  1548. if (code!=2 && code!=3)
  1549. {
  1550. error=TRUE;
  1551. break;
  1552. }
  1553. if (pData->bPasv)
  1554. {
  1555. CString temp;
  1556. int i,j;
  1557. if((i=retmsg.Find(_T("(")))==-1||(j=retmsg.Find(_T(")")))==-1)
  1558. {
  1559. if (!pData->bTriedPortPasvOnce)
  1560. {
  1561. pData->bTriedPortPasvOnce = TRUE;
  1562. pData->bPasv = !pData->bPasv;
  1563. }
  1564. else
  1565. error=TRUE;
  1566. break;
  1567. }
  1568. #ifdef MPEXT
  1569. temp = retmsg.Mid(i+1,(j-i)-1);
  1570. #endif
  1571. if (GetFamily() == AF_INET)
  1572. {
  1573. #ifndef MPEXT
  1574. temp = retmsg.Mid(i+1,(j-i)-1);
  1575. #endif
  1576. i=temp.ReverseFind(',');
  1577. pData->port=atol( T2CA( temp.Right(temp.GetLength()-(i+1)) ) ); //get ls byte of server socket
  1578. temp=temp.Left(i);
  1579. i=temp.ReverseFind(',');
  1580. pData->port+=256*atol( T2CA( temp.Right(temp.GetLength()-(i+1)) ) ); // add ms byte to server socket
  1581. pData->host = temp.Left(i);
  1582. pData->host.Replace(',', '.');
  1583. #ifdef MPEXT
  1584. if (!CheckForcePasvIp(pData->host))
  1585. {
  1586. error = TRUE;
  1587. break;
  1588. }
  1589. #endif
  1590. }
  1591. else if (GetFamily() == AF_INET6)
  1592. {
  1593. temp = temp.Mid(3);
  1594. pData->port = atol( T2CA(temp.Left(temp.GetLength() - 1) ) );
  1595. if (pData->port < 0 || pData->port > 65535)
  1596. {
  1597. LogMessage(__FILE__, __LINE__, this, FZ_LOG_WARNING, _T("Port %u not valid"), pData->port);
  1598. error = TRUE;
  1599. break;
  1600. }
  1601. unsigned int tmpPort;
  1602. if (!GetPeerName(pData->host, tmpPort))
  1603. {
  1604. LogMessage(__FILE__, __LINE__, this, FZ_LOG_WARNING, _T("GetPeerName failed"));
  1605. error = TRUE;
  1606. break;
  1607. }
  1608. }
  1609. else
  1610. {
  1611. LogMessage(__FILE__, __LINE__, this, FZ_LOG_WARNING, _T("Protocol %d not supported"), GetFamily());
  1612. error = TRUE;
  1613. break;
  1614. }
  1615. }
  1616. m_Operation.nOpState = LIST_LIST;
  1617. break;
  1618. case LIST_LIST:
  1619. if (IsMisleadingListResponse())
  1620. {
  1621. ShowStatus(IDS_STATUSMSG_DIRLISTSUCCESSFUL, 0);
  1622. t_directory listing;
  1623. listing.server = m_CurrentServer;
  1624. listing.path = m_pOwner->GetCurrentPath();
  1625. #ifndef MPEXT_NO_CACHE
  1626. CDirectoryCache cache;
  1627. cache.Lock();
  1628. t_directory dir;
  1629. if (!pData->path.IsEmpty() && pData->subdir != "")
  1630. {
  1631. if (cache.Lookup(listing.path, listing.server, dir))
  1632. listing.Merge(dir, pData->ListStartTime);
  1633. cache.Store(listing, pData->path, pData->subdir);
  1634. }
  1635. else
  1636. {
  1637. if (cache.Lookup(listing.path, listing.server, dir))
  1638. listing.Merge(dir, pData->ListStartTime);
  1639. cache.Store(listing);
  1640. }
  1641. cache.Unlock();
  1642. #endif
  1643. SetDirectoryListing(&listing);
  1644. ResetOperation(FZ_REPLY_OK);
  1645. return;
  1646. }
  1647. else if (code != 1)
  1648. error = TRUE;
  1649. else
  1650. m_Operation.nOpState = LIST_WAITFINISH;
  1651. break;
  1652. default:
  1653. error = TRUE;
  1654. }
  1655. if (error)
  1656. {
  1657. ResetOperation(FZ_REPLY_ERROR);
  1658. return;
  1659. }
  1660. }
  1661. if (m_Operation.nOpState==LIST_INIT)
  1662. { //Initialize some variables
  1663. pData=new CListData;
  1664. pData->nListMode=nListMode;
  1665. pData->path=path;
  1666. pData->subdir=subdir;
  1667. m_Operation.pData=pData;
  1668. ShowStatus(IDS_STATUSMSG_RETRIEVINGDIRLIST, 0);
  1669. pData->nFinish=-1;
  1670. if (m_pDirectoryListing)
  1671. {
  1672. delete m_pDirectoryListing;
  1673. m_pDirectoryListing=0;
  1674. }
  1675. if (COptions::GetOptionVal(OPTION_PROXYTYPE)!=PROXYTYPE_NOPROXY && !m_CurrentServer.fwbypass)
  1676. pData->bPasv = TRUE;
  1677. else if (m_CurrentServer.nPasv == 1)
  1678. pData->bPasv = TRUE;
  1679. else if (m_CurrentServer.nPasv == 2)
  1680. pData->bPasv = FALSE;
  1681. else
  1682. pData->bPasv = COptions::GetOptionVal(OPTION_PASV);
  1683. CServerPath path = pData->path;
  1684. CServerPath realpath = m_pOwner->GetCurrentPath();
  1685. if (!realpath.IsEmpty())
  1686. {
  1687. if (!pData->path.IsEmpty() && pData->path != realpath)
  1688. m_Operation.nOpState=LIST_CWD;
  1689. else if (!pData->path.IsEmpty() && pData->subdir!="")
  1690. m_Operation.nOpState=LIST_CWD2;
  1691. else
  1692. {
  1693. if (pData->nListMode & FZ_LIST_REALCHANGE)
  1694. {
  1695. if (pData->subdir == "")
  1696. m_Operation.nOpState = LIST_CWD;
  1697. else
  1698. m_Operation.nOpState = LIST_CWD2;
  1699. }
  1700. else
  1701. {
  1702. #ifndef MPEXT_NO_CACHE
  1703. if (pData->nListMode&FZ_LIST_USECACHE)
  1704. {
  1705. t_directory dir;
  1706. CDirectoryCache cache;
  1707. BOOL res = cache.Lookup(realpath, m_CurrentServer,dir);
  1708. if (res)
  1709. {
  1710. BOOL bExact = TRUE;
  1711. if (pData->nListMode & FZ_LIST_EXACT)
  1712. for (int i = 0; i < dir.num; i++)
  1713. if (dir.direntry[i].bUnsure || (dir.direntry[i].size == -1 && !dir.direntry[i].dir))
  1714. {
  1715. bExact = FALSE;
  1716. break;
  1717. }
  1718. if (bExact)
  1719. {
  1720. ShowStatus(IDS_STATUSMSG_DIRLISTSUCCESSFUL,0);
  1721. SetDirectoryListing(&dir);
  1722. ResetOperation(FZ_REPLY_OK);
  1723. return;
  1724. }
  1725. }
  1726. }
  1727. #endif
  1728. m_Operation.nOpState = NeedModeCommand() ? LIST_MODE : (NeedOptsCommand() ? LIST_OPTS : LIST_TYPE);;
  1729. }
  1730. }
  1731. }
  1732. else
  1733. m_Operation.nOpState = LIST_PWD;
  1734. }
  1735. CString cmd;
  1736. if (m_Operation.nOpState == LIST_PWD)
  1737. cmd=_T("PWD");
  1738. else if (m_Operation.nOpState==LIST_CWD)
  1739. cmd=_T("CWD ") + pData->path.GetPath(); //Command to retrieve the current directory
  1740. else if (m_Operation.nOpState==LIST_PWD2)
  1741. cmd=_T("PWD");
  1742. else if (m_Operation.nOpState==LIST_CWD2)
  1743. {
  1744. if (!pData->subdir)
  1745. {
  1746. ResetOperation(FZ_REPLY_ERROR);
  1747. return;
  1748. }
  1749. if (pData->subdir != _T("..") )
  1750. {
  1751. if (m_CurrentServer.nServerType & FZ_SERVERTYPE_SUB_FTP_VMS)
  1752. {
  1753. CServerPath path = m_pOwner->GetCurrentPath();
  1754. path.AddSubdir(pData->subdir);
  1755. cmd = _T("CWD ") + path.GetPath();
  1756. }
  1757. else
  1758. cmd = _T("CWD ") + pData->subdir;
  1759. }
  1760. else
  1761. {
  1762. if (pData->lastCmdSentCDUP)
  1763. {
  1764. pData->lastCmdSentCDUP = false;
  1765. cmd = _T("CWD ..");
  1766. }
  1767. else
  1768. {
  1769. pData->lastCmdSentCDUP = true;
  1770. cmd = _T("CDUP");
  1771. }
  1772. }
  1773. }
  1774. else if (m_Operation.nOpState == LIST_PWD3)
  1775. cmd=_T("PWD");
  1776. else if (m_Operation.nOpState == LIST_MODE)
  1777. {
  1778. #ifdef MPEXT_NO_ZLIB
  1779. ASSERT(false);
  1780. #else
  1781. if (m_useZlib)
  1782. #endif
  1783. cmd = _T("MODE S");
  1784. #ifndef MPEXT_NO_ZLIB
  1785. else
  1786. cmd = _T("MODE Z");
  1787. #endif
  1788. }
  1789. else if (m_Operation.nOpState == LIST_OPTS)
  1790. {
  1791. #ifdef MPEXT_NO_ZLIB
  1792. ASSERT(false);
  1793. #else
  1794. pData->newZlibLevel = COptions::GetOptionVal(OPTION_MODEZ_LEVEL);
  1795. cmd.Format(_T("OPTS MODE Z LEVEL %d"), pData->newZlibLevel);
  1796. #endif
  1797. }
  1798. else if (m_Operation.nOpState == LIST_PORT_PASV)
  1799. {
  1800. m_pTransferSocket = new CTransferSocket(this, m_Operation.nOpMode);
  1801. #ifndef MPEXT_NO_ZLIB
  1802. if (m_useZlib)
  1803. {
  1804. if (!m_pTransferSocket->InitZlib(m_zlibLevel))
  1805. {
  1806. ShowStatus(_T("Failed to initialize zlib"), 1);
  1807. ResetOperation(FZ_REPLY_ERROR);
  1808. return;
  1809. }
  1810. }
  1811. #endif
  1812. m_pTransferSocket->m_nInternalMessageID = m_pOwner->m_nInternalMessageID;
  1813. #ifndef MPEXT_NO_GSS
  1814. if (m_pGssLayer && m_pGssLayer->AuthSuccessful())
  1815. m_pTransferSocket->UseGSS(m_pGssLayer);
  1816. #endif
  1817. m_pTransferSocket->SetFamily(GetFamily());
  1818. if (!m_pTransferSocket->Create(
  1819. #ifndef MPEXT_NO_SSL
  1820. m_pSslLayer && m_bProtP
  1821. #endif
  1822. ) ||
  1823. !m_pTransferSocket->AsyncSelect())
  1824. {
  1825. ShowStatus(_T("Failed to create socket"), 1);
  1826. ResetOperation(FZ_REPLY_ERROR);
  1827. return;
  1828. }
  1829. if (pData->bPasv)
  1830. switch (GetFamily())
  1831. {
  1832. case AF_INET:
  1833. cmd = _T("PASV");
  1834. break;
  1835. case AF_INET6:
  1836. cmd = _T("EPSV");
  1837. break;
  1838. default:
  1839. LogMessage(__FILE__, __LINE__, this, FZ_LOG_WARNING, _T("Protocol %d not supported"), GetFamily());
  1840. ResetOperation(FZ_REPLY_ERROR);
  1841. return;
  1842. }
  1843. else
  1844. {
  1845. m_pTransferSocket->m_bListening=TRUE;
  1846. if (m_pProxyLayer)
  1847. {
  1848. SOCKADDR_IN addr;
  1849. int len=sizeof(addr);
  1850. if (!m_pProxyLayer->GetPeerName((SOCKADDR *)&addr,&len))
  1851. {
  1852. ResetOperation(FZ_REPLY_ERROR);
  1853. return;
  1854. }
  1855. else if (!m_pTransferSocket->Listen(addr.sin_addr.S_un.S_addr))
  1856. {
  1857. ResetOperation(FZ_REPLY_ERROR);
  1858. return;
  1859. }
  1860. }
  1861. else
  1862. {
  1863. //Set up an active file transfer
  1864. CString tempHostname;
  1865. UINT nPort;
  1866. if (// create listen socket (let MFC choose the port) & start the socket listening
  1867. !m_pTransferSocket->Listen() ||
  1868. !m_pTransferSocket->GetSockName(tempHostname, nPort))
  1869. {
  1870. ShowStatus(_T("Failed to create listen socket"), 1);
  1871. ResetOperation(FZ_REPLY_ERROR);
  1872. return;
  1873. }
  1874. CString host;
  1875. bool bError = false;
  1876. if (GetFamily() == AF_INET)
  1877. {
  1878. host = COptions::GetOption(OPTION_TRANSFERIP);
  1879. if (host != "")
  1880. {
  1881. DWORD ip = inet_addr(T2CA(host));
  1882. if (ip != INADDR_NONE)
  1883. host.Format(_T("%d,%d,%d,%d"), ip%256, (ip>>8)%256, (ip>>16)%256, ip>>24);
  1884. else
  1885. {
  1886. hostent *fullname = gethostbyname(T2CA(host));
  1887. if (!fullname)
  1888. host = "";
  1889. else
  1890. {
  1891. DWORD ip = ((LPIN_ADDR)fullname->h_addr)->s_addr;
  1892. if (ip != INADDR_NONE)
  1893. host.Format(_T("%d,%d,%d,%d"), ip%256, (ip>>8)%256, (ip>>16)%256, ip>>24);
  1894. else
  1895. host = "";
  1896. }
  1897. }
  1898. }
  1899. if (host == "")
  1900. {
  1901. UINT temp;
  1902. if (!GetSockName(host, temp))
  1903. {
  1904. ShowStatus(_T("Failed to get socket address "), 1);
  1905. bError = true;
  1906. }
  1907. host.Replace('.', ',');
  1908. }
  1909. if (!bError)
  1910. {
  1911. host.Format(host+",%d,%d", nPort/256, nPort%256);
  1912. cmd = _T("PORT ") + host; // send PORT cmd to server
  1913. }
  1914. }
  1915. else if (GetFamily() == AF_INET6)
  1916. {
  1917. host = COptions::GetOption(OPTION_TRANSFERIP6);
  1918. if (host != "")
  1919. {
  1920. USES_CONVERSION;
  1921. addrinfo hints, *res;
  1922. memset(&hints, 0, sizeof(addrinfo));
  1923. hints.ai_family = AF_INET6;
  1924. hints.ai_socktype = SOCK_STREAM;
  1925. if (!p_getaddrinfo(T2CA(host), "1024", &hints, &res))
  1926. {
  1927. host = Inet6AddrToString(((SOCKADDR_IN6 *)res->ai_addr)->sin6_addr);
  1928. p_freeaddrinfo(res);
  1929. }
  1930. else
  1931. host = _T("");
  1932. }
  1933. if (host == "")
  1934. {
  1935. UINT temp;
  1936. if(!GetSockName(host, temp))
  1937. bError = true;
  1938. }
  1939. if (!bError)
  1940. {
  1941. // assamble EPRT command
  1942. cmd.Format(_T("EPRT |2|") + host + "|%d|", nPort);
  1943. }
  1944. }
  1945. else
  1946. {
  1947. LogMessage(__FILE__, __LINE__, this, FZ_LOG_WARNING, _T("Protocol %d not supported"), GetFamily());
  1948. bError = true;
  1949. }
  1950. if (bError)
  1951. {
  1952. ResetOperation(FZ_REPLY_ERROR);
  1953. return;
  1954. }
  1955. }
  1956. }
  1957. }
  1958. else if (m_Operation.nOpState==LIST_TYPE)
  1959. cmd=_T("TYPE A");
  1960. else if (m_Operation.nOpState==LIST_LIST)
  1961. {
  1962. if (!m_pTransferSocket)
  1963. {
  1964. LogMessage(__FILE__, __LINE__, this,FZ_LOG_APIERROR, _T("Error: m_pTransferSocket==NULL") );
  1965. ResetOperation(FZ_REPLY_ERROR);
  1966. return;
  1967. }
  1968. m_pTransferSocket->SetActive();
  1969. cmd = _T("LIST");
  1970. #ifdef MPEXT
  1971. if (COptions::GetOptionVal(OPTION_MPEXT_SHOWHIDDEN) && !(m_CurrentServer.nServerType & (FZ_SERVERTYPE_SUB_FTP_MVS | FZ_SERVERTYPE_SUB_FTP_VMS | FZ_SERVERTYPE_SUB_FTP_BS2000)))
  1972. #else
  1973. 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)))
  1974. #endif
  1975. cmd += _T(" -a");
  1976. if (!Send(cmd))
  1977. return;
  1978. pData->ListStartTime=CTime::GetCurrentTime();
  1979. if (pData->bPasv)
  1980. {
  1981. // if PASV create the socket & initiate outbound data channel connection
  1982. if (!m_pTransferSocket->Connect(pData->host,pData->port))
  1983. {
  1984. if (GetLastError()!=WSAEWOULDBLOCK)
  1985. {
  1986. ResetOperation(FZ_REPLY_ERROR);
  1987. return;
  1988. }
  1989. }
  1990. }
  1991. return;
  1992. }
  1993. if (cmd != _T(""))
  1994. Send(cmd);
  1995. }
  1996. void CFtpControlSocket::TransferEnd(int nMode)
  1997. {
  1998. LogMessage(__FILE__, __LINE__, this,FZ_LOG_DEBUG, _T("TransferEnd(%d/%x) OpMode=%d OpState=%d"), nMode, nMode, m_Operation.nOpMode, m_Operation.nOpState);
  1999. if (!m_Operation.nOpMode)
  2000. {
  2001. LogMessage(__FILE__, __LINE__, this,FZ_LOG_INFO, _T("Ignoring old TransferEnd message"));
  2002. return;
  2003. }
  2004. m_LastRecvTime=CTime::GetCurrentTime();
  2005. if (m_Operation.nOpMode&CSMODE_TRANSFER)
  2006. FileTransfer(0,TRUE,nMode&(CSMODE_TRANSFERERROR|CSMODE_TRANSFERTIMEOUT));
  2007. else if (m_Operation.nOpMode&CSMODE_LIST)
  2008. List(TRUE,nMode&(CSMODE_TRANSFERERROR|CSMODE_TRANSFERTIMEOUT));
  2009. }
  2010. void CFtpControlSocket::OnClose(int nErrorCode)
  2011. {
  2012. LogMessage(__FILE__, __LINE__, this,FZ_LOG_DEBUG, _T("OnClose(%d) OpMode=%d OpState=%d"), nErrorCode, m_Operation.nOpMode, m_Operation.nOpState);
  2013. ShowStatus(IDS_STATUSMSG_DISCONNECTED, 1);
  2014. if (m_pTransferSocket)
  2015. {
  2016. m_pTransferSocket->OnClose(0);
  2017. m_pTransferSocket->Close();
  2018. delete m_pTransferSocket;
  2019. m_pTransferSocket=0;
  2020. DoClose();
  2021. ShowStatus(IDS_ERRORMSG_TIMEOUT,1);
  2022. return;
  2023. }
  2024. #ifndef MPEXT_NO_SSL
  2025. if (m_bDidRejectCertificate)
  2026. DoClose(FZ_REPLY_CANCEL);
  2027. else
  2028. #endif
  2029. DoClose();
  2030. }
  2031. void CFtpControlSocket::FileTransfer(t_transferfile *transferfile/*=0*/,BOOL bFinish/*=FALSE*/,int nError/*=0*/)
  2032. {
  2033. 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);
  2034. USES_CONVERSION;
  2035. #define FILETRANSFER_INIT -1
  2036. #define FILETRANSFER_PWD 0
  2037. #define FILETRANSFER_CWD 1
  2038. #define FILETRANSFER_MKD 2
  2039. #define FILETRANSFER_CWD2 3
  2040. #define FILETRANSFER_PWD2 4
  2041. #define FILETRANSFER_LIST_MODE 5
  2042. #define FILETRANSFER_LIST_OPTS 6
  2043. #define FILETRANSFER_LIST_PORTPASV 7
  2044. #define FILETRANSFER_LIST_TYPE 8
  2045. #define FILETRANSFER_LIST_LIST 9
  2046. #define FILETRANSFER_LIST_WAITFINISH 10
  2047. #define FILETRANSFER_NOLIST_SIZE 11
  2048. #define FILETRANSFER_NOLIST_MDTM 12
  2049. #define FILETRANSFER_TYPE 13
  2050. #define FILETRANSFER_REST 14
  2051. #define FILETRANSFER_MODE 15
  2052. #define FILETRANSFER_OPTS 16
  2053. #define FILETRANSFER_PORTPASV 17
  2054. #define FILETRANSFER_RETRSTOR 18
  2055. #define FILETRANSFER_WAITFINISH 19
  2056. #define FILETRANSFER_WAIT 20
  2057. #ifdef MPEXT
  2058. #define FILETRANSFER_MFMT 21
  2059. #endif
  2060. //Partial flowchart of FileTransfer
  2061. //
  2062. // +----+
  2063. // /------|Init|--------\
  2064. // | +----+ |
  2065. // | | |
  2066. // | /---+ |
  2067. // | | | |
  2068. // | | +---+ |
  2069. // | | |PWD| |
  2070. // | | +---+ |
  2071. // | | | |
  2072. // | \---+ |
  2073. // | | |
  2074. // | +---+ |
  2075. // | |CWD|--\ |
  2076. // | +---+ | |
  2077. // | | | |
  2078. // | | | |
  2079. // | | +---+ |
  2080. // | | |MKD| |
  2081. // | | +---+ |
  2082. // | | | |
  2083. // | | | |
  2084. // | | +----+ |
  2085. // | | |CWD2| |
  2086. // | | +----+ |
  2087. // | | | |
  2088. // | +----/ |
  2089. // | | |
  2090. // | +---+ |
  2091. // +-------|PWD| |
  2092. // | +---+ |
  2093. // | | |
  2094. // | +----------/
  2095. // | |
  2096. // | +---------+
  2097. // | |LIST_TYPE|
  2098. // | +---------+
  2099. // | |
  2100. // | |
  2101. // | +-------------+
  2102. // | |LIST_PORTPASV|
  2103. // | +-------------+
  2104. // | |
  2105. // | |
  2106. // | +---------+
  2107. // | |LIST_LIST|-----\ //List failes, maybe folder is list protected
  2108. // | +---------+ | //Use SIZE and MDTM to get file information
  2109. // | | +----+
  2110. // | | |SIZE|
  2111. // | | +----+
  2112. // | | |
  2113. // | | +----+
  2114. // | | |MDTM|
  2115. // | | +----+
  2116. // | | |
  2117. // | | |
  2118. // | +---------------+ |
  2119. // | |LIST_WAITFINISH| |
  2120. // | +---------------+ |
  2121. // | | |
  2122. // | | |
  2123. // | +----------/
  2124. // | |
  2125. // \---------+
  2126. // |
  2127. // +----+
  2128. // |TYPE|
  2129. // +----+
  2130. // |
  2131. // |
  2132. // +--------+
  2133. // |PORTPASV|--\
  2134. // +--------+ |
  2135. // | |
  2136. // | |
  2137. // | +----+
  2138. // | |REST|
  2139. // | +----+
  2140. // | |
  2141. // +------/
  2142. // |
  2143. // +--------+
  2144. // |RETRSTOR|
  2145. // +--------+
  2146. // |
  2147. // |
  2148. // +----------+
  2149. // |WAITFINISH|
  2150. // +----------+
  2151. ASSERT(!m_Operation.nOpMode || m_Operation.nOpMode&CSMODE_TRANSFER);
  2152. if (!m_pOwner->IsConnected())
  2153. {
  2154. m_Operation.nOpMode=CSMODE_TRANSFER|(transferfile->get?CSMODE_DOWNLOAD:CSMODE_UPLOAD);
  2155. ResetOperation(FZ_REPLY_ERROR|FZ_REPLY_DISCONNECTED);
  2156. return;
  2157. }
  2158. CFileTransferData *pData=static_cast<CFileTransferData *>(m_Operation.pData);
  2159. //Process finish and error messages
  2160. if (bFinish || nError)
  2161. {
  2162. ASSERT(m_Operation.nOpMode&CSMODE_TRANSFER);
  2163. // APPE failed, ignore this reply
  2164. if (m_Operation.nOpMode == FILETRANSFER_WAIT && bFinish)
  2165. return;
  2166. if (!(m_Operation.nOpMode&CSMODE_TRANSFER))
  2167. return;
  2168. if (nError)
  2169. {
  2170. if (m_Operation.nOpState == FILETRANSFER_LIST_LIST && nError & CSMODE_TRANSFERERROR)
  2171. { //Don't abort operation, use fallback to SIZE and MDTM (when actual LIST reply comes in)
  2172. if (m_pTransferSocket)
  2173. m_pTransferSocket=0;
  2174. delete m_pDirectoryListing;
  2175. m_pDirectoryListing=0;
  2176. }
  2177. else if (nError&CSMODE_TRANSFERTIMEOUT)
  2178. DoClose();
  2179. else
  2180. // MPEXT: we may get here when connection was closed, when the closure
  2181. // was first detected while reading/writing,
  2182. // when we abort file transfer with regular error,
  2183. // possibly preventing automatic reconnect
  2184. ResetOperation(FZ_REPLY_ERROR);
  2185. return;
  2186. }
  2187. if (m_Operation.nOpState <= FILETRANSFER_LIST_PORTPASV)
  2188. {
  2189. ResetOperation(FZ_REPLY_ERROR);
  2190. return;
  2191. }
  2192. else if (m_Operation.nOpState<=FILETRANSFER_LIST_WAITFINISH)
  2193. {
  2194. if (!m_pTransferSocket || m_pTransferSocket->m_bListening)
  2195. {
  2196. delete m_pDirectoryListing;
  2197. m_pDirectoryListing=0;
  2198. ResetOperation(FZ_REPLY_ERROR);
  2199. return;
  2200. }
  2201. int num=0;
  2202. pData->pDirectoryListing=new t_directory;
  2203. if (COptions::GetOptionVal(OPTION_DEBUGSHOWLISTING))
  2204. m_pTransferSocket->m_pListResult->SendToMessageLog(m_pOwner->m_hOwnerWnd, m_pOwner->m_nReplyMessageID);
  2205. pData->pDirectoryListing->direntry=m_pTransferSocket->m_pListResult->getList(num, pData->ListStartTime);
  2206. pData->pDirectoryListing->num=num;
  2207. if (m_pTransferSocket->m_pListResult->m_server.nServerType&FZ_SERVERTYPE_SUB_FTP_VMS && m_CurrentServer.nServerType&FZ_SERVERTYPE_FTP)
  2208. m_CurrentServer.nServerType |= FZ_SERVERTYPE_SUB_FTP_VMS;
  2209. pData->pDirectoryListing->server = m_CurrentServer;
  2210. pData->pDirectoryListing->path.SetServer(m_CurrentServer);
  2211. pData->pDirectoryListing->path = pData->transferfile.remotepath;
  2212. if (pData->rawpwd!="")
  2213. {
  2214. if (!pData->pDirectoryListing->path.SetPath(pData->rawpwd))
  2215. {
  2216. delete m_pDirectoryListing;
  2217. m_pDirectoryListing=0;
  2218. delete m_pTransferSocket;
  2219. m_pTransferSocket=0;
  2220. ResetOperation(FZ_REPLY_ERROR);
  2221. return;
  2222. }
  2223. }
  2224. else
  2225. pData->pDirectoryListing->path=pData->transferfile.remotepath;
  2226. if (m_Operation.nOpState!=FILETRANSFER_LIST_WAITFINISH)
  2227. return;
  2228. }
  2229. else if (m_Operation.nOpState <= FILETRANSFER_PORTPASV)
  2230. {
  2231. ResetOperation(FZ_REPLY_ERROR);
  2232. return;
  2233. }
  2234. else if (m_Operation.nOpState<=FILETRANSFER_WAITFINISH)
  2235. {
  2236. if (m_pTransferSocket->m_bListening)
  2237. {
  2238. ResetOperation(FZ_REPLY_ERROR);
  2239. return;
  2240. }
  2241. pData->nGotTransferEndReply |= 2;
  2242. if (m_Operation.nOpState!=FILETRANSFER_WAITFINISH)
  2243. return;
  2244. else
  2245. {
  2246. delete m_pTransferSocket;
  2247. m_pTransferSocket=0;
  2248. }
  2249. }
  2250. }
  2251. //////////////////
  2252. //Initialization//
  2253. //////////////////
  2254. int nReplyError = 0;
  2255. if (m_Operation.nOpState == FILETRANSFER_INIT)
  2256. {
  2257. ASSERT(transferfile);
  2258. ASSERT(!m_Operation.nOpMode);
  2259. ASSERT(!m_Operation.pData);
  2260. CString str;
  2261. str.Format(transferfile->get?IDS_STATUSMSG_DOWNLOADSTART:IDS_STATUSMSG_UPLOADSTART,
  2262. transferfile->get ? transferfile->remotepath.FormatFilename(transferfile->remotefile) : transferfile->localfile);
  2263. ShowStatus(str,0);
  2264. m_Operation.nOpMode=CSMODE_TRANSFER|(transferfile->get?CSMODE_DOWNLOAD:CSMODE_UPLOAD);
  2265. m_Operation.pData=new CFileTransferData;
  2266. pData=static_cast<CFileTransferData *>(m_Operation.pData);
  2267. if (COptions::GetOptionVal(OPTION_PROXYTYPE)!=PROXYTYPE_NOPROXY && !m_CurrentServer.fwbypass)
  2268. pData->bPasv = TRUE;
  2269. else if (m_CurrentServer.nPasv == 1)
  2270. pData->bPasv = TRUE;
  2271. else if (m_CurrentServer.nPasv == 2)
  2272. pData->bPasv = FALSE;
  2273. else
  2274. pData->bPasv = COptions::GetOptionVal(OPTION_PASV);
  2275. //Replace invalid characters in the local filename
  2276. int pos=transferfile->localfile.ReverseFind('\\');
  2277. for (int i=(pos+1);i<transferfile->localfile.GetLength();i++)
  2278. if (transferfile->localfile[i]==':')
  2279. transferfile->localfile.SetAt(i, '_');
  2280. pData->transferfile=*transferfile;
  2281. pData->transferdata.transfersize=pData->transferfile.size;
  2282. pData->transferdata.transferleft=pData->transferfile.size;
  2283. pData->transferdata.bResume = FALSE;
  2284. pData->transferdata.bType = (pData->transferfile.nType == 1) ? TRUE : FALSE;
  2285. CServerPath path;
  2286. VERIFY(m_pOwner->GetCurrentPath(path));
  2287. if (path == pData->transferfile.remotepath)
  2288. {
  2289. if (m_pDirectoryListing)
  2290. {
  2291. m_Operation.nOpState=FILETRANSFER_TYPE;
  2292. CString remotefile=pData->transferfile.remotefile;
  2293. int i;
  2294. for (i=0; i<m_pDirectoryListing->num; i++)
  2295. {
  2296. if (m_pDirectoryListing->direntry[i].name==remotefile &&
  2297. ( m_pDirectoryListing->direntry[i].bUnsure || m_pDirectoryListing->direntry[i].size==-1 ))
  2298. {
  2299. delete m_pDirectoryListing;
  2300. m_pDirectoryListing=0;
  2301. m_Operation.nOpState = NeedModeCommand() ? FILETRANSFER_LIST_MODE : (NeedOptsCommand() ? FILETRANSFER_LIST_OPTS : FILETRANSFER_LIST_TYPE);
  2302. break;
  2303. }
  2304. }
  2305. if (m_pDirectoryListing && i==m_pDirectoryListing->num)
  2306. {
  2307. nReplyError = CheckOverwriteFile();
  2308. if (!nReplyError)
  2309. {
  2310. if (pData->transferfile.get)
  2311. {
  2312. CString path=pData->transferfile.localfile;
  2313. if (path.ReverseFind('\\')!=-1)
  2314. {
  2315. path=path.Left(path.ReverseFind('\\')+1);
  2316. CString path2;
  2317. while (path!="")
  2318. {
  2319. path2+=path.Left(path.Find( _T("\\") )+1);
  2320. path=path.Mid(path.Find( _T("\\") )+1);
  2321. CreateDirectory(path2, 0);
  2322. }
  2323. }
  2324. }
  2325. }
  2326. }
  2327. }
  2328. else
  2329. {
  2330. #ifndef MPEXT_NO_CACHE
  2331. CDirectoryCache cache;
  2332. t_server server;
  2333. m_pOwner->GetCurrentServer(server);
  2334. t_directory dir;
  2335. BOOL res = cache.Lookup(pData->transferfile.remotepath,server,dir);
  2336. if (res)
  2337. {
  2338. CString remotefile=pData->transferfile.remotefile;
  2339. int i;
  2340. for (i=0; i<dir.num; i++)
  2341. {
  2342. if (dir.direntry[i].name==remotefile &&
  2343. ( dir.direntry[i].bUnsure || dir.direntry[i].size==-1 ))
  2344. {
  2345. m_Operation.nOpState = NeedModeCommand() ? FILETRANSFER_LIST_MODE : (NeedOptsCommand() ? FILETRANSFER_LIST_OPTS : FILETRANSFER_LIST_TYPE);
  2346. break;
  2347. }
  2348. }
  2349. if (i == dir.num)
  2350. {
  2351. SetDirectoryListing(&dir);
  2352. m_Operation.nOpState=FILETRANSFER_TYPE;
  2353. nReplyError = CheckOverwriteFile();
  2354. if (!nReplyError)
  2355. {
  2356. if (pData->transferfile.get)
  2357. {
  2358. CString path=pData->transferfile.localfile;
  2359. if (path.ReverseFind('\\')!=-1)
  2360. {
  2361. path=path.Left(path.ReverseFind('\\')+1);
  2362. CString path2;
  2363. while (path!="")
  2364. {
  2365. path2+=path.Left(path.Find( _T("\\") )+1);
  2366. path=path.Mid(path.Find(_T( "\\") )+1);
  2367. CreateDirectory(path2, 0);
  2368. }
  2369. }
  2370. }
  2371. }
  2372. }
  2373. }
  2374. else
  2375. #endif
  2376. m_Operation.nOpState = NeedModeCommand() ? FILETRANSFER_LIST_MODE : (NeedOptsCommand() ? FILETRANSFER_LIST_OPTS : FILETRANSFER_LIST_TYPE);
  2377. }
  2378. }
  2379. else
  2380. {
  2381. if (path.IsEmpty())
  2382. m_Operation.nOpState = FILETRANSFER_PWD;
  2383. else
  2384. m_Operation.nOpState = FILETRANSFER_CWD;
  2385. }
  2386. }
  2387. else
  2388. {
  2389. ///////////
  2390. //Replies//
  2391. ///////////
  2392. int code = GetReplyCode();
  2393. switch(m_Operation.nOpState)
  2394. {
  2395. case FILETRANSFER_PWD:
  2396. if (code != 2 && code != 3)
  2397. {
  2398. nReplyError = FZ_REPLY_ERROR;
  2399. break;
  2400. }
  2401. pData->rawpwd = GetReply();
  2402. if ((m_mayBeMvsFilesystem || m_mayBeBS2000Filesystem) && m_CurrentServer.nServerType & FZ_SERVERTYPE_FTP &&
  2403. pData->rawpwd[0] != '/')
  2404. {
  2405. m_mayBeMvsFilesystem = false;
  2406. m_mayBeBS2000Filesystem = false;
  2407. if (m_mayBeBS2000Filesystem)
  2408. m_CurrentServer.nServerType |= FZ_SERVERTYPE_SUB_FTP_BS2000;
  2409. else
  2410. m_CurrentServer.nServerType |= FZ_SERVERTYPE_SUB_FTP_MVS;
  2411. pData->transferfile.remotepath.SetServer(m_CurrentServer);
  2412. }
  2413. if (!ParsePwdReply(pData->rawpwd))
  2414. return;
  2415. if (m_pOwner->GetCurrentPath() == pData->transferfile.remotepath)
  2416. {
  2417. #ifndef MPEXT_NO_CACHE
  2418. CDirectoryCache cache;
  2419. t_server server;
  2420. m_pOwner->GetCurrentServer(server);
  2421. t_directory dir;
  2422. BOOL res = cache.Lookup(pData->transferfile.remotepath,server,dir);
  2423. if (res)
  2424. {
  2425. CString remotefile = pData->transferfile.remotefile;
  2426. int i;
  2427. for (i = 0; i < dir.num; i++)
  2428. {
  2429. if (dir.direntry[i].name == remotefile &&
  2430. (dir.direntry[i].bUnsure || dir.direntry[i].size == -1))
  2431. {
  2432. m_Operation.nOpState = NeedModeCommand() ? FILETRANSFER_LIST_MODE : (NeedOptsCommand() ? FILETRANSFER_LIST_OPTS : FILETRANSFER_LIST_TYPE);
  2433. break;
  2434. }
  2435. }
  2436. if (i == dir.num)
  2437. {
  2438. SetDirectoryListing(&dir);
  2439. m_Operation.nOpState=FILETRANSFER_TYPE;
  2440. nReplyError = CheckOverwriteFile();
  2441. if (!nReplyError)
  2442. {
  2443. if (pData->transferfile.get)
  2444. {
  2445. CString path=pData->transferfile.localfile;
  2446. if (path.ReverseFind('\\')!=-1)
  2447. {
  2448. path=path.Left(path.ReverseFind('\\')+1);
  2449. CString path2;
  2450. while (path!="")
  2451. {
  2452. path2+=path.Left(path.Find( _T("\\") )+1);
  2453. path=path.Mid(path.Find(_T( "\\") )+1);
  2454. int res = CreateDirectory(path2, 0);
  2455. }
  2456. }
  2457. }
  2458. }
  2459. }
  2460. }
  2461. else
  2462. #endif
  2463. m_Operation.nOpState = NeedModeCommand() ? FILETRANSFER_LIST_MODE : (NeedOptsCommand() ? FILETRANSFER_LIST_OPTS : FILETRANSFER_LIST_TYPE);
  2464. }
  2465. else
  2466. m_Operation.nOpState = LIST_CWD;
  2467. break;
  2468. case FILETRANSFER_CWD:
  2469. if (code != 2 && code != 3)
  2470. if (pData->transferfile.get)
  2471. {
  2472. pData->bUseAbsolutePaths = TRUE;
  2473. m_Operation.nOpState = FILETRANSFER_NOLIST_SIZE;
  2474. }
  2475. else
  2476. m_Operation.nOpState = FILETRANSFER_MKD;
  2477. else
  2478. m_Operation.nOpState = FILETRANSFER_PWD2;
  2479. break;
  2480. case FILETRANSFER_MKD:
  2481. switch(pData->nMKDOpState)
  2482. {
  2483. case MKD_FINDPARENT:
  2484. {
  2485. if (code == 2 || code == 3)
  2486. {
  2487. m_pOwner->SetCurrentPath(pData->MKDCurrent);
  2488. #ifndef MPEXT_NO_CACHE
  2489. if (!m_pDirectoryListing)
  2490. {
  2491. CDirectoryCache cache;
  2492. t_directory dir;
  2493. BOOL res = cache.Lookup(pData->MKDCurrent, m_CurrentServer, dir, TRUE);
  2494. if (res)
  2495. SetDirectoryListing(&dir);
  2496. }
  2497. #endif
  2498. pData->nMKDOpState=MKD_CHANGETOSUBDIR;
  2499. pData->MKDCurrent.AddSubdir(pData->MKDSegments.front());
  2500. CString Segment=pData->MKDSegments.front();
  2501. pData->MKDSegments.pop_front();
  2502. if (!Send( _T("MKD ") + Segment))
  2503. return;
  2504. }
  2505. else
  2506. {
  2507. if (!pData->MKDCurrent.HasParent())
  2508. nReplyError = FZ_REPLY_ERROR | ((code == 5) ? FZ_REPLY_CRITICALERROR : 0);
  2509. else
  2510. {
  2511. pData->MKDSegments.push_front(pData->MKDCurrent.GetLastSegment());
  2512. pData->MKDCurrent=pData->MKDCurrent.GetParent();
  2513. if (!Send("CWD "+pData->MKDCurrent.GetPath()))
  2514. return;
  2515. }
  2516. }
  2517. }
  2518. break;
  2519. case MKD_MAKESUBDIRS:
  2520. {
  2521. if (code == 2 || code == 3)
  2522. { //Create dir entry in parent dir
  2523. ASSERT(!pData->MKDSegments.empty());
  2524. pData->MKDCurrent.AddSubdir(pData->MKDSegments.front());
  2525. CString Segment=pData->MKDSegments.front();
  2526. pData->MKDSegments.pop_front();
  2527. if (Send( _T("MKD ") + Segment))
  2528. pData->nMKDOpState=MKD_CHANGETOSUBDIR;
  2529. else
  2530. return;
  2531. }
  2532. else
  2533. nReplyError=FZ_REPLY_ERROR;
  2534. }
  2535. break;
  2536. case MKD_CHANGETOSUBDIR:
  2537. {
  2538. if (code == 2 || code == 3 || //Creation successful
  2539. m_RecvBuffer.front() == "550 Directory already exists") //Creation was successful, although someone else did the work for us
  2540. {
  2541. CServerPath path2 = pData->MKDCurrent;
  2542. if (path2.HasParent())
  2543. {
  2544. CString name=path2.GetLastSegment();
  2545. path2=path2.GetParent();
  2546. #ifndef MPEXT_NO_CACHE
  2547. CDirectoryCache cache;
  2548. cache.Lock();
  2549. t_directory dir;
  2550. BOOL bCached=TRUE;
  2551. BOOL res=cache.Lookup(path2,m_CurrentServer,dir);
  2552. if (!res)
  2553. bCached=FALSE;
  2554. #else
  2555. t_directory dir;
  2556. BOOL res=FALSE;
  2557. #endif
  2558. if (!res && m_pDirectoryListing)
  2559. {
  2560. if (m_pDirectoryListing->path==path2)
  2561. {
  2562. dir=*m_pDirectoryListing;
  2563. res=TRUE;
  2564. }
  2565. }
  2566. t_directory WorkingDir;
  2567. BOOL bFound=m_pOwner->GetWorkingDir(&WorkingDir);
  2568. if (!res && bFound)
  2569. if (WorkingDir.path==path2)
  2570. {
  2571. dir=WorkingDir;
  2572. res=TRUE;
  2573. }
  2574. if (!res)
  2575. {
  2576. dir.path=path2;
  2577. dir.server=m_CurrentServer;
  2578. }
  2579. int i;
  2580. for (i=0; i<dir.num; i++)
  2581. if (dir.direntry[i].name == name)
  2582. {
  2583. LogMessage(__FILE__, __LINE__, this, FZ_LOG_WARNING, _T("Dir already exists in cache!"));
  2584. break;
  2585. }
  2586. if (i==dir.num)
  2587. {
  2588. t_directory::t_direntry *entries = new t_directory::t_direntry[dir.num+1];
  2589. for (i=0;i<dir.num;i++)
  2590. entries[i]=dir.direntry[i];
  2591. entries[i].name=name;
  2592. entries[i].lName=name;
  2593. entries[i].lName.MakeLower();
  2594. entries[i].dir=TRUE;
  2595. entries[i].date.hasdate=FALSE;
  2596. entries[i].size=-1;
  2597. entries[i].bUnsure=FALSE;
  2598. delete [] dir.direntry;
  2599. dir.direntry=entries;
  2600. dir.num++;
  2601. #ifndef MPEXT_NO_CACHE
  2602. cache.Store(dir, bCached);
  2603. #endif
  2604. BOOL updated=FALSE;
  2605. if (m_pDirectoryListing && m_pDirectoryListing->path==dir.path)
  2606. {
  2607. updated=TRUE;
  2608. SetDirectoryListing(&dir);
  2609. }
  2610. if (!updated)
  2611. if (WorkingDir.path==dir.path)
  2612. {
  2613. updated=TRUE;
  2614. m_pOwner->SetWorkingDir(&dir);
  2615. }
  2616. }
  2617. #ifndef MPEXT_NO_CACHE
  2618. cache.Unlock();
  2619. #endif
  2620. }
  2621. }
  2622. //Continue operation even if MKD failed, maybe another thread did create this directory for us
  2623. if (pData->MKDSegments.empty())
  2624. m_Operation.nOpState=FILETRANSFER_CWD2;
  2625. else
  2626. {
  2627. if (Send( _T("CWD ") + pData->MKDCurrent.GetPath()))
  2628. pData->nMKDOpState=MKD_MAKESUBDIRS;
  2629. else
  2630. return;
  2631. }
  2632. }
  2633. break;
  2634. default:
  2635. ASSERT(FALSE);
  2636. }
  2637. break;
  2638. case FILETRANSFER_CWD2:
  2639. if (code != 2 && code != 3)
  2640. if (code == 4)
  2641. nReplyError=FZ_REPLY_ERROR;
  2642. else
  2643. nReplyError=FZ_REPLY_CRITICALERROR;
  2644. else
  2645. m_Operation.nOpState=FILETRANSFER_PWD2;
  2646. break;
  2647. case FILETRANSFER_PWD2:
  2648. if (code != 2 && code != 2)
  2649. nReplyError = FZ_REPLY_ERROR;
  2650. else
  2651. {
  2652. pData->rawpwd = GetReply();
  2653. if (!ParsePwdReply(pData->rawpwd))
  2654. return;
  2655. if (m_pOwner->GetCurrentPath() != pData->transferfile.remotepath)
  2656. {
  2657. #ifdef MPEXT
  2658. // More user-friendly message when the actual paths differ
  2659. if (m_pOwner->GetCurrentPath().GetPath() != pData->transferfile.remotepath.GetPath())
  2660. {
  2661. 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());
  2662. }
  2663. else
  2664. #endif
  2665. {
  2666. 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());
  2667. }
  2668. nReplyError = FZ_REPLY_CRITICALERROR;
  2669. }
  2670. else
  2671. {
  2672. #ifndef MPEXT_NO_CACHE
  2673. CDirectoryCache cache;
  2674. t_server server;
  2675. m_pOwner->GetCurrentServer(server);
  2676. t_directory dir;
  2677. BOOL res = cache.Lookup(pData->transferfile.remotepath, server,dir);
  2678. if (res)
  2679. {
  2680. CString remotefile = pData->transferfile.remotefile;
  2681. int i;
  2682. for (i = 0; i < dir.num; i++)
  2683. {
  2684. if (dir.direntry[i].name == remotefile &&
  2685. (dir.direntry[i].bUnsure || dir.direntry[i].size == -1))
  2686. {
  2687. m_Operation.nOpState = NeedModeCommand() ? FILETRANSFER_LIST_MODE : (NeedOptsCommand() ? FILETRANSFER_LIST_OPTS : FILETRANSFER_LIST_TYPE);
  2688. break;
  2689. }
  2690. }
  2691. if (i == dir.num)
  2692. {
  2693. SetDirectoryListing(&dir);
  2694. m_Operation.nOpState=FILETRANSFER_TYPE;
  2695. nReplyError=CheckOverwriteFile();
  2696. if (!nReplyError)
  2697. {
  2698. if (pData->transferfile.get)
  2699. {
  2700. CString path=pData->transferfile.localfile;
  2701. if (path.ReverseFind('\\')!=-1)
  2702. {
  2703. path=path.Left(path.ReverseFind('\\')+1);
  2704. CString path2;
  2705. while (path!="")
  2706. {
  2707. path2+=path.Left(path.Find( _T("\\") )+1);
  2708. path=path.Mid(path.Find( _T("\\") )+1);
  2709. CreateDirectory(path2, 0);
  2710. }
  2711. }
  2712. }
  2713. }
  2714. }
  2715. }
  2716. else
  2717. #endif
  2718. m_Operation.nOpState = NeedModeCommand() ? FILETRANSFER_LIST_MODE : (NeedOptsCommand() ? FILETRANSFER_LIST_OPTS : FILETRANSFER_LIST_TYPE);
  2719. }
  2720. }
  2721. break;
  2722. case FILETRANSFER_LIST_MODE:
  2723. #ifdef MPEXT_NO_ZLIB
  2724. ASSERT(false);
  2725. m_Operation.nOpState = FILETRANSFER_LIST_TYPE;
  2726. #else
  2727. if (code == 2 || code == 3)
  2728. m_useZlib = !m_useZlib;
  2729. m_Operation.nOpState = NeedOptsCommand() ? FILETRANSFER_LIST_OPTS : FILETRANSFER_LIST_TYPE;
  2730. #endif
  2731. break;
  2732. case FILETRANSFER_LIST_OPTS:
  2733. #ifdef MPEXT_NO_ZLIB
  2734. ASSERT(false);
  2735. #else
  2736. if (code == 2 || code == 3)
  2737. m_zlibLevel = pData->newZlibLevel;
  2738. m_Operation.nOpState = FILETRANSFER_LIST_TYPE;
  2739. #endif
  2740. break;
  2741. case FILETRANSFER_LIST_TYPE:
  2742. if (code != 2 && code != 3)
  2743. nReplyError = FZ_REPLY_ERROR;
  2744. else
  2745. m_Operation.nOpState = FILETRANSFER_LIST_PORTPASV;
  2746. break;
  2747. case FILETRANSFER_LIST_PORTPASV:
  2748. if (code!=3 && code!=2)
  2749. {
  2750. if (!pData->bTriedPortPasvOnce)
  2751. {
  2752. pData->bTriedPortPasvOnce = TRUE;
  2753. pData->bPasv = !pData->bPasv;
  2754. }
  2755. else
  2756. nReplyError=FZ_REPLY_ERROR;
  2757. break;
  2758. }
  2759. if (pData->bPasv)
  2760. {
  2761. CString reply = GetReply();
  2762. int i = reply.Find( _T("(") );
  2763. int j = j = reply.Find( _T(")") );
  2764. // extract connect port number and IP from string returned by server
  2765. if (i==-1 || j==-1 || (i+11)>=j)
  2766. {
  2767. if (!pData->bTriedPortPasvOnce)
  2768. {
  2769. pData->bTriedPortPasvOnce = TRUE;
  2770. pData->bPasv = !pData->bPasv;
  2771. }
  2772. else
  2773. nReplyError = FZ_REPLY_ERROR;
  2774. break;
  2775. }
  2776. CString temp;
  2777. temp = reply.Mid(i+1,(j-i)-1);
  2778. if (GetFamily() == AF_INET)
  2779. {
  2780. int count=0;
  2781. int pos=0;
  2782. //Convert commas to dots
  2783. temp.Replace( _T(","), _T(".") );
  2784. while(1)
  2785. {
  2786. pos=temp.Find(_T("."),pos);
  2787. if (pos!=-1)
  2788. count++;
  2789. else
  2790. break;
  2791. pos++;
  2792. }
  2793. if (count!=5)
  2794. {
  2795. if (!pData->bTriedPortPasvOnce)
  2796. {
  2797. pData->bTriedPortPasvOnce = TRUE;
  2798. pData->bPasv = !pData->bPasv;
  2799. }
  2800. else
  2801. nReplyError = FZ_REPLY_ERROR;
  2802. break;
  2803. }
  2804. i=temp.ReverseFind('.');
  2805. pData->port=atol( T2CA( temp.Right(temp.GetLength()-(i+1)) ) ); //get ls byte of server socket
  2806. temp=temp.Left(i);
  2807. i=temp.ReverseFind('.');
  2808. pData->port+=256*atol( T2CA( temp.Right(temp.GetLength()-(i+1)) ) ); // add ms byte to server socket
  2809. pData->host=temp.Left(i);
  2810. #ifdef MPEXT
  2811. if (!CheckForcePasvIp(pData->host))
  2812. {
  2813. nReplyError = FZ_REPLY_ERROR;
  2814. break;
  2815. }
  2816. #endif
  2817. }
  2818. else if (GetFamily() == AF_INET6)
  2819. {
  2820. temp = temp.Mid(3);
  2821. pData->port = atol( T2CA(temp.Left(temp.GetLength() - 1) ) );
  2822. if (pData->port < 0 || pData->port > 65535)
  2823. {
  2824. LogMessage(__FILE__, __LINE__, this, FZ_LOG_WARNING, _T("Port %u not valid"), pData->port);
  2825. nReplyError = FZ_REPLY_ERROR;
  2826. break;
  2827. }
  2828. unsigned int tmpPort;
  2829. if (!GetPeerName(pData->host, tmpPort))
  2830. {
  2831. LogMessage(__FILE__, __LINE__, this, FZ_LOG_WARNING, _T("GetPeerName failed"));
  2832. nReplyError = FZ_REPLY_ERROR;
  2833. break;
  2834. }
  2835. }
  2836. m_pTransferSocket = new CTransferSocket(this, CSMODE_LIST);
  2837. #ifndef MPEXT_NO_ZLIB
  2838. if (m_useZlib)
  2839. {
  2840. if (!m_pTransferSocket->InitZlib(m_zlibLevel))
  2841. {
  2842. ShowStatus("Failed to initialize zlib", 1);
  2843. ResetOperation(FZ_REPLY_ERROR);
  2844. return;
  2845. }
  2846. }
  2847. #endif
  2848. #ifndef MPEXT_NO_GSS
  2849. if (m_pGssLayer && m_pGssLayer->AuthSuccessful())
  2850. m_pTransferSocket->UseGSS(m_pGssLayer);
  2851. #endif
  2852. m_pTransferSocket->m_nInternalMessageID = m_pOwner->m_nInternalMessageID;
  2853. m_pTransferSocket->SetFamily(GetFamily());
  2854. if (!m_pTransferSocket->Create(
  2855. #ifndef MPEXT_NO_SSL
  2856. m_pSslLayer && m_bProtP
  2857. #endif
  2858. ))
  2859. {
  2860. nReplyError = FZ_REPLY_ERROR;
  2861. break;
  2862. }
  2863. VERIFY(m_pTransferSocket->AsyncSelect());
  2864. }
  2865. m_Operation.nOpState=FILETRANSFER_LIST_LIST;
  2866. break;
  2867. case FILETRANSFER_LIST_LIST:
  2868. if (IsMisleadingListResponse())
  2869. {
  2870. ShowStatus(IDS_STATUSMSG_DIRLISTSUCCESSFUL, 0);
  2871. t_directory listing;
  2872. listing.server = m_CurrentServer;
  2873. listing.path.SetServer(m_CurrentServer);
  2874. if (pData->rawpwd != "")
  2875. {
  2876. if (!listing.path.SetPath(pData->rawpwd))
  2877. {
  2878. delete m_pDirectoryListing;
  2879. m_pDirectoryListing = 0;
  2880. delete m_pTransferSocket;
  2881. m_pTransferSocket = 0;
  2882. ResetOperation(FZ_REPLY_ERROR);
  2883. return;
  2884. }
  2885. }
  2886. else
  2887. listing.path = pData->transferfile.remotepath;
  2888. #ifndef MPEXT_NO_CACHE
  2889. CDirectoryCache cache;
  2890. cache.Lock();
  2891. t_directory dir;
  2892. if (cache.Lookup(listing.path, listing.server, dir))
  2893. listing.Merge(dir, pData->ListStartTime);
  2894. cache.Store(listing);
  2895. cache.Unlock();
  2896. #endif
  2897. SetDirectoryListing(&listing);
  2898. m_Operation.nOpState = FILETRANSFER_TYPE;
  2899. delete m_pTransferSocket;
  2900. m_pTransferSocket = 0;
  2901. nReplyError = CheckOverwriteFile();
  2902. if (!nReplyError)
  2903. {
  2904. if (pData->transferfile.get)
  2905. {
  2906. CString path=pData->transferfile.localfile;
  2907. if (path.ReverseFind('\\')!=-1)
  2908. {
  2909. path=path.Left(path.ReverseFind('\\')+1);
  2910. CString path2;
  2911. while (path!="")
  2912. {
  2913. path2+=path.Left(path.Find( _T("\\") )+1);
  2914. path=path.Mid(path.Find( _T("\\") )+1);
  2915. CreateDirectory(path2, 0);
  2916. }
  2917. }
  2918. }
  2919. }
  2920. }
  2921. else if (code==4 || code==5) //LIST failed, try getting file information using SIZE and MDTM
  2922. {
  2923. if (m_pTransferSocket)
  2924. delete m_pTransferSocket;
  2925. m_pTransferSocket=0;
  2926. m_Operation.nOpState = FILETRANSFER_NOLIST_SIZE;
  2927. }
  2928. else if (code!=1)
  2929. nReplyError=FZ_REPLY_ERROR;
  2930. else
  2931. m_Operation.nOpState=FILETRANSFER_LIST_WAITFINISH;
  2932. break;
  2933. case FILETRANSFER_LIST_WAITFINISH:
  2934. if (!bFinish)
  2935. {
  2936. if (code!=2 && code!=3)
  2937. nReplyError=FZ_REPLY_ERROR;
  2938. else
  2939. pData->nGotTransferEndReply = 1;
  2940. }
  2941. if (pData->nGotTransferEndReply && pData->pDirectoryListing)
  2942. {
  2943. #ifndef MPEXT_NO_CACHE
  2944. CDirectoryCache cache;
  2945. t_directory dir;
  2946. cache.Lock();
  2947. if (cache.Lookup(pData->pDirectoryListing->path, pData->pDirectoryListing->server, dir, TRUE))
  2948. {
  2949. pData->pDirectoryListing->Merge(dir, pData->ListStartTime);
  2950. }
  2951. cache.Store(*pData->pDirectoryListing);
  2952. cache.Unlock();
  2953. #endif
  2954. SetDirectoryListing(pData->pDirectoryListing);
  2955. delete m_pTransferSocket;
  2956. m_pTransferSocket=0;
  2957. m_Operation.nOpState=FILETRANSFER_TYPE;
  2958. nReplyError = CheckOverwriteFile();
  2959. if (!nReplyError)
  2960. {
  2961. if (pData->transferfile.get)
  2962. {
  2963. CString path=pData->transferfile.localfile;
  2964. if (path.ReverseFind('\\')!=-1)
  2965. {
  2966. path=path.Left(path.ReverseFind('\\')+1);
  2967. CString path2;
  2968. while (path!="")
  2969. {
  2970. path2+=path.Left(path.Find( _T("\\") )+1);
  2971. path=path.Mid(path.Find( _T("\\") )+1);
  2972. CreateDirectory(path2, 0);
  2973. }
  2974. }
  2975. }
  2976. }
  2977. pData->nGotTransferEndReply=0;
  2978. }
  2979. break;
  2980. case FILETRANSFER_NOLIST_SIZE:
  2981. if (code==2)
  2982. {
  2983. CString line = GetReply();
  2984. if ( line.GetLength()>4 && line.Left(4) == _T("213 ") )
  2985. {
  2986. __int64 size=_ttoi64(line.Mid(4));
  2987. ASSERT(!pData->pFileSize);
  2988. pData->pFileSize=new _int64;
  2989. *pData->pFileSize=size;
  2990. }
  2991. }
  2992. m_Operation.nOpState=FILETRANSFER_NOLIST_MDTM;
  2993. break;
  2994. case FILETRANSFER_NOLIST_MDTM:
  2995. if (code==2)
  2996. {
  2997. CString line = GetReply();
  2998. if ( line.GetLength()>4 && line.Left(4) == _T("213 ") )
  2999. {
  3000. int y=0, M=0, d=0, h=0, m=0;
  3001. line=line.Mid(4);
  3002. y=_ttoi(line.Left(4));
  3003. if (y && line.GetLength()>4)
  3004. {
  3005. line=line.Mid(4);
  3006. M=_ttoi(line.Left(2));
  3007. if (M && line.GetLength()>2)
  3008. {
  3009. line=line.Mid(2);
  3010. d=_ttoi(line.Left(2));
  3011. if (d && line.GetLength()>2)
  3012. {
  3013. line=line.Mid(2);
  3014. h=_ttoi(line.Left(2));
  3015. if (h && line.GetLength()>2)
  3016. {
  3017. line=line.Mid(2);
  3018. m=_ttoi(line.Left(2));
  3019. if (m && line.GetLength()>2)
  3020. {
  3021. line=line.Mid(2);
  3022. }
  3023. }
  3024. }
  3025. if (M>0 && M<=12 && d>0 && d<=31 && h>=0 && h<24 && m>=0 && m<60)
  3026. {
  3027. if (pData->pFileTime)
  3028. delete pData->pFileTime;
  3029. TRY
  3030. {
  3031. pData->pFileTime = new CTime(y, M, d, h, m, 0);
  3032. }
  3033. CATCH_ALL(e)
  3034. {
  3035. TCHAR buffer[1024];
  3036. CString str =_T("Exception creating CTime object: ");
  3037. if (e->GetErrorMessage(buffer, 1024, NULL))
  3038. str += buffer;
  3039. else
  3040. str += _T("Unknown exception");
  3041. LogMessageRaw(__FILE__, __LINE__, this, FZ_LOG_WARNING, str);
  3042. pData->pFileTime = 0;
  3043. }
  3044. END_CATCH_ALL;
  3045. }
  3046. }
  3047. }
  3048. }
  3049. }
  3050. m_Operation.nOpState=FILETRANSFER_TYPE;
  3051. nReplyError=CheckOverwriteFile();
  3052. break;
  3053. case FILETRANSFER_TYPE:
  3054. if (code!=2 && code!=3)
  3055. nReplyError = FZ_REPLY_ERROR;
  3056. m_Operation.nOpState = NeedModeCommand() ? FILETRANSFER_MODE : (NeedOptsCommand() ? FILETRANSFER_OPTS : FILETRANSFER_PORTPASV);
  3057. break;
  3058. case FILETRANSFER_WAIT:
  3059. if (!pData->nWaitNextOpState)
  3060. nReplyError=FZ_REPLY_ERROR;
  3061. else
  3062. m_Operation.nOpState=pData->nWaitNextOpState;
  3063. break;
  3064. case FILETRANSFER_MODE:
  3065. #ifdef MPEXT_NO_ZLIB
  3066. ASSERT(false);
  3067. m_Operation.nOpState = FILETRANSFER_PORTPASV;
  3068. #else
  3069. if (code == 2 || code == 3)
  3070. m_useZlib = !m_useZlib;
  3071. m_Operation.nOpState = NeedOptsCommand() ? FILETRANSFER_OPTS : FILETRANSFER_PORTPASV;
  3072. #endif
  3073. break;
  3074. case FILETRANSFER_OPTS:
  3075. #ifdef MPEXT_NO_ZLIB
  3076. ASSERT(false);
  3077. #else
  3078. if (code == 2 || code == 3)
  3079. m_zlibLevel = pData->newZlibLevel;
  3080. #endif
  3081. m_Operation.nOpState = FILETRANSFER_PORTPASV;
  3082. break;
  3083. case FILETRANSFER_PORTPASV:
  3084. if (code == 3 || code == 2)
  3085. {
  3086. if (pData->bPasv)
  3087. {
  3088. CString reply = GetReply();
  3089. int i = reply.Find( _T("(") );
  3090. int j = j = reply.Find( _T(")") );
  3091. // extract connect port number and IP from string returned by server
  3092. if(i==-1 || j==-1 || (GetFamily() == AF_INET && (i+11) >= j))
  3093. {
  3094. if (!pData->bTriedPortPasvOnce)
  3095. {
  3096. pData->bTriedPortPasvOnce = TRUE;
  3097. pData->bPasv = !pData->bPasv;
  3098. }
  3099. else
  3100. nReplyError = FZ_REPLY_ERROR;
  3101. break;
  3102. }
  3103. CString temp;
  3104. temp = reply.Mid(i+1,(j-i)-1);
  3105. if (GetFamily() == AF_INET)
  3106. {
  3107. int count=0;
  3108. int pos=0;
  3109. //Convert commas to dots
  3110. temp.Replace( _T(","), _T(".") );
  3111. while(1)
  3112. {
  3113. pos=temp.Find( _T("."), pos);
  3114. if (pos!=-1)
  3115. count++;
  3116. else
  3117. break;
  3118. pos++;
  3119. }
  3120. if (count!=5)
  3121. {
  3122. if (!pData->bTriedPortPasvOnce)
  3123. {
  3124. pData->bTriedPortPasvOnce = TRUE;
  3125. pData->bPasv = !pData->bPasv;
  3126. }
  3127. else
  3128. nReplyError = FZ_REPLY_ERROR;
  3129. break;
  3130. }
  3131. i=temp.ReverseFind('.');
  3132. pData->port=atol( T2CA( temp.Right(temp.GetLength()-(i+1)) ) ); //get ls byte of server socket
  3133. temp=temp.Left(i);
  3134. i=temp.ReverseFind('.');
  3135. pData->port+=256*atol( T2CA( temp.Right(temp.GetLength()-(i+1)) ) ); // add ms byte to server socket
  3136. pData->host=temp.Left(i);
  3137. #ifdef MPEXT
  3138. if (!CheckForcePasvIp(pData->host))
  3139. {
  3140. nReplyError = FZ_REPLY_ERROR;
  3141. break;
  3142. }
  3143. #endif
  3144. }
  3145. else if (GetFamily() == AF_INET6)
  3146. {
  3147. temp = temp.Mid(3);
  3148. pData->port = atol( T2CA(temp.Left(temp.GetLength() - 1) ) );
  3149. if (pData->port < 0 || pData->port > 65535)
  3150. {
  3151. LogMessage(__FILE__, __LINE__, this, FZ_LOG_WARNING, _T("Port %u not valid"), pData->port);
  3152. nReplyError = FZ_REPLY_ERROR;
  3153. break;
  3154. }
  3155. unsigned int tmpPort;
  3156. if (!GetPeerName(pData->host, tmpPort))
  3157. {
  3158. LogMessage(__FILE__, __LINE__, this, FZ_LOG_WARNING, _T("GetPeerName failed"));
  3159. nReplyError = FZ_REPLY_ERROR;
  3160. break;
  3161. }
  3162. }
  3163. else
  3164. {
  3165. nReplyError = FZ_REPLY_ERROR;
  3166. break;
  3167. }
  3168. m_pTransferSocket = new CTransferSocket(this, m_Operation.nOpMode);
  3169. #ifndef MPEXT_NO_ZLIB
  3170. if (m_useZlib)
  3171. {
  3172. if (!m_pTransferSocket->InitZlib(m_zlibLevel))
  3173. {
  3174. ShowStatus("Failed to initialize zlib", 1);
  3175. ResetOperation(FZ_REPLY_ERROR);
  3176. return;
  3177. }
  3178. }
  3179. #endif
  3180. #ifndef MPEXT_NO_GSS
  3181. if (m_pGssLayer && m_pGssLayer->AuthSuccessful())
  3182. m_pTransferSocket->UseGSS(m_pGssLayer);
  3183. #endif
  3184. m_pTransferSocket->m_nInternalMessageID = m_pOwner->m_nInternalMessageID;
  3185. m_pTransferSocket->SetFamily(GetFamily());
  3186. if (!m_pTransferSocket->Create(
  3187. #ifndef MPEXT_NO_SSL
  3188. m_pSslLayer && m_bProtP
  3189. #endif
  3190. ))
  3191. {
  3192. nReplyError = FZ_REPLY_ERROR;
  3193. break;
  3194. }
  3195. VERIFY(m_pTransferSocket->AsyncSelect());
  3196. }
  3197. if (pData->transferdata.bResume && pData->transferfile.get)
  3198. m_Operation.nOpState = FILETRANSFER_REST;
  3199. else
  3200. m_Operation.nOpState = FILETRANSFER_RETRSTOR;
  3201. BOOL res = FALSE;
  3202. if (!m_pDataFile)
  3203. m_pDataFile = new CFile;
  3204. if (pData->transferfile.get)
  3205. {
  3206. if (pData->transferdata.bResume)
  3207. res = m_pDataFile->Open(pData->transferfile.localfile,CFile::modeCreate|CFile::modeWrite|CFile::modeNoTruncate|CFile::shareDenyWrite);
  3208. else
  3209. res = m_pDataFile->Open(pData->transferfile.localfile,CFile::modeWrite|CFile::modeCreate|CFile::shareDenyWrite);
  3210. }
  3211. else
  3212. #ifdef MPEXT
  3213. res = m_pDataFile->Open(pData->transferfile.localfile,CFile::modeRead|CFile::shareDenyNone);
  3214. #else
  3215. res = m_pDataFile->Open(pData->transferfile.localfile,CFile::modeRead|CFile::shareDenyWrite);
  3216. #endif
  3217. if (!res)
  3218. {
  3219. //Error opening the file
  3220. CString str;
  3221. str.Format(IDS_ERRORMSG_FILEOPENFAILED,pData->transferfile.localfile);
  3222. ShowStatus(str,1);
  3223. nReplyError = FZ_REPLY_ERROR;
  3224. break;
  3225. }
  3226. if (!m_pTransferSocket)
  3227. {
  3228. nReplyError=FZ_REPLY_ERROR;
  3229. break;
  3230. }
  3231. m_pTransferSocket->m_pFile = m_pDataFile;
  3232. if (!pData->transferfile.get)
  3233. {
  3234. pData->transferdata.transfersize=GetLength64(*m_pDataFile);
  3235. pData->transferdata.transferleft=pData->transferdata.transfersize;
  3236. if (pData->transferdata.bResume)
  3237. {
  3238. CString remotefile=pData->transferfile.remotefile;
  3239. if (m_pDirectoryListing)
  3240. for (int i = 0; i < m_pDirectoryListing->num; i++)
  3241. {
  3242. if (m_pDirectoryListing->direntry[i].name == remotefile)
  3243. {
  3244. pData->transferdata.transferleft -= m_pDirectoryListing->direntry[i].size;
  3245. break;
  3246. }
  3247. }
  3248. _int64 size = pData->transferdata.transfersize-pData->transferdata.transferleft;
  3249. LONG low = static_cast<LONG>(size&0xFFFFFFFF);
  3250. LONG high = static_cast<LONG>(size>>32);
  3251. if (SetFilePointer((HANDLE)m_pDataFile->m_hFile, low, &high, FILE_BEGIN)==0xFFFFFFFF && GetLastError()!=NO_ERROR)
  3252. {
  3253. ShowStatus(IDS_ERRORMSG_SETFILEPOINTER, 1);
  3254. nReplyError = FZ_REPLY_ERROR;
  3255. }
  3256. }
  3257. }
  3258. else
  3259. {
  3260. pData->transferdata.transfersize=-1;
  3261. CString remotefile=pData->transferfile.remotefile;
  3262. if (m_pDirectoryListing)
  3263. for (int i=0; i<m_pDirectoryListing->num; i++)
  3264. {
  3265. if (m_pDirectoryListing->direntry[i].name==remotefile)
  3266. {
  3267. if (pData->pFileTime)
  3268. {
  3269. delete pData->pFileTime;
  3270. pData->pFileTime = 0;
  3271. }
  3272. t_directory::t_direntry::t_date *pDate=&m_pDirectoryListing->direntry[i].date;
  3273. if (pDate->hasdate)
  3274. {
  3275. TRY
  3276. {
  3277. if (pDate->hastime)
  3278. pData->pFileTime = new CTime(pDate->year, pDate->month, pDate->day, pDate->hour, pDate->minute, 0);
  3279. else
  3280. pData->pFileTime = new CTime(pDate->year, pDate->month, pDate->day, 0, 0, 0);
  3281. TIME_ZONE_INFORMATION tzInfo = {0};
  3282. BOOL res = GetTimeZoneInformation(&tzInfo);
  3283. CTimeSpan span(0, 0, tzInfo.Bias + ((res == TIME_ZONE_ID_DAYLIGHT) ? tzInfo.DaylightBias : tzInfo.StandardBias), 0);
  3284. *pData->pFileTime += span;
  3285. }
  3286. CATCH_ALL(e)
  3287. {
  3288. TCHAR buffer[1024];
  3289. CString str =_T("Exception creating CTime object: ");
  3290. if (e->GetErrorMessage(buffer, 1024, NULL))
  3291. str += buffer;
  3292. else
  3293. str += _T("Unknown exception");
  3294. LogMessageRaw(__FILE__, __LINE__, this, FZ_LOG_WARNING, str);
  3295. pData->pFileTime = 0;
  3296. }
  3297. END_CATCH_ALL;
  3298. }
  3299. pData->transferdata.transfersize=m_pDirectoryListing->direntry[i].size;
  3300. }
  3301. }
  3302. else if (pData->pFileSize)
  3303. pData->transferdata.transfersize=*pData->pFileSize;
  3304. pData->transferdata.transferleft=pData->transferdata.transfersize;
  3305. }
  3306. }
  3307. else
  3308. if (!pData->bTriedPortPasvOnce)
  3309. {
  3310. pData->bTriedPortPasvOnce = TRUE;
  3311. pData->bPasv = !pData->bPasv;
  3312. }
  3313. else
  3314. nReplyError = FZ_REPLY_ERROR;
  3315. break;
  3316. case FILETRANSFER_REST:
  3317. { //Resume
  3318. if (code==3 || code==2)
  3319. {
  3320. LONG high = 0;
  3321. pData->transferdata.transferleft = pData->transferdata.transfersize - GetLength64(*m_pDataFile);
  3322. if (SetFilePointer((HANDLE)m_pDataFile->m_hFile, 0, &high, FILE_END)==0xFFFFFFFF && GetLastError()!=NO_ERROR)
  3323. {
  3324. ShowStatus(IDS_ERRORMSG_SETFILEPOINTER, 1);
  3325. nReplyError = FZ_REPLY_ERROR;
  3326. }
  3327. else
  3328. m_Operation.nOpState = FILETRANSFER_RETRSTOR;
  3329. }
  3330. else
  3331. {
  3332. if (code==5 && GetReply()[1]=='0')
  3333. {
  3334. if (pData->transferdata.transfersize!=-1 && pData->transferfile.get)
  3335. {
  3336. ASSERT(m_pDataFile);
  3337. if (GetLength64(*m_pDataFile) == pData->transferdata.transfersize)
  3338. {
  3339. ShowStatus(IDS_ERRORMSG_CANTRESUME_FINISH, 0);
  3340. ResetOperation(FZ_REPLY_OK);
  3341. return;
  3342. }
  3343. }
  3344. ShowStatus(IDS_ERRORMSG_CANTRESUME, 1);
  3345. pData->transferdata.transferleft=pData->transferdata.transfersize;
  3346. pData->transferdata.bResume=FALSE;
  3347. m_Operation.nOpState=FILETRANSFER_RETRSTOR;
  3348. }
  3349. else
  3350. nReplyError=FZ_REPLY_ERROR;
  3351. }
  3352. }
  3353. break;
  3354. case FILETRANSFER_RETRSTOR:
  3355. // A '1xy opening data connection' reply is expected if RETR/STOR/APPE
  3356. // is successful.
  3357. // On failure, it's a 4xy or 5xy reply.
  3358. // However, some servers send a 2xy transfer complete reply without opening a data
  3359. // connection if there's no data to send.
  3360. if (code==2)
  3361. {
  3362. //Transfer successful, however server did not open data connection
  3363. ResetOperation(FZ_REPLY_OK);
  3364. return;
  3365. }
  3366. else if (code!=1)
  3367. {
  3368. if (!pData->transferfile.get && pData->transferdata.bResume && pData->askOnResumeFail)
  3369. {
  3370. pData->askOnResumeFail = false;
  3371. delete m_pTransferSocket;
  3372. m_pTransferSocket = 0;
  3373. delete m_pDataFile;
  3374. m_pDataFile = 0;
  3375. pData->nGotTransferEndReply = 0;
  3376. nReplyError = CheckOverwriteFile();
  3377. }
  3378. else
  3379. {
  3380. nReplyError = FZ_REPLY_ERROR;
  3381. if (code == 5)
  3382. nReplyError |= FZ_REPLY_CRITICALERROR;
  3383. }
  3384. }
  3385. else
  3386. {
  3387. m_Operation.nOpState=FILETRANSFER_WAITFINISH;
  3388. //Look if we can find any information about the resume offset
  3389. if (!pData->transferfile.get && pData->transferdata.bResume)
  3390. {
  3391. _int64 nOffset = -1;
  3392. CString reply = GetReply();
  3393. reply.MakeLower();
  3394. int pos = reply.Find(_T("restarting at offset "));
  3395. if (pos != -1)
  3396. pos += _tcslen(_T("restarting at offset "));
  3397. reply = reply.Mid(pos);
  3398. int i;
  3399. for (i=0; i<reply.GetLength(); i++)
  3400. {
  3401. if (reply[i] < '0' || reply[i] > '9')
  3402. break;
  3403. }
  3404. if (i == reply.GetLength())
  3405. nOffset = _ttoi64(reply);
  3406. if (nOffset != -1 && m_pDataFile)
  3407. {
  3408. LONG low = 0;
  3409. LONG high = 0;
  3410. if (nOffset >= GetLength64(*m_pDataFile))
  3411. if (SetFilePointer((HANDLE)m_pDataFile->m_hFile, 0, &high, FILE_END)==0xFFFFFFFF && GetLastError()!=NO_ERROR)
  3412. {
  3413. ShowStatus(IDS_ERRORMSG_SETFILEPOINTER, 1);
  3414. nReplyError = FZ_REPLY_ERROR;
  3415. }
  3416. else
  3417. {
  3418. low=static_cast<LONG>(nOffset&0xFFFFFFFF);
  3419. high=static_cast<LONG>(nOffset>>32);
  3420. if (SetFilePointer((HANDLE)m_pDataFile->m_hFile, low, &high, FILE_BEGIN)==0xFFFFFFFF && GetLastError()!=NO_ERROR)
  3421. {
  3422. ShowStatus(IDS_ERRORMSG_SETFILEPOINTER, 1);
  3423. nReplyError = FZ_REPLY_ERROR;
  3424. }
  3425. }
  3426. }
  3427. if (!nReplyError)
  3428. m_pTransferSocket->SetActive();
  3429. }
  3430. else if (pData->bPasv)
  3431. m_pTransferSocket->SetActive();
  3432. }
  3433. break;
  3434. case FILETRANSFER_WAITFINISH:
  3435. if (!bFinish)
  3436. {
  3437. if (code == 1)
  3438. {
  3439. /* Some non-rfc959 compatible servers send more than one code 1yz reply, especially if using APPE.
  3440. * Just ignore the additional ones.
  3441. */
  3442. LogMessage(FZ_LOG_WARNING, _T("Server sent more than one code 1yz reply, ignoring additional reply"));
  3443. break;
  3444. }
  3445. else if (code!=2 && code!=3)
  3446. nReplyError = FZ_REPLY_ERROR;
  3447. else
  3448. {
  3449. pData->nGotTransferEndReply |= 1;
  3450. }
  3451. }
  3452. if (pData->nGotTransferEndReply==3)
  3453. {
  3454. if (COptions::GetOptionVal(OPTION_PRESERVEDOWNLOADFILETIME) && m_pDataFile)
  3455. {
  3456. if (pData->pFileTime)
  3457. {
  3458. SYSTEMTIME stime;
  3459. FILETIME ftime;
  3460. if (pData->pFileTime->GetAsSystemTime(stime))
  3461. if (SystemTimeToFileTime(&stime, &ftime))
  3462. SetFileTime((HANDLE)m_pDataFile->m_hFile, &ftime, &ftime, &ftime);
  3463. }
  3464. }
  3465. #ifdef MPEXT
  3466. if (!pData->transferfile.get &&
  3467. COptions::GetOptionVal(OPTION_MPEXT_PRESERVEUPLOADFILETIME) && m_pDataFile &&
  3468. m_hasMfmtCmd)
  3469. {
  3470. CString filename =
  3471. pData->transferfile.remotepath.FormatFilename(pData->transferfile.remotefile, !pData->bUseAbsolutePaths);
  3472. CFileStatus64 status;
  3473. if (GetStatus64(pData->transferfile.localfile, status) &&
  3474. status.m_has_mtime)
  3475. {
  3476. struct tm tm;
  3477. status.m_mtime.GetGmtTm(&tm);
  3478. CString timestr;
  3479. timestr.Format("%02d%02d%02d%02d%02d%02d",
  3480. 1900 + tm.tm_year, 1 + tm.tm_mon, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);
  3481. if (Send( _T("MFMT ") + timestr + _T(" ") + filename))
  3482. {
  3483. m_Operation.nOpState = FILETRANSFER_MFMT;
  3484. return;
  3485. }
  3486. }
  3487. }
  3488. #endif
  3489. //Transfer successful
  3490. ResetOperation(FZ_REPLY_OK);
  3491. return;
  3492. }
  3493. break;
  3494. #ifdef MPEXT
  3495. case FILETRANSFER_MFMT:
  3496. //Transfer successful
  3497. ResetOperation(FZ_REPLY_OK);
  3498. break;
  3499. #endif
  3500. }
  3501. if (nReplyError)
  3502. { //Error transferring the file
  3503. ResetOperation(nReplyError);
  3504. return;
  3505. }
  3506. }
  3507. /////////////////
  3508. //Send commands//
  3509. /////////////////
  3510. BOOL bError=FALSE;
  3511. switch(m_Operation.nOpState)
  3512. {
  3513. case FILETRANSFER_PWD:
  3514. if (!Send("PWD"))
  3515. bError = TRUE;
  3516. break;
  3517. case FILETRANSFER_CWD:
  3518. if (!Send("CWD "+pData->transferfile.remotepath.GetPath()))
  3519. bError=TRUE;
  3520. break;
  3521. case FILETRANSFER_MKD:
  3522. if (pData->nMKDOpState==MKD_INIT)
  3523. {
  3524. if (!pData->transferfile.remotepath.HasParent())
  3525. {
  3526. LogMessage(__FILE__, __LINE__, this,FZ_LOG_WARNING, _T("Can't create root dir"));
  3527. ResetOperation(FZ_REPLY_CRITICALERROR);
  3528. return;
  3529. }
  3530. if (!Send("CWD "+pData->transferfile.remotepath.GetParent().GetPath()))
  3531. bError=TRUE;
  3532. pData->MKDCurrent=pData->transferfile.remotepath.GetParent();
  3533. pData->MKDSegments.push_front(pData->transferfile.remotepath.GetLastSegment());
  3534. pData->nMKDOpState=MKD_FINDPARENT;
  3535. }
  3536. break;
  3537. case FILETRANSFER_CWD2:
  3538. if (!Send("CWD "+pData->transferfile.remotepath.GetPath()))
  3539. bError=TRUE;
  3540. break;
  3541. case FILETRANSFER_PWD2:
  3542. if (!Send("PWD"))
  3543. bError=TRUE;
  3544. break;
  3545. case FILETRANSFER_LIST_MODE:
  3546. #ifdef MPEXT_NO_ZLIB
  3547. ASSERT(false);
  3548. #else
  3549. if (m_useZlib)
  3550. {
  3551. if (!Send("MODE S"))
  3552. bError = TRUE;
  3553. }
  3554. else
  3555. if (!Send("MODE Z"))
  3556. bError = TRUE;
  3557. #endif
  3558. break;
  3559. case FILETRANSFER_LIST_OPTS:
  3560. #ifdef MPEXT_NO_ZLIB
  3561. ASSERT(false);
  3562. #else
  3563. {
  3564. pData->newZlibLevel = COptions::GetOptionVal(OPTION_MODEZ_LEVEL);
  3565. CString str;
  3566. str.Format(_T("OPTS MODE Z LEVEL %d"), pData->newZlibLevel);
  3567. if (!Send(str))
  3568. bError = TRUE;
  3569. }
  3570. #endif
  3571. break;
  3572. case FILETRANSFER_LIST_PORTPASV:
  3573. delete m_pDirectoryListing;
  3574. m_pDirectoryListing=0;
  3575. if (pData->bPasv)
  3576. {
  3577. if (!Send((GetFamily() == AF_INET) ? "PASV" : "EPSV"))
  3578. bError=TRUE;
  3579. }
  3580. else
  3581. {
  3582. if (m_pTransferSocket)
  3583. {
  3584. LogMessage(__FILE__, __LINE__, this, FZ_LOG_WARNING, _T("m_pTransferSocket != 0"));
  3585. delete m_pTransferSocket;
  3586. }
  3587. m_pTransferSocket = new CTransferSocket(this, CSMODE_LIST);
  3588. #ifndef MPEXT_NO_ZLIB
  3589. if (m_useZlib)
  3590. {
  3591. if (!m_pTransferSocket->InitZlib(m_zlibLevel))
  3592. {
  3593. ShowStatus("Failed to initialize zlib", 1);
  3594. ResetOperation(FZ_REPLY_ERROR);
  3595. return;
  3596. }
  3597. }
  3598. #endif
  3599. #ifndef MPEXT_NO_GSS
  3600. if (m_pGssLayer && m_pGssLayer->AuthSuccessful())
  3601. m_pTransferSocket->UseGSS(m_pGssLayer);
  3602. #endif
  3603. m_pTransferSocket->m_nInternalMessageID = m_pOwner->m_nInternalMessageID;
  3604. m_pTransferSocket->m_bListening = TRUE;
  3605. m_pTransferSocket->SetFamily(GetFamily());
  3606. if(!m_pTransferSocket->Create(
  3607. #ifndef MPEXT_NO_SSL
  3608. m_pSslLayer && m_bProtP
  3609. #endif
  3610. ) || !m_pTransferSocket->AsyncSelect())
  3611. bError=TRUE;
  3612. else if (m_pProxyLayer)
  3613. {
  3614. SOCKADDR_IN addr;
  3615. int len=sizeof(addr);
  3616. if (!m_pProxyLayer->GetPeerName((SOCKADDR *)&addr,&len))
  3617. {
  3618. ShowStatus(IDS_ERRORMSG_CANTGETLIST,1);
  3619. bError=TRUE;
  3620. }
  3621. else if (!m_pTransferSocket->Listen(addr.sin_addr.S_un.S_addr))
  3622. {
  3623. ShowStatus(IDS_ERRORMSG_CANTGETLIST,1);
  3624. bError=TRUE;
  3625. }
  3626. //Don't send PORT command yet, params are unknown.
  3627. //will be sent in TransfersocketListenFinished
  3628. }
  3629. else
  3630. {
  3631. //Set up an active file transfer
  3632. CString temp;
  3633. UINT nPort;
  3634. if (//create listen socket (let Windows choose the port) & start listening
  3635. !m_pTransferSocket->Listen() ||
  3636. !m_pTransferSocket->GetSockName(temp, nPort))
  3637. {
  3638. bError = TRUE;
  3639. break;
  3640. }
  3641. CString host;
  3642. if (GetFamily() == AF_INET)
  3643. {
  3644. host = COptions::GetOption(OPTION_TRANSFERIP);
  3645. if (host != "")
  3646. {
  3647. DWORD ip = inet_addr(T2CA(host));
  3648. if (ip != INADDR_NONE)
  3649. host.Format(_T("%d,%d,%d,%d"), ip%256, (ip>>8)%256, (ip>>16)%256, ip>>24);
  3650. else
  3651. {
  3652. hostent *fullname = gethostbyname(T2CA(host));
  3653. if (!fullname)
  3654. host = "";
  3655. else
  3656. {
  3657. DWORD ip = ((LPIN_ADDR)fullname->h_addr)->s_addr;
  3658. if (ip != INADDR_NONE)
  3659. host.Format(_T("%d,%d,%d,%d"), ip%256, (ip>>8)%256, (ip>>16)%256, ip>>24);
  3660. else
  3661. host = "";
  3662. }
  3663. }
  3664. }
  3665. if (host == "")
  3666. {
  3667. UINT temp;
  3668. if (!GetSockName(host, temp))
  3669. {
  3670. bError = true;
  3671. break;
  3672. }
  3673. host.Replace('.', ',');
  3674. }
  3675. if (!bError)
  3676. {
  3677. host.Format(host+",%d,%d", nPort/256, nPort%256);
  3678. if (!Send(_T("PORT ") + host)) // send PORT cmd to server
  3679. bError = TRUE;
  3680. }
  3681. }
  3682. else if (GetFamily() == AF_INET6)
  3683. {
  3684. host = COptions::GetOption(OPTION_TRANSFERIP6);
  3685. if (host != "")
  3686. {
  3687. USES_CONVERSION;
  3688. addrinfo hints, *res;
  3689. memset(&hints, 0, sizeof(addrinfo));
  3690. hints.ai_family = AF_INET6;
  3691. hints.ai_socktype = SOCK_STREAM;
  3692. if (!p_getaddrinfo(T2CA(host), "1024", &hints, &res))
  3693. {
  3694. host = Inet6AddrToString(((SOCKADDR_IN6 *)res->ai_addr)->sin6_addr);
  3695. p_freeaddrinfo(res);
  3696. }
  3697. else
  3698. host = _T("");
  3699. }
  3700. if (host == "")
  3701. {
  3702. UINT temp;
  3703. if(!GetSockName(host, temp))
  3704. bError = true;
  3705. }
  3706. if (!bError)
  3707. {
  3708. // assamble EPRT command
  3709. CString cmd;
  3710. cmd.Format(_T("EPRT |2|") + host + "|%d|", nPort);
  3711. if (!Send(cmd))
  3712. bError = TRUE;
  3713. }
  3714. }
  3715. else
  3716. {
  3717. LogMessage(__FILE__, __LINE__, this, FZ_LOG_WARNING, _T("Protocol %d not supported"), GetFamily());
  3718. bError = true;
  3719. }
  3720. }
  3721. }
  3722. break;
  3723. case FILETRANSFER_LIST_TYPE:
  3724. if (!Send("TYPE A"))
  3725. bError=TRUE;
  3726. break;
  3727. case FILETRANSFER_LIST_LIST:
  3728. {
  3729. if (!m_pTransferSocket)
  3730. {
  3731. LogMessage(__FILE__, __LINE__, this,FZ_LOG_APIERROR, _T("Error: m_pTransferSocket==NULL") );
  3732. ResetOperation(FZ_REPLY_ERROR);
  3733. return;
  3734. }
  3735. m_pTransferSocket->SetActive();
  3736. pData->ListStartTime=CTime::GetCurrentTime();
  3737. CString cmd="LIST";
  3738. #ifdef MPEXT
  3739. 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)))
  3740. #else
  3741. 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)))
  3742. #endif
  3743. cmd += " -a";
  3744. if(!Send(cmd))
  3745. bError=TRUE;
  3746. else if(pData->bPasv)
  3747. {
  3748. // if PASV create the socket & initiate outbound data channel connection
  3749. if (!m_pTransferSocket->Connect(pData->host,pData->port))
  3750. {
  3751. if (GetLastError()!=WSAEWOULDBLOCK)
  3752. {
  3753. bError=TRUE;
  3754. ShowStatus(IDS_ERRORMSG_CANTGETLIST,1);
  3755. }
  3756. }
  3757. }
  3758. }
  3759. break;
  3760. case FILETRANSFER_NOLIST_SIZE:
  3761. {
  3762. CString command = _T("SIZE ");
  3763. command += pData->transferfile.remotepath.FormatFilename(pData->transferfile.remotefile, !pData->bUseAbsolutePaths);
  3764. if (!Send(command))
  3765. bError=TRUE;
  3766. }
  3767. break;
  3768. case FILETRANSFER_NOLIST_MDTM:
  3769. {
  3770. CString command = _T("MDTM ");
  3771. command += pData->transferfile.remotepath.FormatFilename(pData->transferfile.remotefile, !pData->bUseAbsolutePaths);
  3772. if (!Send(command))
  3773. bError=TRUE;
  3774. }
  3775. break;
  3776. case FILETRANSFER_TYPE:
  3777. if (pData->transferfile.nType==1)
  3778. {
  3779. if (!Send("TYPE A"))
  3780. bError=TRUE;
  3781. }
  3782. else
  3783. if (!Send("TYPE I"))
  3784. bError=TRUE;
  3785. break;
  3786. case FILETRANSFER_MODE:
  3787. #ifdef MPEXT_NO_ZLIB
  3788. ASSERT(false);
  3789. #else
  3790. if (m_useZlib)
  3791. {
  3792. if (!Send("MODE S"))
  3793. bError = TRUE;
  3794. }
  3795. else
  3796. if (!Send("MODE Z"))
  3797. bError = TRUE;
  3798. #endif
  3799. break;
  3800. case FILETRANSFER_OPTS:
  3801. #ifdef MPEXT_NO_ZLIB
  3802. ASSERT(false);
  3803. #else
  3804. {
  3805. pData->newZlibLevel = COptions::GetOptionVal(OPTION_MODEZ_LEVEL);
  3806. CString str;
  3807. str.Format(_T("OPTS MODE Z LEVEL %d"), pData->newZlibLevel);
  3808. if (!Send(str))
  3809. bError = TRUE;
  3810. }
  3811. #endif
  3812. break;
  3813. case FILETRANSFER_PORTPASV:
  3814. if (pData->bPasv)
  3815. {
  3816. if (!Send((GetFamily() == AF_INET) ? "PASV" : "EPSV"))
  3817. bError=TRUE;
  3818. }
  3819. else
  3820. {
  3821. if (m_pTransferSocket)
  3822. {
  3823. LogMessage(__FILE__, __LINE__, this, FZ_LOG_WARNING, _T("m_pTransferSocket != 0"));
  3824. delete m_pTransferSocket;
  3825. }
  3826. m_pTransferSocket=new CTransferSocket(this, m_Operation.nOpMode);
  3827. #ifndef MPEXT_NO_ZLIB
  3828. if (m_useZlib)
  3829. {
  3830. if (!m_pTransferSocket->InitZlib(m_zlibLevel))
  3831. {
  3832. ShowStatus("Failed to initialize zlib", 1);
  3833. ResetOperation(FZ_REPLY_ERROR);
  3834. return;
  3835. }
  3836. }
  3837. #endif
  3838. #ifndef MPEXT_NO_GSS
  3839. if (m_pGssLayer && m_pGssLayer->AuthSuccessful())
  3840. m_pTransferSocket->UseGSS(m_pGssLayer);
  3841. #endif
  3842. m_pTransferSocket->m_nInternalMessageID=m_pOwner->m_nInternalMessageID;
  3843. m_pTransferSocket->m_bListening = TRUE;
  3844. m_pTransferSocket->SetFamily(GetFamily());
  3845. if(!m_pTransferSocket->Create(
  3846. #ifndef MPEXT_NO_SSL
  3847. m_pSslLayer && m_bProtP
  3848. #endif
  3849. ) || !m_pTransferSocket->AsyncSelect())
  3850. bError = TRUE;
  3851. else if (m_pProxyLayer)
  3852. {
  3853. SOCKADDR_IN addr;
  3854. int len=sizeof(addr);
  3855. if (!m_pProxyLayer->GetPeerName((SOCKADDR *)&addr,&len))
  3856. {
  3857. ShowStatus(IDS_ERRORMSG_CANTGETLIST,1);
  3858. bError=TRUE;
  3859. }
  3860. else if (!m_pTransferSocket->Listen(addr.sin_addr.S_un.S_addr))
  3861. {
  3862. ShowStatus(IDS_ERRORMSG_CANTGETLIST,1);
  3863. bError=TRUE;
  3864. }
  3865. //Don't send PORT command yet, params are unknown.
  3866. //will be sent in TransfersocketListenFinished
  3867. }
  3868. else
  3869. {
  3870. //Set up an active file transfer
  3871. CString temp;
  3872. UINT nPort;
  3873. if (//create listen socket (let Windows choose the port) & start listening
  3874. !m_pTransferSocket->Listen() ||
  3875. !m_pTransferSocket->GetSockName(temp, nPort))
  3876. {
  3877. bError = TRUE;
  3878. break;
  3879. }
  3880. CString host;
  3881. if (GetFamily() == AF_INET)
  3882. {
  3883. host = COptions::GetOption(OPTION_TRANSFERIP);
  3884. if (host != "")
  3885. {
  3886. DWORD ip = inet_addr(T2CA(host));
  3887. if (ip != INADDR_NONE)
  3888. host.Format(_T("%d,%d,%d,%d"), ip%256, (ip>>8)%256, (ip>>16)%256, ip>>24);
  3889. else
  3890. {
  3891. hostent *fullname = gethostbyname(T2CA(host));
  3892. if (!fullname)
  3893. host = "";
  3894. else
  3895. {
  3896. DWORD ip = ((LPIN_ADDR)fullname->h_addr)->s_addr;
  3897. if (ip != INADDR_NONE)
  3898. host.Format(_T("%d,%d,%d,%d"), ip%256, (ip>>8)%256, (ip>>16)%256, ip>>24);
  3899. else
  3900. host = "";
  3901. }
  3902. }
  3903. }
  3904. if (host == "")
  3905. {
  3906. UINT temp;
  3907. if (!GetSockName(host, temp))
  3908. bError = true;
  3909. host.Replace('.', ',');
  3910. }
  3911. if (!bError)
  3912. {
  3913. host.Format(host+",%d,%d", nPort/256, nPort%256);
  3914. if (!Send(_T("PORT ") + host)) // send PORT cmd to server
  3915. bError = TRUE;
  3916. }
  3917. }
  3918. else if (GetFamily() == AF_INET6)
  3919. {
  3920. host = COptions::GetOption(OPTION_TRANSFERIP6);
  3921. if (host != "")
  3922. {
  3923. USES_CONVERSION;
  3924. addrinfo hints, *res;
  3925. memset(&hints, 0, sizeof(addrinfo));
  3926. hints.ai_family = AF_INET6;
  3927. hints.ai_socktype = SOCK_STREAM;
  3928. if (!p_getaddrinfo(T2CA(host), "1024", &hints, &res))
  3929. {
  3930. host = Inet6AddrToString(((SOCKADDR_IN6 *)res->ai_addr)->sin6_addr);
  3931. p_freeaddrinfo(res);
  3932. }
  3933. else
  3934. host = _T("");
  3935. }
  3936. if (host == "")
  3937. {
  3938. UINT temp;
  3939. if(!GetSockName(host, temp))
  3940. bError = true;
  3941. }
  3942. if (!bError)
  3943. {
  3944. // assamble EPRT command
  3945. CString cmd;
  3946. cmd.Format(_T("EPRT |2|") + host + "|%d|", nPort);
  3947. if (!Send(cmd))
  3948. bError = TRUE;
  3949. }
  3950. }
  3951. else
  3952. {
  3953. LogMessage(__FILE__, __LINE__, this, FZ_LOG_WARNING, _T("Protocol %d not supported"), GetFamily());
  3954. bError = true;
  3955. }
  3956. if (bError)
  3957. {
  3958. ResetOperation(FZ_REPLY_ERROR);
  3959. return;
  3960. }
  3961. }
  3962. }
  3963. break;
  3964. case FILETRANSFER_REST:
  3965. ASSERT(m_pDataFile);
  3966. {
  3967. CString command;
  3968. command.Format(_T("REST %I64d"), GetLength64(*m_pDataFile));
  3969. if (!Send(command))
  3970. bError=TRUE;
  3971. }
  3972. break;
  3973. case FILETRANSFER_RETRSTOR:
  3974. pData->transferdata.nTransferStart=pData->transferdata.transfersize-pData->transferdata.transferleft;
  3975. m_pTransferSocket->m_transferdata=pData->transferdata;
  3976. // send RETR/STOR command to server
  3977. if (!m_pTransferSocket)
  3978. {
  3979. LogMessage(__FILE__, __LINE__, this,FZ_LOG_APIERROR, _T("Error: m_pTransferSocket==NULL") );
  3980. ResetOperation(FZ_REPLY_ERROR);
  3981. return;
  3982. }
  3983. if ((pData->transferfile.get || !pData->transferdata.bResume) && !pData->bPasv)
  3984. m_pTransferSocket->SetActive();
  3985. CString filename;
  3986. filename = pData->transferfile.remotepath.FormatFilename(pData->transferfile.remotefile, !pData->bUseAbsolutePaths);
  3987. if(!Send((pData->transferfile.get?"RETR ":(pData->transferdata.bResume)?"APPE ":"STOR ")+ filename))
  3988. bError = TRUE;
  3989. else
  3990. {
  3991. if (pData->bPasv)
  3992. {// if PASV create the socket & initiate outbound data channel connection
  3993. if (!m_pTransferSocket->Connect(pData->host,pData->port))
  3994. {
  3995. if (GetLastError()!=WSAEWOULDBLOCK)
  3996. bError=TRUE;
  3997. }
  3998. }
  3999. }
  4000. break;
  4001. }
  4002. if (bError)
  4003. { //Error transferring the file
  4004. ResetOperation(FZ_REPLY_ERROR);
  4005. return;
  4006. }
  4007. }
  4008. void CFtpControlSocket::Cancel(BOOL bQuit/*=FALSE*/)
  4009. {
  4010. 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);
  4011. const int nOpMode = m_Operation.nOpMode;
  4012. if (nOpMode==CSMODE_CONNECT)
  4013. DoClose(FZ_REPLY_CANCEL);
  4014. else if (nOpMode & CSMODE_LIST)
  4015. {
  4016. if (m_Operation.nOpState == LIST_WAITFINISH)
  4017. m_skipReply = true;
  4018. ResetOperation(FZ_REPLY_ERROR | FZ_REPLY_CANCEL);
  4019. }
  4020. else if (nOpMode & CSMODE_TRANSFER)
  4021. {
  4022. if (m_Operation.nOpState == FILETRANSFER_WAITFINISH || m_Operation.nOpState == FILETRANSFER_LIST_WAITFINISH)
  4023. m_skipReply = true;
  4024. ResetOperation(FZ_REPLY_ERROR | FZ_REPLY_CANCEL | FZ_REPLY_ABORTED);
  4025. }
  4026. else if (nOpMode != CSMODE_NONE)
  4027. ResetOperation(FZ_REPLY_ERROR | FZ_REPLY_CANCEL);
  4028. if (nOpMode != CSMODE_NONE && !bQuit)
  4029. ShowStatus(IDS_ERRORMSG_INTERRUPTED, 1);
  4030. if (m_awaitsReply)
  4031. m_skipReply = true;
  4032. }
  4033. void CFtpControlSocket::TransfersocketListenFinished(unsigned int ip, unsigned short port)
  4034. {
  4035. if (m_Operation.nOpMode&CSMODE_TRANSFER || m_Operation.nOpMode&CSMODE_LIST)
  4036. {
  4037. CString host;
  4038. host.Format(_T("%d,%d,%d,%d,%d,%d"),ip%256,(ip>>8)%256,(ip>>16)%256,(ip>>24)%256,port%256,port>>8);
  4039. Send("PORT "+host);
  4040. }
  4041. }
  4042. void CFtpControlSocket::ResumeTransfer()
  4043. {
  4044. if (m_pTransferSocket && (m_Operation.nOpMode&CSMODE_TRANSFER || m_Operation.nOpMode&CSMODE_LIST))
  4045. {
  4046. m_pTransferSocket->OnSend(0);
  4047. m_pTransferSocket->OnReceive(0);
  4048. }
  4049. }
  4050. BOOL CFtpControlSocket::Create()
  4051. {
  4052. if (!COptions::GetOptionVal(OPTION_LIMITPORTRANGE))
  4053. 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);
  4054. else
  4055. {
  4056. int min=COptions::GetOptionVal(OPTION_PORTRANGELOW);
  4057. int max=COptions::GetOptionVal(OPTION_PORTRANGEHIGH);
  4058. if (min>=max)
  4059. {
  4060. ShowStatus(IDS_ERRORMSG_CANTCREATEDUETOPORTRANGE,1);
  4061. return FALSE;
  4062. }
  4063. int startport = static_cast<int>(min+((double)rand()*(max-min))/(RAND_MAX+1));
  4064. int port = startport;
  4065. 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))
  4066. {
  4067. port++;
  4068. if (port>max)
  4069. port=min;
  4070. if (port==startport)
  4071. {
  4072. ShowStatus(IDS_ERRORMSG_CANTCREATEDUETOPORTRANGE,1);
  4073. return FALSE;
  4074. }
  4075. if (!InitConnect())
  4076. return FALSE;
  4077. }
  4078. }
  4079. return TRUE;
  4080. }
  4081. void CFtpControlSocket::ResetOperation(int nSuccessful /*=FALSE*/)
  4082. {
  4083. LogMessage(__FILE__, __LINE__, this,FZ_LOG_DEBUG, _T("ResetOperation(%d) OpMode=%d OpState=%d"), nSuccessful, m_Operation.nOpMode, m_Operation.nOpState);
  4084. if (nSuccessful & FZ_REPLY_CRITICALERROR)
  4085. nSuccessful |= FZ_REPLY_ERROR;
  4086. if (m_pTransferSocket)
  4087. delete m_pTransferSocket;
  4088. m_pTransferSocket=0;
  4089. #ifndef MPEXT_NO_IDENT
  4090. //There may be an active ident socket, close it
  4091. if (m_pIdentControl)
  4092. {
  4093. delete m_pIdentControl;
  4094. m_pIdentControl=0;
  4095. }
  4096. #endif
  4097. if (m_pDataFile)
  4098. delete m_pDataFile;
  4099. m_pDataFile=0;
  4100. if (m_Operation.nOpMode)
  4101. {
  4102. //Unset busy attribute so that new commands can be executed
  4103. m_pOwner->SetBusy(FALSE);
  4104. if (m_Operation.nOpMode&CSMODE_CONNECT && nSuccessful&FZ_REPLY_ERROR)
  4105. {
  4106. nSuccessful|=FZ_REPLY_DISCONNECTED;
  4107. ShowStatus(IDS_ERRORMSG_CANTCONNECT, 1);
  4108. }
  4109. if (m_Operation.nOpMode & (CSMODE_LIST|CSMODE_TRANSFER) && nSuccessful==FZ_REPLY_OK)
  4110. m_LastSendTime=CTime::GetCurrentTime();
  4111. //Update remote file entry
  4112. if (m_Operation.pData &&
  4113. m_Operation.nOpMode&CSMODE_TRANSFER &&
  4114. (!((CFileTransferData*)m_Operation.pData)->transferfile.get) &&
  4115. m_pDirectoryListing &&
  4116. m_Operation.nOpState>=FILETRANSFER_RETRSTOR)
  4117. {
  4118. CString filename=((CFileTransferData*)m_Operation.pData)->transferfile.remotefile;
  4119. CServerPath path=((CFileTransferData*)m_Operation.pData)->transferfile.remotepath;
  4120. #ifndef MPEXT_NO_CACHE
  4121. CDirectoryCache cache;
  4122. cache.Lock();
  4123. t_directory dir;
  4124. BOOL bCached=TRUE;
  4125. BOOL res=cache.Lookup(path, m_CurrentServer, dir);
  4126. if (!res)
  4127. bCached=FALSE;
  4128. #else
  4129. t_directory dir;
  4130. BOOL res=FALSE;
  4131. #endif
  4132. if (!res && m_pDirectoryListing)
  4133. {
  4134. if (m_pDirectoryListing->path==path)
  4135. {
  4136. dir=*m_pDirectoryListing;
  4137. res=TRUE;
  4138. }
  4139. }
  4140. t_directory WorkingDir;
  4141. BOOL bFound=m_pOwner->GetWorkingDir(&WorkingDir);
  4142. if (!res && bFound)
  4143. if (WorkingDir.path==path)
  4144. {
  4145. dir=WorkingDir;
  4146. res=TRUE;
  4147. }
  4148. if (res)
  4149. {
  4150. int i;
  4151. for (i=0; i<dir.num; i++)
  4152. if (dir.direntry[i].name==filename)
  4153. {
  4154. dir.direntry[i].bUnsure = TRUE;
  4155. if (nSuccessful & FZ_REPLY_ERROR)
  4156. {
  4157. dir.direntry[i].bUnsure = TRUE;
  4158. if (!((CFileTransferData *)m_Operation.pData)->transferfile.get)
  4159. dir.direntry[i].size = -1;
  4160. }
  4161. else if (nSuccessful & FZ_REPLY_ERROR)
  4162. {
  4163. if (!GetLength64(((CFileTransferData *)m_Operation.pData)->transferfile.localfile, dir.direntry[i].size))
  4164. dir.direntry[i].size = -1;
  4165. }
  4166. dir.direntry[i].date.hasdate = false;
  4167. break;
  4168. }
  4169. if (i==dir.num)
  4170. {
  4171. t_directory::t_direntry *entries=new t_directory::t_direntry[dir.num+1];
  4172. int i;
  4173. for (i=0; i<dir.num; i++)
  4174. entries[i]=dir.direntry[i];
  4175. entries[i].name=filename;
  4176. entries[i].lName=filename;
  4177. entries[i].lName.MakeLower();
  4178. entries[i].dir=FALSE;
  4179. entries[i].date.hasdate=FALSE;
  4180. entries[i].size=-1;
  4181. if (nSuccessful&FZ_REPLY_OK)
  4182. entries[i].bUnsure=FALSE;
  4183. else
  4184. entries[i].bUnsure=TRUE;
  4185. delete [] dir.direntry;
  4186. dir.direntry=entries;
  4187. dir.num++;
  4188. }
  4189. #ifndef MPEXT_NO_CACHE
  4190. cache.Store(dir, bCached);
  4191. #endif
  4192. BOOL updated=FALSE;
  4193. if (m_pDirectoryListing && m_pDirectoryListing->path==dir.path)
  4194. {
  4195. updated=TRUE;
  4196. SetDirectoryListing(&dir, bFound && WorkingDir.path == dir.path);
  4197. }
  4198. if (!updated)
  4199. if (bFound && WorkingDir.path==dir.path)
  4200. {
  4201. updated = TRUE;
  4202. m_pOwner->SetWorkingDir(&dir);
  4203. }
  4204. }
  4205. #ifndef MPEXT_NO_CACHE
  4206. cache.Unlock();
  4207. #endif
  4208. }
  4209. if (m_Operation.pData && nSuccessful&FZ_REPLY_ERROR)
  4210. {
  4211. if (m_Operation.nOpMode&CSMODE_TRANSFER)
  4212. if (nSuccessful&FZ_REPLY_ABORTED)
  4213. //Transfer aborted by user
  4214. ShowStatus((m_Operation.nOpMode&CSMODE_DOWNLOAD)?IDS_ERRORMSG_DOWNLOADABORTED:IDS_ERRORMSG_UPLOADABORTED,1);
  4215. else
  4216. ShowStatus(((CFileTransferData*)m_Operation.pData)->transferfile.get?IDS_ERRORMSG_DOWNLOADFAILED:IDS_ERRORMSG_UPLOADFAILED,1);
  4217. else if (m_Operation.nOpMode&CSMODE_LIST)
  4218. ShowStatus(IDS_ERRORMSG_CANTGETLIST,1);
  4219. }
  4220. else if (m_Operation.pData && m_Operation.nOpMode&CSMODE_TRANSFER && nSuccessful==FZ_REPLY_OK)
  4221. ShowStatus(((CFileTransferData*)m_Operation.pData)->transferfile.get?IDS_STATUSMSG_DOWNLOADSUCCESSFUL:IDS_STATUSMSG_UPLOADSUCCESSFUL,0);
  4222. }
  4223. else
  4224. {
  4225. #ifdef MPEXT
  4226. // When control socket is waiting for reply
  4227. // to keepalive (!IsReady), while new command comes,
  4228. // its execution is postponed
  4229. // (CMainThread::m_pPostKeepAliveCommand),
  4230. // but the main thread
  4231. // is set to busy state already (CMainThread::Command).
  4232. // if connection is closed before without receiving reply,
  4233. // main thread would stay busy forever.
  4234. m_pOwner->SetBusy(FALSE);
  4235. #endif
  4236. //No operation in progress
  4237. nSuccessful&=FZ_REPLY_DISCONNECTED|FZ_REPLY_CANCEL;
  4238. if (!nSuccessful)
  4239. ASSERT(FALSE);
  4240. }
  4241. if (nSuccessful&FZ_REPLY_DISCONNECTED)
  4242. m_pOwner->SetWorkingDir(0); //Disconnected, reset working dir
  4243. if (m_Operation.nOpMode)
  4244. PostMessage(m_pOwner->m_hOwnerWnd, m_pOwner->m_nReplyMessageID, FZ_MSG_MAKEMSG(FZ_MSG_REPLY, m_pOwner->m_LastCommand.id), nSuccessful);
  4245. else
  4246. PostMessage(m_pOwner->m_hOwnerWnd, m_pOwner->m_nReplyMessageID, FZ_MSG_MAKEMSG(FZ_MSG_REPLY, 0), nSuccessful);
  4247. m_Operation.nOpMode=0;
  4248. m_Operation.nOpState=-1;
  4249. if (m_Operation.pData)
  4250. delete m_Operation.pData;
  4251. m_Operation.pData=0;
  4252. }
  4253. void CFtpControlSocket::Delete(CString filename, const CServerPath &path)
  4254. {
  4255. LogMessage(__FILE__, __LINE__, this,FZ_LOG_DEBUG, _T("Delete(\"%s\", \"%s\") OpMode=%d OpState=%d"), filename, path.GetPath(), m_Operation.nOpMode, m_Operation.nOpState);
  4256. class CDeleteData : public CFtpControlSocket::t_operation::COpData
  4257. {
  4258. public:
  4259. CDeleteData() {}
  4260. virtual ~CDeleteData() {}
  4261. CString m_FileName;
  4262. CServerPath path;
  4263. };
  4264. if (filename!="")
  4265. {
  4266. ASSERT(!path.IsEmpty());
  4267. ASSERT(m_Operation.nOpMode==CSMODE_NONE);
  4268. ASSERT(m_Operation.nOpState==-1);
  4269. ASSERT(!m_Operation.pData);
  4270. m_Operation.nOpMode=CSMODE_DELETE;
  4271. if (!Send("DELE " + path.FormatFilename(filename)))
  4272. return;
  4273. CDeleteData *data=new CDeleteData;
  4274. data->m_FileName=filename;
  4275. data->path=path;
  4276. m_Operation.pData=data;
  4277. }
  4278. else
  4279. {
  4280. ASSERT(path.IsEmpty());
  4281. ASSERT(m_Operation.nOpMode==CSMODE_DELETE);
  4282. ASSERT(m_Operation.nOpState==-1);
  4283. ASSERT(m_Operation.pData);
  4284. int res=GetReplyCode();
  4285. if (res==2 || res==3)
  4286. { //Remove file from cached dirs
  4287. CDeleteData *pData=(CDeleteData *)m_Operation.pData;
  4288. #ifndef MPEXT_NO_CACHE
  4289. CDirectoryCache cache;
  4290. cache.Lock();
  4291. BOOL bCached=TRUE;
  4292. t_directory dir;
  4293. BOOL res=cache.Lookup(pData->path,m_CurrentServer,dir);
  4294. if (!res)
  4295. bCached=FALSE;
  4296. #else
  4297. t_directory dir;
  4298. BOOL res=FALSE;
  4299. #endif
  4300. if (!res && m_pDirectoryListing)
  4301. {
  4302. if (m_pDirectoryListing->path==pData->path)
  4303. {
  4304. dir=*m_pDirectoryListing;
  4305. res=TRUE;
  4306. }
  4307. }
  4308. t_directory WorkingDir;
  4309. BOOL bFound=m_pOwner->GetWorkingDir(&WorkingDir);
  4310. if (!res && bFound)
  4311. if (WorkingDir.path==pData->path)
  4312. {
  4313. dir=WorkingDir;
  4314. res=TRUE;
  4315. }
  4316. if (res)
  4317. {
  4318. BOOL found=FALSE;
  4319. for (int i=0;i<dir.num;i++)
  4320. {
  4321. if (dir.direntry[i].name==pData->m_FileName)
  4322. {
  4323. ASSERT(!dir.direntry[i].dir || dir.direntry[i].bLink);
  4324. found=TRUE;
  4325. break;
  4326. }
  4327. }
  4328. if (found)
  4329. {
  4330. t_directory::t_direntry *direntry=new t_directory::t_direntry[dir.num-1];
  4331. int j=0;
  4332. int i;
  4333. for (i=0; i<dir.num; i++)
  4334. {
  4335. if (dir.direntry[i].name==pData->m_FileName)
  4336. continue;
  4337. direntry[j]=dir.direntry[i];
  4338. j++;
  4339. }
  4340. delete [] dir.direntry;
  4341. dir.direntry=direntry;
  4342. dir.num--;
  4343. #ifndef MPEXT_NO_CACHE
  4344. cache.Store(dir, bCached);
  4345. #endif
  4346. BOOL updated=FALSE;
  4347. if (m_pDirectoryListing)
  4348. if (m_pDirectoryListing->path==dir.path)
  4349. {
  4350. updated=TRUE;
  4351. SetDirectoryListing(&dir);
  4352. }
  4353. if (!updated)
  4354. if (WorkingDir.path==dir.path)
  4355. {
  4356. updated=TRUE;
  4357. m_pOwner->SetWorkingDir(&dir);
  4358. }
  4359. }
  4360. }
  4361. #ifndef MPEXT_NO_CACHE
  4362. cache.Unlock();
  4363. #endif
  4364. }
  4365. ResetOperation(FZ_REPLY_OK);
  4366. }
  4367. }
  4368. void CFtpControlSocket::RemoveDir(CString dirname, const CServerPath &path)
  4369. {
  4370. LogMessage(__FILE__, __LINE__, this,FZ_LOG_DEBUG, _T("RemoveDir(\"%s\", \"%s\") OpMode=%d OpState=%d"), dirname, path.GetPath(), m_Operation.nOpMode, m_Operation.nOpState);
  4371. class CRemoveDirData : public CFtpControlSocket::t_operation::COpData
  4372. {
  4373. public:
  4374. CRemoveDirData() {}
  4375. virtual ~CRemoveDirData() {}
  4376. CString m_DirName;
  4377. CServerPath path;
  4378. };
  4379. if (dirname != "")
  4380. {
  4381. ASSERT(!path.IsEmpty());
  4382. ASSERT(m_Operation.nOpMode == CSMODE_NONE);
  4383. ASSERT(m_Operation.nOpState == -1);
  4384. ASSERT(!m_Operation.pData);
  4385. m_Operation.nOpMode = CSMODE_RMDIR;
  4386. CServerPath newPath = path;
  4387. if (!newPath.AddSubdir(dirname))
  4388. {
  4389. ShowStatus(_T("Unable to concatenate path"), 1);
  4390. return;
  4391. }
  4392. if (!Send("RMD "+ newPath.GetPath()))
  4393. return;
  4394. CRemoveDirData *data = new CRemoveDirData;
  4395. data->m_DirName = dirname;
  4396. data->path = path;
  4397. m_Operation.pData = data;
  4398. }
  4399. else
  4400. {
  4401. ASSERT(path.IsEmpty());
  4402. ASSERT(m_Operation.nOpMode == CSMODE_RMDIR);
  4403. ASSERT(m_Operation.nOpState == -1);
  4404. ASSERT(m_Operation.pData);
  4405. int res = GetReplyCode();
  4406. if (res == 2 || res == 3)
  4407. { //Remove dir from cached dirs
  4408. CRemoveDirData *pData= (CRemoveDirData *)m_Operation.pData;
  4409. #ifndef MPEXT_NO_CACHE
  4410. CDirectoryCache cache;
  4411. cache.Lock();
  4412. BOOL bCached = TRUE;
  4413. t_directory dir;
  4414. BOOL res = cache.Lookup(pData->path, m_CurrentServer, dir);
  4415. if (!res)
  4416. bCached = FALSE;
  4417. #else
  4418. t_directory dir;
  4419. BOOL res = FALSE;
  4420. #endif
  4421. if (!res && m_pDirectoryListing)
  4422. {
  4423. if (m_pDirectoryListing->path == pData->path)
  4424. {
  4425. dir = *m_pDirectoryListing;
  4426. res = TRUE;
  4427. }
  4428. }
  4429. t_directory WorkingDir;
  4430. BOOL bFound = m_pOwner->GetWorkingDir(&WorkingDir);
  4431. if (!res && bFound)
  4432. if (WorkingDir.path == pData->path)
  4433. {
  4434. dir = WorkingDir;
  4435. res = TRUE;
  4436. }
  4437. if (res)
  4438. {
  4439. BOOL found = FALSE;
  4440. for (int i = 0; i < dir.num; i++)
  4441. {
  4442. if (dir.direntry[i].name == pData->m_DirName)
  4443. {
  4444. ASSERT(dir.direntry[i].dir);
  4445. found = TRUE;
  4446. break;
  4447. }
  4448. }
  4449. if (found)
  4450. {
  4451. t_directory::t_direntry *direntry = new t_directory::t_direntry[dir.num-1];
  4452. int j = 0;
  4453. int i;
  4454. for (i = 0; i < dir.num; i++)
  4455. {
  4456. if (dir.direntry[i].name == pData->m_DirName)
  4457. continue;
  4458. direntry[j] = dir.direntry[i];
  4459. j++;
  4460. }
  4461. delete [] dir.direntry;
  4462. dir.direntry = direntry;
  4463. dir.num--;
  4464. #ifndef MPEXT_NO_CACHE
  4465. cache.Store(dir, bCached);
  4466. #endif
  4467. BOOL updated = FALSE;
  4468. if (m_pDirectoryListing)
  4469. if (m_pDirectoryListing->path == dir.path)
  4470. {
  4471. updated = TRUE;
  4472. SetDirectoryListing(&dir);
  4473. }
  4474. if (!updated)
  4475. if (WorkingDir.path == dir.path)
  4476. {
  4477. updated = TRUE;
  4478. m_pOwner->SetWorkingDir(&dir);
  4479. }
  4480. }
  4481. }
  4482. #ifndef MPEXT_NO_CACHE
  4483. if (cache.Lookup(pData->path, pData->m_DirName, m_CurrentServer, dir))
  4484. cache.Purge(dir.path, dir.server);
  4485. cache.Unlock();
  4486. #endif
  4487. ResetOperation(FZ_REPLY_OK);
  4488. }
  4489. else
  4490. ResetOperation(FZ_REPLY_ERROR);
  4491. }
  4492. }
  4493. int CFtpControlSocket::CheckOverwriteFile()
  4494. {
  4495. if (!m_Operation.pData)
  4496. return FZ_REPLY_ERROR;
  4497. CFileTransferData *pData = reinterpret_cast<CFileTransferData *>(m_Operation.pData);
  4498. int nReplyError = 0;
  4499. CFileStatus64 status;
  4500. BOOL res = GetStatus64(pData->transferfile.localfile, status);
  4501. if (!res)
  4502. if (!pData->transferfile.get)
  4503. nReplyError = FZ_REPLY_CRITICALERROR; //File has to exist when uploading
  4504. else
  4505. m_Operation.nOpState = FILETRANSFER_TYPE;
  4506. else
  4507. {
  4508. if (status.m_attribute & 0x10)
  4509. nReplyError = FZ_REPLY_CRITICALERROR; //Can't transfer to/from dirs
  4510. else
  4511. {
  4512. _int64 localsize;
  4513. if (!GetLength64(pData->transferfile.localfile, localsize))
  4514. if (!pData->transferfile.get)
  4515. nReplyError = FZ_REPLY_CRITICALERROR;
  4516. else
  4517. m_Operation.nOpState = FILETRANSFER_TYPE;
  4518. CTime *localtime = NULL;
  4519. TRY
  4520. {
  4521. if (status.m_has_mtime && status.m_mtime != -1)
  4522. localtime = new CTime(status.m_mtime);
  4523. }
  4524. CATCH_ALL(e)
  4525. {
  4526. TCHAR buffer[1024];
  4527. CString str =_T("Exception creating CTime object: ");
  4528. if (e->GetErrorMessage(buffer, 1024, NULL))
  4529. str += buffer;
  4530. else
  4531. str += _T("Unknown exception");
  4532. LogMessageRaw(__FILE__, __LINE__, this, FZ_LOG_WARNING, str);
  4533. localtime = NULL;
  4534. }
  4535. END_CATCH_ALL;
  4536. BOOL bRemoteFileExists = FALSE;
  4537. __int64 remotesize = -1;
  4538. CTime *remotetime = 0;
  4539. if (m_pDirectoryListing)
  4540. {
  4541. for (int i=0; i<m_pDirectoryListing->num; i++)
  4542. {
  4543. CString remotefile = pData->transferfile.remotefile;
  4544. if (m_pDirectoryListing->direntry[i].name == remotefile)
  4545. {
  4546. remotesize = m_pDirectoryListing->direntry[i].size;
  4547. if (m_pDirectoryListing->direntry[i].date.hasdate)
  4548. {
  4549. TRY
  4550. {
  4551. remotetime = new CTime(m_pDirectoryListing->direntry[i].date.year,
  4552. m_pDirectoryListing->direntry[i].date.month,
  4553. m_pDirectoryListing->direntry[i].date.day,
  4554. m_pDirectoryListing->direntry[i].date.hastime?m_pDirectoryListing->direntry[i].date.hour:0,
  4555. m_pDirectoryListing->direntry[i].date.hastime?m_pDirectoryListing->direntry[i].date.minute:0,
  4556. 0,-1);
  4557. }
  4558. CATCH_ALL(e)
  4559. {
  4560. TCHAR buffer[1024];
  4561. CString str =_T("Exception creating CTime object: ");
  4562. if (e->GetErrorMessage(buffer, 1024, NULL))
  4563. str += buffer;
  4564. else
  4565. str += _T("Unknown exception");
  4566. LogMessageRaw(__FILE__, __LINE__, this, FZ_LOG_WARNING, str);
  4567. remotetime = NULL;
  4568. }
  4569. END_CATCH_ALL;
  4570. }
  4571. bRemoteFileExists = TRUE;
  4572. break;
  4573. }
  4574. }
  4575. }
  4576. if (remotesize == -1 && pData->pFileSize)
  4577. {
  4578. remotesize = *pData->pFileSize;
  4579. bRemoteFileExists = TRUE;
  4580. }
  4581. if (!remotetime && pData->pFileTime)
  4582. {
  4583. remotetime = new CTime;
  4584. *remotetime = *pData->pFileTime;
  4585. bRemoteFileExists = TRUE;
  4586. }
  4587. if (bRemoteFileExists || pData->transferfile.get )
  4588. {
  4589. COverwriteRequestData *pOverwriteData = new COverwriteRequestData;
  4590. t_transferfile *pTransferFile = new t_transferfile;
  4591. *pTransferFile = pData->transferfile;
  4592. pOverwriteData->pTransferFile = pTransferFile;
  4593. if (pData->transferfile.get)
  4594. {
  4595. int pos = pData->transferfile.localfile.ReverseFind('\\');
  4596. ASSERT(pos!=-1);
  4597. pOverwriteData->FileName1 = pData->transferfile.localfile.Mid(pos+1);
  4598. pOverwriteData->FileName2 = pData->transferfile.remotefile;
  4599. pOverwriteData->path1 = pData->transferfile.localfile.Left(pos+1);
  4600. pOverwriteData->path2 = pData->transferfile.remotepath.GetPath();
  4601. pOverwriteData->size1 = localsize;
  4602. pOverwriteData->size2 = remotesize;
  4603. pOverwriteData->time1 = localtime;
  4604. pOverwriteData->time2 = remotetime;
  4605. }
  4606. else
  4607. {
  4608. int pos = pData->transferfile.localfile.ReverseFind('\\');
  4609. ASSERT(pos!=-1);
  4610. pOverwriteData->FileName1 = pData->transferfile.remotefile;
  4611. pOverwriteData->FileName2 = pData->transferfile.localfile.Mid(pos+1);
  4612. pOverwriteData->path1 = pData->transferfile.remotepath.GetPath();
  4613. pOverwriteData->path2 = pData->transferfile.localfile.Left(pos+1);
  4614. pOverwriteData->size1 = remotesize;
  4615. pOverwriteData->size2 = localsize;
  4616. pOverwriteData->time1 = remotetime;
  4617. pOverwriteData->time2 = localtime;
  4618. }
  4619. pOverwriteData->nRequestID = m_pOwner->GetNextAsyncRequestID();
  4620. if (!PostMessage(m_pOwner->m_hOwnerWnd, m_pOwner->m_nReplyMessageID, FZ_MSG_MAKEMSG(FZ_MSG_ASYNCREQUEST, FZ_ASYNCREQUEST_OVERWRITE), (LPARAM)pOverwriteData))
  4621. {
  4622. delete pOverwriteData;
  4623. nReplyError = FZ_REPLY_ERROR;
  4624. }
  4625. else
  4626. {
  4627. m_bCheckForTimeout = FALSE;
  4628. m_Operation.nOpState = FILETRANSFER_WAIT;
  4629. }
  4630. }
  4631. else
  4632. {
  4633. m_Operation.nOpState = FILETRANSFER_TYPE;
  4634. delete localtime;
  4635. delete remotetime;
  4636. }
  4637. }
  4638. }
  4639. return nReplyError;
  4640. }
  4641. void CFtpControlSocket::SetFileExistsAction(int nAction, COverwriteRequestData *pData)
  4642. {
  4643. if (!pData)
  4644. return;
  4645. if (!(m_Operation.nOpMode & CSMODE_TRANSFER))
  4646. return;
  4647. if (m_Operation.nOpState != FILETRANSFER_WAIT)
  4648. return;
  4649. CFileTransferData* pTransferData = reinterpret_cast<CFileTransferData*>(m_Operation.pData);
  4650. if (!pTransferData)
  4651. return;
  4652. pTransferData->transferdata.bResume = false;
  4653. m_bCheckForTimeout = TRUE;
  4654. int nReplyError = 0;
  4655. switch (nAction)
  4656. {
  4657. case FILEEXISTS_SKIP:
  4658. nReplyError = FZ_REPLY_OK;
  4659. break;
  4660. case FILEEXISTS_OVERWRITE:
  4661. pTransferData->nWaitNextOpState = FILETRANSFER_TYPE;
  4662. break;
  4663. case FILEEXISTS_OVERWRITEIFNEWER:
  4664. if ( !pData->time1 || !pData->time2 )
  4665. pTransferData->nWaitNextOpState = FILETRANSFER_TYPE;
  4666. else if (*pData->time2 <= *pData->time1)
  4667. nReplyError = FZ_REPLY_OK;
  4668. else
  4669. pTransferData->nWaitNextOpState = FILETRANSFER_TYPE;
  4670. break;
  4671. case FILEEXISTS_RENAME:
  4672. if (pTransferData->transferfile.get)
  4673. {
  4674. CFileStatus64 status;
  4675. if (GetStatus64(pData->FileName1, status))
  4676. {
  4677. ShowStatus(IDS_ERRORMSG_NAMEINUSE, 1);
  4678. nReplyError= FZ_REPLY_CRITICALERROR;
  4679. }
  4680. else
  4681. {
  4682. pTransferData->transferfile.localfile = pData->path1+pData->FileName1;
  4683. //Replace invalid characters in the local filename
  4684. int pos = pTransferData->transferfile.localfile.ReverseFind('\\');
  4685. for (int i = (pos+1); i < pTransferData->transferfile.localfile.GetLength(); i++)
  4686. if (pTransferData->transferfile.localfile[i] == ':')
  4687. pTransferData->transferfile.localfile.SetAt(i, '_');
  4688. pTransferData->nWaitNextOpState= FILETRANSFER_TYPE;
  4689. }
  4690. }
  4691. else
  4692. {
  4693. ASSERT(m_pDirectoryListing);
  4694. int i;
  4695. for (i = 0; i < m_pDirectoryListing->num; i++)
  4696. {
  4697. if (m_pDirectoryListing->direntry[i].name == pData->FileName1)
  4698. {
  4699. ShowStatus(IDS_ERRORMSG_NAMEINUSE, 1);
  4700. nReplyError = FZ_REPLY_CRITICALERROR;
  4701. break;
  4702. }
  4703. }
  4704. if (i==m_pDirectoryListing->num)
  4705. {
  4706. pTransferData->transferfile.remotefile = pData->FileName1;
  4707. pTransferData->nWaitNextOpState = FILETRANSFER_TYPE;
  4708. }
  4709. }
  4710. break;
  4711. case FILEEXISTS_RESUME_ASKONFAIL:
  4712. pTransferData->askOnResumeFail = true;
  4713. case FILEEXISTS_RESUME:
  4714. if (pData->size1 >= 0)
  4715. {
  4716. pTransferData->transferdata.bResume = TRUE;
  4717. }
  4718. pTransferData->nWaitNextOpState = FILETRANSFER_TYPE;
  4719. break;
  4720. }
  4721. if (nReplyError == FZ_REPLY_OK)
  4722. ResetOperation(FZ_REPLY_OK);
  4723. else if (nReplyError)
  4724. ResetOperation(FZ_REPLY_ERROR | nReplyError); //Error transferring the file
  4725. else
  4726. FileTransfer();
  4727. }
  4728. void CFtpControlSocket::SendKeepAliveCommand()
  4729. {
  4730. m_bKeepAliveActive=TRUE;
  4731. //Choose a random command from the list
  4732. char commands[4][7]={"PWD","REST 0","TYPE A","TYPE I"};
  4733. int choice=(rand()*4)/(RAND_MAX+1);
  4734. Send(commands[choice], FALSE);
  4735. }
  4736. void CFtpControlSocket::MakeDir(const CServerPath &path)
  4737. {
  4738. //Directory creation works like this:
  4739. //Find existing parent and create subdirs one by one
  4740. LogMessage(__FILE__, __LINE__, this, FZ_LOG_DEBUG, _T("MakeDir(\"%s\") OpMode=%d OpState=%d"), path.GetPath(), m_Operation.nOpMode, m_Operation.nOpState);
  4741. if (m_Operation.nOpState == MKD_INIT)
  4742. {
  4743. ASSERT(!path.IsEmpty());
  4744. ASSERT(m_Operation.nOpMode==CSMODE_NONE);
  4745. ASSERT(!m_Operation.pData);
  4746. m_Operation.nOpMode = CSMODE_MKDIR;
  4747. if (!Send("CWD "+path.GetParent().GetPath()))
  4748. return;
  4749. CMakeDirData *data = new CMakeDirData;
  4750. data->path = path;
  4751. data->Current = path.GetParent();
  4752. data->Segments.push_front(path.GetLastSegment());
  4753. m_Operation.pData = data;
  4754. m_Operation.nOpState = MKD_FINDPARENT;
  4755. }
  4756. else if (m_Operation.nOpState==MKD_FINDPARENT)
  4757. {
  4758. ASSERT(m_Operation.nOpMode==CSMODE_MKDIR);
  4759. ASSERT(path.IsEmpty());
  4760. ASSERT(m_Operation.pData);
  4761. CMakeDirData *pData=(CMakeDirData *)m_Operation.pData;
  4762. int res=GetReplyCode();
  4763. if (res==2 || res==3)
  4764. {
  4765. m_pOwner->SetCurrentPath(pData->Current);
  4766. m_Operation.nOpState=MKD_MAKESUBDIRS;
  4767. pData->Current.AddSubdir(pData->Segments.front());
  4768. CString Segment=pData->Segments.front();
  4769. pData->Segments.pop_front();
  4770. if (Send( _T("MKD ") + Segment))
  4771. m_Operation.nOpState = MKD_CHANGETOSUBDIR;
  4772. else
  4773. return;
  4774. }
  4775. else
  4776. {
  4777. if (!pData->Current.HasParent())
  4778. ResetOperation(FZ_REPLY_ERROR);
  4779. else
  4780. {
  4781. pData->Segments.push_front(pData->Current.GetLastSegment());
  4782. pData->Current=pData->Current.GetParent();
  4783. if (!Send("CWD "+pData->Current.GetPath()))
  4784. return;
  4785. }
  4786. }
  4787. }
  4788. else if (m_Operation.nOpState==MKD_MAKESUBDIRS)
  4789. {
  4790. int res=GetReplyCode();
  4791. if (res==2 || res==3)
  4792. { //Create dir entry in parent dir
  4793. CMakeDirData *pData=(CMakeDirData *)m_Operation.pData;
  4794. ASSERT(!pData->Segments.empty());
  4795. m_pOwner->SetCurrentPath(pData->Current);
  4796. pData->Current.AddSubdir(pData->Segments.front());
  4797. CString Segment=pData->Segments.front();
  4798. pData->Segments.pop_front();
  4799. if (Send( _T("MKD ") + Segment))
  4800. m_Operation.nOpState=MKD_CHANGETOSUBDIR;
  4801. else
  4802. return;
  4803. }
  4804. else
  4805. ResetOperation(FZ_REPLY_ERROR);
  4806. }
  4807. else if (m_Operation.nOpState==MKD_CHANGETOSUBDIR)
  4808. {
  4809. CMakeDirData *pData=(CMakeDirData *)m_Operation.pData;
  4810. int res=GetReplyCode();
  4811. if (res==2 || res==3 || //Creation successful
  4812. GetReply() == _T("550 Directory already exists"))//Creation was successful, although someone else did the work for us
  4813. { //Create dir entry in parent dir
  4814. CServerPath path2=pData->Current;
  4815. if (path2.HasParent())
  4816. {
  4817. CString name=path2.GetLastSegment();
  4818. path2=path2.GetParent();
  4819. #ifndef MPEXT_NO_CACHE
  4820. CDirectoryCache cache;
  4821. t_directory dir;
  4822. cache.Lock();
  4823. BOOL bCached = TRUE;
  4824. BOOL res = cache.Lookup(path2, m_CurrentServer,dir);
  4825. if (!res)
  4826. bCached = FALSE;
  4827. #else
  4828. t_directory dir;
  4829. BOOL res = FALSE;
  4830. #endif
  4831. if (!res && m_pDirectoryListing)
  4832. {
  4833. if (m_pDirectoryListing->path == path2)
  4834. {
  4835. dir = *m_pDirectoryListing;
  4836. res = TRUE;
  4837. }
  4838. }
  4839. t_directory WorkingDir;
  4840. BOOL bFound = m_pOwner->GetWorkingDir(&WorkingDir);
  4841. if (!res && bFound)
  4842. if (WorkingDir.path == path2)
  4843. {
  4844. dir = WorkingDir;
  4845. res = TRUE;
  4846. }
  4847. if (!res)
  4848. {
  4849. dir.path = path2;
  4850. dir.server = m_CurrentServer;
  4851. }
  4852. int i;
  4853. for (i=0; i<dir.num; i++)
  4854. if (dir.direntry[i].name==name)
  4855. {
  4856. LogMessage(__FILE__, __LINE__, this,FZ_LOG_WARNING, _T("Dir already exists in cache!"));
  4857. break;
  4858. }
  4859. if (i==dir.num)
  4860. {
  4861. t_directory::t_direntry *entries=new t_directory::t_direntry[dir.num+1];
  4862. for (i=0;i<dir.num;i++)
  4863. entries[i]=dir.direntry[i];
  4864. entries[i].name=name;
  4865. entries[i].lName=name;
  4866. entries[i].lName.MakeLower();
  4867. entries[i].dir=TRUE;
  4868. entries[i].date.hasdate=FALSE;
  4869. entries[i].size=-1;
  4870. entries[i].bUnsure=FALSE;
  4871. delete [] dir.direntry;
  4872. dir.direntry=entries;
  4873. dir.num++;
  4874. #ifndef MPEXT_NO_CACHE
  4875. cache.Store(dir, bCached);
  4876. #endif
  4877. BOOL updated = FALSE;
  4878. if (m_pDirectoryListing && m_pDirectoryListing->path == dir.path)
  4879. {
  4880. updated = TRUE;
  4881. SetDirectoryListing(&dir, bFound && WorkingDir.path == dir.path);
  4882. }
  4883. if (!updated)
  4884. if (bFound && WorkingDir.path == dir.path)
  4885. {
  4886. updated = TRUE;
  4887. m_pOwner->SetWorkingDir(&dir);
  4888. }
  4889. }
  4890. #ifndef MPEXT_NO_CACHE
  4891. cache.Unlock();
  4892. #endif
  4893. }
  4894. }
  4895. //Continue operation even if MKD failed, maybe another thread did create this directory for us
  4896. if (pData->Segments.empty())
  4897. ResetOperation(FZ_REPLY_OK);
  4898. else
  4899. {
  4900. if (Send( _T("CWD ") + pData->Current.GetPath()))
  4901. m_Operation.nOpState=MKD_MAKESUBDIRS;
  4902. else
  4903. return;
  4904. }
  4905. }
  4906. else
  4907. ASSERT(FALSE);
  4908. }
  4909. void CFtpControlSocket::Rename(CString oldName, CString newName, const CServerPath &path, const CServerPath &newPath)
  4910. {
  4911. LogMessage(__FILE__, __LINE__, this,FZ_LOG_DEBUG, _T("Rename(\"%s\", \"%s\", \"%s\") OpMode=%d OpState=%d"), oldName, newName, path.GetPath(),
  4912. m_Operation.nOpMode, m_Operation.nOpState);
  4913. class CRenameData : public CFtpControlSocket::t_operation::COpData
  4914. {
  4915. public:
  4916. CRenameData() {}
  4917. virtual ~CRenameData() {}
  4918. CString oldName, newName;
  4919. CServerPath path;
  4920. CServerPath newPath;
  4921. };
  4922. if (oldName != "")
  4923. {
  4924. ASSERT(newName != "");
  4925. ASSERT(!path.IsEmpty());
  4926. ASSERT(m_Operation.nOpMode == CSMODE_NONE);
  4927. ASSERT(m_Operation.nOpState == -1);
  4928. ASSERT(!m_Operation.pData);
  4929. m_Operation.nOpMode = CSMODE_RENAME;
  4930. if (!Send("RNFR " + path.FormatFilename(oldName)))
  4931. return;
  4932. CRenameData *data = new CRenameData;
  4933. data->oldName = oldName;
  4934. data->newName = newName;
  4935. data->path = path;
  4936. data->newPath = newPath;
  4937. m_Operation.pData = data;
  4938. }
  4939. else
  4940. {
  4941. ASSERT(oldName == "");
  4942. ASSERT(path.IsEmpty());
  4943. ASSERT(m_Operation.nOpMode == CSMODE_RENAME);
  4944. ASSERT(m_Operation.pData);
  4945. CRenameData *pData = reinterpret_cast<CRenameData *>(m_Operation.pData);
  4946. if (m_Operation.nOpState == -1)
  4947. {
  4948. int res = GetReplyCode();
  4949. if (res == 2 || res == 3)
  4950. {
  4951. m_Operation.nOpState++;
  4952. if (pData->newPath.IsEmpty())
  4953. {
  4954. if (!Send("RNTO " + pData->path.FormatFilename(((CRenameData *)m_Operation.pData)->newName)))
  4955. return;
  4956. }
  4957. else
  4958. if (!Send("RNTO " + pData->newPath.FormatFilename(((CRenameData *)m_Operation.pData)->newName)))
  4959. return;
  4960. }
  4961. else
  4962. ResetOperation(FZ_REPLY_ERROR);
  4963. }
  4964. else
  4965. {
  4966. int res = GetReplyCode();
  4967. if (res == 2 || res == 3)
  4968. { //Rename entry in cached directory
  4969. CRenameData *pData = reinterpret_cast<CRenameData *>(m_Operation.pData);
  4970. #ifndef MPEXT_NO_CACHE
  4971. CDirectoryCache cache;
  4972. cache.Lock();
  4973. //Rename all references to the directory in the cache
  4974. if (pData->newPath.IsEmpty())
  4975. cache.Rename(pData->path, pData->oldName, pData->newName, m_CurrentServer);
  4976. BOOL bCached = TRUE;
  4977. t_directory dir;
  4978. BOOL res = cache.Lookup(pData->path, m_CurrentServer, dir);
  4979. if (!res)
  4980. bCached = FALSE;
  4981. #else
  4982. t_directory dir;
  4983. BOOL res = FALSE;
  4984. #endif
  4985. if (!res && m_pDirectoryListing)
  4986. {
  4987. if (m_pDirectoryListing->path == pData->path)
  4988. {
  4989. dir = *m_pDirectoryListing;
  4990. res = TRUE;
  4991. }
  4992. }
  4993. t_directory WorkingDir;
  4994. BOOL bFound = m_pOwner->GetWorkingDir(&WorkingDir);
  4995. if (!res && bFound)
  4996. if (WorkingDir.path == pData->path)
  4997. {
  4998. dir = WorkingDir;
  4999. res = TRUE;
  5000. }
  5001. if (res)
  5002. {
  5003. for (int i=0; i<dir.num; i++)
  5004. if (dir.direntry[i].name == pData->oldName)
  5005. {
  5006. if (pData->newPath.IsEmpty())
  5007. {
  5008. dir.direntry[i].name = pData->newName;
  5009. dir.direntry[i].lName = pData->newName;
  5010. dir.direntry[i].lName.MakeLower();
  5011. #ifndef MPEXT_NO_CACHE
  5012. CDirectoryCache cache;
  5013. cache.Store(dir, bCached);
  5014. #endif
  5015. BOOL updated = FALSE;
  5016. if (m_pDirectoryListing && m_pDirectoryListing->path == dir.path)
  5017. {
  5018. updated = TRUE;
  5019. SetDirectoryListing(&dir, WorkingDir.path == dir.path);
  5020. }
  5021. if (!updated)
  5022. if (WorkingDir.path == dir.path)
  5023. {
  5024. updated = TRUE;
  5025. m_pOwner->SetWorkingDir(&dir);
  5026. }
  5027. }
  5028. else
  5029. {
  5030. t_directory::t_direntry oldentry = dir.direntry[i];
  5031. for (int j = i+1; j < dir.num; j++)
  5032. {
  5033. dir.direntry[j-1] = dir.direntry[j];
  5034. }
  5035. dir.num--;
  5036. #ifndef MPEXT_NO_CACHE
  5037. cache.Store(dir, bCached);
  5038. // If directory, delete old directory from cache
  5039. t_directory olddir;
  5040. res = cache.Lookup(pData->path, pData->oldName, m_CurrentServer, olddir);
  5041. if (res)
  5042. {
  5043. cache.Purge(olddir.path, m_CurrentServer);
  5044. t_directory newdir;
  5045. if (cache.Lookup(dir.path, m_CurrentServer, newdir))
  5046. dir = newdir;
  5047. }
  5048. #endif
  5049. BOOL updated = FALSE;
  5050. if (m_pDirectoryListing && m_pDirectoryListing->path == dir.path)
  5051. {
  5052. updated = TRUE;
  5053. SetDirectoryListing(&dir, WorkingDir.path == dir.path);
  5054. }
  5055. if (!updated)
  5056. if (WorkingDir.path == dir.path)
  5057. {
  5058. updated = TRUE;
  5059. m_pOwner->SetWorkingDir(&dir);
  5060. }
  5061. #ifndef MPEXT_NO_CACHE
  5062. BOOL bCached = TRUE;
  5063. BOOL res = cache.Lookup(pData->newPath, m_CurrentServer, dir);
  5064. if (!res)
  5065. bCached = FALSE;
  5066. #else
  5067. BOOL res = FALSE;
  5068. #endif
  5069. if (!res && m_pDirectoryListing)
  5070. {
  5071. if (m_pDirectoryListing->path == pData->newPath)
  5072. {
  5073. dir = *m_pDirectoryListing;
  5074. res = TRUE;
  5075. }
  5076. }
  5077. t_directory WorkingDir;
  5078. BOOL bFound = m_pOwner->GetWorkingDir(&WorkingDir);
  5079. if (!res && bFound)
  5080. if (WorkingDir.path == pData->newPath)
  5081. {
  5082. dir = WorkingDir;
  5083. res = TRUE;
  5084. }
  5085. if (res)
  5086. {
  5087. t_directory::t_direntry *direntry = new t_directory::t_direntry[dir.num + 1];
  5088. for (int i = 0; i < dir.num; i++)
  5089. direntry[i] = dir.direntry[i];
  5090. direntry[dir.num] = oldentry;
  5091. direntry[dir.num].name = pData->newName;
  5092. direntry[dir.num].lName = pData->newName;
  5093. direntry[dir.num].lName.MakeLower();
  5094. dir.num++;
  5095. delete [] dir.direntry;
  5096. dir.direntry = direntry;
  5097. #ifndef MPEXT_NO_CACHE
  5098. cache.Store(dir, bCached);
  5099. #endif
  5100. BOOL updated = FALSE;
  5101. if (m_pDirectoryListing && m_pDirectoryListing->path == dir.path)
  5102. {
  5103. updated = TRUE;
  5104. SetDirectoryListing(&dir, bFound && WorkingDir.path == dir.path);
  5105. }
  5106. if (!updated)
  5107. if (bFound && WorkingDir.path == dir.path)
  5108. {
  5109. updated = TRUE;
  5110. m_pOwner->SetWorkingDir(&dir);
  5111. }
  5112. }
  5113. }
  5114. break;
  5115. }
  5116. }
  5117. #ifndef MPEXT_NO_CACHE
  5118. cache.Unlock();
  5119. #endif
  5120. ResetOperation(FZ_REPLY_OK);
  5121. }
  5122. else
  5123. ResetOperation(FZ_REPLY_ERROR);
  5124. }
  5125. }
  5126. }
  5127. #ifndef MPEXT_NO_SSL
  5128. void CFtpControlSocket::SetVerifyCertResult(int nResult, t_SslCertData *pData)
  5129. {
  5130. ASSERT(pData);
  5131. if (!m_pSslLayer)
  5132. return;
  5133. if (!m_Operation.nOpMode == CSMODE_CONNECT)
  5134. return;
  5135. m_bCheckForTimeout = TRUE;
  5136. m_pSslLayer->SetNotifyReply(pData->priv_data, SSL_VERIFY_CERT, nResult);
  5137. m_LastRecvTime = CTime::GetCurrentTime();
  5138. }
  5139. #endif
  5140. void CFtpControlSocket::OnTimer()
  5141. {
  5142. CheckForTimeout();
  5143. ResumeTransfer();
  5144. if (COptions::GetOptionVal(OPTION_KEEPALIVE))
  5145. {
  5146. if (!m_pOwner->IsBusy() && m_pOwner->IsConnected() && !m_bKeepAliveActive)
  5147. {
  5148. //Getting intervals for the Keep Alive feature
  5149. int low=COptions::GetOptionVal(OPTION_INTERVALLOW);
  5150. int diff=COptions::GetOptionVal(OPTION_INTERVALHIGH)-low;
  5151. //Choose a new delay
  5152. #ifdef MPEXT
  5153. int delay=low+(rand()*diff)/RAND_MAX;
  5154. #else
  5155. static int delay=low+(rand()*diff)/RAND_MAX;
  5156. #endif
  5157. CTimeSpan span=CTime::GetCurrentTime()-m_LastSendTime;
  5158. if (span.GetTotalSeconds()>=delay)
  5159. SendKeepAliveCommand();
  5160. }
  5161. }
  5162. }
  5163. BOOL CFtpControlSocket::IsReady()
  5164. {
  5165. return !m_bKeepAliveActive;
  5166. }
  5167. void CFtpControlSocket::Chmod(CString filename, const CServerPath &path, int nValue)
  5168. {
  5169. m_Operation.nOpMode=CSMODE_CHMOD;
  5170. CString str;
  5171. str.Format( _T("SITE CHMOD %03d %s"), nValue, path.FormatFilename(filename));
  5172. Send(str);
  5173. }
  5174. void CFtpControlSocket::SetAsyncRequestResult(int nAction, CAsyncRequestData *pData)
  5175. {
  5176. switch (pData->nRequestType)
  5177. {
  5178. case FZ_ASYNCREQUEST_OVERWRITE:
  5179. SetFileExistsAction(nAction, (COverwriteRequestData *)pData);
  5180. break;
  5181. #ifndef MPEXT_NO_SSL
  5182. case FZ_ASYNCREQUEST_VERIFYCERT:
  5183. SetVerifyCertResult(nAction, ((CVerifyCertRequestData *)pData)->pCertData );
  5184. break;
  5185. #endif
  5186. #ifndef MPEXT_NO_GSS
  5187. case FZ_ASYNCREQUEST_GSS_AUTHFAILED:
  5188. if (m_Operation.nOpMode!=CSMODE_CONNECT || m_Operation.nOpState!=CONNECT_GSS_FAILED)
  5189. break;
  5190. if (!m_RecvBuffer.empty() && m_RecvBuffer.front() != "")
  5191. {
  5192. DoClose();
  5193. break;
  5194. }
  5195. if (!nAction)
  5196. {
  5197. DoClose(FZ_REPLY_CRITICALERROR|FZ_REPLY_CANCEL);
  5198. ShowStatus(IDS_ERRORMSG_INTERRUPTED,1);
  5199. break;
  5200. }
  5201. m_Operation.nOpState=-1;
  5202. LogOnToServer(TRUE);
  5203. break;
  5204. case FZ_ASYNCREQUEST_GSS_NEEDPASS:
  5205. if (m_Operation.nOpMode!=CSMODE_CONNECT ||
  5206. m_Operation.nOpState != CONNECT_GSS_NEEDPASS)
  5207. break;
  5208. if (!m_RecvBuffer.empty() && m_RecvBuffer.front() != "")
  5209. {
  5210. DoClose();
  5211. break;
  5212. }
  5213. if (!nAction)
  5214. {
  5215. DoClose(FZ_REPLY_CRITICALERROR|FZ_REPLY_CANCEL);
  5216. ShowStatus(IDS_ERRORMSG_INTERRUPTED,1);
  5217. break;
  5218. }
  5219. else
  5220. {
  5221. m_CurrentServer.pass=((CGssNeedPassRequestData *)pData)->pass;
  5222. m_Operation.nOpState=((CGssNeedPassRequestData *)pData)->nOldOpState;
  5223. LogOnToServer(TRUE);
  5224. }
  5225. break;
  5226. case FZ_ASYNCREQUEST_GSS_NEEDUSER:
  5227. if (m_Operation.nOpMode != CSMODE_CONNECT ||
  5228. m_Operation.nOpState != CONNECT_GSS_NEEDUSER)
  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. else
  5242. {
  5243. m_CurrentServer.user = ((CGssNeedUserRequestData *)pData)->user;
  5244. m_Operation.nOpState=((CGssNeedUserRequestData *)pData)->nOldOpState;
  5245. LogOnToServer(TRUE);
  5246. }
  5247. break;
  5248. #endif
  5249. default:
  5250. LogMessage(__FILE__, __LINE__, this,FZ_LOG_WARNING, _T("Unknown request reply %d"), pData->nRequestType);
  5251. break;
  5252. }
  5253. }
  5254. int CFtpControlSocket::OnLayerCallback(std::list<t_callbackMsg>& callbacks)
  5255. {
  5256. for (std::list<t_callbackMsg>::iterator iter = callbacks.begin(); iter != callbacks.end(); iter++)
  5257. {
  5258. if (iter->nType == LAYERCALLBACK_STATECHANGE)
  5259. {
  5260. #ifndef MPEXT_NO_SSL
  5261. if (iter->pLayer == m_pSslLayer)
  5262. {
  5263. LogMessage(__FILE__, __LINE__, this, FZ_LOG_INFO, _T("m_pSslLayer changed state from %d to %d"), iter->nParam2, iter->nParam1);
  5264. delete [] iter->str;
  5265. continue;
  5266. }
  5267. #endif
  5268. }
  5269. else if (iter->nType == LAYERCALLBACK_LAYERSPECIFIC)
  5270. {
  5271. #ifndef MPEXT_NO_SSL
  5272. if (iter->pLayer == m_pSslLayer)
  5273. {
  5274. USES_CONVERSION;
  5275. switch (iter->nParam1)
  5276. {
  5277. case SSL_INFO:
  5278. switch (iter->nParam2)
  5279. {
  5280. case SSL_INFO_ESTABLISHED:
  5281. ShowStatus(IDS_STATUSMSG_SSLESTABLISHED, 0);
  5282. PostMessage(m_pOwner->m_hOwnerWnd, m_pOwner->m_nReplyMessageID, FZ_MSG_MAKEMSG(FZ_MSG_SECURESERVER, 1), 0);
  5283. if (m_Operation.nOpState == CONNECT_SSL_WAITDONE)
  5284. {
  5285. LogOnToServer();
  5286. }
  5287. break;
  5288. }
  5289. break;
  5290. case SSL_FAILURE:
  5291. switch (iter->nParam2)
  5292. {
  5293. case SSL_FAILURE_UNKNOWN:
  5294. ShowStatus(IDS_ERRORMSG_UNKNOWNSSLERROR, 1);
  5295. break;
  5296. case SSL_FAILURE_ESTABLISH:
  5297. ShowStatus(IDS_ERRORMSG_CANTESTABLISHSSLCONNECTION, 1);
  5298. break;
  5299. #ifndef MPEXT_NO_SSLDLL
  5300. case SSL_FAILURE_LOADDLLS:
  5301. ShowStatus(IDS_ERRORMSG_CANTLOADSSLDLLS, 1);
  5302. break;
  5303. #endif
  5304. case SSL_FAILURE_INITSSL:
  5305. ShowStatus(IDS_ERRORMSG_CANTINITSSL, 1);
  5306. break;
  5307. case SSL_FAILURE_VERIFYCERT:
  5308. ShowStatus(IDS_ERRORMSG_SSLCERTIFICATEERROR, 1);
  5309. break;
  5310. case SSL_FAILURE_CERTREJECTED:
  5311. ShowStatus(IDS_ERRORMSG_CERTREJECTED, 1);
  5312. m_bDidRejectCertificate = TRUE;
  5313. break;
  5314. }
  5315. TriggerEvent(FD_CLOSE);
  5316. break;
  5317. case SSL_VERBOSE_INFO:
  5318. LogMessageRaw(FZ_LOG_INFO, A2CT(iter->str));
  5319. break;
  5320. case SSL_VERBOSE_WARNING:
  5321. LogMessageRaw(FZ_LOG_WARNING, A2CT(iter->str));
  5322. break;
  5323. case SSL_VERIFY_CERT:
  5324. t_SslCertData *pData = new t_SslCertData;
  5325. if (m_pSslLayer->GetPeerCertificateData(*pData))
  5326. {
  5327. CVerifyCertRequestData *pRequestData = new CVerifyCertRequestData;
  5328. pRequestData->nRequestID=m_pOwner->GetNextAsyncRequestID();
  5329. pRequestData->pCertData = pData;
  5330. m_bCheckForTimeout = FALSE;
  5331. if (!PostMessage(m_pOwner->m_hOwnerWnd, m_pOwner->m_nReplyMessageID, FZ_MSG_MAKEMSG(FZ_MSG_ASYNCREQUEST, FZ_ASYNCREQUEST_VERIFYCERT), (LPARAM)pRequestData))
  5332. {
  5333. delete pRequestData->pCertData;
  5334. delete pRequestData;
  5335. ResetOperation(FZ_REPLY_ERROR);
  5336. }
  5337. delete [] iter->str;
  5338. continue;
  5339. }
  5340. else
  5341. {
  5342. delete pData;
  5343. delete [] iter->str;
  5344. ResetOperation(FZ_REPLY_ERROR);
  5345. delete [] iter->str;
  5346. continue;
  5347. }
  5348. break;
  5349. }
  5350. delete [] iter->str;
  5351. continue;
  5352. }
  5353. #ifndef MPEXT_NO_GSS
  5354. else
  5355. #endif
  5356. #endif
  5357. #ifndef MPEXT_NO_GSS
  5358. if (iter->pLayer == m_pGssLayer)
  5359. {
  5360. if (iter->nParam1 == GSS_AUTHCOMPLETE ||
  5361. iter->nParam1 == GSS_AUTHFAILED)
  5362. {
  5363. LogOnToServer(TRUE);
  5364. delete [] iter->str;
  5365. continue;
  5366. }
  5367. }
  5368. #endif
  5369. }
  5370. std::list<t_callbackMsg> tmp;
  5371. tmp.push_back(*iter);
  5372. CControlSocket::OnLayerCallback(tmp);
  5373. }
  5374. return 0;
  5375. }
  5376. BOOL CFtpControlSocket::ParsePwdReply(CString& rawpwd)
  5377. {
  5378. CListData *pData = static_cast<CListData *>(m_Operation.pData);
  5379. ASSERT(pData);
  5380. int pos1 = rawpwd.Find('"');
  5381. int pos2 = rawpwd.ReverseFind('"');
  5382. if (pos1 == -1 || pos2 == -1 || pos1 >= pos2)
  5383. {
  5384. LogMessage(__FILE__, __LINE__, this, FZ_LOG_WARNING, _T("No quoted path found, try using first token as path"));
  5385. pos1 = rawpwd.Find(' ');
  5386. if (pos1 != -1)
  5387. {
  5388. pos2 = rawpwd.Find(' ', pos1 + 1);
  5389. if (pos2 == -1)
  5390. pos2 = rawpwd.GetLength();
  5391. }
  5392. if (pos1 == -1)
  5393. {
  5394. LogMessage(__FILE__, __LINE__, this, FZ_LOG_WARNING, _T("Can't parse path!"));
  5395. ResetOperation(FZ_REPLY_ERROR);
  5396. return FALSE;
  5397. }
  5398. }
  5399. rawpwd = rawpwd.Mid(pos1 + 1, pos2 - pos1 - 1);
  5400. CServerPath realPath = m_pOwner->GetCurrentPath();
  5401. realPath.SetServer(m_CurrentServer);
  5402. if (!realPath.SetPath(rawpwd))
  5403. {
  5404. LogMessage(__FILE__, __LINE__, this, FZ_LOG_WARNING, _T("Can't parse path!"));
  5405. ResetOperation(FZ_REPLY_ERROR);
  5406. return FALSE;
  5407. }
  5408. m_pOwner->SetCurrentPath(realPath);
  5409. return TRUE;
  5410. }
  5411. void CFtpControlSocket::DiscardLine(CStringA line)
  5412. {
  5413. if (m_Operation.nOpMode == CSMODE_CONNECT && m_Operation.nOpState == CONNECT_FEAT)
  5414. {
  5415. line.MakeUpper();
  5416. #ifndef MPEXT_NO_ZLIB
  5417. if (line == _T(" MODE Z") || line.Left(8) == _T(" MODE Z "))
  5418. m_zlibSupported = true;
  5419. else
  5420. #endif
  5421. if (line == _T(" UTF8") && m_CurrentServer.nUTF8 != 2)
  5422. m_bAnnouncesUTF8 = true;
  5423. else if (line == _T(" CLNT") || line.Left(6) == _T(" CLNT "))
  5424. m_hasClntCmd = true;
  5425. #ifdef MPEXT
  5426. else if (line == _T(" MFMT"))
  5427. m_hasMfmtCmd = true;
  5428. #endif
  5429. }
  5430. }
  5431. bool CFtpControlSocket::NeedModeCommand()
  5432. {
  5433. #ifdef MPEXT_NO_ZLIB
  5434. return false;
  5435. #else
  5436. bool useZlib;
  5437. if (m_Operation.nOpMode == CSMODE_LIST || (m_Operation.nOpMode == CSMODE_TRANSFER && m_Operation.nOpMode <= FILETRANSFER_TYPE))
  5438. useZlib = COptions::GetOptionVal(OPTION_MODEZ_USE) != 0;
  5439. else
  5440. useZlib = COptions::GetOptionVal(OPTION_MODEZ_USE) > 1;
  5441. if (!m_useZlib && !m_zlibSupported)
  5442. return false;
  5443. return m_useZlib != useZlib;
  5444. #endif
  5445. }
  5446. bool CFtpControlSocket::NeedOptsCommand()
  5447. {
  5448. #ifndef MPEXT_NO_ZLIB
  5449. if (!m_useZlib)
  5450. #endif
  5451. return false;
  5452. #ifndef MPEXT_NO_ZLIB
  5453. return m_zlibLevel != COptions::GetOptionVal(OPTION_MODEZ_LEVEL);
  5454. #endif
  5455. }
  5456. CString CFtpControlSocket::GetReply()
  5457. {
  5458. if (m_RecvBuffer.empty())
  5459. return "";
  5460. USES_CONVERSION;
  5461. if (m_bUTF8)
  5462. {
  5463. // convert from UTF-8 to ANSI
  5464. LPCSTR utf8 = (LPCSTR)m_RecvBuffer.front();
  5465. if (!utf8_valid((const unsigned char*)utf8, strlen(utf8)))
  5466. {
  5467. if (m_CurrentServer.nUTF8 != 1)
  5468. {
  5469. LogMessage(__FILE__, __LINE__, this, FZ_LOG_WARNING, _T("Server does not send proper UTF-8, falling back to local charset"));
  5470. m_bUTF8 = false;
  5471. }
  5472. return A2CT(m_RecvBuffer.front());
  5473. }
  5474. // convert from UTF-8 to ANSI
  5475. int len = MultiByteToWideChar(CP_UTF8, 0, utf8, -1, NULL, 0);
  5476. if (!len)
  5477. {
  5478. m_RecvBuffer.pop_front();
  5479. if (m_RecvBuffer.empty())
  5480. m_RecvBuffer.push_back("");
  5481. return "";
  5482. }
  5483. else
  5484. {
  5485. LPWSTR p1 = new WCHAR[len + 1];
  5486. MultiByteToWideChar(CP_UTF8, 0, utf8, -1 , (LPWSTR)p1, len + 1);
  5487. CString reply = W2CT(p1);
  5488. delete [] p1;
  5489. return reply;
  5490. }
  5491. }
  5492. else
  5493. return A2CT(m_RecvBuffer.front());
  5494. }
  5495. void CFtpControlSocket::OnSend(int nErrorCode)
  5496. {
  5497. if (!m_sendBufferLen || !m_sendBuffer || m_awaitsReply)
  5498. return;
  5499. int res = CAsyncSocketEx::Send(m_sendBuffer, m_sendBufferLen);
  5500. if (res == -1)
  5501. {
  5502. if (GetLastError() != WSAEWOULDBLOCK)
  5503. {
  5504. ShowStatus(IDS_ERRORMSG_CANTSENDCOMMAND, 1);
  5505. DoClose();
  5506. }
  5507. return;
  5508. }
  5509. if (!res)
  5510. {
  5511. ShowStatus(IDS_ERRORMSG_CANTSENDCOMMAND, 1);
  5512. DoClose();
  5513. }
  5514. m_awaitsReply = true;
  5515. m_LastSendTime = CTime::GetCurrentTime();
  5516. PostMessage(m_pOwner->m_hOwnerWnd, m_pOwner->m_nReplyMessageID, FZ_MSG_MAKEMSG(FZ_MSG_SOCKETSTATUS, FZ_SOCKETSTATUS_SEND), 0);
  5517. if (res == m_sendBufferLen)
  5518. {
  5519. delete [] m_sendBuffer;
  5520. m_sendBuffer = 0;
  5521. m_sendBufferLen = 0;
  5522. }
  5523. else
  5524. {
  5525. char* tmp = new char[m_sendBufferLen - res];
  5526. memcpy(tmp, m_sendBuffer + res, m_sendBufferLen - res);
  5527. delete [] m_sendBuffer;
  5528. m_sendBuffer = tmp;
  5529. m_sendBufferLen -= res;
  5530. }
  5531. }
  5532. bool CFtpControlSocket::IsMisleadingListResponse()
  5533. {
  5534. // Some servers are broken. Instead of an empty listing, some MVS servers
  5535. // for example they return something "550 no members found"
  5536. // Other servers return "550 No files found."
  5537. CString retmsg = GetReply();
  5538. if (!retmsg.CompareNoCase(_T("550 No members found.")))
  5539. return true;
  5540. if (!retmsg.CompareNoCase(_T("550 No data sets found.")))
  5541. return true;
  5542. if (!retmsg.CompareNoCase(_T("550 No files found.")))
  5543. return true;
  5544. return false;
  5545. }
  5546. #ifdef MPEXT
  5547. bool CFtpControlSocket::CheckForcePasvIp(CString & host)
  5548. {
  5549. bool result = true;
  5550. if (m_CurrentServer.bForcePasvIp)
  5551. {
  5552. unsigned int tmpPort;
  5553. CString ahost;
  5554. if (!GetPeerName(ahost, tmpPort))
  5555. {
  5556. LogMessage(__FILE__, __LINE__, this, FZ_LOG_WARNING, _T("GetPeerName failed"));
  5557. result = false;
  5558. }
  5559. else if (ahost != host)
  5560. {
  5561. LogMessage(__FILE__, __LINE__, this, FZ_LOG_WARNING, _T("Using host address %s instead of the one suggested by the server: %s"), ahost, host);
  5562. host = ahost;
  5563. }
  5564. }
  5565. return result;
  5566. }
  5567. #endif