SessionData.cpp 190 KB

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