Terminal.cpp 178 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816
  1. //---------------------------------------------------------------------------
  2. #include <vcl.h>
  3. #pragma hdrstop
  4. #include "Terminal.h"
  5. #include <SysUtils.hpp>
  6. #include <FileCtrl.hpp>
  7. #include "Common.h"
  8. #include "PuttyTools.h"
  9. #include "FileBuffer.h"
  10. #include "Interface.h"
  11. #include "RemoteFiles.h"
  12. #include "SecureShell.h"
  13. #include "ScpFileSystem.h"
  14. #include "SftpFileSystem.h"
  15. #ifndef NO_FILEZILLA
  16. #include "FtpFileSystem.h"
  17. #endif
  18. #include "WebDAVFileSystem.h"
  19. #include "TextsCore.h"
  20. #include "HelpCore.h"
  21. #include "CoreMain.h"
  22. #include "Queue.h"
  23. #ifndef AUTO_WINSOCK
  24. #include <winsock2.h>
  25. #endif
  26. //---------------------------------------------------------------------------
  27. #pragma package(smart_init)
  28. //---------------------------------------------------------------------------
  29. #define COMMAND_ERROR_ARI(MESSAGE, REPEAT) \
  30. { \
  31. unsigned int Result = CommandError(&E, MESSAGE, qaRetry | qaSkip | qaAbort); \
  32. switch (Result) { \
  33. case qaRetry: { REPEAT; } break; \
  34. case qaAbort: Abort(); \
  35. } \
  36. }
  37. //---------------------------------------------------------------------------
  38. // Note that the action may already be canceled when RollbackAction is called
  39. #define COMMAND_ERROR_ARI_ACTION(MESSAGE, REPEAT, ACTION) \
  40. { \
  41. unsigned int Result; \
  42. try \
  43. { \
  44. Result = CommandError(&E, MESSAGE, qaRetry | qaSkip | qaAbort); \
  45. } \
  46. catch(Exception & E2) \
  47. { \
  48. RollbackAction(ACTION, NULL, &E2); \
  49. throw; \
  50. } \
  51. switch (Result) { \
  52. case qaRetry: ACTION.Cancel(); { REPEAT; } break; \
  53. case qaAbort: RollbackAction(ACTION, NULL, &E); Abort(); \
  54. case qaSkip: ACTION.Cancel(); break; \
  55. default: FAIL; \
  56. } \
  57. }
  58. #define FILE_OPERATION_LOOP_TERMINAL this
  59. //---------------------------------------------------------------------------
  60. //---------------------------------------------------------------------------
  61. class TLoopDetector
  62. {
  63. public:
  64. __fastcall TLoopDetector();
  65. void __fastcall RecordVisitedDirectory(const UnicodeString & Directory);
  66. bool __fastcall IsUnvisitedDirectory(const TRemoteFile * File);
  67. private:
  68. std::unique_ptr<TStringList> FVisitedDirectories;
  69. };
  70. //---------------------------------------------------------------------------
  71. __fastcall TLoopDetector::TLoopDetector()
  72. {
  73. FVisitedDirectories.reset(CreateSortedStringList());
  74. }
  75. //---------------------------------------------------------------------------
  76. void __fastcall TLoopDetector::RecordVisitedDirectory(const UnicodeString & Directory)
  77. {
  78. UnicodeString VisitedDirectory = ExcludeTrailingBackslash(Directory);
  79. FVisitedDirectories->Add(VisitedDirectory);
  80. }
  81. //---------------------------------------------------------------------------
  82. bool __fastcall TLoopDetector::IsUnvisitedDirectory(const TRemoteFile * File)
  83. {
  84. assert(File->IsDirectory);
  85. UnicodeString Directory = UnixExcludeTrailingBackslash(File->FullFileName);
  86. bool Result = (FVisitedDirectories->IndexOf(Directory) < 0);
  87. if (Result)
  88. {
  89. if (File->IsSymLink)
  90. {
  91. UnicodeString BaseDirectory = UnixExtractFileDir(Directory);
  92. UnicodeString SymlinkDirectory =
  93. UnixExcludeTrailingBackslash(AbsolutePath(BaseDirectory, File->LinkTo));
  94. Result = (FVisitedDirectories->IndexOf(SymlinkDirectory) < 0);
  95. }
  96. }
  97. if (Result)
  98. {
  99. RecordVisitedDirectory(Directory);
  100. }
  101. return Result;
  102. }
  103. //---------------------------------------------------------------------------
  104. //---------------------------------------------------------------------------
  105. struct TMoveFileParams
  106. {
  107. UnicodeString Target;
  108. UnicodeString FileMask;
  109. };
  110. //---------------------------------------------------------------------------
  111. struct TFilesFindParams
  112. {
  113. TFileMasks FileMask;
  114. TFileFoundEvent OnFileFound;
  115. TFindingFileEvent OnFindingFile;
  116. bool Cancel;
  117. TLoopDetector LoopDetector;
  118. };
  119. //---------------------------------------------------------------------------
  120. TCalculateSizeStats::TCalculateSizeStats()
  121. {
  122. memset(this, 0, sizeof(*this));
  123. }
  124. //---------------------------------------------------------------------------
  125. TSynchronizeOptions::TSynchronizeOptions()
  126. {
  127. memset(this, 0, sizeof(*this));
  128. }
  129. //---------------------------------------------------------------------------
  130. TSynchronizeOptions::~TSynchronizeOptions()
  131. {
  132. delete Filter;
  133. }
  134. //---------------------------------------------------------------------------
  135. bool __fastcall TSynchronizeOptions::MatchesFilter(const UnicodeString & FileName)
  136. {
  137. int FoundIndex;
  138. bool Result;
  139. if (Filter == NULL)
  140. {
  141. Result = true;
  142. }
  143. else
  144. {
  145. Result = Filter->Find(FileName, FoundIndex);
  146. }
  147. return Result;
  148. }
  149. //---------------------------------------------------------------------------
  150. TSpaceAvailable::TSpaceAvailable()
  151. {
  152. memset(this, 0, sizeof(*this));
  153. }
  154. //---------------------------------------------------------------------------
  155. TOverwriteFileParams::TOverwriteFileParams()
  156. {
  157. SourceSize = 0;
  158. DestSize = 0;
  159. SourcePrecision = mfFull;
  160. DestPrecision = mfFull;
  161. }
  162. //---------------------------------------------------------------------------
  163. //---------------------------------------------------------------------------
  164. TSynchronizeChecklist::TItem::TItem() :
  165. Action(saNone), IsDirectory(false), RemoteFile(NULL), Checked(true), ImageIndex(-1)
  166. {
  167. Local.ModificationFmt = mfFull;
  168. Local.Modification = 0;
  169. Local.Size = 0;
  170. Remote.ModificationFmt = mfFull;
  171. Remote.Modification = 0;
  172. Remote.Size = 0;
  173. }
  174. //---------------------------------------------------------------------------
  175. TSynchronizeChecklist::TItem::~TItem()
  176. {
  177. delete RemoteFile;
  178. }
  179. //---------------------------------------------------------------------------
  180. const UnicodeString& TSynchronizeChecklist::TItem::GetFileName() const
  181. {
  182. if (!Remote.FileName.IsEmpty())
  183. {
  184. return Remote.FileName;
  185. }
  186. else
  187. {
  188. assert(!Local.FileName.IsEmpty());
  189. return Local.FileName;
  190. }
  191. }
  192. //---------------------------------------------------------------------------
  193. //---------------------------------------------------------------------------
  194. TSynchronizeChecklist::TSynchronizeChecklist() :
  195. FList(new TList())
  196. {
  197. }
  198. //---------------------------------------------------------------------------
  199. TSynchronizeChecklist::~TSynchronizeChecklist()
  200. {
  201. for (int Index = 0; Index < FList->Count; Index++)
  202. {
  203. delete static_cast<TItem *>(FList->Items[Index]);
  204. }
  205. delete FList;
  206. }
  207. //---------------------------------------------------------------------------
  208. void TSynchronizeChecklist::Add(TItem * Item)
  209. {
  210. FList->Add(Item);
  211. }
  212. //---------------------------------------------------------------------------
  213. int __fastcall TSynchronizeChecklist::Compare(void * AItem1, void * AItem2)
  214. {
  215. TItem * Item1 = static_cast<TItem *>(AItem1);
  216. TItem * Item2 = static_cast<TItem *>(AItem2);
  217. int Result;
  218. if (!Item1->Local.Directory.IsEmpty())
  219. {
  220. Result = AnsiCompareText(Item1->Local.Directory, Item2->Local.Directory);
  221. }
  222. else
  223. {
  224. assert(!Item1->Remote.Directory.IsEmpty());
  225. Result = AnsiCompareText(Item1->Remote.Directory, Item2->Remote.Directory);
  226. }
  227. if (Result == 0)
  228. {
  229. Result = AnsiCompareText(Item1->GetFileName(), Item2->GetFileName());
  230. }
  231. return Result;
  232. }
  233. //---------------------------------------------------------------------------
  234. void TSynchronizeChecklist::Sort()
  235. {
  236. FList->Sort(Compare);
  237. }
  238. //---------------------------------------------------------------------------
  239. int TSynchronizeChecklist::GetCount() const
  240. {
  241. return FList->Count;
  242. }
  243. //---------------------------------------------------------------------------
  244. const TSynchronizeChecklist::TItem * TSynchronizeChecklist::GetItem(int Index) const
  245. {
  246. return static_cast<TItem *>(FList->Items[Index]);
  247. }
  248. //---------------------------------------------------------------------------
  249. void __fastcall TSynchronizeChecklist::Update(const TItem * Item, bool Check, TAction Action)
  250. {
  251. // TSynchronizeChecklist owns non-const items so it can manipulate them freely,
  252. // const_cast here is just an optimization
  253. TItem * MutableItem = const_cast<TItem *>(Item);
  254. assert(FList->IndexOf(MutableItem) >= 0);
  255. MutableItem->Checked = Check;
  256. MutableItem->Action = Action;
  257. }
  258. //---------------------------------------------------------------------------
  259. TSynchronizeChecklist::TAction __fastcall TSynchronizeChecklist::Reverse(TSynchronizeChecklist::TAction Action)
  260. {
  261. switch (Action)
  262. {
  263. case saUploadNew:
  264. return saDeleteLocal;
  265. case saDownloadNew:
  266. return saDeleteRemote;
  267. case saUploadUpdate:
  268. return saDownloadUpdate;
  269. case saDownloadUpdate:
  270. return saUploadUpdate;
  271. case saDeleteRemote:
  272. return saDownloadNew;
  273. case saDeleteLocal:
  274. return saUploadNew;
  275. default:
  276. case saNone:
  277. FAIL;
  278. return saNone;
  279. }
  280. }
  281. //---------------------------------------------------------------------------
  282. //---------------------------------------------------------------------------
  283. class TTunnelThread : public TSimpleThread
  284. {
  285. public:
  286. __fastcall TTunnelThread(TSecureShell * SecureShell);
  287. virtual __fastcall ~TTunnelThread();
  288. virtual void __fastcall Terminate();
  289. protected:
  290. virtual void __fastcall Execute();
  291. private:
  292. TSecureShell * FSecureShell;
  293. bool FTerminated;
  294. };
  295. //---------------------------------------------------------------------------
  296. __fastcall TTunnelThread::TTunnelThread(TSecureShell * SecureShell) :
  297. FSecureShell(SecureShell),
  298. FTerminated(false)
  299. {
  300. Start();
  301. }
  302. //---------------------------------------------------------------------------
  303. __fastcall TTunnelThread::~TTunnelThread()
  304. {
  305. // close before the class's virtual functions (Terminate particularly) are lost
  306. Close();
  307. }
  308. //---------------------------------------------------------------------------
  309. void __fastcall TTunnelThread::Terminate()
  310. {
  311. FTerminated = true;
  312. }
  313. //---------------------------------------------------------------------------
  314. void __fastcall TTunnelThread::Execute()
  315. {
  316. try
  317. {
  318. while (!FTerminated)
  319. {
  320. FSecureShell->Idle(250);
  321. }
  322. }
  323. catch(...)
  324. {
  325. if (FSecureShell->Active)
  326. {
  327. FSecureShell->Close();
  328. }
  329. // do not pass exception out of thread's proc
  330. }
  331. }
  332. //---------------------------------------------------------------------------
  333. //---------------------------------------------------------------------------
  334. class TTunnelUI : public TSessionUI
  335. {
  336. public:
  337. __fastcall TTunnelUI(TTerminal * Terminal);
  338. virtual void __fastcall Information(const UnicodeString & Str, bool Status);
  339. virtual unsigned int __fastcall QueryUser(const UnicodeString Query,
  340. TStrings * MoreMessages, unsigned int Answers, const TQueryParams * Params,
  341. TQueryType QueryType);
  342. virtual unsigned int __fastcall QueryUserException(const UnicodeString Query,
  343. Exception * E, unsigned int Answers, const TQueryParams * Params,
  344. TQueryType QueryType);
  345. virtual bool __fastcall PromptUser(TSessionData * Data, TPromptKind Kind,
  346. UnicodeString Name, UnicodeString Instructions, TStrings * Prompts,
  347. TStrings * Results);
  348. virtual void __fastcall DisplayBanner(const UnicodeString & Banner);
  349. virtual void __fastcall FatalError(Exception * E, UnicodeString Msg, UnicodeString HelpContext);
  350. virtual void __fastcall HandleExtendedException(Exception * E);
  351. virtual void __fastcall Closed();
  352. virtual void __fastcall ProcessGUI();
  353. private:
  354. TTerminal * FTerminal;
  355. unsigned int FTerminalThread;
  356. };
  357. //---------------------------------------------------------------------------
  358. __fastcall TTunnelUI::TTunnelUI(TTerminal * Terminal)
  359. {
  360. FTerminal = Terminal;
  361. FTerminalThread = GetCurrentThreadId();
  362. }
  363. //---------------------------------------------------------------------------
  364. void __fastcall TTunnelUI::Information(const UnicodeString & Str, bool Status)
  365. {
  366. if (GetCurrentThreadId() == FTerminalThread)
  367. {
  368. FTerminal->Information(Str, Status);
  369. }
  370. }
  371. //---------------------------------------------------------------------------
  372. unsigned int __fastcall TTunnelUI::QueryUser(const UnicodeString Query,
  373. TStrings * MoreMessages, unsigned int Answers, const TQueryParams * Params,
  374. TQueryType QueryType)
  375. {
  376. unsigned int Result;
  377. if (GetCurrentThreadId() == FTerminalThread)
  378. {
  379. Result = FTerminal->QueryUser(Query, MoreMessages, Answers, Params, QueryType);
  380. }
  381. else
  382. {
  383. Result = AbortAnswer(Answers);
  384. }
  385. return Result;
  386. }
  387. //---------------------------------------------------------------------------
  388. unsigned int __fastcall TTunnelUI::QueryUserException(const UnicodeString Query,
  389. Exception * E, unsigned int Answers, const TQueryParams * Params,
  390. TQueryType QueryType)
  391. {
  392. unsigned int Result;
  393. if (GetCurrentThreadId() == FTerminalThread)
  394. {
  395. Result = FTerminal->QueryUserException(Query, E, Answers, Params, QueryType);
  396. }
  397. else
  398. {
  399. Result = AbortAnswer(Answers);
  400. }
  401. return Result;
  402. }
  403. //---------------------------------------------------------------------------
  404. bool __fastcall TTunnelUI::PromptUser(TSessionData * Data, TPromptKind Kind,
  405. UnicodeString Name, UnicodeString Instructions, TStrings * Prompts, TStrings * Results)
  406. {
  407. bool Result;
  408. if (GetCurrentThreadId() == FTerminalThread)
  409. {
  410. if (IsAuthenticationPrompt(Kind))
  411. {
  412. Instructions = LoadStr(TUNNEL_INSTRUCTION) +
  413. (Instructions.IsEmpty() ? L"" : L"\n") +
  414. Instructions;
  415. }
  416. Result = FTerminal->PromptUser(Data, Kind, Name, Instructions, Prompts, Results);
  417. }
  418. else
  419. {
  420. Result = false;
  421. }
  422. return Result;
  423. }
  424. //---------------------------------------------------------------------------
  425. void __fastcall TTunnelUI::DisplayBanner(const UnicodeString & Banner)
  426. {
  427. if (GetCurrentThreadId() == FTerminalThread)
  428. {
  429. FTerminal->DisplayBanner(Banner);
  430. }
  431. }
  432. //---------------------------------------------------------------------------
  433. void __fastcall TTunnelUI::FatalError(Exception * E, UnicodeString Msg, UnicodeString HelpKeyword)
  434. {
  435. throw ESshFatal(E, Msg, HelpKeyword);
  436. }
  437. //---------------------------------------------------------------------------
  438. void __fastcall TTunnelUI::HandleExtendedException(Exception * E)
  439. {
  440. if (GetCurrentThreadId() == FTerminalThread)
  441. {
  442. FTerminal->HandleExtendedException(E);
  443. }
  444. }
  445. //---------------------------------------------------------------------------
  446. void __fastcall TTunnelUI::Closed()
  447. {
  448. // noop
  449. }
  450. //---------------------------------------------------------------------------
  451. void __fastcall TTunnelUI::ProcessGUI()
  452. {
  453. // noop
  454. }
  455. //---------------------------------------------------------------------------
  456. //---------------------------------------------------------------------------
  457. class TCallbackGuard
  458. {
  459. public:
  460. inline __fastcall TCallbackGuard(TTerminal * FTerminal);
  461. inline __fastcall ~TCallbackGuard();
  462. void __fastcall FatalError(Exception * E, const UnicodeString & Msg, const UnicodeString & HelpKeyword);
  463. inline void __fastcall Verify();
  464. void __fastcall Dismiss();
  465. private:
  466. ExtException * FFatalError;
  467. TTerminal * FTerminal;
  468. bool FGuarding;
  469. };
  470. //---------------------------------------------------------------------------
  471. __fastcall TCallbackGuard::TCallbackGuard(TTerminal * Terminal) :
  472. FTerminal(Terminal),
  473. FFatalError(NULL),
  474. FGuarding(FTerminal->FCallbackGuard == NULL)
  475. {
  476. if (FGuarding)
  477. {
  478. FTerminal->FCallbackGuard = this;
  479. }
  480. }
  481. //---------------------------------------------------------------------------
  482. __fastcall TCallbackGuard::~TCallbackGuard()
  483. {
  484. if (FGuarding)
  485. {
  486. assert((FTerminal->FCallbackGuard == this) || (FTerminal->FCallbackGuard == NULL));
  487. FTerminal->FCallbackGuard = NULL;
  488. }
  489. delete FFatalError;
  490. }
  491. //---------------------------------------------------------------------------
  492. void __fastcall TCallbackGuard::FatalError(Exception * E, const UnicodeString & Msg, const UnicodeString & HelpKeyword)
  493. {
  494. assert(FGuarding);
  495. // make sure we do not bother about getting back the silent abort exception
  496. // we issued ourselves. this may happen when there is an exception handler
  497. // that converts any exception to fatal one (such as in TTerminal::Open).
  498. if (dynamic_cast<ECallbackGuardAbort *>(E) == NULL)
  499. {
  500. delete FFatalError;
  501. FFatalError = new ExtException(E, Msg, HelpKeyword);
  502. }
  503. // silently abort what we are doing.
  504. // non-silent exception would be caught probably by default application
  505. // exception handler, which may not do an appropriate action
  506. // (particularly it will not resume broken transfer).
  507. throw ECallbackGuardAbort();
  508. }
  509. //---------------------------------------------------------------------------
  510. void __fastcall TCallbackGuard::Dismiss()
  511. {
  512. assert(FFatalError == NULL);
  513. FGuarding = false;
  514. }
  515. //---------------------------------------------------------------------------
  516. void __fastcall TCallbackGuard::Verify()
  517. {
  518. if (FGuarding)
  519. {
  520. FGuarding = false;
  521. assert(FTerminal->FCallbackGuard == this);
  522. FTerminal->FCallbackGuard = NULL;
  523. if (FFatalError != NULL)
  524. {
  525. throw ESshFatal(FFatalError, L"");
  526. }
  527. }
  528. }
  529. //---------------------------------------------------------------------------
  530. //---------------------------------------------------------------------------
  531. TRobustOperationLoop::TRobustOperationLoop(TTerminal * Terminal, TFileOperationProgressType * OperationProgress) :
  532. FTerminal(Terminal),
  533. FOperationProgress(OperationProgress),
  534. FRetry(false)
  535. {
  536. }
  537. //---------------------------------------------------------------------------
  538. bool TRobustOperationLoop::TryReopen(Exception & E)
  539. {
  540. FRetry =
  541. !FTerminal->Active &&
  542. FTerminal->QueryReopen(&E, ropNoReadDirectory, FOperationProgress);
  543. return FRetry;
  544. }
  545. //---------------------------------------------------------------------------
  546. bool TRobustOperationLoop::ShouldRetry()
  547. {
  548. return FRetry;
  549. }
  550. //---------------------------------------------------------------------------
  551. bool TRobustOperationLoop::Retry()
  552. {
  553. bool Result = FRetry;
  554. FRetry = false;
  555. return Result;
  556. }
  557. //---------------------------------------------------------------------------
  558. //---------------------------------------------------------------------------
  559. __fastcall TTerminal::TTerminal(TSessionData * SessionData,
  560. TConfiguration * Configuration)
  561. {
  562. FConfiguration = Configuration;
  563. FSessionData = new TSessionData(L"");
  564. FSessionData->Assign(SessionData);
  565. FLog = new TSessionLog(this, FSessionData, Configuration);
  566. FActionLog = new TActionLog(this, FSessionData, Configuration);
  567. FFiles = new TRemoteDirectory(this);
  568. FExceptionOnFail = 0;
  569. FInTransaction = 0;
  570. FReadCurrentDirectoryPending = false;
  571. FReadDirectoryPending = false;
  572. FUsersGroupsLookedup = False;
  573. FTunnelLocalPortNumber = 0;
  574. FFileSystem = NULL;
  575. FSecureShell = NULL;
  576. FOnProgress = NULL;
  577. FOnFinished = NULL;
  578. FOnDeleteLocalFile = NULL;
  579. FOnReadDirectoryProgress = NULL;
  580. FOnQueryUser = NULL;
  581. FOnPromptUser = NULL;
  582. FOnDisplayBanner = NULL;
  583. FOnShowExtendedException = NULL;
  584. FOnInformation = NULL;
  585. FOnClose = NULL;
  586. FOnFindingFile = NULL;
  587. FUseBusyCursor = True;
  588. FLockDirectory = L"";
  589. FDirectoryCache = new TRemoteDirectoryCache();
  590. FDirectoryChangesCache = NULL;
  591. FFSProtocol = cfsUnknown;
  592. FCommandSession = NULL;
  593. FAutoReadDirectory = true;
  594. FReadingCurrentDirectory = false;
  595. FStatus = ssClosed;
  596. FTunnelThread = NULL;
  597. FTunnel = NULL;
  598. FTunnelData = NULL;
  599. FTunnelLog = NULL;
  600. FTunnelUI = NULL;
  601. FTunnelOpening = false;
  602. FCallbackGuard = NULL;
  603. FNesting = 0;
  604. }
  605. //---------------------------------------------------------------------------
  606. __fastcall TTerminal::~TTerminal()
  607. {
  608. if (Active)
  609. {
  610. Close();
  611. }
  612. if (FCallbackGuard != NULL)
  613. {
  614. // see TTerminal::HandleExtendedException
  615. FCallbackGuard->Dismiss();
  616. }
  617. assert(FTunnel == NULL);
  618. SAFE_DESTROY(FCommandSession);
  619. if (SessionData->CacheDirectoryChanges && SessionData->PreserveDirectoryChanges &&
  620. (FDirectoryChangesCache != NULL))
  621. {
  622. Configuration->SaveDirectoryChangesCache(SessionData->SessionKey,
  623. FDirectoryChangesCache);
  624. }
  625. SAFE_DESTROY_EX(TCustomFileSystem, FFileSystem);
  626. SAFE_DESTROY_EX(TSessionLog, FLog);
  627. SAFE_DESTROY_EX(TActionLog, FActionLog);
  628. delete FFiles;
  629. delete FDirectoryCache;
  630. delete FDirectoryChangesCache;
  631. SAFE_DESTROY(FSessionData);
  632. }
  633. //---------------------------------------------------------------------------
  634. void __fastcall TTerminal::Idle()
  635. {
  636. // Once we disconnect, do nothing, until reconnect handler
  637. // "receives the information".
  638. // Never go idle when called from within ::ProcessGUI() call
  639. // as we may recurse for good, timeouting eventually.
  640. if (Active && (FNesting == 0))
  641. {
  642. TAutoNestingCounter NestingCounter(FNesting);
  643. if (Configuration->ActualLogProtocol >= 1)
  644. {
  645. LogEvent(L"Session upkeep");
  646. }
  647. assert(FFileSystem != NULL);
  648. FFileSystem->Idle();
  649. if (CommandSessionOpened)
  650. {
  651. try
  652. {
  653. FCommandSession->Idle();
  654. }
  655. catch(Exception & E)
  656. {
  657. // If the secondary session is dropped, ignore the error and let
  658. // it be reconnected when needed.
  659. // BTW, non-fatal error can hardly happen here, that's why
  660. // it is displayed, because it can be useful to know.
  661. if (FCommandSession->Active)
  662. {
  663. FCommandSession->HandleExtendedException(&E);
  664. }
  665. }
  666. }
  667. }
  668. }
  669. //---------------------------------------------------------------------
  670. RawByteString __fastcall TTerminal::EncryptPassword(const UnicodeString & Password)
  671. {
  672. return Configuration->EncryptPassword(Password, SessionData->SessionName);
  673. }
  674. //---------------------------------------------------------------------
  675. UnicodeString __fastcall TTerminal::DecryptPassword(const RawByteString & Password)
  676. {
  677. UnicodeString Result;
  678. try
  679. {
  680. Result = Configuration->DecryptPassword(Password, SessionData->SessionName);
  681. }
  682. catch(EAbort &)
  683. {
  684. // silently ignore aborted prompts for master password and return empty password
  685. }
  686. return Result;
  687. }
  688. //---------------------------------------------------------------------------
  689. void __fastcall TTerminal::RecryptPasswords()
  690. {
  691. FSessionData->RecryptPasswords();
  692. FRememberedPassword = EncryptPassword(DecryptPassword(FRememberedPassword));
  693. FRememberedTunnelPassword = EncryptPassword(DecryptPassword(FRememberedTunnelPassword));
  694. }
  695. //---------------------------------------------------------------------------
  696. UnicodeString __fastcall TTerminal::ExpandFileName(UnicodeString Path,
  697. const UnicodeString BasePath)
  698. {
  699. // replace this by AbsolutePath()
  700. Path = UnixExcludeTrailingBackslash(Path);
  701. if (!UnixIsAbsolutePath(Path) && !BasePath.IsEmpty())
  702. {
  703. // TODO: Handle more complicated cases like "../../xxx"
  704. if (Path == L"..")
  705. {
  706. Path = UnixExcludeTrailingBackslash(UnixExtractFilePath(
  707. UnixExcludeTrailingBackslash(BasePath)));
  708. }
  709. else
  710. {
  711. Path = UnixIncludeTrailingBackslash(BasePath) + Path;
  712. }
  713. }
  714. return Path;
  715. }
  716. //---------------------------------------------------------------------------
  717. bool __fastcall TTerminal::GetActive()
  718. {
  719. return (FFileSystem != NULL) && FFileSystem->GetActive();
  720. }
  721. //---------------------------------------------------------------------------
  722. void __fastcall TTerminal::Close()
  723. {
  724. FFileSystem->Close();
  725. if (CommandSessionOpened)
  726. {
  727. FCommandSession->Close();
  728. }
  729. }
  730. //---------------------------------------------------------------------------
  731. void __fastcall TTerminal::ResetConnection()
  732. {
  733. // used to be called from Reopen(), why?
  734. FTunnelError = L"";
  735. FRememberedPasswordTried = false;
  736. FRememberedTunnelPasswordTried = false;
  737. if (FDirectoryChangesCache != NULL)
  738. {
  739. delete FDirectoryChangesCache;
  740. FDirectoryChangesCache = NULL;
  741. }
  742. FFiles->Directory = L"";
  743. // note that we cannot clear contained files
  744. // as they can still be referenced in the GUI atm
  745. }
  746. //---------------------------------------------------------------------------
  747. void __fastcall TTerminal::Open()
  748. {
  749. ReflectSettings();
  750. try
  751. {
  752. DoInformation(L"", true, 1);
  753. try
  754. {
  755. try
  756. {
  757. ResetConnection();
  758. FStatus = ssOpening;
  759. try
  760. {
  761. if (FFileSystem == NULL)
  762. {
  763. Log->AddSystemInfo();
  764. DoInitializeLog();
  765. Log->AddStartupInfo();
  766. }
  767. assert(FTunnel == NULL);
  768. if (FSessionData->Tunnel)
  769. {
  770. DoInformation(LoadStr(OPEN_TUNNEL), true);
  771. LogEvent(L"Opening tunnel.");
  772. OpenTunnel();
  773. Log->AddSeparator();
  774. FSessionData->ConfigureTunnel(FTunnelLocalPortNumber);
  775. DoInformation(LoadStr(USING_TUNNEL), false);
  776. LogEvent(FORMAT(L"Connecting via tunnel interface %s:%d.",
  777. (FSessionData->HostNameExpanded, FSessionData->PortNumber)));
  778. }
  779. else
  780. {
  781. assert(FTunnelLocalPortNumber == 0);
  782. }
  783. if (FFileSystem == NULL)
  784. {
  785. if (SessionData->FSProtocol == fsFTP)
  786. {
  787. #ifdef NO_FILEZILLA
  788. LogEvent(L"FTP protocol is not supported by this build.");
  789. FatalError(NULL, LoadStr(FTP_UNSUPPORTED));
  790. #else
  791. FFSProtocol = cfsFTP;
  792. FFileSystem = new TFTPFileSystem(this);
  793. FFileSystem->Open();
  794. Log->AddSeparator();
  795. LogEvent(L"Using FTP protocol.");
  796. #endif
  797. }
  798. else if (SessionData->FSProtocol == fsWebDAV)
  799. {
  800. FFSProtocol = cfsWebDAV;
  801. FFileSystem = new TWebDAVFileSystem(this);
  802. FFileSystem->Open();
  803. Log->AddSeparator();
  804. LogEvent(L"Using WebDAV protocol.");
  805. }
  806. else
  807. {
  808. assert(FSecureShell == NULL);
  809. try
  810. {
  811. FSecureShell = new TSecureShell(this, FSessionData, Log, Configuration);
  812. try
  813. {
  814. // there will be only one channel in this session
  815. FSecureShell->Simple = true;
  816. FSecureShell->Open();
  817. }
  818. catch(Exception & E)
  819. {
  820. assert(!FSecureShell->Active);
  821. if (!FSecureShell->Active && !FTunnelError.IsEmpty())
  822. {
  823. // the only case where we expect this to happen
  824. assert(E.Message == LoadStr(UNEXPECTED_CLOSE_ERROR));
  825. FatalError(&E, FMTLOAD(TUNNEL_ERROR, (FTunnelError)));
  826. }
  827. else
  828. {
  829. throw;
  830. }
  831. }
  832. Log->AddSeparator();
  833. if ((SessionData->FSProtocol == fsSCPonly) ||
  834. (SessionData->FSProtocol == fsSFTP && FSecureShell->SshFallbackCmd()))
  835. {
  836. FFSProtocol = cfsSCP;
  837. FFileSystem = new TSCPFileSystem(this, FSecureShell);
  838. FSecureShell = NULL; // ownership passed
  839. LogEvent(L"Using SCP protocol.");
  840. }
  841. else
  842. {
  843. FFSProtocol = cfsSFTP;
  844. FFileSystem = new TSFTPFileSystem(this, FSecureShell);
  845. FSecureShell = NULL; // ownership passed
  846. LogEvent(L"Using SFTP protocol.");
  847. }
  848. }
  849. __finally
  850. {
  851. delete FSecureShell;
  852. FSecureShell = NULL;
  853. }
  854. }
  855. }
  856. else
  857. {
  858. FFileSystem->Open();
  859. }
  860. }
  861. __finally
  862. {
  863. if (FSessionData->Tunnel)
  864. {
  865. FSessionData->RollbackTunnel();
  866. }
  867. }
  868. if (SessionData->CacheDirectoryChanges)
  869. {
  870. assert(FDirectoryChangesCache == NULL);
  871. FDirectoryChangesCache = new TRemoteDirectoryChangesCache(
  872. Configuration->CacheDirectoryChangesMaxSize);
  873. if (SessionData->PreserveDirectoryChanges)
  874. {
  875. Configuration->LoadDirectoryChangesCache(SessionData->SessionKey,
  876. FDirectoryChangesCache);
  877. }
  878. }
  879. DoStartup();
  880. if (FCollectFileSystemUsage)
  881. {
  882. FFileSystem->CollectUsage();
  883. FCollectFileSystemUsage = false;
  884. }
  885. DoInformation(LoadStr(STATUS_READY), true);
  886. FStatus = ssOpened;
  887. }
  888. catch(...)
  889. {
  890. // rollback
  891. if (FDirectoryChangesCache != NULL)
  892. {
  893. delete FDirectoryChangesCache;
  894. FDirectoryChangesCache = NULL;
  895. }
  896. throw;
  897. }
  898. }
  899. __finally
  900. {
  901. DoInformation(L"", true, 0);
  902. }
  903. }
  904. catch(EFatal &)
  905. {
  906. throw;
  907. }
  908. catch(Exception & E)
  909. {
  910. // any exception while opening session is fatal
  911. FatalError(&E, L"");
  912. }
  913. }
  914. //---------------------------------------------------------------------------
  915. bool __fastcall TTerminal::IsListenerFree(unsigned int PortNumber)
  916. {
  917. SOCKET Socket = socket(AF_INET, SOCK_STREAM, 0);
  918. bool Result = (Socket != INVALID_SOCKET);
  919. if (Result)
  920. {
  921. SOCKADDR_IN Address;
  922. memset(&Address, 0, sizeof(Address));
  923. Address.sin_family = AF_INET;
  924. Address.sin_port = htons(static_cast<short>(PortNumber));
  925. Address.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  926. Result = (bind(Socket, reinterpret_cast<sockaddr *>(&Address), sizeof(Address)) == 0);
  927. closesocket(Socket);
  928. }
  929. return Result;
  930. }
  931. //---------------------------------------------------------------------------
  932. void __fastcall TTerminal::OpenTunnel()
  933. {
  934. assert(FTunnelData == NULL);
  935. FTunnelLocalPortNumber = FSessionData->TunnelLocalPortNumber;
  936. if (FTunnelLocalPortNumber == 0)
  937. {
  938. FTunnelLocalPortNumber = Configuration->TunnelLocalPortNumberLow;
  939. while (!IsListenerFree(FTunnelLocalPortNumber))
  940. {
  941. FTunnelLocalPortNumber++;
  942. if (FTunnelLocalPortNumber > Configuration->TunnelLocalPortNumberHigh)
  943. {
  944. FTunnelLocalPortNumber = 0;
  945. FatalError(NULL, FMTLOAD(TUNNEL_NO_FREE_PORT,
  946. (Configuration->TunnelLocalPortNumberLow, Configuration->TunnelLocalPortNumberHigh)));
  947. }
  948. }
  949. LogEvent(FORMAT(L"Autoselected tunnel local port number %d", (FTunnelLocalPortNumber)));
  950. }
  951. try
  952. {
  953. FTunnelData = new TSessionData(L"");
  954. FTunnelData->Assign(StoredSessions->DefaultSettings);
  955. FTunnelData->Name = FMTLOAD(TUNNEL_SESSION_NAME, (FSessionData->SessionName));
  956. FTunnelData->Tunnel = false;
  957. FTunnelData->HostName = FSessionData->TunnelHostName;
  958. FTunnelData->PortNumber = FSessionData->TunnelPortNumber;
  959. FTunnelData->UserName = FSessionData->TunnelUserName;
  960. FTunnelData->Password = FSessionData->TunnelPassword;
  961. FTunnelData->PublicKeyFile = FSessionData->TunnelPublicKeyFile;
  962. FTunnelData->TunnelPortFwd = FORMAT(L"L%d\t%s:%d",
  963. (FTunnelLocalPortNumber, FSessionData->HostNameExpanded, FSessionData->PortNumber));
  964. FTunnelData->HostKey = FSessionData->TunnelHostKey;
  965. FTunnelData->ProxyMethod = FSessionData->ProxyMethod;
  966. FTunnelData->ProxyHost = FSessionData->ProxyHost;
  967. FTunnelData->ProxyPort = FSessionData->ProxyPort;
  968. FTunnelData->ProxyUsername = FSessionData->ProxyUsername;
  969. FTunnelData->ProxyPassword = FSessionData->ProxyPassword;
  970. FTunnelData->ProxyTelnetCommand = FSessionData->ProxyTelnetCommand;
  971. FTunnelData->ProxyLocalCommand = FSessionData->ProxyLocalCommand;
  972. FTunnelData->ProxyDNS = FSessionData->ProxyDNS;
  973. FTunnelData->ProxyLocalhost = FSessionData->ProxyLocalhost;
  974. FTunnelLog = new TSessionLog(this, FTunnelData, Configuration);
  975. FTunnelLog->Parent = FLog;
  976. FTunnelLog->Name = L"Tunnel";
  977. FTunnelLog->ReflectSettings();
  978. FTunnelUI = new TTunnelUI(this);
  979. FTunnel = new TSecureShell(FTunnelUI, FTunnelData, FTunnelLog, Configuration);
  980. FTunnelOpening = true;
  981. try
  982. {
  983. FTunnel->Open();
  984. }
  985. __finally
  986. {
  987. FTunnelOpening = false;
  988. }
  989. FTunnelThread = new TTunnelThread(FTunnel);
  990. }
  991. catch(...)
  992. {
  993. CloseTunnel();
  994. throw;
  995. }
  996. }
  997. //---------------------------------------------------------------------------
  998. void __fastcall TTerminal::CloseTunnel()
  999. {
  1000. SAFE_DESTROY_EX(TTunnelThread, FTunnelThread);
  1001. FTunnelError = FTunnel->LastTunnelError;
  1002. SAFE_DESTROY_EX(TSecureShell, FTunnel);
  1003. SAFE_DESTROY_EX(TTunnelUI, FTunnelUI);
  1004. SAFE_DESTROY_EX(TSessionLog, FTunnelLog);
  1005. SAFE_DESTROY(FTunnelData);
  1006. FTunnelLocalPortNumber = 0;
  1007. }
  1008. //---------------------------------------------------------------------------
  1009. void __fastcall TTerminal::Closed()
  1010. {
  1011. if (FTunnel != NULL)
  1012. {
  1013. CloseTunnel();
  1014. }
  1015. if (OnClose)
  1016. {
  1017. TCallbackGuard Guard(this);
  1018. OnClose(this);
  1019. Guard.Verify();
  1020. }
  1021. FStatus = ssClosed;
  1022. }
  1023. //---------------------------------------------------------------------------
  1024. void __fastcall TTerminal::ProcessGUI()
  1025. {
  1026. // Do not process GUI here, as we are called directly from a GUI loop and may
  1027. // recurse for good.
  1028. // Alternatively we may check for (FOperationProgress == NULL)
  1029. if (FNesting == 0)
  1030. {
  1031. TAutoNestingCounter NestingCounter(FNesting);
  1032. ::ProcessGUI();
  1033. }
  1034. }
  1035. //---------------------------------------------------------------------------
  1036. void __fastcall TTerminal::Reopen(int Params)
  1037. {
  1038. TFSProtocol OrigFSProtocol = SessionData->FSProtocol;
  1039. UnicodeString PrevRemoteDirectory = SessionData->RemoteDirectory;
  1040. bool PrevReadCurrentDirectoryPending = FReadCurrentDirectoryPending;
  1041. bool PrevReadDirectoryPending = FReadDirectoryPending;
  1042. assert(!FSuspendTransaction);
  1043. bool PrevAutoReadDirectory = FAutoReadDirectory;
  1044. // here used to be a check for FExceptionOnFail being 0
  1045. // but it can happen, e.g. when we are downloading file to execute it.
  1046. // however I'm not sure why we mind having excaption-on-fail enabled here
  1047. int PrevExceptionOnFail = FExceptionOnFail;
  1048. try
  1049. {
  1050. FReadCurrentDirectoryPending = false;
  1051. FReadDirectoryPending = false;
  1052. FSuspendTransaction = true;
  1053. FExceptionOnFail = 0;
  1054. // typically, we avoid reading directory, when there is operation ongoing,
  1055. // for file list which may reference files from current directory
  1056. if (FLAGSET(Params, ropNoReadDirectory))
  1057. {
  1058. AutoReadDirectory = false;
  1059. }
  1060. // only peek, we may not be connected at all atm,
  1061. // so make sure we do not try retrieving current directory from the server
  1062. // (particularly with FTP)
  1063. AnsiString ACurrentDirectory = PeekCurrentDirectory();
  1064. if (!ACurrentDirectory.IsEmpty())
  1065. {
  1066. SessionData->RemoteDirectory = ACurrentDirectory;
  1067. }
  1068. if (SessionData->FSProtocol == fsSFTP)
  1069. {
  1070. SessionData->FSProtocol = (FFSProtocol == cfsSCP ? fsSCPonly : fsSFTPonly);
  1071. }
  1072. if (Active)
  1073. {
  1074. Close();
  1075. }
  1076. Open();
  1077. }
  1078. __finally
  1079. {
  1080. SessionData->RemoteDirectory = PrevRemoteDirectory;
  1081. SessionData->FSProtocol = OrigFSProtocol;
  1082. FAutoReadDirectory = PrevAutoReadDirectory;
  1083. FReadCurrentDirectoryPending = PrevReadCurrentDirectoryPending;
  1084. FReadDirectoryPending = PrevReadDirectoryPending;
  1085. FSuspendTransaction = false;
  1086. FExceptionOnFail = PrevExceptionOnFail;
  1087. }
  1088. }
  1089. //---------------------------------------------------------------------------
  1090. bool __fastcall TTerminal::PromptUser(TSessionData * Data, TPromptKind Kind,
  1091. UnicodeString Name, UnicodeString Instructions, UnicodeString Prompt, bool Echo, int MaxLen, UnicodeString & Result)
  1092. {
  1093. bool AResult;
  1094. TStrings * Prompts = new TStringList;
  1095. TStrings * Results = new TStringList;
  1096. try
  1097. {
  1098. Prompts->AddObject(Prompt, (TObject *)(FLAGMASK(Echo, pupEcho)));
  1099. Results->AddObject(Result, (TObject *)MaxLen);
  1100. AResult = PromptUser(Data, Kind, Name, Instructions, Prompts, Results);
  1101. Result = Results->Strings[0];
  1102. }
  1103. __finally
  1104. {
  1105. delete Prompts;
  1106. delete Results;
  1107. }
  1108. return AResult;
  1109. }
  1110. //---------------------------------------------------------------------------
  1111. bool __fastcall TTerminal::PromptUser(TSessionData * Data, TPromptKind Kind,
  1112. UnicodeString Name, UnicodeString Instructions, TStrings * Prompts, TStrings * Results)
  1113. {
  1114. // If PromptUser is overridden in descendant class, the overridden version
  1115. // is not called when accessed via TSessionIU interface.
  1116. // So this is workaround.
  1117. // Actually no longer needed as we do not uverride DoPromptUser
  1118. // anymore in TSecondaryTerminal.
  1119. return DoPromptUser(Data, Kind, Name, Instructions, Prompts, Results);
  1120. }
  1121. //---------------------------------------------------------------------------
  1122. TTerminal * __fastcall TTerminal::GetPasswordSource()
  1123. {
  1124. return this;
  1125. }
  1126. //---------------------------------------------------------------------------
  1127. bool __fastcall TTerminal::DoPromptUser(TSessionData * /*Data*/, TPromptKind Kind,
  1128. UnicodeString Name, UnicodeString Instructions, TStrings * Prompts, TStrings * Results)
  1129. {
  1130. bool AResult = false;
  1131. bool PasswordOrPassphrasePrompt = IsPasswordOrPassphrasePrompt(Kind, Prompts);
  1132. if (PasswordOrPassphrasePrompt)
  1133. {
  1134. bool & PasswordTried =
  1135. FTunnelOpening ? FRememberedTunnelPasswordTried : FRememberedPasswordTried;
  1136. if (!PasswordTried)
  1137. {
  1138. // let's expect that the main session is already authenticated and its password
  1139. // is not written after, so no locking is necessary
  1140. // (no longer true, once the main session can be reconnected)
  1141. UnicodeString APassword;
  1142. if (FTunnelOpening)
  1143. {
  1144. APassword = GetPasswordSource()->RememberedTunnelPassword;
  1145. }
  1146. else
  1147. {
  1148. APassword = GetPasswordSource()->RememberedPassword;
  1149. }
  1150. Results->Strings[0] = APassword;
  1151. if (!Results->Strings[0].IsEmpty())
  1152. {
  1153. LogEvent(L"Using remembered password.");
  1154. AResult = true;
  1155. }
  1156. PasswordTried = true;
  1157. }
  1158. }
  1159. if (!AResult)
  1160. {
  1161. if (PasswordOrPassphrasePrompt && !Configuration->RememberPassword)
  1162. {
  1163. Prompts->Objects[0] = (TObject*)(int(Prompts->Objects[0]) | pupRemember);
  1164. }
  1165. if (OnPromptUser != NULL)
  1166. {
  1167. TCallbackGuard Guard(this);
  1168. OnPromptUser(this, Kind, Name, Instructions, Prompts, Results, AResult, NULL);
  1169. Guard.Verify();
  1170. }
  1171. if (AResult && PasswordOrPassphrasePrompt &&
  1172. (Configuration->RememberPassword || FLAGSET(int(Prompts->Objects[0]), pupRemember)))
  1173. {
  1174. RawByteString EncryptedPassword = EncryptPassword(Results->Strings[0]);
  1175. if (FTunnelOpening)
  1176. {
  1177. GetPasswordSource()->FRememberedTunnelPassword = EncryptedPassword;
  1178. }
  1179. else
  1180. {
  1181. GetPasswordSource()->FRememberedPassword = EncryptedPassword;
  1182. }
  1183. }
  1184. }
  1185. return AResult;
  1186. }
  1187. //---------------------------------------------------------------------------
  1188. unsigned int __fastcall TTerminal::QueryUser(const UnicodeString Query,
  1189. TStrings * MoreMessages, unsigned int Answers, const TQueryParams * Params,
  1190. TQueryType QueryType)
  1191. {
  1192. LogEvent(FORMAT(L"Asking user:\n%s (%s)", (Query, (MoreMessages ? MoreMessages->CommaText : UnicodeString() ))));
  1193. unsigned int Answer = AbortAnswer(Answers);
  1194. if (FOnQueryUser)
  1195. {
  1196. TCallbackGuard Guard(this);
  1197. FOnQueryUser(this, Query, MoreMessages, Answers, Params, Answer, QueryType, NULL);
  1198. Guard.Verify();
  1199. }
  1200. return Answer;
  1201. }
  1202. //---------------------------------------------------------------------------
  1203. unsigned int __fastcall TTerminal::QueryUserException(const UnicodeString Query,
  1204. Exception * E, unsigned int Answers, const TQueryParams * Params,
  1205. TQueryType QueryType)
  1206. {
  1207. unsigned int Result;
  1208. UnicodeString ExMessage;
  1209. if (ALWAYS_TRUE(ExceptionMessage(E, ExMessage) || !Query.IsEmpty()))
  1210. {
  1211. TStrings * MoreMessages = new TStringList();
  1212. try
  1213. {
  1214. if (!ExMessage.IsEmpty() && !Query.IsEmpty())
  1215. {
  1216. MoreMessages->Add(UnformatMessage(ExMessage));
  1217. }
  1218. ExtException * EE = dynamic_cast<ExtException*>(E);
  1219. if ((EE != NULL) && (EE->MoreMessages != NULL))
  1220. {
  1221. MoreMessages->AddStrings(EE->MoreMessages);
  1222. }
  1223. // We know MoreMessages not to be NULL here,
  1224. // AppendExceptionStackTraceAndForget should never return true
  1225. // (indicating it had to create the string list)
  1226. ALWAYS_FALSE(AppendExceptionStackTraceAndForget(MoreMessages));
  1227. TQueryParams HelpKeywordOverrideParams;
  1228. if (Params != NULL)
  1229. {
  1230. HelpKeywordOverrideParams.Assign(*Params);
  1231. }
  1232. HelpKeywordOverrideParams.HelpKeyword =
  1233. MergeHelpKeyword(HelpKeywordOverrideParams.HelpKeyword, GetExceptionHelpKeyword(E));
  1234. Result = QueryUser(!Query.IsEmpty() ? Query : ExMessage,
  1235. MoreMessages->Count ? MoreMessages : NULL,
  1236. Answers, &HelpKeywordOverrideParams, QueryType);
  1237. }
  1238. __finally
  1239. {
  1240. delete MoreMessages;
  1241. }
  1242. }
  1243. return Result;
  1244. }
  1245. //---------------------------------------------------------------------------
  1246. void __fastcall TTerminal::DisplayBanner(const UnicodeString & Banner)
  1247. {
  1248. if (OnDisplayBanner != NULL)
  1249. {
  1250. if (Configuration->ForceBanners ||
  1251. Configuration->ShowBanner(SessionData->SessionKey, Banner))
  1252. {
  1253. bool NeverShowAgain = false;
  1254. int Options =
  1255. FLAGMASK(Configuration->ForceBanners, boDisableNeverShowAgain);
  1256. TCallbackGuard Guard(this);
  1257. OnDisplayBanner(this, SessionData->SessionName, Banner,
  1258. NeverShowAgain, Options);
  1259. Guard.Verify();
  1260. if (!Configuration->ForceBanners && NeverShowAgain)
  1261. {
  1262. Configuration->NeverShowBanner(SessionData->SessionKey, Banner);
  1263. }
  1264. }
  1265. }
  1266. }
  1267. //---------------------------------------------------------------------------
  1268. void __fastcall TTerminal::HandleExtendedException(Exception * E)
  1269. {
  1270. Log->AddException(E);
  1271. if (OnShowExtendedException != NULL)
  1272. {
  1273. TCallbackGuard Guard(this);
  1274. // the event handler may destroy 'this' ...
  1275. OnShowExtendedException(this, E, NULL);
  1276. // .. hence guard is dismissed from destructor, to make following call no-op
  1277. Guard.Verify();
  1278. }
  1279. }
  1280. //---------------------------------------------------------------------------
  1281. void __fastcall TTerminal::ShowExtendedException(Exception * E)
  1282. {
  1283. Log->AddException(E);
  1284. if (OnShowExtendedException != NULL)
  1285. {
  1286. OnShowExtendedException(this, E, NULL);
  1287. }
  1288. }
  1289. //---------------------------------------------------------------------------
  1290. void __fastcall TTerminal::DoInformation(const UnicodeString & Str, bool Status,
  1291. int Phase)
  1292. {
  1293. if (OnInformation)
  1294. {
  1295. TCallbackGuard Guard(this);
  1296. OnInformation(this, Str, Status, Phase);
  1297. Guard.Verify();
  1298. }
  1299. }
  1300. //---------------------------------------------------------------------------
  1301. void __fastcall TTerminal::Information(const UnicodeString & Str, bool Status)
  1302. {
  1303. DoInformation(Str, Status);
  1304. }
  1305. //---------------------------------------------------------------------------
  1306. void __fastcall TTerminal::DoProgress(TFileOperationProgressType & ProgressData)
  1307. {
  1308. if (OnProgress != NULL)
  1309. {
  1310. TCallbackGuard Guard(this);
  1311. OnProgress(ProgressData);
  1312. Guard.Verify();
  1313. }
  1314. }
  1315. //---------------------------------------------------------------------------
  1316. void __fastcall TTerminal::DoFinished(TFileOperation Operation, TOperationSide Side, bool Temp,
  1317. const UnicodeString & FileName, bool Success, TOnceDoneOperation & OnceDoneOperation)
  1318. {
  1319. if (OnFinished != NULL)
  1320. {
  1321. TCallbackGuard Guard(this);
  1322. OnFinished(Operation, Side, Temp, FileName, Success, OnceDoneOperation);
  1323. Guard.Verify();
  1324. }
  1325. }
  1326. //---------------------------------------------------------------------------
  1327. void __fastcall TTerminal::SaveCapabilities(TFileSystemInfo & FileSystemInfo)
  1328. {
  1329. for (int Index = 0; Index < fcCount; Index++)
  1330. {
  1331. FileSystemInfo.IsCapable[Index] = IsCapable[(TFSCapability)Index];
  1332. }
  1333. }
  1334. //---------------------------------------------------------------------------
  1335. bool __fastcall TTerminal::GetIsCapable(TFSCapability Capability) const
  1336. {
  1337. assert(FFileSystem);
  1338. return FFileSystem->IsCapable(Capability);
  1339. }
  1340. //---------------------------------------------------------------------------
  1341. UnicodeString __fastcall TTerminal::AbsolutePath(UnicodeString Path, bool Local)
  1342. {
  1343. return FFileSystem->AbsolutePath(Path, Local);
  1344. }
  1345. //---------------------------------------------------------------------------
  1346. void __fastcall TTerminal::ReactOnCommand(int /*TFSCommand*/ Cmd)
  1347. {
  1348. bool ChangesDirectory = false;
  1349. bool ModifiesFiles = false;
  1350. switch ((TFSCommand)Cmd) {
  1351. case fsChangeDirectory:
  1352. case fsHomeDirectory:
  1353. ChangesDirectory = true;
  1354. break;
  1355. case fsCopyToRemote:
  1356. case fsDeleteFile:
  1357. case fsRenameFile:
  1358. case fsMoveFile:
  1359. case fsCopyFile:
  1360. case fsCreateDirectory:
  1361. case fsChangeMode:
  1362. case fsChangeGroup:
  1363. case fsChangeOwner:
  1364. case fsChangeProperties:
  1365. ModifiesFiles = true;
  1366. break;
  1367. case fsAnyCommand:
  1368. ChangesDirectory = true;
  1369. ModifiesFiles = true;
  1370. break;
  1371. }
  1372. if (ChangesDirectory)
  1373. {
  1374. if (!InTransaction())
  1375. {
  1376. ReadCurrentDirectory();
  1377. if (AutoReadDirectory)
  1378. {
  1379. ReadDirectory(false);
  1380. }
  1381. }
  1382. else
  1383. {
  1384. FReadCurrentDirectoryPending = true;
  1385. if (AutoReadDirectory)
  1386. {
  1387. FReadDirectoryPending = true;
  1388. }
  1389. }
  1390. }
  1391. else if (ModifiesFiles && AutoReadDirectory && Configuration->AutoReadDirectoryAfterOp)
  1392. {
  1393. if (!InTransaction())
  1394. {
  1395. ReadDirectory(true);
  1396. }
  1397. else
  1398. {
  1399. FReadDirectoryPending = true;
  1400. }
  1401. }
  1402. }
  1403. //---------------------------------------------------------------------------
  1404. void __fastcall TTerminal::TerminalError(UnicodeString Msg)
  1405. {
  1406. TerminalError(NULL, Msg);
  1407. }
  1408. //---------------------------------------------------------------------------
  1409. void __fastcall TTerminal::TerminalError(
  1410. Exception * E, UnicodeString Msg, UnicodeString HelpKeyword)
  1411. {
  1412. throw ETerminal(E, Msg, HelpKeyword);
  1413. }
  1414. //---------------------------------------------------------------------------
  1415. bool __fastcall TTerminal::DoQueryReopen(Exception * E)
  1416. {
  1417. EFatal * Fatal = dynamic_cast<EFatal *>(E);
  1418. assert(Fatal != NULL);
  1419. bool Result;
  1420. if ((Fatal != NULL) && Fatal->ReopenQueried)
  1421. {
  1422. Result = false;
  1423. }
  1424. else
  1425. {
  1426. LogEvent(L"Connection was lost, asking what to do.");
  1427. TQueryParams Params(qpAllowContinueOnError);
  1428. Params.Timeout = Configuration->SessionReopenAuto;
  1429. Params.TimeoutAnswer = qaRetry;
  1430. TQueryButtonAlias Aliases[1];
  1431. Aliases[0].Button = qaRetry;
  1432. Aliases[0].Alias = LoadStr(RECONNECT_BUTTON);
  1433. Params.Aliases = Aliases;
  1434. Params.AliasesCount = LENOF(Aliases);
  1435. Result = (QueryUserException(L"", E, qaRetry | qaAbort, &Params, qtError) == qaRetry);
  1436. if (Fatal != NULL)
  1437. {
  1438. Fatal->ReopenQueried = true;
  1439. }
  1440. }
  1441. return Result;
  1442. }
  1443. //---------------------------------------------------------------------------
  1444. bool __fastcall TTerminal::QueryReopen(Exception * E, int Params,
  1445. TFileOperationProgressType * OperationProgress)
  1446. {
  1447. TSuspendFileOperationProgress Suspend(OperationProgress);
  1448. bool Result = DoQueryReopen(E);
  1449. if (Result)
  1450. {
  1451. TDateTime Start = Now();
  1452. do
  1453. {
  1454. try
  1455. {
  1456. Reopen(Params);
  1457. }
  1458. catch(Exception & E)
  1459. {
  1460. if (!Active)
  1461. {
  1462. Result =
  1463. ((Configuration->SessionReopenTimeout == 0) ||
  1464. (int(double(Now() - Start) * MSecsPerDay) < Configuration->SessionReopenTimeout)) &&
  1465. DoQueryReopen(&E);
  1466. }
  1467. else
  1468. {
  1469. throw;
  1470. }
  1471. }
  1472. }
  1473. while (!Active && Result);
  1474. }
  1475. return Result;
  1476. }
  1477. //---------------------------------------------------------------------------
  1478. bool __fastcall TTerminal::FileOperationLoopQuery(Exception & E,
  1479. TFileOperationProgressType * OperationProgress, const UnicodeString Message,
  1480. bool AllowSkip, UnicodeString SpecialRetry, UnicodeString HelpKeyword)
  1481. {
  1482. bool Result = false;
  1483. Log->AddException(&E);
  1484. unsigned int Answer;
  1485. bool SkipToAllPossible = AllowSkip && (OperationProgress != NULL);
  1486. if (SkipToAllPossible && OperationProgress->SkipToAll)
  1487. {
  1488. Answer = qaSkip;
  1489. }
  1490. else
  1491. {
  1492. int Answers = qaRetry | qaAbort |
  1493. FLAGMASK(AllowSkip, qaSkip) |
  1494. FLAGMASK(SkipToAllPossible, qaAll) |
  1495. FLAGMASK(!SpecialRetry.IsEmpty(), qaYes);
  1496. TQueryParams Params(qpAllowContinueOnError | FLAGMASK(!AllowSkip, qpFatalAbort));
  1497. Params.HelpKeyword = HelpKeyword;
  1498. TQueryButtonAlias Aliases[2];
  1499. int AliasCount = 0;
  1500. if (FLAGSET(Answers, qaAll))
  1501. {
  1502. Aliases[AliasCount].Button = qaAll;
  1503. Aliases[AliasCount].Alias = LoadStr(SKIP_ALL_BUTTON);
  1504. AliasCount++;
  1505. }
  1506. if (FLAGSET(Answers, qaYes))
  1507. {
  1508. Aliases[AliasCount].Button = qaYes;
  1509. Aliases[AliasCount].Alias = SpecialRetry;
  1510. AliasCount++;
  1511. }
  1512. if (AliasCount > 0)
  1513. {
  1514. Params.Aliases = Aliases;
  1515. Params.AliasesCount = AliasCount;
  1516. }
  1517. {
  1518. TSuspendFileOperationProgress Suspend(OperationProgress);
  1519. Answer = QueryUserException(Message, &E, Answers, &Params, qtError);
  1520. }
  1521. if (Answer == qaAll)
  1522. {
  1523. assert(OperationProgress != NULL);
  1524. OperationProgress->SkipToAll = true;
  1525. Answer = qaSkip;
  1526. }
  1527. if (Answer == qaYes)
  1528. {
  1529. Result = true;
  1530. Answer = qaRetry;
  1531. }
  1532. }
  1533. if (Answer != qaRetry)
  1534. {
  1535. if ((Answer == qaAbort) && (OperationProgress != NULL))
  1536. {
  1537. OperationProgress->Cancel = csCancel;
  1538. }
  1539. if (AllowSkip)
  1540. {
  1541. THROW_SKIP_FILE(&E, Message);
  1542. }
  1543. else
  1544. {
  1545. // this can happen only during file transfer with SCP
  1546. throw ExtException(&E, Message);
  1547. }
  1548. }
  1549. return Result;
  1550. }
  1551. //---------------------------------------------------------------------------
  1552. int __fastcall TTerminal::FileOperationLoop(TFileOperationEvent CallBackFunc,
  1553. TFileOperationProgressType * OperationProgress, bool AllowSkip,
  1554. const UnicodeString Message, void * Param1, void * Param2)
  1555. {
  1556. assert(CallBackFunc);
  1557. int Result;
  1558. FILE_OPERATION_LOOP_BEGIN
  1559. {
  1560. Result = CallBackFunc(Param1, Param2);
  1561. }
  1562. FILE_OPERATION_LOOP_END_EX(Message, AllowSkip);
  1563. return Result;
  1564. }
  1565. //---------------------------------------------------------------------------
  1566. UnicodeString __fastcall TTerminal::TranslateLockedPath(UnicodeString Path, bool Lock)
  1567. {
  1568. if (SessionData->LockInHome && !Path.IsEmpty() && (Path[1] == L'/'))
  1569. {
  1570. if (Lock)
  1571. {
  1572. if (Path.SubString(1, FLockDirectory.Length()) == FLockDirectory)
  1573. {
  1574. Path.Delete(1, FLockDirectory.Length());
  1575. if (Path.IsEmpty()) Path = L"/";
  1576. }
  1577. }
  1578. else
  1579. {
  1580. Path = UnixExcludeTrailingBackslash(FLockDirectory + Path);
  1581. }
  1582. }
  1583. return Path;
  1584. }
  1585. //---------------------------------------------------------------------------
  1586. void __fastcall TTerminal::ClearCaches()
  1587. {
  1588. FDirectoryCache->Clear();
  1589. if (FDirectoryChangesCache != NULL)
  1590. {
  1591. FDirectoryChangesCache->Clear();
  1592. }
  1593. if (FCommandSession != NULL)
  1594. {
  1595. FCommandSession->ClearCaches();
  1596. }
  1597. }
  1598. //---------------------------------------------------------------------------
  1599. void __fastcall TTerminal::ClearCachedFileList(const UnicodeString Path,
  1600. bool SubDirs)
  1601. {
  1602. FDirectoryCache->ClearFileList(Path, SubDirs);
  1603. }
  1604. //---------------------------------------------------------------------------
  1605. void __fastcall TTerminal::AddCachedFileList(TRemoteFileList * FileList)
  1606. {
  1607. FDirectoryCache->AddFileList(FileList);
  1608. }
  1609. //---------------------------------------------------------------------------
  1610. bool __fastcall TTerminal::DirectoryFileList(const UnicodeString Path,
  1611. TRemoteFileList *& FileList, bool CanLoad)
  1612. {
  1613. bool Result = false;
  1614. if (UnixSamePath(FFiles->Directory, Path))
  1615. {
  1616. Result = (FileList == NULL) || (FileList->Timestamp < FFiles->Timestamp);
  1617. if (Result)
  1618. {
  1619. if (FileList == NULL)
  1620. {
  1621. FileList = new TRemoteFileList();
  1622. }
  1623. FFiles->DuplicateTo(FileList);
  1624. }
  1625. }
  1626. else
  1627. {
  1628. if (((FileList == NULL) && FDirectoryCache->HasFileList(Path)) ||
  1629. ((FileList != NULL) && FDirectoryCache->HasNewerFileList(Path, FileList->Timestamp)))
  1630. {
  1631. bool Created = (FileList == NULL);
  1632. if (Created)
  1633. {
  1634. FileList = new TRemoteFileList();
  1635. }
  1636. Result = FDirectoryCache->GetFileList(Path, FileList);
  1637. if (!Result && Created)
  1638. {
  1639. SAFE_DESTROY(FileList);
  1640. }
  1641. }
  1642. // do not attempt to load file list if there is cached version,
  1643. // only absence of cached version indicates that we consider
  1644. // the directory content obsolete
  1645. else if (CanLoad && !FDirectoryCache->HasFileList(Path))
  1646. {
  1647. bool Created = (FileList == NULL);
  1648. if (Created)
  1649. {
  1650. FileList = new TRemoteFileList();
  1651. }
  1652. FileList->Directory = Path;
  1653. try
  1654. {
  1655. ReadDirectory(FileList);
  1656. Result = true;
  1657. }
  1658. catch(...)
  1659. {
  1660. if (Created)
  1661. {
  1662. SAFE_DESTROY(FileList);
  1663. }
  1664. throw;
  1665. }
  1666. }
  1667. }
  1668. return Result;
  1669. }
  1670. //---------------------------------------------------------------------------
  1671. void __fastcall TTerminal::SetCurrentDirectory(UnicodeString value)
  1672. {
  1673. assert(FFileSystem);
  1674. value = TranslateLockedPath(value, false);
  1675. if (value != FFileSystem->CurrentDirectory)
  1676. {
  1677. ChangeDirectory(value);
  1678. }
  1679. }
  1680. //---------------------------------------------------------------------------
  1681. UnicodeString __fastcall TTerminal::GetCurrentDirectory()
  1682. {
  1683. if (FFileSystem != NULL)
  1684. {
  1685. // there's occasional crash when assigning FFileSystem->CurrentDirectory
  1686. // to FCurrentDirectory, splitting the assignment to two statemets
  1687. // to locate the crash more closely
  1688. UnicodeString CurrentDirectory = FFileSystem->CurrentDirectory;
  1689. FCurrentDirectory = CurrentDirectory;
  1690. if (FCurrentDirectory.IsEmpty())
  1691. {
  1692. ReadCurrentDirectory();
  1693. }
  1694. }
  1695. UnicodeString Result = TranslateLockedPath(FCurrentDirectory, true);
  1696. return Result;
  1697. }
  1698. //---------------------------------------------------------------------------
  1699. UnicodeString __fastcall TTerminal::PeekCurrentDirectory()
  1700. {
  1701. if (FFileSystem)
  1702. {
  1703. FCurrentDirectory = FFileSystem->CurrentDirectory;
  1704. }
  1705. UnicodeString Result = TranslateLockedPath(FCurrentDirectory, true);
  1706. return Result;
  1707. }
  1708. //---------------------------------------------------------------------------
  1709. const TRemoteTokenList * __fastcall TTerminal::GetGroups()
  1710. {
  1711. assert(FFileSystem);
  1712. LookupUsersGroups();
  1713. return &FGroups;
  1714. }
  1715. //---------------------------------------------------------------------------
  1716. const TRemoteTokenList * __fastcall TTerminal::GetUsers()
  1717. {
  1718. assert(FFileSystem);
  1719. LookupUsersGroups();
  1720. return &FUsers;
  1721. }
  1722. //---------------------------------------------------------------------------
  1723. const TRemoteTokenList * __fastcall TTerminal::GetMembership()
  1724. {
  1725. assert(FFileSystem);
  1726. LookupUsersGroups();
  1727. return &FMembership;
  1728. }
  1729. //---------------------------------------------------------------------------
  1730. UnicodeString __fastcall TTerminal::GetUserName() const
  1731. {
  1732. // in future might also be implemented to detect username similar to GetUserGroups
  1733. assert(FFileSystem != NULL);
  1734. UnicodeString Result = FFileSystem->GetUserName();
  1735. // Is empty also when stored username was used
  1736. if (Result.IsEmpty())
  1737. {
  1738. Result = SessionData->UserNameExpanded;
  1739. }
  1740. return Result;
  1741. }
  1742. //---------------------------------------------------------------------------
  1743. bool __fastcall TTerminal::GetAreCachesEmpty() const
  1744. {
  1745. return FDirectoryCache->IsEmpty &&
  1746. ((FDirectoryChangesCache == NULL) || FDirectoryChangesCache->IsEmpty);
  1747. }
  1748. //---------------------------------------------------------------------------
  1749. void __fastcall TTerminal::DoInitializeLog()
  1750. {
  1751. if (FOnInitializeLog)
  1752. {
  1753. TCallbackGuard Guard(this);
  1754. FOnInitializeLog(this);
  1755. Guard.Verify();
  1756. }
  1757. }
  1758. //---------------------------------------------------------------------------
  1759. void __fastcall TTerminal::DoChangeDirectory()
  1760. {
  1761. if (FOnChangeDirectory)
  1762. {
  1763. TCallbackGuard Guard(this);
  1764. FOnChangeDirectory(this);
  1765. Guard.Verify();
  1766. }
  1767. }
  1768. //---------------------------------------------------------------------------
  1769. void __fastcall TTerminal::DoReadDirectory(bool ReloadOnly)
  1770. {
  1771. if (FOnReadDirectory)
  1772. {
  1773. TCallbackGuard Guard(this);
  1774. FOnReadDirectory(this, ReloadOnly);
  1775. Guard.Verify();
  1776. }
  1777. }
  1778. //---------------------------------------------------------------------------
  1779. void __fastcall TTerminal::DoStartReadDirectory()
  1780. {
  1781. if (FOnStartReadDirectory)
  1782. {
  1783. TCallbackGuard Guard(this);
  1784. FOnStartReadDirectory(this);
  1785. Guard.Verify();
  1786. }
  1787. }
  1788. //---------------------------------------------------------------------------
  1789. void __fastcall TTerminal::DoReadDirectoryProgress(int Progress, int ResolvedLinks, bool & Cancel)
  1790. {
  1791. if (FReadingCurrentDirectory && (FOnReadDirectoryProgress != NULL))
  1792. {
  1793. TCallbackGuard Guard(this);
  1794. FOnReadDirectoryProgress(this, Progress, ResolvedLinks, Cancel);
  1795. Guard.Verify();
  1796. }
  1797. if (FOnFindingFile != NULL)
  1798. {
  1799. TCallbackGuard Guard(this);
  1800. FOnFindingFile(this, L"", Cancel);
  1801. Guard.Verify();
  1802. }
  1803. }
  1804. //---------------------------------------------------------------------------
  1805. bool __fastcall TTerminal::InTransaction()
  1806. {
  1807. return (FInTransaction > 0) && !FSuspendTransaction;
  1808. }
  1809. //---------------------------------------------------------------------------
  1810. void __fastcall TTerminal::BeginTransaction()
  1811. {
  1812. if (FInTransaction == 0)
  1813. {
  1814. FReadCurrentDirectoryPending = false;
  1815. FReadDirectoryPending = false;
  1816. }
  1817. FInTransaction++;
  1818. if (FCommandSession != NULL)
  1819. {
  1820. FCommandSession->BeginTransaction();
  1821. }
  1822. }
  1823. //---------------------------------------------------------------------------
  1824. void __fastcall TTerminal::EndTransaction()
  1825. {
  1826. DoEndTransaction(false);
  1827. }
  1828. //---------------------------------------------------------------------------
  1829. void __fastcall TTerminal::DoEndTransaction(bool Inform)
  1830. {
  1831. if (FInTransaction == 0)
  1832. TerminalError(L"Can't end transaction, not in transaction");
  1833. assert(FInTransaction > 0);
  1834. FInTransaction--;
  1835. // it connection was closed due to fatal error during transaction, do nothing
  1836. if (Active)
  1837. {
  1838. if (FInTransaction == 0)
  1839. {
  1840. try
  1841. {
  1842. if (FReadCurrentDirectoryPending)
  1843. {
  1844. ReadCurrentDirectory();
  1845. }
  1846. if (FReadDirectoryPending)
  1847. {
  1848. if (Inform)
  1849. {
  1850. DoInformation(LoadStr(STATUS_OPEN_DIRECTORY), true);
  1851. }
  1852. ReadDirectory(!FReadCurrentDirectoryPending);
  1853. }
  1854. }
  1855. __finally
  1856. {
  1857. FReadCurrentDirectoryPending = false;
  1858. FReadDirectoryPending = false;
  1859. }
  1860. }
  1861. }
  1862. if (FCommandSession != NULL)
  1863. {
  1864. FCommandSession->EndTransaction();
  1865. }
  1866. }
  1867. //---------------------------------------------------------------------------
  1868. void __fastcall TTerminal::SetExceptionOnFail(bool value)
  1869. {
  1870. if (value)
  1871. {
  1872. FExceptionOnFail++;
  1873. }
  1874. else
  1875. {
  1876. if (FExceptionOnFail == 0)
  1877. throw Exception(L"ExceptionOnFail is already zero.");
  1878. FExceptionOnFail--;
  1879. }
  1880. if (FCommandSession != NULL)
  1881. {
  1882. FCommandSession->FExceptionOnFail = FExceptionOnFail;
  1883. }
  1884. }
  1885. //---------------------------------------------------------------------------
  1886. bool __fastcall TTerminal::GetExceptionOnFail() const
  1887. {
  1888. return (bool)(FExceptionOnFail > 0);
  1889. }
  1890. //---------------------------------------------------------------------------
  1891. void __fastcall TTerminal::FatalAbort()
  1892. {
  1893. FatalError(NULL, "");
  1894. }
  1895. //---------------------------------------------------------------------------
  1896. void __fastcall TTerminal::FatalError(Exception * E, UnicodeString Msg, UnicodeString HelpKeyword)
  1897. {
  1898. bool SecureShellActive = (FSecureShell != NULL) && FSecureShell->Active;
  1899. if (Active || SecureShellActive)
  1900. {
  1901. // We log this instead of exception handler, because Close() would
  1902. // probably cause exception handler to loose pointer to TShellLog()
  1903. LogEvent(L"Attempt to close connection due to fatal exception:");
  1904. Log->Add(llException, Msg);
  1905. Log->AddException(E);
  1906. if (Active)
  1907. {
  1908. Close();
  1909. }
  1910. // this may happen if failure of authentication of SSH, owned by terminal yet
  1911. // (because the protocol was not decided yet), is detected by us (not by putty).
  1912. // e.g. not verified host key
  1913. if (SecureShellActive)
  1914. {
  1915. FSecureShell->Close();
  1916. }
  1917. }
  1918. if (FCallbackGuard != NULL)
  1919. {
  1920. FCallbackGuard->FatalError(E, Msg, HelpKeyword);
  1921. }
  1922. else
  1923. {
  1924. throw ESshFatal(E, Msg, HelpKeyword);
  1925. }
  1926. }
  1927. //---------------------------------------------------------------------------
  1928. void __fastcall TTerminal::CommandError(Exception * E, const UnicodeString Msg)
  1929. {
  1930. CommandError(E, Msg, 0);
  1931. }
  1932. //---------------------------------------------------------------------------
  1933. unsigned int __fastcall TTerminal::CommandError(Exception * E, const UnicodeString Msg,
  1934. unsigned int Answers, const UnicodeString HelpKeyword)
  1935. {
  1936. // may not be, particularly when TTerminal::Reopen is being called
  1937. // from within OnShowExtendedException handler
  1938. assert(FCallbackGuard == NULL);
  1939. unsigned int Result = 0;
  1940. if (E && E->InheritsFrom(__classid(EFatal)))
  1941. {
  1942. FatalError(E, Msg, HelpKeyword);
  1943. }
  1944. else if (E && E->InheritsFrom(__classid(EAbort)))
  1945. {
  1946. // resent EAbort exception
  1947. Abort();
  1948. }
  1949. else if (ExceptionOnFail)
  1950. {
  1951. throw ECommand(E, Msg, HelpKeyword);
  1952. }
  1953. else if (!Answers)
  1954. {
  1955. ECommand * ECmd = new ECommand(E, Msg, HelpKeyword);
  1956. try
  1957. {
  1958. HandleExtendedException(ECmd);
  1959. }
  1960. __finally
  1961. {
  1962. delete ECmd;
  1963. }
  1964. }
  1965. else
  1966. {
  1967. // small hack to enable "skip to all" for COMMAND_ERROR_ARI
  1968. bool CanSkip = FLAGSET(Answers, qaSkip) && (OperationProgress != NULL);
  1969. if (CanSkip && OperationProgress->SkipToAll)
  1970. {
  1971. Result = qaSkip;
  1972. }
  1973. else
  1974. {
  1975. TQueryParams Params(qpAllowContinueOnError, HelpKeyword);
  1976. TQueryButtonAlias Aliases[1];
  1977. if (CanSkip)
  1978. {
  1979. Aliases[0].Button = qaAll;
  1980. Aliases[0].Alias = LoadStr(SKIP_ALL_BUTTON);
  1981. Params.Aliases = Aliases;
  1982. Params.AliasesCount = LENOF(Aliases);
  1983. Answers |= qaAll;
  1984. }
  1985. Result = QueryUserException(Msg, E, Answers, &Params, qtError);
  1986. if (Result == qaAll)
  1987. {
  1988. assert(OperationProgress != NULL);
  1989. OperationProgress->SkipToAll = true;
  1990. Result = qaSkip;
  1991. }
  1992. }
  1993. }
  1994. return Result;
  1995. }
  1996. //---------------------------------------------------------------------------
  1997. bool __fastcall TTerminal::HandleException(Exception * E)
  1998. {
  1999. if (ExceptionOnFail)
  2000. {
  2001. return false;
  2002. }
  2003. else
  2004. {
  2005. Log->AddException(E);
  2006. return true;
  2007. }
  2008. }
  2009. //---------------------------------------------------------------------------
  2010. void __fastcall TTerminal::CloseOnCompletion(TOnceDoneOperation Operation, const UnicodeString Message)
  2011. {
  2012. Configuration->Usage->Inc(L"ClosesOnCompletion");
  2013. LogEvent(L"Closing session after completed operation (as requested by user)");
  2014. Close();
  2015. throw ESshTerminate(NULL,
  2016. Message.IsEmpty() ? UnicodeString(LoadStr(CLOSED_ON_COMPLETION)) : Message,
  2017. Operation);
  2018. }
  2019. //---------------------------------------------------------------------------
  2020. TBatchOverwrite __fastcall TTerminal::EffectiveBatchOverwrite(
  2021. const UnicodeString & SourceFullFileName, const TCopyParamType * CopyParam, int Params, TFileOperationProgressType * OperationProgress, bool Special)
  2022. {
  2023. TBatchOverwrite Result;
  2024. if (Special &&
  2025. (FLAGSET(Params, cpResume) || CopyParam->ResumeTransfer(SourceFullFileName)))
  2026. {
  2027. Result = boResume;
  2028. }
  2029. else if (FLAGSET(Params, cpAppend))
  2030. {
  2031. Result = boAppend;
  2032. }
  2033. else if (CopyParam->NewerOnly &&
  2034. (((OperationProgress->Side == osLocal) && IsCapable[fcNewerOnlyUpload]) ||
  2035. (OperationProgress->Side != osLocal)))
  2036. {
  2037. // no way to change batch overwrite mode when CopyParam->NewerOnly is on
  2038. Result = boOlder;
  2039. }
  2040. else if (FLAGSET(Params, cpNoConfirmation) || !Configuration->ConfirmOverwriting)
  2041. {
  2042. // no way to change batch overwrite mode when overwrite confirmations are off
  2043. assert(OperationProgress->BatchOverwrite == boNo);
  2044. Result = boAll;
  2045. }
  2046. else
  2047. {
  2048. Result = OperationProgress->BatchOverwrite;
  2049. if (!Special &&
  2050. ((Result == boOlder) || (Result == boAlternateResume) || (Result == boResume)))
  2051. {
  2052. Result = boNo;
  2053. }
  2054. }
  2055. return Result;
  2056. }
  2057. //---------------------------------------------------------------------------
  2058. bool __fastcall TTerminal::CheckRemoteFile(
  2059. const UnicodeString & FileName, const TCopyParamType * CopyParam, int Params, TFileOperationProgressType * OperationProgress)
  2060. {
  2061. return (EffectiveBatchOverwrite(FileName, CopyParam, Params, OperationProgress, true) != boAll);
  2062. }
  2063. //---------------------------------------------------------------------------
  2064. unsigned int __fastcall TTerminal::ConfirmFileOverwrite(
  2065. const UnicodeString & SourceFullFileName, const UnicodeString & TargetFileName,
  2066. const TOverwriteFileParams * FileParams, unsigned int Answers, TQueryParams * QueryParams,
  2067. TOperationSide Side, const TCopyParamType * CopyParam, int Params, TFileOperationProgressType * OperationProgress,
  2068. UnicodeString Message)
  2069. {
  2070. unsigned int Result;
  2071. // duplicated in TSFTPFileSystem::SFTPConfirmOverwrite
  2072. bool CanAlternateResume =
  2073. (FileParams != NULL) &&
  2074. (FileParams->DestSize < FileParams->SourceSize) &&
  2075. !OperationProgress->AsciiTransfer;
  2076. TBatchOverwrite BatchOverwrite = EffectiveBatchOverwrite(SourceFullFileName, CopyParam, Params, OperationProgress, true);
  2077. bool Applicable = true;
  2078. switch (BatchOverwrite)
  2079. {
  2080. case boOlder:
  2081. Applicable = (FileParams != NULL);
  2082. break;
  2083. case boAlternateResume:
  2084. Applicable = CanAlternateResume;
  2085. break;
  2086. case boResume:
  2087. Applicable = CanAlternateResume;
  2088. break;
  2089. }
  2090. if (!Applicable)
  2091. {
  2092. TBatchOverwrite ABatchOverwrite = EffectiveBatchOverwrite(SourceFullFileName, CopyParam, Params, OperationProgress, false);
  2093. assert(BatchOverwrite != ABatchOverwrite);
  2094. BatchOverwrite = ABatchOverwrite;
  2095. }
  2096. if (BatchOverwrite == boNo)
  2097. {
  2098. if (Message.IsEmpty())
  2099. {
  2100. // Side refers to destination side here
  2101. Message = FMTLOAD((Side == osLocal ? LOCAL_FILE_OVERWRITE2 :
  2102. REMOTE_FILE_OVERWRITE2), (TargetFileName, TargetFileName));
  2103. }
  2104. if (FileParams != NULL)
  2105. {
  2106. Message = FMTLOAD(FILE_OVERWRITE_DETAILS, (Message,
  2107. FormatSize(FileParams->SourceSize),
  2108. UserModificationStr(FileParams->SourceTimestamp, FileParams->SourcePrecision),
  2109. FormatSize(FileParams->DestSize),
  2110. UserModificationStr(FileParams->DestTimestamp, FileParams->DestPrecision)));
  2111. }
  2112. if (ALWAYS_TRUE(QueryParams->HelpKeyword.IsEmpty()))
  2113. {
  2114. QueryParams->HelpKeyword = HELP_OVERWRITE;
  2115. }
  2116. Result = QueryUser(Message, NULL, Answers, QueryParams);
  2117. switch (Result)
  2118. {
  2119. case qaNeverAskAgain:
  2120. Configuration->ConfirmOverwriting = false;
  2121. Result = qaYes;
  2122. break;
  2123. case qaYesToAll:
  2124. BatchOverwrite = boAll;
  2125. break;
  2126. case qaAll:
  2127. BatchOverwrite = boOlder;
  2128. break;
  2129. case qaNoToAll:
  2130. BatchOverwrite = boNone;
  2131. break;
  2132. }
  2133. // we user has not selected another batch overwrite mode,
  2134. // keep the current one. note that we may get here even
  2135. // when batch overwrite was selected already, but it could not be applied
  2136. // to current transfer (see condition above)
  2137. if (BatchOverwrite != boNo)
  2138. {
  2139. OperationProgress->BatchOverwrite = BatchOverwrite;
  2140. }
  2141. }
  2142. if (BatchOverwrite != boNo)
  2143. {
  2144. switch (BatchOverwrite)
  2145. {
  2146. case boAll:
  2147. Result = qaYes;
  2148. break;
  2149. case boNone:
  2150. Result = qaNo;
  2151. break;
  2152. case boOlder:
  2153. if (FileParams == NULL)
  2154. {
  2155. Result = qaNo;
  2156. }
  2157. else
  2158. {
  2159. TModificationFmt Precision = LessDateTimePrecision(FileParams->SourcePrecision, FileParams->DestPrecision);
  2160. TDateTime ReducedSourceTimestamp =
  2161. ReduceDateTimePrecision(FileParams->SourceTimestamp, Precision);
  2162. TDateTime ReducedDestTimestamp =
  2163. ReduceDateTimePrecision(FileParams->DestTimestamp, Precision);
  2164. Result =
  2165. (CompareFileTime(ReducedSourceTimestamp, ReducedDestTimestamp) > 0) ?
  2166. qaYes : qaNo;
  2167. LogEvent(FORMAT(L"Source file timestamp is [%s], destination timestamp is [%s], will%s overwrite",
  2168. (StandardTimestamp(ReducedSourceTimestamp),
  2169. StandardTimestamp(ReducedDestTimestamp),
  2170. ((Result == qaYes) ? L"" : L" not"))));
  2171. }
  2172. break;
  2173. case boAlternateResume:
  2174. assert(CanAlternateResume);
  2175. Result = qaSkip; // ugh
  2176. break;
  2177. case boAppend:
  2178. Result = qaRetry;
  2179. break;
  2180. case boResume:
  2181. Result = qaRetry;
  2182. break;
  2183. }
  2184. }
  2185. return Result;
  2186. }
  2187. //---------------------------------------------------------------------------
  2188. void __fastcall TTerminal::FileModified(const TRemoteFile * File,
  2189. const UnicodeString FileName, bool ClearDirectoryChange)
  2190. {
  2191. UnicodeString ParentDirectory;
  2192. UnicodeString Directory;
  2193. if (SessionData->CacheDirectories || SessionData->CacheDirectoryChanges)
  2194. {
  2195. if ((File != NULL) && (File->Directory != NULL))
  2196. {
  2197. if (File->IsDirectory)
  2198. {
  2199. Directory = File->Directory->FullDirectory + File->FileName;
  2200. }
  2201. ParentDirectory = File->Directory->Directory;
  2202. }
  2203. else if (!FileName.IsEmpty())
  2204. {
  2205. ParentDirectory = UnixExtractFilePath(FileName);
  2206. if (ParentDirectory.IsEmpty())
  2207. {
  2208. ParentDirectory = CurrentDirectory;
  2209. }
  2210. // this case for scripting
  2211. if ((File != NULL) && File->IsDirectory)
  2212. {
  2213. Directory = UnixIncludeTrailingBackslash(ParentDirectory) +
  2214. UnixExtractFileName(File->FileName);
  2215. }
  2216. }
  2217. }
  2218. if (SessionData->CacheDirectories)
  2219. {
  2220. if (!Directory.IsEmpty())
  2221. {
  2222. DirectoryModified(Directory, true);
  2223. }
  2224. if (!ParentDirectory.IsEmpty())
  2225. {
  2226. DirectoryModified(ParentDirectory, false);
  2227. }
  2228. }
  2229. if (SessionData->CacheDirectoryChanges && ClearDirectoryChange)
  2230. {
  2231. if (!Directory.IsEmpty())
  2232. {
  2233. FDirectoryChangesCache->ClearDirectoryChange(Directory);
  2234. FDirectoryChangesCache->ClearDirectoryChangeTarget(Directory);
  2235. }
  2236. }
  2237. }
  2238. //---------------------------------------------------------------------------
  2239. void __fastcall TTerminal::DirectoryModified(const UnicodeString Path, bool SubDirs)
  2240. {
  2241. if (Path.IsEmpty())
  2242. {
  2243. ClearCachedFileList(CurrentDirectory, SubDirs);
  2244. }
  2245. else
  2246. {
  2247. ClearCachedFileList(Path, SubDirs);
  2248. }
  2249. }
  2250. //---------------------------------------------------------------------------
  2251. void __fastcall TTerminal::DirectoryLoaded(TRemoteFileList * FileList)
  2252. {
  2253. AddCachedFileList(FileList);
  2254. }
  2255. //---------------------------------------------------------------------------
  2256. void __fastcall TTerminal::ReloadDirectory()
  2257. {
  2258. if (SessionData->CacheDirectories)
  2259. {
  2260. DirectoryModified(CurrentDirectory, false);
  2261. }
  2262. if (SessionData->CacheDirectoryChanges)
  2263. {
  2264. assert(FDirectoryChangesCache != NULL);
  2265. FDirectoryChangesCache->ClearDirectoryChange(CurrentDirectory);
  2266. }
  2267. ReadCurrentDirectory();
  2268. FReadCurrentDirectoryPending = false;
  2269. ReadDirectory(true);
  2270. FReadDirectoryPending = false;
  2271. }
  2272. //---------------------------------------------------------------------------
  2273. void __fastcall TTerminal::RefreshDirectory()
  2274. {
  2275. if (!SessionData->CacheDirectories)
  2276. {
  2277. LogEvent(L"Not refreshing directory, caching is off.");
  2278. }
  2279. else if (FDirectoryCache->HasNewerFileList(CurrentDirectory, FFiles->Timestamp))
  2280. {
  2281. // Second parameter was added to allow (rather force) using the cache.
  2282. // Before, the directory was reloaded always, it seems useless,
  2283. // has it any reason?
  2284. ReadDirectory(true, true);
  2285. FReadDirectoryPending = false;
  2286. }
  2287. }
  2288. //---------------------------------------------------------------------------
  2289. void __fastcall TTerminal::EnsureNonExistence(const UnicodeString FileName)
  2290. {
  2291. // if filename doesn't contain path, we check for existence of file
  2292. if ((UnixExtractFileDir(FileName).IsEmpty()) &&
  2293. UnixSamePath(CurrentDirectory, FFiles->Directory))
  2294. {
  2295. TRemoteFile *File = FFiles->FindFile(FileName);
  2296. if (File)
  2297. {
  2298. if (File->IsDirectory) throw ECommand(NULL, FMTLOAD(RENAME_CREATE_DIR_EXISTS, (FileName)));
  2299. else throw ECommand(NULL, FMTLOAD(RENAME_CREATE_FILE_EXISTS, (FileName)));
  2300. }
  2301. }
  2302. }
  2303. //---------------------------------------------------------------------------
  2304. void __fastcall inline TTerminal::LogEvent(const UnicodeString & Str)
  2305. {
  2306. if (Log->Logging)
  2307. {
  2308. Log->Add(llMessage, Str);
  2309. }
  2310. }
  2311. //---------------------------------------------------------------------------
  2312. void __fastcall TTerminal::RollbackAction(TSessionAction & Action,
  2313. TFileOperationProgressType * OperationProgress, Exception * E)
  2314. {
  2315. // EScpSkipFile without "cancel" is file skip,
  2316. // and we do not want to record skipped actions.
  2317. // But EScpSkipFile with "cancel" is abort and we want to record that.
  2318. // Note that TSCPFileSystem modifies the logic of RollbackAction little bit.
  2319. if ((dynamic_cast<EScpSkipFile *>(E) != NULL) &&
  2320. ((OperationProgress == NULL) ||
  2321. (OperationProgress->Cancel == csContinue)))
  2322. {
  2323. Action.Cancel();
  2324. }
  2325. else
  2326. {
  2327. Action.Rollback(E);
  2328. }
  2329. }
  2330. //---------------------------------------------------------------------------
  2331. void __fastcall TTerminal::DoStartup()
  2332. {
  2333. LogEvent(L"Doing startup conversation with host.");
  2334. BeginTransaction();
  2335. try
  2336. {
  2337. DoInformation(LoadStr(STATUS_STARTUP), true);
  2338. // Make sure that directory would be loaded at last
  2339. FReadCurrentDirectoryPending = true;
  2340. FReadDirectoryPending = AutoReadDirectory;
  2341. FFileSystem->DoStartup();
  2342. LookupUsersGroups();
  2343. if (!SessionData->RemoteDirectory.IsEmpty())
  2344. {
  2345. ChangeDirectory(SessionData->RemoteDirectory);
  2346. }
  2347. }
  2348. __finally
  2349. {
  2350. DoEndTransaction(true);
  2351. }
  2352. LogEvent(L"Startup conversation with host finished.");
  2353. }
  2354. //---------------------------------------------------------------------------
  2355. void __fastcall TTerminal::ReadCurrentDirectory()
  2356. {
  2357. assert(FFileSystem);
  2358. try
  2359. {
  2360. // reset flag is case we are called externally (like from console dialog)
  2361. FReadCurrentDirectoryPending = false;
  2362. LogEvent(L"Getting current directory name.");
  2363. UnicodeString OldDirectory = FFileSystem->CurrentDirectory;
  2364. FFileSystem->ReadCurrentDirectory();
  2365. ReactOnCommand(fsCurrentDirectory);
  2366. if (SessionData->CacheDirectoryChanges)
  2367. {
  2368. assert(FDirectoryChangesCache != NULL);
  2369. if (!CurrentDirectory.IsEmpty() && !FLastDirectoryChange.IsEmpty() && (CurrentDirectory != OldDirectory))
  2370. {
  2371. FDirectoryChangesCache->AddDirectoryChange(OldDirectory,
  2372. FLastDirectoryChange, CurrentDirectory);
  2373. }
  2374. // not to broke the cache, if the next directory change would not
  2375. // be initialized by ChangeDirectory(), which sets it
  2376. // (HomeDirectory() particularly)
  2377. FLastDirectoryChange = L"";
  2378. }
  2379. if (OldDirectory.IsEmpty())
  2380. {
  2381. FLockDirectory = (SessionData->LockInHome ?
  2382. FFileSystem->CurrentDirectory : UnicodeString(L""));
  2383. }
  2384. if (OldDirectory != FFileSystem->CurrentDirectory) DoChangeDirectory();
  2385. }
  2386. catch (Exception &E)
  2387. {
  2388. CommandError(&E, LoadStr(READ_CURRENT_DIR_ERROR));
  2389. }
  2390. }
  2391. //---------------------------------------------------------------------------
  2392. void __fastcall TTerminal::ReadDirectory(bool ReloadOnly, bool ForceCache)
  2393. {
  2394. bool LoadedFromCache = false;
  2395. if (SessionData->CacheDirectories && FDirectoryCache->HasFileList(CurrentDirectory))
  2396. {
  2397. if (ReloadOnly && !ForceCache)
  2398. {
  2399. LogEvent(L"Cached directory not reloaded.");
  2400. }
  2401. else
  2402. {
  2403. DoStartReadDirectory();
  2404. try
  2405. {
  2406. LoadedFromCache = FDirectoryCache->GetFileList(CurrentDirectory, FFiles);
  2407. }
  2408. __finally
  2409. {
  2410. DoReadDirectory(ReloadOnly);
  2411. }
  2412. if (LoadedFromCache)
  2413. {
  2414. LogEvent(L"Directory content loaded from cache.");
  2415. }
  2416. else
  2417. {
  2418. LogEvent(L"Cached Directory content has been removed.");
  2419. }
  2420. }
  2421. }
  2422. if (!LoadedFromCache)
  2423. {
  2424. DoStartReadDirectory();
  2425. FReadingCurrentDirectory = true;
  2426. bool Cancel = false; // dummy
  2427. DoReadDirectoryProgress(0, 0, Cancel);
  2428. try
  2429. {
  2430. TRemoteDirectory * Files = new TRemoteDirectory(this, FFiles);
  2431. try
  2432. {
  2433. Files->Directory = CurrentDirectory;
  2434. CustomReadDirectory(Files);
  2435. }
  2436. __finally
  2437. {
  2438. DoReadDirectoryProgress(-1, 0, Cancel);
  2439. FReadingCurrentDirectory = false;
  2440. TRemoteDirectory * OldFiles = FFiles;
  2441. FFiles = Files;
  2442. try
  2443. {
  2444. DoReadDirectory(ReloadOnly);
  2445. }
  2446. __finally
  2447. {
  2448. // delete only after loading new files to dir view,
  2449. // not to destroy the file objects that the view holds
  2450. // (can be issue in multi threaded environment, such as when the
  2451. // terminal is reconnecting in the terminal thread)
  2452. delete OldFiles;
  2453. }
  2454. if (Active)
  2455. {
  2456. if (SessionData->CacheDirectories)
  2457. {
  2458. DirectoryLoaded(FFiles);
  2459. }
  2460. }
  2461. }
  2462. }
  2463. catch (Exception &E)
  2464. {
  2465. CommandError(&E, FmtLoadStr(LIST_DIR_ERROR, ARRAYOFCONST((FFiles->Directory))));
  2466. }
  2467. }
  2468. }
  2469. //---------------------------------------------------------------------------
  2470. void __fastcall TTerminal::LogRemoteFile(TRemoteFile * File)
  2471. {
  2472. // optimization
  2473. if (Log->Logging)
  2474. {
  2475. LogEvent(FORMAT(L"%s;%s;%d;%s;%s;%s;%s;%d",
  2476. (File->FileName, File->Type, File->Size, StandardTimestamp(File->Modification),
  2477. File->Owner.LogText, File->Group.LogText, File->Rights->Text,
  2478. File->Attr)));
  2479. }
  2480. }
  2481. //---------------------------------------------------------------------------
  2482. UnicodeString __fastcall TTerminal::FormatFileDetailsForLog(const UnicodeString & FileName, TDateTime Modification, __int64 Size)
  2483. {
  2484. UnicodeString Result;
  2485. // optimization
  2486. if (Log->Logging)
  2487. {
  2488. Result = FORMAT(L"'%s' [%s] [%s]", (FileName, (Modification != TDateTime() ? StandardTimestamp(Modification) : UnicodeString(L"n/a")), IntToStr(Size)));
  2489. }
  2490. return Result;
  2491. }
  2492. //---------------------------------------------------------------------------
  2493. void __fastcall TTerminal::LogFileDetails(const UnicodeString & FileName, TDateTime Modification, __int64 Size)
  2494. {
  2495. // optimization
  2496. if (Log->Logging)
  2497. {
  2498. LogEvent(FORMAT("File: %s", (FormatFileDetailsForLog(FileName, Modification, Size))));
  2499. }
  2500. }
  2501. //---------------------------------------------------------------------------
  2502. void __fastcall TTerminal::LogFileDone(TFileOperationProgressType * OperationProgress)
  2503. {
  2504. // optimization
  2505. if (Log->Logging)
  2506. {
  2507. LogEvent(FORMAT("Transfer done: '%s' [%s]", (OperationProgress->FullFileName, IntToStr(OperationProgress->TransferedSize))));
  2508. }
  2509. }
  2510. //---------------------------------------------------------------------------
  2511. void __fastcall TTerminal::CustomReadDirectory(TRemoteFileList * FileList)
  2512. {
  2513. assert(FileList);
  2514. assert(FFileSystem);
  2515. TRobustOperationLoop RobustLoop(this, OperationProgress);
  2516. do
  2517. {
  2518. try
  2519. {
  2520. FFileSystem->ReadDirectory(FileList);
  2521. }
  2522. catch (Exception & E)
  2523. {
  2524. if (!RobustLoop.TryReopen(E))
  2525. {
  2526. throw;
  2527. }
  2528. }
  2529. }
  2530. while (RobustLoop.Retry());
  2531. if (Log->Logging)
  2532. {
  2533. for (int Index = 0; Index < FileList->Count; Index++)
  2534. {
  2535. LogRemoteFile(FileList->Files[Index]);
  2536. }
  2537. }
  2538. ReactOnCommand(fsListDirectory);
  2539. }
  2540. //---------------------------------------------------------------------------
  2541. TRemoteFileList * __fastcall TTerminal::ReadDirectoryListing(UnicodeString Directory, const TFileMasks & Mask)
  2542. {
  2543. TLsSessionAction Action(ActionLog, AbsolutePath(Directory, true));
  2544. TRemoteFileList * FileList = NULL;
  2545. try
  2546. {
  2547. FileList = DoReadDirectoryListing(Directory, false);
  2548. if (FileList != NULL)
  2549. {
  2550. int Index = 0;
  2551. while (Index < FileList->Count)
  2552. {
  2553. TRemoteFile * File = FileList->Files[Index];
  2554. TFileMasks::TParams Params;
  2555. Params.Size = File->Size;
  2556. Params.Modification = File->Modification;
  2557. // Have to use UnicodeString(), instead of L"", as with that
  2558. // overload with (UnicodeString, bool, bool, TParams*) wins
  2559. if (!Mask.Matches(File->FileName, false, UnicodeString(), &Params))
  2560. {
  2561. FileList->Delete(Index);
  2562. }
  2563. else
  2564. {
  2565. Index++;
  2566. }
  2567. }
  2568. Action.FileList(FileList);
  2569. }
  2570. }
  2571. catch(Exception & E)
  2572. {
  2573. COMMAND_ERROR_ARI_ACTION
  2574. (
  2575. L"",
  2576. FileList = ReadDirectoryListing(Directory, Mask),
  2577. Action
  2578. );
  2579. }
  2580. return FileList;
  2581. }
  2582. //---------------------------------------------------------------------------
  2583. TRemoteFile * __fastcall TTerminal::ReadFileListing(UnicodeString Path)
  2584. {
  2585. TStatSessionAction Action(ActionLog, AbsolutePath(Path, true));
  2586. TRemoteFile * File = NULL;
  2587. try
  2588. {
  2589. // reset caches
  2590. AnnounceFileListOperation();
  2591. ReadFile(Path, File);
  2592. Action.File(File);
  2593. }
  2594. catch(Exception & E)
  2595. {
  2596. COMMAND_ERROR_ARI_ACTION
  2597. (
  2598. L"",
  2599. File = ReadFileListing(Path),
  2600. Action
  2601. );
  2602. }
  2603. return File;
  2604. }
  2605. //---------------------------------------------------------------------------
  2606. TRemoteFileList * __fastcall TTerminal::CustomReadDirectoryListing(UnicodeString Directory, bool UseCache)
  2607. {
  2608. TRemoteFileList * FileList = NULL;
  2609. try
  2610. {
  2611. FileList = DoReadDirectoryListing(Directory, UseCache);
  2612. }
  2613. catch(Exception & E)
  2614. {
  2615. COMMAND_ERROR_ARI
  2616. (
  2617. L"",
  2618. FileList = CustomReadDirectoryListing(Directory, UseCache);
  2619. );
  2620. }
  2621. return FileList;
  2622. }
  2623. //---------------------------------------------------------------------------
  2624. TRemoteFileList * __fastcall TTerminal::DoReadDirectoryListing(UnicodeString Directory, bool UseCache)
  2625. {
  2626. TRemoteFileList * FileList = new TRemoteFileList();
  2627. try
  2628. {
  2629. bool Cache = UseCache && SessionData->CacheDirectories;
  2630. bool LoadedFromCache = Cache && FDirectoryCache->HasFileList(Directory);
  2631. if (LoadedFromCache)
  2632. {
  2633. LoadedFromCache = FDirectoryCache->GetFileList(Directory, FileList);
  2634. }
  2635. if (!LoadedFromCache)
  2636. {
  2637. FileList->Directory = Directory;
  2638. ExceptionOnFail = true;
  2639. try
  2640. {
  2641. ReadDirectory(FileList);
  2642. }
  2643. __finally
  2644. {
  2645. ExceptionOnFail = false;
  2646. }
  2647. if (Cache)
  2648. {
  2649. AddCachedFileList(FileList);
  2650. }
  2651. }
  2652. }
  2653. catch(...)
  2654. {
  2655. delete FileList;
  2656. throw;
  2657. }
  2658. return FileList;
  2659. }
  2660. //---------------------------------------------------------------------------
  2661. void __fastcall TTerminal::ProcessDirectory(const UnicodeString DirName,
  2662. TProcessFileEvent CallBackFunc, void * Param, bool UseCache, bool IgnoreErrors)
  2663. {
  2664. TRemoteFileList * FileList = NULL;
  2665. if (IgnoreErrors)
  2666. {
  2667. ExceptionOnFail = true;
  2668. try
  2669. {
  2670. try
  2671. {
  2672. FileList = CustomReadDirectoryListing(DirName, UseCache);
  2673. }
  2674. catch(...)
  2675. {
  2676. if (!Active)
  2677. {
  2678. throw;
  2679. }
  2680. }
  2681. }
  2682. __finally
  2683. {
  2684. ExceptionOnFail = false;
  2685. }
  2686. }
  2687. else
  2688. {
  2689. FileList = CustomReadDirectoryListing(DirName, UseCache);
  2690. }
  2691. // skip if directory listing fails and user selects "skip"
  2692. if (FileList)
  2693. {
  2694. try
  2695. {
  2696. UnicodeString Directory = UnixIncludeTrailingBackslash(DirName);
  2697. TRemoteFile * File;
  2698. for (int Index = 0; Index < FileList->Count; Index++)
  2699. {
  2700. File = FileList->Files[Index];
  2701. if (!File->IsParentDirectory && !File->IsThisDirectory)
  2702. {
  2703. CallBackFunc(Directory + File->FileName, File, Param);
  2704. // We should catch EScpSkipFile here as we do in ProcessFiles.
  2705. // Now we have to handle EScpSkipFile in every callback implementation.
  2706. }
  2707. }
  2708. }
  2709. __finally
  2710. {
  2711. delete FileList;
  2712. }
  2713. }
  2714. }
  2715. //---------------------------------------------------------------------------
  2716. void __fastcall TTerminal::ReadDirectory(TRemoteFileList * FileList)
  2717. {
  2718. try
  2719. {
  2720. CustomReadDirectory(FileList);
  2721. }
  2722. catch (Exception &E)
  2723. {
  2724. CommandError(&E, FmtLoadStr(LIST_DIR_ERROR, ARRAYOFCONST((FileList->Directory))));
  2725. }
  2726. }
  2727. //---------------------------------------------------------------------------
  2728. void __fastcall TTerminal::ReadSymlink(TRemoteFile * SymlinkFile,
  2729. TRemoteFile *& File)
  2730. {
  2731. assert(FFileSystem);
  2732. try
  2733. {
  2734. LogEvent(FORMAT(L"Reading symlink \"%s\".", (SymlinkFile->FileName)));
  2735. FFileSystem->ReadSymlink(SymlinkFile, File);
  2736. ReactOnCommand(fsReadSymlink);
  2737. }
  2738. catch (Exception &E)
  2739. {
  2740. CommandError(&E, FMTLOAD(READ_SYMLINK_ERROR, (SymlinkFile->FileName)));
  2741. }
  2742. }
  2743. //---------------------------------------------------------------------------
  2744. void __fastcall TTerminal::ReadFile(const UnicodeString FileName,
  2745. TRemoteFile *& File)
  2746. {
  2747. assert(FFileSystem);
  2748. File = NULL;
  2749. try
  2750. {
  2751. LogEvent(FORMAT(L"Listing file \"%s\".", (FileName)));
  2752. FFileSystem->ReadFile(FileName, File);
  2753. ReactOnCommand(fsListFile);
  2754. LogRemoteFile(File);
  2755. }
  2756. catch (Exception &E)
  2757. {
  2758. if (File) delete File;
  2759. File = NULL;
  2760. CommandError(&E, FMTLOAD(CANT_GET_ATTRS, (FileName)));
  2761. }
  2762. }
  2763. //---------------------------------------------------------------------------
  2764. bool __fastcall TTerminal::FileExists(const UnicodeString FileName, TRemoteFile ** AFile)
  2765. {
  2766. bool Result;
  2767. TRemoteFile * File = NULL;
  2768. try
  2769. {
  2770. ExceptionOnFail = true;
  2771. try
  2772. {
  2773. ReadFile(FileName, File);
  2774. }
  2775. __finally
  2776. {
  2777. ExceptionOnFail = false;
  2778. }
  2779. if (AFile != NULL)
  2780. {
  2781. *AFile = File;
  2782. }
  2783. else
  2784. {
  2785. delete File;
  2786. }
  2787. Result = true;
  2788. }
  2789. catch(...)
  2790. {
  2791. if (Active)
  2792. {
  2793. Result = false;
  2794. }
  2795. else
  2796. {
  2797. throw;
  2798. }
  2799. }
  2800. return Result;
  2801. }
  2802. //---------------------------------------------------------------------------
  2803. void __fastcall TTerminal::AnnounceFileListOperation()
  2804. {
  2805. FFileSystem->AnnounceFileListOperation();
  2806. }
  2807. //---------------------------------------------------------------------------
  2808. bool __fastcall TTerminal::ProcessFiles(TStrings * FileList,
  2809. TFileOperation Operation, TProcessFileEvent ProcessFile, void * Param,
  2810. TOperationSide Side, bool Ex)
  2811. {
  2812. assert(FFileSystem);
  2813. assert(FileList);
  2814. bool Result = false;
  2815. TOnceDoneOperation OnceDoneOperation = odoIdle;
  2816. try
  2817. {
  2818. TFileOperationProgressType Progress(&DoProgress, &DoFinished);
  2819. Progress.Start(Operation, Side, FileList->Count);
  2820. FOperationProgress = &Progress;
  2821. try
  2822. {
  2823. if (Side == osRemote)
  2824. {
  2825. BeginTransaction();
  2826. }
  2827. try
  2828. {
  2829. int Index = 0;
  2830. UnicodeString FileName;
  2831. bool Success;
  2832. while ((Index < FileList->Count) && (Progress.Cancel == csContinue))
  2833. {
  2834. FileName = FileList->Strings[Index];
  2835. try
  2836. {
  2837. try
  2838. {
  2839. Success = false;
  2840. if (!Ex)
  2841. {
  2842. ProcessFile(FileName, (TRemoteFile *)FileList->Objects[Index], Param);
  2843. }
  2844. else
  2845. {
  2846. // not used anymore
  2847. TProcessFileEventEx ProcessFileEx = (TProcessFileEventEx)ProcessFile;
  2848. ProcessFileEx(FileName, (TRemoteFile *)FileList->Objects[Index], Param, Index);
  2849. }
  2850. Success = true;
  2851. }
  2852. __finally
  2853. {
  2854. Progress.Finish(FileName, Success, OnceDoneOperation);
  2855. }
  2856. }
  2857. catch(EScpSkipFile & E)
  2858. {
  2859. TSuspendFileOperationProgress Suspend(OperationProgress);
  2860. if (!HandleException(&E))
  2861. {
  2862. throw;
  2863. }
  2864. }
  2865. Index++;
  2866. }
  2867. }
  2868. __finally
  2869. {
  2870. if (Side == osRemote)
  2871. {
  2872. EndTransaction();
  2873. }
  2874. }
  2875. if (Progress.Cancel == csContinue)
  2876. {
  2877. Result = true;
  2878. }
  2879. }
  2880. __finally
  2881. {
  2882. FOperationProgress = NULL;
  2883. Progress.Stop();
  2884. }
  2885. }
  2886. catch (...)
  2887. {
  2888. OnceDoneOperation = odoIdle;
  2889. // this was missing here. was it by purpose?
  2890. // without it any error message is lost
  2891. throw;
  2892. }
  2893. if (OnceDoneOperation != odoIdle)
  2894. {
  2895. CloseOnCompletion(OnceDoneOperation);
  2896. }
  2897. return Result;
  2898. }
  2899. //---------------------------------------------------------------------------
  2900. // not used anymore
  2901. bool __fastcall TTerminal::ProcessFilesEx(TStrings * FileList, TFileOperation Operation,
  2902. TProcessFileEventEx ProcessFile, void * Param, TOperationSide Side)
  2903. {
  2904. return ProcessFiles(FileList, Operation, TProcessFileEvent(ProcessFile),
  2905. Param, Side, true);
  2906. }
  2907. //---------------------------------------------------------------------------
  2908. TStrings * __fastcall TTerminal::GetFixedPaths()
  2909. {
  2910. assert(FFileSystem != NULL);
  2911. return FFileSystem->GetFixedPaths();
  2912. }
  2913. //---------------------------------------------------------------------------
  2914. bool __fastcall TTerminal::GetResolvingSymlinks()
  2915. {
  2916. return SessionData->ResolveSymlinks && IsCapable[fcResolveSymlink];
  2917. }
  2918. //---------------------------------------------------------------------------
  2919. TUsableCopyParamAttrs __fastcall TTerminal::UsableCopyParamAttrs(int Params)
  2920. {
  2921. TUsableCopyParamAttrs Result;
  2922. Result.General =
  2923. FLAGMASK(!IsCapable[fcTextMode], cpaNoTransferMode) |
  2924. FLAGMASK(!IsCapable[fcModeChanging], cpaNoRights) |
  2925. FLAGMASK(!IsCapable[fcModeChanging], cpaNoPreserveReadOnly) |
  2926. FLAGMASK(FLAGSET(Params, cpDelete), cpaNoClearArchive) |
  2927. FLAGMASK(!IsCapable[fcIgnorePermErrors], cpaNoIgnorePermErrors) |
  2928. // the following three are never supported for download,
  2929. // so when they are not suppored for upload too,
  2930. // set them in General flags, so that they do not get enabled on
  2931. // Synchronize dialog.
  2932. FLAGMASK(!IsCapable[fcModeChangingUpload], cpaNoRights) |
  2933. FLAGMASK(!IsCapable[fcRemoveCtrlZUpload], cpaNoRemoveCtrlZ) |
  2934. FLAGMASK(!IsCapable[fcRemoveBOMUpload], cpaNoRemoveBOM);
  2935. Result.Download = Result.General | cpaNoClearArchive |
  2936. cpaNoIgnorePermErrors |
  2937. // May be already set in General flags, but it's unconditional here
  2938. cpaNoRights | cpaNoRemoveCtrlZ | cpaNoRemoveBOM;
  2939. Result.Upload = Result.General | cpaNoPreserveReadOnly |
  2940. FLAGMASK(!IsCapable[fcPreservingTimestampUpload], cpaNoPreserveTime);
  2941. return Result;
  2942. }
  2943. //---------------------------------------------------------------------------
  2944. bool __fastcall TTerminal::IsRecycledFile(UnicodeString FileName)
  2945. {
  2946. bool Result = !SessionData->RecycleBinPath.IsEmpty();
  2947. if (Result)
  2948. {
  2949. UnicodeString Path = UnixExtractFilePath(FileName);
  2950. if (Path.IsEmpty())
  2951. {
  2952. Path = CurrentDirectory;
  2953. }
  2954. Result = UnixSamePath(Path, SessionData->RecycleBinPath);
  2955. }
  2956. return Result;
  2957. }
  2958. //---------------------------------------------------------------------------
  2959. void __fastcall TTerminal::RecycleFile(UnicodeString FileName,
  2960. const TRemoteFile * File)
  2961. {
  2962. if (FileName.IsEmpty())
  2963. {
  2964. assert(File != NULL);
  2965. FileName = File->FileName;
  2966. }
  2967. if (!IsRecycledFile(FileName))
  2968. {
  2969. LogEvent(FORMAT(L"Moving file \"%s\" to remote recycle bin '%s'.",
  2970. (FileName, SessionData->RecycleBinPath)));
  2971. TMoveFileParams Params;
  2972. Params.Target = SessionData->RecycleBinPath;
  2973. Params.FileMask = FORMAT(L"*-%s.*", (FormatDateTime(L"yyyymmdd-hhnnss", Now())));
  2974. MoveFile(FileName, File, &Params);
  2975. }
  2976. }
  2977. //---------------------------------------------------------------------------
  2978. void __fastcall TTerminal::DeleteFile(UnicodeString FileName,
  2979. const TRemoteFile * File, void * AParams)
  2980. {
  2981. if (FileName.IsEmpty() && File)
  2982. {
  2983. FileName = File->FileName;
  2984. }
  2985. if (OperationProgress && OperationProgress->Operation == foDelete)
  2986. {
  2987. if (OperationProgress->Cancel != csContinue) Abort();
  2988. OperationProgress->SetFile(FileName);
  2989. }
  2990. int Params = (AParams != NULL) ? *((int*)AParams) : 0;
  2991. bool Recycle =
  2992. FLAGCLEAR(Params, dfForceDelete) &&
  2993. (SessionData->DeleteToRecycleBin != FLAGSET(Params, dfAlternative)) &&
  2994. !SessionData->RecycleBinPath.IsEmpty();
  2995. if (Recycle && !IsRecycledFile(FileName))
  2996. {
  2997. RecycleFile(FileName, File);
  2998. }
  2999. else
  3000. {
  3001. LogEvent(FORMAT(L"Deleting file \"%s\".", (FileName)));
  3002. if (File) FileModified(File, FileName, true);
  3003. DoDeleteFile(FileName, File, Params);
  3004. ReactOnCommand(fsDeleteFile);
  3005. }
  3006. }
  3007. //---------------------------------------------------------------------------
  3008. void __fastcall TTerminal::DoDeleteFile(const UnicodeString FileName,
  3009. const TRemoteFile * File, int Params)
  3010. {
  3011. TRmSessionAction Action(ActionLog, AbsolutePath(FileName, true));
  3012. try
  3013. {
  3014. assert(FFileSystem);
  3015. // 'File' parameter: SFTPFileSystem needs to know if file is file or directory
  3016. FFileSystem->DeleteFile(FileName, File, Params, Action);
  3017. }
  3018. catch(Exception & E)
  3019. {
  3020. COMMAND_ERROR_ARI_ACTION
  3021. (
  3022. FMTLOAD(DELETE_FILE_ERROR, (FileName)),
  3023. DoDeleteFile(FileName, File, Params),
  3024. Action
  3025. );
  3026. }
  3027. }
  3028. //---------------------------------------------------------------------------
  3029. bool __fastcall TTerminal::DeleteFiles(TStrings * FilesToDelete, int Params)
  3030. {
  3031. // TODO: avoid resolving symlinks while reading subdirectories.
  3032. // Resolving does not work anyway for relative symlinks in subdirectories
  3033. // (at least for SFTP).
  3034. return ProcessFiles(FilesToDelete, foDelete, DeleteFile, &Params);
  3035. }
  3036. //---------------------------------------------------------------------------
  3037. void __fastcall TTerminal::DeleteLocalFile(UnicodeString FileName,
  3038. const TRemoteFile * /*File*/, void * Params)
  3039. {
  3040. if ((OperationProgress != NULL) && (OperationProgress->Operation == foDelete))
  3041. {
  3042. OperationProgress->SetFile(FileName);
  3043. }
  3044. if (OnDeleteLocalFile == NULL)
  3045. {
  3046. if (!RecursiveDeleteFile(FileName, false))
  3047. {
  3048. throw Exception(FMTLOAD(DELETE_FILE_ERROR, (FileName)));
  3049. }
  3050. }
  3051. else
  3052. {
  3053. OnDeleteLocalFile(FileName, FLAGSET(*((int*)Params), dfAlternative));
  3054. }
  3055. }
  3056. //---------------------------------------------------------------------------
  3057. bool __fastcall TTerminal::DeleteLocalFiles(TStrings * FileList, int Params)
  3058. {
  3059. return ProcessFiles(FileList, foDelete, DeleteLocalFile, &Params, osLocal);
  3060. }
  3061. //---------------------------------------------------------------------------
  3062. void __fastcall TTerminal::CustomCommandOnFile(UnicodeString FileName,
  3063. const TRemoteFile * File, void * AParams)
  3064. {
  3065. TCustomCommandParams * Params = ((TCustomCommandParams *)AParams);
  3066. if (FileName.IsEmpty() && File)
  3067. {
  3068. FileName = File->FileName;
  3069. }
  3070. if (OperationProgress && OperationProgress->Operation == foCustomCommand)
  3071. {
  3072. if (OperationProgress->Cancel != csContinue) Abort();
  3073. OperationProgress->SetFile(FileName);
  3074. }
  3075. LogEvent(FORMAT(L"Executing custom command \"%s\" (%d) on file \"%s\".",
  3076. (Params->Command, Params->Params, FileName)));
  3077. if (File) FileModified(File, FileName);
  3078. DoCustomCommandOnFile(FileName, File, Params->Command, Params->Params,
  3079. Params->OutputEvent);
  3080. ReactOnCommand(fsAnyCommand);
  3081. }
  3082. //---------------------------------------------------------------------------
  3083. void __fastcall TTerminal::DoCustomCommandOnFile(UnicodeString FileName,
  3084. const TRemoteFile * File, UnicodeString Command, int Params,
  3085. TCaptureOutputEvent OutputEvent)
  3086. {
  3087. try
  3088. {
  3089. if (IsCapable[fcAnyCommand])
  3090. {
  3091. assert(FFileSystem);
  3092. assert(fcShellAnyCommand);
  3093. FFileSystem->CustomCommandOnFile(FileName, File, Command, Params, OutputEvent);
  3094. }
  3095. else
  3096. {
  3097. assert(CommandSessionOpened);
  3098. assert(FCommandSession->FSProtocol == cfsSCP);
  3099. LogEvent(L"Executing custom command on command session.");
  3100. if (FCommandSession->CurrentDirectory != CurrentDirectory)
  3101. {
  3102. FCommandSession->CurrentDirectory = CurrentDirectory;
  3103. // We are likely in transaction, so ReadCurrentDirectory won't get called
  3104. // until transaction ends. But we need to know CurrentDirectory to
  3105. // expand !/ pattern.
  3106. // Doing this only, when current directory of the main and secondary shell differs,
  3107. // what would be the case before the first file in transaction.
  3108. // Otherwise we would be reading pwd before every time as the
  3109. // CustomCommandOnFile on its own sets FReadCurrentDirectoryPending
  3110. if (FCommandSession->FReadCurrentDirectoryPending)
  3111. {
  3112. FCommandSession->ReadCurrentDirectory();
  3113. }
  3114. }
  3115. FCommandSession->FFileSystem->CustomCommandOnFile(FileName, File, Command,
  3116. Params, OutputEvent);
  3117. }
  3118. }
  3119. catch(Exception & E)
  3120. {
  3121. COMMAND_ERROR_ARI
  3122. (
  3123. FMTLOAD(CUSTOM_COMMAND_ERROR, (Command, FileName)),
  3124. DoCustomCommandOnFile(FileName, File, Command, Params, OutputEvent)
  3125. );
  3126. }
  3127. }
  3128. //---------------------------------------------------------------------------
  3129. void __fastcall TTerminal::CustomCommandOnFiles(UnicodeString Command,
  3130. int Params, TStrings * Files, TCaptureOutputEvent OutputEvent)
  3131. {
  3132. if (!TRemoteCustomCommand().IsFileListCommand(Command))
  3133. {
  3134. TCustomCommandParams AParams;
  3135. AParams.Command = Command;
  3136. AParams.Params = Params;
  3137. AParams.OutputEvent = OutputEvent;
  3138. ProcessFiles(Files, foCustomCommand, CustomCommandOnFile, &AParams);
  3139. }
  3140. else
  3141. {
  3142. UnicodeString FileList;
  3143. for (int i = 0; i < Files->Count; i++)
  3144. {
  3145. TRemoteFile * File = static_cast<TRemoteFile *>(Files->Objects[i]);
  3146. bool Dir = File->IsDirectory && !File->IsSymLink;
  3147. if (!Dir || FLAGSET(Params, ccApplyToDirectories))
  3148. {
  3149. if (!FileList.IsEmpty())
  3150. {
  3151. FileList += L" ";
  3152. }
  3153. FileList += L"\"" + ShellDelimitStr(Files->Strings[i], L'"') + L"\"";
  3154. }
  3155. }
  3156. TCustomCommandData Data(this);
  3157. UnicodeString Cmd =
  3158. TRemoteCustomCommand(Data, CurrentDirectory, L"", FileList).
  3159. Complete(Command, true);
  3160. DoAnyCommand(Cmd, OutputEvent, NULL);
  3161. }
  3162. }
  3163. //---------------------------------------------------------------------------
  3164. void __fastcall TTerminal::ChangeFileProperties(UnicodeString FileName,
  3165. const TRemoteFile * File, /*const TRemoteProperties*/ void * Properties)
  3166. {
  3167. TRemoteProperties * RProperties = (TRemoteProperties *)Properties;
  3168. assert(RProperties && !RProperties->Valid.Empty());
  3169. if (FileName.IsEmpty() && File)
  3170. {
  3171. FileName = File->FileName;
  3172. }
  3173. if (OperationProgress && OperationProgress->Operation == foSetProperties)
  3174. {
  3175. if (OperationProgress->Cancel != csContinue) Abort();
  3176. OperationProgress->SetFile(FileName);
  3177. }
  3178. if (Log->Logging)
  3179. {
  3180. LogEvent(FORMAT(L"Changing properties of \"%s\" (%s)",
  3181. (FileName, BooleanToEngStr(RProperties->Recursive))));
  3182. if (RProperties->Valid.Contains(vpRights))
  3183. {
  3184. LogEvent(FORMAT(L" - mode: \"%s\"", (RProperties->Rights.ModeStr)));
  3185. }
  3186. if (RProperties->Valid.Contains(vpGroup))
  3187. {
  3188. LogEvent(FORMAT(L" - group: %s", (RProperties->Group.LogText)));
  3189. }
  3190. if (RProperties->Valid.Contains(vpOwner))
  3191. {
  3192. LogEvent(FORMAT(L" - owner: %s", (RProperties->Owner.LogText)));
  3193. }
  3194. if (RProperties->Valid.Contains(vpModification))
  3195. {
  3196. LogEvent(FORMAT(L" - modification: \"%s\"",
  3197. (FormatDateTime(L"dddddd tt",
  3198. UnixToDateTime(RProperties->Modification, SessionData->DSTMode)))));
  3199. }
  3200. if (RProperties->Valid.Contains(vpLastAccess))
  3201. {
  3202. LogEvent(FORMAT(L" - last access: \"%s\"",
  3203. (FormatDateTime(L"dddddd tt",
  3204. UnixToDateTime(RProperties->LastAccess, SessionData->DSTMode)))));
  3205. }
  3206. }
  3207. FileModified(File, FileName);
  3208. DoChangeFileProperties(FileName, File, RProperties);
  3209. ReactOnCommand(fsChangeProperties);
  3210. }
  3211. //---------------------------------------------------------------------------
  3212. void __fastcall TTerminal::DoChangeFileProperties(const UnicodeString FileName,
  3213. const TRemoteFile * File, const TRemoteProperties * Properties)
  3214. {
  3215. TChmodSessionAction Action(ActionLog, AbsolutePath(FileName, true));
  3216. try
  3217. {
  3218. assert(FFileSystem);
  3219. FFileSystem->ChangeFileProperties(FileName, File, Properties, Action);
  3220. }
  3221. catch(Exception & E)
  3222. {
  3223. COMMAND_ERROR_ARI_ACTION
  3224. (
  3225. FMTLOAD(CHANGE_PROPERTIES_ERROR, (FileName)),
  3226. DoChangeFileProperties(FileName, File, Properties),
  3227. Action
  3228. );
  3229. }
  3230. }
  3231. //---------------------------------------------------------------------------
  3232. void __fastcall TTerminal::ChangeFilesProperties(TStrings * FileList,
  3233. const TRemoteProperties * Properties)
  3234. {
  3235. AnnounceFileListOperation();
  3236. ProcessFiles(FileList, foSetProperties, ChangeFileProperties, (void *)Properties);
  3237. }
  3238. //---------------------------------------------------------------------------
  3239. bool __fastcall TTerminal::LoadFilesProperties(TStrings * FileList)
  3240. {
  3241. // see comment in TSFTPFileSystem::IsCapable
  3242. bool Result =
  3243. IsCapable[fcLoadingAdditionalProperties] &&
  3244. FFileSystem->LoadFilesProperties(FileList);
  3245. if (Result && SessionData->CacheDirectories &&
  3246. (FileList->Count > 0) &&
  3247. (dynamic_cast<TRemoteFile *>(FileList->Objects[0])->Directory == FFiles))
  3248. {
  3249. AddCachedFileList(FFiles);
  3250. }
  3251. return Result;
  3252. }
  3253. //---------------------------------------------------------------------------
  3254. void __fastcall TTerminal::CalculateFileSize(UnicodeString FileName,
  3255. const TRemoteFile * File, /*TCalculateSizeParams*/ void * Param)
  3256. {
  3257. assert(Param);
  3258. assert(File);
  3259. TCalculateSizeParams * AParams = static_cast<TCalculateSizeParams*>(Param);
  3260. if (FileName.IsEmpty())
  3261. {
  3262. FileName = File->FileName;
  3263. }
  3264. if (OperationProgress && OperationProgress->Operation == foCalculateSize)
  3265. {
  3266. if (OperationProgress->Cancel != csContinue)
  3267. {
  3268. AParams->Result = false;
  3269. Abort();
  3270. }
  3271. OperationProgress->SetFile(FileName);
  3272. }
  3273. bool AllowTransfer = (AParams->CopyParam == NULL);
  3274. if (!AllowTransfer)
  3275. {
  3276. TFileMasks::TParams MaskParams;
  3277. MaskParams.Size = File->Size;
  3278. MaskParams.Modification = File->Modification;
  3279. AllowTransfer = AParams->CopyParam->AllowTransfer(
  3280. UnixExcludeTrailingBackslash(File->FullFileName), osRemote, File->IsDirectory,
  3281. MaskParams);
  3282. }
  3283. if (AllowTransfer)
  3284. {
  3285. if (File->IsDirectory)
  3286. {
  3287. if (!File->IsSymLink)
  3288. {
  3289. if (!AParams->AllowDirs)
  3290. {
  3291. AParams->Result = false;
  3292. }
  3293. else
  3294. {
  3295. LogEvent(FORMAT(L"Getting size of directory \"%s\"", (FileName)));
  3296. // pass in full path so we get it back in file list for AllowTransfer() exclusion
  3297. DoCalculateDirectorySize(File->FullFileName, File, AParams);
  3298. }
  3299. }
  3300. if (AParams->Stats != NULL)
  3301. {
  3302. AParams->Stats->Directories++;
  3303. }
  3304. }
  3305. else
  3306. {
  3307. AParams->Size += File->Size;
  3308. if (AParams->Stats != NULL)
  3309. {
  3310. AParams->Stats->Files++;
  3311. }
  3312. }
  3313. if ((AParams->Stats != NULL) && File->IsSymLink)
  3314. {
  3315. AParams->Stats->SymLinks++;
  3316. }
  3317. }
  3318. }
  3319. //---------------------------------------------------------------------------
  3320. void __fastcall TTerminal::DoCalculateDirectorySize(const UnicodeString FileName,
  3321. const TRemoteFile * File, TCalculateSizeParams * Params)
  3322. {
  3323. try
  3324. {
  3325. ProcessDirectory(FileName, CalculateFileSize, Params);
  3326. }
  3327. catch(Exception & E)
  3328. {
  3329. if (!Active || ((Params->Params & csIgnoreErrors) == 0))
  3330. {
  3331. COMMAND_ERROR_ARI
  3332. (
  3333. FMTLOAD(CALCULATE_SIZE_ERROR, (FileName)),
  3334. DoCalculateDirectorySize(FileName, File, Params)
  3335. );
  3336. }
  3337. }
  3338. }
  3339. //---------------------------------------------------------------------------
  3340. bool __fastcall TTerminal::CalculateFilesSize(TStrings * FileList,
  3341. __int64 & Size, int Params, const TCopyParamType * CopyParam,
  3342. bool AllowDirs, TCalculateSizeStats * Stats)
  3343. {
  3344. // With FTP protocol, we may se DSIZ command from
  3345. // draft-peterson-streamlined-ftp-command-extensions-10
  3346. // Implemented by Serv-U FTP.
  3347. TCalculateSizeParams Param;
  3348. Param.Size = 0;
  3349. Param.Params = Params;
  3350. Param.CopyParam = CopyParam;
  3351. Param.Stats = Stats;
  3352. Param.AllowDirs = AllowDirs;
  3353. Param.Result = true;
  3354. ProcessFiles(FileList, foCalculateSize, CalculateFileSize, &Param);
  3355. Size = Param.Size;
  3356. return Param.Result;
  3357. }
  3358. //---------------------------------------------------------------------------
  3359. void __fastcall TTerminal::CalculateFilesChecksum(const UnicodeString & Alg,
  3360. TStrings * FileList, TStrings * Checksums,
  3361. TCalculatedChecksumEvent OnCalculatedChecksum)
  3362. {
  3363. FFileSystem->CalculateFilesChecksum(Alg, FileList, Checksums, OnCalculatedChecksum);
  3364. }
  3365. //---------------------------------------------------------------------------
  3366. void __fastcall TTerminal::RenameFile(const UnicodeString FileName,
  3367. const UnicodeString NewName)
  3368. {
  3369. LogEvent(FORMAT(L"Renaming file \"%s\" to \"%s\".", (FileName, NewName)));
  3370. DoRenameFile(FileName, NewName, false);
  3371. ReactOnCommand(fsRenameFile);
  3372. }
  3373. //---------------------------------------------------------------------------
  3374. void __fastcall TTerminal::RenameFile(const TRemoteFile * File,
  3375. const UnicodeString NewName, bool CheckExistence)
  3376. {
  3377. assert(File && File->Directory == FFiles);
  3378. bool Proceed = true;
  3379. // if filename doesn't contain path, we check for existence of file
  3380. if ((File->FileName != NewName) && CheckExistence &&
  3381. Configuration->ConfirmOverwriting &&
  3382. UnixSamePath(CurrentDirectory, FFiles->Directory))
  3383. {
  3384. TRemoteFile * DuplicateFile = FFiles->FindFile(NewName);
  3385. if (DuplicateFile)
  3386. {
  3387. UnicodeString QuestionFmt;
  3388. if (DuplicateFile->IsDirectory)
  3389. {
  3390. QuestionFmt = LoadStr(DIRECTORY_OVERWRITE);
  3391. }
  3392. else
  3393. {
  3394. QuestionFmt = LoadStr(FILE_OVERWRITE);
  3395. }
  3396. TQueryParams Params(qpNeverAskAgainCheck);
  3397. UnicodeString Question = MainInstructions(FORMAT(QuestionFmt, (NewName)));
  3398. unsigned int Result = QueryUser(Question, NULL,
  3399. qaYes | qaNo, &Params);
  3400. if (Result == qaNeverAskAgain)
  3401. {
  3402. Proceed = true;
  3403. Configuration->ConfirmOverwriting = false;
  3404. }
  3405. else
  3406. {
  3407. Proceed = (Result == qaYes);
  3408. }
  3409. }
  3410. }
  3411. if (Proceed)
  3412. {
  3413. FileModified(File, File->FileName);
  3414. RenameFile(File->FileName, NewName);
  3415. }
  3416. }
  3417. //---------------------------------------------------------------------------
  3418. void __fastcall TTerminal::DoRenameFile(const UnicodeString FileName,
  3419. const UnicodeString NewName, bool Move)
  3420. {
  3421. TMvSessionAction Action(ActionLog, AbsolutePath(FileName, true), AbsolutePath(NewName, true));
  3422. try
  3423. {
  3424. assert(FFileSystem);
  3425. FFileSystem->RenameFile(FileName, NewName);
  3426. }
  3427. catch(Exception & E)
  3428. {
  3429. COMMAND_ERROR_ARI_ACTION
  3430. (
  3431. FMTLOAD(Move ? MOVE_FILE_ERROR : RENAME_FILE_ERROR, (FileName, NewName)),
  3432. DoRenameFile(FileName, NewName, Move),
  3433. Action
  3434. );
  3435. }
  3436. }
  3437. //---------------------------------------------------------------------------
  3438. void __fastcall TTerminal::MoveFile(const UnicodeString FileName,
  3439. const TRemoteFile * File, /*const TMoveFileParams*/ void * Param)
  3440. {
  3441. if (OperationProgress &&
  3442. ((OperationProgress->Operation == foRemoteMove) ||
  3443. (OperationProgress->Operation == foDelete)))
  3444. {
  3445. if (OperationProgress->Cancel != csContinue) Abort();
  3446. OperationProgress->SetFile(FileName);
  3447. }
  3448. assert(Param != NULL);
  3449. const TMoveFileParams & Params = *static_cast<const TMoveFileParams*>(Param);
  3450. UnicodeString NewName = UnixIncludeTrailingBackslash(Params.Target) +
  3451. MaskFileName(UnixExtractFileName(FileName), Params.FileMask);
  3452. LogEvent(FORMAT(L"Moving file \"%s\" to \"%s\".", (FileName, NewName)));
  3453. FileModified(File, FileName);
  3454. DoRenameFile(FileName, NewName, true);
  3455. ReactOnCommand(fsMoveFile);
  3456. }
  3457. //---------------------------------------------------------------------------
  3458. bool __fastcall TTerminal::MoveFiles(TStrings * FileList, const UnicodeString Target,
  3459. const UnicodeString FileMask)
  3460. {
  3461. TMoveFileParams Params;
  3462. Params.Target = Target;
  3463. Params.FileMask = FileMask;
  3464. DirectoryModified(Target, true);
  3465. bool Result;
  3466. BeginTransaction();
  3467. try
  3468. {
  3469. Result = ProcessFiles(FileList, foRemoteMove, MoveFile, &Params);
  3470. }
  3471. __finally
  3472. {
  3473. if (Active)
  3474. {
  3475. UnicodeString WithTrailing = UnixIncludeTrailingBackslash(CurrentDirectory);
  3476. bool PossiblyMoved = false;
  3477. // check if we was moving current directory.
  3478. // this is just optimization to avoid checking existence of current
  3479. // directory after each move operation.
  3480. for (int Index = 0; !PossiblyMoved && (Index < FileList->Count); Index++)
  3481. {
  3482. const TRemoteFile * File =
  3483. dynamic_cast<const TRemoteFile *>(FileList->Objects[Index]);
  3484. // File can be NULL, and filename may not be full path,
  3485. // but currently this is the only way we can move (at least in GUI)
  3486. // current directory
  3487. if ((File != NULL) &&
  3488. File->IsDirectory &&
  3489. ((CurrentDirectory.SubString(1, FileList->Strings[Index].Length()) == FileList->Strings[Index]) &&
  3490. ((FileList->Strings[Index].Length() == CurrentDirectory.Length()) ||
  3491. (CurrentDirectory[FileList->Strings[Index].Length() + 1] == L'/'))))
  3492. {
  3493. PossiblyMoved = true;
  3494. }
  3495. }
  3496. if (PossiblyMoved && !FileExists(CurrentDirectory))
  3497. {
  3498. UnicodeString NearestExisting = CurrentDirectory;
  3499. do
  3500. {
  3501. NearestExisting = UnixExtractFileDir(NearestExisting);
  3502. }
  3503. while (!IsUnixRootPath(NearestExisting) && !FileExists(NearestExisting));
  3504. ChangeDirectory(NearestExisting);
  3505. }
  3506. }
  3507. EndTransaction();
  3508. }
  3509. return Result;
  3510. }
  3511. //---------------------------------------------------------------------------
  3512. void __fastcall TTerminal::DoCopyFile(const UnicodeString FileName,
  3513. const UnicodeString NewName)
  3514. {
  3515. try
  3516. {
  3517. assert(FFileSystem);
  3518. if (IsCapable[fcRemoteCopy])
  3519. {
  3520. FFileSystem->CopyFile(FileName, NewName);
  3521. }
  3522. else
  3523. {
  3524. assert(CommandSessionOpened);
  3525. assert(FCommandSession->FSProtocol == cfsSCP);
  3526. LogEvent(L"Copying file on command session.");
  3527. FCommandSession->CurrentDirectory = CurrentDirectory;
  3528. FCommandSession->FFileSystem->CopyFile(FileName, NewName);
  3529. }
  3530. }
  3531. catch(Exception & E)
  3532. {
  3533. COMMAND_ERROR_ARI
  3534. (
  3535. FMTLOAD(COPY_FILE_ERROR, (FileName, NewName)),
  3536. DoCopyFile(FileName, NewName)
  3537. );
  3538. }
  3539. }
  3540. //---------------------------------------------------------------------------
  3541. void __fastcall TTerminal::CopyFile(const UnicodeString FileName,
  3542. const TRemoteFile * /*File*/, /*const TMoveFileParams*/ void * Param)
  3543. {
  3544. if (OperationProgress && (OperationProgress->Operation == foRemoteCopy))
  3545. {
  3546. if (OperationProgress->Cancel != csContinue) Abort();
  3547. OperationProgress->SetFile(FileName);
  3548. }
  3549. assert(Param != NULL);
  3550. const TMoveFileParams & Params = *static_cast<const TMoveFileParams*>(Param);
  3551. UnicodeString NewName = UnixIncludeTrailingBackslash(Params.Target) +
  3552. MaskFileName(UnixExtractFileName(FileName), Params.FileMask);
  3553. LogEvent(FORMAT(L"Copying file \"%s\" to \"%s\".", (FileName, NewName)));
  3554. DoCopyFile(FileName, NewName);
  3555. ReactOnCommand(fsCopyFile);
  3556. }
  3557. //---------------------------------------------------------------------------
  3558. bool __fastcall TTerminal::CopyFiles(TStrings * FileList, const UnicodeString Target,
  3559. const UnicodeString FileMask)
  3560. {
  3561. TMoveFileParams Params;
  3562. Params.Target = Target;
  3563. Params.FileMask = FileMask;
  3564. DirectoryModified(Target, true);
  3565. return ProcessFiles(FileList, foRemoteCopy, CopyFile, &Params);
  3566. }
  3567. //---------------------------------------------------------------------------
  3568. void __fastcall TTerminal::CreateDirectory(const UnicodeString DirName,
  3569. const TRemoteProperties * Properties)
  3570. {
  3571. assert(FFileSystem);
  3572. EnsureNonExistence(DirName);
  3573. FileModified(NULL, DirName);
  3574. LogEvent(FORMAT(L"Creating directory \"%s\".", (DirName)));
  3575. DoCreateDirectory(DirName);
  3576. if ((Properties != NULL) && !Properties->Valid.Empty())
  3577. {
  3578. DoChangeFileProperties(DirName, NULL, Properties);
  3579. }
  3580. ReactOnCommand(fsCreateDirectory);
  3581. }
  3582. //---------------------------------------------------------------------------
  3583. void __fastcall TTerminal::DoCreateDirectory(const UnicodeString DirName)
  3584. {
  3585. TMkdirSessionAction Action(ActionLog, AbsolutePath(DirName, true));
  3586. try
  3587. {
  3588. assert(FFileSystem);
  3589. FFileSystem->CreateDirectory(DirName);
  3590. }
  3591. catch(Exception & E)
  3592. {
  3593. COMMAND_ERROR_ARI_ACTION
  3594. (
  3595. FMTLOAD(CREATE_DIR_ERROR, (DirName)),
  3596. DoCreateDirectory(DirName),
  3597. Action
  3598. );
  3599. }
  3600. }
  3601. //---------------------------------------------------------------------------
  3602. void __fastcall TTerminal::CreateLink(const UnicodeString FileName,
  3603. const UnicodeString PointTo, bool Symbolic)
  3604. {
  3605. assert(FFileSystem);
  3606. EnsureNonExistence(FileName);
  3607. if (SessionData->CacheDirectories)
  3608. {
  3609. DirectoryModified(CurrentDirectory, false);
  3610. }
  3611. LogEvent(FORMAT(L"Creating link \"%s\" to \"%s\" (symbolic: %s).",
  3612. (FileName, PointTo, BooleanToEngStr(Symbolic))));
  3613. DoCreateLink(FileName, PointTo, Symbolic);
  3614. ReactOnCommand(fsCreateDirectory);
  3615. }
  3616. //---------------------------------------------------------------------------
  3617. void __fastcall TTerminal::DoCreateLink(const UnicodeString FileName,
  3618. const UnicodeString PointTo, bool Symbolic)
  3619. {
  3620. try
  3621. {
  3622. assert(FFileSystem);
  3623. FFileSystem->CreateLink(FileName, PointTo, Symbolic);
  3624. }
  3625. catch(Exception & E)
  3626. {
  3627. COMMAND_ERROR_ARI
  3628. (
  3629. FMTLOAD(CREATE_LINK_ERROR, (FileName)),
  3630. DoCreateLink(FileName, PointTo, Symbolic);
  3631. );
  3632. }
  3633. }
  3634. //---------------------------------------------------------------------------
  3635. void __fastcall TTerminal::HomeDirectory()
  3636. {
  3637. assert(FFileSystem);
  3638. try
  3639. {
  3640. LogEvent(L"Changing directory to home directory.");
  3641. FFileSystem->HomeDirectory();
  3642. ReactOnCommand(fsHomeDirectory);
  3643. }
  3644. catch (Exception &E)
  3645. {
  3646. CommandError(&E, LoadStr(CHANGE_HOMEDIR_ERROR));
  3647. }
  3648. }
  3649. //---------------------------------------------------------------------------
  3650. void __fastcall TTerminal::ChangeDirectory(const UnicodeString Directory)
  3651. {
  3652. assert(FFileSystem);
  3653. try
  3654. {
  3655. UnicodeString CachedDirectory;
  3656. assert(!SessionData->CacheDirectoryChanges || (FDirectoryChangesCache != NULL));
  3657. // never use directory change cache during startup, this ensures, we never
  3658. // end-up initially in non-existing directory
  3659. if ((Status == ssOpened) &&
  3660. SessionData->CacheDirectoryChanges &&
  3661. FDirectoryChangesCache->GetDirectoryChange(PeekCurrentDirectory(),
  3662. Directory, CachedDirectory))
  3663. {
  3664. LogEvent(FORMAT(L"Cached directory change via \"%s\" to \"%s\".",
  3665. (Directory, CachedDirectory)));
  3666. FFileSystem->CachedChangeDirectory(CachedDirectory);
  3667. }
  3668. else
  3669. {
  3670. LogEvent(FORMAT(L"Changing directory to \"%s\".", (Directory)));
  3671. FFileSystem->ChangeDirectory(Directory);
  3672. }
  3673. FLastDirectoryChange = Directory;
  3674. ReactOnCommand(fsChangeDirectory);
  3675. }
  3676. catch (Exception &E)
  3677. {
  3678. CommandError(&E, FMTLOAD(CHANGE_DIR_ERROR, (Directory)));
  3679. }
  3680. }
  3681. //---------------------------------------------------------------------------
  3682. void __fastcall TTerminal::LookupUsersGroups()
  3683. {
  3684. if (!FUsersGroupsLookedup && (SessionData->LookupUserGroups != asOff) &&
  3685. IsCapable[fcUserGroupListing])
  3686. {
  3687. assert(FFileSystem);
  3688. try
  3689. {
  3690. FUsersGroupsLookedup = true;
  3691. LogEvent(L"Looking up groups and users.");
  3692. FFileSystem->LookupUsersGroups();
  3693. ReactOnCommand(fsLookupUsersGroups);
  3694. if (Log->Logging)
  3695. {
  3696. FGroups.Log(this, L"groups");
  3697. FMembership.Log(this, L"membership");
  3698. FUsers.Log(this, L"users");
  3699. }
  3700. }
  3701. catch (Exception &E)
  3702. {
  3703. if (!Active || (SessionData->LookupUserGroups == asOn))
  3704. {
  3705. CommandError(&E, LoadStr(LOOKUP_GROUPS_ERROR));
  3706. }
  3707. }
  3708. }
  3709. }
  3710. //---------------------------------------------------------------------------
  3711. bool __fastcall TTerminal::AllowedAnyCommand(const UnicodeString Command)
  3712. {
  3713. return !Command.Trim().IsEmpty();
  3714. }
  3715. //---------------------------------------------------------------------------
  3716. bool __fastcall TTerminal::GetCommandSessionOpened()
  3717. {
  3718. // consider secondary terminal open in "ready" state only
  3719. // so we never do keepalives on it until it is completely initialized
  3720. return (FCommandSession != NULL) &&
  3721. (FCommandSession->Status == ssOpened);
  3722. }
  3723. //---------------------------------------------------------------------------
  3724. TTerminal * __fastcall TTerminal::GetCommandSession()
  3725. {
  3726. if ((FCommandSession != NULL) && !FCommandSession->Active)
  3727. {
  3728. SAFE_DESTROY(FCommandSession);
  3729. }
  3730. if (FCommandSession == NULL)
  3731. {
  3732. // transaction cannot be started yet to allow proper matching transaction
  3733. // levels between main and command session
  3734. assert(FInTransaction == 0);
  3735. try
  3736. {
  3737. FCommandSession = new TSecondaryTerminal(this, SessionData,
  3738. Configuration, L"Shell");
  3739. FCommandSession->AutoReadDirectory = false;
  3740. TSessionData * CommandSessionData = FCommandSession->FSessionData;
  3741. CommandSessionData->RemoteDirectory = CurrentDirectory;
  3742. CommandSessionData->FSProtocol = fsSCPonly;
  3743. CommandSessionData->ClearAliases = false;
  3744. CommandSessionData->UnsetNationalVars = false;
  3745. CommandSessionData->LookupUserGroups = asOff;
  3746. FCommandSession->FExceptionOnFail = FExceptionOnFail;
  3747. FCommandSession->OnQueryUser = OnQueryUser;
  3748. FCommandSession->OnPromptUser = OnPromptUser;
  3749. FCommandSession->OnShowExtendedException = OnShowExtendedException;
  3750. FCommandSession->OnProgress = OnProgress;
  3751. FCommandSession->OnFinished = OnFinished;
  3752. FCommandSession->OnInformation = OnInformation;
  3753. // do not copy OnDisplayBanner to avoid it being displayed
  3754. }
  3755. catch(...)
  3756. {
  3757. SAFE_DESTROY(FCommandSession);
  3758. throw;
  3759. }
  3760. }
  3761. return FCommandSession;
  3762. }
  3763. //---------------------------------------------------------------------------
  3764. void __fastcall TTerminal::AnyCommand(const UnicodeString Command,
  3765. TCaptureOutputEvent OutputEvent)
  3766. {
  3767. class TOutputProxy
  3768. {
  3769. public:
  3770. __fastcall TOutputProxy(TCallSessionAction & Action, TCaptureOutputEvent OutputEvent) :
  3771. FAction(Action),
  3772. FOutputEvent(OutputEvent)
  3773. {
  3774. }
  3775. void __fastcall Output(const UnicodeString & Str, TCaptureOutputType OutputType)
  3776. {
  3777. switch (OutputType)
  3778. {
  3779. case cotOutput:
  3780. FAction.AddOutput(Str, false);
  3781. break;
  3782. case cotError:
  3783. FAction.AddOutput(Str, true);
  3784. break;
  3785. case cotExitCode:
  3786. FAction.ExitCode(StrToInt(Str));
  3787. break;
  3788. }
  3789. if (FOutputEvent != NULL)
  3790. {
  3791. FOutputEvent(Str, OutputType);
  3792. }
  3793. }
  3794. private:
  3795. TCallSessionAction & FAction;
  3796. TCaptureOutputEvent FOutputEvent;
  3797. };
  3798. TCallSessionAction Action(ActionLog, Command, CurrentDirectory);
  3799. TOutputProxy ProxyOutputEvent(Action, OutputEvent);
  3800. DoAnyCommand(Command, ProxyOutputEvent.Output, &Action);
  3801. }
  3802. //---------------------------------------------------------------------------
  3803. void __fastcall TTerminal::DoAnyCommand(const UnicodeString Command,
  3804. TCaptureOutputEvent OutputEvent, TCallSessionAction * Action)
  3805. {
  3806. assert(FFileSystem);
  3807. try
  3808. {
  3809. DirectoryModified(CurrentDirectory, false);
  3810. if (IsCapable[fcAnyCommand])
  3811. {
  3812. LogEvent(L"Executing user defined command.");
  3813. FFileSystem->AnyCommand(Command, OutputEvent);
  3814. }
  3815. else
  3816. {
  3817. assert(CommandSessionOpened);
  3818. assert(FCommandSession->FSProtocol == cfsSCP);
  3819. LogEvent(L"Executing user defined command on command session.");
  3820. FCommandSession->CurrentDirectory = CurrentDirectory;
  3821. FCommandSession->FFileSystem->AnyCommand(Command, OutputEvent);
  3822. FCommandSession->FFileSystem->ReadCurrentDirectory();
  3823. // synchronize pwd (by purpose we lose transaction optimization here)
  3824. ChangeDirectory(FCommandSession->CurrentDirectory);
  3825. }
  3826. ReactOnCommand(fsAnyCommand);
  3827. }
  3828. catch (Exception &E)
  3829. {
  3830. if (Action != NULL)
  3831. {
  3832. RollbackAction(*Action, NULL, &E);
  3833. }
  3834. if (ExceptionOnFail || (E.InheritsFrom(__classid(EFatal)))) throw;
  3835. else HandleExtendedException(&E);
  3836. }
  3837. }
  3838. //---------------------------------------------------------------------------
  3839. bool __fastcall TTerminal::DoCreateLocalFile(const UnicodeString FileName,
  3840. TFileOperationProgressType * OperationProgress, HANDLE * AHandle,
  3841. bool NoConfirmation)
  3842. {
  3843. bool Result = true;
  3844. bool Done;
  3845. unsigned int CreateAttr = FILE_ATTRIBUTE_NORMAL;
  3846. do
  3847. {
  3848. *AHandle = CreateFile(ApiPath(FileName).c_str(), GENERIC_WRITE, FILE_SHARE_READ,
  3849. NULL, CREATE_ALWAYS, CreateAttr, 0);
  3850. Done = (*AHandle != INVALID_HANDLE_VALUE);
  3851. if (!Done)
  3852. {
  3853. // save the error, otherwise it gets overwritten by call to FileExists
  3854. int LastError = GetLastError();
  3855. int FileAttr;
  3856. if (::FileExists(ApiPath(FileName)) &&
  3857. (((FileAttr = FileGetAttr(ApiPath(FileName))) & (faReadOnly | faHidden)) != 0))
  3858. {
  3859. if (FLAGSET(FileAttr, faReadOnly))
  3860. {
  3861. if (OperationProgress->BatchOverwrite == boNone)
  3862. {
  3863. Result = false;
  3864. }
  3865. else if ((OperationProgress->BatchOverwrite != boAll) && !NoConfirmation)
  3866. {
  3867. unsigned int Answer;
  3868. {
  3869. TSuspendFileOperationProgress Suspend(OperationProgress);
  3870. Answer = QueryUser(
  3871. MainInstructions(FMTLOAD(READ_ONLY_OVERWRITE, (FileName))), NULL,
  3872. qaYes | qaNo | qaCancel | qaYesToAll | qaNoToAll, 0);
  3873. }
  3874. switch (Answer) {
  3875. case qaYesToAll: OperationProgress->BatchOverwrite = boAll; break;
  3876. case qaCancel: OperationProgress->Cancel = csCancel; // continue on next case
  3877. case qaNoToAll: OperationProgress->BatchOverwrite = boNone;
  3878. case qaNo: Result = false; break;
  3879. }
  3880. }
  3881. }
  3882. else
  3883. {
  3884. assert(FLAGSET(FileAttr, faHidden));
  3885. Result = true;
  3886. }
  3887. if (Result)
  3888. {
  3889. CreateAttr |=
  3890. FLAGMASK(FLAGSET(FileAttr, faHidden), FILE_ATTRIBUTE_HIDDEN) |
  3891. FLAGMASK(FLAGSET(FileAttr, faReadOnly), FILE_ATTRIBUTE_READONLY);
  3892. FILE_OPERATION_LOOP_BEGIN
  3893. {
  3894. if (FileSetAttr(ApiPath(FileName), FileAttr & ~(faReadOnly | faHidden)) != 0)
  3895. {
  3896. RaiseLastOSError();
  3897. }
  3898. }
  3899. FILE_OPERATION_LOOP_END(FMTLOAD(CANT_SET_ATTRS, (FileName)));
  3900. }
  3901. else
  3902. {
  3903. Done = true;
  3904. }
  3905. }
  3906. else
  3907. {
  3908. RaiseLastOSError(LastError);
  3909. }
  3910. }
  3911. }
  3912. while (!Done);
  3913. return Result;
  3914. }
  3915. //---------------------------------------------------------------------------
  3916. bool __fastcall TTerminal::CreateLocalFile(const UnicodeString FileName,
  3917. TFileOperationProgressType * OperationProgress, HANDLE * AHandle,
  3918. bool NoConfirmation)
  3919. {
  3920. assert(AHandle);
  3921. bool Result = true;
  3922. FILE_OPERATION_LOOP_BEGIN
  3923. {
  3924. Result = DoCreateLocalFile(FileName, OperationProgress, AHandle, NoConfirmation);
  3925. }
  3926. FILE_OPERATION_LOOP_END(FMTLOAD(CREATE_FILE_ERROR, (FileName)));
  3927. return Result;
  3928. }
  3929. //---------------------------------------------------------------------------
  3930. void __fastcall TTerminal::OpenLocalFile(const UnicodeString FileName,
  3931. unsigned int Access, int * AAttrs, HANDLE * AHandle, __int64 * ACTime,
  3932. __int64 * AMTime, __int64 * AATime, __int64 * ASize,
  3933. bool TryWriteReadOnly)
  3934. {
  3935. int Attrs = 0;
  3936. HANDLE Handle = 0;
  3937. FILE_OPERATION_LOOP_BEGIN
  3938. {
  3939. Attrs = FileGetAttr(ApiPath(FileName));
  3940. if (Attrs < 0) RaiseLastOSError();
  3941. }
  3942. FILE_OPERATION_LOOP_END(FMTLOAD(FILE_NOT_EXISTS, (FileName)));
  3943. if ((Attrs & faDirectory) == 0)
  3944. {
  3945. bool NoHandle = false;
  3946. if (!TryWriteReadOnly && (Access == GENERIC_WRITE) &&
  3947. ((Attrs & faReadOnly) != 0))
  3948. {
  3949. Access = GENERIC_READ;
  3950. NoHandle = true;
  3951. }
  3952. FILE_OPERATION_LOOP_BEGIN
  3953. {
  3954. Handle = CreateFile(ApiPath(FileName).c_str(), Access,
  3955. Access == GENERIC_READ ? FILE_SHARE_READ | FILE_SHARE_WRITE : FILE_SHARE_READ,
  3956. NULL, OPEN_EXISTING, 0, 0);
  3957. if (Handle == INVALID_HANDLE_VALUE)
  3958. {
  3959. Handle = 0;
  3960. RaiseLastOSError();
  3961. }
  3962. }
  3963. FILE_OPERATION_LOOP_END(FMTLOAD(OPENFILE_ERROR, (FileName)));
  3964. try
  3965. {
  3966. if (AATime || AMTime || ACTime)
  3967. {
  3968. FILETIME ATime;
  3969. FILETIME MTime;
  3970. FILETIME CTime;
  3971. // Get last file access and modification time
  3972. FILE_OPERATION_LOOP_BEGIN
  3973. {
  3974. THROWOSIFFALSE(GetFileTime(Handle, &CTime, &ATime, &MTime));
  3975. }
  3976. FILE_OPERATION_LOOP_END(FMTLOAD(CANT_GET_ATTRS, (FileName)));
  3977. if (ACTime)
  3978. {
  3979. *ACTime = ConvertTimestampToUnixSafe(CTime, SessionData->DSTMode);
  3980. }
  3981. if (AATime)
  3982. {
  3983. *AATime = ConvertTimestampToUnixSafe(ATime, SessionData->DSTMode);
  3984. }
  3985. if (AMTime)
  3986. {
  3987. *AMTime = ConvertTimestampToUnix(MTime, SessionData->DSTMode);
  3988. }
  3989. }
  3990. if (ASize)
  3991. {
  3992. // Get file size
  3993. FILE_OPERATION_LOOP_BEGIN
  3994. {
  3995. unsigned long LSize;
  3996. unsigned long HSize;
  3997. LSize = GetFileSize(Handle, &HSize);
  3998. if ((LSize == 0xFFFFFFFF) && (GetLastError() != NO_ERROR)) RaiseLastOSError();
  3999. *ASize = (__int64(HSize) << 32) + LSize;
  4000. }
  4001. FILE_OPERATION_LOOP_END(FMTLOAD(CANT_GET_ATTRS, (FileName)));
  4002. }
  4003. if ((AHandle == NULL) || NoHandle)
  4004. {
  4005. CloseHandle(Handle);
  4006. Handle = NULL;
  4007. }
  4008. }
  4009. catch(...)
  4010. {
  4011. CloseHandle(Handle);
  4012. throw;
  4013. }
  4014. }
  4015. if (AAttrs) *AAttrs = Attrs;
  4016. if (AHandle) *AHandle = Handle;
  4017. }
  4018. //---------------------------------------------------------------------------
  4019. bool __fastcall TTerminal::AllowLocalFileTransfer(UnicodeString FileName,
  4020. const TCopyParamType * CopyParam, TFileOperationProgressType * OperationProgress)
  4021. {
  4022. bool Result = true;
  4023. // optimization
  4024. if (Log->Logging || !CopyParam->AllowAnyTransfer())
  4025. {
  4026. WIN32_FIND_DATA FindData;
  4027. HANDLE Handle;
  4028. FILE_OPERATION_LOOP_BEGIN
  4029. {
  4030. Handle = FindFirstFile(ApiPath(ExcludeTrailingBackslash(FileName)).c_str(), &FindData);
  4031. if (Handle == INVALID_HANDLE_VALUE)
  4032. {
  4033. RaiseLastOSError();
  4034. }
  4035. }
  4036. FILE_OPERATION_LOOP_END(FMTLOAD(FILE_NOT_EXISTS, (FileName)));
  4037. ::FindClose(Handle);
  4038. bool Directory = FLAGSET(FindData.dwFileAttributes, FILE_ATTRIBUTE_DIRECTORY);
  4039. TFileMasks::TParams Params;
  4040. // SearchRec.Size in C++B2010 is __int64,
  4041. // so we should be able to use it instead of FindData.nFileSize*
  4042. Params.Size =
  4043. (static_cast<__int64>(FindData.nFileSizeHigh) << 32) +
  4044. FindData.nFileSizeLow;
  4045. Params.Modification = FileTimeToDateTime(FindData.ftLastWriteTime);
  4046. if (!CopyParam->AllowTransfer(FileName, osLocal, Directory, Params))
  4047. {
  4048. LogEvent(FORMAT(L"File \"%s\" excluded from transfer", (FileName)));
  4049. Result = false;
  4050. }
  4051. else if (CopyParam->SkipTransfer(FileName, Directory))
  4052. {
  4053. OperationProgress->AddSkippedFileSize(Params.Size);
  4054. Result = false;
  4055. }
  4056. if (Result)
  4057. {
  4058. LogFileDetails(FileName, Params.Modification, Params.Size);
  4059. }
  4060. }
  4061. return Result;
  4062. }
  4063. //---------------------------------------------------------------------------
  4064. void __fastcall TTerminal::MakeLocalFileList(const UnicodeString FileName,
  4065. const TSearchRec Rec, void * Param)
  4066. {
  4067. TMakeLocalFileListParams & Params = *static_cast<TMakeLocalFileListParams*>(Param);
  4068. bool Directory = FLAGSET(Rec.Attr, faDirectory);
  4069. if (Directory && Params.Recursive)
  4070. {
  4071. ProcessLocalDirectory(FileName, MakeLocalFileList, &Params);
  4072. }
  4073. if (!Directory || Params.IncludeDirs)
  4074. {
  4075. Params.FileList->Add(FileName);
  4076. if (Params.FileTimes != NULL)
  4077. {
  4078. Params.FileTimes->push_back(const_cast<TSearchRec &>(Rec).TimeStamp);
  4079. }
  4080. }
  4081. }
  4082. //---------------------------------------------------------------------------
  4083. void __fastcall TTerminal::CalculateLocalFileSize(const UnicodeString FileName,
  4084. const TSearchRec Rec, /*TCalculateSizeParams*/ void * Params)
  4085. {
  4086. TCalculateSizeParams * AParams = static_cast<TCalculateSizeParams*>(Params);
  4087. bool Dir = FLAGSET(Rec.Attr, faDirectory);
  4088. bool AllowTransfer = (AParams->CopyParam == NULL);
  4089. // SearchRec.Size in C++B2010 is __int64,
  4090. // so we should be able to use it instead of FindData.nFileSize*
  4091. __int64 Size =
  4092. (static_cast<__int64>(Rec.FindData.nFileSizeHigh) << 32) +
  4093. Rec.FindData.nFileSizeLow;
  4094. if (!AllowTransfer)
  4095. {
  4096. TFileMasks::TParams MaskParams;
  4097. MaskParams.Size = Size;
  4098. MaskParams.Modification = FileTimeToDateTime(Rec.FindData.ftLastWriteTime);
  4099. AllowTransfer = AParams->CopyParam->AllowTransfer(FileName, osLocal, Dir, MaskParams);
  4100. }
  4101. if (AllowTransfer)
  4102. {
  4103. if (!Dir)
  4104. {
  4105. AParams->Size += Size;
  4106. }
  4107. else
  4108. {
  4109. ProcessLocalDirectory(FileName, CalculateLocalFileSize, Params);
  4110. }
  4111. }
  4112. if (OperationProgress && OperationProgress->Operation == foCalculateSize)
  4113. {
  4114. if (OperationProgress->Cancel != csContinue) Abort();
  4115. OperationProgress->SetFile(FileName);
  4116. }
  4117. }
  4118. //---------------------------------------------------------------------------
  4119. bool __fastcall TTerminal::CalculateLocalFilesSize(TStrings * FileList,
  4120. __int64 & Size, const TCopyParamType * CopyParam, bool AllowDirs)
  4121. {
  4122. bool Result = true;
  4123. TFileOperationProgressType OperationProgress(&DoProgress, &DoFinished);
  4124. TOnceDoneOperation OnceDoneOperation = odoIdle;
  4125. OperationProgress.Start(foCalculateSize, osLocal, FileList->Count);
  4126. try
  4127. {
  4128. TCalculateSizeParams Params;
  4129. Params.Size = 0;
  4130. Params.Params = 0;
  4131. Params.CopyParam = CopyParam;
  4132. assert(!FOperationProgress);
  4133. FOperationProgress = &OperationProgress;
  4134. for (int Index = 0; Result && (Index < FileList->Count); Index++)
  4135. {
  4136. UnicodeString FileName = FileList->Strings[Index];
  4137. TSearchRec Rec;
  4138. if (FileSearchRec(FileName, Rec))
  4139. {
  4140. if (FLAGSET(Rec.Attr, faDirectory) && !AllowDirs)
  4141. {
  4142. Result = false;
  4143. }
  4144. else
  4145. {
  4146. CalculateLocalFileSize(FileName, Rec, &Params);
  4147. OperationProgress.Finish(FileName, true, OnceDoneOperation);
  4148. }
  4149. }
  4150. }
  4151. Size = Params.Size;
  4152. }
  4153. __finally
  4154. {
  4155. FOperationProgress = NULL;
  4156. OperationProgress.Stop();
  4157. }
  4158. if (OnceDoneOperation != odoIdle)
  4159. {
  4160. CloseOnCompletion(OnceDoneOperation);
  4161. }
  4162. return Result;
  4163. }
  4164. //---------------------------------------------------------------------------
  4165. struct TSynchronizeFileData
  4166. {
  4167. bool Modified;
  4168. bool New;
  4169. bool IsDirectory;
  4170. TSynchronizeChecklist::TItem::TFileInfo Info;
  4171. TSynchronizeChecklist::TItem::TFileInfo MatchingRemoteFile;
  4172. TRemoteFile * MatchingRemoteFileFile;
  4173. int MatchingRemoteFileImageIndex;
  4174. FILETIME LocalLastWriteTime;
  4175. };
  4176. //---------------------------------------------------------------------------
  4177. const int sfFirstLevel = 0x01;
  4178. struct TSynchronizeData
  4179. {
  4180. UnicodeString LocalDirectory;
  4181. UnicodeString RemoteDirectory;
  4182. TTerminal::TSynchronizeMode Mode;
  4183. int Params;
  4184. TSynchronizeDirectory OnSynchronizeDirectory;
  4185. TSynchronizeOptions * Options;
  4186. int Flags;
  4187. TStringList * LocalFileList;
  4188. const TCopyParamType * CopyParam;
  4189. TSynchronizeChecklist * Checklist;
  4190. };
  4191. //---------------------------------------------------------------------------
  4192. TSynchronizeChecklist * __fastcall TTerminal::SynchronizeCollect(const UnicodeString LocalDirectory,
  4193. const UnicodeString RemoteDirectory, TSynchronizeMode Mode,
  4194. const TCopyParamType * CopyParam, int Params,
  4195. TSynchronizeDirectory OnSynchronizeDirectory,
  4196. TSynchronizeOptions * Options)
  4197. {
  4198. TSynchronizeChecklist * Checklist = new TSynchronizeChecklist();
  4199. try
  4200. {
  4201. DoSynchronizeCollectDirectory(LocalDirectory, RemoteDirectory, Mode,
  4202. CopyParam, Params, OnSynchronizeDirectory, Options, sfFirstLevel,
  4203. Checklist);
  4204. Checklist->Sort();
  4205. }
  4206. catch(...)
  4207. {
  4208. delete Checklist;
  4209. throw;
  4210. }
  4211. return Checklist;
  4212. }
  4213. //---------------------------------------------------------------------------
  4214. static void __fastcall AddFlagName(UnicodeString & ParamsStr, int & Params, int Param, const UnicodeString & Name)
  4215. {
  4216. if (FLAGSET(Params, Param))
  4217. {
  4218. AddToList(ParamsStr, Name, ", ");
  4219. }
  4220. Params &= ~Param;
  4221. }
  4222. //---------------------------------------------------------------------------
  4223. UnicodeString __fastcall TTerminal::SynchronizeModeStr(TSynchronizeMode Mode)
  4224. {
  4225. UnicodeString ModeStr;
  4226. switch (Mode)
  4227. {
  4228. case smRemote:
  4229. ModeStr = L"Remote";
  4230. break;
  4231. case smLocal:
  4232. ModeStr = L"Local";
  4233. break;
  4234. case smBoth:
  4235. ModeStr = L"Both";
  4236. break;
  4237. default:
  4238. ModeStr = L"Unknown";
  4239. break;
  4240. }
  4241. return ModeStr;
  4242. }
  4243. //---------------------------------------------------------------------------
  4244. UnicodeString __fastcall TTerminal::SynchronizeParamsStr(int Params)
  4245. {
  4246. UnicodeString ParamsStr;
  4247. AddFlagName(ParamsStr, Params, spDelete, L"Delete");
  4248. AddFlagName(ParamsStr, Params, spNoConfirmation, L"NoConfirmation");
  4249. AddFlagName(ParamsStr, Params, spExistingOnly, L"ExistingOnly");
  4250. AddFlagName(ParamsStr, Params, spNoRecurse, L"NoRecurse");
  4251. AddFlagName(ParamsStr, Params, spUseCache, L"UseCache");
  4252. AddFlagName(ParamsStr, Params, spDelayProgress, L"DelayProgress");
  4253. AddFlagName(ParamsStr, Params, spPreviewChanges, L"*PreviewChanges"); // GUI only
  4254. AddFlagName(ParamsStr, Params, spSubDirs, L"SubDirs");
  4255. AddFlagName(ParamsStr, Params, spTimestamp, L"Timestamp");
  4256. AddFlagName(ParamsStr, Params, spNotByTime, L"NotByTime");
  4257. AddFlagName(ParamsStr, Params, spBySize, L"BySize");
  4258. AddFlagName(ParamsStr, Params, spSelectedOnly, L"*SelectedOnly"); // GUI only
  4259. AddFlagName(ParamsStr, Params, spMirror, L"Mirror");
  4260. if (Params > 0)
  4261. {
  4262. AddToList(ParamsStr, FORMAT(L"0x%x", (int(Params))), L", ");
  4263. }
  4264. return ParamsStr;
  4265. }
  4266. //---------------------------------------------------------------------------
  4267. void __fastcall TTerminal::DoSynchronizeCollectDirectory(const UnicodeString LocalDirectory,
  4268. const UnicodeString RemoteDirectory, TSynchronizeMode Mode,
  4269. const TCopyParamType * CopyParam, int Params,
  4270. TSynchronizeDirectory OnSynchronizeDirectory, TSynchronizeOptions * Options,
  4271. int Flags, TSynchronizeChecklist * Checklist)
  4272. {
  4273. TSynchronizeData Data;
  4274. Data.LocalDirectory = IncludeTrailingBackslash(LocalDirectory);
  4275. Data.RemoteDirectory = UnixIncludeTrailingBackslash(RemoteDirectory);
  4276. Data.Mode = Mode;
  4277. Data.Params = Params;
  4278. Data.OnSynchronizeDirectory = OnSynchronizeDirectory;
  4279. Data.LocalFileList = NULL;
  4280. Data.CopyParam = CopyParam;
  4281. Data.Options = Options;
  4282. Data.Flags = Flags;
  4283. Data.Checklist = Checklist;
  4284. LogEvent(FORMAT(L"Collecting synchronization list for local directory '%s' and remote directory '%s', "
  4285. "mode = %s, params = 0x%x (%s)", (LocalDirectory, RemoteDirectory,
  4286. SynchronizeModeStr(Mode), int(Params), SynchronizeParamsStr(Params))));
  4287. if (FLAGCLEAR(Params, spDelayProgress))
  4288. {
  4289. DoSynchronizeProgress(Data, true);
  4290. }
  4291. try
  4292. {
  4293. bool Found;
  4294. TSearchRecChecked SearchRec;
  4295. Data.LocalFileList = CreateSortedStringList();
  4296. FILE_OPERATION_LOOP_BEGIN
  4297. {
  4298. int FindAttrs = faReadOnly | faHidden | faSysFile | faDirectory | faArchive;
  4299. Found = (FindFirstChecked(Data.LocalDirectory + L"*.*", FindAttrs, SearchRec) == 0);
  4300. }
  4301. FILE_OPERATION_LOOP_END(FMTLOAD(LIST_DIR_ERROR, (LocalDirectory)));
  4302. if (Found)
  4303. {
  4304. try
  4305. {
  4306. UnicodeString FileName;
  4307. while (Found)
  4308. {
  4309. FileName = SearchRec.Name;
  4310. // add dirs for recursive mode or when we are interested in newly
  4311. // added subdirs
  4312. // SearchRec.Size in C++B2010 is __int64,
  4313. // so we should be able to use it instead of FindData.nFileSize*
  4314. __int64 Size =
  4315. (static_cast<__int64>(SearchRec.FindData.nFileSizeHigh) << 32) +
  4316. SearchRec.FindData.nFileSizeLow;
  4317. TDateTime Modification = FileTimeToDateTime(SearchRec.FindData.ftLastWriteTime);
  4318. TFileMasks::TParams MaskParams;
  4319. MaskParams.Size = Size;
  4320. MaskParams.Modification = Modification;
  4321. UnicodeString RemoteFileName =
  4322. CopyParam->ChangeFileName(FileName, osLocal, false);
  4323. UnicodeString FullLocalFileName = Data.LocalDirectory + FileName;
  4324. if ((FileName != L".") && (FileName != L"..") &&
  4325. CopyParam->AllowTransfer(FullLocalFileName, osLocal,
  4326. FLAGSET(SearchRec.Attr, faDirectory), MaskParams) &&
  4327. !FFileSystem->TemporaryTransferFile(FileName) &&
  4328. (FLAGCLEAR(Flags, sfFirstLevel) ||
  4329. (Options == NULL) ||
  4330. Options->MatchesFilter(FileName) ||
  4331. Options->MatchesFilter(RemoteFileName)))
  4332. {
  4333. TSynchronizeFileData * FileData = new TSynchronizeFileData;
  4334. FileData->IsDirectory = FLAGSET(SearchRec.Attr, faDirectory);
  4335. FileData->Info.FileName = FileName;
  4336. FileData->Info.Directory = Data.LocalDirectory;
  4337. FileData->Info.Modification = Modification;
  4338. FileData->Info.ModificationFmt = mfFull;
  4339. FileData->Info.Size = Size;
  4340. FileData->LocalLastWriteTime = SearchRec.FindData.ftLastWriteTime;
  4341. FileData->New = true;
  4342. FileData->Modified = false;
  4343. Data.LocalFileList->AddObject(FileName,
  4344. reinterpret_cast<TObject*>(FileData));
  4345. LogEvent(FORMAT(L"Local file %s included to synchronization",
  4346. (FormatFileDetailsForLog(FullLocalFileName, Modification, Size))));
  4347. }
  4348. else
  4349. {
  4350. LogEvent(FORMAT(L"Local file %s excluded from synchronization",
  4351. (FormatFileDetailsForLog(FullLocalFileName, Modification, Size))));
  4352. }
  4353. FILE_OPERATION_LOOP_BEGIN
  4354. {
  4355. Found = (FindNextChecked(SearchRec) == 0);
  4356. }
  4357. FILE_OPERATION_LOOP_END(FMTLOAD(LIST_DIR_ERROR, (LocalDirectory)));
  4358. }
  4359. }
  4360. __finally
  4361. {
  4362. FindClose(SearchRec);
  4363. }
  4364. // can we expect that ProcessDirectory would take so little time
  4365. // that we can postpone showing progress window until anything actually happens?
  4366. bool Cached = FLAGSET(Params, spUseCache) && SessionData->CacheDirectories &&
  4367. FDirectoryCache->HasFileList(RemoteDirectory);
  4368. if (!Cached && FLAGSET(Params, spDelayProgress))
  4369. {
  4370. DoSynchronizeProgress(Data, true);
  4371. }
  4372. ProcessDirectory(RemoteDirectory, SynchronizeCollectFile, &Data,
  4373. FLAGSET(Params, spUseCache));
  4374. TSynchronizeFileData * FileData;
  4375. for (int Index = 0; Index < Data.LocalFileList->Count; Index++)
  4376. {
  4377. FileData = reinterpret_cast<TSynchronizeFileData *>
  4378. (Data.LocalFileList->Objects[Index]);
  4379. // add local file either if we are going to upload it
  4380. // (i.e. if it is updated or we want to upload even new files)
  4381. // or if we are going to delete it (i.e. all "new"=obsolete files)
  4382. bool Modified = (FileData->Modified && ((Mode == smBoth) || (Mode == smRemote)));
  4383. bool New = (FileData->New &&
  4384. ((Mode == smLocal) ||
  4385. (((Mode == smBoth) || (Mode == smRemote)) && FLAGCLEAR(Params, spTimestamp))));
  4386. if (New)
  4387. {
  4388. LogEvent(FORMAT(L"Local file %s is new",
  4389. (FormatFileDetailsForLog(FileData->Info.Directory + FileData->Info.FileName,
  4390. FileData->Info.Modification, FileData->Info.Size))));
  4391. }
  4392. if (Modified || New)
  4393. {
  4394. TSynchronizeChecklist::TItem * ChecklistItem = new TSynchronizeChecklist::TItem();
  4395. try
  4396. {
  4397. ChecklistItem->IsDirectory = FileData->IsDirectory;
  4398. ChecklistItem->Local = FileData->Info;
  4399. ChecklistItem->FLocalLastWriteTime = FileData->LocalLastWriteTime;
  4400. if (Modified)
  4401. {
  4402. assert(!FileData->MatchingRemoteFile.Directory.IsEmpty());
  4403. ChecklistItem->Remote = FileData->MatchingRemoteFile;
  4404. ChecklistItem->ImageIndex = FileData->MatchingRemoteFileImageIndex;
  4405. ChecklistItem->RemoteFile = FileData->MatchingRemoteFileFile;
  4406. }
  4407. else
  4408. {
  4409. ChecklistItem->Remote.Directory = Data.RemoteDirectory;
  4410. }
  4411. if ((Mode == smBoth) || (Mode == smRemote))
  4412. {
  4413. ChecklistItem->Action =
  4414. (Modified ? TSynchronizeChecklist::saUploadUpdate : TSynchronizeChecklist::saUploadNew);
  4415. ChecklistItem->Checked =
  4416. (Modified || FLAGCLEAR(Params, spExistingOnly)) &&
  4417. (!ChecklistItem->IsDirectory || FLAGCLEAR(Params, spNoRecurse) ||
  4418. FLAGSET(Params, spSubDirs));
  4419. }
  4420. else if ((Mode == smLocal) && FLAGCLEAR(Params, spTimestamp))
  4421. {
  4422. ChecklistItem->Action = TSynchronizeChecklist::saDeleteLocal;
  4423. ChecklistItem->Checked =
  4424. FLAGSET(Params, spDelete) &&
  4425. (!ChecklistItem->IsDirectory || FLAGCLEAR(Params, spNoRecurse) ||
  4426. FLAGSET(Params, spSubDirs));
  4427. }
  4428. if (ChecklistItem->Action != TSynchronizeChecklist::saNone)
  4429. {
  4430. Data.Checklist->Add(ChecklistItem);
  4431. ChecklistItem = NULL;
  4432. }
  4433. }
  4434. __finally
  4435. {
  4436. delete ChecklistItem;
  4437. }
  4438. }
  4439. else
  4440. {
  4441. if (FileData->Modified)
  4442. {
  4443. delete FileData->MatchingRemoteFileFile;
  4444. }
  4445. }
  4446. }
  4447. }
  4448. }
  4449. __finally
  4450. {
  4451. if (Data.LocalFileList != NULL)
  4452. {
  4453. for (int Index = 0; Index < Data.LocalFileList->Count; Index++)
  4454. {
  4455. TSynchronizeFileData * FileData = reinterpret_cast<TSynchronizeFileData*>
  4456. (Data.LocalFileList->Objects[Index]);
  4457. delete FileData;
  4458. }
  4459. delete Data.LocalFileList;
  4460. }
  4461. }
  4462. }
  4463. //---------------------------------------------------------------------------
  4464. void __fastcall TTerminal::SynchronizeCollectFile(const UnicodeString FileName,
  4465. const TRemoteFile * File, /*TSynchronizeData*/ void * Param)
  4466. {
  4467. try
  4468. {
  4469. DoSynchronizeCollectFile(FileName, File, Param);
  4470. }
  4471. catch(EScpSkipFile & E)
  4472. {
  4473. TSuspendFileOperationProgress Suspend(OperationProgress);
  4474. if (!HandleException(&E))
  4475. {
  4476. throw;
  4477. }
  4478. }
  4479. }
  4480. //---------------------------------------------------------------------------
  4481. void __fastcall TTerminal::DoSynchronizeCollectFile(const UnicodeString FileName,
  4482. const TRemoteFile * File, /*TSynchronizeData*/ void * Param)
  4483. {
  4484. TSynchronizeData * Data = static_cast<TSynchronizeData *>(Param);
  4485. TFileMasks::TParams MaskParams;
  4486. MaskParams.Size = File->Size;
  4487. MaskParams.Modification = File->Modification;
  4488. UnicodeString LocalFileName =
  4489. Data->CopyParam->ChangeFileName(File->FileName, osRemote, false);
  4490. UnicodeString FullRemoteFileName =
  4491. UnixExcludeTrailingBackslash(File->FullFileName);
  4492. if (Data->CopyParam->AllowTransfer(
  4493. FullRemoteFileName, osRemote,
  4494. File->IsDirectory, MaskParams) &&
  4495. !FFileSystem->TemporaryTransferFile(File->FileName) &&
  4496. (FLAGCLEAR(Data->Flags, sfFirstLevel) ||
  4497. (Data->Options == NULL) ||
  4498. Data->Options->MatchesFilter(File->FileName) ||
  4499. Data->Options->MatchesFilter(LocalFileName)))
  4500. {
  4501. TSynchronizeChecklist::TItem * ChecklistItem = new TSynchronizeChecklist::TItem();
  4502. try
  4503. {
  4504. ChecklistItem->IsDirectory = File->IsDirectory;
  4505. ChecklistItem->ImageIndex = File->IconIndex;
  4506. ChecklistItem->Remote.FileName = File->FileName;
  4507. ChecklistItem->Remote.Directory = Data->RemoteDirectory;
  4508. ChecklistItem->Remote.Modification = File->Modification;
  4509. ChecklistItem->Remote.ModificationFmt = File->ModificationFmt;
  4510. ChecklistItem->Remote.Size = File->Size;
  4511. bool Modified = false;
  4512. int LocalIndex = Data->LocalFileList->IndexOf(LocalFileName);
  4513. bool New = (LocalIndex < 0);
  4514. if (!New)
  4515. {
  4516. TSynchronizeFileData * LocalData =
  4517. reinterpret_cast<TSynchronizeFileData *>(Data->LocalFileList->Objects[LocalIndex]);
  4518. LocalData->New = false;
  4519. if (File->IsDirectory != LocalData->IsDirectory)
  4520. {
  4521. LogEvent(FORMAT(L"%s is directory on one side, but file on the another",
  4522. (File->FileName)));
  4523. }
  4524. else if (!File->IsDirectory)
  4525. {
  4526. ChecklistItem->Local = LocalData->Info;
  4527. ChecklistItem->Local.Modification =
  4528. ReduceDateTimePrecision(ChecklistItem->Local.Modification, File->ModificationFmt);
  4529. bool LocalModified = false;
  4530. // for spTimestamp+spBySize require that the file sizes are the same
  4531. // before comparing file time
  4532. int TimeCompare;
  4533. if (FLAGCLEAR(Data->Params, spNotByTime) &&
  4534. (FLAGCLEAR(Data->Params, spTimestamp) ||
  4535. FLAGCLEAR(Data->Params, spBySize) ||
  4536. (ChecklistItem->Local.Size == ChecklistItem->Remote.Size)))
  4537. {
  4538. TimeCompare = CompareFileTime(ChecklistItem->Local.Modification,
  4539. ChecklistItem->Remote.Modification);
  4540. }
  4541. else
  4542. {
  4543. TimeCompare = 0;
  4544. }
  4545. if (TimeCompare < 0)
  4546. {
  4547. if ((FLAGCLEAR(Data->Params, spTimestamp) && FLAGCLEAR(Data->Params, spMirror)) ||
  4548. (Data->Mode == smBoth) || (Data->Mode == smLocal))
  4549. {
  4550. Modified = true;
  4551. }
  4552. else
  4553. {
  4554. LocalModified = true;
  4555. }
  4556. }
  4557. else if (TimeCompare > 0)
  4558. {
  4559. if ((FLAGCLEAR(Data->Params, spTimestamp) && FLAGCLEAR(Data->Params, spMirror)) ||
  4560. (Data->Mode == smBoth) || (Data->Mode == smRemote))
  4561. {
  4562. LocalModified = true;
  4563. }
  4564. else
  4565. {
  4566. Modified = true;
  4567. }
  4568. }
  4569. else if (FLAGSET(Data->Params, spBySize) &&
  4570. (ChecklistItem->Local.Size != ChecklistItem->Remote.Size) &&
  4571. FLAGCLEAR(Data->Params, spTimestamp))
  4572. {
  4573. Modified = true;
  4574. LocalModified = true;
  4575. }
  4576. if (LocalModified)
  4577. {
  4578. LocalData->Modified = true;
  4579. LocalData->MatchingRemoteFile = ChecklistItem->Remote;
  4580. LocalData->MatchingRemoteFileImageIndex = ChecklistItem->ImageIndex;
  4581. // we need this for custom commands over checklist only,
  4582. // not for sync itself
  4583. LocalData->MatchingRemoteFileFile = File->Duplicate();
  4584. LogEvent(FORMAT(L"Local file %s is modified comparing to remote file %s",
  4585. (FormatFileDetailsForLog(LocalData->Info.Directory + LocalData->Info.FileName,
  4586. LocalData->Info.Modification, LocalData->Info.Size),
  4587. FormatFileDetailsForLog(FullRemoteFileName,
  4588. File->Modification, File->Size))));
  4589. }
  4590. if (Modified)
  4591. {
  4592. LogEvent(FORMAT(L"Remote file %s is modified comparing to local file %s",
  4593. (FormatFileDetailsForLog(FullRemoteFileName, File->Modification, File->Size),
  4594. FormatFileDetailsForLog(LocalData->Info.Directory + LocalData->Info.FileName,
  4595. LocalData->Info.Modification, LocalData->Info.Size))));
  4596. }
  4597. }
  4598. else if (FLAGCLEAR(Data->Params, spNoRecurse))
  4599. {
  4600. DoSynchronizeCollectDirectory(
  4601. Data->LocalDirectory + LocalData->Info.FileName,
  4602. Data->RemoteDirectory + File->FileName,
  4603. Data->Mode, Data->CopyParam, Data->Params, Data->OnSynchronizeDirectory,
  4604. Data->Options, (Data->Flags & ~sfFirstLevel),
  4605. Data->Checklist);
  4606. }
  4607. }
  4608. else
  4609. {
  4610. ChecklistItem->Local.Directory = Data->LocalDirectory;
  4611. LogEvent(FORMAT(L"Remote file %s is new",
  4612. (FormatFileDetailsForLog(FullRemoteFileName, File->Modification, File->Size))));
  4613. }
  4614. if (New || Modified)
  4615. {
  4616. assert(!New || !Modified);
  4617. // download the file if it changed or is new and we want to have it locally
  4618. if ((Data->Mode == smBoth) || (Data->Mode == smLocal))
  4619. {
  4620. if (FLAGCLEAR(Data->Params, spTimestamp) || Modified)
  4621. {
  4622. ChecklistItem->Action =
  4623. (Modified ? TSynchronizeChecklist::saDownloadUpdate : TSynchronizeChecklist::saDownloadNew);
  4624. ChecklistItem->Checked =
  4625. (Modified || FLAGCLEAR(Data->Params, spExistingOnly)) &&
  4626. (!ChecklistItem->IsDirectory || FLAGCLEAR(Data->Params, spNoRecurse) ||
  4627. FLAGSET(Data->Params, spSubDirs));
  4628. }
  4629. }
  4630. else if ((Data->Mode == smRemote) && New)
  4631. {
  4632. if (FLAGCLEAR(Data->Params, spTimestamp))
  4633. {
  4634. ChecklistItem->Action = TSynchronizeChecklist::saDeleteRemote;
  4635. ChecklistItem->Checked =
  4636. FLAGSET(Data->Params, spDelete) &&
  4637. (!ChecklistItem->IsDirectory || FLAGCLEAR(Data->Params, spNoRecurse) ||
  4638. FLAGSET(Data->Params, spSubDirs));
  4639. }
  4640. }
  4641. if (ChecklistItem->Action != TSynchronizeChecklist::saNone)
  4642. {
  4643. ChecklistItem->RemoteFile = File->Duplicate();
  4644. Data->Checklist->Add(ChecklistItem);
  4645. ChecklistItem = NULL;
  4646. }
  4647. }
  4648. }
  4649. __finally
  4650. {
  4651. delete ChecklistItem;
  4652. }
  4653. }
  4654. else
  4655. {
  4656. LogEvent(FORMAT(L"Remote file %s excluded from synchronization",
  4657. (FormatFileDetailsForLog(FullRemoteFileName, File->Modification, File->Size))));
  4658. }
  4659. }
  4660. //---------------------------------------------------------------------------
  4661. void __fastcall TTerminal::SynchronizeApply(TSynchronizeChecklist * Checklist,
  4662. const UnicodeString LocalDirectory, const UnicodeString RemoteDirectory,
  4663. const TCopyParamType * CopyParam, int Params,
  4664. TSynchronizeDirectory OnSynchronizeDirectory)
  4665. {
  4666. TSynchronizeData Data;
  4667. Data.OnSynchronizeDirectory = OnSynchronizeDirectory;
  4668. int CopyParams =
  4669. FLAGMASK(FLAGSET(Params, spNoConfirmation), cpNoConfirmation);
  4670. TCopyParamType SyncCopyParam = *CopyParam;
  4671. // when synchronizing by time, we force preserving time,
  4672. // otherwise it does not make any sense
  4673. if (FLAGCLEAR(Params, spNotByTime))
  4674. {
  4675. SyncCopyParam.PreserveTime = true;
  4676. }
  4677. TStringList * DownloadList = new TStringList();
  4678. TStringList * DeleteRemoteList = new TStringList();
  4679. TStringList * UploadList = new TStringList();
  4680. TStringList * DeleteLocalList = new TStringList();
  4681. BeginTransaction();
  4682. try
  4683. {
  4684. int IIndex = 0;
  4685. while (IIndex < Checklist->Count)
  4686. {
  4687. const TSynchronizeChecklist::TItem * ChecklistItem;
  4688. DownloadList->Clear();
  4689. DeleteRemoteList->Clear();
  4690. UploadList->Clear();
  4691. DeleteLocalList->Clear();
  4692. ChecklistItem = Checklist->Item[IIndex];
  4693. UnicodeString CurrentLocalDirectory = ChecklistItem->Local.Directory;
  4694. UnicodeString CurrentRemoteDirectory = ChecklistItem->Remote.Directory;
  4695. LogEvent(FORMAT(L"Synchronizing local directory '%s' with remote directory '%s', "
  4696. "params = 0x%x (%s)", (CurrentLocalDirectory, CurrentRemoteDirectory,
  4697. int(Params), SynchronizeParamsStr(Params))));
  4698. int Count = 0;
  4699. while ((IIndex < Checklist->Count) &&
  4700. (Checklist->Item[IIndex]->Local.Directory == CurrentLocalDirectory) &&
  4701. (Checklist->Item[IIndex]->Remote.Directory == CurrentRemoteDirectory))
  4702. {
  4703. ChecklistItem = Checklist->Item[IIndex];
  4704. if (ChecklistItem->Checked)
  4705. {
  4706. Count++;
  4707. if (FLAGSET(Params, spTimestamp))
  4708. {
  4709. switch (ChecklistItem->Action)
  4710. {
  4711. case TSynchronizeChecklist::saDownloadUpdate:
  4712. DownloadList->AddObject(
  4713. UnixIncludeTrailingBackslash(ChecklistItem->Remote.Directory) +
  4714. ChecklistItem->Remote.FileName,
  4715. (TObject *)(ChecklistItem));
  4716. break;
  4717. case TSynchronizeChecklist::saUploadUpdate:
  4718. UploadList->AddObject(
  4719. IncludeTrailingBackslash(ChecklistItem->Local.Directory) +
  4720. ChecklistItem->Local.FileName,
  4721. (TObject *)(ChecklistItem));
  4722. break;
  4723. default:
  4724. FAIL;
  4725. break;
  4726. }
  4727. }
  4728. else
  4729. {
  4730. switch (ChecklistItem->Action)
  4731. {
  4732. case TSynchronizeChecklist::saDownloadNew:
  4733. case TSynchronizeChecklist::saDownloadUpdate:
  4734. DownloadList->AddObject(
  4735. UnixIncludeTrailingBackslash(ChecklistItem->Remote.Directory) +
  4736. ChecklistItem->Remote.FileName,
  4737. ChecklistItem->RemoteFile);
  4738. break;
  4739. case TSynchronizeChecklist::saDeleteRemote:
  4740. DeleteRemoteList->AddObject(
  4741. UnixIncludeTrailingBackslash(ChecklistItem->Remote.Directory) +
  4742. ChecklistItem->Remote.FileName,
  4743. ChecklistItem->RemoteFile);
  4744. break;
  4745. case TSynchronizeChecklist::saUploadNew:
  4746. case TSynchronizeChecklist::saUploadUpdate:
  4747. UploadList->Add(
  4748. IncludeTrailingBackslash(ChecklistItem->Local.Directory) +
  4749. ChecklistItem->Local.FileName);
  4750. break;
  4751. case TSynchronizeChecklist::saDeleteLocal:
  4752. DeleteLocalList->Add(
  4753. IncludeTrailingBackslash(ChecklistItem->Local.Directory) +
  4754. ChecklistItem->Local.FileName);
  4755. break;
  4756. default:
  4757. FAIL;
  4758. break;
  4759. }
  4760. }
  4761. }
  4762. IIndex++;
  4763. }
  4764. // prevent showing/updating of progress dialog if there's nothing to do
  4765. if (Count > 0)
  4766. {
  4767. Data.LocalDirectory = IncludeTrailingBackslash(CurrentLocalDirectory);
  4768. Data.RemoteDirectory = UnixIncludeTrailingBackslash(CurrentRemoteDirectory);
  4769. DoSynchronizeProgress(Data, false);
  4770. if (FLAGSET(Params, spTimestamp))
  4771. {
  4772. if (DownloadList->Count > 0)
  4773. {
  4774. ProcessFiles(DownloadList, foSetProperties,
  4775. SynchronizeLocalTimestamp, NULL, osLocal);
  4776. }
  4777. if (UploadList->Count > 0)
  4778. {
  4779. ProcessFiles(UploadList, foSetProperties,
  4780. SynchronizeRemoteTimestamp);
  4781. }
  4782. }
  4783. else
  4784. {
  4785. if ((DownloadList->Count > 0) &&
  4786. !CopyToLocal(DownloadList, Data.LocalDirectory, &SyncCopyParam, CopyParams))
  4787. {
  4788. Abort();
  4789. }
  4790. if ((DeleteRemoteList->Count > 0) &&
  4791. !DeleteFiles(DeleteRemoteList))
  4792. {
  4793. Abort();
  4794. }
  4795. if ((UploadList->Count > 0) &&
  4796. !CopyToRemote(UploadList, Data.RemoteDirectory, &SyncCopyParam, CopyParams))
  4797. {
  4798. Abort();
  4799. }
  4800. if ((DeleteLocalList->Count > 0) &&
  4801. !DeleteLocalFiles(DeleteLocalList))
  4802. {
  4803. Abort();
  4804. }
  4805. }
  4806. }
  4807. }
  4808. }
  4809. __finally
  4810. {
  4811. delete DownloadList;
  4812. delete DeleteRemoteList;
  4813. delete UploadList;
  4814. delete DeleteLocalList;
  4815. EndTransaction();
  4816. }
  4817. }
  4818. //---------------------------------------------------------------------------
  4819. void __fastcall TTerminal::DoSynchronizeProgress(const TSynchronizeData & Data,
  4820. bool Collect)
  4821. {
  4822. if (Data.OnSynchronizeDirectory != NULL)
  4823. {
  4824. bool Continue = true;
  4825. Data.OnSynchronizeDirectory(Data.LocalDirectory, Data.RemoteDirectory,
  4826. Continue, Collect);
  4827. if (!Continue)
  4828. {
  4829. Abort();
  4830. }
  4831. }
  4832. }
  4833. //---------------------------------------------------------------------------
  4834. void __fastcall TTerminal::SynchronizeLocalTimestamp(const UnicodeString /*FileName*/,
  4835. const TRemoteFile * File, void * /*Param*/)
  4836. {
  4837. const TSynchronizeChecklist::TItem * ChecklistItem =
  4838. reinterpret_cast<const TSynchronizeChecklist::TItem *>(File);
  4839. UnicodeString LocalFile =
  4840. IncludeTrailingBackslash(ChecklistItem->Local.Directory) +
  4841. ChecklistItem->Local.FileName;
  4842. FILE_OPERATION_LOOP_BEGIN
  4843. {
  4844. HANDLE Handle;
  4845. OpenLocalFile(LocalFile, GENERIC_WRITE, NULL, &Handle,
  4846. NULL, NULL, NULL, NULL);
  4847. FILETIME WrTime = DateTimeToFileTime(ChecklistItem->Remote.Modification,
  4848. SessionData->DSTMode);
  4849. bool Result = SetFileTime(Handle, NULL, NULL, &WrTime);
  4850. int Error = GetLastError();
  4851. CloseHandle(Handle);
  4852. if (!Result)
  4853. {
  4854. RaiseLastOSError(Error);
  4855. }
  4856. }
  4857. FILE_OPERATION_LOOP_END(FMTLOAD(CANT_SET_ATTRS, (LocalFile)));
  4858. }
  4859. //---------------------------------------------------------------------------
  4860. void __fastcall TTerminal::SynchronizeRemoteTimestamp(const UnicodeString /*FileName*/,
  4861. const TRemoteFile * File, void * /*Param*/)
  4862. {
  4863. const TSynchronizeChecklist::TItem * ChecklistItem =
  4864. reinterpret_cast<const TSynchronizeChecklist::TItem *>(File);
  4865. TRemoteProperties Properties;
  4866. Properties.Valid << vpModification;
  4867. Properties.Modification = ConvertTimestampToUnix(ChecklistItem->FLocalLastWriteTime,
  4868. SessionData->DSTMode);
  4869. ChangeFileProperties(
  4870. UnixIncludeTrailingBackslash(ChecklistItem->Remote.Directory) + ChecklistItem->Remote.FileName,
  4871. NULL, &Properties);
  4872. }
  4873. //---------------------------------------------------------------------------
  4874. void __fastcall TTerminal::FileFind(UnicodeString FileName,
  4875. const TRemoteFile * File, /*TFilesFindParams*/ void * Param)
  4876. {
  4877. // see DoFilesFind
  4878. FOnFindingFile = NULL;
  4879. assert(Param);
  4880. assert(File);
  4881. TFilesFindParams * AParams = static_cast<TFilesFindParams*>(Param);
  4882. if (!AParams->Cancel)
  4883. {
  4884. if (FileName.IsEmpty())
  4885. {
  4886. FileName = File->FileName;
  4887. }
  4888. TFileMasks::TParams MaskParams;
  4889. MaskParams.Size = File->Size;
  4890. MaskParams.Modification = File->Modification;
  4891. UnicodeString FullFileName = UnixExcludeTrailingBackslash(File->FullFileName);
  4892. bool ImplicitMatch;
  4893. if (AParams->FileMask.Matches(FullFileName, false,
  4894. File->IsDirectory, &MaskParams, ImplicitMatch))
  4895. {
  4896. if (!ImplicitMatch)
  4897. {
  4898. AParams->OnFileFound(this, FileName, File, AParams->Cancel);
  4899. }
  4900. if (File->IsDirectory)
  4901. {
  4902. if (!AParams->LoopDetector.IsUnvisitedDirectory(File))
  4903. {
  4904. LogEvent(FORMAT(L"Already searched \"%s\" directory, link loop detected", (FullFileName)));
  4905. }
  4906. else
  4907. {
  4908. DoFilesFind(FullFileName, *AParams);
  4909. }
  4910. }
  4911. }
  4912. }
  4913. }
  4914. //---------------------------------------------------------------------------
  4915. void __fastcall TTerminal::DoFilesFind(UnicodeString Directory, TFilesFindParams & Params)
  4916. {
  4917. Params.OnFindingFile(this, Directory, Params.Cancel);
  4918. if (!Params.Cancel)
  4919. {
  4920. assert(FOnFindingFile == NULL);
  4921. // ideally we should set the handler only around actually reading
  4922. // of the directory listing, so we at least reset the handler in
  4923. // FileFind
  4924. FOnFindingFile = Params.OnFindingFile;
  4925. try
  4926. {
  4927. ProcessDirectory(Directory, FileFind, &Params, false, true);
  4928. }
  4929. __finally
  4930. {
  4931. FOnFindingFile = NULL;
  4932. }
  4933. }
  4934. }
  4935. //---------------------------------------------------------------------------
  4936. void __fastcall TTerminal::FilesFind(UnicodeString Directory, const TFileMasks & FileMask,
  4937. TFileFoundEvent OnFileFound, TFindingFileEvent OnFindingFile)
  4938. {
  4939. TFilesFindParams Params;
  4940. Params.FileMask = FileMask;
  4941. Params.OnFileFound = OnFileFound;
  4942. Params.OnFindingFile = OnFindingFile;
  4943. Params.Cancel = false;
  4944. Params.LoopDetector.RecordVisitedDirectory(Directory);
  4945. DoFilesFind(Directory, Params);
  4946. }
  4947. //---------------------------------------------------------------------------
  4948. void __fastcall TTerminal::SpaceAvailable(const UnicodeString Path,
  4949. TSpaceAvailable & ASpaceAvailable)
  4950. {
  4951. assert(IsCapable[fcCheckingSpaceAvailable]);
  4952. try
  4953. {
  4954. FFileSystem->SpaceAvailable(Path, ASpaceAvailable);
  4955. }
  4956. catch (Exception &E)
  4957. {
  4958. CommandError(&E, FMTLOAD(SPACE_AVAILABLE_ERROR, (Path)));
  4959. }
  4960. }
  4961. //---------------------------------------------------------------------------
  4962. const TSessionInfo & __fastcall TTerminal::GetSessionInfo()
  4963. {
  4964. return FFileSystem->GetSessionInfo();
  4965. }
  4966. //---------------------------------------------------------------------------
  4967. const TFileSystemInfo & __fastcall TTerminal::GetFileSystemInfo(bool Retrieve)
  4968. {
  4969. return FFileSystem->GetFileSystemInfo(Retrieve);
  4970. }
  4971. //---------------------------------------------------------------------
  4972. void __fastcall TTerminal::GetSupportedChecksumAlgs(TStrings * Algs)
  4973. {
  4974. FFileSystem->GetSupportedChecksumAlgs(Algs);
  4975. }
  4976. //---------------------------------------------------------------------
  4977. UnicodeString __fastcall TTerminal::GetPassword()
  4978. {
  4979. UnicodeString Result;
  4980. // FRememberedPassword is empty also when stored password was used
  4981. if (FRememberedPassword.IsEmpty())
  4982. {
  4983. Result = SessionData->Password;
  4984. }
  4985. else
  4986. {
  4987. Result = RememberedPassword;
  4988. }
  4989. return Result;
  4990. }
  4991. //---------------------------------------------------------------------
  4992. UnicodeString __fastcall TTerminal::GetRememberedPassword()
  4993. {
  4994. return DecryptPassword(FRememberedPassword);
  4995. }
  4996. //---------------------------------------------------------------------
  4997. UnicodeString __fastcall TTerminal::GetRememberedTunnelPassword()
  4998. {
  4999. return DecryptPassword(FRememberedTunnelPassword);
  5000. }
  5001. //---------------------------------------------------------------------
  5002. bool __fastcall TTerminal::GetStoredCredentialsTried()
  5003. {
  5004. bool Result;
  5005. if (FFileSystem != NULL)
  5006. {
  5007. Result = FFileSystem->GetStoredCredentialsTried();
  5008. }
  5009. else if (FSecureShell != NULL)
  5010. {
  5011. Result = FSecureShell->GetStoredCredentialsTried();
  5012. }
  5013. else
  5014. {
  5015. assert(FTunnelOpening);
  5016. Result = false;
  5017. }
  5018. return Result;
  5019. }
  5020. //---------------------------------------------------------------------------
  5021. bool __fastcall TTerminal::CopyToRemote(TStrings * FilesToCopy,
  5022. const UnicodeString TargetDir, const TCopyParamType * CopyParam, int Params)
  5023. {
  5024. assert(FFileSystem);
  5025. assert(FilesToCopy);
  5026. bool Result = false;
  5027. TOnceDoneOperation OnceDoneOperation = odoIdle;
  5028. try
  5029. {
  5030. __int64 Size;
  5031. // dirty trick: when moving, do not pass copy param to avoid exclude mask
  5032. bool CalculatedSize =
  5033. CalculateLocalFilesSize(
  5034. FilesToCopy, Size,
  5035. (FLAGCLEAR(Params, cpDelete) ? CopyParam : NULL),
  5036. CopyParam->CalculateSize);
  5037. TFileOperationProgressType OperationProgress(&DoProgress, &DoFinished);
  5038. OperationProgress.Start((Params & cpDelete ? foMove : foCopy), osLocal,
  5039. FilesToCopy->Count, Params & cpTemporary, TargetDir, CopyParam->CPSLimit);
  5040. FOperationProgress = &OperationProgress;
  5041. bool CollectingUsage = false;
  5042. try
  5043. {
  5044. if (CalculatedSize)
  5045. {
  5046. if (Configuration->Usage->Collect)
  5047. {
  5048. int CounterSize = TUsage::CalculateCounterSize(Size);
  5049. Configuration->Usage->Inc(L"Uploads");
  5050. Configuration->Usage->Inc(L"UploadedBytes", CounterSize);
  5051. Configuration->Usage->SetMax(L"MaxUploadSize", CounterSize);
  5052. CollectingUsage = true;
  5053. }
  5054. OperationProgress.SetTotalSize(Size);
  5055. }
  5056. UnicodeString UnlockedTargetDir = TranslateLockedPath(TargetDir, false);
  5057. BeginTransaction();
  5058. try
  5059. {
  5060. if (Log->Logging)
  5061. {
  5062. LogEvent(FORMAT(L"Copying %d files/directories to remote directory "
  5063. "\"%s\"", (FilesToCopy->Count, TargetDir)));
  5064. LogEvent(CopyParam->LogStr);
  5065. }
  5066. FFileSystem->CopyToRemote(FilesToCopy, UnlockedTargetDir,
  5067. CopyParam, Params, &OperationProgress, OnceDoneOperation);
  5068. }
  5069. __finally
  5070. {
  5071. if (Active)
  5072. {
  5073. ReactOnCommand(fsCopyToRemote);
  5074. }
  5075. EndTransaction();
  5076. }
  5077. if (OperationProgress.Cancel == csContinue)
  5078. {
  5079. Result = true;
  5080. }
  5081. }
  5082. __finally
  5083. {
  5084. if (CollectingUsage)
  5085. {
  5086. int CounterTime = TimeToSeconds(OperationProgress.TimeElapsed());
  5087. Configuration->Usage->Inc(L"UploadTime", CounterTime);
  5088. Configuration->Usage->SetMax(L"MaxUploadTime", CounterTime);
  5089. }
  5090. OperationProgress.Stop();
  5091. FOperationProgress = NULL;
  5092. }
  5093. }
  5094. catch (Exception &E)
  5095. {
  5096. CommandError(&E, MainInstructions(LoadStr(TOREMOTE_COPY_ERROR)));
  5097. OnceDoneOperation = odoIdle;
  5098. }
  5099. if (OnceDoneOperation != odoIdle)
  5100. {
  5101. CloseOnCompletion(OnceDoneOperation);
  5102. }
  5103. return Result;
  5104. }
  5105. //---------------------------------------------------------------------------
  5106. bool __fastcall TTerminal::CopyToLocal(TStrings * FilesToCopy,
  5107. const UnicodeString TargetDir, const TCopyParamType * CopyParam, int Params)
  5108. {
  5109. assert(FFileSystem);
  5110. // see scp.c: sink(), tolocal()
  5111. bool Result = false;
  5112. bool OwnsFileList = (FilesToCopy == NULL);
  5113. TOnceDoneOperation OnceDoneOperation = odoIdle;
  5114. try
  5115. {
  5116. if (OwnsFileList)
  5117. {
  5118. FilesToCopy = new TStringList();
  5119. FilesToCopy->Assign(Files->SelectedFiles);
  5120. }
  5121. BeginTransaction();
  5122. try
  5123. {
  5124. __int64 TotalSize;
  5125. bool TotalSizeKnown = false;
  5126. TFileOperationProgressType OperationProgress(&DoProgress, &DoFinished);
  5127. ExceptionOnFail = true;
  5128. try
  5129. {
  5130. // dirty trick: when moving, do not pass copy param to avoid exclude mask
  5131. if (CalculateFilesSize(
  5132. FilesToCopy, TotalSize, csIgnoreErrors,
  5133. (FLAGCLEAR(Params, cpDelete) ? CopyParam : NULL),
  5134. CopyParam->CalculateSize, NULL))
  5135. {
  5136. TotalSizeKnown = true;
  5137. }
  5138. }
  5139. __finally
  5140. {
  5141. ExceptionOnFail = false;
  5142. }
  5143. OperationProgress.Start((Params & cpDelete ? foMove : foCopy), osRemote,
  5144. FilesToCopy->Count, Params & cpTemporary, TargetDir, CopyParam->CPSLimit);
  5145. FOperationProgress = &OperationProgress;
  5146. bool CollectingUsage = false;
  5147. try
  5148. {
  5149. if (TotalSizeKnown)
  5150. {
  5151. if (Configuration->Usage->Collect)
  5152. {
  5153. int CounterTotalSize = TUsage::CalculateCounterSize(TotalSize);
  5154. Configuration->Usage->Inc(L"Downloads");
  5155. Configuration->Usage->Inc(L"DownloadedBytes", CounterTotalSize);
  5156. Configuration->Usage->SetMax(L"MaxDownloadSize", CounterTotalSize);
  5157. CollectingUsage = true;
  5158. }
  5159. OperationProgress.SetTotalSize(TotalSize);
  5160. }
  5161. try
  5162. {
  5163. try
  5164. {
  5165. if (Log->Logging)
  5166. {
  5167. LogEvent(FORMAT(L"Copying %d files/directories to local directory "
  5168. "\"%s\"", (FilesToCopy->Count, TargetDir)));
  5169. LogEvent(CopyParam->LogStr);
  5170. }
  5171. FFileSystem->CopyToLocal(FilesToCopy, TargetDir, CopyParam, Params,
  5172. &OperationProgress, OnceDoneOperation);
  5173. }
  5174. __finally
  5175. {
  5176. if (Active)
  5177. {
  5178. ReactOnCommand(fsCopyToLocal);
  5179. }
  5180. }
  5181. }
  5182. catch (Exception &E)
  5183. {
  5184. CommandError(&E, MainInstructions(LoadStr(TOLOCAL_COPY_ERROR)));
  5185. OnceDoneOperation = odoIdle;
  5186. }
  5187. if (OperationProgress.Cancel == csContinue)
  5188. {
  5189. Result = true;
  5190. }
  5191. }
  5192. __finally
  5193. {
  5194. if (CollectingUsage)
  5195. {
  5196. int CounterTime = TimeToSeconds(OperationProgress.TimeElapsed());
  5197. Configuration->Usage->Inc(L"DownloadTime", CounterTime);
  5198. Configuration->Usage->SetMax(L"MaxDownloadTime", CounterTime);
  5199. }
  5200. FOperationProgress = NULL;
  5201. OperationProgress.Stop();
  5202. }
  5203. }
  5204. __finally
  5205. {
  5206. // If session is still active (no fatal error) we reload directory
  5207. // by calling EndTransaction
  5208. EndTransaction();
  5209. }
  5210. }
  5211. __finally
  5212. {
  5213. if (OwnsFileList) delete FilesToCopy;
  5214. }
  5215. if (OnceDoneOperation != odoIdle)
  5216. {
  5217. CloseOnCompletion(OnceDoneOperation);
  5218. }
  5219. return Result;
  5220. }
  5221. //---------------------------------------------------------------------------
  5222. void __fastcall TTerminal::ReflectSettings()
  5223. {
  5224. assert(FLog != NULL);
  5225. FLog->ReflectSettings();
  5226. assert(FActionLog != NULL);
  5227. FActionLog->ReflectSettings();
  5228. // also FTunnelLog ?
  5229. }
  5230. //---------------------------------------------------------------------------
  5231. void __fastcall TTerminal::CollectUsage()
  5232. {
  5233. switch (SessionData->FSProtocol)
  5234. {
  5235. case fsSCPonly:
  5236. Configuration->Usage->Inc(L"OpenedSessionsSCP");
  5237. break;
  5238. case fsSFTP:
  5239. case fsSFTPonly:
  5240. Configuration->Usage->Inc(L"OpenedSessionsSFTP");
  5241. break;
  5242. case fsFTP:
  5243. if (SessionData->Ftps == ftpsNone)
  5244. {
  5245. Configuration->Usage->Inc(L"OpenedSessionsFTP");
  5246. }
  5247. else
  5248. {
  5249. Configuration->Usage->Inc(L"OpenedSessionsFTPS");
  5250. }
  5251. break;
  5252. case fsWebDAV:
  5253. if (SessionData->Ftps == ftpsNone)
  5254. {
  5255. Configuration->Usage->Inc(L"OpenedSessionsWebDAV");
  5256. }
  5257. else
  5258. {
  5259. Configuration->Usage->Inc(L"OpenedSessionsWebDAVS");
  5260. }
  5261. break;
  5262. }
  5263. if (Configuration->Logging && Configuration->LogToFile)
  5264. {
  5265. Configuration->Usage->Inc(L"OpenedSessionsLogToFile2");
  5266. }
  5267. if (Configuration->LogActions)
  5268. {
  5269. Configuration->Usage->Inc(L"OpenedSessionsXmlLog");
  5270. }
  5271. std::unique_ptr<TSessionData> FactoryDefaults(new TSessionData(L""));
  5272. if (!SessionData->IsSame(FactoryDefaults.get(), true))
  5273. {
  5274. Configuration->Usage->Inc(L"OpenedSessionsAdvanced");
  5275. }
  5276. if (SessionData->ProxyMethod != ::pmNone)
  5277. {
  5278. Configuration->Usage->Inc(L"OpenedSessionsProxy");
  5279. }
  5280. if (SessionData->FtpProxyLogonType > 0)
  5281. {
  5282. Configuration->Usage->Inc(L"OpenedSessionsFtpProxy");
  5283. }
  5284. FCollectFileSystemUsage = true;
  5285. }
  5286. //---------------------------------------------------------------------------
  5287. static UnicodeString __fastcall FormatCertificateData(const UnicodeString & Fingerprint, int Failures)
  5288. {
  5289. return FORMAT(L"%s;%2.2X", (Fingerprint, Failures));
  5290. }
  5291. //---------------------------------------------------------------------------
  5292. bool __fastcall TTerminal::VerifyCertificate(
  5293. const UnicodeString & CertificateStorageKey, const UnicodeString & Fingerprint,
  5294. const UnicodeString & CertificateSubject, int Failures)
  5295. {
  5296. bool Result = false;
  5297. UnicodeString CertificateData = FormatCertificateData(Fingerprint, Failures);
  5298. std::unique_ptr<THierarchicalStorage> Storage(Configuration->CreateConfigStorage());
  5299. Storage->AccessMode = smRead;
  5300. if (Storage->OpenSubKey(CertificateStorageKey, false))
  5301. {
  5302. if (Storage->ValueExists(SessionData->SiteKey))
  5303. {
  5304. UnicodeString CachedCertificateData = Storage->ReadString(SessionData->SiteKey, L"");
  5305. if (CertificateData == CachedCertificateData)
  5306. {
  5307. LogEvent(FORMAT(L"Certificate for \"%s\" matches cached fingerprint and failures", (CertificateSubject)));
  5308. Result = true;
  5309. }
  5310. }
  5311. else if (Storage->ValueExists(Fingerprint))
  5312. {
  5313. LogEvent(FORMAT(L"Certificate for \"%s\" matches legacy cached fingerprint", (CertificateSubject)));
  5314. Result = true;
  5315. }
  5316. }
  5317. if (!Result)
  5318. {
  5319. UnicodeString Buf = SessionData->HostKey;
  5320. while (!Result && !Buf.IsEmpty())
  5321. {
  5322. UnicodeString ExpectedKey = CutToChar(Buf, L';', false);
  5323. if (ExpectedKey == L"*")
  5324. {
  5325. UnicodeString Message = LoadStr(ANY_CERTIFICATE);
  5326. Information(Message, true);
  5327. Log->Add(llException, Message);
  5328. Result = true;
  5329. }
  5330. else if (ExpectedKey == Fingerprint)
  5331. {
  5332. LogEvent(FORMAT(L"Certificate for \"%s\" matches configured fingerprint", (CertificateSubject)));
  5333. Result = true;
  5334. }
  5335. }
  5336. }
  5337. return Result;
  5338. }
  5339. //---------------------------------------------------------------------------
  5340. void __fastcall TTerminal::CacheCertificate(const UnicodeString & CertificateStorageKey,
  5341. const UnicodeString & Fingerprint, int Failures)
  5342. {
  5343. UnicodeString CertificateData = FormatCertificateData(Fingerprint, Failures);
  5344. std::unique_ptr<THierarchicalStorage> Storage(Configuration->CreateConfigStorage());
  5345. Storage->AccessMode = smReadWrite;
  5346. if (Storage->OpenSubKey(CertificateStorageKey, true))
  5347. {
  5348. Storage->WriteString(SessionData->SiteKey, CertificateData);
  5349. }
  5350. }
  5351. //---------------------------------------------------------------------------
  5352. void __fastcall TTerminal::CollectTlsUsage(const UnicodeString & TlsVersionStr)
  5353. {
  5354. // see SSL_get_version() in OpenSSL ssl_lib.c
  5355. if (TlsVersionStr == L"TLSv1.2")
  5356. {
  5357. Configuration->Usage->Inc(L"OpenedSessionsTLS12");
  5358. }
  5359. else if (TlsVersionStr == L"TLSv1.1")
  5360. {
  5361. Configuration->Usage->Inc(L"OpenedSessionsTLS11");
  5362. }
  5363. else if (TlsVersionStr == L"TLSv1")
  5364. {
  5365. Configuration->Usage->Inc(L"OpenedSessionsTLS10");
  5366. }
  5367. else if (TlsVersionStr == L"SSLv3")
  5368. {
  5369. Configuration->Usage->Inc(L"OpenedSessionsSSL30");
  5370. }
  5371. else if (TlsVersionStr == L"SSLv2")
  5372. {
  5373. Configuration->Usage->Inc(L"OpenedSessionsSSL20");
  5374. }
  5375. else
  5376. {
  5377. FAIL;
  5378. }
  5379. }
  5380. //---------------------------------------------------------------------------
  5381. __fastcall TSecondaryTerminal::TSecondaryTerminal(TTerminal * MainTerminal,
  5382. TSessionData * ASessionData, TConfiguration * Configuration, const UnicodeString & Name) :
  5383. TTerminal(ASessionData, Configuration),
  5384. FMainTerminal(MainTerminal)
  5385. {
  5386. Log->Parent = FMainTerminal->Log;
  5387. Log->Name = Name;
  5388. ActionLog->Enabled = false;
  5389. SessionData->NonPersistant();
  5390. assert(FMainTerminal != NULL);
  5391. if (!FMainTerminal->UserName.IsEmpty())
  5392. {
  5393. SessionData->UserName = FMainTerminal->UserName;
  5394. }
  5395. }
  5396. //---------------------------------------------------------------------------
  5397. void __fastcall TSecondaryTerminal::DirectoryLoaded(TRemoteFileList * FileList)
  5398. {
  5399. FMainTerminal->DirectoryLoaded(FileList);
  5400. assert(FileList != NULL);
  5401. }
  5402. //---------------------------------------------------------------------------
  5403. void __fastcall TSecondaryTerminal::DirectoryModified(const UnicodeString Path,
  5404. bool SubDirs)
  5405. {
  5406. // clear cache of main terminal
  5407. FMainTerminal->DirectoryModified(Path, SubDirs);
  5408. }
  5409. //---------------------------------------------------------------------------
  5410. TTerminal * __fastcall TSecondaryTerminal::GetPasswordSource()
  5411. {
  5412. return FMainTerminal;
  5413. }
  5414. //---------------------------------------------------------------------------
  5415. __fastcall TTerminalList::TTerminalList(TConfiguration * AConfiguration) :
  5416. TObjectList()
  5417. {
  5418. assert(AConfiguration);
  5419. FConfiguration = AConfiguration;
  5420. }
  5421. //---------------------------------------------------------------------------
  5422. __fastcall TTerminalList::~TTerminalList()
  5423. {
  5424. assert(Count == 0);
  5425. }
  5426. //---------------------------------------------------------------------------
  5427. TTerminal * __fastcall TTerminalList::CreateTerminal(TSessionData * Data)
  5428. {
  5429. return new TTerminal(Data, FConfiguration);
  5430. }
  5431. //---------------------------------------------------------------------------
  5432. TTerminal * __fastcall TTerminalList::NewTerminal(TSessionData * Data)
  5433. {
  5434. TTerminal * Terminal = CreateTerminal(Data);
  5435. Add(Terminal);
  5436. return Terminal;
  5437. }
  5438. //---------------------------------------------------------------------------
  5439. void __fastcall TTerminalList::FreeTerminal(TTerminal * Terminal)
  5440. {
  5441. assert(IndexOf(Terminal) >= 0);
  5442. Remove(Terminal);
  5443. }
  5444. //---------------------------------------------------------------------------
  5445. void __fastcall TTerminalList::FreeAndNullTerminal(TTerminal * & Terminal)
  5446. {
  5447. TTerminal * T = Terminal;
  5448. Terminal = NULL;
  5449. FreeTerminal(T);
  5450. }
  5451. //---------------------------------------------------------------------------
  5452. TTerminal * __fastcall TTerminalList::GetTerminal(int Index)
  5453. {
  5454. return dynamic_cast<TTerminal *>(Items[Index]);
  5455. }
  5456. //---------------------------------------------------------------------------
  5457. void __fastcall TTerminalList::Idle()
  5458. {
  5459. TTerminal * Terminal;
  5460. for (int i = 0; i < Count; i++)
  5461. {
  5462. Terminal = Terminals[i];
  5463. if (Terminal->Status == ssOpened)
  5464. {
  5465. Terminal->Idle();
  5466. }
  5467. }
  5468. }
  5469. //---------------------------------------------------------------------------
  5470. void __fastcall TTerminalList::RecryptPasswords()
  5471. {
  5472. for (int Index = 0; Index < Count; Index++)
  5473. {
  5474. Terminals[Index]->RecryptPasswords();
  5475. }
  5476. }