FtpControlSocket.cpp 182 KB

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