Terminal.cpp 268 KB

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