Terminal.cpp 298 KB

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