FtpControlSocket.cpp 170 KB

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