FtpControlSocket.cpp 172 KB

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