1
0

Terminal.cpp 266 KB

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