FtpControlSocket.cpp 183 KB

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