FtpControlSocket.cpp 154 KB

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