FtpControlSocket.cpp 178 KB

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