FtpControlSocket.cpp 154 KB

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