SessionData.cpp 188 KB

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