FtpControlSocket.cpp 183 KB

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