FtpControlSocket.cpp 182 KB

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