FtpControlSocket.cpp 172 KB

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