1
0

FtpControlSocket.cpp 182 KB

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