1
0

FtpControlSocket.cpp 182 KB

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