FtpControlSocket.cpp 182 KB

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