FtpControlSocket.cpp 183 KB

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