Terminal.cpp 298 KB

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