SessionData.cpp 192 KB

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