SessionData.cpp 195 KB

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