SessionData.cpp 195 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960
  1. //---------------------------------------------------------------------------
  2. #include <vcl.h>
  3. #pragma hdrstop
  4. #include "SessionData.h"
  5. #include "Common.h"
  6. #include "Exceptions.h"
  7. #include "FileBuffer.h"
  8. #include "CoreMain.h"
  9. #include "TextsCore.h"
  10. #include "PuttyIntf.h"
  11. #include "RemoteFiles.h"
  12. #include "SFTPFileSystem.h"
  13. #include "S3FileSystem.h"
  14. #include "FileMasks.h"
  15. #include <Soap.EncdDecd.hpp>
  16. #include <StrUtils.hpp>
  17. #include <XMLDoc.hpp>
  18. #include <System.IOUtils.hpp>
  19. #include <algorithm>
  20. //---------------------------------------------------------------------------
  21. #pragma package(smart_init)
  22. //---------------------------------------------------------------------------
  23. #define SET_SESSION_PROPERTY_FROM(PROPERTY, FROM) \
  24. if (F##PROPERTY != FROM) { F##PROPERTY = FROM; Modify(); }
  25. //---------------------------------------------------------------------------
  26. #define SET_SESSION_PROPERTY(PROPERTY) \
  27. SET_SESSION_PROPERTY_FROM(PROPERTY, value)
  28. //---------------------------------------------------------------------------
  29. const wchar_t * PingTypeNames = L"Off;Null;Dummy";
  30. const wchar_t * FtpPingTypeNames = L"Off;Dummy;Dummy;List";
  31. const wchar_t * ProxyMethodNames = L"None;SOCKS4;SOCKS5;HTTP;Telnet;Cmd";
  32. TIntMapping ProxyMethodMapping = CreateIntMappingFromEnumNames(LowerCase(ProxyMethodNames));
  33. const wchar_t * DefaultName = L"Default Settings";
  34. const UnicodeString CipherNames[CIPHER_COUNT] = {L"WARN", L"3des", L"blowfish", L"aes", L"des", L"arcfour", L"chacha20", "aesgcm"};
  35. const UnicodeString KexNames[KEX_COUNT] = {L"WARN", L"dh-group1-sha1", L"dh-group14-sha1", L"dh-group15-sha512", L"dh-group16-sha512", L"dh-group17-sha512", L"dh-group18-sha512", L"dh-gex-sha1", L"rsa", L"ecdh", L"ntru-curve25519"};
  36. const UnicodeString HostKeyNames[HOSTKEY_COUNT] = {L"WARN", L"rsa", L"dsa", L"ecdsa", L"ed25519", L"ed448"};
  37. const UnicodeString GssLibNames[GSSLIB_COUNT] = {L"gssapi32", L"sspi", L"custom"};
  38. // Update also order in SshCipherList()
  39. const TCipher DefaultCipherList[CIPHER_COUNT] =
  40. { cipAES, cipChaCha20, cipAESGCM, cip3DES, cipWarn, cipDES, cipBlowfish, cipArcfour };
  41. // Update also order in SshKexList()
  42. const TKex DefaultKexList[KEX_COUNT] =
  43. { kexNTRUHybrid, kexECDH, kexDHGEx, kexDHGroup18, kexDHGroup17, kexDHGroup16, kexDHGroup15, kexDHGroup14, kexRSA, kexWarn, kexDHGroup1 };
  44. const THostKey DefaultHostKeyList[HOSTKEY_COUNT] =
  45. { hkED448, hkED25519, hkECDSA, hkRSA, hkDSA, hkWarn };
  46. const TGssLib DefaultGssLibList[GSSLIB_COUNT] =
  47. { gssGssApi32, gssSspi, gssCustom };
  48. const wchar_t FSProtocolNames[FSPROTOCOL_COUNT][16] = { L"SCP", L"SFTP (SCP)", L"SFTP", L"", L"", L"FTP", L"WebDAV", L"S3" };
  49. const int SshPortNumber = 22;
  50. const int FtpPortNumber = 21;
  51. const int FtpsImplicitPortNumber = 990;
  52. const int HTTPPortNumber = 80;
  53. const int HTTPSPortNumber = 443;
  54. const int TelnetPortNumber = 23;
  55. const int DefaultSendBuf = 262144;
  56. const int ProxyPortNumber = 80;
  57. const UnicodeString AnonymousUserName(L"anonymous");
  58. const UnicodeString AnonymousPassword(L"[email protected]");
  59. const UnicodeString PuttySshProtocol(L"ssh");
  60. const UnicodeString PuttyTelnetProtocol(L"telnet");
  61. const UnicodeString SftpProtocol(L"sftp");
  62. const UnicodeString ScpProtocol(L"scp");
  63. const UnicodeString FtpProtocol(L"ftp");
  64. const UnicodeString FtpsProtocol(L"ftps");
  65. const UnicodeString FtpesProtocol(L"ftpes");
  66. const UnicodeString WebDAVProtocol(L"dav");
  67. const UnicodeString WebDAVSProtocol(L"davs");
  68. const UnicodeString S3Protocol(L"s3");
  69. const UnicodeString S3PlainProtocol(L"s3plain");
  70. const UnicodeString SshProtocol(L"ssh");
  71. const UnicodeString WinSCPProtocolPrefix(L"winscp-");
  72. const wchar_t UrlParamSeparator = L';';
  73. const wchar_t UrlParamValueSeparator = L'=';
  74. const UnicodeString UrlHostKeyParamName(L"fingerprint");
  75. const UnicodeString UrlSaveParamName(L"save");
  76. const UnicodeString UrlRawSettingsParamNamePrefix(L"x-");
  77. const UnicodeString PassphraseOption(L"passphrase");
  78. const UnicodeString RawSettingsOption(L"rawsettings");
  79. const UnicodeString S3HostName(S3LibDefaultHostName());
  80. const UnicodeString S3GoogleCloudHostName(L"storage.googleapis.com");
  81. const UnicodeString OpensshHostDirective(L"Host");
  82. //---------------------------------------------------------------------
  83. TDateTime __fastcall SecToDateTime(int Sec)
  84. {
  85. return TDateTime(double(Sec) / SecsPerDay);
  86. }
  87. //---------------------------------------------------------------------
  88. static bool IsValidOpensshLine(const UnicodeString & Line)
  89. {
  90. return !Line.IsEmpty() && (Line[1] != L'#');
  91. }
  92. //---------------------------------------------------------------------
  93. bool ParseOpensshDirective(const UnicodeString & ALine, UnicodeString & Directive, UnicodeString & Value)
  94. {
  95. bool Result = IsValidOpensshLine(ALine);
  96. if (Result)
  97. {
  98. UnicodeString Line = Trim(ALine);
  99. if (Line.SubString(1, 1) == "\"")
  100. {
  101. Line.Delete(1, 1);
  102. int P = Line.Pos("\"");
  103. Result = (P > 0);
  104. if (Result)
  105. {
  106. Directive = Line.SubString(1, P - 1);
  107. Line = MidStr(Line, P + 1).Trim();
  108. }
  109. }
  110. else
  111. {
  112. wchar_t Equal = L'=';
  113. UnicodeString Whitespaces(L" \t");
  114. UnicodeString Delimiters(Whitespaces + Equal);
  115. int P = FindDelimiter(Delimiters, Line);
  116. Result = (P > 0);
  117. if (Result)
  118. {
  119. Directive = Line.SubString(1, P - 1);
  120. Line.Delete(1, P - 1);
  121. UnicodeString TrimChars = Delimiters;
  122. while (!Line.IsEmpty() && Line.IsDelimiter(TrimChars, 1))
  123. {
  124. if (Line[1] == Equal)
  125. {
  126. TrimChars = Whitespaces;
  127. }
  128. Line.Delete(1, 1);
  129. }
  130. }
  131. }
  132. Value = Line;
  133. Result = !Value.IsEmpty();
  134. }
  135. return Result;
  136. }
  137. //--- TSessionData ----------------------------------------------------
  138. __fastcall TSessionData::TSessionData(UnicodeString aName):
  139. TNamedObject(aName)
  140. {
  141. Default();
  142. FModified = true;
  143. }
  144. //---------------------------------------------------------------------
  145. _fastcall TSessionData::~TSessionData()
  146. {
  147. }
  148. //---------------------------------------------------------------------
  149. int __fastcall TSessionData::Compare(TNamedObject * Other)
  150. {
  151. int Result;
  152. // To avoid using CompareLogicalText on hex names of sessions in workspace.
  153. // The session 000A would be sorted before 0001.
  154. if (IsWorkspace && DebugNotNull(dynamic_cast<TSessionData *>(Other))->IsWorkspace)
  155. {
  156. Result = CompareText(Name, Other->Name);
  157. }
  158. else
  159. {
  160. Result = TNamedObject::Compare(Other);
  161. }
  162. return Result;
  163. }
  164. //---------------------------------------------------------------------
  165. TSessionData * __fastcall TSessionData::Clone()
  166. {
  167. std::unique_ptr<TSessionData> Data(new TSessionData(L""));
  168. Data->Assign(this);
  169. return Data.release();
  170. }
  171. //---------------------------------------------------------------------
  172. void __fastcall TSessionData::DefaultSettings()
  173. {
  174. HostName = L"";
  175. PortNumber = SshPortNumber;
  176. UserName = L"";
  177. Password = L"";
  178. NewPassword = L"";
  179. ChangePassword = false;
  180. PingInterval = 30;
  181. PingType = ptOff;
  182. Timeout = 15;
  183. TryAgent = true;
  184. AgentFwd = false;
  185. AuthKI = true;
  186. AuthKIPassword = true;
  187. AuthGSSAPI = true;
  188. AuthGSSAPIKEX = false;
  189. GSSAPIFwdTGT = false;
  190. LogicalHostName = L"";
  191. ChangeUsername = false;
  192. Compression = false;
  193. Ssh2DES = false;
  194. SshNoUserAuth = false;
  195. for (int Index = 0; Index < CIPHER_COUNT; Index++)
  196. {
  197. Cipher[Index] = DefaultCipherList[Index];
  198. }
  199. for (int Index = 0; Index < KEX_COUNT; Index++)
  200. {
  201. Kex[Index] = DefaultKexList[Index];
  202. }
  203. for (int Index = 0; Index < HOSTKEY_COUNT; Index++)
  204. {
  205. HostKeys[Index] = DefaultHostKeyList[Index];
  206. }
  207. for (int Index = 0; Index < GSSLIB_COUNT; Index++)
  208. {
  209. GssLib[Index] = DefaultGssLibList[Index];
  210. }
  211. GssLibCustom = L"";
  212. PublicKeyFile = EmptyStr;
  213. DetachedCertificate = EmptyStr;
  214. Passphrase = L"";
  215. FPuttyProtocol = L"";
  216. TcpNoDelay = false;
  217. SendBuf = DefaultSendBuf;
  218. SourceAddress = L"";
  219. ProtocolFeatures = L"";
  220. SshSimple = true;
  221. HostKey = L"";
  222. FingerprintScan = false;
  223. FOverrideCachedHostKey = true;
  224. Note = L"";
  225. WinTitle = L"";
  226. InternalEditorEncoding = -1;
  227. EncryptKey = UnicodeString();
  228. WebDavLiberalEscaping = false;
  229. WebDavAuthLegacy = false;
  230. ProxyMethod = ::pmNone;
  231. ProxyHost = L"proxy";
  232. ProxyPort = ProxyPortNumber;
  233. ProxyUsername = L"";
  234. ProxyPassword = L"";
  235. ProxyTelnetCommand = L"connect %host %port\\n";
  236. ProxyLocalCommand = L"";
  237. ProxyDNS = asAuto;
  238. ProxyLocalhost = false;
  239. for (unsigned int Index = 0; Index < LENOF(FBugs); Index++)
  240. {
  241. Bug[(TSshBug)Index] = asAuto;
  242. }
  243. Special = false;
  244. FSProtocol = fsSFTP;
  245. AddressFamily = afAuto;
  246. RekeyData = L"1G";
  247. RekeyTime = MinsPerHour;
  248. // FS common
  249. LocalDirectory = L"";
  250. OtherLocalDirectory = L"";
  251. RemoteDirectory = L"";
  252. SynchronizeBrowsing = false;
  253. UpdateDirectories = true;
  254. RequireDirectories = false;
  255. CacheDirectories = true;
  256. CacheDirectoryChanges = true;
  257. PreserveDirectoryChanges = true;
  258. ResolveSymlinks = true;
  259. FollowDirectorySymlinks = false;
  260. DSTMode = dstmUnix;
  261. DeleteToRecycleBin = false;
  262. OverwrittenToRecycleBin = false;
  263. RecycleBinPath = L"";
  264. Color = 0;
  265. PostLoginCommands = L"";
  266. // SCP
  267. LookupUserGroups = asAuto;
  268. EOLType = eolLF;
  269. TrimVMSVersions = false;
  270. VMSAllRevisions = false;
  271. Shell = L""; //default shell
  272. ReturnVar = L"";
  273. ExitCode1IsError = false;
  274. ClearAliases = true;
  275. UnsetNationalVars = true;
  276. ListingCommand = L"ls -la";
  277. IgnoreLsWarnings = true;
  278. Scp1Compatibility = false;
  279. TimeDifference = 0;
  280. TimeDifferenceAuto = true;
  281. SCPLsFullTime = asAuto;
  282. NotUtf = asAuto;
  283. // S3
  284. S3DefaultRegion = EmptyStr;
  285. S3SessionToken = EmptyStr;
  286. S3RoleArn = EmptyStr;
  287. S3RoleSessionName = EmptyStr;
  288. S3Profile = EmptyStr;
  289. S3UrlStyle = s3usVirtualHost;
  290. S3MaxKeys = asAuto;
  291. S3CredentialsEnv = false;
  292. S3RequesterPays = false;
  293. // SFTP
  294. SftpServer = L"";
  295. SFTPDownloadQueue = 32;
  296. SFTPUploadQueue = 64;
  297. SFTPListingQueue = 2;
  298. SFTPMaxVersion = SFTPMaxVersionAuto;
  299. SFTPMaxPacketSize = 0;
  300. SFTPRealPath = asAuto;
  301. UsePosixRename = false;
  302. for (unsigned int Index = 0; Index < LENOF(FSFTPBugs); Index++)
  303. {
  304. SFTPBug[(TSftpBug)Index] = asAuto;
  305. }
  306. Tunnel = false;
  307. TunnelHostName = L"";
  308. TunnelPortNumber = SshPortNumber;
  309. TunnelUserName = L"";
  310. TunnelPassword = L"";
  311. TunnelPublicKeyFile = L"";
  312. TunnelPassphrase = L"";
  313. TunnelLocalPortNumber = 0;
  314. TunnelPortFwd = L"";
  315. TunnelHostKey = L"";
  316. // FTP
  317. FtpPasvMode = true;
  318. FtpForcePasvIp = asAuto;
  319. FtpUseMlsd = asAuto;
  320. FtpAccount = L"";
  321. FtpPingInterval = 30;
  322. FtpPingType = fptDummyCommand;
  323. FtpTransferActiveImmediately = asAuto;
  324. Ftps = ftpsNone;
  325. MinTlsVersion = tlsDefaultMin;
  326. MaxTlsVersion = tlsMax;
  327. CompleteTlsShutdown = asAuto;
  328. FtpListAll = asAuto;
  329. FtpHost = asAuto;
  330. FtpWorkFromCwd = asAuto;
  331. FtpAnyCodeForPwd = false;
  332. SslSessionReuse = true;
  333. TlsCertificateFile = L"";
  334. FtpProxyLogonType = 0; // none
  335. PuttySettings = UnicodeString();
  336. CustomParam1 = L"";
  337. CustomParam2 = L"";
  338. }
  339. //---------------------------------------------------------------------
  340. void __fastcall TSessionData::Default()
  341. {
  342. DefaultSettings();
  343. IsWorkspace = false;
  344. Link = L"";
  345. NameOverride = L"";
  346. Selected = false;
  347. FModified = false;
  348. FSource = ::ssNone;
  349. FSaveOnly = false;
  350. // add also to TSessionLog::AddStartupInfo()
  351. }
  352. //---------------------------------------------------------------------
  353. void __fastcall TSessionData::NonPersistent()
  354. {
  355. UpdateDirectories = false;
  356. PreserveDirectoryChanges = false;
  357. }
  358. //---------------------------------------------------------------------
  359. #define PROPERTY(P) PROPERTY_HANDLER(P, )
  360. #define BASE_PROPERTIES \
  361. PROPERTY(HostName); \
  362. PROPERTY(PortNumber); \
  363. PROPERTY(UserName); \
  364. PROPERTY_HANDLER(Password, F); \
  365. PROPERTY(PublicKeyFile); \
  366. PROPERTY(DetachedCertificate); \
  367. PROPERTY_HANDLER(Passphrase, F); \
  368. PROPERTY(FSProtocol); \
  369. PROPERTY(Ftps); \
  370. PROPERTY(LocalDirectory); \
  371. PROPERTY(OtherLocalDirectory); \
  372. PROPERTY(RemoteDirectory); \
  373. PROPERTY(RequireDirectories); \
  374. PROPERTY(Color); \
  375. PROPERTY(SynchronizeBrowsing); \
  376. PROPERTY(Note);
  377. //---------------------------------------------------------------------
  378. #define ADVANCED_PROPERTIES \
  379. PROPERTY_HANDLER(NewPassword, F); \
  380. PROPERTY(ChangePassword); \
  381. PROPERTY(PingInterval); \
  382. PROPERTY(PingType); \
  383. PROPERTY(Timeout); \
  384. PROPERTY(TryAgent); \
  385. PROPERTY(AgentFwd); \
  386. PROPERTY(LogicalHostName); \
  387. PROPERTY(ChangeUsername); \
  388. PROPERTY(Compression); \
  389. PROPERTY(Ssh2DES); \
  390. PROPERTY(SshNoUserAuth); \
  391. PROPERTY(CipherList); \
  392. PROPERTY(KexList); \
  393. PROPERTY(HostKeyList); \
  394. PROPERTY(GssLibList); \
  395. PROPERTY(GssLibCustom); \
  396. PROPERTY(AddressFamily); \
  397. PROPERTY(RekeyData); \
  398. PROPERTY(RekeyTime); \
  399. PROPERTY(HostKey); \
  400. PROPERTY(FingerprintScan); \
  401. PROPERTY(InternalEditorEncoding); \
  402. \
  403. PROPERTY(UpdateDirectories); \
  404. PROPERTY(CacheDirectories); \
  405. PROPERTY(CacheDirectoryChanges); \
  406. PROPERTY(PreserveDirectoryChanges); \
  407. \
  408. PROPERTY(ResolveSymlinks); \
  409. PROPERTY(FollowDirectorySymlinks); \
  410. PROPERTY(DSTMode); \
  411. PROPERTY(Special); \
  412. PROPERTY(Selected); \
  413. PROPERTY(ReturnVar); \
  414. PROPERTY(ExitCode1IsError); \
  415. PROPERTY(LookupUserGroups); \
  416. PROPERTY(EOLType); \
  417. PROPERTY(TrimVMSVersions); \
  418. PROPERTY(VMSAllRevisions); \
  419. PROPERTY(Shell); \
  420. PROPERTY(ClearAliases); \
  421. PROPERTY(Scp1Compatibility); \
  422. PROPERTY(UnsetNationalVars); \
  423. PROPERTY(ListingCommand); \
  424. PROPERTY(IgnoreLsWarnings); \
  425. PROPERTY(SCPLsFullTime); \
  426. \
  427. PROPERTY(TimeDifference); \
  428. PROPERTY(TimeDifferenceAuto); \
  429. PROPERTY(TcpNoDelay); \
  430. PROPERTY(SendBuf); \
  431. PROPERTY(SourceAddress); \
  432. PROPERTY(ProtocolFeatures); \
  433. PROPERTY(SshSimple); \
  434. PROPERTY(AuthKI); \
  435. PROPERTY(AuthKIPassword); \
  436. PROPERTY(AuthGSSAPI); \
  437. PROPERTY(AuthGSSAPIKEX); \
  438. PROPERTY(GSSAPIFwdTGT); \
  439. PROPERTY(DeleteToRecycleBin); \
  440. PROPERTY(OverwrittenToRecycleBin); \
  441. PROPERTY(RecycleBinPath); \
  442. PROPERTY(NotUtf); \
  443. PROPERTY(PostLoginCommands); \
  444. \
  445. PROPERTY(S3DefaultRegion); \
  446. PROPERTY(S3SessionToken); \
  447. PROPERTY(S3RoleArn); \
  448. PROPERTY(S3RoleSessionName); \
  449. PROPERTY(S3Profile); \
  450. PROPERTY(S3UrlStyle); \
  451. PROPERTY(S3MaxKeys); \
  452. PROPERTY(S3CredentialsEnv); \
  453. PROPERTY(S3RequesterPays); \
  454. \
  455. PROPERTY(ProxyMethod); \
  456. PROPERTY(ProxyHost); \
  457. PROPERTY(ProxyPort); \
  458. PROPERTY(ProxyUsername); \
  459. PROPERTY_HANDLER(ProxyPassword, F); \
  460. PROPERTY(ProxyTelnetCommand); \
  461. PROPERTY(ProxyLocalCommand); \
  462. PROPERTY(ProxyDNS); \
  463. PROPERTY(ProxyLocalhost); \
  464. \
  465. for (unsigned int Index = 0; Index < LENOF(FBugs); Index++) \
  466. { \
  467. PROPERTY(Bug[(TSshBug)Index]); \
  468. } \
  469. \
  470. PROPERTY(SftpServer); \
  471. PROPERTY(SFTPDownloadQueue); \
  472. PROPERTY(SFTPUploadQueue); \
  473. PROPERTY(SFTPListingQueue); \
  474. PROPERTY(SFTPMaxVersion); \
  475. PROPERTY(SFTPMaxPacketSize); \
  476. PROPERTY(SFTPRealPath); \
  477. PROPERTY(UsePosixRename); \
  478. \
  479. for (unsigned int Index = 0; Index < LENOF(FSFTPBugs); Index++) \
  480. { \
  481. PROPERTY(SFTPBug[(TSftpBug)Index]); \
  482. } \
  483. \
  484. PROPERTY(Tunnel); \
  485. PROPERTY(TunnelHostName); \
  486. PROPERTY(TunnelPortNumber); \
  487. PROPERTY(TunnelUserName); \
  488. PROPERTY_HANDLER(TunnelPassword, F); \
  489. PROPERTY(TunnelPublicKeyFile); \
  490. PROPERTY_HANDLER(TunnelPassphrase, F); \
  491. PROPERTY(TunnelLocalPortNumber); \
  492. PROPERTY(TunnelPortFwd); \
  493. PROPERTY(TunnelHostKey); \
  494. \
  495. PROPERTY(FtpPasvMode); \
  496. PROPERTY(FtpForcePasvIp); \
  497. PROPERTY(FtpUseMlsd); \
  498. PROPERTY(FtpAccount); \
  499. PROPERTY(FtpPingInterval); \
  500. PROPERTY(FtpPingType); \
  501. PROPERTY(FtpTransferActiveImmediately); \
  502. PROPERTY(FtpListAll); \
  503. PROPERTY(FtpHost); \
  504. PROPERTY(FtpWorkFromCwd); \
  505. PROPERTY(FtpAnyCodeForPwd); \
  506. PROPERTY(SslSessionReuse); \
  507. PROPERTY(TlsCertificateFile); \
  508. \
  509. PROPERTY(FtpProxyLogonType); \
  510. \
  511. PROPERTY(MinTlsVersion); \
  512. PROPERTY(MaxTlsVersion); \
  513. PROPERTY(CompleteTlsShutdown); \
  514. \
  515. PROPERTY(WinTitle); \
  516. \
  517. PROPERTY_HANDLER(EncryptKey, F); \
  518. \
  519. PROPERTY(WebDavLiberalEscaping); \
  520. PROPERTY(WebDavAuthLegacy); \
  521. \
  522. PROPERTY(PuttySettings); \
  523. \
  524. PROPERTY(CustomParam1); \
  525. PROPERTY(CustomParam2);
  526. #define META_PROPERTIES \
  527. PROPERTY(IsWorkspace); \
  528. PROPERTY(Link); \
  529. PROPERTY(NameOverride);
  530. //---------------------------------------------------------------------
  531. void __fastcall TSessionData::Assign(TPersistent * Source)
  532. {
  533. if (Source && Source->InheritsFrom(__classid(TSessionData)))
  534. {
  535. TSessionData * SourceData = (TSessionData *)Source;
  536. // Master password prompt shows implicitly here, when cloning the session data for a new terminal
  537. CopyData(SourceData);
  538. FSource = SourceData->FSource;
  539. }
  540. else
  541. {
  542. TNamedObject::Assign(Source);
  543. }
  544. }
  545. //---------------------------------------------------------------------
  546. void __fastcall TSessionData::DoCopyData(TSessionData * SourceData, bool NoRecrypt)
  547. {
  548. #define PROPERTY_HANDLER(P, F) \
  549. if (NoRecrypt) \
  550. { \
  551. F##P = SourceData->F##P; \
  552. } \
  553. else \
  554. { \
  555. P = SourceData->P; \
  556. }
  557. PROPERTY(Name);
  558. BASE_PROPERTIES;
  559. ADVANCED_PROPERTIES;
  560. META_PROPERTIES;
  561. #undef PROPERTY_HANDLER
  562. FOverrideCachedHostKey = SourceData->FOverrideCachedHostKey;
  563. FModified = SourceData->Modified;
  564. FSaveOnly = SourceData->FSaveOnly;
  565. }
  566. //---------------------------------------------------------------------
  567. void __fastcall TSessionData::CopyData(TSessionData * SourceData)
  568. {
  569. DoCopyData(SourceData, false);
  570. }
  571. //---------------------------------------------------------------------
  572. void __fastcall TSessionData::CopyDataNoRecrypt(TSessionData * SourceData)
  573. {
  574. DoCopyData(SourceData, true);
  575. }
  576. //---------------------------------------------------------------------
  577. void __fastcall TSessionData::CopyDirectoriesStateData(TSessionData * SourceData)
  578. {
  579. RemoteDirectory = SourceData->RemoteDirectory;
  580. LocalDirectory = SourceData->LocalDirectory;
  581. OtherLocalDirectory = SourceData->OtherLocalDirectory;
  582. SynchronizeBrowsing = SourceData->SynchronizeBrowsing;
  583. }
  584. //---------------------------------------------------------------------
  585. bool __fastcall TSessionData::HasStateData()
  586. {
  587. return
  588. !RemoteDirectory.IsEmpty() ||
  589. !LocalDirectory.IsEmpty() ||
  590. !OtherLocalDirectory.IsEmpty() ||
  591. (Color != 0);
  592. }
  593. //---------------------------------------------------------------------
  594. void __fastcall TSessionData::CopyStateData(TSessionData * SourceData)
  595. {
  596. // Keep in sync with TCustomScpExplorerForm::UpdateSessionData.
  597. CopyDirectoriesStateData(SourceData);
  598. Color = SourceData->Color;
  599. }
  600. //---------------------------------------------------------------------
  601. void __fastcall TSessionData::CopyNonCoreData(TSessionData * SourceData)
  602. {
  603. CopyStateData(SourceData);
  604. UpdateDirectories = SourceData->UpdateDirectories;
  605. Note = SourceData->Note;
  606. }
  607. //---------------------------------------------------------------------
  608. bool __fastcall TSessionData::IsSame(
  609. const TSessionData * Default, bool AdvancedOnly, TStrings * DifferentProperties, bool Decrypted)
  610. {
  611. bool Result = true;
  612. #define PROPERTY_HANDLER(P, F) \
  613. if ((Decrypted && (P != Default->P)) || \
  614. (!Decrypted && (F##P != Default->F##P))) \
  615. { \
  616. Result = false; \
  617. if (DifferentProperties != NULL) \
  618. { \
  619. DifferentProperties->Add(#P); \
  620. } \
  621. else \
  622. { \
  623. return Result; \
  624. } \
  625. }
  626. if (!AdvancedOnly)
  627. {
  628. BASE_PROPERTIES;
  629. META_PROPERTIES;
  630. }
  631. ADVANCED_PROPERTIES;
  632. #undef PROPERTY_HANDLER
  633. return Result;
  634. }
  635. //---------------------------------------------------------------------
  636. bool __fastcall TSessionData::IsSame(const TSessionData * Default, bool AdvancedOnly)
  637. {
  638. return IsSame(Default, AdvancedOnly, NULL, false);
  639. }
  640. //---------------------------------------------------------------------
  641. bool __fastcall TSessionData::IsSameDecrypted(const TSessionData * Default)
  642. {
  643. return IsSame(Default, false, NULL, true);
  644. }
  645. //---------------------------------------------------------------------
  646. TFSProtocol NormalizeFSProtocol(TFSProtocol FSProtocol)
  647. {
  648. if (FSProtocol == fsSFTPonly)
  649. {
  650. FSProtocol = fsSFTP;
  651. }
  652. return FSProtocol;
  653. }
  654. //---------------------------------------------------------------------
  655. bool __fastcall TSessionData::IsSameSite(const TSessionData * Other)
  656. {
  657. return
  658. // Particularly when handling /refresh,
  659. // fsSFTPonly sites when compared against sftp:// URLs (fsSFTP) have to match.
  660. // But similarly also falled back SCP sites.
  661. (NormalizeFSProtocol(FSProtocol) == NormalizeFSProtocol(Other->FSProtocol)) &&
  662. (HostName == Other->HostName) &&
  663. (PortNumber == Other->PortNumber) &&
  664. (UserName == Other->UserName);
  665. }
  666. //---------------------------------------------------------------------
  667. bool __fastcall TSessionData::IsInFolderOrWorkspace(const UnicodeString & AFolder)
  668. {
  669. return StartsText(UnixIncludeTrailingBackslash(AFolder), Name);
  670. }
  671. //---------------------------------------------------------------------
  672. void __fastcall TSessionData::DoLoad(THierarchicalStorage * Storage, bool PuttyImport, bool & RewritePassword, bool Unsafe, bool RespectDisablePasswordStoring)
  673. {
  674. // Make sure we only ever use methods supported by TOptionsStorage
  675. // (implemented by TOptionsIniFile)
  676. PortNumber = Storage->ReadInteger(L"PortNumber", PortNumber);
  677. UserName = Storage->ReadString(L"UserName", UserName);
  678. // must be loaded after UserName, because HostName may be in format user@host
  679. HostName = Storage->ReadString(L"HostName", HostName);
  680. #define LOAD_PASSWORD_EX(PROP, PLAIN_NAME, ENC_NAME, ONPLAIN) \
  681. if (Storage->ValueExists(PLAIN_NAME)) \
  682. { \
  683. PROP = Storage->ReadString(PLAIN_NAME, PROP); \
  684. ONPLAIN \
  685. } \
  686. else \
  687. { \
  688. RawByteString A##PROP = Storage->ReadStringAsBinaryData(ENC_NAME, F##PROP); \
  689. SET_SESSION_PROPERTY_FROM(PROP, A##PROP); \
  690. }
  691. #define LOAD_PASSWORD(PROP, PLAIN_NAME) LOAD_PASSWORD_EX(PROP, PLAIN_NAME, TEXT(#PROP), RewritePassword = true;)
  692. bool LoadPasswords = !Configuration->DisablePasswordStoring || !RespectDisablePasswordStoring;
  693. if (LoadPasswords)
  694. {
  695. LOAD_PASSWORD(Password, L"PasswordPlain");
  696. }
  697. HostKey = Storage->ReadString(L"SshHostKey", HostKey); // probably never used
  698. Note = Storage->ReadString(L"Note", Note);
  699. // Putty uses PingIntervalSecs
  700. int PingIntervalSecs = Storage->ReadInteger(L"PingIntervalSecs", -1);
  701. if (PingIntervalSecs < 0)
  702. {
  703. PingIntervalSecs = Storage->ReadInteger(L"PingIntervalSec", PingInterval%SecsPerMin);
  704. }
  705. PingInterval =
  706. Storage->ReadInteger(L"PingInterval", PingInterval/SecsPerMin)*SecsPerMin +
  707. PingIntervalSecs;
  708. if (PingInterval == 0)
  709. {
  710. PingInterval = 30;
  711. }
  712. PingType = static_cast<TPingType>(Storage->ReadInteger(L"PingType", PingType));
  713. Timeout = Storage->ReadInteger(L"Timeout", Timeout);
  714. TryAgent = Storage->ReadBool(L"TryAgent", TryAgent);
  715. AgentFwd = Storage->ReadBool(L"AgentFwd", AgentFwd);
  716. AuthKI = Storage->ReadBool(L"AuthKI", AuthKI);
  717. AuthKIPassword = Storage->ReadBool(L"AuthKIPassword", AuthKIPassword);
  718. // Continue to use setting keys of previous kerberos implementation (vaclav tomec),
  719. // but fallback to keys of other implementations (official putty and vintela quest putty),
  720. // to allow imports from all putty versions.
  721. // Both vaclav tomec and official putty use AuthGSSAPI
  722. AuthGSSAPI = Storage->ReadBool(L"AuthGSSAPI", Storage->ReadBool(L"AuthSSPI", AuthGSSAPI));
  723. AuthGSSAPIKEX = Storage->ReadBool(L"AuthGSSAPIKEX", AuthGSSAPIKEX);
  724. GSSAPIFwdTGT = Storage->ReadBool(L"GSSAPIFwdTGT", Storage->ReadBool(L"GssapiFwd", Storage->ReadBool(L"SSPIFwdTGT", GSSAPIFwdTGT)));
  725. // KerbPrincipal was used by Quest PuTTY
  726. // GSSAPIServerRealm was used by Vaclav Tomec
  727. LogicalHostName = Storage->ReadString(L"LogicalHostName", Storage->ReadString(L"GSSAPIServerRealm", Storage->ReadString(L"KerbPrincipal", LogicalHostName)));
  728. ChangeUsername = Storage->ReadBool(L"ChangeUsername", ChangeUsername);
  729. Compression = Storage->ReadBool(L"Compression", Compression);
  730. Ssh2DES = Storage->ReadBool(L"Ssh2DES", Ssh2DES);
  731. SshNoUserAuth = Storage->ReadBool(L"SshNoUserAuth", SshNoUserAuth);
  732. CipherList = Storage->ReadString(L"Cipher", CipherList);
  733. KexList = Storage->ReadString(L"KEX", KexList);
  734. HostKeyList = Storage->ReadString(L"HostKey", HostKeyList);
  735. if (!Unsafe)
  736. {
  737. GssLibList = Storage->ReadString(L"GSSLibs", GssLibList);
  738. }
  739. GssLibCustom = Storage->ReadString(L"GSSCustom", GssLibCustom);
  740. PublicKeyFile = Storage->ReadString(L"PublicKeyFile", PublicKeyFile);
  741. DetachedCertificate = Storage->ReadString(L"DetachedCertificate", DetachedCertificate);
  742. AddressFamily = static_cast<TAddressFamily>
  743. (Storage->ReadInteger(L"AddressFamily", AddressFamily));
  744. RekeyData = Storage->ReadString(L"RekeyBytes", RekeyData);
  745. RekeyTime = Storage->ReadInteger(L"RekeyTime", RekeyTime);
  746. FSProtocol = (TFSProtocol)Storage->ReadInteger(L"FSProtocol", FSProtocol);
  747. LocalDirectory = Storage->ReadString(L"LocalDirectory", LocalDirectory);
  748. OtherLocalDirectory = Storage->ReadString(L"OtherLocalDirectory", OtherLocalDirectory);
  749. RemoteDirectory = Storage->ReadString(L"RemoteDirectory", RemoteDirectory);
  750. SynchronizeBrowsing = Storage->ReadBool(L"SynchronizeBrowsing", SynchronizeBrowsing);
  751. UpdateDirectories = Storage->ReadBool(L"UpdateDirectories", UpdateDirectories);
  752. CacheDirectories = Storage->ReadBool(L"CacheDirectories", CacheDirectories);
  753. CacheDirectoryChanges = Storage->ReadBool(L"CacheDirectoryChanges", CacheDirectoryChanges);
  754. PreserveDirectoryChanges = Storage->ReadBool(L"PreserveDirectoryChanges", PreserveDirectoryChanges);
  755. ResolveSymlinks = Storage->ReadBool(L"ResolveSymlinks", ResolveSymlinks);
  756. FollowDirectorySymlinks = Storage->ReadBool(L"FollowDirectorySymlinks", FollowDirectorySymlinks);
  757. DSTMode = (TDSTMode)Storage->ReadInteger(L"ConsiderDST", DSTMode);
  758. Special = Storage->ReadBool(L"Special", Special);
  759. if (!Unsafe)
  760. {
  761. Shell = Storage->ReadString(L"Shell", Shell);
  762. }
  763. ClearAliases = Storage->ReadBool(L"ClearAliases", ClearAliases);
  764. UnsetNationalVars = Storage->ReadBool(L"UnsetNationalVars", UnsetNationalVars);
  765. if (!Unsafe)
  766. {
  767. ListingCommand = Storage->ReadString(L"ListingCommand",
  768. Storage->ReadBool(L"AliasGroupList", false) ? UnicodeString(L"ls -gla") : ListingCommand);
  769. }
  770. IgnoreLsWarnings = Storage->ReadBool(L"IgnoreLsWarnings", IgnoreLsWarnings);
  771. SCPLsFullTime = Storage->ReadEnum(L"SCPLsFullTime", SCPLsFullTime, AutoSwitchMapping);
  772. Scp1Compatibility = Storage->ReadBool(L"Scp1Compatibility", Scp1Compatibility);
  773. TimeDifference = Storage->ReadFloat(L"TimeDifference", TimeDifference);
  774. TimeDifferenceAuto = Storage->ReadBool(L"TimeDifferenceAuto", (TimeDifference == TDateTime()));
  775. if (!Unsafe)
  776. {
  777. DeleteToRecycleBin = Storage->ReadBool(L"DeleteToRecycleBin", DeleteToRecycleBin);
  778. OverwrittenToRecycleBin = Storage->ReadBool(L"OverwrittenToRecycleBin", OverwrittenToRecycleBin);
  779. RecycleBinPath = Storage->ReadString(L"RecycleBinPath", RecycleBinPath);
  780. PostLoginCommands = Storage->ReadString(L"PostLoginCommands", PostLoginCommands);
  781. ReturnVar = Storage->ReadString(L"ReturnVar", ReturnVar);
  782. }
  783. ExitCode1IsError = Storage->ReadBool(L"ExitCode1IsError", ExitCode1IsError);
  784. LookupUserGroups = Storage->ReadEnum(L"LookupUserGroups2", LookupUserGroups, AutoSwitchMapping);
  785. EOLType = (TEOLType)Storage->ReadInteger(L"EOLType", EOLType);
  786. TrimVMSVersions = Storage->ReadBool(L"TrimVMSVersions", TrimVMSVersions);
  787. VMSAllRevisions = Storage->ReadBool(L"VMSAllRevisions", VMSAllRevisions);
  788. NotUtf = Storage->ReadEnum(L"Utf", Storage->ReadEnum(L"SFTPUtfBug", NotUtf), AutoSwitchReversedMapping);
  789. InternalEditorEncoding = Storage->ReadInteger(L"InternalEditorEncoding", InternalEditorEncoding);
  790. S3DefaultRegion = Storage->ReadString(L"S3DefaultRegion", S3DefaultRegion);
  791. S3SessionToken = Storage->ReadString(L"S3SessionToken", S3SessionToken);
  792. S3RoleArn = Storage->ReadString(L"S3RoleArn", S3RoleArn);
  793. S3RoleSessionName = Storage->ReadString(L"S3RoleSessionName", S3RoleSessionName);
  794. S3Profile = Storage->ReadString(L"S3Profile", S3Profile);
  795. S3UrlStyle = (TS3UrlStyle)Storage->ReadInteger(L"S3UrlStyle", S3UrlStyle);
  796. S3MaxKeys = Storage->ReadEnum(L"S3MaxKeys", S3MaxKeys, AutoSwitchMapping);
  797. S3CredentialsEnv = Storage->ReadBool(L"S3CredentialsEnv", S3CredentialsEnv);
  798. S3RequesterPays = Storage->ReadBool(L"S3RequesterPays", S3RequesterPays);
  799. // PuTTY defaults to TcpNoDelay, but the psftp/pscp ignores this preference, and always set this to off (what is our default too)
  800. if (!PuttyImport)
  801. {
  802. TcpNoDelay = Storage->ReadBool(L"TcpNoDelay", TcpNoDelay);
  803. }
  804. SendBuf = Storage->ReadInteger(L"SendBuf", Storage->ReadInteger("SshSendBuf", SendBuf));
  805. SourceAddress = Storage->ReadString(L"SourceAddress", SourceAddress);
  806. ProtocolFeatures = Storage->ReadString(L"ProtocolFeatures", ProtocolFeatures);
  807. SshSimple = Storage->ReadBool(L"SshSimple", SshSimple);
  808. ProxyMethod = Storage->ReadEnum(L"ProxyMethod", ProxyMethod, ProxyMethodMapping);
  809. ProxyHost = Storage->ReadString(L"ProxyHost", ProxyHost);
  810. ProxyPort = Storage->ReadInteger(L"ProxyPort", ProxyPort);
  811. ProxyUsername = Storage->ReadString(L"ProxyUsername", ProxyUsername);
  812. // proxy password is not rewritten
  813. LOAD_PASSWORD_EX(ProxyPassword, L"ProxyPassword", L"ProxyPasswordEnc", );
  814. if (!Unsafe)
  815. {
  816. if (ProxyMethod == pmCmd)
  817. {
  818. ProxyLocalCommand = Storage->ReadStringRaw(L"ProxyTelnetCommand", ProxyLocalCommand);
  819. }
  820. else
  821. {
  822. ProxyTelnetCommand = Storage->ReadStringRaw(L"ProxyTelnetCommand", ProxyTelnetCommand);
  823. }
  824. }
  825. ProxyDNS = TAutoSwitch((Storage->ReadInteger(L"ProxyDNS", (ProxyDNS + 2) % 3) + 1) % 3);
  826. ProxyLocalhost = Storage->ReadBool(L"ProxyLocalhost", ProxyLocalhost);
  827. #define READ_BUG(BUG) \
  828. Bug[sb##BUG] = TAutoSwitch(2 - Storage->ReadInteger(L"Bug"#BUG, \
  829. 2 - Bug[sb##BUG]));
  830. READ_BUG(HMAC2);
  831. READ_BUG(DeriveKey2);
  832. READ_BUG(RSAPad2);
  833. READ_BUG(PKSessID2);
  834. READ_BUG(Rekey2);
  835. READ_BUG(MaxPkt2);
  836. READ_BUG(Ignore2);
  837. READ_BUG(OldGex2);
  838. READ_BUG(WinAdj);
  839. READ_BUG(ChanReq);
  840. #undef READ_BUG
  841. if ((Bug[sbHMAC2] == asAuto) &&
  842. Storage->ReadBool(L"BuggyMAC", false))
  843. {
  844. Bug[sbHMAC2] = asOn;
  845. }
  846. if (!Unsafe)
  847. {
  848. SftpServer = Storage->ReadString(L"SftpServer", SftpServer);
  849. }
  850. #define READ_SFTP_BUG(BUG) \
  851. SFTPBug[sb##BUG] = Storage->ReadEnum(L"SFTP" #BUG "Bug", SFTPBug[sb##BUG], AutoSwitchMapping);
  852. READ_SFTP_BUG(Symlink);
  853. READ_SFTP_BUG(SignedTS);
  854. #undef READ_SFTP_BUG
  855. SFTPMaxVersion = Storage->ReadInteger(L"SFTPMaxVersion", SFTPMaxVersion);
  856. SFTPMaxPacketSize = Storage->ReadInteger(L"SFTPMaxPacketSize", SFTPMaxPacketSize);
  857. SFTPDownloadQueue = Storage->ReadInteger(L"SFTPDownloadQueue", SFTPDownloadQueue);
  858. SFTPUploadQueue = Storage->ReadInteger(L"SFTPUploadQueue", SFTPUploadQueue);
  859. SFTPListingQueue = Storage->ReadInteger(L"SFTPListingQueue", SFTPListingQueue);
  860. SFTPRealPath = Storage->ReadEnum(L"SFTPRealPath", SFTPRealPath, AutoSwitchMapping);
  861. UsePosixRename = Storage->ReadBool(L"UsePosixRename", UsePosixRename);
  862. Color = Storage->ReadInteger(L"Color", Color);
  863. PuttyProtocol = Storage->ReadString(L"Protocol", PuttyProtocol);
  864. Tunnel = Storage->ReadBool(L"Tunnel", Tunnel);
  865. TunnelPortNumber = Storage->ReadInteger(L"TunnelPortNumber", TunnelPortNumber);
  866. TunnelUserName = Storage->ReadString(L"TunnelUserName", TunnelUserName);
  867. // must be loaded after TunnelUserName,
  868. // because TunnelHostName may be in format user@host
  869. TunnelHostName = Storage->ReadString(L"TunnelHostName", TunnelHostName);
  870. if (LoadPasswords)
  871. {
  872. LOAD_PASSWORD(TunnelPassword, L"TunnelPasswordPlain");
  873. }
  874. TunnelPublicKeyFile = Storage->ReadString(L"TunnelPublicKeyFile", TunnelPublicKeyFile);
  875. // Contrary to main session passphrase (which has -passphrase switch in scripting),
  876. // we are loading tunnel passphrase, as there's no other way to provide it in scripting
  877. if (LoadPasswords)
  878. {
  879. LOAD_PASSWORD(TunnelPassphrase, L"TunnelPassphrasePlain");
  880. }
  881. TunnelLocalPortNumber = Storage->ReadInteger(L"TunnelLocalPortNumber", TunnelLocalPortNumber);
  882. TunnelHostKey = Storage->ReadString(L"TunnelHostKey", TunnelHostKey);
  883. // Ftp prefix
  884. FtpPasvMode = Storage->ReadBool(L"FtpPasvMode", FtpPasvMode);
  885. FtpForcePasvIp = Storage->ReadEnum(L"FtpForcePasvIp2", FtpForcePasvIp, AutoSwitchMapping);
  886. FtpUseMlsd = Storage->ReadEnum(L"FtpUseMlsd", FtpUseMlsd, AutoSwitchMapping);
  887. FtpAccount = Storage->ReadString(L"FtpAccount", FtpAccount);
  888. FtpPingInterval = Storage->ReadInteger(L"FtpPingInterval", FtpPingInterval);
  889. FtpPingType = static_cast<TFtpPingType>(Storage->ReadInteger(L"FtpPingType", FtpPingType));
  890. FtpTransferActiveImmediately = Storage->ReadEnum(L"FtpTransferActiveImmediately2", FtpTransferActiveImmediately, AutoSwitchMapping);
  891. Ftps = static_cast<TFtps>(Storage->ReadInteger(L"Ftps", Ftps));
  892. FtpListAll = Storage->ReadEnum(L"FtpListAll", FtpListAll, AutoSwitchMapping);
  893. FtpHost = Storage->ReadEnum(L"FtpHost", FtpHost, AutoSwitchMapping);
  894. FtpWorkFromCwd = Storage->ReadEnum(L"FtpWorkFromCwd", Storage->ReadEnum(L"FtpDeleteFromCwd", FtpWorkFromCwd), AutoSwitchMapping);
  895. FtpAnyCodeForPwd = Storage->ReadBool(L"FtpAnyCodeForPwd", FtpAnyCodeForPwd);
  896. SslSessionReuse = Storage->ReadBool(L"SslSessionReuse", SslSessionReuse);
  897. TlsCertificateFile = Storage->ReadString(L"TlsCertificateFile", TlsCertificateFile);
  898. FtpProxyLogonType = Storage->ReadInteger(L"FtpProxyLogonType", FtpProxyLogonType);
  899. MinTlsVersion = static_cast<TTlsVersion>(Storage->ReadInteger(L"MinTlsVersion", MinTlsVersion));
  900. MaxTlsVersion = static_cast<TTlsVersion>(Storage->ReadInteger(L"MaxTlsVersion", MaxTlsVersion));
  901. CompleteTlsShutdown = Storage->ReadEnum(L"CompleteTlsShutdown", CompleteTlsShutdown, AutoSwitchMapping);
  902. LOAD_PASSWORD(EncryptKey, L"EncryptKeyPlain");
  903. WebDavLiberalEscaping = Storage->ReadBool(L"WebDavLiberalEscaping", WebDavLiberalEscaping);
  904. WebDavAuthLegacy = Storage->ReadBool(L"WebDavAuthLegacy", WebDavAuthLegacy);
  905. IsWorkspace = Storage->ReadBool(L"IsWorkspace", IsWorkspace);
  906. Link = Storage->ReadString(L"Link", Link);
  907. NameOverride = Storage->ReadString(L"NameOverride", NameOverride);
  908. PuttySettings = Storage->ReadString(L"PuttySettings", PuttySettings);
  909. CustomParam1 = Storage->ReadString(L"CustomParam1", CustomParam1);
  910. CustomParam2 = Storage->ReadString(L"CustomParam2", CustomParam2);
  911. #undef LOAD_PASSWORD
  912. }
  913. //---------------------------------------------------------------------
  914. void __fastcall TSessionData::Load(THierarchicalStorage * Storage, bool PuttyImport)
  915. {
  916. bool RewritePassword = false;
  917. if (Storage->OpenSubKey(InternalStorageKey, False))
  918. {
  919. // In case we are re-loading, reset passwords, to avoid pointless
  920. // re-cryption, while loading username/hostname. And moreover, when
  921. // the password is wrongly encrypted (using a different master password),
  922. // this breaks sites reload and consequently an overall operation,
  923. // such as opening Sites menu
  924. ClearSessionPasswords();
  925. FProxyPassword = L"";
  926. DoLoad(Storage, PuttyImport, RewritePassword, false, true);
  927. Storage->CloseSubKey();
  928. }
  929. if (RewritePassword)
  930. {
  931. TStorageAccessMode AccessMode = Storage->AccessMode;
  932. Storage->AccessMode = smReadWrite;
  933. try
  934. {
  935. if (Storage->OpenSubKey(InternalStorageKey, true))
  936. {
  937. #define REWRITE_PASSWORD(PROP, PLAIN_NAME) \
  938. Storage->DeleteValue(PLAIN_NAME); \
  939. if (!PROP.IsEmpty()) \
  940. { \
  941. Storage->WriteBinaryDataAsString(TEXT(#PROP), F##PROP); \
  942. }
  943. REWRITE_PASSWORD(Password, L"PasswordPlain");
  944. REWRITE_PASSWORD(TunnelPassword, L"TunnelPasswordPlain");
  945. REWRITE_PASSWORD(EncryptKey, L"EncryptKeyPlain");
  946. REWRITE_PASSWORD(TunnelPassphrase, L"TunnelPassphrasePlain");
  947. #undef REWRITE_PASSWORD
  948. Storage->CloseSubKey();
  949. }
  950. }
  951. catch(...)
  952. {
  953. // ignore errors (like read-only INI file)
  954. }
  955. Storage->AccessMode = AccessMode;
  956. }
  957. FModified = false;
  958. FSource = ssStored;
  959. }
  960. //---------------------------------------------------------------------
  961. void __fastcall TSessionData::DoSave(THierarchicalStorage * Storage,
  962. bool PuttyExport, const TSessionData * Default, bool DoNotEncryptPasswords)
  963. {
  964. // Same as in TCopyParamType::Save
  965. #define WRITE_DATA_EX(TYPE, NAME, PROPERTY, CONV) \
  966. if ((Default != NULL) && (CONV(Default->PROPERTY) == CONV(PROPERTY))) \
  967. { \
  968. Storage->DeleteValue(NAME); \
  969. } \
  970. else \
  971. { \
  972. Storage->Write ## TYPE(NAME, CONV(PROPERTY)); \
  973. }
  974. #define WRITE_DATA_CONV(TYPE, NAME, PROPERTY) WRITE_DATA_EX(TYPE, NAME, PROPERTY, WRITE_DATA_CONV_FUNC)
  975. #define WRITE_DATA(TYPE, PROPERTY) WRITE_DATA_EX(TYPE, TEXT(#PROPERTY), PROPERTY, )
  976. WRITE_DATA(String, HostName);
  977. WRITE_DATA(Integer, PortNumber);
  978. if ((PingType == ptOff) && PuttyExport)
  979. {
  980. // Deleting would do too
  981. Storage->WriteInteger(L"PingInterval", 0);
  982. Storage->WriteInteger(L"PingIntervalSecs", 0);
  983. }
  984. else
  985. {
  986. WRITE_DATA_EX(Integer, L"PingInterval", PingInterval / SecsPerMin, );
  987. WRITE_DATA_EX(Integer, L"PingIntervalSecs", PingInterval % SecsPerMin, );
  988. }
  989. Storage->DeleteValue(L"PingIntervalSec"); // obsolete
  990. WRITE_DATA(Integer, PingType);
  991. WRITE_DATA(Integer, Timeout);
  992. WRITE_DATA(Bool, TryAgent);
  993. WRITE_DATA(Bool, AgentFwd);
  994. WRITE_DATA(Bool, AuthKI);
  995. WRITE_DATA(Bool, AuthKIPassword);
  996. WRITE_DATA_EX(String, L"SshHostKey", HostKey, );
  997. WRITE_DATA(String, Note);
  998. WRITE_DATA(Bool, AuthGSSAPI);
  999. WRITE_DATA(Bool, AuthGSSAPIKEX);
  1000. WRITE_DATA(Bool, GSSAPIFwdTGT);
  1001. Storage->DeleteValue(L"TryGSSKEX");
  1002. Storage->DeleteValue(L"UserNameFromEnvironment");
  1003. Storage->DeleteValue("GSSAPIServerChoosesUserName");
  1004. Storage->DeleteValue(L"GSSAPITrustDNS");
  1005. WRITE_DATA(String, LogicalHostName);
  1006. if (PuttyExport)
  1007. {
  1008. // duplicate kerberos setting with keys of the vintela quest putty
  1009. WRITE_DATA_EX(Bool, L"AuthSSPI", AuthGSSAPI, );
  1010. WRITE_DATA_EX(Bool, L"SSPIFwdTGT", GSSAPIFwdTGT, );
  1011. WRITE_DATA_EX(String, L"KerbPrincipal", LogicalHostName, );
  1012. // duplicate kerberos setting with keys of the official putty
  1013. WRITE_DATA_EX(Bool, L"GssapiFwd", GSSAPIFwdTGT, );
  1014. }
  1015. WRITE_DATA(Bool, ChangeUsername);
  1016. WRITE_DATA(Bool, Compression);
  1017. WRITE_DATA(Bool, Ssh2DES);
  1018. WRITE_DATA(Bool, SshNoUserAuth);
  1019. WRITE_DATA_EX(String, L"Cipher", CipherList, );
  1020. WRITE_DATA_EX(String, L"KEX", KexList, );
  1021. WRITE_DATA_EX(String, L"HostKey", HostKeyList, );
  1022. WRITE_DATA_EX(String, L"GSSLibs", GssLibList, );
  1023. WRITE_DATA_EX(String, L"GSSCustom", GssLibCustom, );
  1024. WRITE_DATA(Integer, AddressFamily);
  1025. WRITE_DATA_EX(String, L"RekeyBytes", RekeyData, );
  1026. WRITE_DATA(Integer, RekeyTime);
  1027. WRITE_DATA(Bool, TcpNoDelay);
  1028. if (PuttyExport)
  1029. {
  1030. WRITE_DATA(StringRaw, UserName);
  1031. // PuTTY is started in its binary directory to allow relative paths when opening PuTTY's own stored session.
  1032. // To allow relative paths in our sessions, we have to expand them for PuTTY.
  1033. WRITE_DATA_EX(StringRaw, L"PublicKeyFile", PublicKeyFile, ExpandFileName);
  1034. WRITE_DATA_EX(StringRaw, L"DetachedCertificate", DetachedCertificate, ExpandFileName);
  1035. }
  1036. else
  1037. {
  1038. WRITE_DATA(String, UserName);
  1039. WRITE_DATA(String, PublicKeyFile);
  1040. WRITE_DATA(String, DetachedCertificate);
  1041. WRITE_DATA(Integer, FSProtocol);
  1042. WRITE_DATA(String, LocalDirectory);
  1043. WRITE_DATA(String, OtherLocalDirectory);
  1044. WRITE_DATA(String, RemoteDirectory);
  1045. WRITE_DATA(Bool, SynchronizeBrowsing);
  1046. WRITE_DATA(Bool, UpdateDirectories);
  1047. WRITE_DATA(Bool, CacheDirectories);
  1048. WRITE_DATA(Bool, CacheDirectoryChanges);
  1049. WRITE_DATA(Bool, PreserveDirectoryChanges);
  1050. WRITE_DATA(Bool, ResolveSymlinks);
  1051. WRITE_DATA(Bool, FollowDirectorySymlinks);
  1052. WRITE_DATA_EX(Integer, L"ConsiderDST", DSTMode, );
  1053. // Special is never stored (if it would, login dialog must be modified not to
  1054. // duplicate Special parameter when Special session is loaded and then stored
  1055. // under different name)
  1056. // WRITE_DATA(Bool, Special);
  1057. WRITE_DATA(String, Shell);
  1058. WRITE_DATA(Bool, ClearAliases);
  1059. WRITE_DATA(Bool, UnsetNationalVars);
  1060. WRITE_DATA(String, ListingCommand);
  1061. WRITE_DATA(Bool, IgnoreLsWarnings);
  1062. WRITE_DATA(Integer, SCPLsFullTime);
  1063. WRITE_DATA(Bool, Scp1Compatibility);
  1064. // TimeDifferenceAuto is valid for FTP protocol only.
  1065. // For other protocols it's typically true (default value),
  1066. // but ignored so TimeDifference is still taken into account (SCP only actually)
  1067. if (TimeDifferenceAuto && (FSProtocol == fsFTP))
  1068. {
  1069. // Have to delete it as TimeDifferenceAuto is not saved when enabled,
  1070. // but the default is derived from value of TimeDifference.
  1071. Storage->DeleteValue(L"TimeDifference");
  1072. }
  1073. else
  1074. {
  1075. WRITE_DATA(Float, TimeDifference);
  1076. }
  1077. WRITE_DATA(Bool, TimeDifferenceAuto);
  1078. WRITE_DATA(Bool, DeleteToRecycleBin);
  1079. WRITE_DATA(Bool, OverwrittenToRecycleBin);
  1080. WRITE_DATA(String, RecycleBinPath);
  1081. WRITE_DATA(String, PostLoginCommands);
  1082. WRITE_DATA(String, ReturnVar);
  1083. WRITE_DATA(Bool, ExitCode1IsError);
  1084. WRITE_DATA_EX(Integer, L"LookupUserGroups2", LookupUserGroups, );
  1085. WRITE_DATA(Integer, EOLType);
  1086. WRITE_DATA(Bool, TrimVMSVersions);
  1087. WRITE_DATA(Bool, VMSAllRevisions);
  1088. Storage->DeleteValue(L"SFTPUtfBug");
  1089. WRITE_DATA_EX(Integer, L"Utf", NotUtf, );
  1090. WRITE_DATA(Integer, InternalEditorEncoding);
  1091. WRITE_DATA(String, S3DefaultRegion);
  1092. WRITE_DATA(String, S3SessionToken);
  1093. WRITE_DATA(String, S3RoleArn);
  1094. WRITE_DATA(String, S3RoleSessionName);
  1095. WRITE_DATA(String, S3Profile);
  1096. WRITE_DATA(Integer, S3UrlStyle);
  1097. WRITE_DATA(Integer, S3MaxKeys);
  1098. WRITE_DATA(Bool, S3CredentialsEnv);
  1099. WRITE_DATA(Bool, S3RequesterPays);
  1100. WRITE_DATA(Integer, SendBuf);
  1101. WRITE_DATA(String, SourceAddress);
  1102. WRITE_DATA(String, ProtocolFeatures);
  1103. WRITE_DATA(Bool, SshSimple);
  1104. }
  1105. WRITE_DATA(Integer, ProxyMethod);
  1106. WRITE_DATA(String, ProxyHost);
  1107. WRITE_DATA(Integer, ProxyPort);
  1108. WRITE_DATA(String, ProxyUsername);
  1109. if (ProxyMethod == pmCmd)
  1110. {
  1111. WRITE_DATA_EX(StringRaw, L"ProxyTelnetCommand", ProxyLocalCommand, );
  1112. }
  1113. else
  1114. {
  1115. WRITE_DATA(StringRaw, ProxyTelnetCommand);
  1116. }
  1117. #define WRITE_DATA_CONV_FUNC(X) (((X) + 2) % 3)
  1118. WRITE_DATA_CONV(Integer, L"ProxyDNS", ProxyDNS);
  1119. #undef WRITE_DATA_CONV_FUNC
  1120. WRITE_DATA(Bool, ProxyLocalhost);
  1121. #define WRITE_DATA_CONV_FUNC(X) (2 - (X))
  1122. #define WRITE_BUG(BUG) WRITE_DATA_CONV(Integer, L"Bug" #BUG, Bug[sb##BUG]);
  1123. WRITE_BUG(HMAC2);
  1124. WRITE_BUG(DeriveKey2);
  1125. WRITE_BUG(RSAPad2);
  1126. WRITE_BUG(PKSessID2);
  1127. WRITE_BUG(Rekey2);
  1128. WRITE_BUG(MaxPkt2);
  1129. WRITE_BUG(Ignore2);
  1130. WRITE_BUG(OldGex2);
  1131. WRITE_BUG(WinAdj);
  1132. WRITE_BUG(ChanReq);
  1133. #undef WRITE_BUG
  1134. #undef WRITE_DATA_CONV_FUNC
  1135. Storage->DeleteValue(L"BuggyMAC");
  1136. Storage->DeleteValue(L"AliasGroupList");
  1137. if (PuttyExport)
  1138. {
  1139. WRITE_DATA_EX(String, L"Protocol", GetNormalizedPuttyProtocol(), );
  1140. WRITE_DATA(String, WinTitle);
  1141. }
  1142. if (!PuttyExport)
  1143. {
  1144. WRITE_DATA(String, SftpServer);
  1145. #define WRITE_SFTP_BUG(BUG) WRITE_DATA_EX(Integer, L"SFTP" #BUG "Bug", SFTPBug[sb##BUG], );
  1146. WRITE_SFTP_BUG(Symlink);
  1147. WRITE_SFTP_BUG(SignedTS);
  1148. #undef WRITE_SFTP_BUG
  1149. WRITE_DATA(Integer, SFTPMaxVersion);
  1150. WRITE_DATA(Integer, SFTPMaxPacketSize);
  1151. WRITE_DATA(Integer, SFTPDownloadQueue);
  1152. WRITE_DATA(Integer, SFTPUploadQueue);
  1153. WRITE_DATA(Integer, SFTPListingQueue);
  1154. WRITE_DATA(Integer, SFTPRealPath);
  1155. WRITE_DATA(Bool, UsePosixRename);
  1156. WRITE_DATA(Integer, Color);
  1157. WRITE_DATA(Bool, Tunnel);
  1158. WRITE_DATA(String, TunnelHostName);
  1159. WRITE_DATA(Integer, TunnelPortNumber);
  1160. WRITE_DATA(String, TunnelUserName);
  1161. WRITE_DATA(String, TunnelPublicKeyFile);
  1162. WRITE_DATA(Integer, TunnelLocalPortNumber);
  1163. WRITE_DATA(String, TunnelHostKey);
  1164. WRITE_DATA(Bool, FtpPasvMode);
  1165. WRITE_DATA_EX(Integer, L"FtpForcePasvIp2", FtpForcePasvIp, );
  1166. WRITE_DATA(Integer, FtpUseMlsd);
  1167. WRITE_DATA(String, FtpAccount);
  1168. WRITE_DATA(Integer, FtpPingInterval);
  1169. WRITE_DATA(Integer, FtpPingType);
  1170. WRITE_DATA_EX(Integer, L"FtpTransferActiveImmediately2", FtpTransferActiveImmediately, );
  1171. WRITE_DATA(Integer, Ftps);
  1172. WRITE_DATA(Integer, FtpListAll);
  1173. WRITE_DATA(Integer, FtpHost);
  1174. WRITE_DATA(Integer, FtpWorkFromCwd);
  1175. WRITE_DATA(Bool, FtpAnyCodeForPwd);
  1176. WRITE_DATA(Bool, SslSessionReuse);
  1177. WRITE_DATA(String, TlsCertificateFile);
  1178. WRITE_DATA(Integer, FtpProxyLogonType);
  1179. WRITE_DATA(Integer, MinTlsVersion);
  1180. WRITE_DATA(Integer, MaxTlsVersion);
  1181. WRITE_DATA(Integer, CompleteTlsShutdown);
  1182. WRITE_DATA(Bool, WebDavLiberalEscaping);
  1183. WRITE_DATA(Bool, WebDavAuthLegacy);
  1184. WRITE_DATA(Bool, IsWorkspace);
  1185. WRITE_DATA(String, Link);
  1186. WRITE_DATA(String, NameOverride);
  1187. WRITE_DATA(String, PuttySettings);
  1188. WRITE_DATA(String, CustomParam1);
  1189. WRITE_DATA(String, CustomParam2);
  1190. }
  1191. // This is for collecting all keys for TSiteRawDialog::AddButtonClick.
  1192. // It should be enough to test for (Default == NULL),
  1193. // the DoNotEncryptPasswords and PuttyExport were added to limit a possible unintended impact.
  1194. bool SaveAll = (Default == NULL) && DoNotEncryptPasswords && !PuttyExport;
  1195. SavePasswords(Storage, PuttyExport, DoNotEncryptPasswords, SaveAll);
  1196. if (PuttyExport)
  1197. {
  1198. WritePuttySettings(Storage, PuttySettings);
  1199. }
  1200. }
  1201. //---------------------------------------------------------------------
  1202. TStrings * __fastcall TSessionData::SaveToOptions(const TSessionData * Default, bool SaveName, bool PuttyExport)
  1203. {
  1204. std::unique_ptr<TStringList> Options(new TStringList());
  1205. std::unique_ptr<TOptionsStorage> OptionsStorage(new TOptionsStorage(Options.get(), true));
  1206. if (SaveName)
  1207. {
  1208. OptionsStorage->WriteString(L"Name", Name);
  1209. }
  1210. DoSave(OptionsStorage.get(), PuttyExport, Default, true);
  1211. return Options.release();
  1212. }
  1213. //---------------------------------------------------------------------
  1214. void __fastcall TSessionData::Save(THierarchicalStorage * Storage,
  1215. bool PuttyExport, const TSessionData * Default)
  1216. {
  1217. if (Storage->OpenSubKey(InternalStorageKey, true))
  1218. {
  1219. DoSave(Storage, PuttyExport, Default, false);
  1220. Storage->CloseSubKey();
  1221. }
  1222. }
  1223. //---------------------------------------------------------------------
  1224. UnicodeString __fastcall TSessionData::ReadXmlNode(_di_IXMLNode Node, const UnicodeString & Name, const UnicodeString & Default)
  1225. {
  1226. _di_IXMLNode TheNode = Node->ChildNodes->FindNode(Name);
  1227. UnicodeString Result;
  1228. if (TheNode != NULL)
  1229. {
  1230. Result = TheNode->Text.Trim();
  1231. }
  1232. if (Result.IsEmpty())
  1233. {
  1234. Result = Default;
  1235. }
  1236. return Result;
  1237. }
  1238. //---------------------------------------------------------------------
  1239. int __fastcall TSessionData::ReadXmlNode(_di_IXMLNode Node, const UnicodeString & Name, int Default)
  1240. {
  1241. _di_IXMLNode TheNode = Node->ChildNodes->FindNode(Name);
  1242. int Result;
  1243. if (TheNode != NULL)
  1244. {
  1245. Result = StrToIntDef(TheNode->Text.Trim(), Default);
  1246. }
  1247. else
  1248. {
  1249. Result = Default;
  1250. }
  1251. return Result;
  1252. }
  1253. //---------------------------------------------------------------------
  1254. _di_IXMLNode __fastcall TSessionData::FindSettingsNode(_di_IXMLNode Node, const UnicodeString & Name)
  1255. {
  1256. for (int Index = 0; Index < Node->ChildNodes->Count; Index++)
  1257. {
  1258. _di_IXMLNode ChildNode = Node->ChildNodes->Get(Index);
  1259. if (ChildNode->NodeName == L"Setting")
  1260. {
  1261. OleVariant SettingName = ChildNode->GetAttribute(L"name");
  1262. if (SettingName == Name)
  1263. {
  1264. return ChildNode;
  1265. }
  1266. }
  1267. }
  1268. return NULL;
  1269. }
  1270. //---------------------------------------------------------------------
  1271. UnicodeString __fastcall TSessionData::ReadSettingsNode(_di_IXMLNode Node, const UnicodeString & Name, const UnicodeString & Default)
  1272. {
  1273. _di_IXMLNode TheNode = FindSettingsNode(Node, Name);
  1274. UnicodeString Result;
  1275. if (TheNode != NULL)
  1276. {
  1277. Result = TheNode->Text.Trim();
  1278. }
  1279. if (Result.IsEmpty())
  1280. {
  1281. Result = Default;
  1282. }
  1283. return Result;
  1284. }
  1285. //---------------------------------------------------------------------
  1286. int __fastcall TSessionData::ReadSettingsNode(_di_IXMLNode Node, const UnicodeString & Name, int Default)
  1287. {
  1288. _di_IXMLNode TheNode = FindSettingsNode(Node, Name);
  1289. int Result;
  1290. if (TheNode != NULL)
  1291. {
  1292. Result = StrToIntDef(TheNode->Text.Trim(), Default);
  1293. }
  1294. else
  1295. {
  1296. Result = Default;
  1297. }
  1298. return Result;
  1299. }
  1300. //---------------------------------------------------------------------
  1301. void __fastcall TSessionData::ImportFromFilezilla(
  1302. _di_IXMLNode Node, const UnicodeString & Path, _di_IXMLNode SettingsNode)
  1303. {
  1304. Name = UnixIncludeTrailingBackslash(Path) + MakeValidName(ReadXmlNode(Node, L"Name", Name));
  1305. HostName = ReadXmlNode(Node, L"Host", HostName);
  1306. PortNumber = ReadXmlNode(Node, L"Port", PortNumber);
  1307. int AProtocol = ReadXmlNode(Node, L"Protocol", 0);
  1308. // ServerProtocol enum
  1309. switch (AProtocol)
  1310. {
  1311. case 0: // FTP
  1312. default: // UNKNOWN, HTTP, HTTPS, INSECURE_FTP
  1313. FSProtocol = fsFTP;
  1314. break;
  1315. case 1: // SFTP
  1316. FSProtocol = fsSFTP;
  1317. break;
  1318. case 3: // FTPS
  1319. FSProtocol = fsFTP;
  1320. Ftps = ftpsImplicit;
  1321. break;
  1322. case 4: // FTPES
  1323. FSProtocol = fsFTP;
  1324. Ftps = ftpsExplicitTls;
  1325. break;
  1326. }
  1327. // LogonType enum
  1328. int LogonType = ReadXmlNode(Node, L"Logontype", 0);
  1329. if (LogonType == 0) // ANONYMOUS
  1330. {
  1331. UserName = AnonymousUserName;
  1332. Password = AnonymousPassword;
  1333. }
  1334. else
  1335. {
  1336. UserName = ReadXmlNode(Node, L"User", UserName);
  1337. FtpAccount = ReadXmlNode(Node, L"Account", FtpAccount);
  1338. _di_IXMLNode PassNode = Node->ChildNodes->FindNode(L"Pass");
  1339. if (PassNode != NULL)
  1340. {
  1341. UnicodeString APassword = PassNode->Text.Trim();
  1342. OleVariant EncodingValue = PassNode->GetAttribute(L"encoding");
  1343. if (!EncodingValue.IsNull())
  1344. {
  1345. UnicodeString EncodingValueStr = EncodingValue;
  1346. if (SameText(EncodingValueStr, L"base64"))
  1347. {
  1348. TBytes Bytes = DecodeBase64(APassword);
  1349. APassword = TEncoding::UTF8->GetString(Bytes);
  1350. }
  1351. }
  1352. Password = APassword;
  1353. }
  1354. }
  1355. PublicKeyFile = ReadXmlNode(Node, L"Keyfile", PublicKeyFile);
  1356. int DefaultTimeDifference = TimeToSeconds(TimeDifference);
  1357. TimeDifference =
  1358. (double(ReadXmlNode(Node, L"TimezoneOffset", DefaultTimeDifference) / SecsPerDay));
  1359. TimeDifferenceAuto = (TimeDifference == TDateTime());
  1360. UnicodeString PasvMode = ReadXmlNode(Node, L"PasvMode", L"");
  1361. if (SameText(PasvMode, L"MODE_PASSIVE"))
  1362. {
  1363. FtpPasvMode = true;
  1364. }
  1365. else if (SameText(PasvMode, L"MODE_ACTIVE"))
  1366. {
  1367. FtpPasvMode = false;
  1368. }
  1369. else if (SettingsNode != NULL)
  1370. {
  1371. int PasvMode = ReadSettingsNode(SettingsNode, L"Use Pasv mode", 1);
  1372. FtpPasvMode = (PasvMode != 0);
  1373. }
  1374. UnicodeString EncodingType = ReadXmlNode(Node, L"EncodingType", L"");
  1375. if (SameText(EncodingType, L"Auto"))
  1376. {
  1377. NotUtf = asAuto;
  1378. }
  1379. else if (SameText(EncodingType, L"UTF-8"))
  1380. {
  1381. NotUtf = asOff;
  1382. }
  1383. // todo PostLoginCommands
  1384. Note = ReadXmlNode(Node, L"Comments", Note);
  1385. LocalDirectory = ReadXmlNode(Node, L"LocalDir", LocalDirectory);
  1386. UnicodeString RemoteDir = ReadXmlNode(Node, L"RemoteDir", L"");
  1387. if (!RemoteDir.IsEmpty())
  1388. {
  1389. CutToChar(RemoteDir, L' ', false); // type
  1390. int PrefixSize = StrToIntDef(CutToChar(RemoteDir, L' ', false), 0); // prefix size
  1391. if (PrefixSize > 0)
  1392. {
  1393. RemoteDir.Delete(1, PrefixSize);
  1394. }
  1395. RemoteDirectory = L"/";
  1396. while (!RemoteDir.IsEmpty())
  1397. {
  1398. int SegmentSize = StrToIntDef(CutToChar(RemoteDir, L' ', false), 0);
  1399. UnicodeString Segment = RemoteDir.SubString(1, SegmentSize);
  1400. RemoteDirectory = UnixIncludeTrailingBackslash(RemoteDirectory) + Segment;
  1401. RemoteDir.Delete(1, SegmentSize + 1);
  1402. }
  1403. }
  1404. SynchronizeBrowsing = (ReadXmlNode(Node, L"SyncBrowsing", SynchronizeBrowsing ? 1 : 0) != 0);
  1405. if (SettingsNode != NULL)
  1406. {
  1407. if (UsesSsh && PublicKeyFile.IsEmpty())
  1408. {
  1409. UnicodeString KeyFiles = ReadSettingsNode(SettingsNode, L"SFTP keyfiles", UnicodeString());
  1410. UnicodeString KeyFile = CutToChar(KeyFiles, L'\n', true).Trim();
  1411. KeyFiles = KeyFiles.Trim();
  1412. // If there are more keys, ignore them, as we do not know which one to use
  1413. if (!KeyFile.IsEmpty() && KeyFiles.IsEmpty())
  1414. {
  1415. PublicKeyFile = KeyFile;
  1416. }
  1417. }
  1418. bool BypassProxy = (ReadXmlNode(Node, L"BypassProxy", 0) != 0);
  1419. if (!BypassProxy)
  1420. {
  1421. int FtpProxyType = ReadSettingsNode(SettingsNode, L"FTP Proxy type", -1);
  1422. if (FtpProxyType > 0)
  1423. {
  1424. switch (FtpProxyType)
  1425. {
  1426. case 1:
  1427. FtpProxyLogonType = 2;
  1428. break;
  1429. case 2:
  1430. FtpProxyLogonType = 1;
  1431. break;
  1432. case 3:
  1433. FtpProxyLogonType = 3;
  1434. break;
  1435. case 4:
  1436. // custom
  1437. // TODO: map known sequences to our enumeration
  1438. FtpProxyLogonType = 0;
  1439. break;
  1440. default:
  1441. DebugFail();
  1442. FtpProxyLogonType = 0;
  1443. break;
  1444. }
  1445. ProxyHost = ReadSettingsNode(SettingsNode, L"FTP Proxy host", ProxyHost);
  1446. ProxyUsername = ReadSettingsNode(SettingsNode, L"FTP Proxy user", ProxyUsername);
  1447. ProxyPassword = ReadSettingsNode(SettingsNode, L"FTP Proxy password", ProxyPassword);
  1448. // ProxyPort is not used with FtpProxyLogonType
  1449. }
  1450. else
  1451. {
  1452. int ProxyType = ReadSettingsNode(SettingsNode, L"Proxy type", -1);
  1453. if (ProxyType >= 0)
  1454. {
  1455. switch (ProxyType)
  1456. {
  1457. case 0:
  1458. ProxyMethod = ::pmNone;
  1459. break;
  1460. case 1:
  1461. ProxyMethod = pmHTTP;
  1462. break;
  1463. case 2:
  1464. ProxyMethod = pmSocks5;
  1465. break;
  1466. case 3:
  1467. ProxyMethod = pmSocks4;
  1468. break;
  1469. default:
  1470. DebugFail();
  1471. ProxyMethod = ::pmNone;
  1472. break;
  1473. }
  1474. ProxyHost = ReadSettingsNode(SettingsNode, L"Proxy host", ProxyHost);
  1475. ProxyPort = ReadSettingsNode(SettingsNode, L"Proxy port", ProxyPort);
  1476. ProxyUsername = ReadSettingsNode(SettingsNode, L"Proxy user", ProxyUsername);
  1477. ProxyPassword = ReadSettingsNode(SettingsNode, L"Proxy password", ProxyPassword);
  1478. }
  1479. }
  1480. }
  1481. }
  1482. }
  1483. //---------------------------------------------------------------------
  1484. bool OpensshBoolValue(const UnicodeString & Value)
  1485. {
  1486. return SameText(Value, L"yes");
  1487. }
  1488. //---------------------------------------------------------------------
  1489. UnicodeString CutOpensshToken(UnicodeString & S)
  1490. {
  1491. const wchar_t NoQuote = L'\0';
  1492. wchar_t Quote = NoQuote;
  1493. UnicodeString Result;
  1494. int P = 1;
  1495. while (P <= S.Length())
  1496. {
  1497. wchar_t C = S[P];
  1498. if ((C == L'\\') &&
  1499. (P < S.Length()) &&
  1500. ((S[P + 1] == L'\'') ||
  1501. (S[P + 1] == L'\"') ||
  1502. (S[P + 1] == L'\\') ||
  1503. ((Quote == NoQuote) && S[P + 1] == L' ')))
  1504. {
  1505. Result += S[P + 1];
  1506. P++;
  1507. }
  1508. else if ((Quote == NoQuote) && ((C == L' ') || (C == L'\t')))
  1509. {
  1510. break;
  1511. }
  1512. else if ((Quote == NoQuote) && ((C == L'\'') || (C == L'"')))
  1513. {
  1514. Quote = C;
  1515. }
  1516. else if ((Quote != NoQuote) && (Quote == C))
  1517. {
  1518. Quote = NoQuote;
  1519. }
  1520. else
  1521. {
  1522. Result += C;
  1523. }
  1524. P++;
  1525. }
  1526. S = MidStr(S, P).Trim();
  1527. return Result;
  1528. }
  1529. //---------------------------------------------------------------------
  1530. UnicodeString ConvertPathFromOpenssh(const UnicodeString & Path)
  1531. {
  1532. // It's likely there would be forward slashes in OpenSSH config file and our load/save dialogs
  1533. // (e.g. when converting keys) work suboptimally when working with forward slashes.
  1534. UnicodeString Result = GetNormalizedPath(Path);
  1535. const UnicodeString HomePathPrefix = L"~";
  1536. if (StartsStr(HomePathPrefix, Result))
  1537. {
  1538. Result =
  1539. GetShellFolderPath(CSIDL_PROFILE) +
  1540. Result.SubString(HomePathPrefix.Length() + 1, Result.Length() - HomePathPrefix.Length());
  1541. }
  1542. return Result;
  1543. }
  1544. //---------------------------------------------------------------------
  1545. void TSessionData::ImportFromOpenssh(TStrings * Lines)
  1546. {
  1547. bool SkippingSection = false;
  1548. std::unique_ptr<TStrings> UsedDirectives(CreateSortedStringList());
  1549. for (int Index = 0; Index < Lines->Count; Index++)
  1550. {
  1551. UnicodeString Line = Lines->Strings[Index];
  1552. UnicodeString Directive, Args;
  1553. if (ParseOpensshDirective(Line, Directive, Args))
  1554. {
  1555. if (SameText(Directive, OpensshHostDirective))
  1556. {
  1557. SkippingSection = true;
  1558. while (!Args.IsEmpty())
  1559. {
  1560. UnicodeString M = CutOpensshToken(Args);
  1561. bool Negated = DebugAlwaysTrue(!M.IsEmpty()) && (M[1] == L'!');
  1562. if (Negated)
  1563. {
  1564. M.Delete(1, 1);
  1565. }
  1566. TFileMasks Mask;
  1567. Mask.SetMask(M);
  1568. // This does way more than OpenSSH, but on the other hand, the special characters of our file masks,
  1569. // should not be present in hostnames.
  1570. if (Mask.MatchesFileName(Name))
  1571. {
  1572. if (Negated)
  1573. {
  1574. // Skip even if matched by other positive patterns
  1575. SkippingSection = true;
  1576. break;
  1577. }
  1578. else
  1579. {
  1580. // Keep looking, in case if negated
  1581. SkippingSection = false;
  1582. }
  1583. }
  1584. }
  1585. }
  1586. else if (SameText(Directive, L"Match"))
  1587. {
  1588. SkippingSection = true;
  1589. }
  1590. else if (!SkippingSection && (UsedDirectives->IndexOf(Directive) < 0))
  1591. {
  1592. UnicodeString Value = CutOpensshToken(Args);
  1593. // All the directives we support allow only one token
  1594. if (Args.IsEmpty())
  1595. {
  1596. if (SameText(Directive, L"AddressFamily"))
  1597. {
  1598. if (SameText(Value, L"inet"))
  1599. {
  1600. AddressFamily = afIPv4;
  1601. }
  1602. else if (SameText(Value, L"inet6"))
  1603. {
  1604. AddressFamily = afIPv6;
  1605. }
  1606. else
  1607. {
  1608. AddressFamily = afAuto;
  1609. }
  1610. }
  1611. else if (SameText(Directive, L"BindAddress"))
  1612. {
  1613. SourceAddress = Value;
  1614. }
  1615. else if (SameText(Directive, L"Compression"))
  1616. {
  1617. Compression = OpensshBoolValue(Value);
  1618. }
  1619. else if (SameText(Directive, L"ForwardAgent"))
  1620. {
  1621. AgentFwd = OpensshBoolValue(Value);
  1622. }
  1623. else if (SameText(Directive, L"GSSAPIAuthentication"))
  1624. {
  1625. AuthGSSAPI = OpensshBoolValue(Value);
  1626. }
  1627. else if (SameText(Directive, L"GSSAPIDelegateCredentials"))
  1628. {
  1629. AuthGSSAPIKEX = OpensshBoolValue(Value);
  1630. }
  1631. else if (SameText(Directive, L"Hostname"))
  1632. {
  1633. HostName = Value;
  1634. }
  1635. else if (SameText(Directive, L"IdentityFile"))
  1636. {
  1637. PublicKeyFile = ConvertPathFromOpenssh(Value);
  1638. }
  1639. else if (SameText(Directive, L"CertificateFile"))
  1640. {
  1641. DetachedCertificate = ConvertPathFromOpenssh(Value);
  1642. }
  1643. else if (SameText(Directive, L"KbdInteractiveAuthentication"))
  1644. {
  1645. AuthKI = OpensshBoolValue(Value);
  1646. }
  1647. else if (SameText(Directive, L"Port"))
  1648. {
  1649. PortNumber = StrToInt(Value);
  1650. }
  1651. else if (SameText(Directive, L"User"))
  1652. {
  1653. UserName = Value;
  1654. }
  1655. else if (SameText(Directive, L"ProxyJump"))
  1656. {
  1657. UnicodeString Jump = Value;
  1658. // multiple jumps are not supported
  1659. if (Jump.Pos(L",") == 0)
  1660. {
  1661. std::unique_ptr<TSessionData> JumpData(new TSessionData(EmptyStr));
  1662. bool DefaultsOnly;
  1663. if ((JumpData->ParseUrl(Jump, NULL, NULL, DefaultsOnly, NULL, NULL, NULL, 0)) &&
  1664. !JumpData->HostName.IsEmpty())
  1665. {
  1666. JumpData->Name = JumpData->HostName;
  1667. JumpData->ImportFromOpenssh(Lines);
  1668. Tunnel = true;
  1669. TunnelHostName = JumpData->HostName;
  1670. TunnelPortNumber = JumpData->PortNumber;
  1671. TunnelUserName = JumpData->UserName;
  1672. TunnelPassword = JumpData->Password;
  1673. TunnelPublicKeyFile = JumpData->PublicKeyFile;
  1674. }
  1675. }
  1676. }
  1677. UsedDirectives->Add(Directive);
  1678. }
  1679. }
  1680. }
  1681. }
  1682. }
  1683. //---------------------------------------------------------------------
  1684. void __fastcall TSessionData::SavePasswords(THierarchicalStorage * Storage, bool PuttyExport, bool DoNotEncryptPasswords, bool SaveAll)
  1685. {
  1686. // It's probably safe to replace this with if (!PuttyExport) { SAVE_PASSWORD(...) }
  1687. if (!Configuration->DisablePasswordStoring && !PuttyExport && (!FPassword.IsEmpty() || SaveAll))
  1688. {
  1689. if (DoNotEncryptPasswords)
  1690. {
  1691. Storage->WriteString(L"PasswordPlain", Password);
  1692. Storage->DeleteValue(L"Password");
  1693. }
  1694. else
  1695. {
  1696. Storage->WriteBinaryDataAsString(L"Password", StronglyRecryptPassword(FPassword, UserName+HostName));
  1697. Storage->DeleteValue(L"PasswordPlain");
  1698. }
  1699. }
  1700. else
  1701. {
  1702. Storage->DeleteValue(L"Password");
  1703. Storage->DeleteValue(L"PasswordPlain");
  1704. }
  1705. if (PuttyExport)
  1706. {
  1707. // save password unencrypted
  1708. Storage->WriteString(L"ProxyPassword", ProxyPassword);
  1709. }
  1710. else
  1711. {
  1712. #define SAVE_PASSWORD_EX(PROP, PLAIN_NAME, ENC_NAME, ENC_KEY, COND) \
  1713. if (DoNotEncryptPasswords) \
  1714. { \
  1715. if (!F##PROP.IsEmpty() || SaveAll) \
  1716. { \
  1717. Storage->WriteString(PLAIN_NAME, PROP); \
  1718. } \
  1719. else \
  1720. { \
  1721. Storage->DeleteValue(PLAIN_NAME); \
  1722. } \
  1723. Storage->DeleteValue(ENC_NAME); \
  1724. } \
  1725. else \
  1726. { \
  1727. if (COND && (!F##PROP.IsEmpty() || SaveAll)) \
  1728. { \
  1729. Storage->WriteBinaryDataAsString(ENC_NAME, StronglyRecryptPassword(F##PROP, ENC_KEY)); \
  1730. } \
  1731. else \
  1732. { \
  1733. Storage->DeleteValue(ENC_NAME); \
  1734. } \
  1735. Storage->DeleteValue(PLAIN_NAME); \
  1736. }
  1737. #define SAVE_PASSWORD(PROP, PLAIN_NAME, ENC_KEY) SAVE_PASSWORD_EX(PROP, PLAIN_NAME, TEXT(#PROP), ENC_KEY, !Configuration->DisablePasswordStoring)
  1738. SAVE_PASSWORD_EX(ProxyPassword, L"ProxyPassword", L"ProxyPasswordEnc", ProxyUsername + ProxyHost, true);
  1739. SAVE_PASSWORD(TunnelPassword, L"TunnelPasswordPlain", TunnelUserName + TunnelHostName);
  1740. SAVE_PASSWORD_EX(EncryptKey, L"EncryptKeyPlain", L"EncryptKey", UserName + HostName, true);
  1741. }
  1742. }
  1743. //---------------------------------------------------------------------
  1744. void __fastcall TSessionData::RecryptPasswords()
  1745. {
  1746. Password = Password;
  1747. NewPassword = NewPassword;
  1748. ProxyPassword = ProxyPassword;
  1749. TunnelPassword = TunnelPassword;
  1750. TunnelPassphrase = TunnelPassphrase;
  1751. Passphrase = Passphrase;
  1752. EncryptKey = EncryptKey;
  1753. }
  1754. //---------------------------------------------------------------------
  1755. // Caching read password files, particularly when the file is actually a named pipe
  1756. // that does not support repeated reading.
  1757. static std::unique_ptr<TCriticalSection> PasswordFilesCacheSection(TraceInitPtr(new TCriticalSection()));
  1758. typedef std::map<UnicodeString, UnicodeString> TPasswordFilesCache;
  1759. static TPasswordFilesCache PasswordFilesCache;
  1760. //---------------------------------------------------------------------
  1761. static UnicodeString ReadPasswordFromFile(const UnicodeString & FileName)
  1762. {
  1763. UnicodeString Result;
  1764. if (!FileName.IsEmpty())
  1765. {
  1766. TGuard Guard(PasswordFilesCacheSection.get());
  1767. TPasswordFilesCache::const_iterator I = PasswordFilesCache.find(FileName);
  1768. if (I != PasswordFilesCache.end())
  1769. {
  1770. Result = I->second;
  1771. }
  1772. else
  1773. {
  1774. std::unique_ptr<TStrings> Lines(new TStringList());
  1775. LoadScriptFromFile(FileName, Lines.get());
  1776. if (Lines->Count > 0)
  1777. {
  1778. Result = Lines->Strings[0];
  1779. }
  1780. PasswordFilesCache[FileName] = Result;
  1781. }
  1782. }
  1783. return Result;
  1784. }
  1785. //---------------------------------------------------------------------
  1786. void TSessionData::ReadPasswordsFromFiles()
  1787. {
  1788. Password = ReadPasswordFromFile(Password);
  1789. NewPassword = ReadPasswordFromFile(NewPassword);
  1790. ProxyPassword = ReadPasswordFromFile(ProxyPassword);
  1791. TunnelPassword = ReadPasswordFromFile(TunnelPassword);
  1792. TunnelPassphrase = ReadPasswordFromFile(TunnelPassphrase);
  1793. Passphrase = ReadPasswordFromFile(Passphrase);
  1794. EncryptKey = ReadPasswordFromFile(EncryptKey);
  1795. }
  1796. //---------------------------------------------------------------------
  1797. bool __fastcall TSessionData::HasPassword()
  1798. {
  1799. return !FPassword.IsEmpty();
  1800. }
  1801. //---------------------------------------------------------------------
  1802. bool __fastcall TSessionData::HasAnySessionPassword()
  1803. {
  1804. // Keep in sync with ClearSessionPasswords
  1805. return
  1806. HasPassword() ||
  1807. !FTunnelPassword.IsEmpty() ||
  1808. // will probably be never used
  1809. !FNewPassword.IsEmpty();
  1810. }
  1811. //---------------------------------------------------------------------
  1812. bool __fastcall TSessionData::HasAnyPassword()
  1813. {
  1814. // Keep in sync with MaskPasswords
  1815. return
  1816. HasAnySessionPassword() ||
  1817. !FProxyPassword.IsEmpty() ||
  1818. !FEncryptKey.IsEmpty() ||
  1819. !FPassphrase.IsEmpty() ||
  1820. !FTunnelPassphrase.IsEmpty();
  1821. }
  1822. //---------------------------------------------------------------------
  1823. void __fastcall TSessionData::ClearSessionPasswords()
  1824. {
  1825. // Keep in sync with HasAnySessionPassword
  1826. FPassword = L"";
  1827. FNewPassword = L"";
  1828. FTunnelPassword = L"";
  1829. }
  1830. //---------------------------------------------------------------------
  1831. void __fastcall TSessionData::Modify()
  1832. {
  1833. FModified = true;
  1834. if (FSource == ssStored)
  1835. {
  1836. FSource = ssStoredModified;
  1837. }
  1838. }
  1839. //---------------------------------------------------------------------
  1840. UnicodeString __fastcall TSessionData::GetSourceName()
  1841. {
  1842. switch (FSource)
  1843. {
  1844. case ::ssNone:
  1845. return L"Ad-Hoc site";
  1846. case ssStored:
  1847. return L"Site";
  1848. case ssStoredModified:
  1849. return L"Modified site";
  1850. default:
  1851. DebugFail();
  1852. return L"";
  1853. }
  1854. }
  1855. //---------------------------------------------------------------------
  1856. void __fastcall TSessionData::SaveRecryptedPasswords(THierarchicalStorage * Storage)
  1857. {
  1858. if (Storage->OpenSubKey(InternalStorageKey, true))
  1859. {
  1860. try
  1861. {
  1862. RecryptPasswords();
  1863. SavePasswords(Storage, false, false, false);
  1864. }
  1865. __finally
  1866. {
  1867. Storage->CloseSubKey();
  1868. }
  1869. }
  1870. }
  1871. //---------------------------------------------------------------------
  1872. void __fastcall TSessionData::Remove(THierarchicalStorage * Storage, const UnicodeString & Name)
  1873. {
  1874. Storage->RecursiveDeleteSubKey(Name);
  1875. }
  1876. //---------------------------------------------------------------------
  1877. void __fastcall TSessionData::Remove()
  1878. {
  1879. bool SessionList = true;
  1880. THierarchicalStorage * Storage = Configuration->CreateScpStorage(SessionList);
  1881. try
  1882. {
  1883. Storage->Explicit = true;
  1884. if (Storage->OpenSubKey(Configuration->StoredSessionsSubKey, false))
  1885. {
  1886. Remove(Storage, InternalStorageKey);
  1887. }
  1888. }
  1889. __finally
  1890. {
  1891. delete Storage;
  1892. }
  1893. }
  1894. //---------------------------------------------------------------------
  1895. void __fastcall TSessionData::CacheHostKeyIfNotCached()
  1896. {
  1897. UnicodeString KeyType = KeyTypeFromFingerprint(HostKey);
  1898. // Should allow importing to INI file as ImportHostKeys
  1899. UnicodeString TargetKey = Configuration->RegistryStorageKey + L"\\" + Configuration->SshHostKeysSubKey;
  1900. std::unique_ptr<TRegistryStorage> Storage(new TRegistryStorage(TargetKey));
  1901. Storage->AccessMode = smReadWrite;
  1902. if (Storage->OpenRootKey(true))
  1903. {
  1904. UnicodeString HostKeyName = PuttyMungeStr(FORMAT(L"%s@%d:%s", (KeyType, PortNumber, HostName)));
  1905. if (!Storage->ValueExists(HostKeyName))
  1906. {
  1907. // fingerprint is a checksum of a host key, so it cannot be translated back to host key,
  1908. // so we store fingerprint and TSecureShell::VerifyHostKey was
  1909. // modified to accept also fingerprint
  1910. Storage->WriteString(HostKeyName, HostKey);
  1911. }
  1912. }
  1913. }
  1914. //---------------------------------------------------------------------
  1915. inline void __fastcall MoveStr(UnicodeString & Source, UnicodeString * Dest, int Count)
  1916. {
  1917. if (Dest != NULL)
  1918. {
  1919. (*Dest) += Source.SubString(1, Count);
  1920. }
  1921. Source.Delete(1, Count);
  1922. }
  1923. //---------------------------------------------------------------------
  1924. bool __fastcall TSessionData::DoIsProtocolUrl(
  1925. const UnicodeString & Url, const UnicodeString & Protocol, int & ProtocolLen)
  1926. {
  1927. bool Result = SameText(Url.SubString(1, Protocol.Length() + 1), Protocol + L":");
  1928. if (Result)
  1929. {
  1930. ProtocolLen = Protocol.Length() + 1;
  1931. }
  1932. return Result;
  1933. }
  1934. //---------------------------------------------------------------------
  1935. bool __fastcall TSessionData::IsProtocolUrl(
  1936. const UnicodeString & Url, const UnicodeString & Protocol, int & ProtocolLen)
  1937. {
  1938. return
  1939. DoIsProtocolUrl(Url, Protocol, ProtocolLen) ||
  1940. DoIsProtocolUrl(Url, WinSCPProtocolPrefix + Protocol, ProtocolLen);
  1941. }
  1942. //---------------------------------------------------------------------
  1943. bool __fastcall TSessionData::IsSensitiveOption(const UnicodeString & Option, const UnicodeString & Value)
  1944. {
  1945. bool Result;
  1946. if (SameText(Option, PassphraseOption) ||
  1947. SameText(Option, PASSWORD_SWITCH) ||
  1948. SameText(Option, NEWPASSWORD_SWITCH))
  1949. {
  1950. Result = true;
  1951. }
  1952. else if (SameText(Option, PRIVATEKEY_SWITCH))
  1953. {
  1954. Filename * AFilename = filename_from_utf8(UTF8String(Value).c_str());
  1955. Result = (in_memory_key_data(AFilename) != NULL);
  1956. filename_free(AFilename);
  1957. }
  1958. else
  1959. {
  1960. Result = false;
  1961. }
  1962. return Result;
  1963. }
  1964. //---------------------------------------------------------------------
  1965. bool __fastcall TSessionData::IsOptionWithParameters(const UnicodeString & Option)
  1966. {
  1967. return SameText(Option, RawSettingsOption);
  1968. }
  1969. //---------------------------------------------------------------------
  1970. bool __fastcall TSessionData::MaskPasswordInOptionParameter(const UnicodeString & Option, UnicodeString & Param)
  1971. {
  1972. bool Result = false;
  1973. if (SameText(Option, RawSettingsOption))
  1974. {
  1975. int P = Param.Pos(L"=");
  1976. if (P > 0)
  1977. {
  1978. // TStrings.IndexOfName does not trim
  1979. UnicodeString Key = Param.SubString(1, P - 1);
  1980. if (SameText(Key, L"ProxyPassword") ||
  1981. SameText(Key, L"ProxyPasswordEnc") ||
  1982. SameText(Key, L"TunnelPassword") ||
  1983. SameText(Key, L"TunnelPasswordPlain") ||
  1984. SameText(Key, L"TunnelPassphrase") ||
  1985. SameText(Key, L"TunnelPassphrasePlain") ||
  1986. SameText(Key, L"EncryptKey") ||
  1987. SameText(Key, L"EncryptKeyPlain"))
  1988. {
  1989. Param = Key + L"=" + PasswordMask;
  1990. Result = true;
  1991. }
  1992. }
  1993. }
  1994. return Result;
  1995. }
  1996. //---------------------------------------------------------------------
  1997. void __fastcall TSessionData::MaskPasswords()
  1998. {
  1999. // Keep in sync with HasAnyPassword
  2000. if (!Password.IsEmpty())
  2001. {
  2002. Password = PasswordMask;
  2003. }
  2004. if (!NewPassword.IsEmpty())
  2005. {
  2006. NewPassword = PasswordMask;
  2007. }
  2008. if (!ProxyPassword.IsEmpty())
  2009. {
  2010. ProxyPassword = PasswordMask;
  2011. }
  2012. if (!TunnelPassword.IsEmpty())
  2013. {
  2014. TunnelPassword = PasswordMask;
  2015. }
  2016. if (!TunnelPassphrase.IsEmpty())
  2017. {
  2018. TunnelPassphrase = PasswordMask;
  2019. }
  2020. if (!EncryptKey.IsEmpty())
  2021. {
  2022. EncryptKey = PasswordMask;
  2023. }
  2024. if (!Passphrase.IsEmpty())
  2025. {
  2026. Passphrase = PasswordMask;
  2027. }
  2028. }
  2029. //---------------------------------------------------------------------
  2030. bool __fastcall TSessionData::ParseUrl(UnicodeString Url, TOptions * Options,
  2031. TStoredSessionList * StoredSessions, bool & DefaultsOnly, UnicodeString * FileName,
  2032. bool * AProtocolDefined, UnicodeString * MaskedUrl, int Flags)
  2033. {
  2034. bool ProtocolDefined = true;
  2035. bool PortNumberDefined = false;
  2036. TFSProtocol AFSProtocol;
  2037. int DefaultProtocolPortNumber;
  2038. TFtps AFtps = ftpsNone;
  2039. int ProtocolLen = 0;
  2040. bool HttpForWebdav = FLAGCLEAR(Flags, pufPreferProtocol) || (FSProtocol != fsS3);
  2041. if (IsProtocolUrl(Url, ScpProtocol, ProtocolLen))
  2042. {
  2043. AFSProtocol = fsSCPonly;
  2044. DefaultProtocolPortNumber = SshPortNumber;
  2045. }
  2046. else if (IsProtocolUrl(Url, SftpProtocol, ProtocolLen))
  2047. {
  2048. AFSProtocol = fsSFTPonly;
  2049. DefaultProtocolPortNumber = SshPortNumber;
  2050. }
  2051. else if (IsProtocolUrl(Url, FtpProtocol, ProtocolLen))
  2052. {
  2053. AFSProtocol = fsFTP;
  2054. Ftps = ftpsNone;
  2055. DefaultProtocolPortNumber = FtpPortNumber;
  2056. }
  2057. else if (IsProtocolUrl(Url, FtpsProtocol, ProtocolLen))
  2058. {
  2059. AFSProtocol = fsFTP;
  2060. AFtps = ftpsImplicit;
  2061. DefaultProtocolPortNumber = FtpsImplicitPortNumber;
  2062. }
  2063. else if (IsProtocolUrl(Url, FtpesProtocol, ProtocolLen))
  2064. {
  2065. AFSProtocol = fsFTP;
  2066. AFtps = ftpsExplicitTls;
  2067. DefaultProtocolPortNumber = FtpPortNumber;
  2068. }
  2069. else if (IsProtocolUrl(Url, WebDAVProtocol, ProtocolLen) ||
  2070. (HttpForWebdav && IsProtocolUrl(Url, HttpProtocol, ProtocolLen)))
  2071. {
  2072. AFSProtocol = fsWebDAV;
  2073. AFtps = ftpsNone;
  2074. DefaultProtocolPortNumber = HTTPPortNumber;
  2075. }
  2076. else if (IsProtocolUrl(Url, WebDAVSProtocol, ProtocolLen) ||
  2077. (HttpForWebdav && IsProtocolUrl(Url, HttpsProtocol, ProtocolLen)))
  2078. {
  2079. AFSProtocol = fsWebDAV;
  2080. AFtps = ftpsImplicit;
  2081. DefaultProtocolPortNumber = HTTPSPortNumber;
  2082. }
  2083. else if (IsProtocolUrl(Url, S3PlainProtocol, ProtocolLen) ||
  2084. IsProtocolUrl(Url, HttpProtocol, ProtocolLen))
  2085. {
  2086. AFSProtocol = fsS3;
  2087. AFtps = ftpsNone;
  2088. DefaultProtocolPortNumber = HTTPPortNumber;
  2089. }
  2090. else if (IsProtocolUrl(Url, S3Protocol, ProtocolLen) ||
  2091. IsProtocolUrl(Url, HttpsProtocol, ProtocolLen))
  2092. {
  2093. AFSProtocol = fsS3;
  2094. AFtps = ftpsImplicit;
  2095. DefaultProtocolPortNumber = HTTPSPortNumber;
  2096. }
  2097. else if (IsProtocolUrl(Url, SshProtocol, ProtocolLen))
  2098. {
  2099. // For most uses, handling ssh:// the same way as sftp://
  2100. // The only place where a difference is made is GetLoginData() in WinMain.cpp
  2101. AFSProtocol = fsSFTPonly;
  2102. PuttyProtocol = PuttySshProtocol;
  2103. DefaultProtocolPortNumber = SshPortNumber;
  2104. }
  2105. else
  2106. {
  2107. ProtocolDefined = false;
  2108. }
  2109. if (ProtocolDefined)
  2110. {
  2111. MoveStr(Url, MaskedUrl, ProtocolLen);
  2112. }
  2113. if (ProtocolDefined && (Url.SubString(1, 2) == L"//"))
  2114. {
  2115. MoveStr(Url, MaskedUrl, 2);
  2116. }
  2117. if (AProtocolDefined != NULL)
  2118. {
  2119. *AProtocolDefined = ProtocolDefined;
  2120. }
  2121. bool Unsafe = FLAGSET(Flags, pufUnsafe);
  2122. bool ParseOnly = FLAGSET(Flags, pufParseOnly);
  2123. if (!Url.IsEmpty())
  2124. {
  2125. UnicodeString DecodedUrl = DecodeUrlChars(Url);
  2126. // lookup stored session even if protocol was defined
  2127. // (this allows setting for example default username for host
  2128. // by creating stored session named by host)
  2129. TSessionData * Data = NULL;
  2130. // When using to paste URL on Login dialog, we do not want to lookup the stored sites
  2131. if ((StoredSessions != NULL) &&
  2132. (!ProtocolDefined || FLAGSET(Flags, pufAllowStoredSiteWithProtocol)))
  2133. {
  2134. // this can be optimized as the list is sorted
  2135. for (Integer Index = 0; Index < StoredSessions->CountIncludingHidden; Index++)
  2136. {
  2137. TSessionData * AData = (TSessionData *)StoredSessions->Items[Index];
  2138. if (!AData->IsWorkspace)
  2139. {
  2140. bool Match = false;
  2141. // Comparison optimizations as this is called many times
  2142. // e.g. when updating jumplist
  2143. if ((AData->Name.Length() == DecodedUrl.Length()) &&
  2144. SameText(AData->Name, DecodedUrl))
  2145. {
  2146. Match = true;
  2147. }
  2148. else if ((AData->Name.Length() < DecodedUrl.Length()) &&
  2149. (DecodedUrl[AData->Name.Length() + 1] == L'/') &&
  2150. // StrLIComp is an equivalent of SameText
  2151. (StrLIComp(AData->Name.c_str(), DecodedUrl.c_str(), AData->Name.Length()) == 0))
  2152. {
  2153. Match = true;
  2154. }
  2155. if (Match)
  2156. {
  2157. Data = AData;
  2158. break;
  2159. }
  2160. }
  2161. }
  2162. }
  2163. UnicodeString ARemoteDirectory;
  2164. if (Data != NULL)
  2165. {
  2166. DoCopyData(Data, ParseOnly);
  2167. FSource = Data->FSource;
  2168. int P = 1;
  2169. while (!AnsiSameText(DecodeUrlChars(Url.SubString(1, P)), Data->Name))
  2170. {
  2171. P++;
  2172. DebugAssert(P <= Url.Length());
  2173. }
  2174. ARemoteDirectory = Url.SubString(P + 1, Url.Length() - P);
  2175. if (Data->Hidden && !ParseOnly)
  2176. {
  2177. Data->Remove();
  2178. StoredSessions->Remove(Data);
  2179. // only modified, implicit
  2180. StoredSessions->Save(false, false);
  2181. }
  2182. if (MaskedUrl != NULL)
  2183. {
  2184. (*MaskedUrl) += Url;
  2185. }
  2186. }
  2187. else
  2188. {
  2189. // When ad-hoc URL is used, always display error when the directories are not valid,
  2190. // no matter if they are part of the URL or raw settings.
  2191. RequireDirectories = true;
  2192. // This happens when pasting URL on Login dialog
  2193. if (StoredSessions != NULL)
  2194. {
  2195. DoCopyData(StoredSessions->DefaultSettings, ParseOnly);
  2196. }
  2197. Name = L"";
  2198. int PSlash = Url.Pos(L"/");
  2199. if (PSlash == 0)
  2200. {
  2201. PSlash = Url.Length() + 1;
  2202. }
  2203. UnicodeString ConnectInfo = Url.SubString(1, PSlash - 1);
  2204. int P = ConnectInfo.LastDelimiter(L"@");
  2205. UnicodeString UserInfo;
  2206. UnicodeString HostInfo;
  2207. if (P > 0)
  2208. {
  2209. UserInfo = ConnectInfo.SubString(1, P - 1);
  2210. HostInfo = ConnectInfo.SubString(P + 1, ConnectInfo.Length() - P);
  2211. }
  2212. else
  2213. {
  2214. HostInfo = ConnectInfo;
  2215. }
  2216. UnicodeString OrigHostInfo = HostInfo;
  2217. if ((HostInfo.Length() >= 2) && (HostInfo[1] == L'[') && ((P = HostInfo.Pos(L"]")) > 0))
  2218. {
  2219. HostName = HostInfo.SubString(2, P - 2);
  2220. HostInfo.Delete(1, P);
  2221. if (!HostInfo.IsEmpty() && (HostInfo[1] == L':'))
  2222. {
  2223. HostInfo.Delete(1, 1);
  2224. }
  2225. }
  2226. else
  2227. {
  2228. HostName = DecodeUrlChars(CutToChar(HostInfo, L':', true));
  2229. }
  2230. // expanded from ?: operator, as it caused strange "access violation" errors
  2231. if (!HostInfo.IsEmpty())
  2232. {
  2233. int APortNumber = StrToIntDef(DecodeUrlChars(HostInfo), -1);
  2234. if ((APortNumber > 0) && (APortNumber <= 65535))
  2235. {
  2236. PortNumber = APortNumber;
  2237. PortNumberDefined = true;
  2238. }
  2239. }
  2240. else if (ProtocolDefined)
  2241. {
  2242. if ((AFSProtocol == fsWebDAV) &&
  2243. (IsDomainOrSubdomain(HostName, S3HostName) ||
  2244. IsDomainOrSubdomain(HostName, L"digitaloceanspaces.com") ||
  2245. IsDomainOrSubdomain(HostName, S3GoogleCloudHostName) ||
  2246. IsDomainOrSubdomain(HostName, L"r2.cloudflarestorage.com") ||
  2247. (IsDomainOrSubdomain(HostName, L"oraclecloud.com") && ContainsText(HostName, L".compat.objectstorage."))))
  2248. {
  2249. AFSProtocol = fsS3;
  2250. }
  2251. PortNumber = DefaultProtocolPortNumber;
  2252. }
  2253. if (ProtocolDefined)
  2254. {
  2255. Ftps = AFtps;
  2256. }
  2257. UnicodeString UserInfoWithoutConnectionParams = CutToChar(UserInfo, UrlParamSeparator, false);
  2258. UnicodeString ConnectionParams = UserInfo;
  2259. UserInfo = UserInfoWithoutConnectionParams;
  2260. std::unique_ptr<TStrings> RawSettings(new TStringList());
  2261. while (!ConnectionParams.IsEmpty())
  2262. {
  2263. UnicodeString ConnectionParam = CutToChar(ConnectionParams, UrlParamSeparator, false);
  2264. UnicodeString ConnectionParamName = CutToChar(ConnectionParam, UrlParamValueSeparator, false);
  2265. if (SameText(ConnectionParamName, UrlHostKeyParamName))
  2266. {
  2267. HostKey = DecodeUrlChars(ConnectionParam);
  2268. FOverrideCachedHostKey = false;
  2269. }
  2270. else if (StartsText(UrlRawSettingsParamNamePrefix, ConnectionParamName))
  2271. {
  2272. UnicodeString AName = RightStr(ConnectionParamName, ConnectionParamName.Length() - UrlRawSettingsParamNamePrefix.Length());
  2273. AName = DecodeUrlChars(AName);
  2274. UnicodeString Value = DecodeUrlChars(ConnectionParam);
  2275. if (SameText(AName, L"Name"))
  2276. {
  2277. Name = Value;
  2278. }
  2279. else
  2280. {
  2281. RawSettings->Values[AName] = Value;
  2282. }
  2283. }
  2284. }
  2285. if (RawSettings->Count > 0) // optimization
  2286. {
  2287. ApplyRawSettings(RawSettings.get(), Unsafe);
  2288. }
  2289. bool HasPassword = (UserInfo.Pos(L':') > 0);
  2290. UnicodeString RawUserName = CutToChar(UserInfo, L':', false);
  2291. UserName = DecodeUrlChars(RawUserName);
  2292. Password = DecodeUrlChars(UserInfo);
  2293. if (HasPassword && Password.IsEmpty())
  2294. {
  2295. Password = EmptyString;
  2296. }
  2297. UnicodeString RemoteDirectoryWithSessionParams = Url.SubString(PSlash, Url.Length() - PSlash + 1);
  2298. ARemoteDirectory = CutToChar(RemoteDirectoryWithSessionParams, UrlParamSeparator, false);
  2299. UnicodeString SessionParams = RemoteDirectoryWithSessionParams;
  2300. // We should handle session params in "stored session" branch too.
  2301. // And particularly if there's a "save" param, we should actually not try to match the
  2302. // URL against site names
  2303. while (!SessionParams.IsEmpty())
  2304. {
  2305. UnicodeString SessionParam = CutToChar(SessionParams, UrlParamSeparator, false);
  2306. UnicodeString SessionParamName = CutToChar(SessionParam, UrlParamValueSeparator, false);
  2307. if (SameText(SessionParamName, UrlSaveParamName))
  2308. {
  2309. FSaveOnly = (StrToIntDef(SessionParam, 1) != 0);
  2310. }
  2311. }
  2312. if (MaskedUrl != NULL)
  2313. {
  2314. (*MaskedUrl) += RawUserName;
  2315. if (HasPassword)
  2316. {
  2317. (*MaskedUrl) += L":" + PasswordMask;
  2318. }
  2319. if (!RawUserName.IsEmpty() || HasPassword)
  2320. {
  2321. (*MaskedUrl) += L"@";
  2322. }
  2323. (*MaskedUrl) += OrigHostInfo + ARemoteDirectory;
  2324. }
  2325. }
  2326. if (!ARemoteDirectory.IsEmpty() && (ARemoteDirectory != L"/"))
  2327. {
  2328. if ((ARemoteDirectory[ARemoteDirectory.Length()] != L'/') &&
  2329. (FileName != NULL))
  2330. {
  2331. *FileName = DecodeUrlChars(UnixExtractFileName(ARemoteDirectory));
  2332. ARemoteDirectory = UnixExtractFilePath(ARemoteDirectory);
  2333. }
  2334. RemoteDirectory = DecodeUrlChars(ARemoteDirectory);
  2335. // Is already true for ad-hoc URL, but we want to error even for "storedsite/path/"-style URL.
  2336. RequireDirectories = true;
  2337. }
  2338. DefaultsOnly = false;
  2339. }
  2340. else
  2341. {
  2342. // This happens when pasting URL on Login dialog
  2343. if (StoredSessions != NULL)
  2344. {
  2345. CopyData(StoredSessions->DefaultSettings);
  2346. }
  2347. DefaultsOnly = true;
  2348. }
  2349. if (ProtocolDefined)
  2350. {
  2351. FSProtocol = AFSProtocol;
  2352. }
  2353. if (Options != NULL)
  2354. {
  2355. // we deliberately do keep defaultonly to false, in presence of any option,
  2356. // as the option should not make session "connectable"
  2357. UnicodeString Value;
  2358. if (Options->FindSwitch(USERNAME_SWITCH, Value))
  2359. {
  2360. UserName = Value;
  2361. }
  2362. if (Options->FindSwitch(PASSWORD_SWITCH, Value))
  2363. {
  2364. Password = Value;
  2365. }
  2366. if (Options->FindSwitch(SESSIONNAME_SWICH, Value))
  2367. {
  2368. Name = Value;
  2369. }
  2370. if (Options->FindSwitch(NEWPASSWORD_SWITCH, Value))
  2371. {
  2372. ChangePassword = true;
  2373. NewPassword = Value;
  2374. }
  2375. if (Options->FindSwitch(PRIVATEKEY_SWITCH, Value))
  2376. {
  2377. PublicKeyFile = Value;
  2378. }
  2379. if (Options->FindSwitch(L"clientcert", Value))
  2380. {
  2381. TlsCertificateFile = Value;
  2382. }
  2383. if (Options->FindSwitch(PassphraseOption, Value))
  2384. {
  2385. Passphrase = Value;
  2386. }
  2387. if (Options->FindSwitch(L"timeout", Value))
  2388. {
  2389. Timeout = StrToInt(Value);
  2390. }
  2391. if (Options->FindSwitch(L"hostkey", Value) ||
  2392. Options->FindSwitch(L"certificate", Value))
  2393. {
  2394. HostKey = Value;
  2395. FOverrideCachedHostKey = true;
  2396. }
  2397. FtpPasvMode = Options->SwitchValue(L"passive", FtpPasvMode);
  2398. if (Options->FindSwitch(L"implicit"))
  2399. {
  2400. bool Enabled = Options->SwitchValue(L"implicit", true);
  2401. Ftps = Enabled ? ftpsImplicit : ftpsNone;
  2402. if (!PortNumberDefined && Enabled)
  2403. {
  2404. PortNumber = FtpsImplicitPortNumber;
  2405. }
  2406. }
  2407. // BACKWARD COMPATIBILITY with 5.5.x
  2408. if (Options->FindSwitch(L"explicitssl"))
  2409. {
  2410. bool Enabled = Options->SwitchValue(L"explicitssl", true);
  2411. Ftps = Enabled ? ftpsExplicitSsl : ftpsNone;
  2412. if (!PortNumberDefined && Enabled)
  2413. {
  2414. PortNumber = FtpPortNumber;
  2415. }
  2416. }
  2417. if (Options->FindSwitch(L"explicit") ||
  2418. // BACKWARD COMPATIBILITY with 5.5.x
  2419. Options->FindSwitch(L"explicittls"))
  2420. {
  2421. UnicodeString SwitchName =
  2422. Options->FindSwitch(L"explicit") ? L"explicit" : L"explicittls";
  2423. bool Enabled = Options->SwitchValue(SwitchName, true);
  2424. Ftps = Enabled ? ftpsExplicitTls : ftpsNone;
  2425. if (!PortNumberDefined && Enabled)
  2426. {
  2427. PortNumber = FtpPortNumber;
  2428. }
  2429. }
  2430. if (Options->FindSwitch(RawSettingsOption))
  2431. {
  2432. std::unique_ptr<TStrings> RawSettings(new TStringList());
  2433. if (Options->FindSwitch(RawSettingsOption, RawSettings.get()))
  2434. {
  2435. ApplyRawSettings(RawSettings.get(), Unsafe);
  2436. }
  2437. }
  2438. if (Options->FindSwitch(PASSWORDSFROMFILES_SWITCH) &&
  2439. // Ad-hoc condition for the current only specific use of pufParseOnly
  2440. // (when we do not want to consume the password pipe by the current instance,
  2441. // in case the URL needs to be passed to another instance)
  2442. !ParseOnly)
  2443. {
  2444. ReadPasswordsFromFiles();
  2445. }
  2446. }
  2447. return true;
  2448. }
  2449. //---------------------------------------------------------------------
  2450. void __fastcall TSessionData::ApplyRawSettings(TStrings * RawSettings, bool Unsafe)
  2451. {
  2452. std::unique_ptr<TOptionsStorage> OptionsStorage(new TOptionsStorage(RawSettings, false));
  2453. ApplyRawSettings(OptionsStorage.get(), Unsafe, false);
  2454. }
  2455. //---------------------------------------------------------------------
  2456. void __fastcall TSessionData::ApplyRawSettings(THierarchicalStorage * Storage, bool Unsafe, bool RespectDisablePasswordStoring)
  2457. {
  2458. bool Dummy;
  2459. DoLoad(Storage, false, Dummy, Unsafe, RespectDisablePasswordStoring);
  2460. }
  2461. //---------------------------------------------------------------------
  2462. void __fastcall TSessionData::ConfigureTunnel(int APortNumber)
  2463. {
  2464. FOrigHostName = HostName;
  2465. FOrigPortNumber = PortNumber;
  2466. FOrigProxyMethod = ProxyMethod;
  2467. HostName = L"127.0.0.1";
  2468. PortNumber = APortNumber;
  2469. // proxy settings is used for tunnel
  2470. ProxyMethod = ::pmNone;
  2471. FLogicalHostName = FOrigHostName;
  2472. }
  2473. //---------------------------------------------------------------------
  2474. void __fastcall TSessionData::RollbackTunnel()
  2475. {
  2476. HostName = FOrigHostName;
  2477. PortNumber = FOrigPortNumber;
  2478. ProxyMethod = FOrigProxyMethod;
  2479. FLogicalHostName = L"";
  2480. }
  2481. //---------------------------------------------------------------------
  2482. TSessionData * TSessionData::CreateTunnelData(int TunnelLocalPortNumber)
  2483. {
  2484. std::unique_ptr<TSessionData> TunnelData(new TSessionData(EmptyStr));
  2485. TunnelData->Assign(StoredSessions->DefaultSettings);
  2486. TunnelData->Name = FMTLOAD(TUNNEL_SESSION_NAME, (SessionName));
  2487. TunnelData->Tunnel = false;
  2488. TunnelData->HostName = TunnelHostName;
  2489. TunnelData->PortNumber = TunnelPortNumber;
  2490. TunnelData->UserName = TunnelUserName;
  2491. TunnelData->Password = TunnelPassword;
  2492. TunnelData->PublicKeyFile = TunnelPublicKeyFile;
  2493. TunnelData->DetachedCertificate = EmptyStr;
  2494. TunnelData->Passphrase = TunnelPassphrase;
  2495. UnicodeString AHostName = HostNameExpanded;
  2496. if (IsIPv6Literal(AHostName))
  2497. {
  2498. AHostName = EscapeIPv6Literal(AHostName);
  2499. }
  2500. TunnelData->TunnelPortFwd = FORMAT(L"L%d\t%s:%d",
  2501. (TunnelLocalPortNumber, AHostName, PortNumber));
  2502. TunnelData->HostKey = TunnelHostKey;
  2503. // inherit proxy options on the main session
  2504. TunnelData->ProxyMethod = ProxyMethod;
  2505. TunnelData->ProxyHost = ProxyHost;
  2506. TunnelData->ProxyPort = ProxyPort;
  2507. TunnelData->ProxyUsername = ProxyUsername;
  2508. TunnelData->ProxyPassword = ProxyPassword;
  2509. TunnelData->ProxyTelnetCommand = ProxyTelnetCommand;
  2510. TunnelData->ProxyLocalCommand = ProxyLocalCommand;
  2511. TunnelData->ProxyDNS = ProxyDNS;
  2512. TunnelData->ProxyLocalhost = ProxyLocalhost;
  2513. // inherit most SSH options of the main session (except for private key and bugs)
  2514. TunnelData->Compression = Compression;
  2515. TunnelData->CipherList = CipherList;
  2516. TunnelData->Ssh2DES = Ssh2DES;
  2517. TunnelData->KexList = KexList;
  2518. TunnelData->RekeyData = RekeyData;
  2519. TunnelData->RekeyTime = RekeyTime;
  2520. TunnelData->SshNoUserAuth = SshNoUserAuth;
  2521. TunnelData->AuthGSSAPI = AuthGSSAPI;
  2522. TunnelData->AuthGSSAPIKEX = AuthGSSAPIKEX;
  2523. TunnelData->GSSAPIFwdTGT = GSSAPIFwdTGT;
  2524. TunnelData->TryAgent = TryAgent;
  2525. TunnelData->AgentFwd = AgentFwd;
  2526. TunnelData->AuthKI = AuthKI;
  2527. TunnelData->AuthKIPassword = AuthKIPassword;
  2528. return TunnelData.release();
  2529. }
  2530. //---------------------------------------------------------------------
  2531. void __fastcall TSessionData::ExpandEnvironmentVariables()
  2532. {
  2533. HostName = HostNameExpanded;
  2534. UserName = UserNameExpanded;
  2535. PublicKeyFile = ::ExpandEnvironmentVariables(PublicKeyFile);
  2536. DetachedCertificate = ::ExpandEnvironmentVariables(DetachedCertificate);
  2537. }
  2538. //---------------------------------------------------------------------
  2539. void __fastcall TSessionData::ValidatePath(const UnicodeString Path)
  2540. {
  2541. // noop
  2542. }
  2543. //---------------------------------------------------------------------
  2544. void __fastcall TSessionData::ValidateName(const UnicodeString Name)
  2545. {
  2546. // keep consistent with MakeValidName
  2547. if (Name.LastDelimiter(L"/") > 0)
  2548. {
  2549. throw Exception(FMTLOAD(ITEM_NAME_INVALID, (Name, L"/")));
  2550. }
  2551. }
  2552. //---------------------------------------------------------------------
  2553. UnicodeString __fastcall TSessionData::MakeValidName(const UnicodeString & Name)
  2554. {
  2555. // keep consistent with ValidateName
  2556. return ReplaceStr(Name, L"/", L"\\");
  2557. }
  2558. //---------------------------------------------------------------------
  2559. RawByteString __fastcall TSessionData::EncryptPassword(const UnicodeString & Password, UnicodeString Key)
  2560. {
  2561. return Configuration->EncryptPassword(Password, Key);
  2562. }
  2563. //---------------------------------------------------------------------
  2564. RawByteString __fastcall TSessionData::StronglyRecryptPassword(const RawByteString & Password, UnicodeString Key)
  2565. {
  2566. return Configuration->StronglyRecryptPassword(Password, Key);
  2567. }
  2568. //---------------------------------------------------------------------
  2569. UnicodeString __fastcall TSessionData::DecryptPassword(const RawByteString & Password, UnicodeString Key)
  2570. {
  2571. UnicodeString Result;
  2572. try
  2573. {
  2574. Result = Configuration->DecryptPassword(Password, Key);
  2575. }
  2576. catch(EAbort &)
  2577. {
  2578. // silently ignore aborted prompts for master password and return empty password
  2579. }
  2580. return Result;
  2581. }
  2582. //---------------------------------------------------------------------
  2583. UnicodeString TSessionData::GetSessionPasswordEncryptionKey() const
  2584. {
  2585. return UserName + HostName;
  2586. }
  2587. //---------------------------------------------------------------------
  2588. bool __fastcall TSessionData::GetCanLogin()
  2589. {
  2590. return !FHostName.IsEmpty();
  2591. }
  2592. //---------------------------------------------------------------------
  2593. bool __fastcall TSessionData::GetIsLocalBrowser()
  2594. {
  2595. return !LocalDirectory.IsEmpty() && !OtherLocalDirectory.IsEmpty();
  2596. }
  2597. //---------------------------------------------------------------------
  2598. bool __fastcall TSessionData::GetCanOpen()
  2599. {
  2600. return CanLogin || IsLocalBrowser;
  2601. }
  2602. //---------------------------------------------------------------------------
  2603. int TSessionData::GetDefaultPort()
  2604. {
  2605. return DefaultPort(FSProtocol, Ftps);
  2606. }
  2607. //---------------------------------------------------------------------------
  2608. UnicodeString __fastcall TSessionData::GetSessionKey()
  2609. {
  2610. UnicodeString Result = FORMAT(L"%s@%s", (UserName, HostName));
  2611. if (PortNumber != GetDefaultPort())
  2612. {
  2613. Result += FORMAT(L":%d", (PortNumber));
  2614. }
  2615. return Result;
  2616. }
  2617. //---------------------------------------------------------------------
  2618. UnicodeString __fastcall TSessionData::GetInternalStorageKey()
  2619. {
  2620. // This is probably useless remnant of previous use of this method from OpenSessionInPutty
  2621. // that needs the method to return something even for ad-hoc sessions
  2622. if (Name.IsEmpty())
  2623. {
  2624. return SessionKey;
  2625. }
  2626. else
  2627. {
  2628. return Name;
  2629. }
  2630. }
  2631. //---------------------------------------------------------------------
  2632. UnicodeString __fastcall TSessionData::GetStorageKey()
  2633. {
  2634. return SessionName;
  2635. }
  2636. //---------------------------------------------------------------------
  2637. UnicodeString __fastcall TSessionData::FormatSiteKey(const UnicodeString & HostName, int PortNumber)
  2638. {
  2639. return FORMAT(L"%s:%d", (HostName, PortNumber));
  2640. }
  2641. //---------------------------------------------------------------------
  2642. UnicodeString __fastcall TSessionData::GetSiteKey()
  2643. {
  2644. return FormatSiteKey(HostNameExpanded, PortNumber);
  2645. }
  2646. //---------------------------------------------------------------------
  2647. void __fastcall TSessionData::SetHostName(UnicodeString value)
  2648. {
  2649. if (FHostName != value)
  2650. {
  2651. // HostName is key for password encryption
  2652. UnicodeString XPassword = Password;
  2653. UnicodeString XNewPassword = NewPassword;
  2654. UnicodeString XEncryptKey = EncryptKey;
  2655. // This is now hardly used as hostname is parsed directly on login dialog.
  2656. // But can be used when importing sites from PuTTY, as it allows same format too.
  2657. int P = value.LastDelimiter(L"@");
  2658. if (P > 0)
  2659. {
  2660. UserName = value.SubString(1, P - 1);
  2661. value = value.SubString(P + 1, value.Length() - P);
  2662. }
  2663. FHostName = value;
  2664. Modify();
  2665. Password = XPassword;
  2666. NewPassword = XNewPassword;
  2667. EncryptKey = XEncryptKey;
  2668. Shred(XPassword);
  2669. Shred(XNewPassword);
  2670. Shred(XEncryptKey);
  2671. }
  2672. }
  2673. //---------------------------------------------------------------------
  2674. UnicodeString __fastcall TSessionData::GetHostNameExpanded()
  2675. {
  2676. return ::ExpandEnvironmentVariables(HostName);
  2677. }
  2678. //---------------------------------------------------------------------
  2679. UnicodeString TSessionData::GetHostNameSource()
  2680. {
  2681. UnicodeString Result;
  2682. if (HostName != HostNameExpanded)
  2683. {
  2684. Result = HostName;
  2685. }
  2686. return Result;
  2687. }
  2688. //---------------------------------------------------------------------
  2689. void __fastcall TSessionData::SetPortNumber(int value)
  2690. {
  2691. SET_SESSION_PROPERTY(PortNumber);
  2692. }
  2693. //---------------------------------------------------------------------------
  2694. void __fastcall TSessionData::SetShell(UnicodeString value)
  2695. {
  2696. SET_SESSION_PROPERTY(Shell);
  2697. }
  2698. //---------------------------------------------------------------------------
  2699. void __fastcall TSessionData::SetSftpServer(UnicodeString value)
  2700. {
  2701. SET_SESSION_PROPERTY(SftpServer);
  2702. }
  2703. //---------------------------------------------------------------------------
  2704. void __fastcall TSessionData::SetClearAliases(bool value)
  2705. {
  2706. SET_SESSION_PROPERTY(ClearAliases);
  2707. }
  2708. //---------------------------------------------------------------------------
  2709. void __fastcall TSessionData::SetListingCommand(UnicodeString value)
  2710. {
  2711. SET_SESSION_PROPERTY(ListingCommand);
  2712. }
  2713. //---------------------------------------------------------------------------
  2714. void __fastcall TSessionData::SetIgnoreLsWarnings(bool value)
  2715. {
  2716. SET_SESSION_PROPERTY(IgnoreLsWarnings);
  2717. }
  2718. //---------------------------------------------------------------------------
  2719. void __fastcall TSessionData::SetUnsetNationalVars(bool value)
  2720. {
  2721. SET_SESSION_PROPERTY(UnsetNationalVars);
  2722. }
  2723. //---------------------------------------------------------------------
  2724. void __fastcall TSessionData::SetUserName(UnicodeString value)
  2725. {
  2726. // Avoid password recryption (what may popup master password prompt)
  2727. if (FUserName != value)
  2728. {
  2729. // UserName is key for password encryption
  2730. UnicodeString XPassword = Password;
  2731. UnicodeString XNewPassword = NewPassword;
  2732. UnicodeString XEncryptKey = EncryptKey;
  2733. SET_SESSION_PROPERTY(UserName);
  2734. Password = XPassword;
  2735. NewPassword = XNewPassword;
  2736. EncryptKey = XEncryptKey;
  2737. Shred(XPassword);
  2738. Shred(XNewPassword);
  2739. Shred(XEncryptKey);
  2740. }
  2741. }
  2742. //---------------------------------------------------------------------
  2743. UnicodeString __fastcall TSessionData::GetUserNameExpanded()
  2744. {
  2745. UnicodeString Result = ::ExpandEnvironmentVariables(UserName);
  2746. if (Result.IsEmpty() && HasS3AutoCredentials())
  2747. {
  2748. Result = S3EnvUserName(S3Profile);
  2749. }
  2750. return Result;
  2751. }
  2752. //---------------------------------------------------------------------
  2753. UnicodeString TSessionData::GetUserNameSource()
  2754. {
  2755. UnicodeString Result;
  2756. if (UserName.IsEmpty() && HasS3AutoCredentials())
  2757. {
  2758. S3EnvUserName(S3Profile, &Result);
  2759. }
  2760. if (Result.IsEmpty() && (UserName != UserNameExpanded))
  2761. {
  2762. Result = UserName;
  2763. }
  2764. return Result;
  2765. }
  2766. //---------------------------------------------------------------------
  2767. void __fastcall TSessionData::SetPassword(UnicodeString avalue)
  2768. {
  2769. RawByteString value = EncryptPassword(avalue, GetSessionPasswordEncryptionKey());
  2770. SET_SESSION_PROPERTY(Password);
  2771. }
  2772. //---------------------------------------------------------------------
  2773. UnicodeString __fastcall TSessionData::GetPassword() const
  2774. {
  2775. return DecryptPassword(FPassword, GetSessionPasswordEncryptionKey());
  2776. }
  2777. //---------------------------------------------------------------------
  2778. void __fastcall TSessionData::SetNewPassword(UnicodeString avalue)
  2779. {
  2780. RawByteString value = EncryptPassword(avalue, GetSessionPasswordEncryptionKey());
  2781. SET_SESSION_PROPERTY(NewPassword);
  2782. }
  2783. //---------------------------------------------------------------------
  2784. UnicodeString __fastcall TSessionData::GetNewPassword() const
  2785. {
  2786. return DecryptPassword(FNewPassword, GetSessionPasswordEncryptionKey());
  2787. }
  2788. //---------------------------------------------------------------------
  2789. void __fastcall TSessionData::SetChangePassword(bool value)
  2790. {
  2791. SET_SESSION_PROPERTY(ChangePassword);
  2792. }
  2793. //---------------------------------------------------------------------
  2794. void __fastcall TSessionData::SetPingInterval(int value)
  2795. {
  2796. SET_SESSION_PROPERTY(PingInterval);
  2797. }
  2798. //---------------------------------------------------------------------
  2799. void __fastcall TSessionData::SetTryAgent(bool value)
  2800. {
  2801. SET_SESSION_PROPERTY(TryAgent);
  2802. }
  2803. //---------------------------------------------------------------------
  2804. void __fastcall TSessionData::SetAgentFwd(bool value)
  2805. {
  2806. SET_SESSION_PROPERTY(AgentFwd);
  2807. }
  2808. //---------------------------------------------------------------------
  2809. void __fastcall TSessionData::SetAuthKI(bool value)
  2810. {
  2811. SET_SESSION_PROPERTY(AuthKI);
  2812. }
  2813. //---------------------------------------------------------------------
  2814. void __fastcall TSessionData::SetAuthKIPassword(bool value)
  2815. {
  2816. SET_SESSION_PROPERTY(AuthKIPassword);
  2817. }
  2818. //---------------------------------------------------------------------
  2819. void __fastcall TSessionData::SetAuthGSSAPI(bool value)
  2820. {
  2821. SET_SESSION_PROPERTY(AuthGSSAPI);
  2822. }
  2823. //---------------------------------------------------------------------
  2824. void __fastcall TSessionData::SetAuthGSSAPIKEX(bool value)
  2825. {
  2826. SET_SESSION_PROPERTY(AuthGSSAPIKEX);
  2827. }
  2828. //---------------------------------------------------------------------
  2829. void __fastcall TSessionData::SetGSSAPIFwdTGT(bool value)
  2830. {
  2831. SET_SESSION_PROPERTY(GSSAPIFwdTGT);
  2832. }
  2833. //---------------------------------------------------------------------
  2834. void __fastcall TSessionData::SetChangeUsername(bool value)
  2835. {
  2836. SET_SESSION_PROPERTY(ChangeUsername);
  2837. }
  2838. //---------------------------------------------------------------------
  2839. void __fastcall TSessionData::SetCompression(bool value)
  2840. {
  2841. SET_SESSION_PROPERTY(Compression);
  2842. }
  2843. //---------------------------------------------------------------------
  2844. void __fastcall TSessionData::SetSsh2DES(bool value)
  2845. {
  2846. SET_SESSION_PROPERTY(Ssh2DES);
  2847. }
  2848. //---------------------------------------------------------------------
  2849. void __fastcall TSessionData::SetSshNoUserAuth(bool value)
  2850. {
  2851. SET_SESSION_PROPERTY(SshNoUserAuth);
  2852. }
  2853. //---------------------------------------------------------------------
  2854. bool __fastcall TSessionData::GetUsesSsh()
  2855. {
  2856. return IsSshProtocol(FSProtocol);
  2857. }
  2858. //---------------------------------------------------------------------
  2859. void __fastcall TSessionData::SetCipher(int Index, TCipher value)
  2860. {
  2861. DebugAssert(Index >= 0 && Index < CIPHER_COUNT);
  2862. SET_SESSION_PROPERTY(Ciphers[Index]);
  2863. }
  2864. //---------------------------------------------------------------------
  2865. TCipher __fastcall TSessionData::GetCipher(int Index) const
  2866. {
  2867. DebugAssert(Index >= 0 && Index < CIPHER_COUNT);
  2868. return FCiphers[Index];
  2869. }
  2870. //---------------------------------------------------------------------
  2871. template<class AlgoT>
  2872. void __fastcall TSessionData::SetAlgoList(AlgoT * List, const AlgoT * DefaultList, const UnicodeString * Names,
  2873. int Count, AlgoT WarnAlgo, UnicodeString value)
  2874. {
  2875. std::vector<bool> Used(Count); // initialized to false
  2876. std::vector<AlgoT> NewList(Count);
  2877. bool HasWarnAlgo = (WarnAlgo >= AlgoT());
  2878. const AlgoT * WarnPtr;
  2879. int WarnDefaultIndex;
  2880. if (!HasWarnAlgo)
  2881. {
  2882. WarnPtr = NULL;
  2883. WarnDefaultIndex = -1;
  2884. }
  2885. else
  2886. {
  2887. WarnPtr = std::find(DefaultList, DefaultList + Count, WarnAlgo);
  2888. DebugAssert(WarnPtr != NULL);
  2889. WarnDefaultIndex = (WarnPtr - DefaultList);
  2890. }
  2891. int Index = 0;
  2892. while (!value.IsEmpty())
  2893. {
  2894. UnicodeString AlgoStr = CutToChar(value, L',', true);
  2895. for (int Algo = 0; Algo < Count; Algo++)
  2896. {
  2897. if (!AlgoStr.CompareIC(Names[Algo]) &&
  2898. !Used[Algo] && DebugAlwaysTrue(Index < Count))
  2899. {
  2900. NewList[Index] = (AlgoT)Algo;
  2901. Used[Algo] = true;
  2902. Index++;
  2903. break;
  2904. }
  2905. }
  2906. }
  2907. if (HasWarnAlgo && !Used[WarnAlgo] && DebugAlwaysTrue(Index < Count))
  2908. {
  2909. NewList[Index] = WarnAlgo;
  2910. Used[WarnAlgo] = true;
  2911. Index++;
  2912. }
  2913. int WarnIndex = -1;
  2914. if (HasWarnAlgo)
  2915. {
  2916. WarnIndex = std::find(NewList.begin(), NewList.end(), WarnAlgo) - NewList.begin();
  2917. }
  2918. bool Priority = true;
  2919. for (int DefaultIndex = 0; (DefaultIndex < Count); DefaultIndex++)
  2920. {
  2921. AlgoT DefaultAlgo = DefaultList[DefaultIndex];
  2922. if (!Used[DefaultAlgo] && DebugAlwaysTrue(Index < Count))
  2923. {
  2924. int TargetIndex;
  2925. // Unused algs that are prioritized in the default list,
  2926. // should be merged before the existing custom list
  2927. if (Priority)
  2928. {
  2929. TargetIndex = DefaultIndex;
  2930. }
  2931. else
  2932. {
  2933. if (HasWarnAlgo && (DefaultIndex < WarnDefaultIndex))
  2934. {
  2935. TargetIndex = WarnIndex;
  2936. }
  2937. else
  2938. {
  2939. TargetIndex = Index;
  2940. }
  2941. }
  2942. NewList.insert(NewList.begin() + TargetIndex, DefaultAlgo);
  2943. DebugAssert(NewList.back() == AlgoT());
  2944. NewList.pop_back();
  2945. if (HasWarnAlgo && (TargetIndex <= WarnIndex))
  2946. {
  2947. WarnIndex++;
  2948. }
  2949. Index++;
  2950. }
  2951. else
  2952. {
  2953. Priority = false;
  2954. }
  2955. }
  2956. if (!std::equal(NewList.begin(), NewList.end(), List))
  2957. {
  2958. std::copy(NewList.begin(), NewList.end(), List);
  2959. Modify();
  2960. }
  2961. }
  2962. //---------------------------------------------------------------------
  2963. void __fastcall TSessionData::SetCipherList(UnicodeString value)
  2964. {
  2965. SetAlgoList(FCiphers, DefaultCipherList, CipherNames, CIPHER_COUNT, cipWarn, value);
  2966. }
  2967. //---------------------------------------------------------------------
  2968. UnicodeString __fastcall TSessionData::GetCipherList() const
  2969. {
  2970. UnicodeString Result;
  2971. for (int Index = 0; Index < CIPHER_COUNT; Index++)
  2972. {
  2973. Result += UnicodeString(Index ? L"," : L"") + CipherNames[Cipher[Index]];
  2974. }
  2975. return Result;
  2976. }
  2977. //---------------------------------------------------------------------
  2978. void __fastcall TSessionData::SetKex(int Index, TKex value)
  2979. {
  2980. DebugAssert(Index >= 0 && Index < KEX_COUNT);
  2981. SET_SESSION_PROPERTY(Kex[Index]);
  2982. }
  2983. //---------------------------------------------------------------------
  2984. TKex __fastcall TSessionData::GetKex(int Index) const
  2985. {
  2986. DebugAssert(Index >= 0 && Index < KEX_COUNT);
  2987. return FKex[Index];
  2988. }
  2989. //---------------------------------------------------------------------
  2990. void __fastcall TSessionData::SetKexList(UnicodeString value)
  2991. {
  2992. SetAlgoList(FKex, DefaultKexList, KexNames, KEX_COUNT, kexWarn, value);
  2993. }
  2994. //---------------------------------------------------------------------
  2995. UnicodeString __fastcall TSessionData::GetKexList() const
  2996. {
  2997. UnicodeString Result;
  2998. for (int Index = 0; Index < KEX_COUNT; Index++)
  2999. {
  3000. Result += UnicodeString(Index ? L"," : L"") + KexNames[Kex[Index]];
  3001. }
  3002. return Result;
  3003. }
  3004. //---------------------------------------------------------------------
  3005. void __fastcall TSessionData::SetHostKeys(int Index, THostKey value)
  3006. {
  3007. DebugAssert(Index >= 0 && Index < HOSTKEY_COUNT);
  3008. SET_SESSION_PROPERTY(HostKeys[Index]);
  3009. }
  3010. //---------------------------------------------------------------------
  3011. THostKey __fastcall TSessionData::GetHostKeys(int Index) const
  3012. {
  3013. DebugAssert(Index >= 0 && Index < HOSTKEY_COUNT);
  3014. return FHostKeys[Index];
  3015. }
  3016. //---------------------------------------------------------------------
  3017. void __fastcall TSessionData::SetHostKeyList(UnicodeString value)
  3018. {
  3019. SetAlgoList(FHostKeys, DefaultHostKeyList, HostKeyNames, HOSTKEY_COUNT, hkWarn, value);
  3020. }
  3021. //---------------------------------------------------------------------
  3022. UnicodeString __fastcall TSessionData::GetHostKeyList() const
  3023. {
  3024. UnicodeString Result;
  3025. for (int Index = 0; Index < HOSTKEY_COUNT; Index++)
  3026. {
  3027. Result += UnicodeString(Index ? L"," : L"") + HostKeyNames[HostKeys[Index]];
  3028. }
  3029. return Result;
  3030. }
  3031. //---------------------------------------------------------------------
  3032. void __fastcall TSessionData::SetGssLib(int Index, TGssLib value)
  3033. {
  3034. DebugAssert(Index >= 0 && Index < GSSLIB_COUNT);
  3035. SET_SESSION_PROPERTY(GssLib[Index]);
  3036. }
  3037. //---------------------------------------------------------------------
  3038. TGssLib __fastcall TSessionData::GetGssLib(int Index) const
  3039. {
  3040. DebugAssert(Index >= 0 && Index < GSSLIB_COUNT);
  3041. return FGssLib[Index];
  3042. }
  3043. //---------------------------------------------------------------------
  3044. void __fastcall TSessionData::SetGssLibList(UnicodeString value)
  3045. {
  3046. SetAlgoList(FGssLib, DefaultGssLibList, GssLibNames, GSSLIB_COUNT, TGssLib(-1), value);
  3047. }
  3048. //---------------------------------------------------------------------
  3049. UnicodeString __fastcall TSessionData::GetGssLibList() const
  3050. {
  3051. UnicodeString Result;
  3052. for (int Index = 0; Index < GSSLIB_COUNT; Index++)
  3053. {
  3054. Result += UnicodeString(Index ? L"," : L"") + GssLibNames[GssLib[Index]];
  3055. }
  3056. return Result;
  3057. }
  3058. //---------------------------------------------------------------------
  3059. void __fastcall TSessionData::SetGssLibCustom(UnicodeString value)
  3060. {
  3061. SET_SESSION_PROPERTY(GssLibCustom);
  3062. }
  3063. //---------------------------------------------------------------------
  3064. void __fastcall TSessionData::SetPublicKeyFile(UnicodeString value)
  3065. {
  3066. if (FPublicKeyFile != value)
  3067. {
  3068. // PublicKeyFile is key for Passphrase encryption
  3069. UnicodeString XPassphrase = Passphrase;
  3070. // StripPathQuotes should not be needed as we do not feed quotes anymore
  3071. FPublicKeyFile = StripPathQuotes(value);
  3072. Modify();
  3073. Passphrase = XPassphrase;
  3074. Shred(XPassphrase);
  3075. }
  3076. }
  3077. //---------------------------------------------------------------------
  3078. void __fastcall TSessionData::SetDetachedCertificate(UnicodeString value)
  3079. {
  3080. SET_SESSION_PROPERTY(DetachedCertificate);
  3081. }
  3082. //---------------------------------------------------------------------
  3083. UnicodeString TSessionData::ResolvePublicKeyFile()
  3084. {
  3085. UnicodeString Result = PublicKeyFile;
  3086. if (Result.IsEmpty())
  3087. {
  3088. Result = Configuration->DefaultKeyFile;
  3089. }
  3090. // StripPathQuotes should not be needed as we do not feed quotes anymore
  3091. Result = StripPathQuotes(::ExpandEnvironmentVariables(Result));
  3092. return Result;
  3093. }
  3094. //---------------------------------------------------------------------
  3095. void __fastcall TSessionData::SetPassphrase(UnicodeString avalue)
  3096. {
  3097. RawByteString value = EncryptPassword(avalue, PublicKeyFile);
  3098. SET_SESSION_PROPERTY(Passphrase);
  3099. }
  3100. //---------------------------------------------------------------------
  3101. UnicodeString __fastcall TSessionData::GetPassphrase() const
  3102. {
  3103. return DecryptPassword(FPassphrase, PublicKeyFile);
  3104. }
  3105. //---------------------------------------------------------------------
  3106. void __fastcall TSessionData::SetReturnVar(UnicodeString value)
  3107. {
  3108. SET_SESSION_PROPERTY(ReturnVar);
  3109. }
  3110. //---------------------------------------------------------------------
  3111. void __fastcall TSessionData::SetExitCode1IsError(bool value)
  3112. {
  3113. SET_SESSION_PROPERTY(ExitCode1IsError);
  3114. }
  3115. //---------------------------------------------------------------------------
  3116. void __fastcall TSessionData::SetLookupUserGroups(TAutoSwitch value)
  3117. {
  3118. SET_SESSION_PROPERTY(LookupUserGroups);
  3119. }
  3120. //---------------------------------------------------------------------------
  3121. void __fastcall TSessionData::SetEOLType(TEOLType value)
  3122. {
  3123. SET_SESSION_PROPERTY(EOLType);
  3124. }
  3125. //---------------------------------------------------------------------------
  3126. void __fastcall TSessionData::SetTrimVMSVersions(bool value)
  3127. {
  3128. SET_SESSION_PROPERTY(TrimVMSVersions);
  3129. }
  3130. //---------------------------------------------------------------------------
  3131. void __fastcall TSessionData::SetVMSAllRevisions(bool value)
  3132. {
  3133. SET_SESSION_PROPERTY(VMSAllRevisions);
  3134. }
  3135. //---------------------------------------------------------------------------
  3136. TDateTime __fastcall TSessionData::GetTimeoutDT()
  3137. {
  3138. return SecToDateTime(Timeout);
  3139. }
  3140. //---------------------------------------------------------------------------
  3141. void __fastcall TSessionData::SetTimeout(int value)
  3142. {
  3143. SET_SESSION_PROPERTY(Timeout);
  3144. }
  3145. //---------------------------------------------------------------------------
  3146. void __fastcall TSessionData::SetFSProtocol(TFSProtocol value)
  3147. {
  3148. SET_SESSION_PROPERTY(FSProtocol);
  3149. }
  3150. //---------------------------------------------------------------------
  3151. UnicodeString __fastcall TSessionData::GetFSProtocolStr()
  3152. {
  3153. DebugAssert(FSProtocol >= 0 && FSProtocol < FSPROTOCOL_COUNT);
  3154. return FSProtocolNames[FSProtocol];
  3155. }
  3156. //---------------------------------------------------------------------------
  3157. void __fastcall TSessionData::SetDetectReturnVar(bool value)
  3158. {
  3159. if (value != DetectReturnVar)
  3160. {
  3161. ReturnVar = value ? L"" : L"$?";
  3162. }
  3163. }
  3164. //---------------------------------------------------------------------------
  3165. bool __fastcall TSessionData::GetDetectReturnVar()
  3166. {
  3167. return ReturnVar.IsEmpty();
  3168. }
  3169. //---------------------------------------------------------------------------
  3170. void __fastcall TSessionData::SetDefaultShell(bool value)
  3171. {
  3172. if (value != DefaultShell)
  3173. {
  3174. Shell = value ? L"" : L"/bin/bash";
  3175. }
  3176. }
  3177. //---------------------------------------------------------------------------
  3178. bool __fastcall TSessionData::GetDefaultShell()
  3179. {
  3180. return Shell.IsEmpty();
  3181. }
  3182. //---------------------------------------------------------------------------
  3183. void __fastcall TSessionData::SetPuttyProtocol(UnicodeString value)
  3184. {
  3185. SET_SESSION_PROPERTY(PuttyProtocol);
  3186. }
  3187. //---------------------------------------------------------------------
  3188. UnicodeString __fastcall TSessionData::GetNormalizedPuttyProtocol() const
  3189. {
  3190. return DefaultStr(PuttyProtocol, PuttySshProtocol);
  3191. }
  3192. //---------------------------------------------------------------------
  3193. void __fastcall TSessionData::SetPingIntervalDT(TDateTime value)
  3194. {
  3195. unsigned short hour, min, sec, msec;
  3196. value.DecodeTime(&hour, &min, &sec, &msec);
  3197. PingInterval = ((int)hour)*SecsPerHour + ((int)min)*SecsPerMin + sec;
  3198. }
  3199. //---------------------------------------------------------------------------
  3200. TDateTime __fastcall TSessionData::GetPingIntervalDT()
  3201. {
  3202. return SecToDateTime(PingInterval);
  3203. }
  3204. //---------------------------------------------------------------------------
  3205. void __fastcall TSessionData::SetPingType(TPingType value)
  3206. {
  3207. SET_SESSION_PROPERTY(PingType);
  3208. }
  3209. //---------------------------------------------------------------------------
  3210. void __fastcall TSessionData::SetAddressFamily(TAddressFamily value)
  3211. {
  3212. SET_SESSION_PROPERTY(AddressFamily);
  3213. }
  3214. //---------------------------------------------------------------------------
  3215. void __fastcall TSessionData::SetRekeyData(UnicodeString value)
  3216. {
  3217. SET_SESSION_PROPERTY(RekeyData);
  3218. }
  3219. //---------------------------------------------------------------------------
  3220. void __fastcall TSessionData::SetRekeyTime(unsigned int value)
  3221. {
  3222. SET_SESSION_PROPERTY(RekeyTime);
  3223. }
  3224. //---------------------------------------------------------------------
  3225. UnicodeString __fastcall TSessionData::GetDefaultSessionName()
  3226. {
  3227. UnicodeString Result;
  3228. if (IsLocalBrowser)
  3229. {
  3230. // See also TScpCommanderForm::GetLocalBrowserSessionTitle
  3231. UnicodeString Path1 = ExtractShortName(LocalDirectory, false);
  3232. UnicodeString Path2 = ExtractShortName(OtherLocalDirectory, false);
  3233. Result = Path1 + TitleSeparator + Path2;
  3234. }
  3235. else if (!HostName.IsEmpty() && !UserName.IsEmpty())
  3236. {
  3237. // If we ever choose to include port number,
  3238. // we have to escape IPv6 literals in HostName
  3239. Result = FORMAT(L"%s@%s", (UserName, HostName));
  3240. }
  3241. else if (!HostName.IsEmpty())
  3242. {
  3243. Result = HostName;
  3244. }
  3245. else
  3246. {
  3247. Result = L"session";
  3248. }
  3249. Result = MakeValidName(Result);
  3250. return Result;
  3251. }
  3252. //---------------------------------------------------------------------
  3253. UnicodeString __fastcall TSessionData::GetNameWithoutHiddenPrefix()
  3254. {
  3255. UnicodeString Result = Name;
  3256. if (Hidden)
  3257. {
  3258. Result = Result.SubString(TNamedObjectList::HiddenPrefix.Length() + 1, Result.Length() - TNamedObjectList::HiddenPrefix.Length());
  3259. }
  3260. return Result;
  3261. }
  3262. //---------------------------------------------------------------------
  3263. bool __fastcall TSessionData::HasSessionName()
  3264. {
  3265. return (!GetNameWithoutHiddenPrefix().IsEmpty() && (Name != DefaultName));
  3266. }
  3267. //---------------------------------------------------------------------
  3268. UnicodeString __fastcall TSessionData::GetSessionName()
  3269. {
  3270. UnicodeString Result;
  3271. if (HasSessionName())
  3272. {
  3273. Result = GetNameWithoutHiddenPrefix();
  3274. }
  3275. else
  3276. {
  3277. Result = DefaultSessionName;
  3278. }
  3279. return Result;
  3280. }
  3281. //---------------------------------------------------------------------
  3282. bool __fastcall TSessionData::IsSecure()
  3283. {
  3284. bool Result;
  3285. switch (FSProtocol)
  3286. {
  3287. case fsSCPonly:
  3288. case fsSFTP:
  3289. case fsSFTPonly:
  3290. Result = true;
  3291. break;
  3292. case fsFTP:
  3293. case fsWebDAV:
  3294. case fsS3:
  3295. Result = (Ftps != ftpsNone);
  3296. break;
  3297. default:
  3298. DebugFail();
  3299. break;
  3300. }
  3301. return Result;
  3302. }
  3303. //---------------------------------------------------------------------
  3304. UnicodeString __fastcall TSessionData::GetProtocolUrl(bool HttpForWebDAV)
  3305. {
  3306. UnicodeString Url;
  3307. switch (FSProtocol)
  3308. {
  3309. case fsSCPonly:
  3310. Url = ScpProtocol;
  3311. break;
  3312. default:
  3313. DebugFail();
  3314. // fallback
  3315. case fsSFTP:
  3316. case fsSFTPonly:
  3317. Url = SftpProtocol;
  3318. break;
  3319. case fsFTP:
  3320. if (Ftps == ftpsImplicit)
  3321. {
  3322. Url = FtpsProtocol;
  3323. }
  3324. else if ((Ftps == ftpsExplicitTls) || (Ftps == ftpsExplicitSsl))
  3325. {
  3326. Url = FtpesProtocol;
  3327. }
  3328. else
  3329. {
  3330. Url = FtpProtocol;
  3331. }
  3332. break;
  3333. case fsWebDAV:
  3334. if (HttpForWebDAV)
  3335. {
  3336. if (Ftps == ftpsImplicit)
  3337. {
  3338. Url = HttpsProtocol;
  3339. }
  3340. else
  3341. {
  3342. Url = HttpProtocol;
  3343. }
  3344. }
  3345. else
  3346. {
  3347. if (Ftps == ftpsImplicit)
  3348. {
  3349. Url = WebDAVSProtocol;
  3350. }
  3351. else
  3352. {
  3353. Url = WebDAVProtocol;
  3354. }
  3355. }
  3356. break;
  3357. case fsS3:
  3358. if (Ftps == ftpsImplicit)
  3359. {
  3360. Url = S3Protocol;
  3361. }
  3362. else
  3363. {
  3364. Url = S3PlainProtocol;
  3365. }
  3366. break;
  3367. }
  3368. Url += ProtocolSeparator;
  3369. return Url;
  3370. }
  3371. //---------------------------------------------------------------------
  3372. bool HasIP6LiteralBrackets(const UnicodeString & HostName)
  3373. {
  3374. return
  3375. (HostName.Length() >= 2) &&
  3376. (HostName[1] == L'[') &&
  3377. (HostName[HostName.Length()] == L']');
  3378. }
  3379. //---------------------------------------------------------------------
  3380. UnicodeString StripIP6LiteralBrackets(const UnicodeString & HostName)
  3381. {
  3382. UnicodeString Result = HostName;
  3383. if (DebugAlwaysTrue(HasIP6LiteralBrackets(Result)))
  3384. {
  3385. Result = Result.SubString(2, Result.Length() - 2);
  3386. }
  3387. return Result;
  3388. }
  3389. //---------------------------------------------------------------------
  3390. bool __fastcall IsIPv6Literal(const UnicodeString & HostName)
  3391. {
  3392. UnicodeString Buf = HostName;
  3393. if (HasIP6LiteralBrackets(Buf))
  3394. {
  3395. Buf = StripIP6LiteralBrackets(Buf);
  3396. }
  3397. int Colons = 0;
  3398. bool Result = true;
  3399. for (int Index = 1; Result && (Index <= Buf.Length()); Index++)
  3400. {
  3401. wchar_t C = Buf[Index];
  3402. if (C == L'%')
  3403. {
  3404. break;
  3405. }
  3406. else if (C == L':')
  3407. {
  3408. Colons++;
  3409. }
  3410. else
  3411. {
  3412. Result = IsHex(C);
  3413. }
  3414. }
  3415. Result = Result && (Colons >= 2);
  3416. return Result;
  3417. }
  3418. //---------------------------------------------------------------------
  3419. UnicodeString __fastcall EscapeIPv6Literal(const UnicodeString & IP)
  3420. {
  3421. UnicodeString Result = IP;
  3422. if (!HasIP6LiteralBrackets(Result))
  3423. {
  3424. Result = L"[" + IP + L"]";
  3425. }
  3426. return Result;
  3427. }
  3428. //---------------------------------------------------------------------
  3429. TStrings * __fastcall TSessionData::GetRawSettingsForUrl()
  3430. {
  3431. std::unique_ptr<TSessionData> FactoryDefaults(new TSessionData(L""));
  3432. std::unique_ptr<TSessionData> SessionData(Clone());
  3433. SessionData->FSProtocol = FactoryDefaults->FSProtocol;
  3434. SessionData->HostName = FactoryDefaults->HostName;
  3435. SessionData->PortNumber = FactoryDefaults->PortNumber;
  3436. SessionData->UserName = FactoryDefaults->UserName;
  3437. SessionData->Password = FactoryDefaults->Password;
  3438. SessionData->Ftps = FactoryDefaults->Ftps;
  3439. SessionData->HostKey = FactoryDefaults->HostKey;
  3440. SessionData->CopyNonCoreData(FactoryDefaults.get());
  3441. // Cannot be decided in SaveToOptions as it does not have HostName and UserName, so it cannot calculate DefaultSessionName.
  3442. bool SaveName = HasSessionName() && (Name != DefaultSessionName);
  3443. return SessionData->SaveToOptions(FactoryDefaults.get(), SaveName, false);
  3444. }
  3445. //---------------------------------------------------------------------
  3446. bool __fastcall TSessionData::HasRawSettingsForUrl()
  3447. {
  3448. std::unique_ptr<TStrings> RawSettings(GetRawSettingsForUrl());
  3449. return (RawSettings->Count > 0);
  3450. }
  3451. //---------------------------------------------------------------------
  3452. UnicodeString __fastcall TSessionData::GenerateSessionUrl(unsigned int Flags)
  3453. {
  3454. UnicodeString Url;
  3455. if (FLAGSET(Flags, sufSpecific))
  3456. {
  3457. Url += WinSCPProtocolPrefix;
  3458. }
  3459. Url += GetProtocolUrl(FLAGSET(Flags, sufHttpForWebDAV));
  3460. // Add username only if it was somehow explicitly specified (so not with S3CredentialsEnv), but if it was, add it in the expanded form.
  3461. // For scripting, we might use unexpanded form (keeping the environment variables),
  3462. // but for consistency with code generation (where explicit expansion code would need to be added), we do not.
  3463. if (FLAGSET(Flags, sufUserName) && !UserName.IsEmpty())
  3464. {
  3465. Url += EncodeUrlString(UserNameExpanded);
  3466. if (FLAGSET(Flags, sufPassword) && !Password.IsEmpty())
  3467. {
  3468. Url += L":" + EncodeUrlString(NormalizeString(Password));
  3469. }
  3470. if (FLAGSET(Flags, sufHostKey) && !HostKey.IsEmpty())
  3471. {
  3472. UnicodeString KeyName;
  3473. UnicodeString Fingerprint = HostKey;
  3474. NormalizeFingerprint(Fingerprint, KeyName);
  3475. UnicodeString S = Fingerprint;
  3476. if (!KeyName.IsEmpty())
  3477. {
  3478. S = KeyName + NormalizedFingerprintSeparator + S;
  3479. }
  3480. S = Base64ToUrlSafe(S); // Noop for MD5 (both in SSH host keys and TLS/SSL)
  3481. S = MD5ToUrlSafe(S); // TLS/SSL fingerprints
  3482. UnicodeString S2 = EncodeUrlString(S);
  3483. DebugAssert(S2 == S2); // There should be nothing left for encoding
  3484. Url +=
  3485. UnicodeString(UrlParamSeparator) + UrlHostKeyParamName +
  3486. UnicodeString(UrlParamValueSeparator) + S2;
  3487. }
  3488. if (FLAGSET(Flags, sufRawSettings))
  3489. {
  3490. std::unique_ptr<TStrings> RawSettings(GetRawSettingsForUrl());
  3491. for (int Index = 0; Index < RawSettings->Count; Index++)
  3492. {
  3493. Url +=
  3494. UnicodeString(UrlParamSeparator) +
  3495. UrlRawSettingsParamNamePrefix + EncodeUrlString(LowerCase(RawSettings->Names[Index])) +
  3496. UnicodeString(UrlParamValueSeparator) + EncodeUrlString(RawSettings->ValueFromIndex[Index]);
  3497. }
  3498. }
  3499. Url += L"@";
  3500. }
  3501. DebugAssert(!HostNameExpanded.IsEmpty());
  3502. if (IsIPv6Literal(HostNameExpanded))
  3503. {
  3504. Url += EscapeIPv6Literal(HostNameExpanded);
  3505. }
  3506. else
  3507. {
  3508. Url += EncodeUrlString(HostNameExpanded);
  3509. }
  3510. if (PortNumber != GetDefaultPort())
  3511. {
  3512. Url += L":" + IntToStr(PortNumber);
  3513. }
  3514. Url += L"/";
  3515. return Url;
  3516. }
  3517. //---------------------------------------------------------------------
  3518. UnicodeString ScriptCommandOpenLink(TraceInitStr(ScriptCommandLink(L"open")));
  3519. //---------------------------------------------------------------------
  3520. void __fastcall TSessionData::AddSwitch(
  3521. UnicodeString & Result, const UnicodeString & Name, bool Rtf)
  3522. {
  3523. Result += RtfSwitch(Name, ScriptCommandOpenLink, Rtf);
  3524. }
  3525. //---------------------------------------------------------------------
  3526. void __fastcall TSessionData::AddSwitch(
  3527. UnicodeString & Result, const UnicodeString & Name, const UnicodeString & Value, bool Rtf)
  3528. {
  3529. Result += RtfSwitch(Name, ScriptCommandOpenLink, Value, Rtf);
  3530. }
  3531. //---------------------------------------------------------------------
  3532. void __fastcall TSessionData::AddSwitch(
  3533. UnicodeString & Result, const UnicodeString & Name, int Value, bool Rtf)
  3534. {
  3535. Result += RtfSwitch(Name, ScriptCommandOpenLink, Value, Rtf);
  3536. }
  3537. //---------------------------------------------------------------------
  3538. void __fastcall TSessionData::LookupLastFingerprint()
  3539. {
  3540. UnicodeString FingerprintType;
  3541. if (IsSshProtocol(FSProtocol))
  3542. {
  3543. FingerprintType = SshFingerprintType;
  3544. }
  3545. else if (Ftps != ftpsNone)
  3546. {
  3547. FingerprintType = TlsFingerprintType;
  3548. }
  3549. if (!FingerprintType.IsEmpty())
  3550. {
  3551. HostKey = Configuration->LastFingerprint(SiteKey, FingerprintType);
  3552. }
  3553. if (Tunnel)
  3554. {
  3555. // not used anyway
  3556. int TunnelPortNumber = std::max(TunnelLocalPortNumber, Configuration->TunnelLocalPortNumberLow);
  3557. std::unique_ptr<TSessionData> TunnelData(CreateTunnelData(TunnelPortNumber));
  3558. TunnelHostKey = Configuration->LastFingerprint(TunnelData->SiteKey, SshFingerprintType);
  3559. }
  3560. }
  3561. //---------------------------------------------------------------------
  3562. UnicodeString __fastcall TSessionData::GenerateOpenCommandArgs(bool Rtf)
  3563. {
  3564. std::unique_ptr<TSessionData> FactoryDefaults(new TSessionData(L""));
  3565. std::unique_ptr<TSessionData> SessionData(new TSessionData(L""));
  3566. SessionData->Assign(this);
  3567. UnicodeString Result = SessionData->GenerateSessionUrl(sufOpen);
  3568. // Before we reset the FSProtocol
  3569. bool AUsesSsh = SessionData->UsesSsh;
  3570. // SFTP-only is not reflected by the protocol prefix, we have to use rawsettings for that
  3571. if (SessionData->FSProtocol != fsSFTPonly)
  3572. {
  3573. SessionData->FSProtocol = FactoryDefaults->FSProtocol;
  3574. }
  3575. SessionData->HostName = FactoryDefaults->HostName;
  3576. SessionData->PortNumber = FactoryDefaults->PortNumber;
  3577. SessionData->UserName = FactoryDefaults->UserName;
  3578. SessionData->Password = FactoryDefaults->Password;
  3579. SessionData->CopyNonCoreData(FactoryDefaults.get());
  3580. SessionData->Ftps = FactoryDefaults->Ftps;
  3581. if (SessionData->HostKey != FactoryDefaults->HostKey)
  3582. {
  3583. UnicodeString SwitchName = AUsesSsh ? L"hostkey" : L"certificate";
  3584. AddSwitch(Result, SwitchName, SessionData->HostKey, Rtf);
  3585. SessionData->HostKey = FactoryDefaults->HostKey;
  3586. }
  3587. if (SessionData->PublicKeyFile != FactoryDefaults->PublicKeyFile)
  3588. {
  3589. AddSwitch(Result, PRIVATEKEY_SWITCH, SessionData->PublicKeyFile, Rtf);
  3590. SessionData->PublicKeyFile = FactoryDefaults->PublicKeyFile;
  3591. }
  3592. if (SessionData->TlsCertificateFile != FactoryDefaults->TlsCertificateFile)
  3593. {
  3594. AddSwitch(Result, L"clientcert", SessionData->TlsCertificateFile, Rtf);
  3595. SessionData->TlsCertificateFile = FactoryDefaults->TlsCertificateFile;
  3596. }
  3597. if (SessionData->Passphrase != FactoryDefaults->Passphrase)
  3598. {
  3599. AddSwitch(Result, PassphraseOption, SessionData->Passphrase, Rtf);
  3600. SessionData->Passphrase = FactoryDefaults->Passphrase;
  3601. }
  3602. if (SessionData->FtpPasvMode != FactoryDefaults->FtpPasvMode)
  3603. {
  3604. AddSwitch(Result, L"passive", SessionData->FtpPasvMode ? 1 : 0, Rtf);
  3605. SessionData->FtpPasvMode = FactoryDefaults->FtpPasvMode;
  3606. }
  3607. if (SessionData->Timeout != FactoryDefaults->Timeout)
  3608. {
  3609. AddSwitch(Result, L"timeout", SessionData->Timeout, Rtf);
  3610. SessionData->Timeout = FactoryDefaults->Timeout;
  3611. }
  3612. std::unique_ptr<TStrings> RawSettings(SessionData->SaveToOptions(FactoryDefaults.get(), false, false));
  3613. if (RawSettings->Count > 0)
  3614. {
  3615. AddSwitch(Result, RawSettingsOption, Rtf);
  3616. Result += StringsToParams(RawSettings.get());
  3617. }
  3618. return Result;
  3619. }
  3620. //---------------------------------------------------------------------
  3621. UnicodeString SessionOptionsClassName(L"SessionOptions");
  3622. //---------------------------------------------------------------------
  3623. void __fastcall TSessionData::AddAssemblyProperty(
  3624. UnicodeString & Result, TAssemblyLanguage Language,
  3625. const UnicodeString & Name, const UnicodeString & Type,
  3626. const UnicodeString & Member)
  3627. {
  3628. Result += AssemblyProperty(Language, SessionOptionsClassName, Name, Type, Member, false);
  3629. }
  3630. //---------------------------------------------------------------------
  3631. void __fastcall TSessionData::AddAssemblyProperty(
  3632. UnicodeString & Result, TAssemblyLanguage Language,
  3633. const UnicodeString & Name, const UnicodeString & Value)
  3634. {
  3635. Result += AssemblyProperty(Language, SessionOptionsClassName, Name, Value, false);
  3636. }
  3637. //---------------------------------------------------------------------
  3638. void __fastcall TSessionData::AddAssemblyProperty(
  3639. UnicodeString & Result, TAssemblyLanguage Language,
  3640. const UnicodeString & Name, int Value)
  3641. {
  3642. Result += AssemblyProperty(Language, SessionOptionsClassName, Name, Value, false);
  3643. }
  3644. //---------------------------------------------------------------------
  3645. void __fastcall TSessionData::AddAssemblyProperty(
  3646. UnicodeString & Result, TAssemblyLanguage Language,
  3647. const UnicodeString & Name, bool Value)
  3648. {
  3649. Result += AssemblyProperty(Language, SessionOptionsClassName, Name, Value, false);
  3650. }
  3651. //---------------------------------------------------------------------
  3652. void __fastcall TSessionData::GenerateAssemblyCode(
  3653. TAssemblyLanguage Language, UnicodeString & Head, UnicodeString & Tail, int & Indent)
  3654. {
  3655. std::unique_ptr<TSessionData> FactoryDefaults(new TSessionData(L""));
  3656. std::unique_ptr<TSessionData> SessionData(Clone());
  3657. switch (Language)
  3658. {
  3659. case alCSharp:
  3660. case alVBNET:
  3661. // noop
  3662. break;
  3663. case alPowerShell:
  3664. Head +=
  3665. AssemblyCommentLine(Language, LoadStr(CODE_PS_ADD_TYPE)) +
  3666. RtfKeyword(L"Add-Type") + RtfText(" -Path ") + AssemblyString(Language, "WinSCPnet.dll") + RtfPara +
  3667. RtfPara;
  3668. break;
  3669. default:
  3670. DebugFail();
  3671. break;
  3672. }
  3673. Head +=
  3674. AssemblyCommentLine(Language, LoadStr(CODE_SESSION_OPTIONS)) +
  3675. AssemblyNewClassInstanceStart(Language, SessionOptionsClassName, false);
  3676. UnicodeString ProtocolMember;
  3677. switch (SessionData->FSProtocol)
  3678. {
  3679. case fsSCPonly:
  3680. ProtocolMember = "Scp";
  3681. break;
  3682. default:
  3683. DebugFail();
  3684. // fallback
  3685. case fsSFTP:
  3686. case fsSFTPonly:
  3687. ProtocolMember = "Sftp";
  3688. break;
  3689. case fsFTP:
  3690. ProtocolMember = "Ftp";
  3691. break;
  3692. case fsWebDAV:
  3693. ProtocolMember = "Webdav";
  3694. break;
  3695. case fsS3:
  3696. ProtocolMember = "S3";
  3697. break;
  3698. }
  3699. // Before we reset the FSProtocol
  3700. bool AUsesSsh = SessionData->UsesSsh;
  3701. // Protocol is set unconditionally, we want even the default SFTP
  3702. AddAssemblyProperty(Head, Language, L"Protocol", L"Protocol", ProtocolMember);
  3703. // SFTP-only is not reflected by the protocol prefix, we have to use rawsettings for that
  3704. if (SessionData->FSProtocol != fsSFTPonly)
  3705. {
  3706. SessionData->FSProtocol = FactoryDefaults->FSProtocol;
  3707. }
  3708. if (SessionData->HostName != FactoryDefaults->HostName)
  3709. {
  3710. AddAssemblyProperty(Head, Language, L"HostName", HostName);
  3711. SessionData->HostName = FactoryDefaults->HostName;
  3712. }
  3713. int ADefaultPort = GetDefaultPort();
  3714. if (SessionData->PortNumber != ADefaultPort)
  3715. {
  3716. AddAssemblyProperty(Head, Language, L"PortNumber", PortNumber);
  3717. }
  3718. SessionData->PortNumber = FactoryDefaults->PortNumber;
  3719. if (SessionData->UserName != FactoryDefaults->UserName)
  3720. {
  3721. AddAssemblyProperty(Head, Language, L"UserName", UserName);
  3722. SessionData->UserName = FactoryDefaults->UserName;
  3723. }
  3724. if (SessionData->Password != FactoryDefaults->Password)
  3725. {
  3726. AddAssemblyProperty(Head, Language, L"Password", NormalizeString(Password));
  3727. SessionData->Password = FactoryDefaults->Password;
  3728. }
  3729. SessionData->CopyNonCoreData(FactoryDefaults.get());
  3730. TFtps DefaultFtps = FactoryDefaults->Ftps;
  3731. if (FSProtocol == fsS3)
  3732. {
  3733. DefaultFtps = ftpsImplicit;
  3734. }
  3735. if (SessionData->Ftps != DefaultFtps)
  3736. {
  3737. // SessionData->FSProtocol is reset already
  3738. switch (FSProtocol)
  3739. {
  3740. case fsFTP:
  3741. {
  3742. UnicodeString FtpSecureMember;
  3743. switch (SessionData->Ftps)
  3744. {
  3745. case ftpsNone:
  3746. DebugFail();
  3747. FtpSecureMember = L"None";
  3748. break;
  3749. case ftpsImplicit:
  3750. FtpSecureMember = L"Implicit";
  3751. break;
  3752. case ftpsExplicitTls:
  3753. case ftpsExplicitSsl:
  3754. FtpSecureMember = L"Explicit";
  3755. break;
  3756. default:
  3757. DebugFail();
  3758. break;
  3759. }
  3760. AddAssemblyProperty(Head, Language, L"FtpSecure", L"FtpSecure", FtpSecureMember);
  3761. }
  3762. break;
  3763. case fsWebDAV:
  3764. case fsS3:
  3765. AddAssemblyProperty(Head, Language, L"Secure", (SessionData->Ftps != ftpsNone));
  3766. break;
  3767. default:
  3768. DebugFail();
  3769. break;
  3770. }
  3771. }
  3772. SessionData->Ftps = FactoryDefaults->Ftps;
  3773. if (SessionData->HostKey != FactoryDefaults->HostKey)
  3774. {
  3775. UnicodeString PropertyName = AUsesSsh ? L"SshHostKeyFingerprint" : L"TlsHostCertificateFingerprint";
  3776. AddAssemblyProperty(Head, Language, PropertyName, SessionData->HostKey);
  3777. SessionData->HostKey = FactoryDefaults->HostKey;
  3778. }
  3779. if (SessionData->PublicKeyFile != FactoryDefaults->PublicKeyFile)
  3780. {
  3781. AddAssemblyProperty(Head, Language, L"SshPrivateKeyPath", SessionData->PublicKeyFile);
  3782. SessionData->PublicKeyFile = FactoryDefaults->PublicKeyFile;
  3783. }
  3784. if (SessionData->TlsCertificateFile != FactoryDefaults->TlsCertificateFile)
  3785. {
  3786. AddAssemblyProperty(Head, Language, L"TlsClientCertificatePath", SessionData->TlsCertificateFile);
  3787. SessionData->TlsCertificateFile = FactoryDefaults->TlsCertificateFile;
  3788. }
  3789. if (SessionData->Passphrase != FactoryDefaults->Passphrase)
  3790. {
  3791. AddAssemblyProperty(Head, Language, L"PrivateKeyPassphrase", SessionData->Passphrase);
  3792. SessionData->Passphrase = FactoryDefaults->Passphrase;
  3793. }
  3794. if (SessionData->FtpPasvMode != FactoryDefaults->FtpPasvMode)
  3795. {
  3796. AddAssemblyProperty(Head, Language, L"FtpMode", L"FtpMode", (SessionData->FtpPasvMode ? L"Passive" : L"Active"));
  3797. SessionData->FtpPasvMode = FactoryDefaults->FtpPasvMode;
  3798. }
  3799. if (SessionData->Timeout != FactoryDefaults->Timeout)
  3800. {
  3801. AddAssemblyProperty(Head, Language, L"TimeoutInMilliseconds", SessionData->Timeout * 1000);
  3802. SessionData->Timeout = FactoryDefaults->Timeout;
  3803. }
  3804. Head += AssemblyNewClassInstanceEnd(Language, false);
  3805. std::unique_ptr<TStrings> RawSettings(SessionData->SaveToOptions(FactoryDefaults.get(), false, false));
  3806. UnicodeString SessionOptionsVariableName = AssemblyVariableName(Language, SessionOptionsClassName);
  3807. if (RawSettings->Count > 0)
  3808. {
  3809. Head +=
  3810. RtfPara +
  3811. AssemblyAddRawSettings(Language, RawSettings.get(), SessionOptionsClassName, L"AddRawSettings");
  3812. }
  3813. Head += RtfPara;
  3814. UnicodeString Indentation = L" ";
  3815. UnicodeString SessionVariableName = AssemblyVariableName(Language, SessionClassName);
  3816. UnicodeString RtfSessionClass = RtfLibraryClass(SessionClassName);
  3817. UnicodeString RtfSessionOpenMethod = RtfLibraryMethod(SessionClassName, L"Open", false);
  3818. UnicodeString NewSessionInstance = AssemblyNewClassInstance(Language, SessionClassName, false);
  3819. UnicodeString OpenCall =
  3820. Indentation + AssemblyCommentLine(Language, LoadStr(CODE_CONNECT)) +
  3821. Indentation + RtfText(SessionVariableName + L".") + RtfSessionOpenMethod + RtfText(L"(" + SessionOptionsVariableName + L")") +
  3822. AssemblyStatementSeparator(Language) + RtfPara;
  3823. switch (Language)
  3824. {
  3825. case alCSharp:
  3826. Head +=
  3827. RtfKeyword(L"using") + RtfText(" (") + NewSessionInstance + RtfText(L"())") + RtfPara +
  3828. RtfText(L"{") + RtfPara +
  3829. OpenCall;
  3830. Tail =
  3831. RtfText(L"}") + RtfPara;
  3832. break;
  3833. case alVBNET:
  3834. Head +=
  3835. RtfKeyword(L"Using") + RtfText(L" ") + NewSessionInstance + RtfPara +
  3836. OpenCall;
  3837. Tail =
  3838. RtfKeyword(L"End Using") + RtfPara;
  3839. break;
  3840. case alPowerShell:
  3841. Head +=
  3842. NewSessionInstance + RtfPara +
  3843. RtfPara +
  3844. RtfKeyword(L"try") + RtfPara +
  3845. RtfText(L"{") + RtfPara +
  3846. OpenCall;
  3847. Tail =
  3848. RtfText(L"}") + RtfPara +
  3849. RtfKeyword(L"finally") + RtfPara +
  3850. RtfText(L"{") + RtfPara +
  3851. RtfText(Indentation + SessionVariableName + L".") +
  3852. RtfLibraryMethod(SessionClassName, L"Dispose", false) + RtfText(L"()") + RtfPara +
  3853. RtfText(L"}") + RtfPara;
  3854. break;
  3855. }
  3856. Head += RtfPara;
  3857. Indent = 4; // the same for all languages so far
  3858. }
  3859. //---------------------------------------------------------------------
  3860. void __fastcall TSessionData::SetTimeDifference(TDateTime value)
  3861. {
  3862. SET_SESSION_PROPERTY(TimeDifference);
  3863. }
  3864. //---------------------------------------------------------------------
  3865. void __fastcall TSessionData::SetTimeDifferenceAuto(bool value)
  3866. {
  3867. SET_SESSION_PROPERTY(TimeDifferenceAuto);
  3868. }
  3869. //---------------------------------------------------------------------
  3870. void __fastcall TSessionData::SetLocalDirectory(UnicodeString value)
  3871. {
  3872. SET_SESSION_PROPERTY(LocalDirectory);
  3873. }
  3874. //---------------------------------------------------------------------
  3875. void __fastcall TSessionData::SetOtherLocalDirectory(const UnicodeString & value)
  3876. {
  3877. SET_SESSION_PROPERTY(OtherLocalDirectory);
  3878. }
  3879. //---------------------------------------------------------------------
  3880. UnicodeString __fastcall TSessionData::GetLocalDirectoryExpanded()
  3881. {
  3882. return ExpandFileName(::ExpandEnvironmentVariables(LocalDirectory));
  3883. }
  3884. //---------------------------------------------------------------------
  3885. void __fastcall TSessionData::SetRemoteDirectory(UnicodeString value)
  3886. {
  3887. SET_SESSION_PROPERTY(RemoteDirectory);
  3888. }
  3889. //---------------------------------------------------------------------
  3890. void __fastcall TSessionData::SetSynchronizeBrowsing(bool value)
  3891. {
  3892. SET_SESSION_PROPERTY(SynchronizeBrowsing);
  3893. }
  3894. //---------------------------------------------------------------------
  3895. void __fastcall TSessionData::SetUpdateDirectories(bool value)
  3896. {
  3897. SET_SESSION_PROPERTY(UpdateDirectories);
  3898. }
  3899. //---------------------------------------------------------------------
  3900. void __fastcall TSessionData::SetCacheDirectories(bool value)
  3901. {
  3902. SET_SESSION_PROPERTY(CacheDirectories);
  3903. }
  3904. //---------------------------------------------------------------------
  3905. void __fastcall TSessionData::SetCacheDirectoryChanges(bool value)
  3906. {
  3907. SET_SESSION_PROPERTY(CacheDirectoryChanges);
  3908. }
  3909. //---------------------------------------------------------------------
  3910. void __fastcall TSessionData::SetPreserveDirectoryChanges(bool value)
  3911. {
  3912. SET_SESSION_PROPERTY(PreserveDirectoryChanges);
  3913. }
  3914. //---------------------------------------------------------------------
  3915. void __fastcall TSessionData::SetResolveSymlinks(bool value)
  3916. {
  3917. SET_SESSION_PROPERTY(ResolveSymlinks);
  3918. }
  3919. //---------------------------------------------------------------------
  3920. void __fastcall TSessionData::SetFollowDirectorySymlinks(bool value)
  3921. {
  3922. SET_SESSION_PROPERTY(FollowDirectorySymlinks);
  3923. }
  3924. //---------------------------------------------------------------------------
  3925. void __fastcall TSessionData::SetDSTMode(TDSTMode value)
  3926. {
  3927. SET_SESSION_PROPERTY(DSTMode);
  3928. }
  3929. //---------------------------------------------------------------------------
  3930. void __fastcall TSessionData::SetDeleteToRecycleBin(bool value)
  3931. {
  3932. SET_SESSION_PROPERTY(DeleteToRecycleBin);
  3933. }
  3934. //---------------------------------------------------------------------------
  3935. void __fastcall TSessionData::SetOverwrittenToRecycleBin(bool value)
  3936. {
  3937. SET_SESSION_PROPERTY(OverwrittenToRecycleBin);
  3938. }
  3939. //---------------------------------------------------------------------------
  3940. void __fastcall TSessionData::SetRecycleBinPath(UnicodeString value)
  3941. {
  3942. SET_SESSION_PROPERTY(RecycleBinPath);
  3943. }
  3944. //---------------------------------------------------------------------------
  3945. void __fastcall TSessionData::SetPostLoginCommands(UnicodeString value)
  3946. {
  3947. SET_SESSION_PROPERTY(PostLoginCommands);
  3948. }
  3949. //---------------------------------------------------------------------
  3950. void __fastcall TSessionData::SetSpecial(bool value)
  3951. {
  3952. SET_SESSION_PROPERTY(Special);
  3953. }
  3954. //---------------------------------------------------------------------------
  3955. void __fastcall TSessionData::SetScp1Compatibility(bool value)
  3956. {
  3957. SET_SESSION_PROPERTY(Scp1Compatibility);
  3958. }
  3959. //---------------------------------------------------------------------
  3960. void __fastcall TSessionData::SetTcpNoDelay(bool value)
  3961. {
  3962. SET_SESSION_PROPERTY(TcpNoDelay);
  3963. }
  3964. //---------------------------------------------------------------------
  3965. void __fastcall TSessionData::SetSendBuf(int value)
  3966. {
  3967. SET_SESSION_PROPERTY(SendBuf);
  3968. }
  3969. //---------------------------------------------------------------------
  3970. void __fastcall TSessionData::SetSourceAddress(const UnicodeString & value)
  3971. {
  3972. SET_SESSION_PROPERTY(SourceAddress);
  3973. }
  3974. //---------------------------------------------------------------------
  3975. void __fastcall TSessionData::SetProtocolFeatures(const UnicodeString & value)
  3976. {
  3977. SET_SESSION_PROPERTY(ProtocolFeatures);
  3978. }
  3979. //---------------------------------------------------------------------
  3980. void __fastcall TSessionData::SetSshSimple(bool value)
  3981. {
  3982. SET_SESSION_PROPERTY(SshSimple);
  3983. }
  3984. //---------------------------------------------------------------------
  3985. void __fastcall TSessionData::SetProxyMethod(TProxyMethod value)
  3986. {
  3987. SET_SESSION_PROPERTY(ProxyMethod);
  3988. }
  3989. //---------------------------------------------------------------------
  3990. void __fastcall TSessionData::SetProxyHost(UnicodeString value)
  3991. {
  3992. SET_SESSION_PROPERTY(ProxyHost);
  3993. }
  3994. //---------------------------------------------------------------------
  3995. void __fastcall TSessionData::SetProxyPort(int value)
  3996. {
  3997. SET_SESSION_PROPERTY(ProxyPort);
  3998. }
  3999. //---------------------------------------------------------------------
  4000. void __fastcall TSessionData::SetProxyUsername(UnicodeString value)
  4001. {
  4002. SET_SESSION_PROPERTY(ProxyUsername);
  4003. }
  4004. //---------------------------------------------------------------------
  4005. void __fastcall TSessionData::SetProxyPassword(UnicodeString avalue)
  4006. {
  4007. RawByteString value = EncryptPassword(avalue, ProxyUsername+ProxyHost);
  4008. SET_SESSION_PROPERTY(ProxyPassword);
  4009. }
  4010. //---------------------------------------------------------------------
  4011. UnicodeString __fastcall TSessionData::GetProxyPassword() const
  4012. {
  4013. return DecryptPassword(FProxyPassword, ProxyUsername+ProxyHost);
  4014. }
  4015. //---------------------------------------------------------------------
  4016. void __fastcall TSessionData::SetProxyTelnetCommand(UnicodeString value)
  4017. {
  4018. SET_SESSION_PROPERTY(ProxyTelnetCommand);
  4019. }
  4020. //---------------------------------------------------------------------
  4021. void __fastcall TSessionData::SetProxyLocalCommand(UnicodeString value)
  4022. {
  4023. SET_SESSION_PROPERTY(ProxyLocalCommand);
  4024. }
  4025. //---------------------------------------------------------------------
  4026. void __fastcall TSessionData::SetProxyDNS(TAutoSwitch value)
  4027. {
  4028. SET_SESSION_PROPERTY(ProxyDNS);
  4029. }
  4030. //---------------------------------------------------------------------
  4031. void __fastcall TSessionData::SetProxyLocalhost(bool value)
  4032. {
  4033. SET_SESSION_PROPERTY(ProxyLocalhost);
  4034. }
  4035. //---------------------------------------------------------------------
  4036. void __fastcall TSessionData::SetFtpProxyLogonType(int value)
  4037. {
  4038. SET_SESSION_PROPERTY(FtpProxyLogonType);
  4039. }
  4040. //---------------------------------------------------------------------
  4041. void __fastcall TSessionData::SetBug(TSshBug Bug, TAutoSwitch value)
  4042. {
  4043. DebugAssert(Bug >= 0 && static_cast<unsigned int>(Bug) < LENOF(FBugs));
  4044. SET_SESSION_PROPERTY(Bugs[Bug]);
  4045. }
  4046. //---------------------------------------------------------------------
  4047. TAutoSwitch __fastcall TSessionData::GetBug(TSshBug Bug) const
  4048. {
  4049. DebugAssert(Bug >= 0 && static_cast<unsigned int>(Bug) < LENOF(FBugs));
  4050. return FBugs[Bug];
  4051. }
  4052. //---------------------------------------------------------------------
  4053. void __fastcall TSessionData::SetPuttySettings(UnicodeString value)
  4054. {
  4055. SET_SESSION_PROPERTY(PuttySettings);
  4056. }
  4057. //---------------------------------------------------------------------
  4058. void __fastcall TSessionData::SetCustomParam1(UnicodeString value)
  4059. {
  4060. SET_SESSION_PROPERTY(CustomParam1);
  4061. }
  4062. //---------------------------------------------------------------------
  4063. void __fastcall TSessionData::SetCustomParam2(UnicodeString value)
  4064. {
  4065. SET_SESSION_PROPERTY(CustomParam2);
  4066. }
  4067. //---------------------------------------------------------------------
  4068. void __fastcall TSessionData::SetSFTPDownloadQueue(int value)
  4069. {
  4070. SET_SESSION_PROPERTY(SFTPDownloadQueue);
  4071. }
  4072. //---------------------------------------------------------------------
  4073. void __fastcall TSessionData::SetSFTPUploadQueue(int value)
  4074. {
  4075. SET_SESSION_PROPERTY(SFTPUploadQueue);
  4076. }
  4077. //---------------------------------------------------------------------
  4078. void __fastcall TSessionData::SetSFTPListingQueue(int value)
  4079. {
  4080. SET_SESSION_PROPERTY(SFTPListingQueue);
  4081. }
  4082. //---------------------------------------------------------------------
  4083. void __fastcall TSessionData::SetSFTPMaxVersion(int value)
  4084. {
  4085. SET_SESSION_PROPERTY(SFTPMaxVersion);
  4086. }
  4087. //---------------------------------------------------------------------
  4088. void __fastcall TSessionData::SetSFTPMaxPacketSize(unsigned long value)
  4089. {
  4090. SET_SESSION_PROPERTY(SFTPMaxPacketSize);
  4091. }
  4092. //---------------------------------------------------------------------
  4093. void __fastcall TSessionData::SetSFTPRealPath(TAutoSwitch value)
  4094. {
  4095. SET_SESSION_PROPERTY(SFTPRealPath);
  4096. }
  4097. //---------------------------------------------------------------------
  4098. void TSessionData::SetUsePosixRename(bool value)
  4099. {
  4100. SET_SESSION_PROPERTY(UsePosixRename);
  4101. }
  4102. //---------------------------------------------------------------------
  4103. void __fastcall TSessionData::SetSFTPBug(TSftpBug Bug, TAutoSwitch value)
  4104. {
  4105. DebugAssert(Bug >= 0 && static_cast<unsigned int>(Bug) < LENOF(FSFTPBugs));
  4106. SET_SESSION_PROPERTY(SFTPBugs[Bug]);
  4107. }
  4108. //---------------------------------------------------------------------
  4109. TAutoSwitch __fastcall TSessionData::GetSFTPBug(TSftpBug Bug) const
  4110. {
  4111. DebugAssert(Bug >= 0 && static_cast<unsigned int>(Bug) < LENOF(FSFTPBugs));
  4112. return FSFTPBugs[Bug];
  4113. }
  4114. //---------------------------------------------------------------------
  4115. void __fastcall TSessionData::SetSCPLsFullTime(TAutoSwitch value)
  4116. {
  4117. SET_SESSION_PROPERTY(SCPLsFullTime);
  4118. }
  4119. //---------------------------------------------------------------------------
  4120. void __fastcall TSessionData::SetColor(int value)
  4121. {
  4122. SET_SESSION_PROPERTY(Color);
  4123. }
  4124. //---------------------------------------------------------------------------
  4125. void __fastcall TSessionData::SetTunnel(bool value)
  4126. {
  4127. SET_SESSION_PROPERTY(Tunnel);
  4128. }
  4129. //---------------------------------------------------------------------
  4130. void __fastcall TSessionData::SetTunnelHostName(UnicodeString value)
  4131. {
  4132. if (FTunnelHostName != value)
  4133. {
  4134. // HostName is key for password encryption
  4135. UnicodeString XTunnelPassword = TunnelPassword;
  4136. int P = value.LastDelimiter(L"@");
  4137. if (P > 0)
  4138. {
  4139. TunnelUserName = value.SubString(1, P - 1);
  4140. value = value.SubString(P + 1, value.Length() - P);
  4141. }
  4142. FTunnelHostName = value;
  4143. Modify();
  4144. TunnelPassword = XTunnelPassword;
  4145. Shred(XTunnelPassword);
  4146. }
  4147. }
  4148. //---------------------------------------------------------------------
  4149. void __fastcall TSessionData::SetTunnelPortNumber(int value)
  4150. {
  4151. SET_SESSION_PROPERTY(TunnelPortNumber);
  4152. }
  4153. //---------------------------------------------------------------------
  4154. void __fastcall TSessionData::SetTunnelUserName(UnicodeString value)
  4155. {
  4156. // Avoid password recryption (what may popup master password prompt)
  4157. if (FTunnelUserName != value)
  4158. {
  4159. // TunnelUserName is key for password encryption
  4160. UnicodeString XTunnelPassword = TunnelPassword;
  4161. SET_SESSION_PROPERTY(TunnelUserName);
  4162. TunnelPassword = XTunnelPassword;
  4163. Shred(XTunnelPassword);
  4164. }
  4165. }
  4166. //---------------------------------------------------------------------
  4167. void __fastcall TSessionData::SetTunnelPassword(UnicodeString avalue)
  4168. {
  4169. RawByteString value = EncryptPassword(avalue, TunnelUserName+TunnelHostName);
  4170. SET_SESSION_PROPERTY(TunnelPassword);
  4171. }
  4172. //---------------------------------------------------------------------
  4173. UnicodeString __fastcall TSessionData::GetTunnelPassword() const
  4174. {
  4175. return DecryptPassword(FTunnelPassword, TunnelUserName+TunnelHostName);
  4176. }
  4177. //---------------------------------------------------------------------
  4178. void __fastcall TSessionData::SetTunnelPassphrase(UnicodeString avalue)
  4179. {
  4180. RawByteString value = EncryptPassword(avalue, TunnelPublicKeyFile);
  4181. SET_SESSION_PROPERTY(TunnelPassphrase);
  4182. }
  4183. //---------------------------------------------------------------------
  4184. UnicodeString __fastcall TSessionData::GetTunnelPassphrase() const
  4185. {
  4186. return DecryptPassword(FTunnelPassphrase, TunnelPublicKeyFile);
  4187. }
  4188. //---------------------------------------------------------------------
  4189. void __fastcall TSessionData::SetTunnelPublicKeyFile(UnicodeString value)
  4190. {
  4191. if (FTunnelPublicKeyFile != value)
  4192. {
  4193. // TunnelPublicKeyFile is key for TunnelPassphrase encryption
  4194. UnicodeString XTunnelPassphrase = TunnelPassphrase;
  4195. // StripPathQuotes should not be needed as we do not feed quotes anymore
  4196. FTunnelPublicKeyFile = StripPathQuotes(value);
  4197. Modify();
  4198. TunnelPassphrase = XTunnelPassphrase;
  4199. Shred(XTunnelPassphrase);
  4200. }
  4201. }
  4202. //---------------------------------------------------------------------
  4203. void __fastcall TSessionData::SetTunnelLocalPortNumber(int value)
  4204. {
  4205. SET_SESSION_PROPERTY(TunnelLocalPortNumber);
  4206. }
  4207. //---------------------------------------------------------------------
  4208. bool __fastcall TSessionData::GetTunnelAutoassignLocalPortNumber()
  4209. {
  4210. return (FTunnelLocalPortNumber <= 0);
  4211. }
  4212. //---------------------------------------------------------------------
  4213. void __fastcall TSessionData::SetTunnelPortFwd(UnicodeString value)
  4214. {
  4215. SET_SESSION_PROPERTY(TunnelPortFwd);
  4216. }
  4217. //---------------------------------------------------------------------
  4218. void __fastcall TSessionData::SetTunnelHostKey(UnicodeString value)
  4219. {
  4220. SET_SESSION_PROPERTY(TunnelHostKey);
  4221. }
  4222. //---------------------------------------------------------------------
  4223. void __fastcall TSessionData::SetFtpPasvMode(bool value)
  4224. {
  4225. SET_SESSION_PROPERTY(FtpPasvMode);
  4226. }
  4227. //---------------------------------------------------------------------
  4228. void __fastcall TSessionData::SetFtpForcePasvIp(TAutoSwitch value)
  4229. {
  4230. SET_SESSION_PROPERTY(FtpForcePasvIp);
  4231. }
  4232. //---------------------------------------------------------------------
  4233. void __fastcall TSessionData::SetFtpUseMlsd(TAutoSwitch value)
  4234. {
  4235. SET_SESSION_PROPERTY(FtpUseMlsd);
  4236. }
  4237. //---------------------------------------------------------------------
  4238. void __fastcall TSessionData::SetFtpAccount(UnicodeString value)
  4239. {
  4240. SET_SESSION_PROPERTY(FtpAccount);
  4241. }
  4242. //---------------------------------------------------------------------
  4243. void __fastcall TSessionData::SetFtpPingInterval(int value)
  4244. {
  4245. SET_SESSION_PROPERTY(FtpPingInterval);
  4246. }
  4247. //---------------------------------------------------------------------------
  4248. TDateTime __fastcall TSessionData::GetFtpPingIntervalDT()
  4249. {
  4250. return SecToDateTime(FtpPingInterval);
  4251. }
  4252. //---------------------------------------------------------------------------
  4253. void __fastcall TSessionData::SetFtpPingType(TFtpPingType value)
  4254. {
  4255. SET_SESSION_PROPERTY(FtpPingType);
  4256. }
  4257. //---------------------------------------------------------------------------
  4258. void __fastcall TSessionData::SetFtpTransferActiveImmediately(TAutoSwitch value)
  4259. {
  4260. SET_SESSION_PROPERTY(FtpTransferActiveImmediately);
  4261. }
  4262. //---------------------------------------------------------------------------
  4263. void __fastcall TSessionData::SetFtps(TFtps value)
  4264. {
  4265. SET_SESSION_PROPERTY(Ftps);
  4266. }
  4267. //---------------------------------------------------------------------------
  4268. void __fastcall TSessionData::SetMinTlsVersion(TTlsVersion value)
  4269. {
  4270. SET_SESSION_PROPERTY(MinTlsVersion);
  4271. }
  4272. //---------------------------------------------------------------------------
  4273. void __fastcall TSessionData::SetMaxTlsVersion(TTlsVersion value)
  4274. {
  4275. SET_SESSION_PROPERTY(MaxTlsVersion);
  4276. }
  4277. //---------------------------------------------------------------------------
  4278. void __fastcall TSessionData::SetLogicalHostName(UnicodeString value)
  4279. {
  4280. SET_SESSION_PROPERTY(LogicalHostName);
  4281. }
  4282. //---------------------------------------------------------------------------
  4283. void TSessionData::SetCompleteTlsShutdown(TAutoSwitch value)
  4284. {
  4285. SET_SESSION_PROPERTY(CompleteTlsShutdown);
  4286. }
  4287. //---------------------------------------------------------------------
  4288. void __fastcall TSessionData::SetFtpListAll(TAutoSwitch value)
  4289. {
  4290. SET_SESSION_PROPERTY(FtpListAll);
  4291. }
  4292. //---------------------------------------------------------------------
  4293. void __fastcall TSessionData::SetFtpHost(TAutoSwitch value)
  4294. {
  4295. SET_SESSION_PROPERTY(FtpHost);
  4296. }
  4297. //---------------------------------------------------------------------
  4298. void __fastcall TSessionData::SetFtpWorkFromCwd(TAutoSwitch value)
  4299. {
  4300. SET_SESSION_PROPERTY(FtpWorkFromCwd);
  4301. }
  4302. //---------------------------------------------------------------------
  4303. void TSessionData::SetFtpAnyCodeForPwd(bool value)
  4304. {
  4305. SET_SESSION_PROPERTY(FtpAnyCodeForPwd);
  4306. }
  4307. //---------------------------------------------------------------------
  4308. void __fastcall TSessionData::SetSslSessionReuse(bool value)
  4309. {
  4310. SET_SESSION_PROPERTY(SslSessionReuse);
  4311. }
  4312. //---------------------------------------------------------------------
  4313. void __fastcall TSessionData::SetTlsCertificateFile(UnicodeString value)
  4314. {
  4315. SET_SESSION_PROPERTY(TlsCertificateFile);
  4316. }
  4317. //---------------------------------------------------------------------
  4318. void __fastcall TSessionData::SetNotUtf(TAutoSwitch value)
  4319. {
  4320. SET_SESSION_PROPERTY(NotUtf);
  4321. }
  4322. //---------------------------------------------------------------------
  4323. void __fastcall TSessionData::SetInternalEditorEncoding(int value)
  4324. {
  4325. SET_SESSION_PROPERTY(InternalEditorEncoding);
  4326. }
  4327. //---------------------------------------------------------------------
  4328. void __fastcall TSessionData::SetS3DefaultRegion(UnicodeString value)
  4329. {
  4330. SET_SESSION_PROPERTY(S3DefaultRegion);
  4331. }
  4332. //---------------------------------------------------------------------
  4333. void __fastcall TSessionData::SetS3SessionToken(UnicodeString value)
  4334. {
  4335. SET_SESSION_PROPERTY(S3SessionToken);
  4336. }
  4337. //---------------------------------------------------------------------
  4338. void __fastcall TSessionData::SetS3RoleArn(UnicodeString value)
  4339. {
  4340. SET_SESSION_PROPERTY(S3RoleArn);
  4341. }
  4342. //---------------------------------------------------------------------
  4343. void __fastcall TSessionData::SetS3RoleSessionName(UnicodeString value)
  4344. {
  4345. SET_SESSION_PROPERTY(S3RoleSessionName);
  4346. }
  4347. //---------------------------------------------------------------------
  4348. void __fastcall TSessionData::SetS3Profile(UnicodeString value)
  4349. {
  4350. SET_SESSION_PROPERTY(S3Profile);
  4351. }
  4352. //---------------------------------------------------------------------
  4353. void __fastcall TSessionData::SetS3UrlStyle(TS3UrlStyle value)
  4354. {
  4355. SET_SESSION_PROPERTY(S3UrlStyle);
  4356. }
  4357. //---------------------------------------------------------------------
  4358. void __fastcall TSessionData::SetS3MaxKeys(TAutoSwitch value)
  4359. {
  4360. SET_SESSION_PROPERTY(S3MaxKeys);
  4361. }
  4362. //---------------------------------------------------------------------
  4363. void __fastcall TSessionData::SetS3CredentialsEnv(bool value)
  4364. {
  4365. SET_SESSION_PROPERTY(S3CredentialsEnv);
  4366. }
  4367. //---------------------------------------------------------------------
  4368. void __fastcall TSessionData::SetS3RequesterPays(bool value)
  4369. {
  4370. SET_SESSION_PROPERTY(S3RequesterPays);
  4371. }
  4372. //---------------------------------------------------------------------
  4373. void __fastcall TSessionData::SetIsWorkspace(bool value)
  4374. {
  4375. SET_SESSION_PROPERTY(IsWorkspace);
  4376. }
  4377. //---------------------------------------------------------------------
  4378. void __fastcall TSessionData::SetLink(UnicodeString value)
  4379. {
  4380. SET_SESSION_PROPERTY(Link);
  4381. }
  4382. //---------------------------------------------------------------------
  4383. void __fastcall TSessionData::SetNameOverride(UnicodeString value)
  4384. {
  4385. SET_SESSION_PROPERTY(NameOverride);
  4386. }
  4387. //---------------------------------------------------------------------
  4388. void __fastcall TSessionData::SetHostKey(UnicodeString value)
  4389. {
  4390. SET_SESSION_PROPERTY(HostKey);
  4391. }
  4392. //---------------------------------------------------------------------
  4393. void __fastcall TSessionData::SetNote(UnicodeString value)
  4394. {
  4395. SET_SESSION_PROPERTY(Note);
  4396. }
  4397. //---------------------------------------------------------------------
  4398. void __fastcall TSessionData::SetWinTitle(UnicodeString value)
  4399. {
  4400. SET_SESSION_PROPERTY(WinTitle);
  4401. }
  4402. //---------------------------------------------------------------------
  4403. UnicodeString __fastcall TSessionData::GetEncryptKey() const
  4404. {
  4405. return DecryptPassword(FEncryptKey, GetSessionPasswordEncryptionKey());
  4406. }
  4407. //---------------------------------------------------------------------
  4408. void __fastcall TSessionData::SetEncryptKey(UnicodeString avalue)
  4409. {
  4410. RawByteString value = EncryptPassword(avalue, GetSessionPasswordEncryptionKey());
  4411. SET_SESSION_PROPERTY(EncryptKey);
  4412. }
  4413. //---------------------------------------------------------------------
  4414. void __fastcall TSessionData::SetWebDavLiberalEscaping(bool value)
  4415. {
  4416. SET_SESSION_PROPERTY(WebDavLiberalEscaping);
  4417. }
  4418. //---------------------------------------------------------------------
  4419. void __fastcall TSessionData::SetWebDavAuthLegacy(bool value)
  4420. {
  4421. SET_SESSION_PROPERTY(WebDavAuthLegacy);
  4422. }
  4423. //---------------------------------------------------------------------
  4424. UnicodeString __fastcall TSessionData::GetInfoTip()
  4425. {
  4426. if (UsesSsh)
  4427. {
  4428. return FMTLOAD(SESSION_INFO_TIP2,
  4429. (HostName, UserName,
  4430. (PublicKeyFile.IsEmpty() ? LoadStr(NO_STR) : LoadStr(YES_STR)),
  4431. FSProtocolStr));
  4432. }
  4433. else
  4434. {
  4435. return FMTLOAD(SESSION_INFO_TIP_NO_SSH,
  4436. (HostName, UserName, FSProtocolStr));
  4437. }
  4438. }
  4439. //---------------------------------------------------------------------
  4440. UnicodeString __fastcall TSessionData::ExtractLocalName(const UnicodeString & Name)
  4441. {
  4442. UnicodeString Result = Name;
  4443. int P = Result.LastDelimiter(L"/");
  4444. if (P > 0)
  4445. {
  4446. Result.Delete(1, P);
  4447. }
  4448. return Result;
  4449. }
  4450. //---------------------------------------------------------------------
  4451. UnicodeString __fastcall TSessionData::GetLocalName()
  4452. {
  4453. UnicodeString Result;
  4454. if (HasSessionName())
  4455. {
  4456. Result = ExtractLocalName(Name);
  4457. }
  4458. else
  4459. {
  4460. Result = DefaultSessionName;
  4461. }
  4462. return Result;
  4463. }
  4464. //---------------------------------------------------------------------
  4465. UnicodeString __fastcall TSessionData::ExtractFolderName(const UnicodeString & Name)
  4466. {
  4467. UnicodeString Result;
  4468. int P = Name.LastDelimiter(L"/");
  4469. if (P > 0)
  4470. {
  4471. Result = Name.SubString(1, P - 1);
  4472. }
  4473. return Result;
  4474. }
  4475. //---------------------------------------------------------------------
  4476. UnicodeString __fastcall TSessionData::GetFolderName()
  4477. {
  4478. UnicodeString Result;
  4479. if (HasSessionName() || IsWorkspace)
  4480. {
  4481. Result = ExtractFolderName(Name);
  4482. }
  4483. return Result;
  4484. }
  4485. //---------------------------------------------------------------------
  4486. UnicodeString __fastcall TSessionData::ComposePath(
  4487. const UnicodeString & Path, const UnicodeString & Name)
  4488. {
  4489. return UnixIncludeTrailingBackslash(Path) + Name;
  4490. }
  4491. //---------------------------------------------------------------------
  4492. void __fastcall TSessionData::DisableAuthentationsExceptPassword()
  4493. {
  4494. SshNoUserAuth = false;
  4495. AuthKI = false;
  4496. AuthKIPassword = false;
  4497. AuthGSSAPI = false;
  4498. AuthGSSAPIKEX = false;
  4499. PublicKeyFile = EmptyStr;
  4500. DetachedCertificate = EmptyStr;
  4501. TlsCertificateFile = EmptyStr;
  4502. Passphrase = EmptyStr;
  4503. TryAgent = false;
  4504. }
  4505. //---------------------------------------------------------------------
  4506. TStrings * TSessionData::GetAllOptionNames(bool PuttyExport)
  4507. {
  4508. std::unique_ptr<TSessionData> FactoryDefaults(new TSessionData(L""));
  4509. return FactoryDefaults->SaveToOptions(NULL, false, PuttyExport);
  4510. }
  4511. //---------------------------------------------------------------------
  4512. bool TSessionData::HasS3AutoCredentials()
  4513. {
  4514. return (FSProtocol == fsS3) && S3CredentialsEnv;
  4515. }
  4516. //---------------------------------------------------------------------
  4517. bool TSessionData::HasAutoCredentials()
  4518. {
  4519. return HasS3AutoCredentials();
  4520. }
  4521. //=== TStoredSessionList ----------------------------------------------
  4522. __fastcall TStoredSessionList::TStoredSessionList(bool aReadOnly):
  4523. TNamedObjectList(), FReadOnly(aReadOnly)
  4524. {
  4525. DebugAssert(Configuration);
  4526. FDefaultSettings = new TSessionData(DefaultName);
  4527. FPendingRemovals.reset(new TStringList());
  4528. }
  4529. //---------------------------------------------------------------------
  4530. __fastcall TStoredSessionList::~TStoredSessionList()
  4531. {
  4532. DebugAssert(Configuration);
  4533. delete FDefaultSettings;
  4534. }
  4535. //---------------------------------------------------------------------
  4536. void __fastcall TStoredSessionList::Load(THierarchicalStorage * Storage,
  4537. bool AsModified, bool UseDefaults, bool PuttyImport)
  4538. {
  4539. TStringList *SubKeys = new TStringList();
  4540. TList * Loaded = new TList;
  4541. try
  4542. {
  4543. DebugAssert(AutoSort);
  4544. AutoSort = false;
  4545. bool WasEmpty = (Count == 0);
  4546. Storage->GetSubKeyNames(SubKeys);
  4547. for (int Index = 0; Index < SubKeys->Count; Index++)
  4548. {
  4549. UnicodeString SessionName = SubKeys->Strings[Index];
  4550. bool ValidName = true;
  4551. try
  4552. {
  4553. TSessionData::ValidatePath(SessionName);
  4554. }
  4555. catch(...)
  4556. {
  4557. ValidName = false;
  4558. }
  4559. if (ValidName)
  4560. {
  4561. TSessionData * SessionData;
  4562. if (SessionName == FDefaultSettings->Name)
  4563. {
  4564. SessionData = FDefaultSettings;
  4565. }
  4566. else
  4567. {
  4568. // if the list was empty before loading, do not waste time trying to
  4569. // find existing sites to overwrite (we rely on underlying storage
  4570. // to secure uniqueness of the key names)
  4571. if (WasEmpty)
  4572. {
  4573. SessionData = NULL;
  4574. }
  4575. else
  4576. {
  4577. SessionData = (TSessionData*)FindByName(SessionName);
  4578. }
  4579. }
  4580. if ((SessionData != FDefaultSettings) || !UseDefaults)
  4581. {
  4582. if (SessionData == NULL)
  4583. {
  4584. SessionData = new TSessionData(L"");
  4585. if (UseDefaults)
  4586. {
  4587. SessionData->CopyData(DefaultSettings);
  4588. }
  4589. SessionData->Name = SessionName;
  4590. Add(SessionData);
  4591. }
  4592. Loaded->Add(SessionData);
  4593. SessionData->Load(Storage, PuttyImport);
  4594. if (AsModified)
  4595. {
  4596. SessionData->Modified = true;
  4597. }
  4598. }
  4599. }
  4600. }
  4601. if (!AsModified)
  4602. {
  4603. for (int Index = 0; Index < TObjectList::Count; Index++)
  4604. {
  4605. if (Loaded->IndexOf(Items[Index]) < 0)
  4606. {
  4607. Delete(Index);
  4608. Index--;
  4609. }
  4610. }
  4611. }
  4612. }
  4613. __finally
  4614. {
  4615. AutoSort = true;
  4616. AlphaSort();
  4617. delete SubKeys;
  4618. delete Loaded;
  4619. }
  4620. }
  4621. //---------------------------------------------------------------------
  4622. void __fastcall TStoredSessionList::Reload()
  4623. {
  4624. if (Count <= Configuration->DontReloadMoreThanSessions)
  4625. {
  4626. bool SessionList = true;
  4627. std::unique_ptr<THierarchicalStorage> Storage(Configuration->CreateScpStorage(SessionList));
  4628. if (Storage->OpenSubKey(Configuration->StoredSessionsSubKey, False))
  4629. {
  4630. Load(Storage.get());
  4631. }
  4632. }
  4633. }
  4634. //---------------------------------------------------------------------
  4635. void __fastcall TStoredSessionList::DoSave(THierarchicalStorage * Storage,
  4636. TSessionData * Data, bool All, bool RecryptPasswordOnly,
  4637. TSessionData * FactoryDefaults)
  4638. {
  4639. if (All || Data->Modified)
  4640. {
  4641. if (RecryptPasswordOnly)
  4642. {
  4643. Data->SaveRecryptedPasswords(Storage);
  4644. }
  4645. else
  4646. {
  4647. Data->Save(Storage, false, FactoryDefaults);
  4648. }
  4649. }
  4650. }
  4651. //---------------------------------------------------------------------
  4652. void __fastcall TStoredSessionList::DoSave(THierarchicalStorage * Storage,
  4653. bool All, bool RecryptPasswordOnly, TStrings * RecryptPasswordErrors)
  4654. {
  4655. TSessionData * FactoryDefaults = new TSessionData(L"");
  4656. try
  4657. {
  4658. while (FPendingRemovals->Count > 0)
  4659. {
  4660. TSessionData::Remove(Storage, FPendingRemovals->Strings[0]);
  4661. FPendingRemovals->Delete(0);
  4662. }
  4663. DoSave(Storage, FDefaultSettings, All, RecryptPasswordOnly, FactoryDefaults);
  4664. for (int Index = 0; Index < CountIncludingHidden; Index++)
  4665. {
  4666. TSessionData * SessionData = (TSessionData *)Items[Index];
  4667. try
  4668. {
  4669. DoSave(Storage, SessionData, All, RecryptPasswordOnly, FactoryDefaults);
  4670. }
  4671. catch (Exception & E)
  4672. {
  4673. UnicodeString Message;
  4674. if (RecryptPasswordOnly && DebugAlwaysTrue(RecryptPasswordErrors != NULL) &&
  4675. ExceptionMessage(&E, Message))
  4676. {
  4677. RecryptPasswordErrors->Add(FORMAT("%s: %s", (SessionData->SessionName, Message)));
  4678. }
  4679. else
  4680. {
  4681. throw;
  4682. }
  4683. }
  4684. }
  4685. }
  4686. __finally
  4687. {
  4688. delete FactoryDefaults;
  4689. }
  4690. }
  4691. //---------------------------------------------------------------------
  4692. void __fastcall TStoredSessionList::Save(THierarchicalStorage * Storage, bool All)
  4693. {
  4694. DoSave(Storage, All, false, NULL);
  4695. }
  4696. //---------------------------------------------------------------------
  4697. void __fastcall TStoredSessionList::DoSave(bool All, bool Explicit,
  4698. bool RecryptPasswordOnly, TStrings * RecryptPasswordErrors)
  4699. {
  4700. bool SessionList = true;
  4701. THierarchicalStorage * Storage = Configuration->CreateScpStorage(SessionList);
  4702. try
  4703. {
  4704. Storage->AccessMode = smReadWrite;
  4705. Storage->Explicit = Explicit;
  4706. if (Storage->OpenSubKey(Configuration->StoredSessionsSubKey, true))
  4707. {
  4708. DoSave(Storage, All, RecryptPasswordOnly, RecryptPasswordErrors);
  4709. }
  4710. }
  4711. __finally
  4712. {
  4713. delete Storage;
  4714. }
  4715. Saved();
  4716. }
  4717. //---------------------------------------------------------------------
  4718. void __fastcall TStoredSessionList::Save(bool All, bool Explicit)
  4719. {
  4720. DoSave(All, Explicit, false, NULL);
  4721. }
  4722. //---------------------------------------------------------------------
  4723. void __fastcall TStoredSessionList::RecryptPasswords(TStrings * RecryptPasswordErrors)
  4724. {
  4725. DoSave(true, true, true, RecryptPasswordErrors);
  4726. }
  4727. //---------------------------------------------------------------------
  4728. void __fastcall TStoredSessionList::Saved()
  4729. {
  4730. FDefaultSettings->Modified = false;
  4731. for (int Index = 0; Index < CountIncludingHidden; Index++)
  4732. {
  4733. ((TSessionData *)Items[Index])->Modified = false;
  4734. }
  4735. }
  4736. //---------------------------------------------------------------------
  4737. void __fastcall TStoredSessionList::ImportLevelFromFilezilla(
  4738. _di_IXMLNode Node, const UnicodeString & Path, _di_IXMLNode SettingsNode)
  4739. {
  4740. for (int Index = 0; Index < Node->ChildNodes->Count; Index++)
  4741. {
  4742. _di_IXMLNode ChildNode = Node->ChildNodes->Get(Index);
  4743. if (ChildNode->NodeName == L"Server")
  4744. {
  4745. std::unique_ptr<TSessionData> SessionData(new TSessionData(L""));
  4746. SessionData->CopyData(DefaultSettings);
  4747. SessionData->ImportFromFilezilla(ChildNode, Path, SettingsNode);
  4748. Add(SessionData.release());
  4749. }
  4750. else if (ChildNode->NodeName == L"Folder")
  4751. {
  4752. UnicodeString Name;
  4753. for (int Index = 0; Index < ChildNode->ChildNodes->Count; Index++)
  4754. {
  4755. _di_IXMLNode PossibleTextMode = ChildNode->ChildNodes->Get(Index);
  4756. if (PossibleTextMode->NodeType == ntText)
  4757. {
  4758. UnicodeString NodeValue = PossibleTextMode->NodeValue;
  4759. AddToList(Name, NodeValue.Trim(), L" ");
  4760. }
  4761. }
  4762. Name = TSessionData::MakeValidName(Name).Trim();
  4763. ImportLevelFromFilezilla(ChildNode, TSessionData::ComposePath(Path, Name), SettingsNode);
  4764. }
  4765. }
  4766. }
  4767. //---------------------------------------------------------------------
  4768. void __fastcall TStoredSessionList::ImportFromFilezilla(
  4769. const UnicodeString FileName, const UnicodeString ConfigurationFileName)
  4770. {
  4771. // not sure if the document must exists if we want to use its node
  4772. _di_IXMLDocument ConfigurationDocument;
  4773. _di_IXMLNode SettingsNode;
  4774. if (FileExists(ApiPath(ConfigurationFileName)))
  4775. {
  4776. ConfigurationDocument = interface_cast<Xmlintf::IXMLDocument>(new TXMLDocument(NULL));
  4777. ConfigurationDocument->LoadFromFile(ConfigurationFileName);
  4778. _di_IXMLNode FileZilla3Node = ConfigurationDocument->ChildNodes->FindNode(L"FileZilla3");
  4779. if (FileZilla3Node != NULL)
  4780. {
  4781. SettingsNode = FileZilla3Node->ChildNodes->FindNode(L"Settings");
  4782. }
  4783. }
  4784. const _di_IXMLDocument Document = interface_cast<Xmlintf::IXMLDocument>(new TXMLDocument(NULL));
  4785. Document->LoadFromFile(FileName);
  4786. _di_IXMLNode FileZilla3Node = Document->ChildNodes->FindNode(L"FileZilla3");
  4787. if (FileZilla3Node != NULL)
  4788. {
  4789. _di_IXMLNode ServersNode = FileZilla3Node->ChildNodes->FindNode(L"Servers");
  4790. if (ServersNode != NULL)
  4791. {
  4792. ImportLevelFromFilezilla(ServersNode, L"", SettingsNode);
  4793. }
  4794. }
  4795. }
  4796. //---------------------------------------------------------------------
  4797. UnicodeString FormatKnownHostName(const UnicodeString & HostName, int PortNumber)
  4798. {
  4799. return FORMAT(L"%s:%d", (HostName, PortNumber));
  4800. }
  4801. //---------------------------------------------------------------------
  4802. void __fastcall TStoredSessionList::ImportFromKnownHosts(TStrings * Lines)
  4803. {
  4804. bool SessionList = false;
  4805. std::unique_ptr<THierarchicalStorage> HostKeyStorage(Configuration->CreateScpStorage(SessionList));
  4806. std::unique_ptr<TStrings> KeyList(new TStringList());
  4807. if (OpenHostKeysSubKey(HostKeyStorage.get(), false))
  4808. {
  4809. HostKeyStorage->GetValueNames(KeyList.get());
  4810. }
  4811. HostKeyStorage.reset(NULL);
  4812. UnicodeString FirstError;
  4813. for (int Index = 0; Index < Lines->Count; Index++)
  4814. {
  4815. try
  4816. {
  4817. UnicodeString Line = Lines->Strings[Index];
  4818. Line = Trim(Line);
  4819. if (IsValidOpensshLine(Line))
  4820. {
  4821. int P = Pos(L' ', Line);
  4822. if (P > 0)
  4823. {
  4824. UnicodeString HostNameStr = Line.SubString(1, P - 1);
  4825. Line = Line.SubString(P + 1, Line.Length() - P);
  4826. P = Pos(L',', HostNameStr);
  4827. if (P > 0)
  4828. {
  4829. HostNameStr.SetLength(P - 1);
  4830. }
  4831. P = Pos(L':', HostNameStr);
  4832. int PortNumber = -1;
  4833. if (P > 0)
  4834. {
  4835. UnicodeString PortNumberStr = HostNameStr.SubString(P + 1, HostNameStr.Length() - P);
  4836. PortNumber = StrToInt(PortNumberStr);
  4837. HostNameStr.SetLength(P - 1);
  4838. }
  4839. if (HasIP6LiteralBrackets(HostNameStr))
  4840. {
  4841. HostNameStr = StripIP6LiteralBrackets(HostNameStr);
  4842. }
  4843. UnicodeString NameStr = HostNameStr;
  4844. if (PortNumber >= 0)
  4845. {
  4846. NameStr = FormatKnownHostName(NameStr, PortNumber);
  4847. }
  4848. std::unique_ptr<TSessionData> SessionDataOwner;
  4849. TSessionData * SessionData = dynamic_cast<TSessionData *>(FindByName(NameStr));
  4850. if (SessionData == NULL)
  4851. {
  4852. SessionData = new TSessionData(L"");
  4853. SessionDataOwner.reset(SessionData);
  4854. SessionData->CopyData(DefaultSettings);
  4855. SessionData->Name = NameStr;
  4856. SessionData->HostName = HostNameStr;
  4857. if (PortNumber >= 0)
  4858. {
  4859. SessionData->PortNumber = PortNumber;
  4860. }
  4861. }
  4862. const struct ssh_keyalg * Algorithm;
  4863. UnicodeString Key = ParseOpenSshPubLine(Line, Algorithm);
  4864. UnicodeString KeyKey =
  4865. FORMAT(L"%s@%d:%s", (Algorithm->cache_id, SessionData->PortNumber, HostNameStr));
  4866. UnicodeString HostKey =
  4867. FORMAT(L"%s:%s=%s", (Algorithm->ssh_id, KeyKey, Key));
  4868. UnicodeString HostKeyList = SessionData->HostKey;
  4869. AddToList(HostKeyList, HostKey, L";");
  4870. SessionData->HostKey = HostKeyList;
  4871. // If there's at least one unknown key type for this host, select it
  4872. if (KeyList->IndexOf(KeyKey) < 0)
  4873. {
  4874. SessionData->Selected = true;
  4875. }
  4876. if (SessionDataOwner.get() != NULL)
  4877. {
  4878. Add(SessionDataOwner.release());
  4879. }
  4880. }
  4881. }
  4882. }
  4883. catch (Exception & E)
  4884. {
  4885. if (FirstError.IsEmpty())
  4886. {
  4887. FirstError = E.Message;
  4888. }
  4889. }
  4890. }
  4891. if (Count == 0)
  4892. {
  4893. UnicodeString Message = LoadStr(KNOWN_HOSTS_NO_SITES);
  4894. if (!FirstError.IsEmpty())
  4895. {
  4896. Message = FORMAT(L"%s\n(%s)", (Message, FirstError));
  4897. }
  4898. throw Exception(Message);
  4899. }
  4900. }
  4901. //---------------------------------------------------------------------
  4902. void TStoredSessionList::ImportFromOpenssh(TStrings * Lines)
  4903. {
  4904. std::unique_ptr<TStrings> Hosts(CreateSortedStringList());
  4905. for (int Index = 0; Index < Lines->Count; Index++)
  4906. {
  4907. UnicodeString Line = Lines->Strings[Index];
  4908. UnicodeString Directive, Value;
  4909. if (ParseOpensshDirective(Line, Directive, Value))
  4910. {
  4911. if (SameText(Directive, OpensshHostDirective))
  4912. {
  4913. while (!Value.IsEmpty())
  4914. {
  4915. UnicodeString Name = CutOpensshToken(Value);
  4916. if ((Hosts->IndexOf(Name) < 0) && (Name.LastDelimiter(L"*?") == 0))
  4917. {
  4918. std::unique_ptr<TSessionData> Data(new TSessionData(EmptyStr));
  4919. Data->CopyData(DefaultSettings);
  4920. Data->Name = Name;
  4921. Data->HostName = Name;
  4922. Data->ImportFromOpenssh(Lines);
  4923. Add(Data.release());
  4924. Hosts->Add(Name);
  4925. }
  4926. }
  4927. }
  4928. }
  4929. }
  4930. }
  4931. //---------------------------------------------------------------------
  4932. void __fastcall TStoredSessionList::Export(const UnicodeString FileName)
  4933. {
  4934. THierarchicalStorage * Storage = TIniFileStorage::CreateFromPath(FileName);
  4935. try
  4936. {
  4937. Storage->AccessMode = smReadWrite;
  4938. if (Storage->OpenSubKey(Configuration->StoredSessionsSubKey, true))
  4939. {
  4940. Save(Storage, true);
  4941. }
  4942. }
  4943. __finally
  4944. {
  4945. delete Storage;
  4946. }
  4947. }
  4948. //---------------------------------------------------------------------
  4949. void __fastcall TStoredSessionList::SelectAll(bool Select)
  4950. {
  4951. for (int Index = 0; Index < Count; Index++)
  4952. Sessions[Index]->Selected = Select;
  4953. }
  4954. //---------------------------------------------------------------------
  4955. bool TStoredSessionList::Import(TStoredSessionList * From,
  4956. bool OnlySelected, TList * Imported)
  4957. {
  4958. bool Result = false;
  4959. for (int Index = 0; Index < From->Count; Index++)
  4960. {
  4961. if (!OnlySelected || From->Sessions[Index]->Selected)
  4962. {
  4963. TSessionData *Session = new TSessionData(L"");
  4964. Session->Assign(From->Sessions[Index]);
  4965. Session->Modified = true;
  4966. Session->MakeUniqueIn(this);
  4967. Add(Session);
  4968. Result = true;
  4969. if (Imported != NULL)
  4970. {
  4971. Imported->Add(Session);
  4972. }
  4973. }
  4974. }
  4975. // only modified, explicit
  4976. Save(false, true);
  4977. return Result;
  4978. }
  4979. //---------------------------------------------------------------------
  4980. void __fastcall TStoredSessionList::SelectSessionsToImport
  4981. (TStoredSessionList * Dest, bool SSHOnly)
  4982. {
  4983. for (int Index = 0; Index < Count; Index++)
  4984. {
  4985. Sessions[Index]->Selected =
  4986. (!SSHOnly || (Sessions[Index]->GetNormalizedPuttyProtocol() == PuttySshProtocol)) &&
  4987. !Dest->FindByName(Sessions[Index]->Name);
  4988. }
  4989. }
  4990. //---------------------------------------------------------------------
  4991. void __fastcall TStoredSessionList::Cleanup()
  4992. {
  4993. try
  4994. {
  4995. if (Configuration->Storage == stRegistry) Clear();
  4996. TRegistryStorage * Storage = new TRegistryStorage(Configuration->RegistryStorageKey);
  4997. try
  4998. {
  4999. Storage->AccessMode = smReadWrite;
  5000. if (Storage->OpenRootKey(False))
  5001. Storage->RecursiveDeleteSubKey(Configuration->StoredSessionsSubKey);
  5002. }
  5003. __finally
  5004. {
  5005. delete Storage;
  5006. }
  5007. }
  5008. catch (Exception &E)
  5009. {
  5010. throw ExtException(&E, LoadStr(CLEANUP_SESSIONS_ERROR));
  5011. }
  5012. }
  5013. //---------------------------------------------------------------------------
  5014. void __fastcall TStoredSessionList::UpdateStaticUsage()
  5015. {
  5016. int SCP = 0;
  5017. int SFTP = 0;
  5018. int FTP = 0;
  5019. int FTPS = 0;
  5020. int WebDAV = 0;
  5021. int WebDAVS = 0;
  5022. int S3 = 0;
  5023. int Password = 0;
  5024. int Advanced = 0;
  5025. int Color = 0;
  5026. int Note = 0;
  5027. int Tunnel = 0;
  5028. bool Folders = false;
  5029. bool Workspaces = false;
  5030. std::unique_ptr<TSessionData> FactoryDefaults(new TSessionData(L""));
  5031. std::unique_ptr<TStringList> DifferentAdvancedProperties(CreateSortedStringList());
  5032. for (int Index = 0; Index < Count; Index++)
  5033. {
  5034. TSessionData * Data = Sessions[Index];
  5035. if (Data->IsWorkspace)
  5036. {
  5037. Workspaces = true;
  5038. }
  5039. else
  5040. {
  5041. switch (Data->FSProtocol)
  5042. {
  5043. case fsSCPonly:
  5044. SCP++;
  5045. break;
  5046. case fsSFTP:
  5047. case fsSFTPonly:
  5048. SFTP++;
  5049. break;
  5050. case fsFTP:
  5051. if (Data->Ftps == ftpsNone)
  5052. {
  5053. FTP++;
  5054. }
  5055. else
  5056. {
  5057. FTPS++;
  5058. }
  5059. break;
  5060. case fsWebDAV:
  5061. if (Data->Ftps == ftpsNone)
  5062. {
  5063. WebDAV++;
  5064. }
  5065. else
  5066. {
  5067. WebDAVS++;
  5068. }
  5069. break;
  5070. case fsS3:
  5071. S3++;
  5072. break;
  5073. }
  5074. if (Data->HasAnySessionPassword())
  5075. {
  5076. Password++;
  5077. }
  5078. if (Data->Color != 0)
  5079. {
  5080. Color++;
  5081. }
  5082. if (!Data->Note.IsEmpty())
  5083. {
  5084. Note++;
  5085. }
  5086. // This would not work for passwords, as they are compared in their encrypted form.
  5087. // But there are no passwords set in factory defaults anyway.
  5088. if (!Data->IsSame(FactoryDefaults.get(), true, DifferentAdvancedProperties.get(), false))
  5089. {
  5090. Advanced++;
  5091. }
  5092. if (Data->Tunnel)
  5093. {
  5094. Tunnel++;
  5095. }
  5096. if (!Data->FolderName.IsEmpty())
  5097. {
  5098. Folders = true;
  5099. }
  5100. }
  5101. }
  5102. Configuration->Usage->Set(L"StoredSessionsCountSCP", SCP);
  5103. Configuration->Usage->Set(L"StoredSessionsCountSFTP", SFTP);
  5104. Configuration->Usage->Set(L"StoredSessionsCountFTP", FTP);
  5105. Configuration->Usage->Set(L"StoredSessionsCountFTPS", FTPS);
  5106. Configuration->Usage->Set(L"StoredSessionsCountWebDAV", WebDAV);
  5107. Configuration->Usage->Set(L"StoredSessionsCountWebDAVS", WebDAVS);
  5108. Configuration->Usage->Set(L"StoredSessionsCountS3", S3);
  5109. Configuration->Usage->Set(L"StoredSessionsCountPassword", Password);
  5110. Configuration->Usage->Set(L"StoredSessionsCountColor", Color);
  5111. Configuration->Usage->Set(L"StoredSessionsCountNote", Note);
  5112. Configuration->Usage->Set(L"StoredSessionsCountAdvanced", Advanced);
  5113. DifferentAdvancedProperties->Delimiter = L',';
  5114. Configuration->Usage->Set(L"StoredSessionsAdvancedSettings", DifferentAdvancedProperties->DelimitedText);
  5115. Configuration->Usage->Set(L"StoredSessionsCountTunnel", Tunnel);
  5116. // actually default might be true, see below for when the default is actually used
  5117. bool CustomDefaultStoredSession = false;
  5118. try
  5119. {
  5120. // this can throw, when the default session settings have password set
  5121. // (and no other basic property, like hostname/username),
  5122. // and master password is enabled as we are called before master password
  5123. // handler is set
  5124. CustomDefaultStoredSession = !FDefaultSettings->IsSame(FactoryDefaults.get(), false);
  5125. }
  5126. catch (...)
  5127. {
  5128. }
  5129. Configuration->Usage->Set(L"UsingDefaultStoredSession", CustomDefaultStoredSession);
  5130. Configuration->Usage->Set(L"UsingStoredSessionsFolders", Folders);
  5131. Configuration->Usage->Set(L"UsingWorkspaces", Workspaces);
  5132. }
  5133. //---------------------------------------------------------------------------
  5134. TSessionData * __fastcall TStoredSessionList::FindSame(TSessionData * Data)
  5135. {
  5136. TSessionData * Result;
  5137. if (Data->Hidden || Data->Name.IsEmpty() || Data->IsWorkspace)
  5138. {
  5139. Result = NULL;
  5140. }
  5141. else
  5142. {
  5143. Result = dynamic_cast<TSessionData *>(FindByName(Data->Name));
  5144. }
  5145. return Result;
  5146. }
  5147. //---------------------------------------------------------------------------
  5148. int __fastcall TStoredSessionList::IndexOf(TSessionData * Data)
  5149. {
  5150. for (int Index = 0; Index < Count; Index++)
  5151. if (Data == Sessions[Index]) return Index;
  5152. return -1;
  5153. }
  5154. //---------------------------------------------------------------------------
  5155. TSessionData * __fastcall TStoredSessionList::NewSession(
  5156. UnicodeString SessionName, TSessionData * Session)
  5157. {
  5158. TSessionData * DuplicateSession = (TSessionData*)FindByName(SessionName);
  5159. if (!DuplicateSession)
  5160. {
  5161. DuplicateSession = new TSessionData(L"");
  5162. DuplicateSession->Assign(Session);
  5163. DuplicateSession->Name = SessionName;
  5164. // make sure, that new stored session is saved to registry
  5165. DuplicateSession->Modified = true;
  5166. Add(DuplicateSession);
  5167. }
  5168. else
  5169. {
  5170. DuplicateSession->Assign(Session);
  5171. DuplicateSession->Name = SessionName;
  5172. DuplicateSession->Modified = true;
  5173. }
  5174. // list was saved here before to default storage, but it would not allow
  5175. // to work with special lists (export/import) not using default storage
  5176. return DuplicateSession;
  5177. }
  5178. //---------------------------------------------------------------------------
  5179. void __fastcall TStoredSessionList::SetDefaultSettings(TSessionData * value)
  5180. {
  5181. DebugAssert(FDefaultSettings);
  5182. if (FDefaultSettings != value)
  5183. {
  5184. FDefaultSettings->Assign(value);
  5185. // make sure default settings are saved
  5186. FDefaultSettings->Modified = true;
  5187. FDefaultSettings->Name = DefaultName;
  5188. if (!FReadOnly)
  5189. {
  5190. // only modified, explicit
  5191. Save(false, true);
  5192. }
  5193. }
  5194. }
  5195. //---------------------------------------------------------------------------
  5196. bool __fastcall TStoredSessionList::OpenHostKeysSubKey(THierarchicalStorage * Storage, bool CanCreate)
  5197. {
  5198. return Storage->OpenSubKey(Configuration->SshHostKeysSubKey, CanCreate);
  5199. }
  5200. //---------------------------------------------------------------------------
  5201. THierarchicalStorage * __fastcall TStoredSessionList::CreateHostKeysStorageForWriting()
  5202. {
  5203. bool SessionList = false;
  5204. std::unique_ptr<THierarchicalStorage> Storage(Configuration->CreateScpStorage(SessionList));
  5205. Storage->Explicit = true;
  5206. Storage->AccessMode = smReadWrite;
  5207. return Storage.release();
  5208. }
  5209. //---------------------------------------------------------------------------
  5210. int TStoredSessionList::ImportHostKeys(
  5211. THierarchicalStorage * SourceStorage, THierarchicalStorage * TargetStorage, TStoredSessionList * Sessions, bool OnlySelected)
  5212. {
  5213. int Result = 0;
  5214. if (OpenHostKeysSubKey(SourceStorage, false) &&
  5215. OpenHostKeysSubKey(TargetStorage, true))
  5216. {
  5217. std::unique_ptr<TStringList> KeyList(new TStringList());
  5218. SourceStorage->GetValueNames(KeyList.get());
  5219. DebugAssert(Sessions != NULL);
  5220. for (int Index = 0; Index < Sessions->Count; Index++)
  5221. {
  5222. TSessionData * Session = Sessions->Sessions[Index];
  5223. if (!OnlySelected || Session->Selected)
  5224. {
  5225. UnicodeString HostKeyName = PuttyMungeStr(FORMAT(L"@%d:%s", (Session->PortNumber, Session->HostNameExpanded)));
  5226. for (int KeyIndex = 0; KeyIndex < KeyList->Count; KeyIndex++)
  5227. {
  5228. UnicodeString KeyName = KeyList->Strings[KeyIndex];
  5229. if (EndsText(HostKeyName, KeyName))
  5230. {
  5231. TargetStorage->WriteStringRaw(KeyName, SourceStorage->ReadStringRaw(KeyName, L""));
  5232. Result++;
  5233. }
  5234. }
  5235. }
  5236. }
  5237. }
  5238. return Result;
  5239. }
  5240. //---------------------------------------------------------------------------
  5241. void TStoredSessionList::ImportHostKeys(
  5242. THierarchicalStorage * SourceStorage, TStoredSessionList * Sessions, bool OnlySelected)
  5243. {
  5244. std::unique_ptr<THierarchicalStorage> TargetStorage(CreateHostKeysStorageForWritting());
  5245. ImportHostKeys(SourceStorage, TargetStorage.get(), Sessions, OnlySelected);
  5246. }
  5247. //---------------------------------------------------------------------------
  5248. void TStoredSessionList::ImportHostKeys(
  5249. const UnicodeString & SourceKey, TStoredSessionList * Sessions, bool OnlySelected)
  5250. {
  5251. std::unique_ptr<THierarchicalStorage> SourceStorage(new TRegistryStorage(SourceKey));
  5252. ImportHostKeys(SourceStorage.get(), Sessions, OnlySelected);
  5253. }
  5254. //---------------------------------------------------------------------------
  5255. void __fastcall TStoredSessionList::ImportSelectedKnownHosts(TStoredSessionList * Sessions)
  5256. {
  5257. std::unique_ptr<THierarchicalStorage> Storage(CreateHostKeysStorageForWritting());
  5258. if (OpenHostKeysSubKey(Storage.get(), true))
  5259. {
  5260. for (int Index = 0; Index < Sessions->Count; Index++)
  5261. {
  5262. TSessionData * Session = Sessions->Sessions[Index];
  5263. if (Session->Selected)
  5264. {
  5265. UnicodeString Algs;
  5266. UnicodeString HostKeys = Session->HostKey;
  5267. while (!HostKeys.IsEmpty())
  5268. {
  5269. UnicodeString HostKey = CutToChar(HostKeys, L';', true);
  5270. // skip alg
  5271. CutToChar(HostKey, L':', true);
  5272. UnicodeString Key = CutToChar(HostKey, L'=', true);
  5273. Storage->WriteStringRaw(Key, HostKey);
  5274. }
  5275. }
  5276. }
  5277. }
  5278. }
  5279. //---------------------------------------------------------------------------
  5280. void TStoredSessionList::SelectKnownHostsForSelectedSessions(
  5281. TStoredSessionList * KnownHosts, TStoredSessionList * Sessions)
  5282. {
  5283. for (int SessionIndex = 0; SessionIndex < Sessions->Count; SessionIndex++)
  5284. {
  5285. TSessionData * Session = Sessions->Sessions[SessionIndex];
  5286. if (Session->Selected)
  5287. {
  5288. UnicodeString Key = Session->HostName;
  5289. if (Session->PortNumber != Session->GetDefaultPort())
  5290. {
  5291. Key = FormatKnownHostName(Key, Session->PortNumber);
  5292. }
  5293. TSessionData * KnownHost = dynamic_cast<TSessionData *>(KnownHosts->FindByName(Key));
  5294. if (KnownHost != NULL)
  5295. {
  5296. KnownHost->Selected = true;
  5297. }
  5298. }
  5299. }
  5300. }
  5301. //---------------------------------------------------------------------------
  5302. TSessionData * TStoredSessionList::GetFirstFolderOrWorkspaceSession(const UnicodeString & Name)
  5303. {
  5304. TSessionData * Result = NULL;
  5305. if (!Name.IsEmpty())
  5306. {
  5307. UnicodeString NameWithSlash = UnixIncludeTrailingBackslash(Name); // optimization
  5308. for (int Index = 0; (Result == NULL) && (Index < Count); Index++)
  5309. {
  5310. if (Sessions[Index]->IsInFolderOrWorkspace(NameWithSlash))
  5311. {
  5312. Result = Sessions[Index];
  5313. }
  5314. }
  5315. }
  5316. return Result;
  5317. }
  5318. //---------------------------------------------------------------------------
  5319. bool __fastcall TStoredSessionList::IsFolderOrWorkspace(const UnicodeString & Name)
  5320. {
  5321. return (GetFirstFolderOrWorkspaceSession(Name) != NULL);
  5322. }
  5323. //---------------------------------------------------------------------------
  5324. bool __fastcall TStoredSessionList::IsFolder(const UnicodeString & Name)
  5325. {
  5326. TSessionData * SessionData = GetFirstFolderOrWorkspaceSession(Name);
  5327. return (SessionData != NULL) && !SessionData->IsWorkspace;
  5328. }
  5329. //---------------------------------------------------------------------------
  5330. bool __fastcall TStoredSessionList::IsWorkspace(const UnicodeString & Name)
  5331. {
  5332. TSessionData * SessionData = GetFirstFolderOrWorkspaceSession(Name);
  5333. return (SessionData != NULL) && SessionData->IsWorkspace;
  5334. }
  5335. //---------------------------------------------------------------------------
  5336. TSessionData * __fastcall TStoredSessionList::CheckIsInFolderOrWorkspaceAndResolve(
  5337. TSessionData * Data, const UnicodeString & Name)
  5338. {
  5339. if (Data->IsInFolderOrWorkspace(Name))
  5340. {
  5341. Data = ResolveWorkspaceData(Data);
  5342. if ((Data != NULL) && Data->CanOpen &&
  5343. DebugAlwaysTrue(Data->Link.IsEmpty()))
  5344. {
  5345. return Data;
  5346. }
  5347. }
  5348. return NULL;
  5349. }
  5350. //---------------------------------------------------------------------------
  5351. void __fastcall TStoredSessionList::GetFolderOrWorkspace(const UnicodeString & Name, TList * List)
  5352. {
  5353. DoGetFolderOrWorkspace(Name, List, false);
  5354. }
  5355. //---------------------------------------------------------------------------
  5356. void __fastcall TStoredSessionList::DoGetFolderOrWorkspace(const UnicodeString & Name, TList * List, bool NoRecrypt)
  5357. {
  5358. for (int Index = 0; (Index < Count); Index++)
  5359. {
  5360. TSessionData * RawData = Sessions[Index];
  5361. TSessionData * Data =
  5362. CheckIsInFolderOrWorkspaceAndResolve(RawData, Name);
  5363. if (Data != NULL)
  5364. {
  5365. TSessionData * Data2 = new TSessionData(L"");
  5366. if (NoRecrypt)
  5367. {
  5368. Data2->CopyDataNoRecrypt(Data);
  5369. }
  5370. else
  5371. {
  5372. Data2->Assign(Data);
  5373. }
  5374. if (!RawData->Link.IsEmpty() && (DebugAlwaysTrue(Data != RawData)) &&
  5375. // BACKWARD COMPATIBILITY
  5376. // When loading pre-5.6.4 workspace, that does not have state saved,
  5377. // do not overwrite the site "state" defaults
  5378. // with (empty) workspace state
  5379. RawData->HasStateData())
  5380. {
  5381. Data2->CopyStateData(RawData);
  5382. }
  5383. if (!RawData->NameOverride.IsEmpty())
  5384. {
  5385. Data2->Name = RawData->NameOverride;
  5386. }
  5387. else if (RawData->Link.IsEmpty() && RawData->IsWorkspace)
  5388. {
  5389. // Newly opened ad-hoc session has no name, so restore the workspace that way too.
  5390. // Otherwise we would persist the generated internal workspace name as a real name.
  5391. Data2->Name = UnicodeString();
  5392. }
  5393. List->Add(Data2);
  5394. }
  5395. }
  5396. }
  5397. //---------------------------------------------------------------------------
  5398. TStrings * __fastcall TStoredSessionList::GetFolderOrWorkspaceList(
  5399. const UnicodeString & Name)
  5400. {
  5401. std::unique_ptr<TObjectList> DataList(new TObjectList());
  5402. DoGetFolderOrWorkspace(Name, DataList.get(), true);
  5403. std::unique_ptr<TStringList> Result(new TStringList());
  5404. for (int Index = 0; (Index < DataList->Count); Index++)
  5405. {
  5406. Result->Add(dynamic_cast<TSessionData *>(DataList->Items[Index])->SessionName);
  5407. }
  5408. return Result.release();
  5409. }
  5410. //---------------------------------------------------------------------------
  5411. TStrings * __fastcall TStoredSessionList::GetWorkspaces()
  5412. {
  5413. std::unique_ptr<TStringList> Result(CreateSortedStringList());
  5414. for (int Index = 0; (Index < Count); Index++)
  5415. {
  5416. TSessionData * Data = Sessions[Index];
  5417. if (Data->IsWorkspace)
  5418. {
  5419. Result->Add(Data->FolderName);
  5420. }
  5421. }
  5422. return Result.release();
  5423. }
  5424. //---------------------------------------------------------------------------
  5425. void __fastcall TStoredSessionList::NewWorkspace(
  5426. UnicodeString Name, TList * DataList)
  5427. {
  5428. for (int Index = 0; (Index < Count); Index++)
  5429. {
  5430. TSessionData * Data = Sessions[Index];
  5431. if (Data->IsInFolderOrWorkspace(Name))
  5432. {
  5433. FPendingRemovals->Add(Data->Name);
  5434. Remove(Data);
  5435. Index--;
  5436. }
  5437. }
  5438. for (int Index = 0; (Index < DataList->Count); Index++)
  5439. {
  5440. TSessionData * Data = static_cast<TSessionData *>(DataList->Items[Index]);
  5441. TSessionData * Data2 = new TSessionData(L"");
  5442. Data2->Assign(Data);
  5443. Data2->Name = TSessionData::ComposePath(Name, Data->Name);
  5444. // make sure, that new stored session is saved to registry
  5445. Data2->Modified = true;
  5446. Add(Data2);
  5447. }
  5448. }
  5449. //---------------------------------------------------------------------------
  5450. bool __fastcall TStoredSessionList::HasAnyWorkspace()
  5451. {
  5452. bool Result = false;
  5453. for (int Index = 0; !Result && (Index < Count); Index++)
  5454. {
  5455. TSessionData * Data = Sessions[Index];
  5456. Result = Data->IsWorkspace;
  5457. }
  5458. return Result;
  5459. }
  5460. //---------------------------------------------------------------------------
  5461. TSessionData * __fastcall TStoredSessionList::ParseUrl(UnicodeString Url,
  5462. TOptions * Options, bool & DefaultsOnly, UnicodeString * FileName,
  5463. bool * AProtocolDefined, UnicodeString * MaskedUrl, int Flags)
  5464. {
  5465. TSessionData * Data = new TSessionData(L"");
  5466. try
  5467. {
  5468. Data->ParseUrl(Url, Options, this, DefaultsOnly, FileName, AProtocolDefined, MaskedUrl, Flags);
  5469. }
  5470. catch(...)
  5471. {
  5472. delete Data;
  5473. throw;
  5474. }
  5475. return Data;
  5476. }
  5477. //---------------------------------------------------------------------
  5478. bool __fastcall TStoredSessionList::IsUrl(UnicodeString Url)
  5479. {
  5480. bool DefaultsOnly;
  5481. bool ProtocolDefined = false;
  5482. std::unique_ptr<TSessionData> ParsedData(ParseUrl(Url, NULL, DefaultsOnly, NULL, &ProtocolDefined));
  5483. bool Result = ProtocolDefined;
  5484. return Result;
  5485. }
  5486. //---------------------------------------------------------------------
  5487. TSessionData * __fastcall TStoredSessionList::ResolveWorkspaceData(TSessionData * Data)
  5488. {
  5489. if (!Data->Link.IsEmpty())
  5490. {
  5491. Data = dynamic_cast<TSessionData *>(FindByName(Data->Link));
  5492. if (Data != NULL)
  5493. {
  5494. Data = ResolveWorkspaceData(Data);
  5495. }
  5496. }
  5497. return Data;
  5498. }
  5499. //---------------------------------------------------------------------
  5500. TSessionData * __fastcall TStoredSessionList::SaveWorkspaceData(TSessionData * Data, int Index)
  5501. {
  5502. std::unique_ptr<TSessionData> Result(new TSessionData(L""));
  5503. TSessionData * SameData = StoredSessions->FindSame(Data);
  5504. if (SameData != NULL)
  5505. {
  5506. Result->CopyStateData(Data);
  5507. Result->Link = Data->Name;
  5508. }
  5509. else
  5510. {
  5511. Result->Assign(Data);
  5512. Result->NameOverride = Data->Name;
  5513. }
  5514. Result->IsWorkspace = true;
  5515. Result->Name = IntToHex(Index, 4); // See HasSessionName()
  5516. return Result.release();
  5517. }
  5518. //---------------------------------------------------------------------
  5519. bool __fastcall TStoredSessionList::CanOpen(TSessionData * Data)
  5520. {
  5521. Data = ResolveWorkspaceData(Data);
  5522. return (Data != NULL) && Data->CanOpen;
  5523. }
  5524. //---------------------------------------------------------------------
  5525. UnicodeString GetExpandedLogFileName(UnicodeString LogFileName, TDateTime Started, TSessionData * SessionData)
  5526. {
  5527. // StripPathQuotes should not be needed as we do not feed quotes anymore
  5528. UnicodeString ANewFileName = StripPathQuotes(ExpandEnvironmentVariables(LogFileName));
  5529. for (int Index = 1; Index < ANewFileName.Length(); Index++)
  5530. {
  5531. if (ANewFileName[Index] == L'!')
  5532. {
  5533. UnicodeString Replacement;
  5534. // keep consistent with TFileCustomCommand::PatternReplacement
  5535. switch (towlower(ANewFileName[Index + 1]))
  5536. {
  5537. case L'y':
  5538. Replacement = FormatDateTime(L"yyyy", Started);
  5539. break;
  5540. case L'm':
  5541. Replacement = FormatDateTime(L"mm", Started);
  5542. break;
  5543. case L'd':
  5544. Replacement = FormatDateTime(L"dd", Started);
  5545. break;
  5546. case L't':
  5547. Replacement = FormatDateTime(L"hhnnss", Started);
  5548. break;
  5549. case 'p':
  5550. Replacement = IntToStr(static_cast<int>(GetCurrentProcessId()));
  5551. break;
  5552. case L'@':
  5553. if (SessionData != NULL)
  5554. {
  5555. Replacement = MakeValidFileName(SessionData->HostNameExpanded);
  5556. }
  5557. else
  5558. {
  5559. Replacement = L"nohost";
  5560. }
  5561. break;
  5562. case L's':
  5563. if (SessionData != NULL)
  5564. {
  5565. Replacement = MakeValidFileName(SessionData->SessionName);
  5566. }
  5567. else
  5568. {
  5569. Replacement = L"nosession";
  5570. }
  5571. break;
  5572. case L'!':
  5573. Replacement = L"!";
  5574. break;
  5575. default:
  5576. Replacement = UnicodeString(L"!") + ANewFileName[Index + 1];
  5577. break;
  5578. }
  5579. ANewFileName.Delete(Index, 2);
  5580. ANewFileName.Insert(Replacement, Index);
  5581. Index += Replacement.Length() - 1;
  5582. }
  5583. }
  5584. return ANewFileName;
  5585. }
  5586. //---------------------------------------------------------------------
  5587. bool __fastcall IsSshProtocol(TFSProtocol FSProtocol)
  5588. {
  5589. return
  5590. (FSProtocol == fsSFTPonly) || (FSProtocol == fsSFTP) ||
  5591. (FSProtocol == fsSCPonly);
  5592. }
  5593. //---------------------------------------------------------------------------
  5594. int __fastcall DefaultPort(TFSProtocol FSProtocol, TFtps Ftps)
  5595. {
  5596. int Result;
  5597. switch (FSProtocol)
  5598. {
  5599. case fsFTP:
  5600. if (Ftps == ftpsImplicit)
  5601. {
  5602. Result = FtpsImplicitPortNumber;
  5603. }
  5604. else
  5605. {
  5606. Result = FtpPortNumber;
  5607. }
  5608. break;
  5609. case fsWebDAV:
  5610. case fsS3:
  5611. if (Ftps == ftpsNone)
  5612. {
  5613. Result = HTTPPortNumber;
  5614. }
  5615. else
  5616. {
  5617. Result = HTTPSPortNumber;
  5618. }
  5619. break;
  5620. default:
  5621. if (IsSshProtocol(FSProtocol))
  5622. {
  5623. Result = SshPortNumber;
  5624. }
  5625. else
  5626. {
  5627. DebugFail();
  5628. Result = -1;
  5629. }
  5630. break;
  5631. }
  5632. return Result;
  5633. }
  5634. //---------------------------------------------------------------------------
  5635. UnicodeString GetTlsVersionName(TTlsVersion TlsVersion)
  5636. {
  5637. switch (TlsVersion)
  5638. {
  5639. default:
  5640. DebugFail();
  5641. case ssl2:
  5642. case ssl3:
  5643. case tls10:
  5644. return "TLSv1.0";
  5645. case tls11:
  5646. return "TLSv1.1";
  5647. case tls12:
  5648. return "TLSv1.2";
  5649. case tls13:
  5650. return "TLSv1.3";
  5651. }
  5652. }
  5653. //---------------------------------------------------------------------