FtpControlSocket.cpp 178 KB

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