1
0

Terminal.cpp 288 KB

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