FtpControlSocket.cpp 183 KB

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