FtpControlSocket.cpp 183 KB

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