FtpControlSocket.cpp 155 KB

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