FtpControlSocket.cpp 178 KB

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