Terminal.cpp 269 KB

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