FtpControlSocket.cpp 172 KB

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