SessionData.cpp 188 KB

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