FtpControlSocket.cpp 183 KB

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