Terminal.cpp 261 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339
  1. //---------------------------------------------------------------------------
  2. #include <vcl.h>
  3. #pragma hdrstop
  4. #include "Terminal.h"
  5. #include <SysUtils.hpp>
  6. #include <FileCtrl.hpp>
  7. #include <StrUtils.hpp>
  8. #include <System.IOUtils.hpp>
  9. #include "Common.h"
  10. #include "PuttyTools.h"
  11. #include "FileBuffer.h"
  12. #include "Interface.h"
  13. #include "RemoteFiles.h"
  14. #include "SecureShell.h"
  15. #include "ScpFileSystem.h"
  16. #include "SftpFileSystem.h"
  17. #include "FtpFileSystem.h"
  18. #include "WebDAVFileSystem.h"
  19. #include "S3FileSystem.h"
  20. #include "TextsCore.h"
  21. #include "HelpCore.h"
  22. #include "CoreMain.h"
  23. #include "Queue.h"
  24. #include "Cryptography.h"
  25. #include <openssl/pkcs12.h>
  26. #include <openssl/err.h>
  27. #ifndef AUTO_WINSOCK
  28. #include <winsock2.h>
  29. #endif
  30. //---------------------------------------------------------------------------
  31. #pragma package(smart_init)
  32. //---------------------------------------------------------------------------
  33. #define FILE_OPERATION_LOOP_TERMINAL this
  34. //---------------------------------------------------------------------------
  35. //---------------------------------------------------------------------------
  36. class TLoopDetector
  37. {
  38. public:
  39. __fastcall TLoopDetector();
  40. void __fastcall RecordVisitedDirectory(const UnicodeString & Directory);
  41. bool __fastcall IsUnvisitedDirectory(const UnicodeString & Directory);
  42. private:
  43. std::unique_ptr<TStringList> FVisitedDirectories;
  44. };
  45. //---------------------------------------------------------------------------
  46. __fastcall TLoopDetector::TLoopDetector()
  47. {
  48. FVisitedDirectories.reset(CreateSortedStringList());
  49. }
  50. //---------------------------------------------------------------------------
  51. void __fastcall TLoopDetector::RecordVisitedDirectory(const UnicodeString & Directory)
  52. {
  53. UnicodeString VisitedDirectory = ExcludeTrailingBackslash(Directory);
  54. FVisitedDirectories->Add(VisitedDirectory);
  55. }
  56. //---------------------------------------------------------------------------
  57. bool __fastcall TLoopDetector::IsUnvisitedDirectory(const UnicodeString & Directory)
  58. {
  59. bool Result = (FVisitedDirectories->IndexOf(Directory) < 0);
  60. if (Result)
  61. {
  62. RecordVisitedDirectory(Directory);
  63. }
  64. return Result;
  65. }
  66. //---------------------------------------------------------------------------
  67. //---------------------------------------------------------------------------
  68. struct TMoveFileParams
  69. {
  70. UnicodeString Target;
  71. UnicodeString FileMask;
  72. };
  73. //---------------------------------------------------------------------------
  74. struct TFilesFindParams
  75. {
  76. TFileMasks FileMask;
  77. TFileFoundEvent OnFileFound;
  78. TFindingFileEvent OnFindingFile;
  79. bool Cancel;
  80. TLoopDetector LoopDetector;
  81. UnicodeString RealDirectory;
  82. };
  83. //---------------------------------------------------------------------------
  84. TCalculateSizeStats::TCalculateSizeStats()
  85. {
  86. memset(this, 0, sizeof(*this));
  87. }
  88. //---------------------------------------------------------------------------
  89. TCalculateSizeParams::TCalculateSizeParams()
  90. {
  91. memset(this, 0, sizeof(*this));
  92. Result = true;
  93. AllowDirs = true;
  94. }
  95. //---------------------------------------------------------------------------
  96. TSynchronizeOptions::TSynchronizeOptions()
  97. {
  98. memset(this, 0, sizeof(*this));
  99. }
  100. //---------------------------------------------------------------------------
  101. TSynchronizeOptions::~TSynchronizeOptions()
  102. {
  103. delete Filter;
  104. }
  105. //---------------------------------------------------------------------------
  106. bool __fastcall TSynchronizeOptions::MatchesFilter(const UnicodeString & FileName)
  107. {
  108. int FoundIndex;
  109. bool Result;
  110. if (Filter == NULL)
  111. {
  112. Result = true;
  113. }
  114. else
  115. {
  116. Result = Filter->Find(FileName, FoundIndex);
  117. }
  118. return Result;
  119. }
  120. //---------------------------------------------------------------------------
  121. TSpaceAvailable::TSpaceAvailable()
  122. {
  123. memset(this, 0, sizeof(*this));
  124. }
  125. //---------------------------------------------------------------------------
  126. TOverwriteFileParams::TOverwriteFileParams()
  127. {
  128. SourceSize = 0;
  129. DestSize = 0;
  130. SourcePrecision = mfFull;
  131. DestPrecision = mfFull;
  132. }
  133. //---------------------------------------------------------------------------
  134. //---------------------------------------------------------------------------
  135. class TTunnelThread : public TSimpleThread
  136. {
  137. public:
  138. __fastcall TTunnelThread(TSecureShell * SecureShell);
  139. virtual __fastcall ~TTunnelThread();
  140. virtual void __fastcall Terminate();
  141. protected:
  142. virtual void __fastcall Execute();
  143. private:
  144. TSecureShell * FSecureShell;
  145. bool FTerminated;
  146. };
  147. //---------------------------------------------------------------------------
  148. __fastcall TTunnelThread::TTunnelThread(TSecureShell * SecureShell) :
  149. FSecureShell(SecureShell),
  150. FTerminated(false)
  151. {
  152. Start();
  153. }
  154. //---------------------------------------------------------------------------
  155. __fastcall TTunnelThread::~TTunnelThread()
  156. {
  157. // close before the class's virtual functions (Terminate particularly) are lost
  158. Close();
  159. }
  160. //---------------------------------------------------------------------------
  161. void __fastcall TTunnelThread::Terminate()
  162. {
  163. FTerminated = true;
  164. }
  165. //---------------------------------------------------------------------------
  166. void __fastcall TTunnelThread::Execute()
  167. {
  168. try
  169. {
  170. while (!FTerminated)
  171. {
  172. FSecureShell->Idle(250);
  173. }
  174. }
  175. catch(...)
  176. {
  177. if (FSecureShell->Active)
  178. {
  179. FSecureShell->Close();
  180. }
  181. // do not pass exception out of thread's proc
  182. }
  183. }
  184. //---------------------------------------------------------------------------
  185. //---------------------------------------------------------------------------
  186. class TTunnelUI : public TSessionUI
  187. {
  188. public:
  189. __fastcall TTunnelUI(TTerminal * Terminal);
  190. virtual void __fastcall Information(const UnicodeString & Str, bool Status);
  191. virtual unsigned int __fastcall QueryUser(const UnicodeString Query,
  192. TStrings * MoreMessages, unsigned int Answers, const TQueryParams * Params,
  193. TQueryType QueryType);
  194. virtual unsigned int __fastcall QueryUserException(const UnicodeString Query,
  195. Exception * E, unsigned int Answers, const TQueryParams * Params,
  196. TQueryType QueryType);
  197. virtual bool __fastcall PromptUser(TSessionData * Data, TPromptKind Kind,
  198. UnicodeString Name, UnicodeString Instructions, TStrings * Prompts,
  199. TStrings * Results);
  200. virtual void __fastcall DisplayBanner(const UnicodeString & Banner);
  201. virtual void __fastcall FatalError(Exception * E, UnicodeString Msg, UnicodeString HelpContext);
  202. virtual void __fastcall HandleExtendedException(Exception * E);
  203. virtual void __fastcall Closed();
  204. virtual void __fastcall ProcessGUI();
  205. private:
  206. TTerminal * FTerminal;
  207. unsigned int FTerminalThread;
  208. };
  209. //---------------------------------------------------------------------------
  210. __fastcall TTunnelUI::TTunnelUI(TTerminal * Terminal)
  211. {
  212. FTerminal = Terminal;
  213. FTerminalThread = GetCurrentThreadId();
  214. }
  215. //---------------------------------------------------------------------------
  216. void __fastcall TTunnelUI::Information(const UnicodeString & Str, bool Status)
  217. {
  218. if (GetCurrentThreadId() == FTerminalThread)
  219. {
  220. FTerminal->Information(Str, Status);
  221. }
  222. }
  223. //---------------------------------------------------------------------------
  224. unsigned int __fastcall TTunnelUI::QueryUser(const UnicodeString Query,
  225. TStrings * MoreMessages, unsigned int Answers, const TQueryParams * Params,
  226. TQueryType QueryType)
  227. {
  228. unsigned int Result;
  229. if (GetCurrentThreadId() == FTerminalThread)
  230. {
  231. Result = FTerminal->QueryUser(Query, MoreMessages, Answers, Params, QueryType);
  232. }
  233. else
  234. {
  235. Result = AbortAnswer(Answers);
  236. }
  237. return Result;
  238. }
  239. //---------------------------------------------------------------------------
  240. unsigned int __fastcall TTunnelUI::QueryUserException(const UnicodeString Query,
  241. Exception * E, unsigned int Answers, const TQueryParams * Params,
  242. TQueryType QueryType)
  243. {
  244. unsigned int Result;
  245. if (GetCurrentThreadId() == FTerminalThread)
  246. {
  247. Result = FTerminal->QueryUserException(Query, E, Answers, Params, QueryType);
  248. }
  249. else
  250. {
  251. Result = AbortAnswer(Answers);
  252. }
  253. return Result;
  254. }
  255. //---------------------------------------------------------------------------
  256. bool __fastcall TTunnelUI::PromptUser(TSessionData * Data, TPromptKind Kind,
  257. UnicodeString Name, UnicodeString Instructions, TStrings * Prompts, TStrings * Results)
  258. {
  259. bool Result;
  260. if (GetCurrentThreadId() == FTerminalThread)
  261. {
  262. if (IsAuthenticationPrompt(Kind))
  263. {
  264. Instructions =
  265. FMTLOAD(TUNNEL_INSTRUCTION2, (Data->HostName)) +
  266. (Instructions.IsEmpty() ? L"" : L"\n") +
  267. Instructions;
  268. }
  269. Result = FTerminal->PromptUser(Data, Kind, Name, Instructions, Prompts, Results);
  270. }
  271. else
  272. {
  273. Result = false;
  274. }
  275. return Result;
  276. }
  277. //---------------------------------------------------------------------------
  278. void __fastcall TTunnelUI::DisplayBanner(const UnicodeString & Banner)
  279. {
  280. if (GetCurrentThreadId() == FTerminalThread)
  281. {
  282. FTerminal->DisplayBanner(Banner);
  283. }
  284. }
  285. //---------------------------------------------------------------------------
  286. void __fastcall TTunnelUI::FatalError(Exception * E, UnicodeString Msg, UnicodeString HelpKeyword)
  287. {
  288. throw ESshFatal(E, Msg, HelpKeyword);
  289. }
  290. //---------------------------------------------------------------------------
  291. void __fastcall TTunnelUI::HandleExtendedException(Exception * E)
  292. {
  293. if (GetCurrentThreadId() == FTerminalThread)
  294. {
  295. FTerminal->HandleExtendedException(E);
  296. }
  297. }
  298. //---------------------------------------------------------------------------
  299. void __fastcall TTunnelUI::Closed()
  300. {
  301. // noop
  302. }
  303. //---------------------------------------------------------------------------
  304. void __fastcall TTunnelUI::ProcessGUI()
  305. {
  306. // noop
  307. }
  308. //---------------------------------------------------------------------------
  309. //---------------------------------------------------------------------------
  310. class TCallbackGuard
  311. {
  312. public:
  313. inline __fastcall TCallbackGuard(TTerminal * FTerminal);
  314. inline __fastcall ~TCallbackGuard();
  315. void __fastcall FatalError(Exception * E, const UnicodeString & Msg, const UnicodeString & HelpKeyword);
  316. inline void __fastcall Verify();
  317. inline bool __fastcall Verify(Exception * E);
  318. void __fastcall Dismiss();
  319. private:
  320. ExtException * FFatalError;
  321. TTerminal * FTerminal;
  322. bool FGuarding;
  323. };
  324. //---------------------------------------------------------------------------
  325. __fastcall TCallbackGuard::TCallbackGuard(TTerminal * Terminal) :
  326. FTerminal(Terminal),
  327. FFatalError(NULL),
  328. FGuarding(FTerminal->FCallbackGuard == NULL)
  329. {
  330. if (FGuarding)
  331. {
  332. FTerminal->FCallbackGuard = this;
  333. }
  334. }
  335. //---------------------------------------------------------------------------
  336. __fastcall TCallbackGuard::~TCallbackGuard()
  337. {
  338. if (FGuarding)
  339. {
  340. DebugAssert((FTerminal->FCallbackGuard == this) || (FTerminal->FCallbackGuard == NULL));
  341. FTerminal->FCallbackGuard = NULL;
  342. }
  343. delete FFatalError;
  344. }
  345. //---------------------------------------------------------------------------
  346. void __fastcall TCallbackGuard::FatalError(Exception * E, const UnicodeString & Msg, const UnicodeString & HelpKeyword)
  347. {
  348. DebugAssert(FGuarding);
  349. // make sure we do not bother about getting back the silent abort exception
  350. // we issued ourselves. this may happen when there is an exception handler
  351. // that converts any exception to fatal one (such as in TTerminal::Open).
  352. if (dynamic_cast<ECallbackGuardAbort *>(E) == NULL)
  353. {
  354. delete FFatalError;
  355. FFatalError = new ExtException(E, Msg, HelpKeyword);
  356. }
  357. // silently abort what we are doing.
  358. // non-silent exception would be caught probably by default application
  359. // exception handler, which may not do an appropriate action
  360. // (particularly it will not resume broken transfer).
  361. throw ECallbackGuardAbort();
  362. }
  363. //---------------------------------------------------------------------------
  364. void __fastcall TCallbackGuard::Dismiss()
  365. {
  366. DebugAssert(FFatalError == NULL);
  367. FGuarding = false;
  368. }
  369. //---------------------------------------------------------------------------
  370. void __fastcall TCallbackGuard::Verify()
  371. {
  372. if (FGuarding)
  373. {
  374. FGuarding = false;
  375. DebugAssert(FTerminal->FCallbackGuard == this);
  376. FTerminal->FCallbackGuard = NULL;
  377. if (FFatalError != NULL)
  378. {
  379. throw ESshFatal(FFatalError, L"");
  380. }
  381. }
  382. }
  383. //---------------------------------------------------------------------------
  384. bool __fastcall TCallbackGuard::Verify(Exception * E)
  385. {
  386. bool Result =
  387. (dynamic_cast<ECallbackGuardAbort *>(E) != NULL);
  388. if (Result)
  389. {
  390. DebugAssert(FGuarding && (FFatalError != NULL));
  391. Verify();
  392. }
  393. return Result;
  394. }
  395. //---------------------------------------------------------------------------
  396. //---------------------------------------------------------------------------
  397. TRobustOperationLoop::TRobustOperationLoop(
  398. TTerminal * Terminal, TFileOperationProgressType * OperationProgress, bool * AnyTransfer, bool CanRetry) :
  399. FTerminal(Terminal),
  400. FOperationProgress(OperationProgress),
  401. FRetry(false),
  402. FAnyTransfer(AnyTransfer),
  403. FCanRetry(CanRetry)
  404. {
  405. if (FAnyTransfer != NULL)
  406. {
  407. FPrevAnyTransfer = *FAnyTransfer;
  408. *FAnyTransfer = false;
  409. FStart = Now();
  410. }
  411. }
  412. //---------------------------------------------------------------------------
  413. TRobustOperationLoop::~TRobustOperationLoop()
  414. {
  415. if (FAnyTransfer != NULL)
  416. {
  417. *FAnyTransfer = FPrevAnyTransfer;
  418. }
  419. }
  420. //---------------------------------------------------------------------------
  421. bool TRobustOperationLoop::TryReopen(Exception & E)
  422. {
  423. if (!FCanRetry)
  424. {
  425. FRetry = false;
  426. }
  427. else if (dynamic_cast<ESkipFile *>(&E) != NULL)
  428. {
  429. FRetry = false;
  430. }
  431. else if (FTerminal->Active)
  432. {
  433. FTerminal->LogEvent(1, L"Session is open, will not retry transfer");
  434. FRetry = false;
  435. }
  436. else
  437. {
  438. FRetry = true;
  439. if (FAnyTransfer != NULL)
  440. {
  441. // if there was any transfer, reset the global timestamp
  442. if (*FAnyTransfer)
  443. {
  444. FStart = Now();
  445. FPrevAnyTransfer = true;
  446. *FAnyTransfer = false;
  447. }
  448. else
  449. {
  450. FRetry = FTerminal->ContinueReopen(FStart);
  451. if (!FRetry)
  452. {
  453. FTerminal->LogEvent(L"Retry interval expired, will not retry transfer");
  454. }
  455. }
  456. }
  457. if (FRetry)
  458. {
  459. FRetry =
  460. FTerminal->QueryReopen(&E, ropNoReadDirectory, FOperationProgress);
  461. }
  462. }
  463. return FRetry;
  464. }
  465. //---------------------------------------------------------------------------
  466. bool TRobustOperationLoop::ShouldRetry()
  467. {
  468. return FRetry;
  469. }
  470. //---------------------------------------------------------------------------
  471. bool TRobustOperationLoop::Retry()
  472. {
  473. bool Result = FRetry;
  474. FRetry = false;
  475. return Result;
  476. }
  477. //---------------------------------------------------------------------------
  478. class TRetryOperationLoop
  479. {
  480. public:
  481. TRetryOperationLoop(TTerminal * Terminal);
  482. void Error(Exception & E);
  483. void Error(Exception & E, TSessionAction & Action);
  484. void Error(Exception & E, const UnicodeString & Message);
  485. void Error(Exception & E, TSessionAction & Action, const UnicodeString & Message);
  486. bool Retry();
  487. bool Succeeded();
  488. private:
  489. TTerminal * FTerminal;
  490. bool FRetry;
  491. bool FSucceeded;
  492. void DoError(Exception & E, TSessionAction * Action, const UnicodeString & Message);
  493. };
  494. //---------------------------------------------------------------------------
  495. TRetryOperationLoop::TRetryOperationLoop(TTerminal * Terminal)
  496. {
  497. FTerminal = Terminal;
  498. FRetry = false;
  499. FSucceeded = true;
  500. }
  501. //---------------------------------------------------------------------------
  502. void TRetryOperationLoop::DoError(Exception & E, TSessionAction * Action, const UnicodeString & Message)
  503. {
  504. FSucceeded = false;
  505. // Note that the action may already be canceled when RollbackAction is called
  506. unsigned int Result;
  507. try
  508. {
  509. Result = FTerminal->CommandError(&E, Message, qaRetry | qaSkip | qaAbort);
  510. }
  511. catch (Exception & E2)
  512. {
  513. if (Action != NULL)
  514. {
  515. FTerminal->RollbackAction(*Action, NULL, &E2);
  516. }
  517. throw;
  518. }
  519. switch (Result)
  520. {
  521. case qaRetry:
  522. FRetry = true;
  523. if (Action != NULL)
  524. {
  525. Action->Cancel();
  526. }
  527. break;
  528. case qaAbort:
  529. if (Action != NULL)
  530. {
  531. FTerminal->RollbackAction(*Action, NULL, &E);
  532. }
  533. Abort();
  534. break;
  535. case qaSkip:
  536. if (Action != NULL)
  537. {
  538. Action->Cancel();
  539. }
  540. break;
  541. default:
  542. DebugFail();
  543. break;
  544. }
  545. }
  546. //---------------------------------------------------------------------------
  547. void TRetryOperationLoop::Error(Exception & E)
  548. {
  549. DoError(E, NULL, UnicodeString());
  550. }
  551. //---------------------------------------------------------------------------
  552. void TRetryOperationLoop::Error(Exception & E, TSessionAction & Action)
  553. {
  554. DoError(E, &Action, UnicodeString());
  555. }
  556. //---------------------------------------------------------------------------
  557. void TRetryOperationLoop::Error(Exception & E, const UnicodeString & Message)
  558. {
  559. DoError(E, NULL, Message);
  560. }
  561. //---------------------------------------------------------------------------
  562. void TRetryOperationLoop::Error(Exception & E, TSessionAction & Action, const UnicodeString & Message)
  563. {
  564. DoError(E, &Action, Message);
  565. }
  566. //---------------------------------------------------------------------------
  567. bool TRetryOperationLoop::Retry()
  568. {
  569. bool Result = FRetry;
  570. FRetry = false;
  571. if (Result)
  572. {
  573. FSucceeded = true;
  574. }
  575. return Result;
  576. }
  577. //---------------------------------------------------------------------------
  578. bool TRetryOperationLoop::Succeeded()
  579. {
  580. return FSucceeded;
  581. }
  582. //---------------------------------------------------------------------------
  583. //---------------------------------------------------------------------------
  584. TCollectedFileList::TCollectedFileList()
  585. {
  586. }
  587. //---------------------------------------------------------------------------
  588. int TCollectedFileList::Add(const UnicodeString & FileName, TObject * Object, bool Dir)
  589. {
  590. TFileData Data;
  591. Data.FileName = FileName;
  592. Data.Object = Object;
  593. Data.Dir = Dir;
  594. Data.Recursed = true;
  595. Data.State = 0;
  596. FList.push_back(Data);
  597. return Count() - 1;
  598. }
  599. //---------------------------------------------------------------------------
  600. void TCollectedFileList::DidNotRecurse(int Index)
  601. {
  602. FList[Index].Recursed = false;
  603. }
  604. //---------------------------------------------------------------------------
  605. void TCollectedFileList::Delete(int Index)
  606. {
  607. FList.erase(FList.begin() + Index);
  608. }
  609. //---------------------------------------------------------------------------
  610. int TCollectedFileList::Count() const
  611. {
  612. return FList.size();
  613. }
  614. //---------------------------------------------------------------------------
  615. UnicodeString TCollectedFileList::GetFileName(int Index) const
  616. {
  617. return FList[Index].FileName;
  618. }
  619. //---------------------------------------------------------------------------
  620. TObject * TCollectedFileList::GetObject(int Index) const
  621. {
  622. return FList[Index].Object;
  623. }
  624. //---------------------------------------------------------------------------
  625. bool TCollectedFileList::IsDir(int Index) const
  626. {
  627. return FList[Index].Dir;
  628. }
  629. //---------------------------------------------------------------------------
  630. bool TCollectedFileList::IsRecursed(int Index) const
  631. {
  632. return FList[Index].Recursed;
  633. }
  634. //---------------------------------------------------------------------------
  635. int TCollectedFileList::GetState(int Index) const
  636. {
  637. return FList[Index].State;
  638. }
  639. //---------------------------------------------------------------------------
  640. void TCollectedFileList::SetState(int Index, int State)
  641. {
  642. FList[Index].State = State;
  643. }
  644. //---------------------------------------------------------------------------
  645. //---------------------------------------------------------------------------
  646. TParallelOperation::TParallelOperation(TOperationSide Side)
  647. {
  648. FCopyParam = NULL;
  649. FParams = 0;
  650. FProbablyEmpty = false;
  651. FClients = 0;
  652. FMainOperationProgress = NULL;
  653. DebugAssert((Side == osLocal) || (Side == osRemote));
  654. FSide = Side;
  655. FVersion = 0;
  656. }
  657. //---------------------------------------------------------------------------
  658. void TParallelOperation::Init(
  659. TStrings * AFileList, const UnicodeString & TargetDir, const TCopyParamType * CopyParam, int Params,
  660. TFileOperationProgressType * MainOperationProgress, const UnicodeString & MainName)
  661. {
  662. DebugAssert(FFileList.get() == NULL);
  663. // More lists should really happen in scripting only, which does not support parallel transfers atm.
  664. // But in general the code should work with more lists anyway, it just was not tested for it.
  665. DebugAssert(AFileList->Count == 1);
  666. FFileList.reset(AFileList);
  667. FSection.reset(new TCriticalSection());
  668. FTargetDir = TargetDir;
  669. FCopyParam = CopyParam;
  670. FParams = Params;
  671. FMainOperationProgress = MainOperationProgress;
  672. FMainName = MainName;
  673. FListIndex = 0;
  674. FIndex = 0;
  675. }
  676. //---------------------------------------------------------------------------
  677. TParallelOperation::~TParallelOperation()
  678. {
  679. WaitFor();
  680. }
  681. //---------------------------------------------------------------------------
  682. bool TParallelOperation::IsInitialized()
  683. {
  684. return (FMainOperationProgress != NULL);
  685. }
  686. //---------------------------------------------------------------------------
  687. bool TParallelOperation::ShouldAddClient()
  688. {
  689. bool Result;
  690. // TTransferQueueItem::ProgressUpdated() already checks IsInitialized() before calling this
  691. if (!IsInitialized())
  692. {
  693. Result = false;
  694. }
  695. else
  696. {
  697. TGuard Guard(FSection.get());
  698. Result = !FProbablyEmpty && (FMainOperationProgress->Cancel < csCancel);
  699. }
  700. return Result;
  701. }
  702. //---------------------------------------------------------------------------
  703. void TParallelOperation::AddClient()
  704. {
  705. TGuard Guard(FSection.get());
  706. FClients++;
  707. }
  708. //---------------------------------------------------------------------------
  709. void TParallelOperation::RemoveClient()
  710. {
  711. TGuard Guard(FSection.get());
  712. FClients--;
  713. }
  714. //---------------------------------------------------------------------------
  715. void TParallelOperation::WaitFor()
  716. {
  717. // Even initialized?
  718. // Won't be, when parallel transfers were not possible (like when preserving of directory timestamps is enabled)
  719. if (FSection.get() != NULL)
  720. {
  721. bool Done;
  722. do
  723. {
  724. {
  725. TGuard Guard(FSection.get());
  726. Done = (FClients == 0);
  727. }
  728. if (!Done)
  729. {
  730. // propagate the total progress incremented by the parallel operations
  731. FMainOperationProgress->Progress();
  732. Sleep(200);
  733. }
  734. }
  735. while (!Done);
  736. FProbablyEmpty = true;
  737. }
  738. else
  739. {
  740. DebugAssert(FClients == 0);
  741. }
  742. }
  743. //---------------------------------------------------------------------------
  744. void TParallelOperation::Done(const UnicodeString & FileName, bool Dir, bool Success)
  745. {
  746. if (Dir)
  747. {
  748. TGuard Guard(FSection.get());
  749. TDirectories::iterator DirectoryIterator = FDirectories.find(FileName);
  750. if (DebugAlwaysTrue(DirectoryIterator != FDirectories.end()))
  751. {
  752. if (Success)
  753. {
  754. DebugAssert(!DirectoryIterator->second.Exists);
  755. DirectoryIterator->second.Exists = true;
  756. }
  757. else
  758. {
  759. // This is actually not useful at the moment, as when creating directory fails and "Skip" is pressed,
  760. // the current code in CopyToRemote/CreateDirectory will behave as, if it succedded, so Successs will be true here.
  761. FDirectories.erase(DirectoryIterator);
  762. if (FFileList->Count > FListIndex)
  763. {
  764. UnicodeString FileNameWithSlash;
  765. if (FSide == osLocal)
  766. {
  767. FileNameWithSlash = IncludeTrailingBackslash(FileName);
  768. }
  769. else
  770. {
  771. FileNameWithSlash = UnixIncludeTrailingBackslash(FileName);
  772. }
  773. // It can actually be a different list than the one the directory was taken from,
  774. // but that does not matter that much. It should not happen anyway, as more lists should be in scripting only.
  775. TCollectedFileList * Files = GetFileList(FListIndex);
  776. int Index = 0;
  777. while (Index < Files->Count())
  778. {
  779. if (StartsText(FileNameWithSlash, Files->GetFileName(Index)))
  780. {
  781. // We should add the file to "skip" counters in the OperationProgress,
  782. // but an interactive foreground transfer is not doing that either yet.
  783. Files->Delete(Index);
  784. // Force re-update
  785. FVersion++;
  786. if (Index < FIndex)
  787. {
  788. FIndex--;
  789. }
  790. }
  791. else
  792. {
  793. Index++;
  794. }
  795. }
  796. }
  797. }
  798. }
  799. }
  800. }
  801. //---------------------------------------------------------------------------
  802. bool TParallelOperation::CheckEnd(TCollectedFileList * Files)
  803. {
  804. bool Result = (FIndex >= Files->Count());
  805. if (Result)
  806. {
  807. FListIndex++;
  808. FIndex = 0;
  809. }
  810. return Result;
  811. }
  812. //---------------------------------------------------------------------------
  813. TCollectedFileList * TParallelOperation::GetFileList(int Index)
  814. {
  815. return DebugNotNull(dynamic_cast<TCollectedFileList *>(FFileList->Objects[Index]));
  816. }
  817. //---------------------------------------------------------------------------
  818. int TParallelOperation::GetNext(TTerminal * Terminal, UnicodeString & FileName, TObject *& Object, UnicodeString & TargetDir, bool & Dir, bool & Recursed)
  819. {
  820. TGuard Guard(FSection.get());
  821. int Result = 1;
  822. TCollectedFileList * Files;
  823. do
  824. {
  825. if (FFileList->Count > FListIndex)
  826. {
  827. Files = GetFileList(FListIndex);
  828. // can happen if the file was excluded by file mask
  829. if (CheckEnd(Files))
  830. {
  831. Files = NULL;
  832. }
  833. }
  834. else
  835. {
  836. Files = NULL;
  837. Result = -1;
  838. }
  839. }
  840. while ((Result == 1) && (Files == NULL));
  841. if (Files != NULL)
  842. {
  843. UnicodeString RootPath = FFileList->Strings[FListIndex];
  844. FileName = Files->GetFileName(FIndex);
  845. Object = Files->GetObject(FIndex);
  846. Dir = Files->IsDir(FIndex);
  847. Recursed = Files->IsRecursed(FIndex);
  848. UnicodeString DirPath;
  849. bool FirstLevel;
  850. if (FSide == osLocal)
  851. {
  852. DirPath = ExtractFileDir(FileName);
  853. FirstLevel = SamePaths(DirPath, RootPath);
  854. }
  855. else
  856. {
  857. DirPath = UnixExtractFileDir(FileName);
  858. FirstLevel = UnixSamePath(DirPath, RootPath);
  859. }
  860. if (FirstLevel)
  861. {
  862. TargetDir = FTargetDir;
  863. }
  864. else
  865. {
  866. TDirectories::const_iterator DirectoryIterator = FDirectories.find(DirPath);
  867. if (DebugAlwaysFalse(DirectoryIterator == FDirectories.end()))
  868. {
  869. throw EInvalidOperation(L"Parent path not known");
  870. }
  871. const TDirectoryData & DirectoryData = DirectoryIterator->second;
  872. if (!DirectoryData.Exists)
  873. {
  874. Result = 0; // wait for parent directory to be created
  875. }
  876. else
  877. {
  878. TargetDir = DirectoryData.OppositePath;
  879. }
  880. }
  881. if (!TargetDir.IsEmpty())
  882. {
  883. if (Dir)
  884. {
  885. TDirectoryData DirectoryData;
  886. UnicodeString OnlyFileName;
  887. if (FSide == osLocal)
  888. {
  889. OnlyFileName = ExtractFileName(FileName);
  890. }
  891. else
  892. {
  893. OnlyFileName = UnixExtractFileName(FileName);
  894. }
  895. OnlyFileName = Terminal->ChangeFileName(FCopyParam, OnlyFileName, osRemote, FirstLevel);
  896. if (FSide == osLocal)
  897. {
  898. DirectoryData.OppositePath = UnixCombinePaths(TargetDir, OnlyFileName);
  899. }
  900. else
  901. {
  902. DirectoryData.OppositePath = TPath::Combine(TargetDir, OnlyFileName);
  903. }
  904. DirectoryData.Exists = false;
  905. FDirectories.insert(std::make_pair(FileName, DirectoryData));
  906. }
  907. // The current implementation of UpdateFileList relies on this specific way of changing state
  908. // (all files before FIndex one-by-one)
  909. Files->SetState(FIndex, qfsProcessed);
  910. FIndex++;
  911. CheckEnd(Files);
  912. }
  913. }
  914. FProbablyEmpty = (FFileList->Count == FListIndex);
  915. return Result;
  916. }
  917. //---------------------------------------------------------------------------
  918. bool TParallelOperation::UpdateFileList(TQueueFileList * UpdateFileList)
  919. {
  920. TGuard Guard(FSection.get());
  921. bool Result =
  922. (UpdateFileList->FLastParallelOperation != this) ||
  923. (UpdateFileList->FLastParallelOperationVersion != FVersion);
  924. DebugAssert(FFileList->Count == 1);
  925. TCollectedFileList * Files = GetFileList(0);
  926. if (!Result && (UpdateFileList->GetCount() != Files->Count()))
  927. {
  928. DebugAssert(false);
  929. Result = true;
  930. }
  931. if (Result)
  932. {
  933. UpdateFileList->Clear();
  934. for (int Index = 0; Index < Files->Count(); Index++)
  935. {
  936. UpdateFileList->Add(Files->GetFileName(Index), Files->GetState(Index));
  937. }
  938. }
  939. else
  940. {
  941. int Index = ((FListIndex == 0) ? FIndex : Files->Count()) - 1;
  942. while ((Index >= 0) && (UpdateFileList->GetState(Index) != Files->GetState(Index)))
  943. {
  944. UpdateFileList->SetState(Index, Files->GetState(Index));
  945. Index--;
  946. Result = true;
  947. }
  948. }
  949. UpdateFileList->FLastParallelOperation = this;
  950. UpdateFileList->FLastParallelOperationVersion = FVersion;
  951. return Result;
  952. }
  953. //---------------------------------------------------------------------------
  954. //---------------------------------------------------------------------------
  955. __fastcall TTerminal::TTerminal(TSessionData * SessionData,
  956. TConfiguration * Configuration)
  957. {
  958. FConfiguration = Configuration;
  959. FSessionData = new TSessionData(L"");
  960. FSessionData->Assign(SessionData);
  961. TDateTime Started = Now(); // use the same time for session and XML log
  962. FLog = new TSessionLog(this, Started, FSessionData, Configuration);
  963. FActionLog = new TActionLog(this, Started, FSessionData, Configuration);
  964. FFiles = new TRemoteDirectory(this);
  965. FExceptionOnFail = 0;
  966. FInTransaction = 0;
  967. FReadCurrentDirectoryPending = false;
  968. FReadDirectoryPending = false;
  969. FUsersGroupsLookedup = False;
  970. FTunnelLocalPortNumber = 0;
  971. FFileSystem = NULL;
  972. FSecureShell = NULL;
  973. FOnProgress = NULL;
  974. FOnFinished = NULL;
  975. FOnDeleteLocalFile = NULL;
  976. FOnReadDirectoryProgress = NULL;
  977. FOnQueryUser = NULL;
  978. FOnPromptUser = NULL;
  979. FOnDisplayBanner = NULL;
  980. FOnShowExtendedException = NULL;
  981. FOnInformation = NULL;
  982. FOnCustomCommand = NULL;
  983. FOnClose = NULL;
  984. FOnFindingFile = NULL;
  985. FOperationProgressPersistence = NULL;
  986. FOperationProgressOnceDoneOperation = odoIdle;
  987. FUseBusyCursor = True;
  988. FLockDirectory = L"";
  989. FDirectoryCache = new TRemoteDirectoryCache();
  990. FDirectoryChangesCache = NULL;
  991. FFSProtocol = cfsUnknown;
  992. FCommandSession = NULL;
  993. FAutoReadDirectory = true;
  994. FReadingCurrentDirectory = false;
  995. FStatus = ssClosed;
  996. FOpening = 0;
  997. FTunnelThread = NULL;
  998. FTunnel = NULL;
  999. FTunnelData = NULL;
  1000. FTunnelLog = NULL;
  1001. FTunnelUI = NULL;
  1002. FTunnelOpening = false;
  1003. FCallbackGuard = NULL;
  1004. FNesting = 0;
  1005. FRememberedPasswordKind = TPromptKind(-1);
  1006. }
  1007. //---------------------------------------------------------------------------
  1008. __fastcall TTerminal::~TTerminal()
  1009. {
  1010. if (Active)
  1011. {
  1012. Close();
  1013. }
  1014. if (FCallbackGuard != NULL)
  1015. {
  1016. // see TTerminal::HandleExtendedException
  1017. FCallbackGuard->Dismiss();
  1018. }
  1019. DebugAssert(FTunnel == NULL);
  1020. SAFE_DESTROY(FCommandSession);
  1021. if (SessionData->CacheDirectoryChanges && SessionData->PreserveDirectoryChanges &&
  1022. (FDirectoryChangesCache != NULL))
  1023. {
  1024. Configuration->SaveDirectoryChangesCache(SessionData->SessionKey,
  1025. FDirectoryChangesCache);
  1026. }
  1027. SAFE_DESTROY_EX(TCustomFileSystem, FFileSystem);
  1028. SAFE_DESTROY_EX(TSessionLog, FLog);
  1029. SAFE_DESTROY_EX(TActionLog, FActionLog);
  1030. delete FFiles;
  1031. delete FDirectoryCache;
  1032. delete FDirectoryChangesCache;
  1033. SAFE_DESTROY(FSessionData);
  1034. }
  1035. //---------------------------------------------------------------------------
  1036. void __fastcall TTerminal::Idle()
  1037. {
  1038. // Once we disconnect, do nothing, until reconnect handler
  1039. // "receives the information".
  1040. // Never go idle when called from within ::ProcessGUI() call
  1041. // as we may recurse for good, timeouting eventually.
  1042. if (Active && (FNesting == 0))
  1043. {
  1044. TAutoNestingCounter NestingCounter(FNesting);
  1045. if (Configuration->ActualLogProtocol >= 1)
  1046. {
  1047. LogEvent(L"Session upkeep");
  1048. }
  1049. DebugAssert(FFileSystem != NULL);
  1050. FFileSystem->Idle();
  1051. if (CommandSessionOpened)
  1052. {
  1053. try
  1054. {
  1055. FCommandSession->Idle();
  1056. }
  1057. catch(Exception & E)
  1058. {
  1059. // If the secondary session is dropped, ignore the error and let
  1060. // it be reconnected when needed.
  1061. // BTW, non-fatal error can hardly happen here, that's why
  1062. // it is displayed, because it can be useful to know.
  1063. if (FCommandSession->Active)
  1064. {
  1065. FCommandSession->HandleExtendedException(&E);
  1066. }
  1067. }
  1068. }
  1069. }
  1070. }
  1071. //---------------------------------------------------------------------
  1072. RawByteString __fastcall TTerminal::EncryptPassword(const UnicodeString & Password)
  1073. {
  1074. return Configuration->EncryptPassword(Password, SessionData->SessionName);
  1075. }
  1076. //---------------------------------------------------------------------
  1077. UnicodeString __fastcall TTerminal::DecryptPassword(const RawByteString & Password)
  1078. {
  1079. UnicodeString Result;
  1080. try
  1081. {
  1082. Result = Configuration->DecryptPassword(Password, SessionData->SessionName);
  1083. }
  1084. catch(EAbort &)
  1085. {
  1086. // silently ignore aborted prompts for master password and return empty password
  1087. }
  1088. return Result;
  1089. }
  1090. //---------------------------------------------------------------------------
  1091. void __fastcall TTerminal::RecryptPasswords()
  1092. {
  1093. FSessionData->RecryptPasswords();
  1094. FRememberedPassword = EncryptPassword(GetRememberedPassword());
  1095. FRememberedTunnelPassword = EncryptPassword(GetRememberedTunnelPassword());
  1096. }
  1097. //---------------------------------------------------------------------------
  1098. UnicodeString __fastcall TTerminal::ExpandFileName(UnicodeString Path,
  1099. const UnicodeString BasePath)
  1100. {
  1101. // replace this by AbsolutePath()
  1102. Path = UnixExcludeTrailingBackslash(Path);
  1103. if (!UnixIsAbsolutePath(Path) && !BasePath.IsEmpty())
  1104. {
  1105. // TODO: Handle more complicated cases like "../../xxx"
  1106. if (Path == PARENTDIRECTORY)
  1107. {
  1108. Path = UnixExcludeTrailingBackslash(UnixExtractFilePath(
  1109. UnixExcludeTrailingBackslash(BasePath)));
  1110. }
  1111. else
  1112. {
  1113. Path = UnixIncludeTrailingBackslash(BasePath) + Path;
  1114. }
  1115. }
  1116. return Path;
  1117. }
  1118. //---------------------------------------------------------------------------
  1119. bool __fastcall TTerminal::GetActive()
  1120. {
  1121. return (FFileSystem != NULL) && FFileSystem->GetActive();
  1122. }
  1123. //---------------------------------------------------------------------------
  1124. void __fastcall TTerminal::Close()
  1125. {
  1126. FFileSystem->Close();
  1127. // Cannot rely on CommandSessionOpened here as Status is set to ssClosed too late
  1128. if ((FCommandSession != NULL) && FCommandSession->Active)
  1129. {
  1130. // prevent recursion
  1131. FCommandSession->OnClose = NULL;
  1132. FCommandSession->Close();
  1133. }
  1134. }
  1135. //---------------------------------------------------------------------------
  1136. void __fastcall TTerminal::ResetConnection()
  1137. {
  1138. // used to be called from Reopen(), why?
  1139. FTunnelError = L"";
  1140. FRememberedPasswordTried = false;
  1141. FRememberedTunnelPasswordTried = false;
  1142. if (FDirectoryChangesCache != NULL)
  1143. {
  1144. delete FDirectoryChangesCache;
  1145. FDirectoryChangesCache = NULL;
  1146. }
  1147. FFiles->Directory = L"";
  1148. // note that we cannot clear contained files
  1149. // as they can still be referenced in the GUI atm
  1150. }
  1151. //---------------------------------------------------------------------------
  1152. void __fastcall TTerminal::FingerprintScan(UnicodeString & SHA256, UnicodeString & SHA1, UnicodeString & MD5)
  1153. {
  1154. SessionData->FingerprintScan = true;
  1155. try
  1156. {
  1157. Open();
  1158. // we should never get here
  1159. DebugFail();
  1160. Abort();
  1161. }
  1162. catch (...)
  1163. {
  1164. if (!FFingerprintScannedSHA256.IsEmpty() ||
  1165. !FFingerprintScannedSHA1.IsEmpty() ||
  1166. !FFingerprintScannedMD5.IsEmpty())
  1167. {
  1168. SHA256 = FFingerprintScannedSHA256;
  1169. SHA1 = FFingerprintScannedSHA1;
  1170. MD5 = FFingerprintScannedMD5;
  1171. }
  1172. else
  1173. {
  1174. throw;
  1175. }
  1176. }
  1177. }
  1178. //---------------------------------------------------------------------------
  1179. void __fastcall TTerminal::Open()
  1180. {
  1181. TAutoNestingCounter OpeningCounter(FOpening);
  1182. ReflectSettings();
  1183. try
  1184. {
  1185. FEncryptKey = HexToBytes(FSessionData->EncryptKey);
  1186. if (IsEncryptingFiles())
  1187. {
  1188. ValidateEncryptKey(FEncryptKey);
  1189. }
  1190. DoInformation(L"", true, 1);
  1191. try
  1192. {
  1193. FRememberedPasswordUsed = false;
  1194. try
  1195. {
  1196. ResetConnection();
  1197. FStatus = ssOpening;
  1198. try
  1199. {
  1200. if (FFileSystem == NULL)
  1201. {
  1202. Log->AddSystemInfo();
  1203. DoInitializeLog();
  1204. Log->AddStartupInfo();
  1205. }
  1206. DebugAssert(FTunnel == NULL);
  1207. if (FSessionData->Tunnel)
  1208. {
  1209. DoInformation(LoadStr(OPEN_TUNNEL), true);
  1210. LogEvent(L"Opening tunnel.");
  1211. OpenTunnel();
  1212. Log->AddSeparator();
  1213. FSessionData->ConfigureTunnel(FTunnelLocalPortNumber);
  1214. DoInformation(LoadStr(USING_TUNNEL), false);
  1215. LogEvent(FORMAT(L"Connecting via tunnel interface %s:%d.",
  1216. (FSessionData->HostNameExpanded, FSessionData->PortNumber)));
  1217. }
  1218. else
  1219. {
  1220. DebugAssert(FTunnelLocalPortNumber == 0);
  1221. }
  1222. if (FFileSystem == NULL)
  1223. {
  1224. if (SessionData->FSProtocol == fsFTP)
  1225. {
  1226. FFSProtocol = cfsFTP;
  1227. FFileSystem = new TFTPFileSystem(this);
  1228. FFileSystem->Open();
  1229. Log->AddSeparator();
  1230. LogEvent(L"Using FTP protocol.");
  1231. }
  1232. else if (SessionData->FSProtocol == fsWebDAV)
  1233. {
  1234. FFSProtocol = cfsWebDAV;
  1235. FFileSystem = new TWebDAVFileSystem(this);
  1236. FFileSystem->Open();
  1237. Log->AddSeparator();
  1238. LogEvent(L"Using WebDAV protocol.");
  1239. }
  1240. else if (SessionData->FSProtocol == fsS3)
  1241. {
  1242. FFSProtocol = cfsS3;
  1243. FFileSystem = new TS3FileSystem(this);
  1244. FFileSystem->Open();
  1245. Log->AddSeparator();
  1246. LogEvent(L"Using S3 protocol.");
  1247. }
  1248. else
  1249. {
  1250. DebugAssert(FSecureShell == NULL);
  1251. try
  1252. {
  1253. FSecureShell = new TSecureShell(this, FSessionData, Log, Configuration);
  1254. try
  1255. {
  1256. // there will be only one channel in this session
  1257. FSecureShell->Simple = true;
  1258. FSecureShell->Open();
  1259. }
  1260. catch(Exception & E)
  1261. {
  1262. DebugAssert(!FSecureShell->Active);
  1263. if (SessionData->FingerprintScan)
  1264. {
  1265. FSecureShell->GetHostKeyFingerprint(FFingerprintScannedSHA256, FFingerprintScannedMD5);
  1266. FFingerprintScannedSHA1 = UnicodeString();
  1267. }
  1268. // Tunnel errors that happens only once we connect to the local port (server-side forwarding problems).
  1269. // Contrary to local side problems handled already in OpenTunnel.
  1270. if (!FSecureShell->Active && !FTunnelError.IsEmpty())
  1271. {
  1272. // the only case where we expect this to happen (first in GUI, the latter in scripting)
  1273. DebugAssert((E.Message == LoadStr(UNEXPECTED_CLOSE_ERROR)) || (E.Message == LoadStr(NET_TRANSL_CONN_ABORTED)));
  1274. FatalError(&E, FMTLOAD(TUNNEL_ERROR, (FTunnelError)));
  1275. }
  1276. else
  1277. {
  1278. throw;
  1279. }
  1280. }
  1281. Log->AddSeparator();
  1282. if ((SessionData->FSProtocol == fsSCPonly) ||
  1283. (SessionData->FSProtocol == fsSFTP && FSecureShell->SshFallbackCmd()))
  1284. {
  1285. FFSProtocol = cfsSCP;
  1286. FFileSystem = new TSCPFileSystem(this, FSecureShell);
  1287. FSecureShell = NULL; // ownership passed
  1288. LogEvent(L"Using SCP protocol.");
  1289. }
  1290. else
  1291. {
  1292. FFSProtocol = cfsSFTP;
  1293. FFileSystem = new TSFTPFileSystem(this, FSecureShell);
  1294. FSecureShell = NULL; // ownership passed
  1295. LogEvent(L"Using SFTP protocol.");
  1296. }
  1297. }
  1298. __finally
  1299. {
  1300. delete FSecureShell;
  1301. FSecureShell = NULL;
  1302. }
  1303. }
  1304. }
  1305. else
  1306. {
  1307. FFileSystem->Open();
  1308. }
  1309. }
  1310. __finally
  1311. {
  1312. if (FSessionData->Tunnel)
  1313. {
  1314. FSessionData->RollbackTunnel();
  1315. }
  1316. }
  1317. if (SessionData->CacheDirectoryChanges)
  1318. {
  1319. DebugAssert(FDirectoryChangesCache == NULL);
  1320. FDirectoryChangesCache = new TRemoteDirectoryChangesCache(
  1321. Configuration->CacheDirectoryChangesMaxSize);
  1322. if (SessionData->PreserveDirectoryChanges)
  1323. {
  1324. Configuration->LoadDirectoryChangesCache(SessionData->SessionKey,
  1325. FDirectoryChangesCache);
  1326. }
  1327. }
  1328. DoStartup();
  1329. if (FCollectFileSystemUsage)
  1330. {
  1331. FFileSystem->CollectUsage();
  1332. FCollectFileSystemUsage = false;
  1333. }
  1334. DoInformation(LoadStr(STATUS_READY), true);
  1335. FStatus = ssOpened;
  1336. }
  1337. catch(...)
  1338. {
  1339. // rollback
  1340. if (FDirectoryChangesCache != NULL)
  1341. {
  1342. delete FDirectoryChangesCache;
  1343. FDirectoryChangesCache = NULL;
  1344. }
  1345. if (SessionData->FingerprintScan && (FFileSystem != NULL) &&
  1346. DebugAlwaysTrue(SessionData->Ftps != ftpsNone))
  1347. {
  1348. const TSessionInfo & SessionInfo = FFileSystem->GetSessionInfo();
  1349. FFingerprintScannedSHA256 = SessionInfo.CertificateFingerprintSHA256;
  1350. FFingerprintScannedSHA1 = SessionInfo.CertificateFingerprintSHA1;
  1351. FFingerprintScannedMD5 = UnicodeString();
  1352. }
  1353. if (FRememberedPasswordUsed)
  1354. {
  1355. // Particularly to prevent reusing a wrong client certificate passphrase
  1356. // in the next login attempt
  1357. FRememberedPassword = UnicodeString();
  1358. FRememberedPasswordKind = TPromptKind(-1);
  1359. FRememberedTunnelPassword = UnicodeString();
  1360. }
  1361. throw;
  1362. }
  1363. }
  1364. __finally
  1365. {
  1366. // This does not make it through, if terminal thread is abandonded,
  1367. // see also TTerminalManager::DoConnectTerminal
  1368. DoInformation(L"", true, 0);
  1369. }
  1370. }
  1371. catch(EFatal &)
  1372. {
  1373. throw;
  1374. }
  1375. catch(Exception & E)
  1376. {
  1377. // any exception while opening session is fatal
  1378. FatalError(&E, L"");
  1379. }
  1380. }
  1381. //---------------------------------------------------------------------------
  1382. bool __fastcall TTerminal::IsListenerFree(unsigned int PortNumber)
  1383. {
  1384. SOCKET Socket = socket(AF_INET, SOCK_STREAM, 0);
  1385. bool Result = (Socket != INVALID_SOCKET);
  1386. if (Result)
  1387. {
  1388. SOCKADDR_IN Address;
  1389. memset(&Address, 0, sizeof(Address));
  1390. Address.sin_family = AF_INET;
  1391. Address.sin_port = htons(static_cast<short>(PortNumber));
  1392. Address.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  1393. Result = (bind(Socket, reinterpret_cast<sockaddr *>(&Address), sizeof(Address)) == 0);
  1394. closesocket(Socket);
  1395. }
  1396. return Result;
  1397. }
  1398. //---------------------------------------------------------------------------
  1399. void __fastcall TTerminal::OpenTunnel()
  1400. {
  1401. DebugAssert(FTunnelData == NULL);
  1402. FTunnelLocalPortNumber = FSessionData->TunnelLocalPortNumber;
  1403. if (FTunnelLocalPortNumber == 0)
  1404. {
  1405. // Randomizing the port selection to reduce a chance of conflicts.
  1406. std::vector<int> Ports;
  1407. for (int Port = Configuration->TunnelLocalPortNumberLow; Port <= Configuration->TunnelLocalPortNumberHigh; Port++)
  1408. {
  1409. Ports.push_back(Port);
  1410. }
  1411. do
  1412. {
  1413. if (Ports.empty())
  1414. {
  1415. FatalError(NULL, FMTLOAD(TUNNEL_NO_FREE_PORT,
  1416. (Configuration->TunnelLocalPortNumberLow, Configuration->TunnelLocalPortNumberHigh)));
  1417. }
  1418. int Index = Random(Ports.size());
  1419. int Port = Ports[Index];
  1420. Ports.erase(&Ports.at(Index));
  1421. if (IsListenerFree(Port))
  1422. {
  1423. FTunnelLocalPortNumber = Port;
  1424. LogEvent(FORMAT(L"Autoselected tunnel local port number %d", (FTunnelLocalPortNumber)));
  1425. }
  1426. }
  1427. while (FTunnelLocalPortNumber == 0);
  1428. }
  1429. try
  1430. {
  1431. FTunnelData = new TSessionData(L"");
  1432. FTunnelData->Assign(StoredSessions->DefaultSettings);
  1433. FTunnelData->Name = FMTLOAD(TUNNEL_SESSION_NAME, (FSessionData->SessionName));
  1434. FTunnelData->Tunnel = false;
  1435. FTunnelData->HostName = FSessionData->TunnelHostName;
  1436. FTunnelData->PortNumber = FSessionData->TunnelPortNumber;
  1437. FTunnelData->UserName = FSessionData->TunnelUserName;
  1438. FTunnelData->Password = FSessionData->TunnelPassword;
  1439. FTunnelData->PublicKeyFile = FSessionData->TunnelPublicKeyFile;
  1440. UnicodeString HostName = FSessionData->HostNameExpanded;
  1441. if (IsIPv6Literal(HostName))
  1442. {
  1443. HostName = EscapeIPv6Literal(HostName);
  1444. }
  1445. FTunnelData->TunnelPortFwd = FORMAT(L"L%d\t%s:%d",
  1446. (FTunnelLocalPortNumber, HostName, FSessionData->PortNumber));
  1447. FTunnelData->HostKey = FSessionData->TunnelHostKey;
  1448. // inherit proxy options on the main session
  1449. FTunnelData->ProxyMethod = FSessionData->ProxyMethod;
  1450. FTunnelData->ProxyHost = FSessionData->ProxyHost;
  1451. FTunnelData->ProxyPort = FSessionData->ProxyPort;
  1452. FTunnelData->ProxyUsername = FSessionData->ProxyUsername;
  1453. FTunnelData->ProxyPassword = FSessionData->ProxyPassword;
  1454. FTunnelData->ProxyTelnetCommand = FSessionData->ProxyTelnetCommand;
  1455. FTunnelData->ProxyLocalCommand = FSessionData->ProxyLocalCommand;
  1456. FTunnelData->ProxyDNS = FSessionData->ProxyDNS;
  1457. FTunnelData->ProxyLocalhost = FSessionData->ProxyLocalhost;
  1458. // inherit most SSH options of the main session (except for private key and bugs)
  1459. FTunnelData->Compression = FSessionData->Compression;
  1460. FTunnelData->SshProt = FSessionData->SshProt;
  1461. FTunnelData->CipherList = FSessionData->CipherList;
  1462. FTunnelData->Ssh2DES = FSessionData->Ssh2DES;
  1463. FTunnelData->KexList = FSessionData->KexList;
  1464. FTunnelData->RekeyData = FSessionData->RekeyData;
  1465. FTunnelData->RekeyTime = FSessionData->RekeyTime;
  1466. FTunnelData->SshNoUserAuth = FSessionData->SshNoUserAuth;
  1467. FTunnelData->AuthGSSAPI = FSessionData->AuthGSSAPI;
  1468. FTunnelData->AuthGSSAPIKEX = FSessionData->AuthGSSAPIKEX;
  1469. FTunnelData->GSSAPIFwdTGT = FSessionData->GSSAPIFwdTGT;
  1470. FTunnelData->TryAgent = FSessionData->TryAgent;
  1471. FTunnelData->AgentFwd = FSessionData->AgentFwd;
  1472. FTunnelData->AuthTIS = FSessionData->AuthTIS;
  1473. FTunnelData->AuthKI = FSessionData->AuthKI;
  1474. FTunnelData->AuthKIPassword = FSessionData->AuthKIPassword;
  1475. // The Started argument is not used with Parent being set
  1476. FTunnelLog = new TSessionLog(this, TDateTime(), FTunnelData, Configuration);
  1477. FTunnelLog->SetParent(FLog, L"Tunnel");
  1478. FTunnelLog->ReflectSettings();
  1479. FTunnelUI = new TTunnelUI(this);
  1480. FTunnel = new TSecureShell(FTunnelUI, FTunnelData, FTunnelLog, Configuration);
  1481. FTunnelOpening = true;
  1482. try
  1483. {
  1484. FTunnel->Open();
  1485. }
  1486. __finally
  1487. {
  1488. FTunnelOpening = false;
  1489. }
  1490. // When forwarding fails due to a local problem (e.g. port in use), we get the error already here, so abort asap.
  1491. // If we won't abort, particularly in case of "port in use", we may not even detect the problem,
  1492. // as the connection to the port may succeed.
  1493. // Remote-side tunnel problems are handled in TTerminal::Open().
  1494. if (!FTunnel->LastTunnelError.IsEmpty())
  1495. {
  1496. // Throw and handle with any other theoretical forwarding errors that may cause tunnel connection close
  1497. // (probably cannot happen)
  1498. EXCEPTION;
  1499. }
  1500. FTunnelThread = new TTunnelThread(FTunnel);
  1501. }
  1502. catch (Exception & E)
  1503. {
  1504. LogEvent(L"Error opening tunnel.");
  1505. CloseTunnel();
  1506. if (!FTunnelError.IsEmpty())
  1507. {
  1508. FatalError(&E, FMTLOAD(TUNNEL_ERROR, (FTunnelError)));
  1509. }
  1510. else
  1511. {
  1512. throw;
  1513. }
  1514. }
  1515. }
  1516. //---------------------------------------------------------------------------
  1517. void __fastcall TTerminal::CloseTunnel()
  1518. {
  1519. SAFE_DESTROY_EX(TTunnelThread, FTunnelThread);
  1520. FTunnelError = FTunnel->LastTunnelError;
  1521. SAFE_DESTROY_EX(TSecureShell, FTunnel);
  1522. SAFE_DESTROY_EX(TTunnelUI, FTunnelUI);
  1523. SAFE_DESTROY_EX(TSessionLog, FTunnelLog);
  1524. SAFE_DESTROY(FTunnelData);
  1525. FTunnelLocalPortNumber = 0;
  1526. }
  1527. //---------------------------------------------------------------------------
  1528. void __fastcall TTerminal::Closed()
  1529. {
  1530. if (FTunnel != NULL)
  1531. {
  1532. CloseTunnel();
  1533. }
  1534. if (OnClose)
  1535. {
  1536. TCallbackGuard Guard(this);
  1537. try
  1538. {
  1539. OnClose(this);
  1540. Guard.Verify();
  1541. }
  1542. catch (Exception & E)
  1543. {
  1544. if (!Guard.Verify(&E))
  1545. {
  1546. throw;
  1547. }
  1548. }
  1549. }
  1550. FStatus = ssClosed;
  1551. }
  1552. //---------------------------------------------------------------------------
  1553. void __fastcall TTerminal::ProcessGUI()
  1554. {
  1555. // Do not process GUI here, as we are called directly from a GUI loop and may
  1556. // recurse for good.
  1557. // Alternatively we may check for (FOperationProgress == NULL)
  1558. if (FNesting == 0)
  1559. {
  1560. TAutoNestingCounter NestingCounter(FNesting);
  1561. ::ProcessGUI();
  1562. }
  1563. }
  1564. //---------------------------------------------------------------------------
  1565. void __fastcall TTerminal::Progress(TFileOperationProgressType * OperationProgress)
  1566. {
  1567. if (FNesting == 0)
  1568. {
  1569. TAutoNestingCounter NestingCounter(FNesting);
  1570. OperationProgress->Progress();
  1571. }
  1572. }
  1573. //---------------------------------------------------------------------------
  1574. void __fastcall TTerminal::Reopen(int Params)
  1575. {
  1576. TFSProtocol OrigFSProtocol = SessionData->FSProtocol;
  1577. UnicodeString PrevRemoteDirectory = SessionData->RemoteDirectory;
  1578. bool PrevReadCurrentDirectoryPending = FReadCurrentDirectoryPending;
  1579. bool PrevReadDirectoryPending = FReadDirectoryPending;
  1580. DebugAssert(!FSuspendTransaction);
  1581. bool PrevAutoReadDirectory = FAutoReadDirectory;
  1582. // here used to be a check for FExceptionOnFail being 0
  1583. // but it can happen, e.g. when we are downloading file to execute it.
  1584. // however I'm not sure why we mind having excaption-on-fail enabled here
  1585. int PrevExceptionOnFail = FExceptionOnFail;
  1586. try
  1587. {
  1588. FReadCurrentDirectoryPending = false;
  1589. FReadDirectoryPending = false;
  1590. FSuspendTransaction = true;
  1591. FExceptionOnFail = 0;
  1592. // typically, we avoid reading directory, when there is operation ongoing,
  1593. // for file list which may reference files from current directory
  1594. if (FLAGSET(Params, ropNoReadDirectory))
  1595. {
  1596. AutoReadDirectory = false;
  1597. }
  1598. // only peek, we may not be connected at all atm,
  1599. // so make sure we do not try retrieving current directory from the server
  1600. // (particularly with FTP)
  1601. UnicodeString ACurrentDirectory = PeekCurrentDirectory();
  1602. if (!ACurrentDirectory.IsEmpty())
  1603. {
  1604. SessionData->RemoteDirectory = ACurrentDirectory;
  1605. }
  1606. if (SessionData->FSProtocol == fsSFTP)
  1607. {
  1608. SessionData->FSProtocol = (FFSProtocol == cfsSCP ? fsSCPonly : fsSFTPonly);
  1609. }
  1610. Open();
  1611. }
  1612. __finally
  1613. {
  1614. SessionData->RemoteDirectory = PrevRemoteDirectory;
  1615. SessionData->FSProtocol = OrigFSProtocol;
  1616. FAutoReadDirectory = PrevAutoReadDirectory;
  1617. FReadCurrentDirectoryPending = PrevReadCurrentDirectoryPending;
  1618. FReadDirectoryPending = PrevReadDirectoryPending;
  1619. FSuspendTransaction = false;
  1620. FExceptionOnFail = PrevExceptionOnFail;
  1621. }
  1622. }
  1623. //---------------------------------------------------------------------------
  1624. bool __fastcall TTerminal::PromptUser(TSessionData * Data, TPromptKind Kind,
  1625. UnicodeString Name, UnicodeString Instructions, UnicodeString Prompt, bool Echo, int MaxLen, UnicodeString & Result)
  1626. {
  1627. bool AResult;
  1628. TStrings * Prompts = new TStringList;
  1629. TStrings * Results = new TStringList;
  1630. try
  1631. {
  1632. Prompts->AddObject(Prompt, (TObject *)(FLAGMASK(Echo, pupEcho)));
  1633. Results->AddObject(Result, (TObject *)MaxLen);
  1634. AResult = PromptUser(Data, Kind, Name, Instructions, Prompts, Results);
  1635. Result = Results->Strings[0];
  1636. }
  1637. __finally
  1638. {
  1639. delete Prompts;
  1640. delete Results;
  1641. }
  1642. return AResult;
  1643. }
  1644. //---------------------------------------------------------------------------
  1645. bool __fastcall TTerminal::PromptUser(TSessionData * Data, TPromptKind Kind,
  1646. UnicodeString Name, UnicodeString Instructions, TStrings * Prompts, TStrings * Results)
  1647. {
  1648. // If PromptUser is overridden in descendant class, the overridden version
  1649. // is not called when accessed via TSessionIU interface.
  1650. // So this is workaround.
  1651. // Actually no longer needed as we do not uverride DoPromptUser
  1652. // anymore in TSecondaryTerminal.
  1653. return DoPromptUser(Data, Kind, Name, Instructions, Prompts, Results);
  1654. }
  1655. //---------------------------------------------------------------------------
  1656. TTerminal * __fastcall TTerminal::GetPasswordSource()
  1657. {
  1658. return this;
  1659. }
  1660. //---------------------------------------------------------------------------
  1661. bool __fastcall TTerminal::DoPromptUser(TSessionData * /*Data*/, TPromptKind Kind,
  1662. UnicodeString Name, UnicodeString Instructions, TStrings * Prompts, TStrings * Results)
  1663. {
  1664. bool AResult = false;
  1665. bool PasswordOrPassphrasePrompt = IsPasswordOrPassphrasePrompt(Kind, Prompts);
  1666. if (PasswordOrPassphrasePrompt)
  1667. {
  1668. bool & PasswordTried =
  1669. FTunnelOpening ? FRememberedTunnelPasswordTried : FRememberedPasswordTried;
  1670. if (!PasswordTried)
  1671. {
  1672. // let's expect that the main session is already authenticated and its password
  1673. // is not written after, so no locking is necessary
  1674. // (no longer true, once the main session can be reconnected)
  1675. UnicodeString APassword;
  1676. if (FTunnelOpening)
  1677. {
  1678. APassword = GetPasswordSource()->GetRememberedTunnelPassword();
  1679. }
  1680. else
  1681. {
  1682. APassword = GetPasswordSource()->GetRememberedPassword();
  1683. }
  1684. FRememberedPasswordUsed = true;
  1685. Results->Strings[0] = APassword;
  1686. if (!Results->Strings[0].IsEmpty())
  1687. {
  1688. LogEvent(L"Using remembered password.");
  1689. AResult = true;
  1690. }
  1691. PasswordTried = true;
  1692. }
  1693. }
  1694. if (!AResult)
  1695. {
  1696. if (PasswordOrPassphrasePrompt && !Configuration->RememberPassword)
  1697. {
  1698. Prompts->Objects[0] = (TObject*)(int(Prompts->Objects[0]) | pupRemember);
  1699. }
  1700. if (OnPromptUser != NULL)
  1701. {
  1702. TCallbackGuard Guard(this);
  1703. try
  1704. {
  1705. OnPromptUser(this, Kind, Name, Instructions, Prompts, Results, AResult, NULL);
  1706. Guard.Verify();
  1707. }
  1708. catch (Exception & E)
  1709. {
  1710. if (!Guard.Verify(&E))
  1711. {
  1712. throw;
  1713. }
  1714. }
  1715. }
  1716. if (AResult && PasswordOrPassphrasePrompt &&
  1717. (Configuration->RememberPassword || FLAGSET(int(Prompts->Objects[0]), pupRemember)))
  1718. {
  1719. RawByteString EncryptedPassword = EncryptPassword(Results->Strings[0]);
  1720. if (FTunnelOpening)
  1721. {
  1722. GetPasswordSource()->FRememberedTunnelPassword = EncryptedPassword;
  1723. }
  1724. else
  1725. {
  1726. GetPasswordSource()->FRememberedPassword = EncryptedPassword;
  1727. GetPasswordSource()->FRememberedPasswordKind = Kind;
  1728. }
  1729. }
  1730. }
  1731. return AResult;
  1732. }
  1733. //---------------------------------------------------------------------------
  1734. unsigned int __fastcall TTerminal::QueryUser(const UnicodeString Query,
  1735. TStrings * MoreMessages, unsigned int Answers, const TQueryParams * Params,
  1736. TQueryType QueryType)
  1737. {
  1738. LogEvent(FORMAT(L"Asking user:\n%s (%s)", (Query, (MoreMessages ? MoreMessages->CommaText : UnicodeString() ))));
  1739. unsigned int Answer = AbortAnswer(Answers);
  1740. if (FOnQueryUser)
  1741. {
  1742. TCallbackGuard Guard(this);
  1743. try
  1744. {
  1745. FOnQueryUser(this, Query, MoreMessages, Answers, Params, Answer, QueryType, NULL);
  1746. Guard.Verify();
  1747. }
  1748. catch (Exception & E)
  1749. {
  1750. if (!Guard.Verify(&E))
  1751. {
  1752. throw;
  1753. }
  1754. }
  1755. }
  1756. return Answer;
  1757. }
  1758. //---------------------------------------------------------------------------
  1759. unsigned int __fastcall TTerminal::QueryUserException(const UnicodeString Query,
  1760. Exception * E, unsigned int Answers, const TQueryParams * Params,
  1761. TQueryType QueryType)
  1762. {
  1763. unsigned int Result;
  1764. UnicodeString ExMessage;
  1765. if (DebugAlwaysTrue(ExceptionMessageFormatted(E, ExMessage) || !Query.IsEmpty()))
  1766. {
  1767. TStrings * MoreMessages = new TStringList();
  1768. try
  1769. {
  1770. if (!ExMessage.IsEmpty() && !Query.IsEmpty())
  1771. {
  1772. MoreMessages->Add(UnformatMessage(ExMessage));
  1773. }
  1774. ExtException * EE = dynamic_cast<ExtException*>(E);
  1775. if ((EE != NULL) && (EE->MoreMessages != NULL))
  1776. {
  1777. MoreMessages->AddStrings(EE->MoreMessages);
  1778. }
  1779. // We know MoreMessages not to be NULL here,
  1780. // AppendExceptionStackTraceAndForget should never return true
  1781. // (indicating it had to create the string list)
  1782. DebugAlwaysFalse(AppendExceptionStackTraceAndForget(MoreMessages));
  1783. TQueryParams HelpKeywordOverrideParams;
  1784. if (Params != NULL)
  1785. {
  1786. HelpKeywordOverrideParams.Assign(*Params);
  1787. }
  1788. HelpKeywordOverrideParams.HelpKeyword =
  1789. MergeHelpKeyword(HelpKeywordOverrideParams.HelpKeyword, GetExceptionHelpKeyword(E));
  1790. Result = QueryUser(!Query.IsEmpty() ? Query : ExMessage,
  1791. MoreMessages->Count ? MoreMessages : NULL,
  1792. Answers, &HelpKeywordOverrideParams, QueryType);
  1793. }
  1794. __finally
  1795. {
  1796. delete MoreMessages;
  1797. }
  1798. }
  1799. return Result;
  1800. }
  1801. //---------------------------------------------------------------------------
  1802. void __fastcall TTerminal::DisplayBanner(const UnicodeString & Banner)
  1803. {
  1804. if (OnDisplayBanner != NULL)
  1805. {
  1806. unsigned int OrigParams, Params;
  1807. if (Configuration->ForceBanners ||
  1808. Configuration->ShowBanner(SessionData->SessionKey, Banner, Params))
  1809. {
  1810. bool NeverShowAgain = false;
  1811. int Options =
  1812. FLAGMASK(Configuration->ForceBanners, boDisableNeverShowAgain);
  1813. OrigParams = Params;
  1814. TCallbackGuard Guard(this);
  1815. try
  1816. {
  1817. OnDisplayBanner(this, SessionData->SessionName, Banner, NeverShowAgain, Options, Params);
  1818. Guard.Verify();
  1819. }
  1820. catch (Exception & E)
  1821. {
  1822. if (!Guard.Verify(&E))
  1823. {
  1824. throw;
  1825. }
  1826. }
  1827. if (!Configuration->ForceBanners && NeverShowAgain)
  1828. {
  1829. Configuration->NeverShowBanner(SessionData->SessionKey, Banner);
  1830. }
  1831. if (OrigParams != Params)
  1832. {
  1833. Configuration->SetBannerParams(SessionData->SessionKey, Params);
  1834. }
  1835. }
  1836. }
  1837. }
  1838. //---------------------------------------------------------------------------
  1839. void __fastcall TTerminal::HandleExtendedException(Exception * E)
  1840. {
  1841. Log->AddException(E);
  1842. if (OnShowExtendedException != NULL)
  1843. {
  1844. TCallbackGuard Guard(this);
  1845. try
  1846. {
  1847. // the event handler may destroy 'this' ...
  1848. OnShowExtendedException(this, E, NULL);
  1849. // .. hence guard is dismissed from destructor, to make following call no-op
  1850. Guard.Verify();
  1851. }
  1852. catch (Exception & E)
  1853. {
  1854. if (!Guard.Verify(&E))
  1855. {
  1856. throw;
  1857. }
  1858. }
  1859. }
  1860. }
  1861. //---------------------------------------------------------------------------
  1862. void __fastcall TTerminal::ShowExtendedException(Exception * E)
  1863. {
  1864. Log->AddException(E);
  1865. if (OnShowExtendedException != NULL)
  1866. {
  1867. OnShowExtendedException(this, E, NULL);
  1868. }
  1869. }
  1870. //---------------------------------------------------------------------------
  1871. void __fastcall TTerminal::DoInformation(
  1872. const UnicodeString & Str, bool Status, int Phase, const UnicodeString & Additional)
  1873. {
  1874. if (OnInformation)
  1875. {
  1876. TCallbackGuard Guard(this);
  1877. try
  1878. {
  1879. OnInformation(this, Str, Status, Phase, Additional);
  1880. Guard.Verify();
  1881. }
  1882. catch (Exception & E)
  1883. {
  1884. if (!Guard.Verify(&E))
  1885. {
  1886. throw;
  1887. }
  1888. }
  1889. }
  1890. }
  1891. //---------------------------------------------------------------------------
  1892. void __fastcall TTerminal::Information(const UnicodeString & Str, bool Status)
  1893. {
  1894. DoInformation(Str, Status);
  1895. }
  1896. //---------------------------------------------------------------------------
  1897. void __fastcall TTerminal::DoProgress(TFileOperationProgressType & ProgressData)
  1898. {
  1899. if ((Configuration->ActualLogProtocol >= 1) &&
  1900. ((ProgressData.Operation == foCopy) || (ProgressData.Operation == foMove)))
  1901. {
  1902. DWORD Now = GetTickCount();
  1903. if (Now - FLastProgressLogged >= 1000)
  1904. {
  1905. LogEvent(L"Transfer progress: " + ProgressData.GetLogStr(false));
  1906. FLastProgressLogged = Now;
  1907. }
  1908. }
  1909. if (ProgressData.TransferredSize > 0)
  1910. {
  1911. FFileTransferAny = true;
  1912. }
  1913. if (OnProgress != NULL)
  1914. {
  1915. TCallbackGuard Guard(this);
  1916. try
  1917. {
  1918. OnProgress(ProgressData);
  1919. Guard.Verify();
  1920. }
  1921. catch (Exception & E)
  1922. {
  1923. if (!Guard.Verify(&E))
  1924. {
  1925. throw;
  1926. }
  1927. }
  1928. }
  1929. }
  1930. //---------------------------------------------------------------------------
  1931. void __fastcall TTerminal::DoFinished(TFileOperation Operation, TOperationSide Side, bool Temp,
  1932. const UnicodeString & FileName, bool Success, TOnceDoneOperation & OnceDoneOperation)
  1933. {
  1934. if (OnFinished != NULL)
  1935. {
  1936. TCallbackGuard Guard(this);
  1937. try
  1938. {
  1939. OnFinished(Operation, Side, Temp, FileName, Success, OnceDoneOperation);
  1940. Guard.Verify();
  1941. }
  1942. catch (Exception & E)
  1943. {
  1944. if (!Guard.Verify(&E))
  1945. {
  1946. throw;
  1947. }
  1948. }
  1949. }
  1950. }
  1951. //---------------------------------------------------------------------------
  1952. void __fastcall TTerminal::SaveCapabilities(TFileSystemInfo & FileSystemInfo)
  1953. {
  1954. for (int Index = 0; Index < fcCount; Index++)
  1955. {
  1956. FileSystemInfo.IsCapable[Index] = IsCapable[(TFSCapability)Index];
  1957. }
  1958. }
  1959. //---------------------------------------------------------------------------
  1960. bool __fastcall TTerminal::GetIsCapable(TFSCapability Capability) const
  1961. {
  1962. if (DebugAlwaysTrue(FFileSystem != NULL))
  1963. {
  1964. switch (Capability)
  1965. {
  1966. case fcBackgroundTransfers:
  1967. return !IsEncryptingFiles();
  1968. default:
  1969. return FFileSystem->IsCapable(Capability);
  1970. }
  1971. }
  1972. else
  1973. {
  1974. return false;
  1975. }
  1976. }
  1977. //---------------------------------------------------------------------------
  1978. UnicodeString __fastcall TTerminal::AbsolutePath(UnicodeString Path, bool Local)
  1979. {
  1980. return FFileSystem->AbsolutePath(Path, Local);
  1981. }
  1982. //---------------------------------------------------------------------------
  1983. void __fastcall TTerminal::ReactOnCommand(int /*TFSCommand*/ Cmd)
  1984. {
  1985. bool ChangesDirectory = false;
  1986. bool ModifiesFiles = false;
  1987. switch ((TFSCommand)Cmd) {
  1988. case fsChangeDirectory:
  1989. case fsHomeDirectory:
  1990. ChangesDirectory = true;
  1991. break;
  1992. case fsCopyToRemote:
  1993. case fsDeleteFile:
  1994. case fsRenameFile:
  1995. case fsMoveFile:
  1996. case fsCopyFile:
  1997. case fsCreateDirectory:
  1998. case fsChangeMode:
  1999. case fsChangeGroup:
  2000. case fsChangeOwner:
  2001. case fsChangeProperties:
  2002. case fsLock:
  2003. ModifiesFiles = true;
  2004. break;
  2005. case fsAnyCommand:
  2006. ChangesDirectory = true;
  2007. ModifiesFiles = true;
  2008. break;
  2009. }
  2010. if (ChangesDirectory)
  2011. {
  2012. if (!InTransaction())
  2013. {
  2014. ReadCurrentDirectory();
  2015. if (AutoReadDirectory)
  2016. {
  2017. ReadDirectory(false);
  2018. }
  2019. }
  2020. else
  2021. {
  2022. FReadCurrentDirectoryPending = true;
  2023. if (AutoReadDirectory)
  2024. {
  2025. FReadDirectoryPending = true;
  2026. }
  2027. }
  2028. }
  2029. else if (ModifiesFiles && AutoReadDirectory && Configuration->AutoReadDirectoryAfterOp)
  2030. {
  2031. if (!InTransaction())
  2032. {
  2033. ReadDirectory(true);
  2034. }
  2035. else
  2036. {
  2037. FReadDirectoryPending = true;
  2038. }
  2039. }
  2040. }
  2041. //---------------------------------------------------------------------------
  2042. void __fastcall TTerminal::TerminalError(UnicodeString Msg)
  2043. {
  2044. TerminalError(NULL, Msg);
  2045. }
  2046. //---------------------------------------------------------------------------
  2047. void __fastcall TTerminal::TerminalError(
  2048. Exception * E, UnicodeString Msg, UnicodeString HelpKeyword)
  2049. {
  2050. throw ETerminal(E, Msg, HelpKeyword);
  2051. }
  2052. //---------------------------------------------------------------------------
  2053. bool __fastcall TTerminal::DoQueryReopen(Exception * E)
  2054. {
  2055. EFatal * Fatal = dynamic_cast<EFatal *>(E);
  2056. DebugAssert(Fatal != NULL);
  2057. bool Result;
  2058. if ((Fatal != NULL) && Fatal->ReopenQueried)
  2059. {
  2060. Result = false;
  2061. }
  2062. else
  2063. {
  2064. LogEvent(L"Connection was lost, asking what to do.");
  2065. TQueryParams Params(qpAllowContinueOnError);
  2066. Params.Timeout = Configuration->SessionReopenAuto;
  2067. Params.TimeoutAnswer = qaRetry;
  2068. Params.TimeoutResponse = Params.TimeoutAnswer;
  2069. TQueryButtonAlias Aliases[1];
  2070. Aliases[0].Button = qaRetry;
  2071. Aliases[0].Alias = LoadStr(RECONNECT_BUTTON);
  2072. Params.Aliases = Aliases;
  2073. Params.AliasesCount = LENOF(Aliases);
  2074. Result = (QueryUserException(L"", E, qaRetry | qaAbort, &Params, qtError) == qaRetry);
  2075. if (Fatal != NULL)
  2076. {
  2077. Fatal->ReopenQueried = true;
  2078. }
  2079. }
  2080. return Result;
  2081. }
  2082. //---------------------------------------------------------------------------
  2083. bool __fastcall TTerminal::ContinueReopen(TDateTime Start)
  2084. {
  2085. return
  2086. (Configuration->SessionReopenTimeout == 0) ||
  2087. (int(double(Now() - Start) * MSecsPerDay) < Configuration->SessionReopenTimeout);
  2088. }
  2089. //---------------------------------------------------------------------------
  2090. bool __fastcall TTerminal::QueryReopen(Exception * E, int Params,
  2091. TFileOperationProgressType * OperationProgress)
  2092. {
  2093. TSuspendFileOperationProgress Suspend(OperationProgress);
  2094. bool Result = DoQueryReopen(E);
  2095. if (Result)
  2096. {
  2097. TDateTime Start = Now();
  2098. do
  2099. {
  2100. try
  2101. {
  2102. Reopen(Params);
  2103. }
  2104. catch(Exception & E)
  2105. {
  2106. if (!Active)
  2107. {
  2108. Result =
  2109. ContinueReopen(Start) &&
  2110. DoQueryReopen(&E);
  2111. }
  2112. else
  2113. {
  2114. throw;
  2115. }
  2116. }
  2117. }
  2118. while (!Active && Result);
  2119. }
  2120. return Result;
  2121. }
  2122. //---------------------------------------------------------------------------
  2123. bool __fastcall TTerminal::FileOperationLoopQuery(Exception & E,
  2124. TFileOperationProgressType * OperationProgress, const UnicodeString Message,
  2125. unsigned int Flags, UnicodeString SpecialRetry, UnicodeString HelpKeyword)
  2126. {
  2127. bool Result = false;
  2128. Log->AddException(&E);
  2129. unsigned int Answer;
  2130. bool AllowSkip = FLAGSET(Flags, folAllowSkip);
  2131. bool SkipToAllPossible = AllowSkip && (OperationProgress != NULL);
  2132. if (SkipToAllPossible && OperationProgress->SkipToAll)
  2133. {
  2134. Answer = qaSkip;
  2135. }
  2136. else
  2137. {
  2138. int Answers = qaRetry | qaAbort |
  2139. FLAGMASK(AllowSkip, qaSkip) |
  2140. FLAGMASK(SkipToAllPossible, qaAll) |
  2141. FLAGMASK(!SpecialRetry.IsEmpty(), qaYes);
  2142. TQueryParams Params(qpAllowContinueOnError | FLAGMASK(!AllowSkip, qpFatalAbort));
  2143. Params.HelpKeyword = HelpKeyword;
  2144. TQueryButtonAlias Aliases[2];
  2145. int AliasCount = 0;
  2146. if (FLAGSET(Answers, qaAll))
  2147. {
  2148. Aliases[AliasCount].Button = qaAll;
  2149. Aliases[AliasCount].Alias = LoadStr(SKIP_ALL_BUTTON);
  2150. AliasCount++;
  2151. }
  2152. if (FLAGSET(Answers, qaYes))
  2153. {
  2154. Aliases[AliasCount].Button = qaYes;
  2155. Aliases[AliasCount].Alias = SpecialRetry;
  2156. AliasCount++;
  2157. }
  2158. if (AliasCount > 0)
  2159. {
  2160. Params.Aliases = Aliases;
  2161. Params.AliasesCount = AliasCount;
  2162. }
  2163. {
  2164. TSuspendFileOperationProgress Suspend(OperationProgress);
  2165. Answer = QueryUserException(Message, &E, Answers, &Params, qtError);
  2166. }
  2167. if (Answer == qaAll)
  2168. {
  2169. DebugAssert(OperationProgress != NULL);
  2170. OperationProgress->SetSkipToAll();
  2171. Answer = qaSkip;
  2172. }
  2173. if (Answer == qaYes)
  2174. {
  2175. Result = true;
  2176. Answer = qaRetry;
  2177. }
  2178. }
  2179. if (Answer != qaRetry)
  2180. {
  2181. if ((Answer == qaAbort) && (OperationProgress != NULL))
  2182. {
  2183. OperationProgress->SetCancel(csCancel);
  2184. }
  2185. if (AllowSkip)
  2186. {
  2187. throw ESkipFile(&E, Message);
  2188. }
  2189. else
  2190. {
  2191. // this can happen only during file transfer with SCP
  2192. throw ExtException(&E, Message);
  2193. }
  2194. }
  2195. return Result;
  2196. }
  2197. //---------------------------------------------------------------------------
  2198. void __fastcall TTerminal::FileOperationLoopEnd(Exception & E,
  2199. TFileOperationProgressType * OperationProgress, const UnicodeString & Message,
  2200. unsigned int Flags, const UnicodeString & SpecialRetry, const UnicodeString & HelpKeyword)
  2201. {
  2202. if ((dynamic_cast<EAbort *>(&E) != NULL) ||
  2203. (dynamic_cast<ESkipFile *>(&E) != NULL) ||
  2204. (dynamic_cast<ESkipFile *>(&E) != NULL))
  2205. {
  2206. RethrowException(&E);
  2207. }
  2208. else if (dynamic_cast<EFatal *>(&E) != NULL)
  2209. {
  2210. if (FLAGCLEAR(Flags, folRetryOnFatal))
  2211. {
  2212. RethrowException(&E);
  2213. }
  2214. else
  2215. {
  2216. DebugAssert(SpecialRetry.IsEmpty());
  2217. std::unique_ptr<Exception> E2(new EFatal(&E, Message, HelpKeyword));
  2218. if (!DoQueryReopen(E2.get()))
  2219. {
  2220. RethrowException(E2.get());
  2221. }
  2222. }
  2223. }
  2224. else
  2225. {
  2226. FileOperationLoopQuery(E, OperationProgress, Message, Flags, SpecialRetry, HelpKeyword);
  2227. }
  2228. }
  2229. //---------------------------------------------------------------------------
  2230. int __fastcall TTerminal::FileOperationLoop(TFileOperationEvent CallBackFunc,
  2231. TFileOperationProgressType * OperationProgress, unsigned int Flags,
  2232. const UnicodeString Message, void * Param1, void * Param2)
  2233. {
  2234. DebugAssert(CallBackFunc);
  2235. int Result;
  2236. FILE_OPERATION_LOOP_BEGIN
  2237. {
  2238. Result = CallBackFunc(Param1, Param2);
  2239. }
  2240. FILE_OPERATION_LOOP_END_EX(Message, Flags);
  2241. return Result;
  2242. }
  2243. //---------------------------------------------------------------------------
  2244. UnicodeString __fastcall TTerminal::TranslateLockedPath(UnicodeString Path, bool Lock)
  2245. {
  2246. if (SessionData->LockInHome && !Path.IsEmpty() && (Path[1] == L'/'))
  2247. {
  2248. if (Lock)
  2249. {
  2250. if (Path.SubString(1, FLockDirectory.Length()) == FLockDirectory)
  2251. {
  2252. Path.Delete(1, FLockDirectory.Length());
  2253. if (Path.IsEmpty()) Path = L"/";
  2254. }
  2255. }
  2256. else
  2257. {
  2258. Path = UnixExcludeTrailingBackslash(FLockDirectory + Path);
  2259. }
  2260. }
  2261. return Path;
  2262. }
  2263. //---------------------------------------------------------------------------
  2264. void __fastcall TTerminal::ClearCaches()
  2265. {
  2266. FDirectoryCache->Clear();
  2267. if (FDirectoryChangesCache != NULL)
  2268. {
  2269. FDirectoryChangesCache->Clear();
  2270. }
  2271. if (FCommandSession != NULL)
  2272. {
  2273. FCommandSession->ClearCaches();
  2274. }
  2275. FFileSystem->ClearCaches();
  2276. FEncryptedFileNames.clear();
  2277. FFoldersScannedForEncryptedFiles.clear();
  2278. }
  2279. //---------------------------------------------------------------------------
  2280. void __fastcall TTerminal::ClearCachedFileList(const UnicodeString Path,
  2281. bool SubDirs)
  2282. {
  2283. FDirectoryCache->ClearFileList(Path, SubDirs);
  2284. }
  2285. //---------------------------------------------------------------------------
  2286. void __fastcall TTerminal::AddCachedFileList(TRemoteFileList * FileList)
  2287. {
  2288. FDirectoryCache->AddFileList(FileList);
  2289. }
  2290. //---------------------------------------------------------------------------
  2291. TRemoteFileList * __fastcall TTerminal::DirectoryFileList(const UnicodeString Path, TDateTime Timestamp, bool CanLoad)
  2292. {
  2293. TRemoteFileList * Result = NULL;
  2294. if (UnixSamePath(FFiles->Directory, Path))
  2295. {
  2296. if (Timestamp < FFiles->Timestamp)
  2297. {
  2298. Result = new TRemoteFileList();
  2299. FFiles->DuplicateTo(Result);
  2300. }
  2301. }
  2302. else
  2303. {
  2304. if (FDirectoryCache->HasNewerFileList(Path, Timestamp))
  2305. {
  2306. Result = new TRemoteFileList();
  2307. DebugAlwaysTrue(FDirectoryCache->GetFileList(Path, Result));
  2308. }
  2309. // do not attempt to load file list if there is cached version,
  2310. // only absence of cached version indicates that we consider
  2311. // the directory content obsolete
  2312. else if (CanLoad && !FDirectoryCache->HasFileList(Path))
  2313. {
  2314. Result = new TRemoteFileList();
  2315. Result->Directory = Path;
  2316. try
  2317. {
  2318. ReadDirectory(Result);
  2319. }
  2320. catch(...)
  2321. {
  2322. SAFE_DESTROY(Result);
  2323. throw;
  2324. }
  2325. }
  2326. }
  2327. return Result;
  2328. }
  2329. //---------------------------------------------------------------------------
  2330. void __fastcall TTerminal::SetCurrentDirectory(UnicodeString value)
  2331. {
  2332. DebugAssert(FFileSystem);
  2333. value = TranslateLockedPath(value, false);
  2334. if (value != FFileSystem->CurrentDirectory)
  2335. {
  2336. ChangeDirectory(value);
  2337. }
  2338. }
  2339. //---------------------------------------------------------------------------
  2340. UnicodeString __fastcall TTerminal::GetCurrentDirectory()
  2341. {
  2342. if (FFileSystem != NULL)
  2343. {
  2344. // there's occasional crash when assigning FFileSystem->CurrentDirectory
  2345. // to FCurrentDirectory, splitting the assignment to two statements
  2346. // to locate the crash more closely
  2347. UnicodeString CurrentDirectory = FFileSystem->CurrentDirectory;
  2348. FCurrentDirectory = CurrentDirectory;
  2349. if (FCurrentDirectory.IsEmpty())
  2350. {
  2351. ReadCurrentDirectory();
  2352. }
  2353. }
  2354. UnicodeString Result = TranslateLockedPath(FCurrentDirectory, true);
  2355. return Result;
  2356. }
  2357. //---------------------------------------------------------------------------
  2358. UnicodeString __fastcall TTerminal::PeekCurrentDirectory()
  2359. {
  2360. if (FFileSystem)
  2361. {
  2362. FCurrentDirectory = FFileSystem->CurrentDirectory;
  2363. }
  2364. UnicodeString Result = TranslateLockedPath(FCurrentDirectory, true);
  2365. return Result;
  2366. }
  2367. //---------------------------------------------------------------------------
  2368. const TRemoteTokenList * __fastcall TTerminal::GetGroups()
  2369. {
  2370. DebugAssert(FFileSystem);
  2371. LookupUsersGroups();
  2372. return &FGroups;
  2373. }
  2374. //---------------------------------------------------------------------------
  2375. const TRemoteTokenList * __fastcall TTerminal::GetUsers()
  2376. {
  2377. DebugAssert(FFileSystem);
  2378. LookupUsersGroups();
  2379. return &FUsers;
  2380. }
  2381. //---------------------------------------------------------------------------
  2382. const TRemoteTokenList * __fastcall TTerminal::GetMembership()
  2383. {
  2384. DebugAssert(FFileSystem);
  2385. LookupUsersGroups();
  2386. return &FMembership;
  2387. }
  2388. //---------------------------------------------------------------------------
  2389. UnicodeString __fastcall TTerminal::GetUserName() const
  2390. {
  2391. // in future might also be implemented to detect username similar to GetUserGroups
  2392. DebugAssert(FFileSystem != NULL);
  2393. UnicodeString Result = FFileSystem->GetUserName();
  2394. // Is empty also when stored username was used
  2395. if (Result.IsEmpty())
  2396. {
  2397. Result = SessionData->UserNameExpanded;
  2398. }
  2399. return Result;
  2400. }
  2401. //---------------------------------------------------------------------------
  2402. bool __fastcall TTerminal::GetAreCachesEmpty() const
  2403. {
  2404. return FDirectoryCache->IsEmpty &&
  2405. ((FDirectoryChangesCache == NULL) || FDirectoryChangesCache->IsEmpty);
  2406. }
  2407. //---------------------------------------------------------------------------
  2408. void __fastcall TTerminal::DoInitializeLog()
  2409. {
  2410. if (FOnInitializeLog)
  2411. {
  2412. TCallbackGuard Guard(this);
  2413. try
  2414. {
  2415. FOnInitializeLog(this);
  2416. Guard.Verify();
  2417. }
  2418. catch (Exception & E)
  2419. {
  2420. if (!Guard.Verify(&E))
  2421. {
  2422. throw;
  2423. }
  2424. }
  2425. }
  2426. }
  2427. //---------------------------------------------------------------------------
  2428. void __fastcall TTerminal::DoChangeDirectory()
  2429. {
  2430. if (FOnChangeDirectory)
  2431. {
  2432. TCallbackGuard Guard(this);
  2433. try
  2434. {
  2435. FOnChangeDirectory(this);
  2436. Guard.Verify();
  2437. }
  2438. catch (Exception & E)
  2439. {
  2440. if (!Guard.Verify(&E))
  2441. {
  2442. throw;
  2443. }
  2444. }
  2445. }
  2446. }
  2447. //---------------------------------------------------------------------------
  2448. void __fastcall TTerminal::DoReadDirectory(bool ReloadOnly)
  2449. {
  2450. if (FOnReadDirectory)
  2451. {
  2452. TCallbackGuard Guard(this);
  2453. try
  2454. {
  2455. FOnReadDirectory(this, ReloadOnly);
  2456. Guard.Verify();
  2457. }
  2458. catch (Exception & E)
  2459. {
  2460. if (!Guard.Verify(&E))
  2461. {
  2462. throw;
  2463. }
  2464. }
  2465. }
  2466. }
  2467. //---------------------------------------------------------------------------
  2468. void __fastcall TTerminal::DoStartReadDirectory()
  2469. {
  2470. if (FOnStartReadDirectory)
  2471. {
  2472. TCallbackGuard Guard(this);
  2473. try
  2474. {
  2475. FOnStartReadDirectory(this);
  2476. Guard.Verify();
  2477. }
  2478. catch (Exception & E)
  2479. {
  2480. if (!Guard.Verify(&E))
  2481. {
  2482. throw;
  2483. }
  2484. }
  2485. }
  2486. }
  2487. //---------------------------------------------------------------------------
  2488. void __fastcall TTerminal::DoReadDirectoryProgress(int Progress, int ResolvedLinks, bool & Cancel)
  2489. {
  2490. if (FReadingCurrentDirectory && (FOnReadDirectoryProgress != NULL))
  2491. {
  2492. TCallbackGuard Guard(this);
  2493. try
  2494. {
  2495. FOnReadDirectoryProgress(this, Progress, ResolvedLinks, Cancel);
  2496. Guard.Verify();
  2497. }
  2498. catch (Exception & E)
  2499. {
  2500. if (!Guard.Verify(&E))
  2501. {
  2502. throw;
  2503. }
  2504. }
  2505. }
  2506. if (FOnFindingFile != NULL)
  2507. {
  2508. TCallbackGuard Guard(this);
  2509. try
  2510. {
  2511. FOnFindingFile(this, L"", Cancel);
  2512. Guard.Verify();
  2513. }
  2514. catch (Exception & E)
  2515. {
  2516. if (!Guard.Verify(&E))
  2517. {
  2518. throw;
  2519. }
  2520. }
  2521. }
  2522. }
  2523. //---------------------------------------------------------------------------
  2524. bool __fastcall TTerminal::InTransaction()
  2525. {
  2526. return (FInTransaction > 0) && !FSuspendTransaction;
  2527. }
  2528. //---------------------------------------------------------------------------
  2529. void __fastcall TTerminal::BeginTransaction()
  2530. {
  2531. if (FInTransaction == 0)
  2532. {
  2533. FReadCurrentDirectoryPending = false;
  2534. FReadDirectoryPending = false;
  2535. }
  2536. FInTransaction++;
  2537. if (FCommandSession != NULL)
  2538. {
  2539. FCommandSession->BeginTransaction();
  2540. }
  2541. }
  2542. //---------------------------------------------------------------------------
  2543. void __fastcall TTerminal::EndTransaction()
  2544. {
  2545. DoEndTransaction(false);
  2546. }
  2547. //---------------------------------------------------------------------------
  2548. void __fastcall TTerminal::DoEndTransaction(bool Inform)
  2549. {
  2550. if (FInTransaction == 0)
  2551. TerminalError(L"Can't end transaction, not in transaction");
  2552. DebugAssert(FInTransaction > 0);
  2553. FInTransaction--;
  2554. // it connection was closed due to fatal error during transaction, do nothing
  2555. if (Active)
  2556. {
  2557. if (FInTransaction == 0)
  2558. {
  2559. try
  2560. {
  2561. if (FReadCurrentDirectoryPending)
  2562. {
  2563. ReadCurrentDirectory();
  2564. }
  2565. if (FReadDirectoryPending)
  2566. {
  2567. if (Inform)
  2568. {
  2569. DoInformation(LoadStr(STATUS_OPEN_DIRECTORY), true, -1, CurrentDirectory);
  2570. }
  2571. ReadDirectory(!FReadCurrentDirectoryPending);
  2572. }
  2573. }
  2574. __finally
  2575. {
  2576. FReadCurrentDirectoryPending = false;
  2577. FReadDirectoryPending = false;
  2578. }
  2579. }
  2580. }
  2581. if (FCommandSession != NULL)
  2582. {
  2583. FCommandSession->EndTransaction();
  2584. }
  2585. }
  2586. //---------------------------------------------------------------------------
  2587. void __fastcall TTerminal::SetExceptionOnFail(bool value)
  2588. {
  2589. if (value)
  2590. {
  2591. FExceptionOnFail++;
  2592. }
  2593. else
  2594. {
  2595. if (FExceptionOnFail == 0)
  2596. throw Exception(L"ExceptionOnFail is already zero.");
  2597. FExceptionOnFail--;
  2598. }
  2599. if (FCommandSession != NULL)
  2600. {
  2601. FCommandSession->FExceptionOnFail = FExceptionOnFail;
  2602. }
  2603. }
  2604. //---------------------------------------------------------------------------
  2605. bool __fastcall TTerminal::GetExceptionOnFail() const
  2606. {
  2607. return (bool)(FExceptionOnFail > 0);
  2608. }
  2609. //---------------------------------------------------------------------------
  2610. void __fastcall TTerminal::FatalAbort()
  2611. {
  2612. FatalError(NULL, "");
  2613. }
  2614. //---------------------------------------------------------------------------
  2615. void __fastcall TTerminal::FatalError(Exception * E, UnicodeString Msg, UnicodeString HelpKeyword)
  2616. {
  2617. bool SecureShellActive = (FSecureShell != NULL) && FSecureShell->Active;
  2618. if (Active || SecureShellActive)
  2619. {
  2620. // We log this instead of exception handler, because Close() would
  2621. // probably cause exception handler to loose pointer to TShellLog()
  2622. LogEvent(L"Attempt to close connection due to fatal exception:");
  2623. Log->Add(llException, Msg);
  2624. Log->AddException(E);
  2625. if (Active)
  2626. {
  2627. Close();
  2628. }
  2629. // this may happen if failure of authentication of SSH, owned by terminal yet
  2630. // (because the protocol was not decided yet), is detected by us (not by putty).
  2631. // e.g. not verified host key
  2632. if (SecureShellActive)
  2633. {
  2634. FSecureShell->Close();
  2635. }
  2636. }
  2637. if (FCallbackGuard != NULL)
  2638. {
  2639. FCallbackGuard->FatalError(E, Msg, HelpKeyword);
  2640. }
  2641. else
  2642. {
  2643. throw ESshFatal(E, Msg, HelpKeyword);
  2644. }
  2645. }
  2646. //---------------------------------------------------------------------------
  2647. void __fastcall TTerminal::CommandError(Exception * E, const UnicodeString Msg)
  2648. {
  2649. CommandError(E, Msg, 0);
  2650. }
  2651. //---------------------------------------------------------------------------
  2652. unsigned int __fastcall TTerminal::CommandError(Exception * E, const UnicodeString Msg,
  2653. unsigned int Answers, const UnicodeString HelpKeyword)
  2654. {
  2655. // may not be, particularly when TTerminal::Reopen is being called
  2656. // from within OnShowExtendedException handler
  2657. DebugAssert(FCallbackGuard == NULL);
  2658. unsigned int Result = 0;
  2659. if (E && E->InheritsFrom(__classid(EFatal)))
  2660. {
  2661. FatalError(E, Msg, HelpKeyword);
  2662. }
  2663. else if (E && E->InheritsFrom(__classid(EAbort)))
  2664. {
  2665. // resent EAbort exception
  2666. Abort();
  2667. }
  2668. else if (ExceptionOnFail)
  2669. {
  2670. throw ECommand(E, Msg, HelpKeyword);
  2671. }
  2672. else if (!Answers)
  2673. {
  2674. ECommand * ECmd = new ECommand(E, Msg, HelpKeyword);
  2675. try
  2676. {
  2677. HandleExtendedException(ECmd);
  2678. }
  2679. __finally
  2680. {
  2681. delete ECmd;
  2682. }
  2683. }
  2684. else
  2685. {
  2686. // small hack to enable "skip to all" for TRetryOperationLoop
  2687. bool CanSkip = FLAGSET(Answers, qaSkip) && (OperationProgress != NULL);
  2688. if (CanSkip && OperationProgress->SkipToAll)
  2689. {
  2690. Result = qaSkip;
  2691. }
  2692. else
  2693. {
  2694. TQueryParams Params(qpAllowContinueOnError, HelpKeyword);
  2695. TQueryButtonAlias Aliases[1];
  2696. if (CanSkip)
  2697. {
  2698. Aliases[0].Button = qaAll;
  2699. Aliases[0].Alias = LoadStr(SKIP_ALL_BUTTON);
  2700. Params.Aliases = Aliases;
  2701. Params.AliasesCount = LENOF(Aliases);
  2702. Answers |= qaAll;
  2703. }
  2704. Result = QueryUserException(Msg, E, Answers, &Params, qtError);
  2705. if (Result == qaAll)
  2706. {
  2707. DebugAssert(OperationProgress != NULL);
  2708. OperationProgress->SetSkipToAll();
  2709. Result = qaSkip;
  2710. }
  2711. }
  2712. }
  2713. return Result;
  2714. }
  2715. //---------------------------------------------------------------------------
  2716. bool __fastcall TTerminal::HandleException(Exception * E)
  2717. {
  2718. if (ExceptionOnFail)
  2719. {
  2720. return false;
  2721. }
  2722. else
  2723. {
  2724. Log->AddException(E);
  2725. return true;
  2726. }
  2727. }
  2728. //---------------------------------------------------------------------------
  2729. void __fastcall TTerminal::CloseOnCompletion(
  2730. TOnceDoneOperation Operation, const UnicodeString & Message,
  2731. const UnicodeString & TargetLocalPath, const UnicodeString & DestLocalFileName)
  2732. {
  2733. if (FOperationProgressPersistence != NULL)
  2734. {
  2735. DebugAssert(Message.IsEmpty());
  2736. FOperationProgressOnceDoneOperation = Operation;
  2737. }
  2738. else
  2739. {
  2740. Configuration->Usage->Inc(L"ClosesOnCompletion");
  2741. LogEvent(L"Closing session after completed operation (as requested by user)");
  2742. Close();
  2743. throw ESshTerminate(NULL,
  2744. MainInstructions(Message.IsEmpty() ? LoadStr(CLOSED_ON_COMPLETION) : Message),
  2745. Operation, TargetLocalPath, DestLocalFileName);
  2746. }
  2747. }
  2748. //---------------------------------------------------------------------------
  2749. TBatchOverwrite __fastcall TTerminal::EffectiveBatchOverwrite(
  2750. const UnicodeString & SourceFullFileName, const TCopyParamType * CopyParam, int Params, TFileOperationProgressType * OperationProgress, bool Special)
  2751. {
  2752. TBatchOverwrite Result;
  2753. if (Special &&
  2754. (FLAGSET(Params, cpResume) || CopyParam->ResumeTransfer(SourceFullFileName)))
  2755. {
  2756. Result = boResume;
  2757. }
  2758. else if (FLAGSET(Params, cpAppend))
  2759. {
  2760. Result = boAppend;
  2761. }
  2762. else if (CopyParam->NewerOnly &&
  2763. (((OperationProgress->Side == osLocal) && IsCapable[fcNewerOnlyUpload]) ||
  2764. (OperationProgress->Side != osLocal)))
  2765. {
  2766. // no way to change batch overwrite mode when CopyParam->NewerOnly is on
  2767. Result = boOlder;
  2768. }
  2769. else if (FLAGSET(Params, cpNoConfirmation) || !Configuration->ConfirmOverwriting)
  2770. {
  2771. // no way to change batch overwrite mode when overwrite confirmations are off
  2772. DebugAssert(OperationProgress->BatchOverwrite == boNo);
  2773. Result = boAll;
  2774. }
  2775. else
  2776. {
  2777. Result = OperationProgress->BatchOverwrite;
  2778. if (!Special &&
  2779. ((Result == boOlder) || (Result == boAlternateResume) || (Result == boResume)))
  2780. {
  2781. Result = boNo;
  2782. }
  2783. }
  2784. return Result;
  2785. }
  2786. //---------------------------------------------------------------------------
  2787. bool __fastcall TTerminal::CheckRemoteFile(
  2788. const UnicodeString & FileName, const TCopyParamType * CopyParam, int Params, TFileOperationProgressType * OperationProgress)
  2789. {
  2790. bool Result;
  2791. OperationProgress->LockUserSelections();
  2792. try
  2793. {
  2794. Result = (EffectiveBatchOverwrite(FileName, CopyParam, Params, OperationProgress, true) != boAll);
  2795. }
  2796. __finally
  2797. {
  2798. OperationProgress->UnlockUserSelections();
  2799. }
  2800. return Result;
  2801. }
  2802. //---------------------------------------------------------------------------
  2803. unsigned int __fastcall TTerminal::ConfirmFileOverwrite(
  2804. const UnicodeString & SourceFullFileName, const UnicodeString & TargetFileName,
  2805. const TOverwriteFileParams * FileParams, unsigned int Answers, TQueryParams * QueryParams,
  2806. TOperationSide Side, const TCopyParamType * CopyParam, int Params, TFileOperationProgressType * OperationProgress,
  2807. UnicodeString Message)
  2808. {
  2809. unsigned int Result;
  2810. TBatchOverwrite BatchOverwrite;
  2811. bool CanAlternateResume =
  2812. (FileParams != NULL) &&
  2813. (FileParams->DestSize < FileParams->SourceSize) &&
  2814. !OperationProgress->AsciiTransfer;
  2815. OperationProgress->LockUserSelections();
  2816. try
  2817. {
  2818. // duplicated in TSFTPFileSystem::SFTPConfirmOverwrite
  2819. BatchOverwrite = EffectiveBatchOverwrite(SourceFullFileName, CopyParam, Params, OperationProgress, true);
  2820. bool Applicable = true;
  2821. switch (BatchOverwrite)
  2822. {
  2823. case boOlder:
  2824. Applicable = (FileParams != NULL);
  2825. break;
  2826. case boAlternateResume:
  2827. Applicable = CanAlternateResume;
  2828. break;
  2829. case boResume:
  2830. Applicable = CanAlternateResume;
  2831. break;
  2832. }
  2833. if (!Applicable)
  2834. {
  2835. TBatchOverwrite ABatchOverwrite = EffectiveBatchOverwrite(SourceFullFileName, CopyParam, Params, OperationProgress, false);
  2836. DebugAssert(BatchOverwrite != ABatchOverwrite);
  2837. BatchOverwrite = ABatchOverwrite;
  2838. }
  2839. if (BatchOverwrite == boNo)
  2840. {
  2841. // particularly with parallel transfers, the overal operation can be already cancelled by other parallel operation
  2842. if (OperationProgress->Cancel > csContinue)
  2843. {
  2844. Result = qaCancel;
  2845. }
  2846. else
  2847. {
  2848. if (Message.IsEmpty())
  2849. {
  2850. // Side refers to destination side here
  2851. Message = FMTLOAD((Side == osLocal ? LOCAL_FILE_OVERWRITE2 :
  2852. REMOTE_FILE_OVERWRITE2), (TargetFileName, TargetFileName));
  2853. }
  2854. if (FileParams != NULL)
  2855. {
  2856. Message = FMTLOAD(FILE_OVERWRITE_DETAILS, (Message,
  2857. FormatSize(FileParams->SourceSize),
  2858. DefaultStr(UserModificationStr(FileParams->SourceTimestamp, FileParams->SourcePrecision), LoadStr(TIME_UNKNOWN)),
  2859. FormatSize(FileParams->DestSize),
  2860. DefaultStr(UserModificationStr(FileParams->DestTimestamp, FileParams->DestPrecision), LoadStr(TIME_UNKNOWN))));
  2861. }
  2862. if (DebugAlwaysTrue(QueryParams->HelpKeyword.IsEmpty()))
  2863. {
  2864. QueryParams->HelpKeyword = HELP_OVERWRITE;
  2865. }
  2866. Result = QueryUser(Message, NULL, Answers, QueryParams);
  2867. switch (Result)
  2868. {
  2869. case qaNeverAskAgain:
  2870. Configuration->ConfirmOverwriting = false;
  2871. Result = qaYes;
  2872. break;
  2873. case qaYesToAll:
  2874. BatchOverwrite = boAll;
  2875. break;
  2876. case qaAll:
  2877. BatchOverwrite = boOlder;
  2878. break;
  2879. case qaNoToAll:
  2880. BatchOverwrite = boNone;
  2881. break;
  2882. }
  2883. // we user has not selected another batch overwrite mode,
  2884. // keep the current one. note that we may get here even
  2885. // when batch overwrite was selected already, but it could not be applied
  2886. // to current transfer (see condition above)
  2887. if (BatchOverwrite != boNo)
  2888. {
  2889. OperationProgress->SetBatchOverwrite(BatchOverwrite);
  2890. }
  2891. }
  2892. }
  2893. }
  2894. __finally
  2895. {
  2896. OperationProgress->UnlockUserSelections();
  2897. }
  2898. if (BatchOverwrite != boNo)
  2899. {
  2900. switch (BatchOverwrite)
  2901. {
  2902. case boAll:
  2903. Result = qaYes;
  2904. break;
  2905. case boNone:
  2906. Result = qaNo;
  2907. break;
  2908. case boOlder:
  2909. if (FileParams == NULL)
  2910. {
  2911. Result = qaNo;
  2912. }
  2913. else
  2914. {
  2915. TModificationFmt Precision = LessDateTimePrecision(FileParams->SourcePrecision, FileParams->DestPrecision);
  2916. TDateTime ReducedSourceTimestamp =
  2917. ReduceDateTimePrecision(FileParams->SourceTimestamp, Precision);
  2918. TDateTime ReducedDestTimestamp =
  2919. ReduceDateTimePrecision(FileParams->DestTimestamp, Precision);
  2920. Result =
  2921. (CompareFileTime(ReducedSourceTimestamp, ReducedDestTimestamp) > 0) ?
  2922. qaYes : qaNo;
  2923. LogEvent(FORMAT(L"Source file timestamp is [%s], destination timestamp is [%s], will%s overwrite",
  2924. (StandardTimestamp(ReducedSourceTimestamp),
  2925. StandardTimestamp(ReducedDestTimestamp),
  2926. ((Result == qaYes) ? L"" : L" not"))));
  2927. }
  2928. break;
  2929. case boAlternateResume:
  2930. DebugAssert(CanAlternateResume);
  2931. Result = qaSkip; // ugh
  2932. break;
  2933. case boAppend:
  2934. Result = qaRetry;
  2935. break;
  2936. case boResume:
  2937. Result = qaRetry;
  2938. break;
  2939. }
  2940. }
  2941. return Result;
  2942. }
  2943. //---------------------------------------------------------------------------
  2944. void __fastcall TTerminal::FileModified(const TRemoteFile * File,
  2945. const UnicodeString FileName, bool ClearDirectoryChange)
  2946. {
  2947. UnicodeString ParentDirectory;
  2948. UnicodeString Directory;
  2949. if (SessionData->CacheDirectories || SessionData->CacheDirectoryChanges)
  2950. {
  2951. if ((File != NULL) && (File->Directory != NULL))
  2952. {
  2953. if (File->IsDirectory)
  2954. {
  2955. Directory = File->Directory->FullDirectory + File->FileName;
  2956. }
  2957. ParentDirectory = File->Directory->Directory;
  2958. }
  2959. else if (!FileName.IsEmpty())
  2960. {
  2961. ParentDirectory = UnixExtractFilePath(FileName);
  2962. if (ParentDirectory.IsEmpty())
  2963. {
  2964. ParentDirectory = CurrentDirectory;
  2965. }
  2966. // this case for scripting
  2967. if ((File != NULL) && File->IsDirectory)
  2968. {
  2969. Directory = UnixIncludeTrailingBackslash(ParentDirectory) +
  2970. UnixExtractFileName(File->FileName);
  2971. }
  2972. }
  2973. }
  2974. if (SessionData->CacheDirectories)
  2975. {
  2976. if (!Directory.IsEmpty())
  2977. {
  2978. DirectoryModified(Directory, true);
  2979. }
  2980. if (!ParentDirectory.IsEmpty())
  2981. {
  2982. DirectoryModified(ParentDirectory, false);
  2983. }
  2984. }
  2985. if (SessionData->CacheDirectoryChanges && ClearDirectoryChange)
  2986. {
  2987. if (!Directory.IsEmpty())
  2988. {
  2989. FDirectoryChangesCache->ClearDirectoryChange(Directory);
  2990. FDirectoryChangesCache->ClearDirectoryChangeTarget(Directory);
  2991. }
  2992. }
  2993. }
  2994. //---------------------------------------------------------------------------
  2995. void __fastcall TTerminal::DirectoryModified(const UnicodeString Path, bool SubDirs)
  2996. {
  2997. if (Path.IsEmpty())
  2998. {
  2999. ClearCachedFileList(CurrentDirectory, SubDirs);
  3000. }
  3001. else
  3002. {
  3003. ClearCachedFileList(Path, SubDirs);
  3004. }
  3005. }
  3006. //---------------------------------------------------------------------------
  3007. void __fastcall TTerminal::DirectoryLoaded(TRemoteFileList * FileList)
  3008. {
  3009. AddCachedFileList(FileList);
  3010. }
  3011. //---------------------------------------------------------------------------
  3012. void __fastcall TTerminal::ReloadDirectory()
  3013. {
  3014. if (SessionData->CacheDirectories)
  3015. {
  3016. DirectoryModified(CurrentDirectory, false);
  3017. }
  3018. if (SessionData->CacheDirectoryChanges)
  3019. {
  3020. DebugAssert(FDirectoryChangesCache != NULL);
  3021. FDirectoryChangesCache->ClearDirectoryChange(CurrentDirectory);
  3022. }
  3023. ReadCurrentDirectory();
  3024. FReadCurrentDirectoryPending = false;
  3025. ReadDirectory(true);
  3026. FReadDirectoryPending = false;
  3027. }
  3028. //---------------------------------------------------------------------------
  3029. void __fastcall TTerminal::RefreshDirectory()
  3030. {
  3031. if (!SessionData->CacheDirectories)
  3032. {
  3033. LogEvent(L"Not refreshing directory, caching is off.");
  3034. }
  3035. else if (FDirectoryCache->HasNewerFileList(CurrentDirectory, FFiles->Timestamp))
  3036. {
  3037. // Second parameter was added to allow (rather force) using the cache.
  3038. // Before, the directory was reloaded always, it seems useless,
  3039. // has it any reason?
  3040. ReadDirectory(true, true);
  3041. FReadDirectoryPending = false;
  3042. }
  3043. }
  3044. //---------------------------------------------------------------------------
  3045. void __fastcall TTerminal::EnsureNonExistence(const UnicodeString FileName)
  3046. {
  3047. // if filename doesn't contain path, we check for existence of file
  3048. if ((UnixExtractFileDir(FileName).IsEmpty()) &&
  3049. UnixSamePath(CurrentDirectory, FFiles->Directory))
  3050. {
  3051. TRemoteFile *File = FFiles->FindFile(FileName);
  3052. if (File)
  3053. {
  3054. if (File->IsDirectory) throw ECommand(NULL, FMTLOAD(RENAME_CREATE_DIR_EXISTS, (FileName)));
  3055. else throw ECommand(NULL, FMTLOAD(RENAME_CREATE_FILE_EXISTS, (FileName)));
  3056. }
  3057. }
  3058. }
  3059. //---------------------------------------------------------------------------
  3060. void __fastcall inline TTerminal::LogEvent(const UnicodeString & Str)
  3061. {
  3062. if (Log->Logging)
  3063. {
  3064. Log->Add(llMessage, Str);
  3065. }
  3066. }
  3067. //---------------------------------------------------------------------------
  3068. void __fastcall TTerminal::LogEvent(int Level, const UnicodeString & Str)
  3069. {
  3070. if (Log->Logging && (Configuration->ActualLogProtocol >= Level))
  3071. {
  3072. Log->Add(llMessage, Str);
  3073. }
  3074. }
  3075. //---------------------------------------------------------------------------
  3076. void __fastcall TTerminal::RollbackAction(TSessionAction & Action,
  3077. TFileOperationProgressType * OperationProgress, Exception * E)
  3078. {
  3079. // ESkipFile without "cancel" is file skip,
  3080. // and we do not want to record skipped actions.
  3081. // But ESkipFile with "cancel" is abort and we want to record that.
  3082. // Note that TScpFileSystem modifies the logic of RollbackAction little bit.
  3083. if ((dynamic_cast<ESkipFile *>(E) != NULL) &&
  3084. ((OperationProgress == NULL) ||
  3085. (OperationProgress->Cancel == csContinue)))
  3086. {
  3087. Action.Cancel();
  3088. }
  3089. else
  3090. {
  3091. Action.Rollback(E);
  3092. }
  3093. }
  3094. //---------------------------------------------------------------------------
  3095. void __fastcall TTerminal::DoStartup()
  3096. {
  3097. LogEvent(L"Doing startup conversation with host.");
  3098. BeginTransaction();
  3099. try
  3100. {
  3101. DoInformation(LoadStr(STATUS_STARTUP), true);
  3102. // Make sure that directory would be loaded at last
  3103. FReadCurrentDirectoryPending = true;
  3104. FReadDirectoryPending = AutoReadDirectory;
  3105. FFileSystem->DoStartup();
  3106. LookupUsersGroups();
  3107. if (!SessionData->RemoteDirectory.IsEmpty())
  3108. {
  3109. if (SessionData->UpdateDirectories)
  3110. {
  3111. ExceptionOnFail = true;
  3112. try
  3113. {
  3114. ChangeDirectory(SessionData->RemoteDirectory);
  3115. }
  3116. catch (...)
  3117. {
  3118. if (!Active)
  3119. {
  3120. LogEvent(L"Configured initial remote directory cannot be opened, staying in the home directory.");
  3121. throw;
  3122. }
  3123. }
  3124. ExceptionOnFail = false;
  3125. }
  3126. else
  3127. {
  3128. ChangeDirectory(SessionData->RemoteDirectory);
  3129. }
  3130. }
  3131. }
  3132. __finally
  3133. {
  3134. DoEndTransaction(true);
  3135. }
  3136. LogEvent(L"Startup conversation with host finished.");
  3137. }
  3138. //---------------------------------------------------------------------------
  3139. void __fastcall TTerminal::ReadCurrentDirectory()
  3140. {
  3141. DebugAssert(FFileSystem);
  3142. try
  3143. {
  3144. // reset flag in case we are called externally (like from console dialog)
  3145. FReadCurrentDirectoryPending = false;
  3146. LogEvent(L"Getting current directory name.");
  3147. UnicodeString OldDirectory = FFileSystem->CurrentDirectory;
  3148. FFileSystem->ReadCurrentDirectory();
  3149. ReactOnCommand(fsCurrentDirectory);
  3150. if (SessionData->CacheDirectoryChanges)
  3151. {
  3152. DebugAssert(FDirectoryChangesCache != NULL);
  3153. if (!CurrentDirectory.IsEmpty() && !FLastDirectoryChange.IsEmpty() && (CurrentDirectory != OldDirectory))
  3154. {
  3155. FDirectoryChangesCache->AddDirectoryChange(OldDirectory,
  3156. FLastDirectoryChange, CurrentDirectory);
  3157. }
  3158. // not to breake the cache, if the next directory change would not
  3159. // be initialized by ChangeDirectory(), which sets it
  3160. // (HomeDirectory() particularly)
  3161. FLastDirectoryChange = L"";
  3162. }
  3163. if (OldDirectory.IsEmpty())
  3164. {
  3165. FLockDirectory = (SessionData->LockInHome ?
  3166. FFileSystem->CurrentDirectory : UnicodeString(L""));
  3167. }
  3168. if (OldDirectory != FFileSystem->CurrentDirectory) DoChangeDirectory();
  3169. }
  3170. catch (Exception &E)
  3171. {
  3172. CommandError(&E, LoadStr(READ_CURRENT_DIR_ERROR));
  3173. }
  3174. }
  3175. //---------------------------------------------------------------------------
  3176. void __fastcall TTerminal::ReadDirectory(bool ReloadOnly, bool ForceCache)
  3177. {
  3178. bool LoadedFromCache = false;
  3179. if (SessionData->CacheDirectories && FDirectoryCache->HasFileList(CurrentDirectory))
  3180. {
  3181. if (ReloadOnly && !ForceCache)
  3182. {
  3183. LogEvent(L"Cached directory not reloaded.");
  3184. }
  3185. else
  3186. {
  3187. DoStartReadDirectory();
  3188. try
  3189. {
  3190. LoadedFromCache = FDirectoryCache->GetFileList(CurrentDirectory, FFiles);
  3191. }
  3192. __finally
  3193. {
  3194. DoReadDirectory(ReloadOnly);
  3195. }
  3196. if (LoadedFromCache)
  3197. {
  3198. LogEvent(L"Directory content loaded from cache.");
  3199. }
  3200. else
  3201. {
  3202. LogEvent(L"Cached Directory content has been removed.");
  3203. }
  3204. }
  3205. }
  3206. if (!LoadedFromCache)
  3207. {
  3208. DoStartReadDirectory();
  3209. FReadingCurrentDirectory = true;
  3210. bool Cancel = false; // dummy
  3211. DoReadDirectoryProgress(0, 0, Cancel);
  3212. try
  3213. {
  3214. TRemoteDirectory * Files = new TRemoteDirectory(this, FFiles);
  3215. try
  3216. {
  3217. Files->Directory = CurrentDirectory;
  3218. CustomReadDirectory(Files);
  3219. }
  3220. __finally
  3221. {
  3222. DoReadDirectoryProgress(-1, 0, Cancel);
  3223. FReadingCurrentDirectory = false;
  3224. TRemoteDirectory * OldFiles = FFiles;
  3225. FFiles = Files;
  3226. try
  3227. {
  3228. DoReadDirectory(ReloadOnly);
  3229. }
  3230. __finally
  3231. {
  3232. // delete only after loading new files to dir view,
  3233. // not to destroy the file objects that the view holds
  3234. // (can be issue in multi threaded environment, such as when the
  3235. // terminal is reconnecting in the terminal thread)
  3236. delete OldFiles;
  3237. }
  3238. if (Active)
  3239. {
  3240. if (SessionData->CacheDirectories)
  3241. {
  3242. DirectoryLoaded(FFiles);
  3243. }
  3244. }
  3245. }
  3246. }
  3247. catch (Exception &E)
  3248. {
  3249. CommandError(&E, FmtLoadStr(LIST_DIR_ERROR, ARRAYOFCONST((FFiles->Directory))));
  3250. }
  3251. }
  3252. }
  3253. //---------------------------------------------------------------------------
  3254. UnicodeString __fastcall TTerminal::GetRemoteFileInfo(TRemoteFile * File)
  3255. {
  3256. return
  3257. FORMAT(L"%s;%s;%d;%s;%d;%s;%s;%s;%d",
  3258. (File->FileName, File->Type, File->Size, StandardTimestamp(File->Modification), int(File->ModificationFmt),
  3259. File->Owner.LogText, File->Group.LogText, File->Rights->Text,
  3260. File->Attr));
  3261. }
  3262. //---------------------------------------------------------------------------
  3263. void __fastcall TTerminal::LogRemoteFile(TRemoteFile * File)
  3264. {
  3265. // optimization
  3266. if (Log->Logging)
  3267. {
  3268. LogEvent(GetRemoteFileInfo(File));
  3269. }
  3270. }
  3271. //---------------------------------------------------------------------------
  3272. UnicodeString __fastcall TTerminal::FormatFileDetailsForLog(
  3273. const UnicodeString & FileName, TDateTime Modification, __int64 Size, const TRemoteFile * LinkedFile)
  3274. {
  3275. UnicodeString Result;
  3276. // optimization
  3277. if (Log->Logging)
  3278. {
  3279. Result = FORMAT(L"'%s' [%s] [%s]", (FileName, (Modification != TDateTime() ? StandardTimestamp(Modification) : UnicodeString(L"n/a")), IntToStr(Size)));
  3280. if (LinkedFile != NULL)
  3281. {
  3282. LinkedFile = LinkedFile->Resolve(); // in case it's symlink to symlink
  3283. Result += FORMAT(L" - Link to: %s", (FormatFileDetailsForLog(LinkedFile->FileName, LinkedFile->Modification, LinkedFile->Size, NULL)));
  3284. }
  3285. }
  3286. return Result;
  3287. }
  3288. //---------------------------------------------------------------------------
  3289. void __fastcall TTerminal::LogFileDetails(const UnicodeString & FileName, TDateTime Modification, __int64 Size, const TRemoteFile * LinkedFile)
  3290. {
  3291. // optimization
  3292. if (Log->Logging)
  3293. {
  3294. LogEvent(FORMAT("File: %s", (FormatFileDetailsForLog(FileName, Modification, Size, LinkedFile))));
  3295. }
  3296. }
  3297. //---------------------------------------------------------------------------
  3298. void __fastcall TTerminal::LogFileDone(TFileOperationProgressType * OperationProgress, const UnicodeString & DestFileName)
  3299. {
  3300. if (FDestFileName.IsEmpty())
  3301. {
  3302. FDestFileName = DestFileName;
  3303. }
  3304. else
  3305. {
  3306. FMultipleDestinationFiles = true;
  3307. }
  3308. // optimization
  3309. if (Log->Logging)
  3310. {
  3311. LogEvent(FORMAT("Transfer done: '%s' => '%s' [%s]", (OperationProgress->FullFileName, DestFileName, IntToStr(OperationProgress->TransferredSize))));
  3312. }
  3313. }
  3314. //---------------------------------------------------------------------------
  3315. void __fastcall TTerminal::CustomReadDirectory(TRemoteFileList * FileList)
  3316. {
  3317. DebugAssert(FileList);
  3318. DebugAssert(FFileSystem);
  3319. // To match FTP upload/download, we also limit directory listing.
  3320. // For simplicity, we limit it unconditionally, for all protocols for any kind of errors.
  3321. bool FileTransferAny = false;
  3322. TRobustOperationLoop RobustLoop(this, OperationProgress, &FileTransferAny);
  3323. do
  3324. {
  3325. try
  3326. {
  3327. // Record even an attempt, to avoid listing a directory over and over again, when it is not readable actually
  3328. if (IsEncryptingFiles())
  3329. {
  3330. FFoldersScannedForEncryptedFiles.insert(FileList->Directory);
  3331. }
  3332. FFileSystem->ReadDirectory(FileList);
  3333. }
  3334. catch (Exception & E)
  3335. {
  3336. // Do not retry for initial listing of directory,
  3337. // we instead retry whole connection attempt,
  3338. // what would be done anyway (but Open is not ready for recursion).
  3339. if ((FOpening > 0) ||
  3340. !RobustLoop.TryReopen(E))
  3341. {
  3342. throw;
  3343. }
  3344. }
  3345. }
  3346. while (RobustLoop.Retry());
  3347. if (Log->Logging && (Configuration->ActualLogProtocol >= 0))
  3348. {
  3349. for (int Index = 0; Index < FileList->Count; Index++)
  3350. {
  3351. LogRemoteFile(FileList->Files[Index]);
  3352. }
  3353. }
  3354. ReactOnCommand(fsListDirectory);
  3355. }
  3356. //---------------------------------------------------------------------------
  3357. TRemoteFileList * __fastcall TTerminal::ReadDirectoryListing(UnicodeString Directory, const TFileMasks & Mask)
  3358. {
  3359. TRemoteFileList * FileList;
  3360. TRetryOperationLoop RetryLoop(this);
  3361. do
  3362. {
  3363. FileList = NULL;
  3364. TLsSessionAction Action(ActionLog, AbsolutePath(Directory, true));
  3365. try
  3366. {
  3367. FileList = DoReadDirectoryListing(Directory, false);
  3368. if (FileList != NULL)
  3369. {
  3370. int Index = 0;
  3371. while (Index < FileList->Count)
  3372. {
  3373. TRemoteFile * File = FileList->Files[Index];
  3374. TFileMasks::TParams Params;
  3375. Params.Size = File->Resolve()->Size;
  3376. Params.Modification = File->Modification;
  3377. // Have to use UnicodeString(), instead of L"", as with that
  3378. // overload with (UnicodeString, bool, bool, TParams*) wins
  3379. if (!Mask.Matches(File->FileName, false, UnicodeString(), &Params))
  3380. {
  3381. FileList->Delete(Index);
  3382. }
  3383. else
  3384. {
  3385. Index++;
  3386. }
  3387. }
  3388. Action.FileList(FileList);
  3389. }
  3390. }
  3391. catch(Exception & E)
  3392. {
  3393. RetryLoop.Error(E, Action);
  3394. }
  3395. }
  3396. while (RetryLoop.Retry());
  3397. return FileList;
  3398. }
  3399. //---------------------------------------------------------------------------
  3400. TRemoteFile * __fastcall TTerminal::ReadFileListing(UnicodeString Path)
  3401. {
  3402. TRemoteFile * File;
  3403. TRetryOperationLoop RetryLoop(this);
  3404. do
  3405. {
  3406. File = NULL;
  3407. TStatSessionAction Action(ActionLog, AbsolutePath(Path, true));
  3408. try
  3409. {
  3410. // reset caches
  3411. AnnounceFileListOperation();
  3412. ReadFile(Path, File);
  3413. Action.File(File);
  3414. }
  3415. catch(Exception & E)
  3416. {
  3417. RetryLoop.Error(E, Action);
  3418. }
  3419. }
  3420. while (RetryLoop.Retry());
  3421. return File;
  3422. }
  3423. //---------------------------------------------------------------------------
  3424. TRemoteFileList * __fastcall TTerminal::CustomReadDirectoryListing(UnicodeString Directory, bool UseCache)
  3425. {
  3426. TRemoteFileList * FileList = NULL;
  3427. TRetryOperationLoop RetryLoop(this);
  3428. do
  3429. {
  3430. try
  3431. {
  3432. FileList = DoReadDirectoryListing(Directory, UseCache);
  3433. }
  3434. catch(Exception & E)
  3435. {
  3436. RetryLoop.Error(E);
  3437. }
  3438. }
  3439. while (RetryLoop.Retry());
  3440. return FileList;
  3441. }
  3442. //---------------------------------------------------------------------------
  3443. TRemoteFileList * __fastcall TTerminal::DoReadDirectoryListing(UnicodeString Directory, bool UseCache)
  3444. {
  3445. TRemoteFileList * FileList = new TRemoteFileList();
  3446. try
  3447. {
  3448. bool Cache = UseCache && SessionData->CacheDirectories;
  3449. bool LoadedFromCache = Cache && FDirectoryCache->HasFileList(Directory);
  3450. if (LoadedFromCache)
  3451. {
  3452. LoadedFromCache = FDirectoryCache->GetFileList(Directory, FileList);
  3453. }
  3454. if (!LoadedFromCache)
  3455. {
  3456. FileList->Directory = Directory;
  3457. ExceptionOnFail = true;
  3458. try
  3459. {
  3460. ReadDirectory(FileList);
  3461. }
  3462. __finally
  3463. {
  3464. ExceptionOnFail = false;
  3465. }
  3466. if (Cache)
  3467. {
  3468. AddCachedFileList(FileList);
  3469. }
  3470. }
  3471. }
  3472. catch(...)
  3473. {
  3474. delete FileList;
  3475. throw;
  3476. }
  3477. return FileList;
  3478. }
  3479. //---------------------------------------------------------------------------
  3480. bool __fastcall TTerminal::DeleteContentsIfDirectory(
  3481. const UnicodeString & FileName, const TRemoteFile * File, int Params, TRmSessionAction & Action)
  3482. {
  3483. bool Dir = (File != NULL) && File->IsDirectory && CanRecurseToDirectory(File);
  3484. if (Dir && FLAGCLEAR(Params, dfNoRecursive))
  3485. {
  3486. try
  3487. {
  3488. ProcessDirectory(FileName, DeleteFile, &Params);
  3489. }
  3490. catch(...)
  3491. {
  3492. Action.Cancel();
  3493. throw;
  3494. }
  3495. }
  3496. return Dir && !File->IsSymLink;
  3497. }
  3498. //---------------------------------------------------------------------------
  3499. void __fastcall TTerminal::ProcessDirectory(const UnicodeString DirName,
  3500. TProcessFileEvent CallBackFunc, void * Param, bool UseCache, bool IgnoreErrors)
  3501. {
  3502. TRemoteFileList * FileList = NULL;
  3503. if (IgnoreErrors)
  3504. {
  3505. ExceptionOnFail = true;
  3506. try
  3507. {
  3508. try
  3509. {
  3510. FileList = CustomReadDirectoryListing(DirName, UseCache);
  3511. }
  3512. catch(...)
  3513. {
  3514. if (!Active)
  3515. {
  3516. throw;
  3517. }
  3518. }
  3519. }
  3520. __finally
  3521. {
  3522. ExceptionOnFail = false;
  3523. }
  3524. }
  3525. else
  3526. {
  3527. FileList = CustomReadDirectoryListing(DirName, UseCache);
  3528. }
  3529. // skip if directory listing fails and user selects "skip"
  3530. if (FileList)
  3531. {
  3532. try
  3533. {
  3534. UnicodeString Directory = UnixIncludeTrailingBackslash(DirName);
  3535. TRemoteFile * File;
  3536. for (int Index = 0; Index < FileList->Count; Index++)
  3537. {
  3538. File = FileList->Files[Index];
  3539. if (IsRealFile(File->FileName))
  3540. {
  3541. CallBackFunc(Directory + File->FileName, File, Param);
  3542. // We should catch ESkipFile here as we do in ProcessFiles.
  3543. // Now we have to handle ESkipFile in every callback implementation.
  3544. }
  3545. }
  3546. }
  3547. __finally
  3548. {
  3549. delete FileList;
  3550. }
  3551. }
  3552. }
  3553. //---------------------------------------------------------------------------
  3554. void __fastcall TTerminal::ReadDirectory(TRemoteFileList * FileList)
  3555. {
  3556. try
  3557. {
  3558. CustomReadDirectory(FileList);
  3559. }
  3560. catch (Exception &E)
  3561. {
  3562. CommandError(&E, FmtLoadStr(LIST_DIR_ERROR, ARRAYOFCONST((FileList->Directory))));
  3563. }
  3564. }
  3565. //---------------------------------------------------------------------------
  3566. void __fastcall TTerminal::ReadSymlink(TRemoteFile * SymlinkFile,
  3567. TRemoteFile *& File)
  3568. {
  3569. DebugAssert(FFileSystem);
  3570. try
  3571. {
  3572. LogEvent(FORMAT(L"Reading symlink \"%s\".", (SymlinkFile->FileName)));
  3573. FFileSystem->ReadSymlink(SymlinkFile, File);
  3574. ReactOnCommand(fsReadSymlink);
  3575. }
  3576. catch (Exception &E)
  3577. {
  3578. CommandError(&E, FMTLOAD(READ_SYMLINK_ERROR, (SymlinkFile->FileName)));
  3579. }
  3580. }
  3581. //---------------------------------------------------------------------------
  3582. void __fastcall TTerminal::ReadFile(const UnicodeString FileName,
  3583. TRemoteFile *& File)
  3584. {
  3585. DebugAssert(FFileSystem);
  3586. File = NULL;
  3587. try
  3588. {
  3589. LogEvent(FORMAT(L"Listing file \"%s\".", (FileName)));
  3590. FFileSystem->ReadFile(FileName, File);
  3591. ReactOnCommand(fsListFile);
  3592. LogRemoteFile(File);
  3593. }
  3594. catch (Exception &E)
  3595. {
  3596. if (File) delete File;
  3597. File = NULL;
  3598. CommandError(&E, FMTLOAD(CANT_GET_ATTRS, (FileName)));
  3599. }
  3600. }
  3601. //---------------------------------------------------------------------------
  3602. bool __fastcall TTerminal::FileExists(const UnicodeString FileName, TRemoteFile ** AFile)
  3603. {
  3604. bool Result;
  3605. TRemoteFile * File = NULL;
  3606. try
  3607. {
  3608. ExceptionOnFail = true;
  3609. try
  3610. {
  3611. ReadFile(UnixExcludeTrailingBackslash(FileName), File);
  3612. }
  3613. __finally
  3614. {
  3615. ExceptionOnFail = false;
  3616. }
  3617. if (AFile != NULL)
  3618. {
  3619. *AFile = File;
  3620. }
  3621. else
  3622. {
  3623. delete File;
  3624. }
  3625. Result = true;
  3626. }
  3627. catch(...)
  3628. {
  3629. if (Active)
  3630. {
  3631. Result = false;
  3632. }
  3633. else
  3634. {
  3635. throw;
  3636. }
  3637. }
  3638. return Result;
  3639. }
  3640. //---------------------------------------------------------------------------
  3641. void __fastcall TTerminal::AnnounceFileListOperation()
  3642. {
  3643. FFileSystem->AnnounceFileListOperation();
  3644. }
  3645. //---------------------------------------------------------------------------
  3646. void __fastcall TTerminal::OperationFinish(
  3647. TFileOperationProgressType * Progress, const void * /*Item*/, const UnicodeString & FileName,
  3648. bool Success, TOnceDoneOperation & OnceDoneOperation)
  3649. {
  3650. Progress->Finish(FileName, Success, OnceDoneOperation);
  3651. }
  3652. //---------------------------------------------------------------------------
  3653. void __fastcall TTerminal::OperationStart(
  3654. TFileOperationProgressType & Progress, TFileOperation Operation, TOperationSide Side, int Count)
  3655. {
  3656. OperationStart(Progress, Operation, Side, Count, false, UnicodeString(), 0, odoIdle);
  3657. }
  3658. //---------------------------------------------------------------------------
  3659. void __fastcall TTerminal::OperationStart(
  3660. TFileOperationProgressType & Progress, TFileOperation Operation, TOperationSide Side, int Count,
  3661. bool Temp, const UnicodeString & Directory, unsigned long CPSLimit, TOnceDoneOperation OnceDoneOperation)
  3662. {
  3663. if (FOperationProgressPersistence != NULL)
  3664. {
  3665. Progress.Restore(*FOperationProgressPersistence);
  3666. }
  3667. Progress.Start(Operation, Side, Count, Temp, Directory, CPSLimit, OnceDoneOperation);
  3668. DebugAssert(FOperationProgress == NULL);
  3669. FOperationProgress = &Progress;
  3670. }
  3671. //---------------------------------------------------------------------------
  3672. void __fastcall TTerminal::OperationStop(TFileOperationProgressType & Progress)
  3673. {
  3674. DebugAssert(FOperationProgress == &Progress);
  3675. if (FOperationProgressPersistence != NULL)
  3676. {
  3677. Progress.Store(*FOperationProgressPersistence);
  3678. }
  3679. FOperationProgress = NULL;
  3680. Progress.Stop();
  3681. }
  3682. //---------------------------------------------------------------------------
  3683. bool __fastcall TTerminal::ProcessFiles(TStrings * FileList,
  3684. TFileOperation Operation, TProcessFileEvent ProcessFile, void * Param,
  3685. TOperationSide Side, bool Ex)
  3686. {
  3687. DebugAssert(FileList);
  3688. bool Result = false;
  3689. TOnceDoneOperation OnceDoneOperation = odoIdle;
  3690. try
  3691. {
  3692. TFileOperationProgressType Progress(&DoProgress, &DoFinished);
  3693. OperationStart(Progress, Operation, Side, FileList->Count);
  3694. try
  3695. {
  3696. if (Side == osRemote)
  3697. {
  3698. DebugAssert(FFileSystem != NULL);
  3699. BeginTransaction();
  3700. }
  3701. try
  3702. {
  3703. int Index = 0;
  3704. UnicodeString FileName;
  3705. bool Success;
  3706. while ((Index < FileList->Count) && (Progress.Cancel == csContinue))
  3707. {
  3708. FileName = FileList->Strings[Index];
  3709. TRemoteFile * File = reinterpret_cast<TRemoteFile *>(FileList->Objects[Index]);
  3710. try
  3711. {
  3712. try
  3713. {
  3714. Success = false;
  3715. if (!Ex)
  3716. {
  3717. ProcessFile(FileName, File, Param);
  3718. }
  3719. else
  3720. {
  3721. // not used anymore
  3722. TProcessFileEventEx ProcessFileEx = (TProcessFileEventEx)ProcessFile;
  3723. ProcessFileEx(FileName, File, Param, Index);
  3724. }
  3725. Success = true;
  3726. }
  3727. __finally
  3728. {
  3729. OperationFinish(&Progress, File, FileName, Success, OnceDoneOperation);
  3730. }
  3731. }
  3732. catch(ESkipFile & E)
  3733. {
  3734. TSuspendFileOperationProgress Suspend(OperationProgress);
  3735. if (!HandleException(&E))
  3736. {
  3737. throw;
  3738. }
  3739. }
  3740. Index++;
  3741. }
  3742. }
  3743. __finally
  3744. {
  3745. if (Side == osRemote)
  3746. {
  3747. EndTransaction();
  3748. }
  3749. }
  3750. if (Progress.Cancel == csContinue)
  3751. {
  3752. Result = true;
  3753. }
  3754. }
  3755. __finally
  3756. {
  3757. OperationStop(Progress);
  3758. }
  3759. }
  3760. catch (...)
  3761. {
  3762. OnceDoneOperation = odoIdle;
  3763. // this was missing here. was it by purpose?
  3764. // without it any error message is lost
  3765. throw;
  3766. }
  3767. if (OnceDoneOperation != odoIdle)
  3768. {
  3769. CloseOnCompletion(OnceDoneOperation);
  3770. }
  3771. return Result;
  3772. }
  3773. //---------------------------------------------------------------------------
  3774. // not used anymore
  3775. bool __fastcall TTerminal::ProcessFilesEx(TStrings * FileList, TFileOperation Operation,
  3776. TProcessFileEventEx ProcessFile, void * Param, TOperationSide Side)
  3777. {
  3778. return ProcessFiles(FileList, Operation, TProcessFileEvent(ProcessFile),
  3779. Param, Side, true);
  3780. }
  3781. //---------------------------------------------------------------------------
  3782. TStrings * __fastcall TTerminal::GetFixedPaths()
  3783. {
  3784. DebugAssert(FFileSystem != NULL);
  3785. return FFileSystem->GetFixedPaths();
  3786. }
  3787. //---------------------------------------------------------------------------
  3788. bool __fastcall TTerminal::GetResolvingSymlinks()
  3789. {
  3790. return SessionData->ResolveSymlinks && IsCapable[fcResolveSymlink];
  3791. }
  3792. //---------------------------------------------------------------------------
  3793. TUsableCopyParamAttrs __fastcall TTerminal::UsableCopyParamAttrs(int Params)
  3794. {
  3795. TUsableCopyParamAttrs Result;
  3796. Result.General =
  3797. FLAGMASK(!IsCapable[fcTextMode], cpaNoTransferMode) |
  3798. FLAGMASK(!IsCapable[fcModeChanging], cpaNoRights) |
  3799. FLAGMASK(!IsCapable[fcModeChanging], cpaNoPreserveReadOnly) |
  3800. FLAGMASK(FLAGSET(Params, cpDelete), cpaNoClearArchive) |
  3801. FLAGMASK(!IsCapable[fcIgnorePermErrors], cpaNoIgnorePermErrors) |
  3802. // the following three are never supported for download,
  3803. // so when they are not suppored for upload too,
  3804. // set them in General flags, so that they do not get enabled on
  3805. // Synchronize dialog.
  3806. FLAGMASK(!IsCapable[fcModeChangingUpload], cpaNoRights) |
  3807. FLAGMASK(!IsCapable[fcRemoveCtrlZUpload], cpaNoRemoveCtrlZ) |
  3808. FLAGMASK(!IsCapable[fcRemoveBOMUpload], cpaNoRemoveBOM) |
  3809. FLAGMASK(!IsCapable[fcPreservingTimestampDirs], cpaNoPreserveTimeDirs) |
  3810. FLAGMASK(!IsCapable[fcResumeSupport], cpaNoResumeSupport) |
  3811. FLAGMASK(!IsEncryptingFiles(), cpaNoEncryptNewFiles);
  3812. Result.Download = Result.General | cpaNoClearArchive |
  3813. cpaNoIgnorePermErrors |
  3814. // May be already set in General flags, but it's unconditional here
  3815. cpaNoRights | cpaNoRemoveCtrlZ | cpaNoRemoveBOM | cpaNoEncryptNewFiles;
  3816. Result.Upload = Result.General | cpaNoPreserveReadOnly |
  3817. FLAGMASK(!IsCapable[fcPreservingTimestampUpload], cpaNoPreserveTime);
  3818. return Result;
  3819. }
  3820. //---------------------------------------------------------------------------
  3821. bool __fastcall TTerminal::IsRecycledFile(UnicodeString FileName)
  3822. {
  3823. bool Result = !SessionData->RecycleBinPath.IsEmpty();
  3824. if (Result)
  3825. {
  3826. UnicodeString Path = UnixExtractFilePath(FileName);
  3827. if (Path.IsEmpty())
  3828. {
  3829. Path = CurrentDirectory;
  3830. }
  3831. Result = UnixSamePath(Path, SessionData->RecycleBinPath);
  3832. }
  3833. return Result;
  3834. }
  3835. //---------------------------------------------------------------------------
  3836. bool __fastcall TTerminal::RecycleFile(const UnicodeString & AFileName, const TRemoteFile * File)
  3837. {
  3838. UnicodeString FileName = AFileName;
  3839. if (FileName.IsEmpty())
  3840. {
  3841. DebugAssert(File != NULL);
  3842. FileName = File->FileName;
  3843. }
  3844. bool Result;
  3845. if (IsRecycledFile(FileName))
  3846. {
  3847. Result = true;
  3848. }
  3849. else
  3850. {
  3851. LogEvent(FORMAT(L"Moving file \"%s\" to remote recycle bin '%s'.",
  3852. (FileName, SessionData->RecycleBinPath)));
  3853. TMoveFileParams Params;
  3854. Params.Target = SessionData->RecycleBinPath;
  3855. Params.FileMask = FORMAT(L"*-%s.*", (FormatDateTime(L"yyyymmdd-hhnnss", Now())));
  3856. Result = DoMoveFile(FileName, File, &Params);
  3857. if (Result && (OperationProgress != NULL) && (OperationProgress->Operation == foDelete))
  3858. {
  3859. OperationProgress->Succeeded();
  3860. }
  3861. }
  3862. return Result;
  3863. }
  3864. //---------------------------------------------------------------------------
  3865. bool __fastcall TTerminal::TryStartOperationWithFile(
  3866. const UnicodeString & FileName, TFileOperation Operation1, TFileOperation Operation2)
  3867. {
  3868. bool Result = true;
  3869. if ((OperationProgress != NULL) &&
  3870. ((OperationProgress->Operation == Operation1) ||
  3871. ((Operation2 != foNone) && (OperationProgress->Operation == Operation2))))
  3872. {
  3873. if (OperationProgress->Cancel != csContinue)
  3874. {
  3875. Result = false;
  3876. }
  3877. else
  3878. {
  3879. OperationProgress->SetFile(FileName);
  3880. }
  3881. }
  3882. return Result;
  3883. }
  3884. //---------------------------------------------------------------------------
  3885. void __fastcall TTerminal::StartOperationWithFile(
  3886. const UnicodeString & FileName, TFileOperation Operation1, TFileOperation Operation2)
  3887. {
  3888. if (!TryStartOperationWithFile(FileName, Operation1, Operation2))
  3889. {
  3890. Abort();
  3891. }
  3892. }
  3893. //---------------------------------------------------------------------------
  3894. void __fastcall TTerminal::DeleteFile(UnicodeString FileName,
  3895. const TRemoteFile * File, void * AParams)
  3896. {
  3897. if (FileName.IsEmpty() && File)
  3898. {
  3899. FileName = File->FileName;
  3900. }
  3901. StartOperationWithFile(FileName, foDelete);
  3902. int Params = (AParams != NULL) ? *((int*)AParams) : 0;
  3903. bool Recycle =
  3904. FLAGCLEAR(Params, dfForceDelete) &&
  3905. (SessionData->DeleteToRecycleBin != FLAGSET(Params, dfAlternative)) &&
  3906. !SessionData->RecycleBinPath.IsEmpty();
  3907. if (Recycle && !IsRecycledFile(FileName))
  3908. {
  3909. RecycleFile(FileName, File);
  3910. }
  3911. else
  3912. {
  3913. LogEvent(FORMAT(L"Deleting file \"%s\".", (FileName)));
  3914. FileModified(File, FileName, true);
  3915. DoDeleteFile(FileName, File, Params);
  3916. // Forget if file was or was not encrypted and use user preferences, if we ever recreate it.
  3917. FEncryptedFileNames.erase(AbsolutePath(FileName, true));
  3918. ReactOnCommand(fsDeleteFile);
  3919. }
  3920. }
  3921. //---------------------------------------------------------------------------
  3922. void __fastcall TTerminal::DoDeleteFile(const UnicodeString FileName,
  3923. const TRemoteFile * File, int Params)
  3924. {
  3925. TRetryOperationLoop RetryLoop(this);
  3926. do
  3927. {
  3928. TRmSessionAction Action(ActionLog, AbsolutePath(FileName, true));
  3929. try
  3930. {
  3931. DebugAssert(FFileSystem);
  3932. // 'File' parameter: SFTPFileSystem needs to know if file is file or directory
  3933. FFileSystem->DeleteFile(FileName, File, Params, Action);
  3934. if ((OperationProgress != NULL) && (OperationProgress->Operation == foDelete))
  3935. {
  3936. OperationProgress->Succeeded();
  3937. }
  3938. }
  3939. catch(Exception & E)
  3940. {
  3941. RetryLoop.Error(E, Action, FMTLOAD(DELETE_FILE_ERROR, (FileName)));
  3942. }
  3943. }
  3944. while (RetryLoop.Retry());
  3945. }
  3946. //---------------------------------------------------------------------------
  3947. bool __fastcall TTerminal::DeleteFiles(TStrings * FilesToDelete, int Params)
  3948. {
  3949. TValueRestorer<bool> UseBusyCursorRestorer(FUseBusyCursor);
  3950. FUseBusyCursor = false;
  3951. // TODO: avoid resolving symlinks while reading subdirectories.
  3952. // Resolving does not work anyway for relative symlinks in subdirectories
  3953. // (at least for SFTP).
  3954. return ProcessFiles(FilesToDelete, foDelete, DeleteFile, &Params);
  3955. }
  3956. //---------------------------------------------------------------------------
  3957. void __fastcall TTerminal::DeleteLocalFile(UnicodeString FileName,
  3958. const TRemoteFile * /*File*/, void * Params)
  3959. {
  3960. StartOperationWithFile(FileName, foDelete);
  3961. int Deleted;
  3962. if (OnDeleteLocalFile == NULL)
  3963. {
  3964. Deleted = RecursiveDeleteFileChecked(FileName, false);
  3965. }
  3966. else
  3967. {
  3968. OnDeleteLocalFile(FileName, FLAGSET(*((int*)Params), dfAlternative), Deleted);
  3969. }
  3970. if (DebugAlwaysTrue((OperationProgress != NULL) && (OperationProgress->Operation == foDelete)))
  3971. {
  3972. OperationProgress->Succeeded(Deleted);
  3973. }
  3974. }
  3975. //---------------------------------------------------------------------------
  3976. bool __fastcall TTerminal::DeleteLocalFiles(TStrings * FileList, int Params)
  3977. {
  3978. return ProcessFiles(FileList, foDelete, DeleteLocalFile, &Params, osLocal);
  3979. }
  3980. //---------------------------------------------------------------------------
  3981. void __fastcall TTerminal::CustomCommandOnFile(UnicodeString FileName,
  3982. const TRemoteFile * File, void * AParams)
  3983. {
  3984. TCustomCommandParams * Params = ((TCustomCommandParams *)AParams);
  3985. if (FileName.IsEmpty() && File)
  3986. {
  3987. FileName = File->FileName;
  3988. }
  3989. StartOperationWithFile(FileName, foCustomCommand);
  3990. LogEvent(FORMAT(L"Executing custom command \"%s\" (%d) on file \"%s\".",
  3991. (Params->Command, Params->Params, FileName)));
  3992. FileModified(File, FileName);
  3993. DoCustomCommandOnFile(FileName, File, Params->Command, Params->Params,
  3994. Params->OutputEvent);
  3995. ReactOnCommand(fsAnyCommand);
  3996. }
  3997. //---------------------------------------------------------------------------
  3998. void __fastcall TTerminal::DoCustomCommandOnFile(UnicodeString FileName,
  3999. const TRemoteFile * File, UnicodeString Command, int Params,
  4000. TCaptureOutputEvent OutputEvent)
  4001. {
  4002. TRetryOperationLoop RetryLoop(this);
  4003. do
  4004. {
  4005. try
  4006. {
  4007. if (IsCapable[fcAnyCommand])
  4008. {
  4009. DebugAssert(FFileSystem);
  4010. DebugAssert(fcShellAnyCommand);
  4011. FFileSystem->CustomCommandOnFile(FileName, File, Command, Params, OutputEvent);
  4012. }
  4013. else
  4014. {
  4015. DebugAssert(CommandSessionOpened);
  4016. DebugAssert(FCommandSession->FSProtocol == cfsSCP);
  4017. LogEvent(L"Executing custom command on command session.");
  4018. if (FCommandSession->CurrentDirectory != CurrentDirectory)
  4019. {
  4020. FCommandSession->CurrentDirectory = CurrentDirectory;
  4021. // We are likely in transaction, so ReadCurrentDirectory won't get called
  4022. // until transaction ends. But we need to know CurrentDirectory to
  4023. // expand !/ pattern.
  4024. // Doing this only, when current directory of the main and secondary shell differs,
  4025. // what would be the case before the first file in transaction.
  4026. // Otherwise we would be reading pwd before every time as the
  4027. // CustomCommandOnFile on its own sets FReadCurrentDirectoryPending
  4028. if (FCommandSession->FReadCurrentDirectoryPending)
  4029. {
  4030. FCommandSession->ReadCurrentDirectory();
  4031. }
  4032. }
  4033. FCommandSession->FFileSystem->CustomCommandOnFile(FileName, File, Command,
  4034. Params, OutputEvent);
  4035. }
  4036. }
  4037. catch(Exception & E)
  4038. {
  4039. RetryLoop.Error(E, FMTLOAD(CUSTOM_COMMAND_ERROR, (Command, FileName)));
  4040. }
  4041. }
  4042. while (RetryLoop.Retry());
  4043. }
  4044. //---------------------------------------------------------------------------
  4045. void __fastcall TTerminal::CustomCommandOnFiles(UnicodeString Command,
  4046. int Params, TStrings * Files, TCaptureOutputEvent OutputEvent)
  4047. {
  4048. if (!TRemoteCustomCommand().IsFileListCommand(Command))
  4049. {
  4050. TCustomCommandParams AParams;
  4051. AParams.Command = Command;
  4052. AParams.Params = Params;
  4053. AParams.OutputEvent = OutputEvent;
  4054. ProcessFiles(Files, foCustomCommand, CustomCommandOnFile, &AParams);
  4055. }
  4056. else
  4057. {
  4058. UnicodeString FileList;
  4059. for (int i = 0; i < Files->Count; i++)
  4060. {
  4061. TRemoteFile * File = static_cast<TRemoteFile *>(Files->Objects[i]);
  4062. bool Dir = File->IsDirectory && CanRecurseToDirectory(File);
  4063. if (!Dir || FLAGSET(Params, ccApplyToDirectories))
  4064. {
  4065. if (!FileList.IsEmpty())
  4066. {
  4067. FileList += L" ";
  4068. }
  4069. FileList += L"\"" + ShellDelimitStr(Files->Strings[i], L'"') + L"\"";
  4070. }
  4071. }
  4072. TCustomCommandData Data(this);
  4073. UnicodeString Cmd =
  4074. TRemoteCustomCommand(Data, CurrentDirectory, L"", FileList).
  4075. Complete(Command, true);
  4076. if (!DoOnCustomCommand(Cmd))
  4077. {
  4078. DoAnyCommand(Cmd, OutputEvent, NULL);
  4079. }
  4080. }
  4081. }
  4082. //---------------------------------------------------------------------------
  4083. bool __fastcall TTerminal::DoOnCustomCommand(const UnicodeString & Command)
  4084. {
  4085. bool Result = false;
  4086. if (FOnCustomCommand != NULL)
  4087. {
  4088. FOnCustomCommand(this, Command, Result);
  4089. }
  4090. return Result;
  4091. }
  4092. //---------------------------------------------------------------------------
  4093. void __fastcall TTerminal::ChangeFileProperties(UnicodeString FileName,
  4094. const TRemoteFile * File, /*const TRemoteProperties*/ void * Properties)
  4095. {
  4096. TRemoteProperties * RProperties = (TRemoteProperties *)Properties;
  4097. DebugAssert(RProperties && !RProperties->Valid.Empty());
  4098. if (FileName.IsEmpty() && File)
  4099. {
  4100. FileName = File->FileName;
  4101. }
  4102. StartOperationWithFile(FileName, foSetProperties);
  4103. if (Log->Logging)
  4104. {
  4105. LogEvent(FORMAT(L"Changing properties of \"%s\" (%s)",
  4106. (FileName, BooleanToEngStr(RProperties->Recursive))));
  4107. if (RProperties->Valid.Contains(vpRights))
  4108. {
  4109. LogEvent(FORMAT(L" - mode: \"%s\"", (RProperties->Rights.ModeStr)));
  4110. }
  4111. if (RProperties->Valid.Contains(vpGroup))
  4112. {
  4113. LogEvent(FORMAT(L" - group: %s", (RProperties->Group.LogText)));
  4114. }
  4115. if (RProperties->Valid.Contains(vpOwner))
  4116. {
  4117. LogEvent(FORMAT(L" - owner: %s", (RProperties->Owner.LogText)));
  4118. }
  4119. if (RProperties->Valid.Contains(vpModification))
  4120. {
  4121. LogEvent(FORMAT(L" - modification: \"%s\"",
  4122. (FormatDateTime(L"dddddd tt",
  4123. UnixToDateTime(RProperties->Modification, SessionData->DSTMode)))));
  4124. }
  4125. if (RProperties->Valid.Contains(vpLastAccess))
  4126. {
  4127. LogEvent(FORMAT(L" - last access: \"%s\"",
  4128. (FormatDateTime(L"dddddd tt",
  4129. UnixToDateTime(RProperties->LastAccess, SessionData->DSTMode)))));
  4130. }
  4131. }
  4132. FileModified(File, FileName);
  4133. DoChangeFileProperties(FileName, File, RProperties);
  4134. ReactOnCommand(fsChangeProperties);
  4135. }
  4136. //---------------------------------------------------------------------------
  4137. void __fastcall TTerminal::DoChangeFileProperties(const UnicodeString FileName,
  4138. const TRemoteFile * File, const TRemoteProperties * Properties)
  4139. {
  4140. TRetryOperationLoop RetryLoop(this);
  4141. do
  4142. {
  4143. TChmodSessionAction Action(ActionLog, AbsolutePath(FileName, true));
  4144. try
  4145. {
  4146. DebugAssert(FFileSystem);
  4147. FFileSystem->ChangeFileProperties(FileName, File, Properties, Action);
  4148. }
  4149. catch(Exception & E)
  4150. {
  4151. RetryLoop.Error(E, Action, FMTLOAD(CHANGE_PROPERTIES_ERROR, (FileName)));
  4152. }
  4153. }
  4154. while (RetryLoop.Retry());
  4155. }
  4156. //---------------------------------------------------------------------------
  4157. void __fastcall TTerminal::ChangeFilesProperties(TStrings * FileList,
  4158. const TRemoteProperties * Properties)
  4159. {
  4160. TValueRestorer<bool> UseBusyCursorRestorer(FUseBusyCursor);
  4161. FUseBusyCursor = false;
  4162. AnnounceFileListOperation();
  4163. ProcessFiles(FileList, foSetProperties, ChangeFileProperties, (void *)Properties);
  4164. }
  4165. //---------------------------------------------------------------------------
  4166. bool __fastcall TTerminal::LoadFilesProperties(TStrings * FileList)
  4167. {
  4168. // see comment in TSFTPFileSystem::IsCapable
  4169. bool Result =
  4170. IsCapable[fcLoadingAdditionalProperties] &&
  4171. FFileSystem->LoadFilesProperties(FileList);
  4172. if (Result && SessionData->CacheDirectories &&
  4173. (FileList->Count > 0) &&
  4174. (dynamic_cast<TRemoteFile *>(FileList->Objects[0])->Directory == FFiles))
  4175. {
  4176. AddCachedFileList(FFiles);
  4177. }
  4178. return Result;
  4179. }
  4180. //---------------------------------------------------------------------------
  4181. void __fastcall TTerminal::DoCalculateFileSize(UnicodeString FileName,
  4182. const TRemoteFile * File, void * Param)
  4183. {
  4184. // This is called for top-level entries only
  4185. TCalculateSizeParams * AParams = static_cast<TCalculateSizeParams*>(Param);
  4186. if (AParams->Stats->FoundFiles != NULL)
  4187. {
  4188. UnicodeString DirPath = UnixExtractFilePath(UnixExcludeTrailingBackslash(File->FullFileName));
  4189. if ((DirPath != AParams->LastDirPath) ||
  4190. (AParams->Files == NULL))
  4191. {
  4192. AParams->Files = new TCollectedFileList();
  4193. AParams->LastDirPath = DirPath;
  4194. AParams->Stats->FoundFiles->AddObject(AParams->LastDirPath, AParams->Files);
  4195. }
  4196. }
  4197. __int64 PrevSize = AParams->Size;
  4198. CalculateFileSize(FileName, File, Param);
  4199. if (AParams->Stats->CalculatedSizes != NULL)
  4200. {
  4201. __int64 Size = AParams->Size - PrevSize;
  4202. AParams->Stats->CalculatedSizes->push_back(Size);
  4203. }
  4204. }
  4205. //---------------------------------------------------------------------------
  4206. void __fastcall TTerminal::CalculateFileSize(UnicodeString FileName,
  4207. const TRemoteFile * File, /*TCalculateSizeParams*/ void * Param)
  4208. {
  4209. DebugAssert(Param);
  4210. DebugAssert(File);
  4211. TCalculateSizeParams * AParams = static_cast<TCalculateSizeParams*>(Param);
  4212. if (FileName.IsEmpty())
  4213. {
  4214. FileName = File->FileName;
  4215. }
  4216. if (!TryStartOperationWithFile(FileName, foCalculateSize))
  4217. {
  4218. AParams->Result = false;
  4219. // Combined with csIgnoreErrors, this will not abort completelly, but we get called again
  4220. // with next sibling of our parent directory (and we get again to this branch, throwing again)
  4221. Abort();
  4222. }
  4223. if ((AParams->CopyParam == NULL) ||
  4224. DoAllowRemoteFileTransfer(File, AParams->CopyParam, FLAGSET(AParams->Params, csDisallowTemporaryTransferFiles)))
  4225. {
  4226. int CollectionIndex = -1;
  4227. if (AParams->Files != NULL)
  4228. {
  4229. UnicodeString FullFileName = UnixExcludeTrailingBackslash(File->FullFileName);
  4230. CollectionIndex = AParams->Files->Add(FullFileName, File->Duplicate(), File->IsDirectory);
  4231. }
  4232. if (File->IsDirectory)
  4233. {
  4234. if (CanRecurseToDirectory(File))
  4235. {
  4236. if (!AParams->AllowDirs)
  4237. {
  4238. AParams->Result = false;
  4239. }
  4240. else if (FLAGSET(AParams->Params, csStopOnFirstFile) && (AParams->Stats->Files > 0))
  4241. {
  4242. // do not waste time recursing into a folder, if we already found some files
  4243. }
  4244. else
  4245. {
  4246. if (FLAGCLEAR(AParams->Params, csStopOnFirstFile))
  4247. {
  4248. LogEvent(FORMAT(L"Getting size of directory \"%s\"", (FileName)));
  4249. }
  4250. // pass in full path so we get it back in file list for AllowTransfer() exclusion
  4251. if (!DoCalculateDirectorySize(File->FullFileName, AParams))
  4252. {
  4253. if (CollectionIndex >= 0)
  4254. {
  4255. AParams->Files->DidNotRecurse(CollectionIndex);
  4256. }
  4257. }
  4258. }
  4259. }
  4260. AParams->Stats->Directories++;
  4261. }
  4262. else
  4263. {
  4264. AParams->Size += File->Resolve()->Size;
  4265. AParams->Stats->Files++;
  4266. }
  4267. if (File->IsSymLink)
  4268. {
  4269. AParams->Stats->SymLinks++;
  4270. }
  4271. }
  4272. }
  4273. //---------------------------------------------------------------------------
  4274. bool __fastcall TTerminal::DoCalculateDirectorySize(const UnicodeString & FileName, TCalculateSizeParams * Params)
  4275. {
  4276. bool Result = false;
  4277. if (FLAGSET(Params->Params, csStopOnFirstFile) && (Configuration->ActualLogProtocol >= 1))
  4278. {
  4279. LogEvent(FORMAT(L"Checking if remote directory \"%s\" is empty", (FileName)));
  4280. }
  4281. TRetryOperationLoop RetryLoop(this);
  4282. do
  4283. {
  4284. try
  4285. {
  4286. ProcessDirectory(FileName, CalculateFileSize, Params);
  4287. Result = true;
  4288. }
  4289. catch(Exception & E)
  4290. {
  4291. // We can probably replace the csIgnoreErrors with IgnoreErrors argument of the ProcessDirectory
  4292. if (!Active || ((Params->Params & csIgnoreErrors) == 0))
  4293. {
  4294. RetryLoop.Error(E, FMTLOAD(CALCULATE_SIZE_ERROR, (FileName)));
  4295. }
  4296. }
  4297. }
  4298. while (RetryLoop.Retry());
  4299. if (Configuration->ActualLogProtocol >= 1)
  4300. {
  4301. if (Params->Stats->Files == 0)
  4302. {
  4303. LogEvent(FORMAT(L"Remote directory \"%s\" is empty", (FileName)));
  4304. }
  4305. else
  4306. {
  4307. LogEvent(FORMAT(L"Remote directory \"%s\" is not empty", (FileName)));
  4308. }
  4309. }
  4310. return Result;
  4311. }
  4312. //---------------------------------------------------------------------------
  4313. bool __fastcall TTerminal::CalculateFilesSize(TStrings * FileList,
  4314. __int64 & Size, int Params, const TCopyParamType * CopyParam,
  4315. bool AllowDirs, TCalculateSizeStats & Stats)
  4316. {
  4317. // With FTP protocol, we may use DSIZ command from
  4318. // draft-peterson-streamlined-ftp-command-extensions-10
  4319. // Implemented by Serv-U FTP.
  4320. TValueRestorer<bool> UseBusyCursorRestorer(FUseBusyCursor);
  4321. FUseBusyCursor = false;
  4322. TCalculateSizeParams Param;
  4323. Param.Params = Params;
  4324. Param.CopyParam = CopyParam;
  4325. Param.Stats = &Stats;
  4326. Param.AllowDirs = AllowDirs;
  4327. ProcessFiles(FileList, foCalculateSize, DoCalculateFileSize, &Param);
  4328. Size = Param.Size;
  4329. if (Configuration->ActualLogProtocol >= 1)
  4330. {
  4331. LogEvent(FORMAT(L"Size of %d remote files/folders calculated as %s", (FileList->Count, IntToStr(Size))));
  4332. }
  4333. return Param.Result;
  4334. }
  4335. //---------------------------------------------------------------------------
  4336. void __fastcall TTerminal::CalculateFilesChecksum(const UnicodeString & Alg,
  4337. TStrings * FileList, TStrings * Checksums,
  4338. TCalculatedChecksumEvent OnCalculatedChecksum)
  4339. {
  4340. FFileSystem->CalculateFilesChecksum(Alg, FileList, Checksums, OnCalculatedChecksum);
  4341. }
  4342. //---------------------------------------------------------------------------
  4343. void __fastcall TTerminal::RenameFile(const TRemoteFile * File,
  4344. const UnicodeString NewName, bool CheckExistence)
  4345. {
  4346. DebugAssert(File && File->Directory == FFiles);
  4347. bool Proceed = true;
  4348. // if filename doesn't contain path, we check for existence of file
  4349. if ((File->FileName != NewName) && CheckExistence &&
  4350. Configuration->ConfirmOverwriting &&
  4351. UnixSamePath(CurrentDirectory, FFiles->Directory))
  4352. {
  4353. TRemoteFile * DuplicateFile = FFiles->FindFile(NewName);
  4354. if (DuplicateFile)
  4355. {
  4356. UnicodeString QuestionFmt;
  4357. if (DuplicateFile->IsDirectory)
  4358. {
  4359. QuestionFmt = LoadStr(DIRECTORY_OVERWRITE);
  4360. }
  4361. else
  4362. {
  4363. QuestionFmt = LoadStr(FILE_OVERWRITE);
  4364. }
  4365. TQueryParams Params(qpNeverAskAgainCheck);
  4366. UnicodeString Question = MainInstructions(FORMAT(QuestionFmt, (NewName)));
  4367. unsigned int Result = QueryUser(Question, NULL,
  4368. qaYes | qaNo, &Params);
  4369. if (Result == qaNeverAskAgain)
  4370. {
  4371. Proceed = true;
  4372. Configuration->ConfirmOverwriting = false;
  4373. }
  4374. else
  4375. {
  4376. Proceed = (Result == qaYes);
  4377. }
  4378. }
  4379. }
  4380. if (Proceed)
  4381. {
  4382. FileModified(File, File->FileName);
  4383. LogEvent(FORMAT(L"Renaming file \"%s\" to \"%s\".", (File->FileName, NewName)));
  4384. DoRenameFile(File->FileName, File, NewName, false);
  4385. ReactOnCommand(fsRenameFile);
  4386. }
  4387. }
  4388. //---------------------------------------------------------------------------
  4389. bool __fastcall TTerminal::DoRenameFile(const UnicodeString FileName, const TRemoteFile * File,
  4390. const UnicodeString NewName, bool Move)
  4391. {
  4392. TRetryOperationLoop RetryLoop(this);
  4393. do
  4394. {
  4395. TMvSessionAction Action(ActionLog, AbsolutePath(FileName, true), AbsolutePath(NewName, true));
  4396. try
  4397. {
  4398. DebugAssert(FFileSystem);
  4399. FFileSystem->RenameFile(FileName, File, NewName);
  4400. }
  4401. catch(Exception & E)
  4402. {
  4403. UnicodeString Message = FMTLOAD(Move ? MOVE_FILE_ERROR : RENAME_FILE_ERROR, (FileName, NewName));
  4404. RetryLoop.Error(E, Action, Message);
  4405. }
  4406. }
  4407. while (RetryLoop.Retry());
  4408. return RetryLoop.Succeeded();
  4409. }
  4410. //---------------------------------------------------------------------------
  4411. bool __fastcall TTerminal::DoMoveFile(const UnicodeString & FileName, const TRemoteFile * File, /*const TMoveFileParams*/ void * Param)
  4412. {
  4413. StartOperationWithFile(FileName, foRemoteMove, foDelete);
  4414. DebugAssert(Param != NULL);
  4415. const TMoveFileParams & Params = *static_cast<const TMoveFileParams*>(Param);
  4416. UnicodeString NewName = UnixIncludeTrailingBackslash(Params.Target) +
  4417. MaskFileName(UnixExtractFileName(FileName), Params.FileMask);
  4418. LogEvent(FORMAT(L"Moving file \"%s\" to \"%s\".", (FileName, NewName)));
  4419. FileModified(File, FileName);
  4420. bool Result = DoRenameFile(FileName, File, NewName, true);
  4421. if (Result)
  4422. {
  4423. ReactOnCommand(fsMoveFile);
  4424. }
  4425. return Result;
  4426. }
  4427. //---------------------------------------------------------------------------
  4428. void __fastcall TTerminal::MoveFile(const UnicodeString FileName, const TRemoteFile * File, /*const TMoveFileParams*/ void * Param)
  4429. {
  4430. DoMoveFile(FileName, File, Param);
  4431. }
  4432. //---------------------------------------------------------------------------
  4433. bool __fastcall TTerminal::MoveFiles(TStrings * FileList, const UnicodeString Target,
  4434. const UnicodeString FileMask)
  4435. {
  4436. TMoveFileParams Params;
  4437. Params.Target = Target;
  4438. Params.FileMask = FileMask;
  4439. bool Result;
  4440. BeginTransaction();
  4441. try
  4442. {
  4443. Result = ProcessFiles(FileList, foRemoteMove, MoveFile, &Params);
  4444. }
  4445. __finally
  4446. {
  4447. if (Active)
  4448. {
  4449. // Only after the move, as with encryption, the folders can be read and cached before the move
  4450. // (when determining if the target exists and is encrypted)
  4451. DirectoryModified(Target, true);
  4452. UnicodeString WithTrailing = UnixIncludeTrailingBackslash(CurrentDirectory);
  4453. bool PossiblyMoved = false;
  4454. // check if we was moving current directory.
  4455. // this is just optimization to avoid checking existence of current
  4456. // directory after each move operation.
  4457. for (int Index = 0; !PossiblyMoved && (Index < FileList->Count); Index++)
  4458. {
  4459. const TRemoteFile * File =
  4460. dynamic_cast<const TRemoteFile *>(FileList->Objects[Index]);
  4461. // File can be NULL, and filename may not be full path,
  4462. // but currently this is the only way we can move (at least in GUI)
  4463. // current directory
  4464. if ((File != NULL) &&
  4465. File->IsDirectory &&
  4466. ((CurrentDirectory.SubString(1, FileList->Strings[Index].Length()) == FileList->Strings[Index]) &&
  4467. ((FileList->Strings[Index].Length() == CurrentDirectory.Length()) ||
  4468. (CurrentDirectory[FileList->Strings[Index].Length() + 1] == L'/'))))
  4469. {
  4470. PossiblyMoved = true;
  4471. }
  4472. }
  4473. if (PossiblyMoved && !FileExists(CurrentDirectory))
  4474. {
  4475. UnicodeString NearestExisting = CurrentDirectory;
  4476. do
  4477. {
  4478. NearestExisting = UnixExtractFileDir(NearestExisting);
  4479. }
  4480. while (!IsUnixRootPath(NearestExisting) && !FileExists(NearestExisting));
  4481. ChangeDirectory(NearestExisting);
  4482. }
  4483. }
  4484. EndTransaction();
  4485. }
  4486. return Result;
  4487. }
  4488. //---------------------------------------------------------------------------
  4489. void __fastcall TTerminal::DoCopyFile(const UnicodeString FileName, const TRemoteFile * File,
  4490. const UnicodeString NewName)
  4491. {
  4492. TRetryOperationLoop RetryLoop(this);
  4493. do
  4494. {
  4495. TCpSessionAction Action(ActionLog, AbsolutePath(FileName, true), AbsolutePath(NewName, true));
  4496. try
  4497. {
  4498. DebugAssert(FFileSystem);
  4499. if (IsCapable[fcRemoteCopy])
  4500. {
  4501. FFileSystem->CopyFile(FileName, File, NewName);
  4502. }
  4503. else
  4504. {
  4505. DebugAssert(CommandSessionOpened);
  4506. DebugAssert(FCommandSession->FSProtocol == cfsSCP);
  4507. LogEvent(L"Copying file on command session.");
  4508. FCommandSession->CurrentDirectory = CurrentDirectory;
  4509. FCommandSession->FFileSystem->CopyFile(FileName, File, NewName);
  4510. }
  4511. }
  4512. catch(Exception & E)
  4513. {
  4514. RetryLoop.Error(E, Action, FMTLOAD(COPY_FILE_ERROR, (FileName, NewName)));
  4515. }
  4516. }
  4517. while (RetryLoop.Retry());
  4518. }
  4519. //---------------------------------------------------------------------------
  4520. void __fastcall TTerminal::CopyFile(const UnicodeString FileName,
  4521. const TRemoteFile * File, /*const TMoveFileParams*/ void * Param)
  4522. {
  4523. StartOperationWithFile(FileName, foRemoteCopy);
  4524. DebugAssert(Param != NULL);
  4525. const TMoveFileParams & Params = *static_cast<const TMoveFileParams*>(Param);
  4526. UnicodeString NewName = UnixIncludeTrailingBackslash(Params.Target) +
  4527. MaskFileName(UnixExtractFileName(FileName), Params.FileMask);
  4528. LogEvent(FORMAT(L"Copying file \"%s\" to \"%s\".", (FileName, NewName)));
  4529. DoCopyFile(FileName, File, NewName);
  4530. ReactOnCommand(fsCopyFile);
  4531. }
  4532. //---------------------------------------------------------------------------
  4533. bool __fastcall TTerminal::CopyFiles(TStrings * FileList, const UnicodeString Target,
  4534. const UnicodeString FileMask)
  4535. {
  4536. TMoveFileParams Params;
  4537. Params.Target = Target;
  4538. Params.FileMask = FileMask;
  4539. DirectoryModified(Target, true);
  4540. return ProcessFiles(FileList, foRemoteCopy, CopyFile, &Params);
  4541. }
  4542. //---------------------------------------------------------------------------
  4543. void __fastcall TTerminal::CreateDirectory(const UnicodeString & DirName, const TRemoteProperties * Properties)
  4544. {
  4545. DebugAssert(FFileSystem);
  4546. DebugAssert(Properties != NULL);
  4547. EnsureNonExistence(DirName);
  4548. FileModified(NULL, DirName);
  4549. LogEvent(FORMAT(L"Creating directory \"%s\".", (DirName)));
  4550. bool Encrypt = Properties->Valid.Contains(vpEncrypt) && Properties->Encrypt;
  4551. DoCreateDirectory(DirName, Encrypt);
  4552. TValidProperties RemainingPropeties = Properties->Valid - (TValidProperties() << vpEncrypt);
  4553. if (!RemainingPropeties.Empty() &&
  4554. (IsCapable[fcModeChanging] || IsCapable[fcOwnerChanging] || IsCapable[fcGroupChanging]))
  4555. {
  4556. DoChangeFileProperties(DirName, NULL, Properties);
  4557. }
  4558. ReactOnCommand(fsCreateDirectory);
  4559. }
  4560. //---------------------------------------------------------------------------
  4561. void __fastcall TTerminal::DoCreateDirectory(const UnicodeString & DirName, bool Encrypt)
  4562. {
  4563. TRetryOperationLoop RetryLoop(this);
  4564. do
  4565. {
  4566. TMkdirSessionAction Action(ActionLog, AbsolutePath(DirName, true));
  4567. try
  4568. {
  4569. DebugAssert(FFileSystem);
  4570. FFileSystem->CreateDirectory(DirName, Encrypt);
  4571. }
  4572. catch(Exception & E)
  4573. {
  4574. RetryLoop.Error(E, Action, FMTLOAD(CREATE_DIR_ERROR, (DirName)));
  4575. }
  4576. }
  4577. while (RetryLoop.Retry());
  4578. }
  4579. //---------------------------------------------------------------------------
  4580. void __fastcall TTerminal::CreateLink(const UnicodeString FileName,
  4581. const UnicodeString PointTo, bool Symbolic)
  4582. {
  4583. DebugAssert(FFileSystem);
  4584. EnsureNonExistence(FileName);
  4585. if (SessionData->CacheDirectories)
  4586. {
  4587. DirectoryModified(CurrentDirectory, false);
  4588. }
  4589. LogEvent(FORMAT(L"Creating link \"%s\" to \"%s\" (symbolic: %s).",
  4590. (FileName, PointTo, BooleanToEngStr(Symbolic))));
  4591. DoCreateLink(FileName, PointTo, Symbolic);
  4592. ReactOnCommand(fsCreateDirectory);
  4593. }
  4594. //---------------------------------------------------------------------------
  4595. void __fastcall TTerminal::DoCreateLink(const UnicodeString FileName,
  4596. const UnicodeString PointTo, bool Symbolic)
  4597. {
  4598. TRetryOperationLoop RetryLoop(this);
  4599. do
  4600. {
  4601. try
  4602. {
  4603. DebugAssert(FFileSystem);
  4604. FFileSystem->CreateLink(FileName, PointTo, Symbolic);
  4605. }
  4606. catch(Exception & E)
  4607. {
  4608. RetryLoop.Error(E, FMTLOAD(CREATE_LINK_ERROR, (FileName)));
  4609. }
  4610. }
  4611. while (RetryLoop.Retry());
  4612. }
  4613. //---------------------------------------------------------------------------
  4614. void __fastcall TTerminal::HomeDirectory()
  4615. {
  4616. DebugAssert(FFileSystem);
  4617. try
  4618. {
  4619. LogEvent(L"Changing directory to home directory.");
  4620. FFileSystem->HomeDirectory();
  4621. ReactOnCommand(fsHomeDirectory);
  4622. }
  4623. catch (Exception &E)
  4624. {
  4625. CommandError(&E, LoadStr(CHANGE_HOMEDIR_ERROR));
  4626. }
  4627. }
  4628. //---------------------------------------------------------------------------
  4629. UnicodeString __fastcall TTerminal::GetHomeDirectory()
  4630. {
  4631. return FFileSystem->GetHomeDirectory();
  4632. }
  4633. //---------------------------------------------------------------------------
  4634. void __fastcall TTerminal::ChangeDirectory(const UnicodeString Directory)
  4635. {
  4636. DebugAssert(FFileSystem);
  4637. try
  4638. {
  4639. UnicodeString CachedDirectory;
  4640. DebugAssert(!SessionData->CacheDirectoryChanges || (FDirectoryChangesCache != NULL));
  4641. // never use directory change cache during startup, this ensures, we never
  4642. // end-up initially in non-existing directory
  4643. if ((Status == ssOpened) &&
  4644. SessionData->CacheDirectoryChanges &&
  4645. FDirectoryChangesCache->GetDirectoryChange(PeekCurrentDirectory(),
  4646. Directory, CachedDirectory))
  4647. {
  4648. LogEvent(FORMAT(L"Cached directory change via \"%s\" to \"%s\".",
  4649. (Directory, CachedDirectory)));
  4650. FFileSystem->CachedChangeDirectory(CachedDirectory);
  4651. }
  4652. else
  4653. {
  4654. LogEvent(FORMAT(L"Changing directory to \"%s\".", (Directory)));
  4655. FFileSystem->ChangeDirectory(Directory);
  4656. }
  4657. FLastDirectoryChange = Directory;
  4658. ReactOnCommand(fsChangeDirectory);
  4659. }
  4660. catch (Exception &E)
  4661. {
  4662. CommandError(&E, FMTLOAD(CHANGE_DIR_ERROR, (Directory)));
  4663. }
  4664. }
  4665. //---------------------------------------------------------------------------
  4666. void __fastcall TTerminal::LookupUsersGroups()
  4667. {
  4668. if (!FUsersGroupsLookedup && (SessionData->LookupUserGroups != asOff) &&
  4669. IsCapable[fcUserGroupListing])
  4670. {
  4671. DebugAssert(FFileSystem);
  4672. try
  4673. {
  4674. FUsersGroupsLookedup = true;
  4675. LogEvent(L"Looking up groups and users.");
  4676. FFileSystem->LookupUsersGroups();
  4677. ReactOnCommand(fsLookupUsersGroups);
  4678. if (Log->Logging)
  4679. {
  4680. FGroups.Log(this, L"groups");
  4681. FMembership.Log(this, L"membership");
  4682. FUsers.Log(this, L"users");
  4683. }
  4684. }
  4685. catch (Exception &E)
  4686. {
  4687. if (!Active || (SessionData->LookupUserGroups == asOn))
  4688. {
  4689. CommandError(&E, LoadStr(LOOKUP_GROUPS_ERROR));
  4690. }
  4691. }
  4692. }
  4693. }
  4694. //---------------------------------------------------------------------------
  4695. bool __fastcall TTerminal::AllowedAnyCommand(const UnicodeString Command)
  4696. {
  4697. return !Command.Trim().IsEmpty();
  4698. }
  4699. //---------------------------------------------------------------------------
  4700. bool __fastcall TTerminal::GetCommandSessionOpened()
  4701. {
  4702. // consider secondary terminal open in "ready" state only
  4703. // so we never do keepalives on it until it is completely initialized
  4704. return (FCommandSession != NULL) &&
  4705. (FCommandSession->Status == ssOpened);
  4706. }
  4707. //---------------------------------------------------------------------------
  4708. TTerminal * __fastcall TTerminal::CreateSecondarySession(const UnicodeString & Name, TSessionData * SessionData)
  4709. {
  4710. std::unique_ptr<TTerminal> Result(new TSecondaryTerminal(this, SessionData, Configuration, Name));
  4711. Result->AutoReadDirectory = false;
  4712. Result->FExceptionOnFail = FExceptionOnFail;
  4713. Result->OnQueryUser = OnQueryUser;
  4714. Result->OnPromptUser = OnPromptUser;
  4715. Result->OnShowExtendedException = OnShowExtendedException;
  4716. Result->OnProgress = OnProgress;
  4717. Result->OnFinished = OnFinished;
  4718. Result->OnInformation = OnInformation;
  4719. Result->OnCustomCommand = OnCustomCommand;
  4720. // do not copy OnDisplayBanner to avoid it being displayed
  4721. return Result.release();
  4722. }
  4723. //---------------------------------------------------------------------------
  4724. void __fastcall TTerminal::FillSessionDataForCode(TSessionData * Data)
  4725. {
  4726. const TSessionInfo & SessionInfo = GetSessionInfo();
  4727. if (!SessionInfo.HostKeyFingerprintSHA256.IsEmpty())
  4728. {
  4729. Data->HostKey = SessionInfo.HostKeyFingerprintSHA256;
  4730. }
  4731. else if (SessionInfo.CertificateVerifiedManually && DebugAlwaysTrue(!SessionInfo.CertificateFingerprintSHA256.IsEmpty()))
  4732. {
  4733. Data->HostKey = SessionInfo.CertificateFingerprintSHA256;
  4734. }
  4735. }
  4736. //---------------------------------------------------------------------------
  4737. void __fastcall TTerminal::UpdateSessionCredentials(TSessionData * Data)
  4738. {
  4739. Data->UserName = UserName;
  4740. Data->Password = Password;
  4741. if (!FRememberedPassword.IsEmpty() && (FRememberedPasswordKind == pkPassphrase))
  4742. {
  4743. Data->Passphrase = GetRememberedPassword();
  4744. }
  4745. }
  4746. //---------------------------------------------------------------------------
  4747. TTerminal * __fastcall TTerminal::GetCommandSession()
  4748. {
  4749. if ((FCommandSession != NULL) && !FCommandSession->Active)
  4750. {
  4751. SAFE_DESTROY(FCommandSession);
  4752. }
  4753. if (FCommandSession == NULL)
  4754. {
  4755. // transaction cannot be started yet to allow proper matching transaction
  4756. // levels between main and command session
  4757. DebugAssert(FInTransaction == 0);
  4758. std::unique_ptr<TSessionData> CommandSessionData(SessionData->Clone());
  4759. CommandSessionData->RemoteDirectory = CurrentDirectory;
  4760. CommandSessionData->FSProtocol = fsSCPonly;
  4761. CommandSessionData->ClearAliases = false;
  4762. CommandSessionData->UnsetNationalVars = false;
  4763. CommandSessionData->LookupUserGroups = asOff;
  4764. FCommandSession = CreateSecondarySession(L"Shell", CommandSessionData.get());
  4765. FCommandSession->AutoReadDirectory = false;
  4766. FCommandSession->FExceptionOnFail = FExceptionOnFail;
  4767. FCommandSession->OnQueryUser = OnQueryUser;
  4768. FCommandSession->OnPromptUser = OnPromptUser;
  4769. FCommandSession->OnShowExtendedException = OnShowExtendedException;
  4770. FCommandSession->OnProgress = OnProgress;
  4771. FCommandSession->OnFinished = OnFinished;
  4772. FCommandSession->OnInformation = OnInformation;
  4773. FCommandSession->OnCustomCommand = OnCustomCommand;
  4774. // do not copy OnDisplayBanner to avoid it being displayed
  4775. }
  4776. return FCommandSession;
  4777. }
  4778. //---------------------------------------------------------------------------
  4779. void __fastcall TTerminal::AnyCommand(const UnicodeString Command,
  4780. TCaptureOutputEvent OutputEvent)
  4781. {
  4782. #pragma warn -inl
  4783. class TOutputProxy
  4784. {
  4785. public:
  4786. __fastcall TOutputProxy(TCallSessionAction & Action, TCaptureOutputEvent OutputEvent) :
  4787. FAction(Action),
  4788. FOutputEvent(OutputEvent)
  4789. {
  4790. }
  4791. void __fastcall Output(const UnicodeString & Str, TCaptureOutputType OutputType)
  4792. {
  4793. switch (OutputType)
  4794. {
  4795. case cotOutput:
  4796. FAction.AddOutput(Str, false);
  4797. break;
  4798. case cotError:
  4799. FAction.AddOutput(Str, true);
  4800. break;
  4801. case cotExitCode:
  4802. FAction.ExitCode(StrToInt(Str));
  4803. break;
  4804. }
  4805. if (FOutputEvent != NULL)
  4806. {
  4807. FOutputEvent(Str, OutputType);
  4808. }
  4809. }
  4810. private:
  4811. TCallSessionAction & FAction;
  4812. TCaptureOutputEvent FOutputEvent;
  4813. };
  4814. #pragma warn .inl
  4815. TCallSessionAction Action(ActionLog, Command, CurrentDirectory);
  4816. TOutputProxy ProxyOutputEvent(Action, OutputEvent);
  4817. DoAnyCommand(Command, ProxyOutputEvent.Output, &Action);
  4818. }
  4819. //---------------------------------------------------------------------------
  4820. void __fastcall TTerminal::DoAnyCommand(const UnicodeString Command,
  4821. TCaptureOutputEvent OutputEvent, TCallSessionAction * Action)
  4822. {
  4823. DebugAssert(FFileSystem);
  4824. try
  4825. {
  4826. DirectoryModified(CurrentDirectory, false);
  4827. if (IsCapable[fcAnyCommand])
  4828. {
  4829. LogEvent(L"Executing user defined command.");
  4830. FFileSystem->AnyCommand(Command, OutputEvent);
  4831. }
  4832. else
  4833. {
  4834. DebugAssert(CommandSessionOpened);
  4835. DebugAssert(FCommandSession->FSProtocol == cfsSCP);
  4836. LogEvent(L"Executing user defined command on command session.");
  4837. FCommandSession->CurrentDirectory = CurrentDirectory;
  4838. FCommandSession->FFileSystem->AnyCommand(Command, OutputEvent);
  4839. FCommandSession->FFileSystem->ReadCurrentDirectory();
  4840. // synchronize pwd (by purpose we lose transaction optimization here)
  4841. ChangeDirectory(FCommandSession->CurrentDirectory);
  4842. }
  4843. ReactOnCommand(fsAnyCommand);
  4844. }
  4845. catch (Exception &E)
  4846. {
  4847. if (Action != NULL)
  4848. {
  4849. RollbackAction(*Action, NULL, &E);
  4850. }
  4851. if (ExceptionOnFail || (E.InheritsFrom(__classid(EFatal)))) throw;
  4852. else HandleExtendedException(&E);
  4853. }
  4854. }
  4855. //---------------------------------------------------------------------------
  4856. bool __fastcall TTerminal::DoCreateLocalFile(const UnicodeString FileName,
  4857. TFileOperationProgressType * OperationProgress, HANDLE * AHandle,
  4858. bool NoConfirmation)
  4859. {
  4860. bool Result = true;
  4861. bool Done;
  4862. unsigned int CreateAttr = FILE_ATTRIBUTE_NORMAL;
  4863. do
  4864. {
  4865. *AHandle = CreateFile(ApiPath(FileName).c_str(), GENERIC_WRITE, FILE_SHARE_READ,
  4866. NULL, CREATE_ALWAYS, CreateAttr, 0);
  4867. Done = (*AHandle != INVALID_HANDLE_VALUE);
  4868. if (!Done)
  4869. {
  4870. // save the error, otherwise it gets overwritten by call to FileExists
  4871. int LastError = GetLastError();
  4872. int FileAttr;
  4873. if (::FileExists(ApiPath(FileName)) &&
  4874. (((FileAttr = FileGetAttrFix(ApiPath(FileName))) & (faReadOnly | faHidden)) != 0))
  4875. {
  4876. if (FLAGSET(FileAttr, faReadOnly))
  4877. {
  4878. OperationProgress->LockUserSelections();
  4879. try
  4880. {
  4881. if (OperationProgress->BatchOverwrite == boNone)
  4882. {
  4883. Result = false;
  4884. }
  4885. else if ((OperationProgress->BatchOverwrite != boAll) && !NoConfirmation)
  4886. {
  4887. unsigned int Answer;
  4888. {
  4889. TSuspendFileOperationProgress Suspend(OperationProgress);
  4890. Answer = QueryUser(
  4891. MainInstructions(FMTLOAD(READ_ONLY_OVERWRITE, (FileName))), NULL,
  4892. qaYes | qaNo | qaCancel | qaYesToAll | qaNoToAll, 0);
  4893. }
  4894. switch (Answer) {
  4895. case qaYesToAll: OperationProgress->SetBatchOverwrite(boAll); break;
  4896. case qaCancel: OperationProgress->SetCancel(csCancel); // continue on next case
  4897. case qaNoToAll: OperationProgress->SetBatchOverwrite(boNone);
  4898. case qaNo: Result = false; break;
  4899. }
  4900. }
  4901. }
  4902. __finally
  4903. {
  4904. OperationProgress->UnlockUserSelections();
  4905. }
  4906. }
  4907. else
  4908. {
  4909. DebugAssert(FLAGSET(FileAttr, faHidden));
  4910. Result = true;
  4911. }
  4912. if (Result)
  4913. {
  4914. CreateAttr |=
  4915. FLAGMASK(FLAGSET(FileAttr, faHidden), FILE_ATTRIBUTE_HIDDEN) |
  4916. FLAGMASK(FLAGSET(FileAttr, faReadOnly), FILE_ATTRIBUTE_READONLY);
  4917. FILE_OPERATION_LOOP_BEGIN
  4918. {
  4919. if (FileSetAttr(ApiPath(FileName), FileAttr & ~(faReadOnly | faHidden)) != 0)
  4920. {
  4921. RaiseLastOSError();
  4922. }
  4923. }
  4924. FILE_OPERATION_LOOP_END(FMTLOAD(CANT_SET_ATTRS, (FileName)));
  4925. }
  4926. else
  4927. {
  4928. Done = true;
  4929. }
  4930. }
  4931. else
  4932. {
  4933. RaiseLastOSError(LastError);
  4934. }
  4935. }
  4936. }
  4937. while (!Done);
  4938. return Result;
  4939. }
  4940. //---------------------------------------------------------------------------
  4941. bool __fastcall TTerminal::CreateLocalFile(const UnicodeString FileName,
  4942. TFileOperationProgressType * OperationProgress, HANDLE * AHandle,
  4943. bool NoConfirmation)
  4944. {
  4945. DebugAssert(AHandle);
  4946. bool Result = true;
  4947. FILE_OPERATION_LOOP_BEGIN
  4948. {
  4949. Result = DoCreateLocalFile(FileName, OperationProgress, AHandle, NoConfirmation);
  4950. }
  4951. FILE_OPERATION_LOOP_END(FMTLOAD(CREATE_FILE_ERROR, (FileName)));
  4952. return Result;
  4953. }
  4954. //---------------------------------------------------------------------------
  4955. void __fastcall TTerminal::OpenLocalFile(const UnicodeString FileName,
  4956. unsigned int Access, int * AAttrs, HANDLE * AHandle, __int64 * ACTime,
  4957. __int64 * AMTime, __int64 * AATime, __int64 * ASize,
  4958. bool TryWriteReadOnly)
  4959. {
  4960. int Attrs = 0;
  4961. HANDLE Handle = 0;
  4962. FILE_OPERATION_LOOP_BEGIN
  4963. {
  4964. UnicodeString FileNameApi = ApiPath(FileName);
  4965. Attrs = FileGetAttrFix(FileNameApi);
  4966. if (Attrs < 0)
  4967. {
  4968. RaiseLastOSError();
  4969. }
  4970. }
  4971. FILE_OPERATION_LOOP_END(FMTLOAD(FILE_NOT_EXISTS, (FileName)));
  4972. if (FLAGCLEAR(Attrs, faDirectory) || (AHandle == NULL))
  4973. {
  4974. bool NoHandle = false;
  4975. if (!TryWriteReadOnly && (Access == GENERIC_WRITE) &&
  4976. ((Attrs & faReadOnly) != 0))
  4977. {
  4978. Access = GENERIC_READ;
  4979. NoHandle = true;
  4980. }
  4981. FILE_OPERATION_LOOP_BEGIN
  4982. {
  4983. DWORD Flags = FLAGMASK(FLAGSET(Attrs, faDirectory), FILE_FLAG_BACKUP_SEMANTICS);
  4984. Handle = CreateFile(ApiPath(FileName).c_str(), Access,
  4985. Access == GENERIC_READ ? FILE_SHARE_READ | FILE_SHARE_WRITE : FILE_SHARE_READ,
  4986. NULL, OPEN_EXISTING, Flags, 0);
  4987. if (Handle == INVALID_HANDLE_VALUE)
  4988. {
  4989. Handle = 0;
  4990. RaiseLastOSError();
  4991. }
  4992. }
  4993. FILE_OPERATION_LOOP_END(FMTLOAD(OPENFILE_ERROR, (FileName)));
  4994. try
  4995. {
  4996. if (AATime || AMTime || ACTime)
  4997. {
  4998. FILETIME ATime;
  4999. FILETIME MTime;
  5000. FILETIME CTime;
  5001. // Get last file access and modification time
  5002. FILE_OPERATION_LOOP_BEGIN
  5003. {
  5004. THROWOSIFFALSE(GetFileTime(Handle, &CTime, &ATime, &MTime));
  5005. }
  5006. FILE_OPERATION_LOOP_END(FMTLOAD(CANT_GET_ATTRS, (FileName)));
  5007. if (ACTime)
  5008. {
  5009. *ACTime = ConvertTimestampToUnixSafe(CTime, SessionData->DSTMode);
  5010. }
  5011. if (AATime)
  5012. {
  5013. *AATime = ConvertTimestampToUnixSafe(ATime, SessionData->DSTMode);
  5014. }
  5015. if (AMTime)
  5016. {
  5017. *AMTime = ConvertTimestampToUnix(MTime, SessionData->DSTMode);
  5018. }
  5019. }
  5020. if (ASize)
  5021. {
  5022. // Get file size
  5023. FILE_OPERATION_LOOP_BEGIN
  5024. {
  5025. unsigned long LSize;
  5026. unsigned long HSize;
  5027. LSize = GetFileSize(Handle, &HSize);
  5028. if ((LSize == 0xFFFFFFFF) && (GetLastError() != NO_ERROR)) RaiseLastOSError();
  5029. *ASize = (__int64(HSize) << 32) + LSize;
  5030. }
  5031. FILE_OPERATION_LOOP_END(FMTLOAD(CANT_GET_ATTRS, (FileName)));
  5032. }
  5033. if ((AHandle == NULL) || NoHandle)
  5034. {
  5035. CloseHandle(Handle);
  5036. Handle = NULL;
  5037. }
  5038. }
  5039. catch(...)
  5040. {
  5041. CloseHandle(Handle);
  5042. throw;
  5043. }
  5044. }
  5045. if (AAttrs) *AAttrs = Attrs;
  5046. if (AHandle) *AHandle = Handle;
  5047. }
  5048. //---------------------------------------------------------------------------
  5049. void __fastcall TTerminal::OpenLocalFile(
  5050. const UnicodeString & FileName, unsigned int Access, TLocalFileHandle & Handle, bool TryWriteReadOnly)
  5051. {
  5052. Handle.FileName = FileName;
  5053. OpenLocalFile(
  5054. FileName, Access, &Handle.Attrs, &Handle.Handle, NULL, &Handle.MTime, &Handle.ATime, &Handle.Size,
  5055. TryWriteReadOnly);
  5056. Handle.Modification = UnixToDateTime(Handle.MTime, SessionData->DSTMode);
  5057. Handle.Directory = FLAGSET(Handle.Attrs, faDirectory);
  5058. }
  5059. //---------------------------------------------------------------------------
  5060. bool __fastcall TTerminal::DoAllowLocalFileTransfer(
  5061. const UnicodeString & FileName, const TSearchRecSmart & SearchRec, const TCopyParamType * CopyParam, bool DisallowTemporaryTransferFiles)
  5062. {
  5063. TFileMasks::TParams Params;
  5064. Params.Size = SearchRec.Size;
  5065. Params.Modification = SearchRec.GetLastWriteTime();
  5066. UnicodeString BaseFileName = GetBaseFileName(FileName);
  5067. // Note that for synchronization, we do not need to check "TSynchronizeOptions::MatchesFilter" here as
  5068. // that is checked for top-level entries only and we are never top-level here.
  5069. return
  5070. CopyParam->AllowTransfer(BaseFileName, osLocal, SearchRec.IsDirectory(), Params, SearchRec.IsHidden()) &&
  5071. (!DisallowTemporaryTransferFiles || !FFileSystem->TemporaryTransferFile(FileName)) &&
  5072. (!SearchRec.IsDirectory() || !CopyParam->ExcludeEmptyDirectories ||
  5073. !IsEmptyLocalDirectory(FileName, CopyParam, DisallowTemporaryTransferFiles));
  5074. }
  5075. //---------------------------------------------------------------------------
  5076. bool __fastcall TTerminal::DoAllowRemoteFileTransfer(
  5077. const TRemoteFile * File, const TCopyParamType * CopyParam, bool DisallowTemporaryTransferFiles)
  5078. {
  5079. TFileMasks::TParams MaskParams;
  5080. MaskParams.Size = File->Resolve()->Size;
  5081. MaskParams.Modification = File->Modification;
  5082. UnicodeString FullRemoteFileName = UnixExcludeTrailingBackslash(File->FullFileName);
  5083. UnicodeString BaseFileName = GetBaseFileName(FullRemoteFileName);
  5084. return
  5085. CopyParam->AllowTransfer(BaseFileName, osRemote, File->IsDirectory, MaskParams, File->IsHidden) &&
  5086. (!DisallowTemporaryTransferFiles || !FFileSystem->TemporaryTransferFile(File->FileName)) &&
  5087. (!File->IsDirectory || !CopyParam->ExcludeEmptyDirectories ||
  5088. !IsEmptyRemoteDirectory(File, CopyParam, DisallowTemporaryTransferFiles));
  5089. }
  5090. //---------------------------------------------------------------------------
  5091. bool __fastcall TTerminal::AllowLocalFileTransfer(
  5092. const UnicodeString & FileName, const TSearchRecSmart * SearchRec,
  5093. const TCopyParamType * CopyParam, TFileOperationProgressType * OperationProgress)
  5094. {
  5095. bool Result = true;
  5096. // optimization (though in most uses of the method, the caller actually knows TSearchRec already, so it passes it here
  5097. if (Log->Logging || !CopyParam->AllowAnyTransfer())
  5098. {
  5099. TSearchRecSmart ASearchRec;
  5100. if (SearchRec == NULL)
  5101. {
  5102. if (CopyParam->OnTransferIn != NULL)
  5103. {
  5104. ASearchRec.Clear();
  5105. }
  5106. else
  5107. {
  5108. FILE_OPERATION_LOOP_BEGIN
  5109. {
  5110. if (!FileSearchRec(FileName, ASearchRec))
  5111. {
  5112. RaiseLastOSError();
  5113. }
  5114. }
  5115. FILE_OPERATION_LOOP_END(FMTLOAD(FILE_NOT_EXISTS, (FileName)));
  5116. }
  5117. SearchRec = &ASearchRec;
  5118. }
  5119. if (!DoAllowLocalFileTransfer(FileName, *SearchRec, CopyParam, false))
  5120. {
  5121. LogEvent(FORMAT(L"File \"%s\" excluded from transfer", (FileName)));
  5122. Result = false;
  5123. }
  5124. else if (CopyParam->SkipTransfer(FileName, SearchRec->IsDirectory()))
  5125. {
  5126. OperationProgress->AddSkippedFileSize(SearchRec->Size);
  5127. Result = false;
  5128. }
  5129. if (Result)
  5130. {
  5131. LogFileDetails(FileName, SearchRec->GetLastWriteTime(), SearchRec->Size);
  5132. }
  5133. }
  5134. return Result;
  5135. }
  5136. //---------------------------------------------------------------------------
  5137. void __fastcall TTerminal::MakeLocalFileList(
  5138. const UnicodeString & FileName, const TSearchRecSmart & Rec, void * Param)
  5139. {
  5140. TMakeLocalFileListParams & Params = *static_cast<TMakeLocalFileListParams*>(Param);
  5141. if (Rec.IsDirectory() && Params.Recursive)
  5142. {
  5143. ProcessLocalDirectory(FileName, MakeLocalFileList, &Params);
  5144. }
  5145. if (!Rec.IsDirectory() || Params.IncludeDirs)
  5146. {
  5147. Params.FileList->Add(FileName);
  5148. if (Params.FileTimes != NULL)
  5149. {
  5150. Params.FileTimes->push_back(const_cast<TSearchRecSmart &>(Rec).TimeStamp);
  5151. }
  5152. }
  5153. }
  5154. //---------------------------------------------------------------------------
  5155. void __fastcall TTerminal::CalculateLocalFileSize(
  5156. const UnicodeString & FileName, const TSearchRecSmart & Rec, /*TCalculateSizeParams*/ void * Params)
  5157. {
  5158. TCalculateSizeParams * AParams = static_cast<TCalculateSizeParams*>(Params);
  5159. if (!TryStartOperationWithFile(FileName, foCalculateSize))
  5160. {
  5161. AParams->Result = false;
  5162. }
  5163. else
  5164. {
  5165. try
  5166. {
  5167. if ((AParams->CopyParam == NULL) ||
  5168. DoAllowLocalFileTransfer(FileName, Rec, AParams->CopyParam, false))
  5169. {
  5170. int CollectionIndex = -1;
  5171. if (AParams->Files != NULL)
  5172. {
  5173. UnicodeString FullFileName = ::ExpandFileName(FileName);
  5174. CollectionIndex = AParams->Files->Add(FullFileName, NULL, Rec.IsDirectory());
  5175. }
  5176. if (!Rec.IsDirectory())
  5177. {
  5178. AParams->Size += Rec.Size;
  5179. }
  5180. else
  5181. {
  5182. try
  5183. {
  5184. ProcessLocalDirectory(FileName, CalculateLocalFileSize, Params);
  5185. }
  5186. catch (...)
  5187. {
  5188. if (CollectionIndex >= 0)
  5189. {
  5190. AParams->Files->DidNotRecurse(CollectionIndex);
  5191. }
  5192. }
  5193. }
  5194. }
  5195. }
  5196. catch (...)
  5197. {
  5198. // ignore
  5199. }
  5200. }
  5201. }
  5202. //---------------------------------------------------------------------------
  5203. bool __fastcall TTerminal::CalculateLocalFilesSize(TStrings * FileList,
  5204. __int64 & Size, const TCopyParamType * CopyParam, bool AllowDirs, TStrings * Files,
  5205. TCalculatedSizes * CalculatedSizes)
  5206. {
  5207. bool Result = false;
  5208. TFileOperationProgressType OperationProgress(&DoProgress, &DoFinished);
  5209. TOnceDoneOperation OnceDoneOperation = odoIdle;
  5210. OperationStart(OperationProgress, foCalculateSize, osLocal, FileList->Count);
  5211. try
  5212. {
  5213. TCalculateSizeParams Params;
  5214. Params.Size = 0;
  5215. Params.Params = 0;
  5216. Params.CopyParam = CopyParam;
  5217. Params.Files = NULL;
  5218. Params.Result = true;
  5219. UnicodeString LastDirPath;
  5220. for (int Index = 0; Params.Result && (Index < FileList->Count); Index++)
  5221. {
  5222. UnicodeString FileName = FileList->Strings[Index];
  5223. TSearchRecSmart Rec;
  5224. if (FileSearchRec(FileName, Rec))
  5225. {
  5226. if (Rec.IsDirectory() && !AllowDirs)
  5227. {
  5228. Params.Result = false;
  5229. }
  5230. else
  5231. {
  5232. if (Files != NULL)
  5233. {
  5234. UnicodeString FullFileName = ::ExpandFileName(FileName);
  5235. UnicodeString DirPath = ExtractFilePath(FullFileName);
  5236. if (DirPath != LastDirPath)
  5237. {
  5238. Params.Files = new TCollectedFileList();
  5239. LastDirPath = DirPath;
  5240. Files->AddObject(LastDirPath, Params.Files);
  5241. }
  5242. }
  5243. __int64 PrevSize = Params.Size;
  5244. CalculateLocalFileSize(FileName, Rec, &Params);
  5245. if (CalculatedSizes != NULL)
  5246. {
  5247. __int64 Size = Params.Size - PrevSize;
  5248. CalculatedSizes->push_back(Size);
  5249. }
  5250. OperationFinish(&OperationProgress, FileList->Objects[Index], FileName, true, OnceDoneOperation);
  5251. }
  5252. }
  5253. }
  5254. Size = Params.Size;
  5255. Result = Params.Result;
  5256. }
  5257. __finally
  5258. {
  5259. OperationStop(OperationProgress);
  5260. }
  5261. if (Configuration->ActualLogProtocol >= 1)
  5262. {
  5263. LogEvent(FORMAT(L"Size of %d local files/folders calculated as %s", (FileList->Count, IntToStr(Size))));
  5264. }
  5265. if (OnceDoneOperation != odoIdle)
  5266. {
  5267. CloseOnCompletion(OnceDoneOperation);
  5268. }
  5269. return Result;
  5270. }
  5271. //---------------------------------------------------------------------------
  5272. struct TSynchronizeFileData
  5273. {
  5274. bool Modified;
  5275. bool New;
  5276. bool IsDirectory;
  5277. TSynchronizeChecklist::TItem::TFileInfo Info;
  5278. TSynchronizeChecklist::TItem::TFileInfo MatchingRemoteFile;
  5279. TRemoteFile * MatchingRemoteFileFile;
  5280. int MatchingRemoteFileImageIndex;
  5281. FILETIME LocalLastWriteTime;
  5282. };
  5283. //---------------------------------------------------------------------------
  5284. const int sfFirstLevel = 0x01;
  5285. struct TSynchronizeData
  5286. {
  5287. UnicodeString LocalDirectory;
  5288. UnicodeString RemoteDirectory;
  5289. TTerminal::TSynchronizeMode Mode;
  5290. int Params;
  5291. TSynchronizeDirectory OnSynchronizeDirectory;
  5292. TSynchronizeOptions * Options;
  5293. int Flags;
  5294. TStringList * LocalFileList;
  5295. const TCopyParamType * CopyParam;
  5296. TSynchronizeChecklist * Checklist;
  5297. };
  5298. //---------------------------------------------------------------------------
  5299. TSynchronizeChecklist * __fastcall TTerminal::SynchronizeCollect(const UnicodeString LocalDirectory,
  5300. const UnicodeString RemoteDirectory, TSynchronizeMode Mode,
  5301. const TCopyParamType * CopyParam, int Params,
  5302. TSynchronizeDirectory OnSynchronizeDirectory,
  5303. TSynchronizeOptions * Options)
  5304. {
  5305. TValueRestorer<bool> UseBusyCursorRestorer(FUseBusyCursor);
  5306. FUseBusyCursor = false;
  5307. TSynchronizeChecklist * Checklist = new TSynchronizeChecklist();
  5308. try
  5309. {
  5310. DoSynchronizeCollectDirectory(LocalDirectory, RemoteDirectory, Mode,
  5311. CopyParam, Params, OnSynchronizeDirectory, Options, sfFirstLevel,
  5312. Checklist);
  5313. Checklist->Sort();
  5314. }
  5315. catch(...)
  5316. {
  5317. delete Checklist;
  5318. throw;
  5319. }
  5320. return Checklist;
  5321. }
  5322. //---------------------------------------------------------------------------
  5323. static void __fastcall AddFlagName(UnicodeString & ParamsStr, int & Params, int Param, const UnicodeString & Name)
  5324. {
  5325. if (FLAGSET(Params, Param))
  5326. {
  5327. AddToList(ParamsStr, Name, ", ");
  5328. }
  5329. Params &= ~Param;
  5330. }
  5331. //---------------------------------------------------------------------------
  5332. UnicodeString __fastcall TTerminal::SynchronizeModeStr(TSynchronizeMode Mode)
  5333. {
  5334. UnicodeString ModeStr;
  5335. switch (Mode)
  5336. {
  5337. case smRemote:
  5338. ModeStr = L"Remote";
  5339. break;
  5340. case smLocal:
  5341. ModeStr = L"Local";
  5342. break;
  5343. case smBoth:
  5344. ModeStr = L"Both";
  5345. break;
  5346. default:
  5347. ModeStr = L"Unknown";
  5348. break;
  5349. }
  5350. return ModeStr;
  5351. }
  5352. //---------------------------------------------------------------------------
  5353. UnicodeString __fastcall TTerminal::SynchronizeParamsStr(int Params)
  5354. {
  5355. UnicodeString ParamsStr;
  5356. AddFlagName(ParamsStr, Params, spDelete, L"Delete");
  5357. AddFlagName(ParamsStr, Params, spNoConfirmation, L"NoConfirmation");
  5358. AddFlagName(ParamsStr, Params, spExistingOnly, L"ExistingOnly");
  5359. AddFlagName(ParamsStr, Params, spNoRecurse, L"NoRecurse");
  5360. AddFlagName(ParamsStr, Params, spUseCache, L"UseCache");
  5361. AddFlagName(ParamsStr, Params, spDelayProgress, L"DelayProgress");
  5362. AddFlagName(ParamsStr, Params, spPreviewChanges, L"*PreviewChanges"); // GUI only
  5363. AddFlagName(ParamsStr, Params, spSubDirs, L"SubDirs");
  5364. AddFlagName(ParamsStr, Params, spTimestamp, L"Timestamp");
  5365. AddFlagName(ParamsStr, Params, spNotByTime, L"NotByTime");
  5366. AddFlagName(ParamsStr, Params, spBySize, L"BySize");
  5367. AddFlagName(ParamsStr, Params, spCaseSensitive, L"CaseSensitive");
  5368. AddFlagName(ParamsStr, Params, spSelectedOnly, L"*SelectedOnly"); // GUI only
  5369. AddFlagName(ParamsStr, Params, spMirror, L"Mirror");
  5370. if (Params > 0)
  5371. {
  5372. AddToList(ParamsStr, FORMAT(L"0x%x", (int(Params))), L", ");
  5373. }
  5374. return ParamsStr;
  5375. }
  5376. //---------------------------------------------------------------------------
  5377. bool __fastcall TTerminal::LocalFindFirstLoop(const UnicodeString & Path, TSearchRecChecked & SearchRec)
  5378. {
  5379. bool Result;
  5380. FILE_OPERATION_LOOP_BEGIN
  5381. {
  5382. const int FindAttrs = faReadOnly | faHidden | faSysFile | faDirectory | faArchive;
  5383. Result = (FindFirstChecked(Path, FindAttrs, SearchRec) == 0);
  5384. }
  5385. FILE_OPERATION_LOOP_END(FMTLOAD(LIST_DIR_ERROR, (Path)));
  5386. return Result;
  5387. }
  5388. //---------------------------------------------------------------------------
  5389. bool __fastcall TTerminal::LocalFindNextLoop(TSearchRecChecked & SearchRec)
  5390. {
  5391. bool Result;
  5392. FILE_OPERATION_LOOP_BEGIN
  5393. {
  5394. Result = (FindNextChecked(SearchRec) == 0);
  5395. }
  5396. FILE_OPERATION_LOOP_END(FMTLOAD(LIST_DIR_ERROR, (SearchRec.Path)));
  5397. return Result;
  5398. }
  5399. //---------------------------------------------------------------------------
  5400. bool __fastcall TTerminal::IsEmptyLocalDirectory(
  5401. const UnicodeString & Path, const TCopyParamType * CopyParam, bool DisallowTemporaryTransferFiles)
  5402. {
  5403. UnicodeString Contents;
  5404. if (Configuration->ActualLogProtocol >= 1)
  5405. {
  5406. LogEvent(FORMAT(L"Checking if local directory \"%s\" is empty", (Path)));
  5407. }
  5408. TSearchRecOwned SearchRec;
  5409. if (LocalFindFirstLoop(IncludeTrailingBackslash(Path) + L"*.*", SearchRec))
  5410. {
  5411. do
  5412. {
  5413. UnicodeString FullLocalFileName = IncludeTrailingBackslash(Path) + SearchRec.Name;
  5414. if (SearchRec.IsRealFile() &&
  5415. DoAllowLocalFileTransfer(FullLocalFileName, SearchRec, CopyParam, true))
  5416. {
  5417. if (!SearchRec.IsDirectory() ||
  5418. !IsEmptyLocalDirectory(FullLocalFileName, CopyParam, DisallowTemporaryTransferFiles))
  5419. {
  5420. Contents = SearchRec.Name;
  5421. }
  5422. }
  5423. }
  5424. while (Contents.IsEmpty() && LocalFindNextLoop(SearchRec));
  5425. }
  5426. if (Configuration->ActualLogProtocol >= 1)
  5427. {
  5428. if (Contents.IsEmpty())
  5429. {
  5430. LogEvent(FORMAT(L"Local directory \"%s\" is empty", (Path)));
  5431. }
  5432. else
  5433. {
  5434. LogEvent(FORMAT(L"Local directory \"%s\" is not empty, it contains \"%s\"", (Path, Contents)));
  5435. }
  5436. }
  5437. return Contents.IsEmpty();
  5438. }
  5439. //---------------------------------------------------------------------------
  5440. void __fastcall TTerminal::DoSynchronizeCollectDirectory(const UnicodeString LocalDirectory,
  5441. const UnicodeString RemoteDirectory, TSynchronizeMode Mode,
  5442. const TCopyParamType * CopyParam, int Params,
  5443. TSynchronizeDirectory OnSynchronizeDirectory, TSynchronizeOptions * Options,
  5444. int Flags, TSynchronizeChecklist * Checklist)
  5445. {
  5446. TSynchronizeData Data;
  5447. Data.LocalDirectory = IncludeTrailingBackslash(LocalDirectory);
  5448. Data.RemoteDirectory = UnixIncludeTrailingBackslash(RemoteDirectory);
  5449. Data.Mode = Mode;
  5450. Data.Params = Params;
  5451. Data.OnSynchronizeDirectory = OnSynchronizeDirectory;
  5452. Data.LocalFileList = NULL;
  5453. Data.CopyParam = CopyParam;
  5454. Data.Options = Options;
  5455. Data.Flags = Flags;
  5456. Data.Checklist = Checklist;
  5457. LogEvent(FORMAT(L"Collecting synchronization list for local directory '%s' and remote directory '%s', "
  5458. "mode = %s, params = 0x%x (%s), file mask = '%s'", (LocalDirectory, RemoteDirectory,
  5459. SynchronizeModeStr(Mode), int(Params), SynchronizeParamsStr(Params), CopyParam->IncludeFileMask.Masks)));
  5460. if (FLAGCLEAR(Params, spDelayProgress))
  5461. {
  5462. DoSynchronizeProgress(Data, true);
  5463. }
  5464. try
  5465. {
  5466. Data.LocalFileList = CreateSortedStringList(FLAGSET(Params, spCaseSensitive));
  5467. TSearchRecOwned SearchRec;
  5468. if (LocalFindFirstLoop(Data.LocalDirectory + L"*.*", SearchRec))
  5469. {
  5470. do
  5471. {
  5472. UnicodeString FileName = SearchRec.Name;
  5473. UnicodeString FullLocalFileName = Data.LocalDirectory + FileName;
  5474. UnicodeString RemoteFileName = ChangeFileName(CopyParam, FileName, osLocal, false);
  5475. if (SearchRec.IsRealFile() &&
  5476. DoAllowLocalFileTransfer(FullLocalFileName, SearchRec, CopyParam, true) &&
  5477. (FLAGCLEAR(Flags, sfFirstLevel) ||
  5478. (Options == NULL) ||
  5479. Options->MatchesFilter(FileName) ||
  5480. Options->MatchesFilter(RemoteFileName)))
  5481. {
  5482. TSynchronizeFileData * FileData = new TSynchronizeFileData;
  5483. FileData->IsDirectory = SearchRec.IsDirectory();
  5484. FileData->Info.FileName = FileName;
  5485. FileData->Info.Directory = Data.LocalDirectory;
  5486. FileData->Info.Modification = SearchRec.GetLastWriteTime();
  5487. FileData->Info.ModificationFmt = mfFull;
  5488. FileData->Info.Size = SearchRec.Size;
  5489. FileData->LocalLastWriteTime = SearchRec.FindData.ftLastWriteTime;
  5490. FileData->New = true;
  5491. FileData->Modified = false;
  5492. Data.LocalFileList->AddObject(FileName, reinterpret_cast<TObject*>(FileData));
  5493. LogEvent(0, FORMAT(L"Local file %s included to synchronization",
  5494. (FormatFileDetailsForLog(FullLocalFileName, SearchRec.GetLastWriteTime(), SearchRec.Size))));
  5495. }
  5496. else
  5497. {
  5498. LogEvent(0, FORMAT(L"Local file %s excluded from synchronization",
  5499. (FormatFileDetailsForLog(FullLocalFileName, SearchRec.GetLastWriteTime(), SearchRec.Size))));
  5500. }
  5501. }
  5502. while (LocalFindNextLoop(SearchRec));
  5503. SearchRec.Close();
  5504. // can we expect that ProcessDirectory would take so little time
  5505. // that we can postpone showing progress window until anything actually happens?
  5506. bool Cached = FLAGSET(Params, spUseCache) && SessionData->CacheDirectories &&
  5507. FDirectoryCache->HasFileList(RemoteDirectory);
  5508. if (!Cached && FLAGSET(Params, spDelayProgress))
  5509. {
  5510. DoSynchronizeProgress(Data, true);
  5511. }
  5512. ProcessDirectory(RemoteDirectory, SynchronizeCollectFile, &Data,
  5513. FLAGSET(Params, spUseCache));
  5514. TSynchronizeFileData * FileData;
  5515. for (int Index = 0; Index < Data.LocalFileList->Count; Index++)
  5516. {
  5517. FileData = reinterpret_cast<TSynchronizeFileData *>
  5518. (Data.LocalFileList->Objects[Index]);
  5519. // add local file either if we are going to upload it
  5520. // (i.e. if it is updated or we want to upload even new files)
  5521. // or if we are going to delete it (i.e. all "new"=obsolete files)
  5522. bool Modified = (FileData->Modified && ((Mode == smBoth) || (Mode == smRemote)));
  5523. bool New = (FileData->New &&
  5524. ((Mode == smLocal) ||
  5525. (((Mode == smBoth) || (Mode == smRemote)) && FLAGCLEAR(Params, spTimestamp))));
  5526. if (New)
  5527. {
  5528. LogEvent(FORMAT(L"Local file %s is new",
  5529. (FormatFileDetailsForLog(FileData->Info.Directory + FileData->Info.FileName,
  5530. FileData->Info.Modification, FileData->Info.Size))));
  5531. }
  5532. if (Modified || New)
  5533. {
  5534. TSynchronizeChecklist::TItem * ChecklistItem = new TSynchronizeChecklist::TItem();
  5535. try
  5536. {
  5537. ChecklistItem->IsDirectory = FileData->IsDirectory;
  5538. ChecklistItem->Local = FileData->Info;
  5539. ChecklistItem->FLocalLastWriteTime = FileData->LocalLastWriteTime;
  5540. if (Modified)
  5541. {
  5542. DebugAssert(!FileData->MatchingRemoteFile.Directory.IsEmpty());
  5543. ChecklistItem->Remote = FileData->MatchingRemoteFile;
  5544. ChecklistItem->ImageIndex = FileData->MatchingRemoteFileImageIndex;
  5545. ChecklistItem->RemoteFile = FileData->MatchingRemoteFileFile;
  5546. }
  5547. else
  5548. {
  5549. ChecklistItem->Remote.Directory = Data.RemoteDirectory;
  5550. }
  5551. if ((Mode == smBoth) || (Mode == smRemote))
  5552. {
  5553. ChecklistItem->Action =
  5554. (Modified ? TSynchronizeChecklist::saUploadUpdate : TSynchronizeChecklist::saUploadNew);
  5555. ChecklistItem->Checked =
  5556. (Modified || FLAGCLEAR(Params, spExistingOnly)) &&
  5557. (!ChecklistItem->IsDirectory || FLAGCLEAR(Params, spNoRecurse) ||
  5558. FLAGSET(Params, spSubDirs));
  5559. }
  5560. else if ((Mode == smLocal) && FLAGCLEAR(Params, spTimestamp))
  5561. {
  5562. ChecklistItem->Action = TSynchronizeChecklist::saDeleteLocal;
  5563. ChecklistItem->Checked =
  5564. FLAGSET(Params, spDelete) &&
  5565. (!ChecklistItem->IsDirectory || FLAGCLEAR(Params, spNoRecurse) ||
  5566. FLAGSET(Params, spSubDirs));
  5567. }
  5568. if (ChecklistItem->Action != TSynchronizeChecklist::saNone)
  5569. {
  5570. Data.Checklist->Add(ChecklistItem);
  5571. ChecklistItem = NULL;
  5572. }
  5573. }
  5574. __finally
  5575. {
  5576. delete ChecklistItem;
  5577. }
  5578. }
  5579. else
  5580. {
  5581. if (FileData->Modified)
  5582. {
  5583. delete FileData->MatchingRemoteFileFile;
  5584. }
  5585. }
  5586. }
  5587. }
  5588. }
  5589. __finally
  5590. {
  5591. if (Data.LocalFileList != NULL)
  5592. {
  5593. for (int Index = 0; Index < Data.LocalFileList->Count; Index++)
  5594. {
  5595. TSynchronizeFileData * FileData = reinterpret_cast<TSynchronizeFileData*>
  5596. (Data.LocalFileList->Objects[Index]);
  5597. delete FileData;
  5598. }
  5599. delete Data.LocalFileList;
  5600. }
  5601. }
  5602. }
  5603. //---------------------------------------------------------------------------
  5604. void __fastcall TTerminal::SynchronizeCollectFile(const UnicodeString FileName,
  5605. const TRemoteFile * File, /*TSynchronizeData*/ void * Param)
  5606. {
  5607. try
  5608. {
  5609. DoSynchronizeCollectFile(FileName, File, Param);
  5610. }
  5611. catch(ESkipFile & E)
  5612. {
  5613. TSuspendFileOperationProgress Suspend(OperationProgress);
  5614. if (!HandleException(&E))
  5615. {
  5616. throw;
  5617. }
  5618. }
  5619. }
  5620. //---------------------------------------------------------------------------
  5621. bool __fastcall TTerminal::IsEmptyRemoteDirectory(
  5622. const TRemoteFile * File, const TCopyParamType * ACopyParam, bool DisallowTemporaryTransferFiles)
  5623. {
  5624. TCalculateSizeStats Stats;
  5625. TCopyParamType CopyParam(*ACopyParam);
  5626. CopyParam.ExcludeEmptyDirectories = false; // to avoid endless recursion
  5627. TCalculateSizeParams Params;
  5628. Params.Params = csStopOnFirstFile | csIgnoreErrors | FLAGMASK(DisallowTemporaryTransferFiles, csDisallowTemporaryTransferFiles);
  5629. Params.CopyParam = &CopyParam;
  5630. Params.Stats = &Stats;
  5631. DoCalculateDirectorySize(UnixExcludeTrailingBackslash(File->FullFileName), &Params);
  5632. return Params.Result && (Stats.Files == 0);
  5633. }
  5634. //---------------------------------------------------------------------------
  5635. void __fastcall TTerminal::DoSynchronizeCollectFile(const UnicodeString FileName,
  5636. const TRemoteFile * File, /*TSynchronizeData*/ void * Param)
  5637. {
  5638. TSynchronizeData * Data = static_cast<TSynchronizeData *>(Param);
  5639. // Can be NULL in scripting
  5640. if (Data->Options != NULL)
  5641. {
  5642. Data->Options->Files++;
  5643. }
  5644. UnicodeString LocalFileName = ChangeFileName(Data->CopyParam, File->FileName, osRemote, false);
  5645. UnicodeString FullRemoteFileName = UnixExcludeTrailingBackslash(File->FullFileName);
  5646. if (DoAllowRemoteFileTransfer(File, Data->CopyParam, true) &&
  5647. (FLAGCLEAR(Data->Flags, sfFirstLevel) ||
  5648. (Data->Options == NULL) ||
  5649. Data->Options->MatchesFilter(File->FileName) ||
  5650. Data->Options->MatchesFilter(LocalFileName)))
  5651. {
  5652. TSynchronizeChecklist::TItem * ChecklistItem = new TSynchronizeChecklist::TItem();
  5653. try
  5654. {
  5655. ChecklistItem->IsDirectory = File->IsDirectory;
  5656. ChecklistItem->ImageIndex = File->IconIndex;
  5657. ChecklistItem->Remote.FileName = File->FileName;
  5658. ChecklistItem->Remote.Directory = Data->RemoteDirectory;
  5659. ChecklistItem->Remote.Modification = File->Modification;
  5660. ChecklistItem->Remote.ModificationFmt = File->ModificationFmt;
  5661. ChecklistItem->Remote.Size = File->Resolve()->Size;
  5662. bool Modified = false;
  5663. bool New = false;
  5664. if (File->IsDirectory && !CanRecurseToDirectory(File))
  5665. {
  5666. LogEvent(FORMAT(L"Skipping symlink to directory \"%s\".", (File->FileName)));
  5667. }
  5668. else
  5669. {
  5670. int LocalIndex = Data->LocalFileList->IndexOf(LocalFileName);
  5671. New = (LocalIndex < 0);
  5672. if (!New)
  5673. {
  5674. TSynchronizeFileData * LocalData =
  5675. reinterpret_cast<TSynchronizeFileData *>(Data->LocalFileList->Objects[LocalIndex]);
  5676. LocalData->New = false;
  5677. if (File->IsDirectory != LocalData->IsDirectory)
  5678. {
  5679. LogEvent(FORMAT(L"%s is directory on one side, but file on the another",
  5680. (File->FileName)));
  5681. }
  5682. else if (!File->IsDirectory)
  5683. {
  5684. ChecklistItem->Local = LocalData->Info;
  5685. ChecklistItem->Local.Modification =
  5686. ReduceDateTimePrecision(ChecklistItem->Local.Modification, File->ModificationFmt);
  5687. bool LocalModified = false;
  5688. // for spTimestamp+spBySize require that the file sizes are the same
  5689. // before comparing file time
  5690. int TimeCompare;
  5691. if (FLAGCLEAR(Data->Params, spNotByTime) &&
  5692. (FLAGCLEAR(Data->Params, spTimestamp) ||
  5693. FLAGCLEAR(Data->Params, spBySize) ||
  5694. (ChecklistItem->Local.Size == ChecklistItem->Remote.Size)))
  5695. {
  5696. TimeCompare = CompareFileTime(ChecklistItem->Local.Modification,
  5697. ChecklistItem->Remote.Modification);
  5698. }
  5699. else
  5700. {
  5701. TimeCompare = 0;
  5702. }
  5703. if (TimeCompare < 0)
  5704. {
  5705. if ((FLAGCLEAR(Data->Params, spTimestamp) && FLAGCLEAR(Data->Params, spMirror)) ||
  5706. (Data->Mode == smBoth) || (Data->Mode == smLocal))
  5707. {
  5708. Modified = true;
  5709. }
  5710. else
  5711. {
  5712. LocalModified = true;
  5713. }
  5714. }
  5715. else if (TimeCompare > 0)
  5716. {
  5717. if ((FLAGCLEAR(Data->Params, spTimestamp) && FLAGCLEAR(Data->Params, spMirror)) ||
  5718. (Data->Mode == smBoth) || (Data->Mode == smRemote))
  5719. {
  5720. LocalModified = true;
  5721. }
  5722. else
  5723. {
  5724. Modified = true;
  5725. }
  5726. }
  5727. else if (FLAGSET(Data->Params, spBySize) &&
  5728. (ChecklistItem->Local.Size != ChecklistItem->Remote.Size) &&
  5729. FLAGCLEAR(Data->Params, spTimestamp))
  5730. {
  5731. Modified = true;
  5732. LocalModified = true;
  5733. }
  5734. if (LocalModified)
  5735. {
  5736. LocalData->Modified = true;
  5737. LocalData->MatchingRemoteFile = ChecklistItem->Remote;
  5738. LocalData->MatchingRemoteFileImageIndex = ChecklistItem->ImageIndex;
  5739. // we need this for custom commands over checklist only,
  5740. // not for sync itself
  5741. LocalData->MatchingRemoteFileFile = File->Duplicate();
  5742. LogEvent(FORMAT(L"Local file %s is modified comparing to remote file %s",
  5743. (FormatFileDetailsForLog(LocalData->Info.Directory + LocalData->Info.FileName,
  5744. LocalData->Info.Modification, LocalData->Info.Size),
  5745. FormatFileDetailsForLog(FullRemoteFileName,
  5746. File->Modification, File->Size, File->LinkedFile))));
  5747. }
  5748. if (Modified)
  5749. {
  5750. LogEvent(FORMAT(L"Remote file %s is modified comparing to local file %s",
  5751. (FormatFileDetailsForLog(FullRemoteFileName, File->Modification, File->Size, File->LinkedFile),
  5752. FormatFileDetailsForLog(LocalData->Info.Directory + LocalData->Info.FileName,
  5753. LocalData->Info.Modification, LocalData->Info.Size))));
  5754. }
  5755. }
  5756. else if (FLAGCLEAR(Data->Params, spNoRecurse))
  5757. {
  5758. DoSynchronizeCollectDirectory(
  5759. Data->LocalDirectory + LocalData->Info.FileName,
  5760. Data->RemoteDirectory + File->FileName,
  5761. Data->Mode, Data->CopyParam, Data->Params, Data->OnSynchronizeDirectory,
  5762. Data->Options, (Data->Flags & ~sfFirstLevel),
  5763. Data->Checklist);
  5764. }
  5765. }
  5766. else
  5767. {
  5768. ChecklistItem->Local.Directory = Data->LocalDirectory;
  5769. LogEvent(FORMAT(L"Remote file %s is new",
  5770. (FormatFileDetailsForLog(FullRemoteFileName, File->Modification, File->Size, File->LinkedFile))));
  5771. }
  5772. }
  5773. if (New || Modified)
  5774. {
  5775. DebugAssert(!New || !Modified);
  5776. // download the file if it changed or is new and we want to have it locally
  5777. if ((Data->Mode == smBoth) || (Data->Mode == smLocal))
  5778. {
  5779. if (FLAGCLEAR(Data->Params, spTimestamp) || Modified)
  5780. {
  5781. ChecklistItem->Action =
  5782. (Modified ? TSynchronizeChecklist::saDownloadUpdate : TSynchronizeChecklist::saDownloadNew);
  5783. ChecklistItem->Checked =
  5784. (Modified || FLAGCLEAR(Data->Params, spExistingOnly)) &&
  5785. (!ChecklistItem->IsDirectory || FLAGCLEAR(Data->Params, spNoRecurse) ||
  5786. FLAGSET(Data->Params, spSubDirs));
  5787. }
  5788. }
  5789. else if ((Data->Mode == smRemote) && New)
  5790. {
  5791. if (FLAGCLEAR(Data->Params, spTimestamp))
  5792. {
  5793. ChecklistItem->Action = TSynchronizeChecklist::saDeleteRemote;
  5794. ChecklistItem->Checked =
  5795. FLAGSET(Data->Params, spDelete) &&
  5796. (!ChecklistItem->IsDirectory || FLAGCLEAR(Data->Params, spNoRecurse) ||
  5797. FLAGSET(Data->Params, spSubDirs));
  5798. }
  5799. }
  5800. if (ChecklistItem->Action != TSynchronizeChecklist::saNone)
  5801. {
  5802. ChecklistItem->RemoteFile = File->Duplicate();
  5803. Data->Checklist->Add(ChecklistItem);
  5804. ChecklistItem = NULL;
  5805. }
  5806. }
  5807. }
  5808. __finally
  5809. {
  5810. delete ChecklistItem;
  5811. }
  5812. }
  5813. else
  5814. {
  5815. LogEvent(0, FORMAT(L"Remote file %s excluded from synchronization",
  5816. (FormatFileDetailsForLog(FullRemoteFileName, File->Modification, File->Size, File->LinkedFile))));
  5817. }
  5818. }
  5819. //---------------------------------------------------------------------------
  5820. void __fastcall TTerminal::SynchronizeApply(
  5821. TSynchronizeChecklist * Checklist,
  5822. const TCopyParamType * CopyParam, int Params,
  5823. TSynchronizeDirectory OnSynchronizeDirectory, TProcessedSynchronizationChecklistItem OnProcessedItem,
  5824. TUpdatedSynchronizationChecklistItems OnUpdatedSynchronizationChecklistItems, void * Token,
  5825. TFileOperationStatistics * Statistics)
  5826. {
  5827. TSynchronizeData Data;
  5828. Data.OnSynchronizeDirectory = OnSynchronizeDirectory;
  5829. int CopyParams =
  5830. FLAGMASK(FLAGSET(Params, spNoConfirmation), cpNoConfirmation);
  5831. TCopyParamType SyncCopyParam = *CopyParam;
  5832. // when synchronizing by time, we force preserving time,
  5833. // otherwise it does not make any sense
  5834. if (FLAGCLEAR(Params, spNotByTime))
  5835. {
  5836. SyncCopyParam.PreserveTime = true;
  5837. }
  5838. if (SyncCopyParam.CalculateSize)
  5839. {
  5840. // If we fail to collect the sizes, do not try again during an actual transfer
  5841. SyncCopyParam.CalculateSize = false;
  5842. TSynchronizeChecklist::TItemList Items;
  5843. for (int Index = 0; Index < Checklist->Count; Index++)
  5844. {
  5845. const TSynchronizeChecklist::TItem * ChecklistItem = Checklist->Item[Index];
  5846. // TSynchronizeChecklistDialog relies on us not to update a size of an item that had size already
  5847. // See TSynchronizeChecklistDialog::UpdatedSynchronizationChecklistItems
  5848. if (ChecklistItem->Checked && !TSynchronizeChecklist::IsItemSizeIrrelevant(ChecklistItem->Action) &&
  5849. !ChecklistItem->HasSize() && DebugAlwaysTrue(ChecklistItem->IsDirectory))
  5850. {
  5851. Items.push_back(ChecklistItem);
  5852. }
  5853. }
  5854. SynchronizeChecklistCalculateSize(Checklist, Items, &SyncCopyParam);
  5855. if (OnUpdatedSynchronizationChecklistItems != NULL)
  5856. {
  5857. OnUpdatedSynchronizationChecklistItems(Items);
  5858. }
  5859. }
  5860. BeginTransaction();
  5861. TValueRestorer<TFileOperationProgressType::TPersistence *> OperationProgressPersistenceRestorer(FOperationProgressPersistence);
  5862. TValueRestorer<TOnceDoneOperation> OperationProgressOnceDoneOperationRestorer(FOperationProgressOnceDoneOperation);
  5863. TFileOperationProgressType::TPersistence OperationProgressPersistence;
  5864. OperationProgressPersistence.Statistics = Statistics;
  5865. FOperationProgressPersistence = &OperationProgressPersistence;
  5866. try
  5867. {
  5868. int Index = 0;
  5869. while (Index < Checklist->Count)
  5870. {
  5871. const TSynchronizeChecklist::TItem * ChecklistItem = Checklist->Item[Index];
  5872. if (ChecklistItem->Checked)
  5873. {
  5874. if (!SamePaths(Data.LocalDirectory, ChecklistItem->Local.Directory) ||
  5875. !UnixSamePath(Data.RemoteDirectory, ChecklistItem->Remote.Directory))
  5876. {
  5877. Data.LocalDirectory = IncludeTrailingBackslash(ChecklistItem->Local.Directory);
  5878. Data.RemoteDirectory = UnixIncludeTrailingBackslash(ChecklistItem->Remote.Directory);
  5879. LogEvent(
  5880. FORMAT(L"Synchronizing local directory '%s' with remote directory '%s', params = 0x%x (%s)",
  5881. (Data.LocalDirectory, Data.RemoteDirectory, int(Params), SynchronizeParamsStr(Params))));
  5882. DoSynchronizeProgress(Data, false);
  5883. }
  5884. std::unique_ptr<TStringList> FileList(new TStringList());
  5885. UnicodeString LocalPath = IncludeTrailingBackslash(ChecklistItem->Local.Directory) + ChecklistItem->Local.FileName;
  5886. UnicodeString RemotePath = UnixIncludeTrailingBackslash(ChecklistItem->Remote.Directory) + ChecklistItem->Remote.FileName;
  5887. bool Result = true;
  5888. if (FLAGSET(Params, spTimestamp))
  5889. {
  5890. // used by SynchronizeLocalTimestamp and SynchronizeRemoteTimestamp
  5891. TObject * ChecklistItemToken = const_cast<TObject *>(reinterpret_cast<const TObject *>(ChecklistItem));
  5892. switch (ChecklistItem->Action)
  5893. {
  5894. case TSynchronizeChecklist::saDownloadUpdate:
  5895. FileList->AddObject(RemotePath, ChecklistItemToken);
  5896. ProcessFiles(FileList.get(), foSetProperties, SynchronizeLocalTimestamp, NULL, osLocal);
  5897. break;
  5898. case TSynchronizeChecklist::saUploadUpdate:
  5899. FileList->AddObject(LocalPath, ChecklistItemToken);
  5900. ProcessFiles(FileList.get(), foSetProperties, SynchronizeRemoteTimestamp);
  5901. break;
  5902. default:
  5903. DebugFail();
  5904. Result = false;
  5905. break;
  5906. }
  5907. }
  5908. else
  5909. {
  5910. TCopyParamType ItemCopyParam = SyncCopyParam;
  5911. ItemCopyParam.Size = ChecklistItem->HasSize() ? ChecklistItem->GetSize() : -1;
  5912. switch (ChecklistItem->Action)
  5913. {
  5914. case TSynchronizeChecklist::saDownloadNew:
  5915. case TSynchronizeChecklist::saDownloadUpdate:
  5916. FileList->AddObject(RemotePath, ChecklistItem->RemoteFile);
  5917. Result = CopyToLocal(FileList.get(), Data.LocalDirectory, &ItemCopyParam, CopyParams, NULL);
  5918. break;
  5919. case TSynchronizeChecklist::saDeleteRemote:
  5920. FileList->AddObject(RemotePath, ChecklistItem->RemoteFile);
  5921. Result = DeleteFiles(FileList.get());
  5922. break;
  5923. case TSynchronizeChecklist::saUploadNew:
  5924. case TSynchronizeChecklist::saUploadUpdate:
  5925. FileList->Add(LocalPath);
  5926. Result = CopyToRemote(FileList.get(), Data.RemoteDirectory, &ItemCopyParam, CopyParams, NULL);
  5927. break;
  5928. case TSynchronizeChecklist::saDeleteLocal:
  5929. FileList->Add(LocalPath);
  5930. Result = DeleteLocalFiles(FileList.get());
  5931. break;
  5932. default:
  5933. DebugFail();
  5934. Result = false;
  5935. break;
  5936. }
  5937. }
  5938. if (!Result)
  5939. {
  5940. Abort();
  5941. }
  5942. if (OnProcessedItem != NULL)
  5943. {
  5944. OnProcessedItem(Token, ChecklistItem);
  5945. }
  5946. }
  5947. Index++;
  5948. }
  5949. }
  5950. __finally
  5951. {
  5952. EndTransaction();
  5953. }
  5954. if (FOperationProgressOnceDoneOperation != odoIdle)
  5955. {
  5956. // Otherwise CloseOnCompletion would have no effect
  5957. OperationProgressPersistenceRestorer.Release();
  5958. CloseOnCompletion(FOperationProgressOnceDoneOperation);
  5959. }
  5960. }
  5961. //---------------------------------------------------------------------------
  5962. void __fastcall TTerminal::SynchronizeChecklistCalculateSize(
  5963. TSynchronizeChecklist * Checklist, const TSynchronizeChecklist::TItemList & Items,
  5964. const TCopyParamType * CopyParam)
  5965. {
  5966. std::unique_ptr<TStrings> RemoteFileList(new TStringList());
  5967. std::unique_ptr<TStrings> LocalFileList(new TStringList());
  5968. for (size_t Index = 0; Index < Items.size(); Index++)
  5969. {
  5970. const TSynchronizeChecklist::TItem * ChecklistItem = Items[Index];
  5971. if (ChecklistItem->IsDirectory)
  5972. {
  5973. if (ChecklistItem->IsRemoteOnly())
  5974. {
  5975. RemoteFileList->AddObject(ChecklistItem->RemoteFile->FullFileName, ChecklistItem->RemoteFile);
  5976. }
  5977. else if (ChecklistItem->IsLocalOnly())
  5978. {
  5979. LocalFileList->Add(IncludeTrailingBackslash(ChecklistItem->Local.Directory) + ChecklistItem->Local.FileName);
  5980. }
  5981. else
  5982. {
  5983. // "update" actions are not relevant for directories
  5984. DebugFail();
  5985. }
  5986. }
  5987. }
  5988. TCalculatedSizes RemoteCalculatedSizes;
  5989. TCalculatedSizes LocalCalculatedSizes;
  5990. try
  5991. {
  5992. bool Result = true;
  5993. if (LocalFileList->Count > 0)
  5994. {
  5995. __int64 LocalSize = 0;
  5996. Result = CalculateLocalFilesSize(LocalFileList.get(), LocalSize, CopyParam, true, NULL, &LocalCalculatedSizes);
  5997. }
  5998. if (Result && (RemoteFileList->Count > 0))
  5999. {
  6000. __int64 RemoteSize = 0;
  6001. TCalculateSizeStats RemoteStats;
  6002. RemoteStats.CalculatedSizes = &RemoteCalculatedSizes;
  6003. CalculateFilesSize(RemoteFileList.get(), RemoteSize, 0, CopyParam, true, RemoteStats);
  6004. }
  6005. }
  6006. __finally
  6007. {
  6008. size_t LocalIndex = 0;
  6009. size_t RemoteIndex = 0;
  6010. for (size_t Index = 0; Index < Items.size(); Index++)
  6011. {
  6012. const TSynchronizeChecklist::TItem * ChecklistItem = Items[Index];
  6013. if (ChecklistItem->IsDirectory)
  6014. {
  6015. __int64 Size = -1;
  6016. if (ChecklistItem->IsRemoteOnly())
  6017. {
  6018. if (RemoteIndex < RemoteCalculatedSizes.size())
  6019. {
  6020. Size = RemoteCalculatedSizes[RemoteIndex];
  6021. }
  6022. RemoteIndex++;
  6023. }
  6024. else if (ChecklistItem->IsLocalOnly())
  6025. {
  6026. if (LocalIndex < LocalCalculatedSizes.size())
  6027. {
  6028. Size = LocalCalculatedSizes[LocalIndex];
  6029. }
  6030. LocalIndex++;
  6031. }
  6032. else
  6033. {
  6034. // "update" actions are not relevant for directories
  6035. DebugFail();
  6036. }
  6037. if (Size >= 0)
  6038. {
  6039. Checklist->UpdateDirectorySize(ChecklistItem, Size);
  6040. }
  6041. }
  6042. }
  6043. DebugAssert(RemoteIndex >= RemoteCalculatedSizes.size());
  6044. DebugAssert(LocalIndex >= LocalCalculatedSizes.size());
  6045. }
  6046. }
  6047. //---------------------------------------------------------------------------
  6048. void __fastcall TTerminal::DoSynchronizeProgress(const TSynchronizeData & Data,
  6049. bool Collect)
  6050. {
  6051. if (Data.OnSynchronizeDirectory != NULL)
  6052. {
  6053. bool Continue = true;
  6054. Data.OnSynchronizeDirectory(
  6055. Data.LocalDirectory, Data.RemoteDirectory, Continue, Collect, Data.Options);
  6056. if (!Continue)
  6057. {
  6058. Abort();
  6059. }
  6060. }
  6061. }
  6062. //---------------------------------------------------------------------------
  6063. void __fastcall TTerminal::SynchronizeLocalTimestamp(const UnicodeString /*FileName*/,
  6064. const TRemoteFile * File, void * /*Param*/)
  6065. {
  6066. const TSynchronizeChecklist::TItem * ChecklistItem =
  6067. reinterpret_cast<const TSynchronizeChecklist::TItem *>(File);
  6068. UnicodeString LocalFile =
  6069. IncludeTrailingBackslash(ChecklistItem->Local.Directory) +
  6070. ChecklistItem->Local.FileName;
  6071. FILE_OPERATION_LOOP_BEGIN
  6072. {
  6073. HANDLE Handle;
  6074. OpenLocalFile(LocalFile, GENERIC_WRITE, NULL, &Handle,
  6075. NULL, NULL, NULL, NULL);
  6076. FILETIME WrTime = DateTimeToFileTime(ChecklistItem->Remote.Modification,
  6077. SessionData->DSTMode);
  6078. bool Result = SetFileTime(Handle, NULL, NULL, &WrTime);
  6079. int Error = GetLastError();
  6080. CloseHandle(Handle);
  6081. if (!Result)
  6082. {
  6083. RaiseLastOSError(Error);
  6084. }
  6085. }
  6086. FILE_OPERATION_LOOP_END(FMTLOAD(CANT_SET_ATTRS, (LocalFile)));
  6087. }
  6088. //---------------------------------------------------------------------------
  6089. void __fastcall TTerminal::SynchronizeRemoteTimestamp(const UnicodeString /*FileName*/,
  6090. const TRemoteFile * File, void * /*Param*/)
  6091. {
  6092. const TSynchronizeChecklist::TItem * ChecklistItem =
  6093. reinterpret_cast<const TSynchronizeChecklist::TItem *>(File);
  6094. TRemoteProperties Properties;
  6095. Properties.Valid << vpModification;
  6096. Properties.Modification = ConvertTimestampToUnix(ChecklistItem->FLocalLastWriteTime,
  6097. SessionData->DSTMode);
  6098. ChangeFileProperties(
  6099. UnixIncludeTrailingBackslash(ChecklistItem->Remote.Directory) + ChecklistItem->Remote.FileName,
  6100. NULL, &Properties);
  6101. }
  6102. //---------------------------------------------------------------------------
  6103. void __fastcall TTerminal::FileFind(UnicodeString FileName,
  6104. const TRemoteFile * File, /*TFilesFindParams*/ void * Param)
  6105. {
  6106. // see DoFilesFind
  6107. FOnFindingFile = NULL;
  6108. DebugAssert(Param);
  6109. DebugAssert(File);
  6110. TFilesFindParams * AParams = static_cast<TFilesFindParams*>(Param);
  6111. if (!AParams->Cancel)
  6112. {
  6113. if (FileName.IsEmpty())
  6114. {
  6115. FileName = File->FileName;
  6116. }
  6117. TFileMasks::TParams MaskParams;
  6118. MaskParams.Size = File->Resolve()->Size;
  6119. MaskParams.Modification = File->Modification;
  6120. UnicodeString FullFileName = UnixExcludeTrailingBackslash(File->FullFileName);
  6121. bool ImplicitMatch;
  6122. // Do not use recursive include match
  6123. if (AParams->FileMask.Matches(FullFileName, false,
  6124. File->IsDirectory, &MaskParams, false, ImplicitMatch))
  6125. {
  6126. if (!ImplicitMatch)
  6127. {
  6128. AParams->OnFileFound(this, FileName, File, AParams->Cancel);
  6129. }
  6130. if (File->IsDirectory)
  6131. {
  6132. UnicodeString RealDirectory;
  6133. if (!File->IsSymLink || File->LinkTo.IsEmpty())
  6134. {
  6135. RealDirectory = UnixIncludeTrailingBackslash(AParams->RealDirectory) + File->FileName;
  6136. }
  6137. else
  6138. {
  6139. RealDirectory = ::AbsolutePath(AParams->RealDirectory, File->LinkTo);
  6140. }
  6141. if (!AParams->LoopDetector.IsUnvisitedDirectory(RealDirectory))
  6142. {
  6143. LogEvent(FORMAT(L"Already searched \"%s\" directory (real path \"%s\"), link loop detected", (FullFileName, RealDirectory)));
  6144. }
  6145. else
  6146. {
  6147. DoFilesFind(FullFileName, *AParams, RealDirectory);
  6148. }
  6149. }
  6150. }
  6151. }
  6152. }
  6153. //---------------------------------------------------------------------------
  6154. void __fastcall TTerminal::DoFilesFind(UnicodeString Directory, TFilesFindParams & Params, UnicodeString RealDirectory)
  6155. {
  6156. LogEvent(FORMAT(L"Searching directory \"%s\" (real path \"%s\")", (Directory, RealDirectory)));
  6157. Params.OnFindingFile(this, Directory, Params.Cancel);
  6158. if (!Params.Cancel)
  6159. {
  6160. DebugAssert(FOnFindingFile == NULL);
  6161. // ideally we should set the handler only around actually reading
  6162. // of the directory listing, so we at least reset the handler in
  6163. // FileFind
  6164. FOnFindingFile = Params.OnFindingFile;
  6165. UnicodeString PrevRealDirectory = Params.RealDirectory;
  6166. try
  6167. {
  6168. Params.RealDirectory = RealDirectory;
  6169. ProcessDirectory(Directory, FileFind, &Params, false, true);
  6170. }
  6171. __finally
  6172. {
  6173. Params.RealDirectory = PrevRealDirectory;
  6174. FOnFindingFile = NULL;
  6175. }
  6176. }
  6177. }
  6178. //---------------------------------------------------------------------------
  6179. void __fastcall TTerminal::FilesFind(UnicodeString Directory, const TFileMasks & FileMask,
  6180. TFileFoundEvent OnFileFound, TFindingFileEvent OnFindingFile)
  6181. {
  6182. TFilesFindParams Params;
  6183. Params.FileMask = FileMask;
  6184. Params.FileMask.NoImplicitMatchWithDirExcludeMask = true;
  6185. Params.FileMask.AllDirsAreImplicitlyIncluded = true;
  6186. Params.OnFileFound = OnFileFound;
  6187. Params.OnFindingFile = OnFindingFile;
  6188. Params.Cancel = false;
  6189. Params.LoopDetector.RecordVisitedDirectory(Directory);
  6190. DoFilesFind(Directory, Params, Directory);
  6191. }
  6192. //---------------------------------------------------------------------------
  6193. void __fastcall TTerminal::SpaceAvailable(const UnicodeString Path,
  6194. TSpaceAvailable & ASpaceAvailable)
  6195. {
  6196. DebugAssert(IsCapable[fcCheckingSpaceAvailable]);
  6197. try
  6198. {
  6199. FFileSystem->SpaceAvailable(Path, ASpaceAvailable);
  6200. }
  6201. catch (Exception &E)
  6202. {
  6203. CommandError(&E, FMTLOAD(SPACE_AVAILABLE_ERROR, (Path)));
  6204. }
  6205. }
  6206. //---------------------------------------------------------------------------
  6207. void __fastcall TTerminal::LockFile(const UnicodeString FileName,
  6208. const TRemoteFile * File, void * /*Param*/)
  6209. {
  6210. StartOperationWithFile(FileName, foLock);
  6211. LogEvent(FORMAT(L"Locking file \"%s\".", (FileName)));
  6212. FileModified(File, FileName, true);
  6213. DoLockFile(FileName, File);
  6214. ReactOnCommand(fsLock);
  6215. }
  6216. //---------------------------------------------------------------------------
  6217. void __fastcall TTerminal::DoLockFile(const UnicodeString & FileName, const TRemoteFile * File)
  6218. {
  6219. TRetryOperationLoop RetryLoop(this);
  6220. do
  6221. {
  6222. try
  6223. {
  6224. FFileSystem->LockFile(FileName, File);
  6225. }
  6226. catch(Exception & E)
  6227. {
  6228. RetryLoop.Error(E, FMTLOAD(LOCK_FILE_ERROR, (FileName)));
  6229. }
  6230. }
  6231. while (RetryLoop.Retry());
  6232. }
  6233. //---------------------------------------------------------------------------
  6234. void __fastcall TTerminal::UnlockFile(const UnicodeString FileName,
  6235. const TRemoteFile * File, void * /*Param*/)
  6236. {
  6237. StartOperationWithFile(FileName, foUnlock);
  6238. LogEvent(FORMAT(L"Unlocking file \"%s\".", (FileName)));
  6239. FileModified(File, FileName, true);
  6240. DoUnlockFile(FileName, File);
  6241. ReactOnCommand(fsLock);
  6242. }
  6243. //---------------------------------------------------------------------------
  6244. void __fastcall TTerminal::DoUnlockFile(const UnicodeString & FileName, const TRemoteFile * File)
  6245. {
  6246. TRetryOperationLoop RetryLoop(this);
  6247. do
  6248. {
  6249. try
  6250. {
  6251. FFileSystem->UnlockFile(FileName, File);
  6252. }
  6253. catch(Exception & E)
  6254. {
  6255. RetryLoop.Error(E, FMTLOAD(UNLOCK_FILE_ERROR, (FileName)));
  6256. }
  6257. }
  6258. while (RetryLoop.Retry());
  6259. }
  6260. //---------------------------------------------------------------------------
  6261. void __fastcall TTerminal::LockFiles(TStrings * FileList)
  6262. {
  6263. BeginTransaction();
  6264. try
  6265. {
  6266. ProcessFiles(FileList, foLock, LockFile, NULL);
  6267. }
  6268. __finally
  6269. {
  6270. EndTransaction();
  6271. }
  6272. }
  6273. //---------------------------------------------------------------------------
  6274. void __fastcall TTerminal::UnlockFiles(TStrings * FileList)
  6275. {
  6276. BeginTransaction();
  6277. try
  6278. {
  6279. ProcessFiles(FileList, foUnlock, UnlockFile, NULL);
  6280. }
  6281. __finally
  6282. {
  6283. EndTransaction();
  6284. }
  6285. }
  6286. //---------------------------------------------------------------------------
  6287. const TSessionInfo & __fastcall TTerminal::GetSessionInfo()
  6288. {
  6289. return FFileSystem->GetSessionInfo();
  6290. }
  6291. //---------------------------------------------------------------------------
  6292. const TFileSystemInfo & __fastcall TTerminal::GetFileSystemInfo(bool Retrieve)
  6293. {
  6294. return FFileSystem->GetFileSystemInfo(Retrieve);
  6295. }
  6296. //---------------------------------------------------------------------
  6297. void __fastcall TTerminal::GetSupportedChecksumAlgs(TStrings * Algs)
  6298. {
  6299. FFileSystem->GetSupportedChecksumAlgs(Algs);
  6300. }
  6301. //---------------------------------------------------------------------
  6302. UnicodeString __fastcall TTerminal::GetPassword()
  6303. {
  6304. UnicodeString Result;
  6305. // FRememberedPassword is empty also when stored password was used
  6306. if (FRememberedPassword.IsEmpty())
  6307. {
  6308. Result = SessionData->Password;
  6309. }
  6310. else if (FRememberedPasswordKind != pkPassphrase)
  6311. {
  6312. Result = GetRememberedPassword();
  6313. }
  6314. return Result;
  6315. }
  6316. //---------------------------------------------------------------------
  6317. UnicodeString __fastcall TTerminal::GetRememberedPassword()
  6318. {
  6319. return DecryptPassword(FRememberedPassword);
  6320. }
  6321. //---------------------------------------------------------------------
  6322. UnicodeString __fastcall TTerminal::GetRememberedTunnelPassword()
  6323. {
  6324. return DecryptPassword(FRememberedTunnelPassword);
  6325. }
  6326. //---------------------------------------------------------------------
  6327. bool __fastcall TTerminal::GetStoredCredentialsTried()
  6328. {
  6329. bool Result;
  6330. if (FFileSystem != NULL)
  6331. {
  6332. Result = FFileSystem->GetStoredCredentialsTried();
  6333. }
  6334. else if (FSecureShell != NULL)
  6335. {
  6336. Result = FSecureShell->GetStoredCredentialsTried();
  6337. }
  6338. else
  6339. {
  6340. DebugAssert(FTunnelOpening);
  6341. Result = false;
  6342. }
  6343. return Result;
  6344. }
  6345. //---------------------------------------------------------------------------
  6346. int __fastcall TTerminal::CopyToParallel(TParallelOperation * ParallelOperation, TFileOperationProgressType * OperationProgress)
  6347. {
  6348. UnicodeString FileName;
  6349. TObject * Object;
  6350. UnicodeString TargetDir;
  6351. bool Dir;
  6352. bool Recursed;
  6353. int Result = ParallelOperation->GetNext(this, FileName, Object, TargetDir, Dir, Recursed);
  6354. if (Result > 0)
  6355. {
  6356. std::unique_ptr<TStrings> FilesToCopy(new TStringList());
  6357. FilesToCopy->AddObject(FileName, Object);
  6358. if (ParallelOperation->Side == osLocal)
  6359. {
  6360. TargetDir = TranslateLockedPath(TargetDir, false);
  6361. }
  6362. // OnceDoneOperation is not supported
  6363. TOnceDoneOperation OnceDoneOperation = odoIdle;
  6364. int Params = ParallelOperation->Params;
  6365. // If we failed to recurse the directory when enumerating, recurse now (typically only to show the recursion error)
  6366. if (Dir && Recursed)
  6367. {
  6368. Params = Params | cpNoRecurse;
  6369. }
  6370. int Prev = OperationProgress->FilesFinishedSuccessfully;
  6371. DebugAssert((FOperationProgress == OperationProgress) || (FOperationProgress == NULL));
  6372. TFileOperationProgressType * PrevOperationProgress = FOperationProgress;
  6373. try
  6374. {
  6375. FOperationProgress = OperationProgress;
  6376. if (ParallelOperation->Side == osLocal)
  6377. {
  6378. FFileSystem->CopyToRemote(
  6379. FilesToCopy.get(), TargetDir, ParallelOperation->CopyParam, Params, OperationProgress, OnceDoneOperation);
  6380. }
  6381. else if (DebugAlwaysTrue(ParallelOperation->Side == osRemote))
  6382. {
  6383. FFileSystem->CopyToLocal(
  6384. FilesToCopy.get(), TargetDir, ParallelOperation->CopyParam, Params, OperationProgress, OnceDoneOperation);
  6385. }
  6386. }
  6387. __finally
  6388. {
  6389. bool Success = (Prev < OperationProgress->FilesFinishedSuccessfully);
  6390. ParallelOperation->Done(FileName, Dir, Success);
  6391. // Not to fail an assertion in OperationStop when called from CopyToRemote or CopyToLocal,
  6392. // when FOperationProgress is already OperationProgress.
  6393. FOperationProgress = PrevOperationProgress;
  6394. }
  6395. }
  6396. return Result;
  6397. }
  6398. //---------------------------------------------------------------------------
  6399. bool __fastcall TTerminal::CanParallel(
  6400. const TCopyParamType * CopyParam, int Params, TParallelOperation * ParallelOperation)
  6401. {
  6402. return
  6403. (ParallelOperation != NULL) &&
  6404. FFileSystem->IsCapable(fcParallelTransfers) &&
  6405. // parallel transfer is not implemented for operations needed to be done on a folder
  6406. // after all its files are processed
  6407. FLAGCLEAR(Params, cpDelete) &&
  6408. (!CopyParam->PreserveTime || !CopyParam->PreserveTimeDirs);
  6409. }
  6410. //---------------------------------------------------------------------------
  6411. void __fastcall TTerminal::CopyParallel(TParallelOperation * ParallelOperation, TFileOperationProgressType * OperationProgress)
  6412. {
  6413. try
  6414. {
  6415. bool Continue = true;
  6416. do
  6417. {
  6418. int GotNext = CopyToParallel(ParallelOperation, OperationProgress);
  6419. if (GotNext < 0)
  6420. {
  6421. Continue = false;
  6422. }
  6423. else if (GotNext == 0)
  6424. {
  6425. Sleep(100);
  6426. }
  6427. }
  6428. while (Continue && !OperationProgress->Cancel);
  6429. }
  6430. __finally
  6431. {
  6432. OperationProgress->SetDone();
  6433. ParallelOperation->WaitFor();
  6434. }
  6435. }
  6436. //---------------------------------------------------------------------------
  6437. void __fastcall TTerminal::LogParallelTransfer(TParallelOperation * ParallelOperation)
  6438. {
  6439. LogEvent(
  6440. FORMAT("Adding a parallel transfer to the transfer started on the connection \"%s\"",
  6441. (ParallelOperation->MainName)));
  6442. }
  6443. //---------------------------------------------------------------------------
  6444. void __fastcall TTerminal::LogTotalTransferDetails(
  6445. const UnicodeString TargetDir, const TCopyParamType * CopyParam,
  6446. TFileOperationProgressType * OperationProgress, bool Parallel, TStrings * Files)
  6447. {
  6448. if (Log->Logging)
  6449. {
  6450. UnicodeString TargetSide = ((OperationProgress->Side == osLocal) ? L"remote" : L"local");
  6451. UnicodeString S =
  6452. FORMAT(
  6453. L"Copying %d files/directories to %s directory \"%s\"",
  6454. (OperationProgress->Count, TargetSide, TargetDir));
  6455. if (Parallel && DebugAlwaysTrue(Files != NULL))
  6456. {
  6457. int Count = 0;
  6458. for (int Index = 0; Index < Files->Count; Index++)
  6459. {
  6460. TCollectedFileList * FileList = dynamic_cast<TCollectedFileList *>(Files->Objects[Index]);
  6461. Count += FileList->Count();
  6462. }
  6463. S += FORMAT(L" - in parallel, with %d total files", (Count));
  6464. }
  6465. if (OperationProgress->TotalSizeSet)
  6466. {
  6467. S += FORMAT(L" - total size: %s", (FormatSize(OperationProgress->TotalSize)));
  6468. }
  6469. LogEvent(S);
  6470. LogEvent(0, CopyParam->LogStr);
  6471. }
  6472. }
  6473. //---------------------------------------------------------------------------
  6474. void __fastcall TTerminal::LogTotalTransferDone(TFileOperationProgressType * OperationProgress)
  6475. {
  6476. LogEvent(L"Copying finished: " + OperationProgress->GetLogStr(true));
  6477. }
  6478. //---------------------------------------------------------------------------
  6479. bool __fastcall TTerminal::CopyToRemote(
  6480. TStrings * FilesToCopy, const UnicodeString & TargetDir, const TCopyParamType * CopyParam, int Params,
  6481. TParallelOperation * ParallelOperation)
  6482. {
  6483. DebugAssert(FFileSystem);
  6484. DebugAssert(FilesToCopy);
  6485. bool Result = false;
  6486. TOnceDoneOperation OnceDoneOperation = odoIdle;
  6487. if ((CopyParam->OnTransferIn != NULL) && !FFileSystem->IsCapable(fcTransferIn))
  6488. {
  6489. throw Exception(LoadStr(NOTSUPPORTED));
  6490. }
  6491. try
  6492. {
  6493. __int64 Size;
  6494. std::unique_ptr<TStringList> Files;
  6495. bool ACanParallel =
  6496. CanParallel(CopyParam, Params, ParallelOperation) &&
  6497. !CopyParam->ClearArchive;
  6498. if (ACanParallel)
  6499. {
  6500. Files.reset(new TStringList());
  6501. Files->OwnsObjects = true;
  6502. }
  6503. bool CalculatedSize;
  6504. if ((CopyParam->Size >= 0) &&
  6505. DebugAlwaysTrue(!ACanParallel)) // Size is set for sync only and we never use parallel transfer for sync
  6506. {
  6507. Size = CopyParam->Size;
  6508. CalculatedSize = true;
  6509. }
  6510. else
  6511. {
  6512. bool CalculateSize = ACanParallel || CopyParam->CalculateSize;
  6513. CalculatedSize = CalculateLocalFilesSize(FilesToCopy, Size, CopyParam, CalculateSize, Files.get(), NULL);
  6514. }
  6515. FLastProgressLogged = GetTickCount();
  6516. TFileOperationProgressType OperationProgress(&DoProgress, &DoFinished);
  6517. OperationStart(
  6518. OperationProgress, (Params & cpDelete ? foMove : foCopy), osLocal,
  6519. FilesToCopy->Count, Params & cpTemporary, TargetDir, CopyParam->CPSLimit, CopyParam->OnceDoneOperation);
  6520. bool CollectingUsage = false;
  6521. try
  6522. {
  6523. if (CalculatedSize)
  6524. {
  6525. if (Configuration->Usage->Collect)
  6526. {
  6527. int CounterSize = TUsage::CalculateCounterSize(Size);
  6528. Configuration->Usage->Inc(L"Uploads");
  6529. Configuration->Usage->Inc(L"UploadedBytes", CounterSize);
  6530. Configuration->Usage->SetMax(L"MaxUploadSize", CounterSize);
  6531. CollectingUsage = true;
  6532. }
  6533. OperationProgress.SetTotalSize(Size);
  6534. }
  6535. UnicodeString UnlockedTargetDir = TranslateLockedPath(TargetDir, false);
  6536. BeginTransaction();
  6537. try
  6538. {
  6539. bool Parallel = ACanParallel && CalculatedSize;
  6540. LogTotalTransferDetails(TargetDir, CopyParam, &OperationProgress, Parallel, Files.get());
  6541. if (Parallel)
  6542. {
  6543. // OnceDoneOperation is not supported
  6544. ParallelOperation->Init(Files.release(), UnlockedTargetDir, CopyParam, Params, &OperationProgress, Log->Name);
  6545. CopyParallel(ParallelOperation, &OperationProgress);
  6546. }
  6547. else
  6548. {
  6549. FFileSystem->CopyToRemote(FilesToCopy, UnlockedTargetDir,
  6550. CopyParam, Params, &OperationProgress, OnceDoneOperation);
  6551. }
  6552. LogTotalTransferDone(&OperationProgress);
  6553. }
  6554. __finally
  6555. {
  6556. if (Active)
  6557. {
  6558. ReactOnCommand(fsCopyToRemote);
  6559. }
  6560. EndTransaction();
  6561. }
  6562. if (OperationProgress.Cancel == csContinue)
  6563. {
  6564. Result = true;
  6565. }
  6566. }
  6567. __finally
  6568. {
  6569. if (CollectingUsage)
  6570. {
  6571. int CounterTime = TimeToSeconds(OperationProgress.TimeElapsed());
  6572. Configuration->Usage->Inc(L"UploadTime", CounterTime);
  6573. Configuration->Usage->SetMax(L"MaxUploadTime", CounterTime);
  6574. }
  6575. OperationStop(OperationProgress);
  6576. }
  6577. }
  6578. catch (Exception &E)
  6579. {
  6580. CommandError(&E, MainInstructions(LoadStr(TOREMOTE_COPY_ERROR)));
  6581. OnceDoneOperation = odoIdle;
  6582. }
  6583. if (OnceDoneOperation != odoIdle)
  6584. {
  6585. CloseOnCompletion(OnceDoneOperation);
  6586. }
  6587. return Result;
  6588. }
  6589. //---------------------------------------------------------------------------
  6590. void __fastcall TTerminal::DoCopyToRemote(
  6591. TStrings * FilesToCopy, const UnicodeString & ATargetDir, const TCopyParamType * CopyParam, int Params,
  6592. TFileOperationProgressType * OperationProgress, unsigned int Flags, TOnceDoneOperation & OnceDoneOperation)
  6593. {
  6594. DebugAssert((FilesToCopy != NULL) && (OperationProgress != NULL));
  6595. FFileSystem->TransferOnDirectory(ATargetDir, CopyParam, Params);
  6596. // Must be local resolving, as this is outside of robust loop
  6597. UnicodeString TargetDir = AbsolutePath(ATargetDir, true);
  6598. UnicodeString FullTargetDir = UnixIncludeTrailingBackslash(TargetDir);
  6599. int Index = 0;
  6600. while ((Index < FilesToCopy->Count) && !OperationProgress->Cancel)
  6601. {
  6602. bool Success = false;
  6603. UnicodeString FileName = FilesToCopy->Strings[Index];
  6604. TSearchRecSmart * SearchRec = NULL;
  6605. if (FilesToCopy->Objects[Index] != NULL)
  6606. {
  6607. TLocalFile * LocalFile = dynamic_cast<TLocalFile *>(FilesToCopy->Objects[Index]);
  6608. SearchRec = &LocalFile->SearchRec;
  6609. }
  6610. try
  6611. {
  6612. try
  6613. {
  6614. if (SessionData->CacheDirectories)
  6615. {
  6616. DirectoryModified(TargetDir, false);
  6617. if (DirectoryExists(ApiPath(FileName)))
  6618. {
  6619. UnicodeString FileNameOnly = ExtractFileName(FileName);
  6620. DirectoryModified(FullTargetDir + FileNameOnly, true);
  6621. }
  6622. }
  6623. SourceRobust(FileName, SearchRec, FullTargetDir, CopyParam, Params, OperationProgress, Flags | tfFirstLevel);
  6624. Success = true;
  6625. }
  6626. catch (ESkipFile & E)
  6627. {
  6628. TSuspendFileOperationProgress Suspend(OperationProgress);
  6629. if (!HandleException(&E))
  6630. {
  6631. throw;
  6632. }
  6633. }
  6634. }
  6635. __finally
  6636. {
  6637. OperationFinish(OperationProgress, FilesToCopy->Objects[Index], FileName, Success, OnceDoneOperation);
  6638. }
  6639. Index++;
  6640. }
  6641. }
  6642. //---------------------------------------------------------------------------
  6643. void __fastcall TTerminal::SourceRobust(
  6644. const UnicodeString & FileName, const TSearchRecSmart * SearchRec,
  6645. const UnicodeString & TargetDir, const TCopyParamType * CopyParam, int Params,
  6646. TFileOperationProgressType * OperationProgress, unsigned int Flags)
  6647. {
  6648. TUploadSessionAction Action(ActionLog);
  6649. bool * AFileTransferAny = FLAGSET(Flags, tfUseFileTransferAny) ? &FFileTransferAny : NULL;
  6650. bool CanRetry = (CopyParam->OnTransferIn == NULL);
  6651. TRobustOperationLoop RobustLoop(this, OperationProgress, AFileTransferAny, CanRetry);
  6652. do
  6653. {
  6654. bool ChildError = false;
  6655. try
  6656. {
  6657. Source(FileName, SearchRec, TargetDir, CopyParam, Params, OperationProgress, Flags, Action, ChildError);
  6658. }
  6659. catch (Exception & E)
  6660. {
  6661. if (!RobustLoop.TryReopen(E))
  6662. {
  6663. if (!ChildError)
  6664. {
  6665. RollbackAction(Action, OperationProgress, &E);
  6666. }
  6667. throw;
  6668. }
  6669. }
  6670. if (RobustLoop.ShouldRetry())
  6671. {
  6672. OperationProgress->RollbackTransfer();
  6673. Action.Restart();
  6674. // prevent overwrite and resume confirmations (should not be set for directories!)
  6675. Params |= cpNoConfirmation;
  6676. // enable resume even if we are uploading into new directory
  6677. Flags &= ~tfNewDirectory;
  6678. Flags |= tfAutoResume;
  6679. }
  6680. }
  6681. while (RobustLoop.Retry());
  6682. }
  6683. //---------------------------------------------------------------------------
  6684. bool __fastcall TTerminal::CreateTargetDirectory(
  6685. const UnicodeString & DirectoryPath, int Attrs, const TCopyParamType * CopyParam)
  6686. {
  6687. TRemoteFile * File = NULL;
  6688. bool DoCreate =
  6689. !FileExists(DirectoryPath, &File) ||
  6690. !File->IsDirectory; // just try to create and make it fail
  6691. delete File;
  6692. if (DoCreate)
  6693. {
  6694. TRemoteProperties Properties;
  6695. if (CopyParam->PreserveRights)
  6696. {
  6697. Properties.Valid = Properties.Valid << vpRights;
  6698. Properties.Rights = CopyParam->RemoteFileRights(Attrs);
  6699. }
  6700. Properties.Valid = Properties.Valid << vpEncrypt;
  6701. Properties.Encrypt = CopyParam->EncryptNewFiles;
  6702. CreateDirectory(DirectoryPath, &Properties);
  6703. }
  6704. return DoCreate;
  6705. }
  6706. //---------------------------------------------------------------------------
  6707. void __fastcall TTerminal::DirectorySource(
  6708. const UnicodeString & DirectoryName, const UnicodeString & TargetDir, const UnicodeString & DestDirectoryName,
  6709. int Attrs, const TCopyParamType * CopyParam, int Params,
  6710. TFileOperationProgressType * OperationProgress, unsigned int Flags)
  6711. {
  6712. FFileSystem->TransferOnDirectory(TargetDir, CopyParam, Params);
  6713. UnicodeString DestFullName = UnixIncludeTrailingBackslash(TargetDir + DestDirectoryName);
  6714. OperationProgress->SetFile(DirectoryName);
  6715. bool PostCreateDir = FLAGCLEAR(Flags, tfPreCreateDir);
  6716. // WebDAV, SFTP and S3
  6717. if (!PostCreateDir)
  6718. {
  6719. // This is originally a code for WebDAV, SFTP used a slightly different logic,
  6720. // but functionally it should be very similar.
  6721. if (CreateTargetDirectory(DestFullName, Attrs, CopyParam))
  6722. {
  6723. Flags |= tfNewDirectory;
  6724. }
  6725. }
  6726. bool DoRecurse = FLAGCLEAR(Params, cpNoRecurse);
  6727. if (DoRecurse)
  6728. {
  6729. TSearchRecOwned SearchRec;
  6730. bool FindOK = LocalFindFirstLoop(DirectoryName + L"*.*", SearchRec);
  6731. while (FindOK && !OperationProgress->Cancel)
  6732. {
  6733. UnicodeString FileName = DirectoryName + SearchRec.Name;
  6734. try
  6735. {
  6736. if (SearchRec.IsRealFile())
  6737. {
  6738. SourceRobust(FileName, &SearchRec, DestFullName, CopyParam, Params, OperationProgress, (Flags & ~(tfFirstLevel | tfAutoResume)));
  6739. // FTP: if any file got uploaded (i.e. there were any file in the directory and at least one was not skipped),
  6740. // do not try to create the directory, as it should be already created by FZAPI during upload
  6741. PostCreateDir = false;
  6742. }
  6743. }
  6744. catch (ESkipFile &E)
  6745. {
  6746. // If ESkipFile occurs, just log it and continue with next file
  6747. TSuspendFileOperationProgress Suspend(OperationProgress);
  6748. // here a message to user was displayed, which was not appropriate
  6749. // when user refused to overwrite the file in subdirectory.
  6750. // hopefully it won't be missing in other situations.
  6751. if (!HandleException(&E))
  6752. {
  6753. throw;
  6754. }
  6755. }
  6756. FindOK = LocalFindNextLoop(SearchRec);
  6757. }
  6758. SearchRec.Close();
  6759. }
  6760. // FTP
  6761. if (PostCreateDir)
  6762. {
  6763. CreateTargetDirectory(DestFullName, Attrs, CopyParam);
  6764. }
  6765. // Paralell transfers (cpNoRecurse) won't be allowed if any of these are set anyway (see CanParallel).
  6766. // Exception is ClearArchive, which is does not prevent parallel transfer, but is silently ignored for directories.
  6767. if (DoRecurse && !OperationProgress->Cancel)
  6768. {
  6769. // TODO : Delete also read-only directories.
  6770. // TODO : Show error message on failure.
  6771. if (IsCapable[fcPreservingTimestampDirs] && CopyParam->PreserveTime && CopyParam->PreserveTimeDirs)
  6772. {
  6773. TRemoteProperties Properties;
  6774. Properties.Valid << vpModification;
  6775. OpenLocalFile(
  6776. ExcludeTrailingBackslash(DirectoryName), GENERIC_READ, NULL, NULL, NULL,
  6777. &Properties.Modification, &Properties.LastAccess, NULL);
  6778. ChangeFileProperties(DestFullName, NULL, &Properties);
  6779. }
  6780. if (FLAGSET(Params, cpDelete))
  6781. {
  6782. DebugAssert(FLAGCLEAR(Params, cpNoRecurse));
  6783. RemoveDir(ApiPath(DirectoryName));
  6784. }
  6785. else if (CopyParam->ClearArchive && FLAGSET(Attrs, faArchive))
  6786. {
  6787. FILE_OPERATION_LOOP_BEGIN
  6788. {
  6789. THROWOSIFFALSE(FileSetAttr(ApiPath(DirectoryName), Attrs & ~faArchive) == 0);
  6790. }
  6791. FILE_OPERATION_LOOP_END(FMTLOAD(CANT_SET_ATTRS, (DirectoryName)));
  6792. }
  6793. }
  6794. }
  6795. //---------------------------------------------------------------------------
  6796. void __fastcall TTerminal::SelectTransferMode(
  6797. const UnicodeString & BaseFileName, TOperationSide Side, const TCopyParamType * CopyParam,
  6798. const TFileMasks::TParams & MaskParams)
  6799. {
  6800. bool AsciiTransfer = IsCapable[fcTextMode] && CopyParam->UseAsciiTransfer(BaseFileName, Side, MaskParams);
  6801. OperationProgress->SetAsciiTransfer(AsciiTransfer);
  6802. UnicodeString ModeName = (OperationProgress->AsciiTransfer ? L"Ascii" : L"Binary");
  6803. LogEvent(0, FORMAT(L"%s transfer mode selected.", (ModeName)));
  6804. }
  6805. //---------------------------------------------------------------------------
  6806. void __fastcall TTerminal::SelectSourceTransferMode(const TLocalFileHandle & Handle, const TCopyParamType * CopyParam)
  6807. {
  6808. // Will we use ASCII or BINARY file transfer?
  6809. TFileMasks::TParams MaskParams;
  6810. MaskParams.Size = Handle.Size;
  6811. MaskParams.Modification = Handle.Modification;
  6812. UnicodeString BaseFileName = GetBaseFileName(Handle.FileName);
  6813. SelectTransferMode(BaseFileName, osLocal, CopyParam, MaskParams);
  6814. }
  6815. //---------------------------------------------------------------------------
  6816. void __fastcall TTerminal::UpdateSource(const TLocalFileHandle & Handle, const TCopyParamType * CopyParam, int Params)
  6817. {
  6818. // TODO: Delete also read-only files.
  6819. if (FLAGSET(Params, cpDelete))
  6820. {
  6821. if (!Handle.Directory)
  6822. {
  6823. LogEvent(FORMAT(L"Deleting successfully uploaded source file \"%s\".", (Handle.FileName)));
  6824. FILE_OPERATION_LOOP_BEGIN
  6825. {
  6826. THROWOSIFFALSE(Sysutils::DeleteFile(ApiPath(Handle.FileName)));
  6827. }
  6828. FILE_OPERATION_LOOP_END(FMTLOAD(DELETE_LOCAL_FILE_ERROR, (Handle.FileName)));
  6829. }
  6830. }
  6831. else if (CopyParam->ClearArchive && FLAGSET(Handle.Attrs, faArchive))
  6832. {
  6833. FILE_OPERATION_LOOP_BEGIN
  6834. {
  6835. THROWOSIFFALSE(FileSetAttr(ApiPath(Handle.FileName), (Handle.Attrs & ~faArchive)) == 0);
  6836. }
  6837. FILE_OPERATION_LOOP_END(FMTLOAD(CANT_SET_ATTRS, (Handle.FileName)));
  6838. }
  6839. }
  6840. //---------------------------------------------------------------------------
  6841. void __fastcall TTerminal::Source(
  6842. const UnicodeString & FileName, const TSearchRecSmart * SearchRec,
  6843. const UnicodeString & TargetDir, const TCopyParamType * CopyParam, int Params,
  6844. TFileOperationProgressType * OperationProgress, unsigned int Flags, TUploadSessionAction & Action, bool & ChildError)
  6845. {
  6846. UnicodeString ActionFileName = FileName;
  6847. if (CopyParam->OnTransferIn == NULL)
  6848. {
  6849. ActionFileName = ExpandUNCFileName(ActionFileName);
  6850. }
  6851. Action.FileName(ActionFileName);
  6852. OperationProgress->SetFile(FileName, false);
  6853. if (!AllowLocalFileTransfer(FileName, SearchRec, CopyParam, OperationProgress))
  6854. {
  6855. throw ESkipFile();
  6856. }
  6857. TLocalFileHandle Handle;
  6858. if (CopyParam->OnTransferIn == NULL)
  6859. {
  6860. OpenLocalFile(FileName, GENERIC_READ, Handle);
  6861. }
  6862. else
  6863. {
  6864. Handle.FileName = FileName;
  6865. }
  6866. OperationProgress->SetFileInProgress();
  6867. UnicodeString DestFileName =
  6868. ChangeFileName(CopyParam, ExtractFileName(FileName), osLocal, FLAGSET(Flags, tfFirstLevel));
  6869. if (Handle.Directory)
  6870. {
  6871. Action.Cancel();
  6872. DirectorySource(
  6873. IncludeTrailingBackslash(FileName), TargetDir, DestFileName, Handle.Attrs,
  6874. CopyParam, Params, OperationProgress, Flags);
  6875. }
  6876. else
  6877. {
  6878. if (CopyParam->OnTransferIn != NULL)
  6879. {
  6880. LogEvent(FORMAT(L"Streaming \"%s\" to remote directory started.", (FileName)));
  6881. }
  6882. else
  6883. {
  6884. LogEvent(FORMAT(L"Copying \"%s\" to remote directory started.", (FileName)));
  6885. OperationProgress->SetLocalSize(Handle.Size);
  6886. // Suppose same data size to transfer as to read
  6887. // (not true with ASCII transfer)
  6888. OperationProgress->SetTransferSize(OperationProgress->LocalSize);
  6889. }
  6890. if (IsCapable[fcTextMode])
  6891. {
  6892. SelectSourceTransferMode(Handle, CopyParam);
  6893. }
  6894. FFileSystem->Source(
  6895. Handle, TargetDir, DestFileName, CopyParam, Params, OperationProgress, Flags, Action, ChildError);
  6896. LogFileDone(OperationProgress, AbsolutePath(TargetDir + DestFileName, true));
  6897. OperationProgress->Succeeded();
  6898. }
  6899. Handle.Release();
  6900. UpdateSource(Handle, CopyParam, Params);
  6901. }
  6902. //---------------------------------------------------------------------------
  6903. bool __fastcall TTerminal::CopyToLocal(
  6904. TStrings * FilesToCopy, const UnicodeString & TargetDir, const TCopyParamType * CopyParam, int Params,
  6905. TParallelOperation * ParallelOperation)
  6906. {
  6907. DebugAssert(FFileSystem);
  6908. // see scp.c: sink(), tolocal()
  6909. bool Result = false;
  6910. DebugAssert(FilesToCopy != NULL);
  6911. TOnceDoneOperation OnceDoneOperation = odoIdle;
  6912. if ((CopyParam->OnTransferOut != NULL) && !FFileSystem->IsCapable(fcTransferOut))
  6913. {
  6914. throw Exception(LoadStr(NOTSUPPORTED));
  6915. }
  6916. FDestFileName = L"";
  6917. FMultipleDestinationFiles = false;
  6918. BeginTransaction();
  6919. try
  6920. {
  6921. __int64 TotalSize;
  6922. bool TotalSizeKnown = false;
  6923. FLastProgressLogged = GetTickCount();
  6924. TFileOperationProgressType OperationProgress(&DoProgress, &DoFinished);
  6925. std::unique_ptr<TStringList> Files;
  6926. bool ACanParallel = CanParallel(CopyParam, Params, ParallelOperation);
  6927. if (ACanParallel)
  6928. {
  6929. Files.reset(new TStringList());
  6930. Files->OwnsObjects = true;
  6931. }
  6932. if ((CopyParam->Size >= 0) &&
  6933. DebugAlwaysTrue(!ACanParallel)) // Size is set for sync only and we never use parallel transfer for sync
  6934. {
  6935. TotalSize = CopyParam->Size;
  6936. TotalSizeKnown = true;
  6937. }
  6938. else
  6939. {
  6940. ExceptionOnFail = true;
  6941. try
  6942. {
  6943. TCalculateSizeStats Stats;
  6944. Stats.FoundFiles = Files.get();
  6945. bool CalculateSize = ACanParallel || CopyParam->CalculateSize;
  6946. if (CalculateFilesSize(FilesToCopy, TotalSize, csIgnoreErrors, CopyParam, CalculateSize, Stats))
  6947. {
  6948. TotalSizeKnown = true;
  6949. }
  6950. }
  6951. __finally
  6952. {
  6953. ExceptionOnFail = false;
  6954. }
  6955. }
  6956. OperationStart(OperationProgress, (Params & cpDelete ? foMove : foCopy), osRemote,
  6957. FilesToCopy->Count, Params & cpTemporary, TargetDir, CopyParam->CPSLimit, CopyParam->OnceDoneOperation);
  6958. bool CollectingUsage = false;
  6959. try
  6960. {
  6961. if (TotalSizeKnown)
  6962. {
  6963. if (Configuration->Usage->Collect)
  6964. {
  6965. int CounterTotalSize = TUsage::CalculateCounterSize(TotalSize);
  6966. Configuration->Usage->Inc(L"Downloads");
  6967. Configuration->Usage->Inc(L"DownloadedBytes", CounterTotalSize);
  6968. Configuration->Usage->SetMax(L"MaxDownloadSize", CounterTotalSize);
  6969. CollectingUsage = true;
  6970. }
  6971. OperationProgress.SetTotalSize(TotalSize);
  6972. }
  6973. try
  6974. {
  6975. try
  6976. {
  6977. bool Parallel = ACanParallel && TotalSizeKnown;
  6978. LogTotalTransferDetails(TargetDir, CopyParam, &OperationProgress, Parallel, Files.get());
  6979. if (Parallel)
  6980. {
  6981. // OnceDoneOperation is not supported
  6982. ParallelOperation->Init(Files.release(), TargetDir, CopyParam, Params, &OperationProgress, Log->Name);
  6983. CopyParallel(ParallelOperation, &OperationProgress);
  6984. }
  6985. else
  6986. {
  6987. FFileSystem->CopyToLocal(FilesToCopy, TargetDir, CopyParam, Params,
  6988. &OperationProgress, OnceDoneOperation);
  6989. }
  6990. LogTotalTransferDone(&OperationProgress);
  6991. }
  6992. __finally
  6993. {
  6994. if (Active)
  6995. {
  6996. ReactOnCommand(fsCopyToLocal);
  6997. }
  6998. }
  6999. }
  7000. catch (Exception &E)
  7001. {
  7002. CommandError(&E, MainInstructions(LoadStr(TOLOCAL_COPY_ERROR)));
  7003. OnceDoneOperation = odoIdle;
  7004. }
  7005. if (OperationProgress.Cancel == csContinue)
  7006. {
  7007. Result = true;
  7008. }
  7009. }
  7010. __finally
  7011. {
  7012. if (CollectingUsage)
  7013. {
  7014. int CounterTime = TimeToSeconds(OperationProgress.TimeElapsed());
  7015. Configuration->Usage->Inc(L"DownloadTime", CounterTime);
  7016. Configuration->Usage->SetMax(L"MaxDownloadTime", CounterTime);
  7017. }
  7018. OperationStop(OperationProgress);
  7019. }
  7020. }
  7021. __finally
  7022. {
  7023. // If session is still active (no fatal error) we reload directory
  7024. // by calling EndTransaction
  7025. EndTransaction();
  7026. }
  7027. if (OnceDoneOperation != odoIdle)
  7028. {
  7029. UnicodeString DestFileName;
  7030. if (!FMultipleDestinationFiles)
  7031. {
  7032. DestFileName = FDestFileName;
  7033. }
  7034. CloseOnCompletion(OnceDoneOperation, UnicodeString(), TargetDir, DestFileName);
  7035. }
  7036. return Result;
  7037. }
  7038. //---------------------------------------------------------------------------
  7039. void __fastcall TTerminal::DoCopyToLocal(
  7040. TStrings * FilesToCopy, const UnicodeString & TargetDir, const TCopyParamType * CopyParam, int Params,
  7041. TFileOperationProgressType * OperationProgress, unsigned int Flags, TOnceDoneOperation & OnceDoneOperation)
  7042. {
  7043. DebugAssert((FilesToCopy != NULL) && (OperationProgress != NULL));
  7044. UnicodeString FullTargetDir = IncludeTrailingBackslash(TargetDir);
  7045. int Index = 0;
  7046. while ((Index < FilesToCopy->Count) && !OperationProgress->Cancel)
  7047. {
  7048. bool Success = false;
  7049. UnicodeString FileName = FilesToCopy->Strings[Index];
  7050. const TRemoteFile * File = dynamic_cast<const TRemoteFile *>(FilesToCopy->Objects[Index]);
  7051. try
  7052. {
  7053. try
  7054. {
  7055. UnicodeString AbsoluteFileName = AbsolutePath(FileName, true);
  7056. SinkRobust(AbsoluteFileName, File, FullTargetDir, CopyParam, Params, OperationProgress, Flags | tfFirstLevel);
  7057. Success = true;
  7058. }
  7059. catch (ESkipFile & E)
  7060. {
  7061. TSuspendFileOperationProgress Suspend(OperationProgress);
  7062. if (!HandleException(&E))
  7063. {
  7064. throw;
  7065. }
  7066. }
  7067. }
  7068. __finally
  7069. {
  7070. OperationFinish(OperationProgress, File, FileName, Success, OnceDoneOperation);
  7071. }
  7072. Index++;
  7073. }
  7074. }
  7075. //---------------------------------------------------------------------------
  7076. void __fastcall TTerminal::SinkRobust(
  7077. const UnicodeString & FileName, const TRemoteFile * File, const UnicodeString & TargetDir,
  7078. const TCopyParamType * CopyParam, int Params, TFileOperationProgressType * OperationProgress, unsigned int Flags)
  7079. {
  7080. TDownloadSessionAction Action(ActionLog);
  7081. try
  7082. {
  7083. bool * AFileTransferAny = FLAGSET(Flags, tfUseFileTransferAny) ? &FFileTransferAny : NULL;
  7084. bool CanRetry = (CopyParam->OnTransferOut == NULL);
  7085. TRobustOperationLoop RobustLoop(this, OperationProgress, AFileTransferAny, CanRetry);
  7086. bool Sunk = false;
  7087. do
  7088. {
  7089. try
  7090. {
  7091. // If connection is lost while deleting the file, so not retry download on the next round.
  7092. // The file may not exist anymore and the download attempt might overwrite the (only) local copy.
  7093. if (!Sunk)
  7094. {
  7095. Sink(FileName, File, TargetDir, CopyParam, Params, OperationProgress, Flags, Action);
  7096. Sunk = true;
  7097. }
  7098. if (FLAGSET(Params, cpDelete))
  7099. {
  7100. DebugAssert(FLAGCLEAR(Params, cpNoRecurse));
  7101. // If file is directory, do not delete it recursively, because it should be
  7102. // empty already. If not, it should not be deleted (some files were
  7103. // skipped or some new files were copied to it, while we were downloading)
  7104. int Params = dfNoRecursive;
  7105. DeleteFile(FileName, File, &Params);
  7106. }
  7107. }
  7108. catch (Exception & E)
  7109. {
  7110. if (!RobustLoop.TryReopen(E))
  7111. {
  7112. if (!Sunk)
  7113. {
  7114. RollbackAction(Action, OperationProgress, &E);
  7115. }
  7116. throw;
  7117. }
  7118. }
  7119. if (RobustLoop.ShouldRetry())
  7120. {
  7121. OperationProgress->RollbackTransfer();
  7122. Action.Restart();
  7123. DebugAssert(File != NULL);
  7124. if (!File->IsDirectory)
  7125. {
  7126. // prevent overwrite and resume confirmations
  7127. Params |= cpNoConfirmation;
  7128. Flags |= tfAutoResume;
  7129. }
  7130. }
  7131. }
  7132. while (RobustLoop.Retry());
  7133. }
  7134. __finally
  7135. {
  7136. // Once we issue <download> we must terminate the data stream
  7137. if (Action.IsValid() && (CopyParam->OnTransferOut != NULL) && DebugAlwaysTrue(IsCapable[fcTransferOut]))
  7138. {
  7139. CopyParam->OnTransferOut(this, NULL, 0);
  7140. }
  7141. }
  7142. }
  7143. //---------------------------------------------------------------------------
  7144. struct TSinkFileParams
  7145. {
  7146. UnicodeString TargetDir;
  7147. const TCopyParamType * CopyParam;
  7148. int Params;
  7149. TFileOperationProgressType * OperationProgress;
  7150. bool Skipped;
  7151. unsigned int Flags;
  7152. };
  7153. //---------------------------------------------------------------------------
  7154. void __fastcall TTerminal::Sink(
  7155. const UnicodeString & FileName, const TRemoteFile * File, const UnicodeString & TargetDir,
  7156. const TCopyParamType * CopyParam, int Params, TFileOperationProgressType * OperationProgress, unsigned int Flags,
  7157. TDownloadSessionAction & Action)
  7158. {
  7159. Action.FileName(FileName);
  7160. DebugAssert(File);
  7161. if (!DoAllowRemoteFileTransfer(File, CopyParam, false))
  7162. {
  7163. LogEvent(FORMAT(L"File \"%s\" excluded from transfer", (FileName)));
  7164. throw ESkipFile();
  7165. }
  7166. if (CopyParam->SkipTransfer(FileName, File->IsDirectory))
  7167. {
  7168. OperationProgress->AddSkippedFileSize(File->Resolve()->Size);
  7169. throw ESkipFile();
  7170. }
  7171. LogFileDetails(FileName, File->Modification, File->Size, File->LinkedFile);
  7172. OperationProgress->SetFile(FileName);
  7173. UnicodeString OnlyFileName = UnixExtractFileName(FileName);
  7174. UnicodeString DestFileName = ChangeFileName(CopyParam, OnlyFileName, osRemote, FLAGSET(Flags, tfFirstLevel));
  7175. UnicodeString DestFullName = TargetDir + DestFileName;
  7176. if (File->IsDirectory)
  7177. {
  7178. Action.Cancel();
  7179. if (CanRecurseToDirectory(File))
  7180. {
  7181. FILE_OPERATION_LOOP_BEGIN
  7182. {
  7183. int Attrs = FileGetAttrFix(ApiPath(DestFullName));
  7184. if (FLAGCLEAR(Attrs, faDirectory))
  7185. {
  7186. EXCEPTION;
  7187. }
  7188. }
  7189. FILE_OPERATION_LOOP_END(FMTLOAD(NOT_DIRECTORY_ERROR, (DestFullName)));
  7190. FILE_OPERATION_LOOP_BEGIN
  7191. {
  7192. THROWOSIFFALSE(ForceDirectories(ApiPath(DestFullName)));
  7193. }
  7194. FILE_OPERATION_LOOP_END(FMTLOAD(CREATE_DIR_ERROR, (DestFullName)));
  7195. if (FLAGCLEAR(Params, cpNoRecurse))
  7196. {
  7197. TSinkFileParams SinkFileParams;
  7198. SinkFileParams.TargetDir = IncludeTrailingBackslash(DestFullName);
  7199. SinkFileParams.CopyParam = CopyParam;
  7200. SinkFileParams.Params = Params;
  7201. SinkFileParams.OperationProgress = OperationProgress;
  7202. SinkFileParams.Skipped = false;
  7203. SinkFileParams.Flags = Flags & ~(tfFirstLevel | tfAutoResume);
  7204. ProcessDirectory(FileName, SinkFile, &SinkFileParams);
  7205. FFileSystem->DirectorySunk(DestFullName, File, CopyParam);
  7206. // Do not delete directory if some of its files were skip.
  7207. // Throw "skip file" for the directory to avoid attempt to deletion
  7208. // of any parent directory
  7209. if (FLAGSET(Params, cpDelete) && SinkFileParams.Skipped)
  7210. {
  7211. throw ESkipFile();
  7212. }
  7213. }
  7214. }
  7215. else
  7216. {
  7217. LogEvent(FORMAT(L"Skipping symlink to directory \"%s\".", (FileName)));
  7218. }
  7219. }
  7220. else
  7221. {
  7222. if (CopyParam->OnTransferOut != NULL)
  7223. {
  7224. LogEvent(FORMAT(L"Streaming \"%s\" to local machine started.", (FileName)));
  7225. }
  7226. else
  7227. {
  7228. LogEvent(FORMAT(L"Copying \"%s\" to local directory started.", (FileName)));
  7229. }
  7230. // Will we use ASCII or BINARY file transfer?
  7231. UnicodeString BaseFileName = GetBaseFileName(FileName);
  7232. const TRemoteFile * UltimateFile = File->Resolve();
  7233. TFileMasks::TParams MaskParams;
  7234. MaskParams.Size = UltimateFile->Size;
  7235. MaskParams.Modification = File->Modification;
  7236. SelectTransferMode(BaseFileName, osRemote, CopyParam, MaskParams);
  7237. // Suppose same data size to transfer as to write
  7238. // (not true with ASCII transfer)
  7239. __int64 TransferSize = UltimateFile->Size;
  7240. OperationProgress->SetLocalSize(TransferSize);
  7241. if (IsFileEncrypted(FileName))
  7242. {
  7243. TransferSize += TEncryption::GetOverhead();
  7244. }
  7245. OperationProgress->SetTransferSize(TransferSize);
  7246. int Attrs;
  7247. UnicodeString LogFileName;
  7248. if (CopyParam->OnTransferOut != NULL)
  7249. {
  7250. Attrs = -1;
  7251. LogFileName = L"-";
  7252. }
  7253. else
  7254. {
  7255. FILE_OPERATION_LOOP_BEGIN
  7256. {
  7257. Attrs = FileGetAttrFix(ApiPath(DestFullName));
  7258. if ((Attrs >= 0) && FLAGSET(Attrs, faDirectory))
  7259. {
  7260. EXCEPTION;
  7261. }
  7262. }
  7263. FILE_OPERATION_LOOP_END(FMTLOAD(NOT_FILE_ERROR, (DestFullName)));
  7264. LogFileName = ExpandUNCFileName(DestFullName);
  7265. }
  7266. FFileSystem->Sink(
  7267. FileName, File, TargetDir, DestFileName, Attrs, CopyParam, Params, OperationProgress, Flags, Action);
  7268. LogFileDone(OperationProgress, LogFileName);
  7269. OperationProgress->Succeeded();
  7270. }
  7271. }
  7272. //---------------------------------------------------------------------------
  7273. void __fastcall TTerminal::UpdateTargetAttrs(
  7274. const UnicodeString & DestFullName, const TRemoteFile * File, const TCopyParamType * CopyParam, int Attrs)
  7275. {
  7276. if (Attrs == -1)
  7277. {
  7278. Attrs = faArchive;
  7279. }
  7280. int NewAttrs = CopyParam->LocalFileAttrs(*File->Rights);
  7281. if ((NewAttrs & Attrs) != NewAttrs)
  7282. {
  7283. FILE_OPERATION_LOOP_BEGIN
  7284. {
  7285. THROWOSIFFALSE(FileSetAttr(ApiPath(DestFullName), Attrs | NewAttrs) == 0);
  7286. }
  7287. FILE_OPERATION_LOOP_END(FMTLOAD(CANT_SET_ATTRS, (DestFullName)));
  7288. }
  7289. }
  7290. //---------------------------------------------------------------------------
  7291. void __fastcall TTerminal::UpdateTargetTime(HANDLE Handle, TDateTime Modification, TDSTMode DSTMode)
  7292. {
  7293. LogEvent(FORMAT(L"Preserving timestamp [%s]", (StandardTimestamp(Modification))));
  7294. FILETIME WrTime = DateTimeToFileTime(Modification, DSTMode);
  7295. if (!SetFileTime(Handle, NULL, NULL, &WrTime))
  7296. {
  7297. int Error = GetLastError();
  7298. LogEvent(FORMAT(L"Preserving timestamp failed, ignoring: %s", (SysErrorMessageForError(Error))));
  7299. }
  7300. }
  7301. //---------------------------------------------------------------------------
  7302. void __fastcall TTerminal::SinkFile(UnicodeString FileName, const TRemoteFile * File, void * Param)
  7303. {
  7304. TSinkFileParams * Params = static_cast<TSinkFileParams *>(Param);
  7305. DebugAssert(Params->OperationProgress != NULL);
  7306. try
  7307. {
  7308. SinkRobust(FileName, File, Params->TargetDir, Params->CopyParam,
  7309. Params->Params, Params->OperationProgress, Params->Flags);
  7310. }
  7311. catch (ESkipFile & E)
  7312. {
  7313. Params->Skipped = true;
  7314. {
  7315. TSuspendFileOperationProgress Suspend(Params->OperationProgress);
  7316. if (!HandleException(&E))
  7317. {
  7318. throw;
  7319. }
  7320. }
  7321. if (Params->OperationProgress->Cancel)
  7322. {
  7323. Abort();
  7324. }
  7325. }
  7326. }
  7327. //---------------------------------------------------------------------------
  7328. void __fastcall TTerminal::ReflectSettings()
  7329. {
  7330. DebugAssert(FLog != NULL);
  7331. FLog->ReflectSettings();
  7332. DebugAssert(FActionLog != NULL);
  7333. FActionLog->ReflectSettings();
  7334. // also FTunnelLog ?
  7335. }
  7336. //---------------------------------------------------------------------------
  7337. void __fastcall TTerminal::CollectUsage()
  7338. {
  7339. switch (SessionData->FSProtocol)
  7340. {
  7341. case fsSCPonly:
  7342. Configuration->Usage->Inc(L"OpenedSessionsSCP");
  7343. break;
  7344. case fsSFTP:
  7345. case fsSFTPonly:
  7346. Configuration->Usage->Inc(L"OpenedSessionsSFTP");
  7347. break;
  7348. case fsFTP:
  7349. if (SessionData->Ftps == ftpsNone)
  7350. {
  7351. Configuration->Usage->Inc(L"OpenedSessionsFTP");
  7352. }
  7353. else
  7354. {
  7355. Configuration->Usage->Inc(L"OpenedSessionsFTPS");
  7356. }
  7357. break;
  7358. case fsWebDAV:
  7359. if (SessionData->Ftps == ftpsNone)
  7360. {
  7361. Configuration->Usage->Inc(L"OpenedSessionsWebDAV");
  7362. }
  7363. else
  7364. {
  7365. Configuration->Usage->Inc(L"OpenedSessionsWebDAVS");
  7366. }
  7367. break;
  7368. case fsS3:
  7369. Configuration->Usage->Inc(L"OpenedSessionsS3");
  7370. break;
  7371. }
  7372. if (Configuration->Logging && Configuration->LogToFile)
  7373. {
  7374. Configuration->Usage->Inc(L"OpenedSessionsLogToFile2");
  7375. }
  7376. if (Configuration->LogActions)
  7377. {
  7378. Configuration->Usage->Inc(L"OpenedSessionsXmlLog");
  7379. }
  7380. std::unique_ptr<TSessionData> FactoryDefaults(new TSessionData(L""));
  7381. if (!SessionData->IsSame(FactoryDefaults.get(), true))
  7382. {
  7383. Configuration->Usage->Inc(L"OpenedSessionsAdvanced");
  7384. }
  7385. if (SessionData->ProxyMethod != ::pmNone)
  7386. {
  7387. Configuration->Usage->Inc(L"OpenedSessionsProxy");
  7388. }
  7389. if (SessionData->FtpProxyLogonType > 0)
  7390. {
  7391. Configuration->Usage->Inc(L"OpenedSessionsFtpProxy");
  7392. }
  7393. if (IsEncryptingFiles())
  7394. {
  7395. Configuration->Usage->Inc(L"OpenedSessionsEncrypted");
  7396. }
  7397. FCollectFileSystemUsage = true;
  7398. }
  7399. //---------------------------------------------------------------------------
  7400. static UnicodeString __fastcall FormatCertificateData(const UnicodeString & Fingerprint, int Failures)
  7401. {
  7402. return FORMAT(L"%s;%2.2X", (Fingerprint, Failures));
  7403. }
  7404. //---------------------------------------------------------------------------
  7405. bool __fastcall TTerminal::VerifyCertificate(
  7406. const UnicodeString & CertificateStorageKey, const UnicodeString & SiteKey,
  7407. const UnicodeString & FingerprintSHA1, const UnicodeString & FingerprintSHA256,
  7408. const UnicodeString & CertificateSubject, int Failures)
  7409. {
  7410. bool Result = false;
  7411. UnicodeString CertificateDataSHA1 = FormatCertificateData(FingerprintSHA1, Failures);
  7412. UnicodeString CertificateDataSHA256 = FormatCertificateData(FingerprintSHA256, Failures);
  7413. std::unique_ptr<THierarchicalStorage> Storage(Configuration->CreateConfigStorage());
  7414. Storage->AccessMode = smRead;
  7415. if (Storage->OpenSubKey(CertificateStorageKey, false))
  7416. {
  7417. if (Storage->ValueExists(SiteKey))
  7418. {
  7419. UnicodeString CachedCertificateData = Storage->ReadString(SiteKey, L"");
  7420. if (SameChecksum(CertificateDataSHA1, CachedCertificateData, false) ||
  7421. SameChecksum(CertificateDataSHA256, CachedCertificateData, false))
  7422. {
  7423. LogEvent(FORMAT(L"Certificate for \"%s\" matches cached fingerprint and failures", (CertificateSubject)));
  7424. Result = true;
  7425. }
  7426. }
  7427. else if (Storage->ValueExists(FingerprintSHA1) || Storage->ValueExists(FingerprintSHA256))
  7428. {
  7429. LogEvent(FORMAT(L"Certificate for \"%s\" matches legacy cached fingerprint", (CertificateSubject)));
  7430. Result = true;
  7431. }
  7432. }
  7433. if (!Result)
  7434. {
  7435. UnicodeString Buf = SessionData->HostKey;
  7436. while (!Result && !Buf.IsEmpty())
  7437. {
  7438. UnicodeString ExpectedKey = CutToChar(Buf, L';', false);
  7439. if (ExpectedKey == L"*")
  7440. {
  7441. UnicodeString Message = LoadStr(ANY_CERTIFICATE);
  7442. Information(Message, true);
  7443. Log->Add(llException, Message);
  7444. Result = true;
  7445. }
  7446. else if (SameChecksum(ExpectedKey, FingerprintSHA1, false) ||
  7447. SameChecksum(ExpectedKey, FingerprintSHA256, false))
  7448. {
  7449. LogEvent(FORMAT(L"Certificate for \"%s\" matches configured fingerprint", (CertificateSubject)));
  7450. Result = true;
  7451. }
  7452. }
  7453. }
  7454. return Result;
  7455. }
  7456. //---------------------------------------------------------------------------
  7457. bool __fastcall TTerminal::ConfirmCertificate(
  7458. TSessionInfo & SessionInfo, int Failures, const UnicodeString & CertificateStorageKey, bool CanRemember)
  7459. {
  7460. TClipboardHandler ClipboardHandler;
  7461. ClipboardHandler.Text =
  7462. FORMAT(L"SHA-256: %s\nSHA-1: %s", (SessionInfo.CertificateFingerprintSHA256, SessionInfo.CertificateFingerprintSHA1));
  7463. TQueryButtonAlias Aliases[1];
  7464. Aliases[0].Button = qaRetry;
  7465. Aliases[0].Alias = LoadStr(COPY_KEY_BUTTON);
  7466. Aliases[0].ActionAlias = LoadStr(COPY_CERTIFICATE_ACTION);
  7467. Aliases[0].OnSubmit = &ClipboardHandler.Copy;
  7468. TQueryParams Params(qpWaitInBatch);
  7469. Params.HelpKeyword = HELP_VERIFY_CERTIFICATE;
  7470. Params.NoBatchAnswers = qaYes | qaRetry;
  7471. Params.Aliases = Aliases;
  7472. Params.AliasesCount = LENOF(Aliases);
  7473. unsigned int Answer =
  7474. QueryUser(
  7475. FMTLOAD(VERIFY_CERT_PROMPT3, (SessionInfo.Certificate)),
  7476. NULL, qaYes | qaNo | qaCancel | qaRetry, &Params, qtWarning);
  7477. bool Result;
  7478. switch (Answer)
  7479. {
  7480. case qaYes:
  7481. CacheCertificate(
  7482. CertificateStorageKey, SessionData->SiteKey,
  7483. SessionInfo.CertificateFingerprintSHA1, SessionInfo.CertificateFingerprintSHA256, Failures);
  7484. Result = true;
  7485. break;
  7486. case qaNo:
  7487. Result = true;
  7488. break;
  7489. case qaCancel:
  7490. Configuration->Usage->Inc(L"HostNotVerified");
  7491. Result = false;
  7492. break;
  7493. default:
  7494. DebugFail();
  7495. Result = false;
  7496. break;
  7497. }
  7498. // Cache only if the certificate was accepted manually
  7499. if (Result && CanRemember)
  7500. {
  7501. Configuration->RememberLastFingerprint(
  7502. SessionData->SiteKey, TlsFingerprintType, SessionInfo.CertificateFingerprintSHA256);
  7503. }
  7504. return Result;
  7505. }
  7506. //---------------------------------------------------------------------------
  7507. void __fastcall TTerminal::CacheCertificate(
  7508. const UnicodeString & CertificateStorageKey, const UnicodeString & SiteKey,
  7509. const UnicodeString & DebugUsedArg(FingerprintSHA1), const UnicodeString & FingerprintSHA256, int Failures)
  7510. {
  7511. UnicodeString CertificateData = FormatCertificateData(FingerprintSHA256, Failures);
  7512. std::unique_ptr<THierarchicalStorage> Storage(Configuration->CreateConfigStorage());
  7513. Storage->AccessMode = smReadWrite;
  7514. if (Storage->OpenSubKey(CertificateStorageKey, true))
  7515. {
  7516. Storage->WriteString(SiteKey, CertificateData);
  7517. }
  7518. }
  7519. //---------------------------------------------------------------------------
  7520. void __fastcall TTerminal::CollectTlsUsage(const UnicodeString & TlsVersionStr)
  7521. {
  7522. // see SSL_get_version() in OpenSSL ssl_lib.c
  7523. if (TlsVersionStr == L"TLSv1.3")
  7524. {
  7525. Configuration->Usage->Inc(L"OpenedSessionsTLS13");
  7526. }
  7527. else if (TlsVersionStr == L"TLSv1.2")
  7528. {
  7529. Configuration->Usage->Inc(L"OpenedSessionsTLS12");
  7530. }
  7531. else if (TlsVersionStr == L"TLSv1.1")
  7532. {
  7533. Configuration->Usage->Inc(L"OpenedSessionsTLS11");
  7534. }
  7535. else if (TlsVersionStr == L"TLSv1")
  7536. {
  7537. Configuration->Usage->Inc(L"OpenedSessionsTLS10");
  7538. }
  7539. else if (TlsVersionStr == L"SSLv3")
  7540. {
  7541. Configuration->Usage->Inc(L"OpenedSessionsSSL30");
  7542. }
  7543. else if (TlsVersionStr == L"SSLv2")
  7544. {
  7545. Configuration->Usage->Inc(L"OpenedSessionsSSL20");
  7546. }
  7547. else
  7548. {
  7549. DebugFail();
  7550. }
  7551. }
  7552. //---------------------------------------------------------------------------
  7553. bool __fastcall TTerminal::LoadTlsCertificate(X509 *& Certificate, EVP_PKEY *& PrivateKey)
  7554. {
  7555. bool Result = !SessionData->TlsCertificateFile.IsEmpty();
  7556. if (Result)
  7557. {
  7558. UnicodeString Passphrase = SessionData->Passphrase;
  7559. // Inspired by neon's ne_ssl_clicert_read
  7560. bool Retry;
  7561. do
  7562. {
  7563. Retry = false;
  7564. bool WrongPassphrase;
  7565. ParseCertificate(SessionData->TlsCertificateFile, Passphrase, Certificate, PrivateKey, WrongPassphrase);
  7566. if (WrongPassphrase)
  7567. {
  7568. if (Passphrase.IsEmpty())
  7569. {
  7570. LogEvent(L"Certificate is encrypted, need passphrase");
  7571. Information(LoadStr(CLIENT_CERTIFICATE_LOADING), false);
  7572. }
  7573. else
  7574. {
  7575. Information(LoadStr(CERTIFICATE_DECODE_ERROR_INFO), false);
  7576. }
  7577. Passphrase = L"";
  7578. if (PromptUser(
  7579. SessionData, pkPassphrase,
  7580. LoadStr(CERTIFICATE_PASSPHRASE_TITLE), L"",
  7581. LoadStr(CERTIFICATE_PASSPHRASE_PROMPT), false, 0, Passphrase))
  7582. {
  7583. Retry = true;
  7584. }
  7585. else
  7586. {
  7587. Result = false;
  7588. }
  7589. }
  7590. }
  7591. while (Retry);
  7592. }
  7593. return Result;
  7594. }
  7595. //---------------------------------------------------------------------------
  7596. UnicodeString __fastcall TTerminal::GetBaseFileName(UnicodeString FileName)
  7597. {
  7598. if (FSessionData->TrimVMSVersions)
  7599. {
  7600. int P = FileName.LastDelimiter(L";");
  7601. if (P > 0)
  7602. {
  7603. FileName.SetLength(P - 1);
  7604. }
  7605. }
  7606. return FileName;
  7607. }
  7608. //---------------------------------------------------------------------------
  7609. UnicodeString __fastcall TTerminal::ChangeFileName(const TCopyParamType * CopyParam,
  7610. UnicodeString FileName, TOperationSide Side, bool FirstLevel)
  7611. {
  7612. FileName = GetBaseFileName(FileName);
  7613. FileName = CopyParam->ChangeFileName(FileName, Side, FirstLevel);
  7614. return FileName;
  7615. }
  7616. //---------------------------------------------------------------------------
  7617. bool __fastcall TTerminal::CanRecurseToDirectory(const TRemoteFile * File)
  7618. {
  7619. return !File->IsSymLink || FSessionData->FollowDirectorySymlinks;
  7620. }
  7621. //---------------------------------------------------------------------------
  7622. TTerminal::TEncryptedFileNames::const_iterator __fastcall TTerminal::GetEncryptedFileName(const UnicodeString & Path)
  7623. {
  7624. UnicodeString FileDir = UnixExtractFileDir(Path);
  7625. // If we haven't been in this folder yet, read it to collect mapping to encrypted file names.
  7626. if (FFoldersScannedForEncryptedFiles.find(FileDir) == FFoldersScannedForEncryptedFiles.end())
  7627. {
  7628. try
  7629. {
  7630. delete DoReadDirectoryListing(FileDir, true);
  7631. }
  7632. catch (Exception & E)
  7633. {
  7634. if (!Active)
  7635. {
  7636. throw;
  7637. }
  7638. if (FEncryptedFileNames.find(Path) == FEncryptedFileNames.end())
  7639. {
  7640. FEncryptedFileNames.insert(std::make_pair(Path, UnixExtractFileName(Path)));
  7641. LogEvent(2, FORMAT(L"Name of file '%s' assumed not to be encrypted", (Path)));
  7642. }
  7643. }
  7644. FFoldersScannedForEncryptedFiles.insert(FileDir);
  7645. }
  7646. TEncryptedFileNames::const_iterator Result = FEncryptedFileNames.find(Path);
  7647. return Result;
  7648. }
  7649. //---------------------------------------------------------------------------
  7650. bool __fastcall TTerminal::IsFileEncrypted(const UnicodeString & Path, bool EncryptNewFiles)
  7651. {
  7652. // can be optimized
  7653. bool Result = (EncryptFileName(Path, EncryptNewFiles) != Path);
  7654. return Result;
  7655. }
  7656. //---------------------------------------------------------------------------
  7657. UnicodeString __fastcall TTerminal::EncryptFileName(const UnicodeString & Path, bool EncryptNewFiles)
  7658. {
  7659. UnicodeString Result = Path;
  7660. if (IsEncryptingFiles() && !IsUnixRootPath(Path))
  7661. {
  7662. UnicodeString FileName = UnixExtractFileName(Path);
  7663. UnicodeString FileDir = UnixExtractFileDir(Path);
  7664. if (!FileName.IsEmpty() && IsRealFile(FileName))
  7665. {
  7666. TEncryptedFileNames::const_iterator I = GetEncryptedFileName(Path);
  7667. if (I != FEncryptedFileNames.end())
  7668. {
  7669. FileName = I->second;
  7670. }
  7671. else if (EncryptNewFiles)
  7672. {
  7673. TEncryption Encryption(FEncryptKey);
  7674. FileName = Encryption.EncryptFileName(FileName);
  7675. FEncryptedFileNames.insert(std::make_pair(Path, FileName));
  7676. LogEvent(2, FORMAT(L"Name of file '%s' encrypted as '%s'", (Path, FileName)));
  7677. }
  7678. }
  7679. FileDir = EncryptFileName(FileDir, EncryptNewFiles);
  7680. Result = UnixCombinePaths(FileDir, FileName);
  7681. }
  7682. return Result;
  7683. }
  7684. //---------------------------------------------------------------------------
  7685. UnicodeString __fastcall TTerminal::DecryptFileName(const UnicodeString & Path)
  7686. {
  7687. UnicodeString Result = Path;
  7688. if (IsEncryptingFiles() && !IsUnixRootPath(Path))
  7689. {
  7690. UnicodeString FileName = UnixExtractFileName(Path);
  7691. UnicodeString FileNameEncrypted = FileName;
  7692. bool Encrypted = TEncryption::IsEncryptedFileName(FileName);
  7693. if (Encrypted)
  7694. {
  7695. TEncryption Encryption(FEncryptKey);
  7696. FileName = Encryption.DecryptFileName(FileName);
  7697. UnicodeString FileDir = UnixExtractFileDir(Path);
  7698. FileDir = DecryptFileName(FileDir);
  7699. Result = UnixCombinePaths(FileDir, FileName);
  7700. }
  7701. TEncryptedFileNames::iterator Iter = FEncryptedFileNames.find(Result);
  7702. bool NotCached = (Iter == FEncryptedFileNames.end());
  7703. if (Encrypted || NotCached)
  7704. {
  7705. if (Encrypted && (NotCached || (Iter->second != FileNameEncrypted)))
  7706. {
  7707. LogEvent(2, FORMAT(L"Name of file '%s' decrypted from '%s'", (Result, FileNameEncrypted)));
  7708. }
  7709. // This may overwrite another variant of encryption
  7710. FEncryptedFileNames[Result] = FileNameEncrypted;
  7711. }
  7712. }
  7713. return Result;
  7714. }
  7715. //---------------------------------------------------------------------------
  7716. //---------------------------------------------------------------------------
  7717. __fastcall TSecondaryTerminal::TSecondaryTerminal(TTerminal * MainTerminal,
  7718. TSessionData * ASessionData, TConfiguration * Configuration, const UnicodeString & Name) :
  7719. TTerminal(ASessionData, Configuration),
  7720. FMainTerminal(MainTerminal)
  7721. {
  7722. Log->SetParent(FMainTerminal->Log, Name);
  7723. ActionLog->Enabled = false;
  7724. SessionData->NonPersistant();
  7725. DebugAssert(FMainTerminal != NULL);
  7726. if (!FMainTerminal->UserName.IsEmpty())
  7727. {
  7728. SessionData->UserName = FMainTerminal->UserName;
  7729. }
  7730. }
  7731. //---------------------------------------------------------------------------
  7732. void __fastcall TSecondaryTerminal::UpdateFromMain()
  7733. {
  7734. if ((FFileSystem != NULL) && (FMainTerminal->FFileSystem != NULL))
  7735. {
  7736. FFileSystem->UpdateFromMain(FMainTerminal->FFileSystem);
  7737. }
  7738. }
  7739. //---------------------------------------------------------------------------
  7740. void __fastcall TSecondaryTerminal::DirectoryLoaded(TRemoteFileList * FileList)
  7741. {
  7742. FMainTerminal->DirectoryLoaded(FileList);
  7743. DebugAssert(FileList != NULL);
  7744. }
  7745. //---------------------------------------------------------------------------
  7746. void __fastcall TSecondaryTerminal::DirectoryModified(const UnicodeString Path,
  7747. bool SubDirs)
  7748. {
  7749. // clear cache of main terminal
  7750. FMainTerminal->DirectoryModified(Path, SubDirs);
  7751. }
  7752. //---------------------------------------------------------------------------
  7753. TTerminal * __fastcall TSecondaryTerminal::GetPasswordSource()
  7754. {
  7755. return FMainTerminal;
  7756. }
  7757. //---------------------------------------------------------------------------
  7758. __fastcall TTerminalList::TTerminalList(TConfiguration * AConfiguration) :
  7759. TObjectList()
  7760. {
  7761. DebugAssert(AConfiguration);
  7762. FConfiguration = AConfiguration;
  7763. }
  7764. //---------------------------------------------------------------------------
  7765. __fastcall TTerminalList::~TTerminalList()
  7766. {
  7767. DebugAssert(Count == 0);
  7768. }
  7769. //---------------------------------------------------------------------------
  7770. TTerminal * __fastcall TTerminalList::CreateTerminal(TSessionData * Data)
  7771. {
  7772. return new TTerminal(Data, FConfiguration);
  7773. }
  7774. //---------------------------------------------------------------------------
  7775. TTerminal * __fastcall TTerminalList::NewTerminal(TSessionData * Data)
  7776. {
  7777. TTerminal * Terminal = CreateTerminal(Data);
  7778. Add(Terminal);
  7779. return Terminal;
  7780. }
  7781. //---------------------------------------------------------------------------
  7782. void __fastcall TTerminalList::FreeTerminal(TTerminal * Terminal)
  7783. {
  7784. DebugAssert(IndexOf(Terminal) >= 0);
  7785. Remove(Terminal);
  7786. }
  7787. //---------------------------------------------------------------------------
  7788. void __fastcall TTerminalList::FreeAndNullTerminal(TTerminal * & Terminal)
  7789. {
  7790. TTerminal * T = Terminal;
  7791. Terminal = NULL;
  7792. FreeTerminal(T);
  7793. }
  7794. //---------------------------------------------------------------------------
  7795. TTerminal * __fastcall TTerminalList::GetTerminal(int Index)
  7796. {
  7797. return dynamic_cast<TTerminal *>(Items[Index]);
  7798. }
  7799. //---------------------------------------------------------------------------
  7800. void __fastcall TTerminalList::RecryptPasswords()
  7801. {
  7802. for (int Index = 0; Index < Count; Index++)
  7803. {
  7804. Terminals[Index]->RecryptPasswords();
  7805. }
  7806. }
  7807. //---------------------------------------------------------------------------
  7808. //---------------------------------------------------------------------------
  7809. TLocalFileHandle::TLocalFileHandle()
  7810. {
  7811. Handle = 0;
  7812. Attrs = 0;
  7813. MTime = 0;
  7814. ATime = 0;
  7815. Size = 0;
  7816. Directory = false;
  7817. }
  7818. //---------------------------------------------------------------------------
  7819. TLocalFileHandle::~TLocalFileHandle()
  7820. {
  7821. Release();
  7822. }
  7823. //---------------------------------------------------------------------------
  7824. void TLocalFileHandle::Release()
  7825. {
  7826. if (Handle != 0)
  7827. {
  7828. Close();
  7829. }
  7830. }
  7831. //---------------------------------------------------------------------------
  7832. void TLocalFileHandle::Dismiss()
  7833. {
  7834. if (DebugAlwaysTrue(Handle != 0))
  7835. {
  7836. Handle = 0;
  7837. }
  7838. }
  7839. //---------------------------------------------------------------------------
  7840. void TLocalFileHandle::Close()
  7841. {
  7842. if (DebugAlwaysTrue(Handle != 0))
  7843. {
  7844. CloseHandle(Handle);
  7845. Dismiss();
  7846. }
  7847. }