FtpControlSocket.cpp 159 KB

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