FtpControlSocket.cpp 182 KB

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