SessionData.cpp 192 KB

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