Terminal.cpp 267 KB

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