FtpControlSocket.cpp 182 KB

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