Terminal.cpp 260 KB

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