app.js 664 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800
  1. // DebTik - Debian Linux Router Frontend Application Logic
  2. let state = {
  3. interfaces: [],
  4. vlans: [],
  5. systemStatus: null,
  6. vpnStatus: null,
  7. routes: [],
  8. activeTab: 'dashboard',
  9. fwSubTab: 'filter',
  10. bridgeSubTab: 'bridges',
  11. bridges: [],
  12. bridgePorts: [],
  13. bridgeVLANs: [],
  14. bridgeHosts: [],
  15. bridgeSummary: null,
  16. routesSubTab: 'routes',
  17. pppSubTab: 'secrets',
  18. eoipTunnels: [],
  19. pppSecrets: [],
  20. pppProfiles: [],
  21. pppActiveSessions: [],
  22. pppoeServer: null,
  23. pptpServer: null,
  24. l2tpServer: null,
  25. ipsecServer: null,
  26. ifaceFilter: 'all',
  27. currentModalIface: null,
  28. isPolling: true,
  29. expandedParents: new Set(['eth0']),
  30. pppoeData: null,
  31. wgData: null,
  32. ipsecData: null,
  33. l2tpData: null,
  34. pptpData: null,
  35. fwSummary: null,
  36. filterRules: [],
  37. natRules: [],
  38. mangleRules: [],
  39. addressLists: [],
  40. connections: [],
  41. policyRules: [],
  42. routingTables: [],
  43. routingFilters: [],
  44. filterChainSelected: 'all',
  45. activeToolsSubTab: 'ping',
  46. dhcpClients: [],
  47. dhcpSummary: null,
  48. dhcpServerTab: 'servers',
  49. dhcpServers: [],
  50. dhcpNetworks: [],
  51. dhcpLeases: [],
  52. dhcpOptions: [],
  53. dhcpServerSummary: null
  54. };
  55. const API_BASE = '/api';
  56. function escapeHtml(str) {
  57. if (str === null || str === undefined) return '';
  58. return String(str)
  59. .replace(/&/g, '&')
  60. .replace(/</g, '&lt;')
  61. .replace(/>/g, '&gt;')
  62. .replace(/"/g, '&quot;')
  63. .replace(/'/g, '&#039;');
  64. }
  65. function formatBytes(bytes) {
  66. if (bytes === undefined || bytes === null || isNaN(bytes) || bytes === 0) return '0 B';
  67. const k = 1024;
  68. const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
  69. const i = Math.floor(Math.log(bytes) / Math.log(k));
  70. if (i < 0 || i >= sizes.length) return `${bytes} B`;
  71. return `${parseFloat((bytes / Math.pow(k, i)).toFixed(2))} ${sizes[i]}`;
  72. }
  73. // Initialize on page load
  74. document.addEventListener('DOMContentLoaded', () => {
  75. const hash = window.location.hash.replace('#', '') || 'dashboard';
  76. navigate(hash);
  77. initTableSorting();
  78. fetchData();
  79. initLiveTrafficStream();
  80. // Full state telemetry polling every 5 seconds (smooth & flicker-free)
  81. setInterval(() => {
  82. if (state.isPolling) {
  83. fetchData(false);
  84. }
  85. }, 5000);
  86. });
  87. let trafficEventSource = null;
  88. let trafficPollFallback = null;
  89. function initLiveTrafficStream() {
  90. if (trafficEventSource) {
  91. try { trafficEventSource.close(); } catch(e) {}
  92. trafficEventSource = null;
  93. }
  94. if (trafficPollFallback) {
  95. clearInterval(trafficPollFallback);
  96. trafficPollFallback = null;
  97. }
  98. if (window.EventSource) {
  99. try {
  100. trafficEventSource = new EventSource(`${API_BASE}/interfaces/traffic/stream`);
  101. trafficEventSource.onmessage = (event) => {
  102. try {
  103. const data = JSON.parse(event.data);
  104. updateLiveInterfaceTraffic(data);
  105. } catch (e) {
  106. console.error('Error parsing live traffic event:', e);
  107. }
  108. };
  109. trafficEventSource.onerror = () => {
  110. // Fallback polling if SSE disconnects
  111. if (!trafficPollFallback) {
  112. trafficPollFallback = setInterval(pollLiveTrafficSnapshot, 1000);
  113. }
  114. };
  115. trafficEventSource.onopen = () => {
  116. if (trafficPollFallback) {
  117. clearInterval(trafficPollFallback);
  118. trafficPollFallback = null;
  119. }
  120. };
  121. return;
  122. } catch (e) {
  123. console.warn('EventSource failed, using 1s polling fallback:', e);
  124. }
  125. }
  126. // Fallback if EventSource is unavailable
  127. trafficPollFallback = setInterval(pollLiveTrafficSnapshot, 1000);
  128. }
  129. async function pollLiveTrafficSnapshot() {
  130. try {
  131. const res = await fetch(`${API_BASE}/interfaces/traffic/rates`);
  132. if (res.ok) {
  133. const data = await res.json();
  134. updateLiveInterfaceTraffic(data);
  135. }
  136. } catch (e) {}
  137. }
  138. function updateLiveInterfaceTraffic(data) {
  139. if (!data || !data.interfaces) return;
  140. state.latestTraffic = data;
  141. // 1. Update Top & Dashboard Total Bandwidth Indicators
  142. const rxHuman = data.total_rx_human || '0 B/s';
  143. const txHuman = data.total_tx_human || '0 B/s';
  144. const statRx = document.getElementById('stat-traffic-rx');
  145. if (statRx && statRx.innerText !== rxHuman) statRx.innerText = rxHuman;
  146. const statTx = document.getElementById('stat-traffic-tx');
  147. if (statTx && statTx.innerText !== txHuman) statTx.innerText = txHuman;
  148. // 2. Update state.interfaces rates in-memory
  149. if (Array.isArray(state.interfaces)) {
  150. state.interfaces.forEach(i => {
  151. const live = data.interfaces[i.name];
  152. if (live) {
  153. i.rate = {
  154. rx_bytes_sec: live.rx_bytes_sec,
  155. tx_bytes_sec: live.tx_bytes_sec,
  156. rx_human: live.rx_human,
  157. tx_human: live.tx_human
  158. };
  159. i.stats = {
  160. rx_bytes: live.rx_bytes,
  161. tx_bytes: live.tx_bytes,
  162. rx_packets: live.rx_packets,
  163. tx_packets: live.tx_packets,
  164. rx_errors: live.rx_errors,
  165. tx_errors: live.tx_errors,
  166. rx_dropped: live.rx_dropped,
  167. tx_dropped: live.tx_dropped
  168. };
  169. }
  170. });
  171. }
  172. // 3. Update all live UI rate spans in-place (ZERO flicker)
  173. Object.keys(data.interfaces).forEach(name => {
  174. const live = data.interfaces[name];
  175. // Dashboard Port Matrix Card
  176. const cardRate = document.getElementById(`port-card-rate-${name}`);
  177. if (cardRate && cardRate.innerText !== live.rx_human) {
  178. cardRate.innerText = live.rx_human;
  179. }
  180. // Dashboard Quick Interfaces Table
  181. const quickRx = document.getElementById(`quick-rx-${name}`);
  182. if (quickRx) quickRx.innerText = `↓ ${live.rx_human}`;
  183. const quickTx = document.getElementById(`quick-tx-${name}`);
  184. if (quickTx) quickTx.innerText = `↑ ${live.tx_human}`;
  185. // Main Interfaces Tree Table
  186. const ifaceRx = document.getElementById(`iface-rate-rx-${name}`);
  187. if (ifaceRx) ifaceRx.innerText = `↓ ${live.rx_human}`;
  188. const ifaceTx = document.getElementById(`iface-rate-tx-${name}`);
  189. if (ifaceTx) ifaceTx.innerText = `↑ ${live.tx_human}`;
  190. // VLAN Sub-interfaces Table
  191. const vlanRx = document.getElementById(`vlan-rate-rx-${name}`);
  192. if (vlanRx) vlanRx.innerText = `↓ ${live.rx_human}`;
  193. const vlanTx = document.getElementById(`vlan-rate-tx-${name}`);
  194. if (vlanTx) vlanTx.innerText = `↑ ${live.tx_human}`;
  195. // VLAN Page Table
  196. const vlanPageRx = document.getElementById(`vlan-page-rate-rx-${name}`);
  197. if (vlanPageRx) vlanPageRx.innerText = `↓ ${live.rx_human}`;
  198. const vlanPageTx = document.getElementById(`vlan-page-rate-tx-${name}`);
  199. if (vlanPageTx) vlanPageTx.innerText = `↑ ${live.tx_human}`;
  200. });
  201. }
  202. // Navigation Handler
  203. function navigate(tabName) {
  204. if (tabName === 'dynamic-routing' || tabName === 'routing') {
  205. navigate('bgp');
  206. return;
  207. }
  208. if (tabName === 'vlans') {
  209. navigate('interfaces');
  210. return;
  211. }
  212. state.activeTab = tabName;
  213. window.location.hash = tabName;
  214. // Update nav links styling
  215. document.querySelectorAll('.nav-link').forEach(link => {
  216. link.className = 'nav-link flex items-center justify-between px-3 py-2 rounded-lg text-xs font-medium transition-all group text-slate-300 hover:bg-slate-800/80 hover:text-white';
  217. });
  218. const activeNav = document.getElementById(`nav-${tabName}`);
  219. if (activeNav) {
  220. activeNav.className = 'nav-link flex items-center justify-between px-3 py-2 rounded-lg text-xs font-medium transition-all group bg-brand-500/10 text-brand-400 border border-brand-500/20';
  221. }
  222. // Update page headers
  223. const titles = {
  224. dashboard: { title: 'Dashboard Overview', sub: 'Live router performance and network telemetry' },
  225. interfaces: { title: 'Network Interfaces', sub: 'Interface Table View' },
  226. 'dhcp-client': { title: 'DHCP Client', sub: 'DHCP Client List' },
  227. 'dhcp-server': { title: 'DHCP Server & Subnets', sub: 'DHCP Server instances, subnet networks (NTP, TFTP, DNS), dynamic leases & static reservations' },
  228. bridge: { title: 'Bridge Interfaces', sub: 'IEEE 802.1D / 802.1Q VLAN-aware Layer 2 switching, RSTP & hardware forwarding (FDB)' },
  229. vlans: { title: 'VLAN Virtual Networks', sub: 'IEEE 802.1Q sub-interface segmentation and routing' },
  230. firewall: { title: 'Network Firewall', sub: 'Stateful packet inspection, NAT, traffic mangle, address lists & connection tracking' },
  231. routes: { title: 'Routing & Policy', sub: 'Routing tables, static routes (DAS/DAC), and policy routing rules' },
  232. bgp: { title: 'BGP Dynamic Routing', sub: 'BGP multi-instance peering sessions, advertised networks, and routing table (RIB)' },
  233. ospf: { title: 'OSPF Dynamic Routing', sub: 'OSPFv2 link-state routing, dynamic neighbor adjacencies, and multi-area topology' },
  234. 'routing-filters': { title: 'Routing Policy Filters', sub: 'Route filter chains, prefix matching, BGP community maps & policy-based path control' },
  235. 'dynamic-routing': { title: 'BGP Dynamic Routing', sub: 'Dynamic routing engine and peering sessions' },
  236. ppp: { title: 'PPP Servers & Secrets', sub: 'Subscriber authentication, dynamic IP pools and VPN access concentrators' },
  237. eoip: { title: 'EoIP Tunnels', sub: 'Ethernet over IP (EoIP / GRETAP) Layer 2 encapsulation & transparent network bridging' },
  238. aerotun: { title: 'AeroTUN High-Speed VPN', sub: 'Ultra-fast Layer 3 encrypted tunnel with ChaCha20-Poly1305 and live Adaptive LZ4 compression' },
  239. pppoe: { title: 'PPPoE Client WAN', sub: 'Point-to-Point Protocol over Ethernet WAN access' },
  240. wireguard: { title: 'WireGuard VPN', sub: 'High-performance cryptographic Layer 3 tunnels with ChaCha20-Poly1305 key exchange' },
  241. ipsec: { title: 'IPSec (IKEv2) strongSwan', sub: 'Enterprise Site-to-Site & Roadwarrior IPSec controller' },
  242. l2tp: { title: 'L2TP VPN Client', sub: 'Layer 2 Tunneling Protocol via xl2tpd' },
  243. pptp: { title: 'PPTP VPN Client', sub: 'Point-to-Point Tunneling Protocol with MPPE-128 encryption' },
  244. vrrp: { title: 'VRRP High Availability', sub: 'Virtual Router Redundancy Protocol, active-backup gateway failover & Virtual IP (VIP) routing' },
  245. bwtest: { title: 'Bandwidth Test Benchmark', sub: 'High-speed line-rate throughput benchmark, token-bucket rate limiting, loss & jitter telemetry' },
  246. tools: { title: 'Diagnostic & Troubleshooting Tools', sub: 'Network latency analysis, ICMP/MTR telemetry, path tracing, DNS resolution and TCP probing' },
  247. persistence: { title: 'Debian Configuration', sub: 'Native /etc/network/interfaces.d/ persistence manager' },
  248. settings: { title: 'Router Settings & DNS', sub: 'System DNS forwarder, upstream resolvers, static host mappings, and appliance identity' }
  249. };
  250. const header = titles[tabName] || titles.dashboard;
  251. const pTitle = document.getElementById('page-title');
  252. if (pTitle) pTitle.innerText = header.title;
  253. const pSub = document.getElementById('page-subtitle');
  254. if (pSub) pSub.innerText = header.sub;
  255. // Toggle sections dynamically for all section elements
  256. document.querySelectorAll('main section[id^="section-"]').forEach(el => {
  257. if (el.id === `section-${tabName}`) {
  258. el.classList.remove('hidden');
  259. } else {
  260. el.classList.add('hidden');
  261. }
  262. });
  263. if (tabName === 'interfaces') {
  264. loadRoles();
  265. if (state.activeIfaceSubTab === 'roles') switchIfaceSubTab('roles');
  266. else switchIfaceSubTab('tree');
  267. }
  268. if (tabName === 'bridge') loadBridge();
  269. if (tabName === 'firewall') loadFirewall();
  270. if (tabName === 'routes') loadRoutes();
  271. if (tabName === 'bgp') {
  272. loadDynamicRouting();
  273. switchBgpSubTab(state.activeBgpSubTab || 'bgp-peers');
  274. }
  275. if (tabName === 'ospf') {
  276. loadDynamicRouting();
  277. switchOspfTab(state.activeOspfTab || 'instances');
  278. }
  279. if (tabName === 'routing-filters') loadDynamicRouting();
  280. if (tabName === 'dynamic-routing') loadDynamicRouting();
  281. if (tabName === 'ppp') loadPPP();
  282. if (tabName === 'eoip') loadEoIP();
  283. if (tabName === 'aerotun') loadAeroTUN();
  284. if (tabName === 'persistence') loadDebianConfig();
  285. if (tabName === 'pppoe') loadPPPoE();
  286. if (tabName === 'wireguard') loadWireGuard();
  287. if (tabName === 'ipsec') loadIPSec();
  288. if (tabName === 'l2tp') loadL2TP();
  289. if (tabName === 'pptp') loadPPTP();
  290. if (tabName === 'tools') loadToolsView();
  291. if (tabName === 'dhcp-client') loadDHCPClients();
  292. if (tabName === 'dhcp-server') loadDHCPServer();
  293. if (tabName === 'vrrp') loadVRRP();
  294. if (tabName === 'bwtest') loadBwTestView();
  295. if (tabName === 'settings') loadSettingsData();
  296. setTimeout(initTableSorting, 50);
  297. }
  298. // Fetch all core system, network and VPN telemetry
  299. async function fetchData(isManual = false) {
  300. const spinner = document.getElementById('refresh-spinner');
  301. if (isManual && spinner) spinner.classList.add('animate-spin');
  302. try {
  303. const [statusRes, ifacesRes, vlansRes, vpnRes, fwRes, dynRes, brSummaryRes, dhcpSumRes, dhcpClientsRes, vrrpSumRes, rolesRes] = await Promise.all([
  304. fetch(`${API_BASE}/system/status`),
  305. fetch(`${API_BASE}/interfaces`),
  306. fetch(`${API_BASE}/vlans`),
  307. fetch(`${API_BASE}/vpn/status`),
  308. fetch(`${API_BASE}/firewall/summary`),
  309. fetch(`${API_BASE}/routing/dynamic/summary`),
  310. fetch(`${API_BASE}/bridge/summary`),
  311. fetch(`${API_BASE}/dhcp/clients/summary`),
  312. fetch(`${API_BASE}/dhcp/clients`),
  313. fetch(`${API_BASE}/vrrp/summary`).catch(() => null),
  314. fetch(`${API_BASE}/roles`).catch(() => null)
  315. ]);
  316. if (rolesRes && rolesRes.ok) {
  317. state.roles = await rolesRes.json();
  318. const countEl = document.getElementById('badge-roles-count');
  319. if (countEl) countEl.innerText = (state.roles || []).length;
  320. }
  321. if (vrrpSumRes && vrrpSumRes.ok) {
  322. state.vrrpSummary = await vrrpSumRes.json();
  323. renderVRRPSummary();
  324. }
  325. if (dhcpSumRes && dhcpSumRes.ok) {
  326. state.dhcpSummary = await dhcpSumRes.json();
  327. const bDhcp = document.getElementById('badge-dhcp-client-count');
  328. if (bDhcp) bDhcp.innerText = state.dhcpSummary?.total_clients || 0;
  329. }
  330. if (dhcpClientsRes && dhcpClientsRes.ok) {
  331. state.dhcpClients = await dhcpClientsRes.json();
  332. }
  333. if (brSummaryRes.ok) {
  334. state.bridgeSummary = await brSummaryRes.json();
  335. const bBridge = document.getElementById('badge-bridge-count');
  336. if (bBridge) bBridge.innerText = state.bridgeSummary?.bridges_count || 0;
  337. const sBr = document.getElementById('bridge-stat-bridges');
  338. if (sBr) sBr.innerText = state.bridgeSummary?.bridges_count || 0;
  339. const sPorts = document.getElementById('bridge-stat-ports');
  340. if (sPorts) sPorts.innerText = state.bridgeSummary?.ports_count || 0;
  341. const sHosts = document.getElementById('bridge-stat-hosts');
  342. if (sHosts) sHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  343. }
  344. if (statusRes.ok) state.systemStatus = await statusRes.json();
  345. if (ifacesRes.ok) {
  346. const ifacesData = await ifacesRes.json();
  347. const rawIfaces = Array.isArray(ifacesData) ? ifacesData : [];
  348. state.interfaces = rawIfaces.filter(i => {
  349. if (!i.name) return false;
  350. if (i.name.startsWith('ep_')) return false;
  351. return !['gre0', 'gretap0', 'erspan0', 'sit0', 'tunl0', 'ip6tnl0', 'ip6gre0', 'ip6erspan0'].includes(i.name);
  352. });
  353. try { populateToolsInterfaces(); } catch (e) {}
  354. }
  355. if (vlansRes.ok) {
  356. const vlansData = await vlansRes.json();
  357. state.vlans = Array.isArray(vlansData) ? vlansData : [];
  358. }
  359. if (vpnRes.ok) state.vpnStatus = await vpnRes.json();
  360. if (fwRes && fwRes.ok) state.fwSummary = await fwRes.json();
  361. if (dynRes && dynRes.ok) state.dynSummary = await dynRes.json();
  362. updateSystemMetrics();
  363. updateBadges();
  364. if (state.activeTab === 'dashboard') renderDashboard();
  365. if (state.activeTab === 'interfaces') {
  366. if (state.activeIfaceSubTab === 'roles') renderRolesTable();
  367. else renderInterfacesList();
  368. }
  369. if (state.activeTab === 'vlans') renderVlansList();
  370. if (state.activeTab === 'firewall') loadFirewall(false);
  371. if (state.activeTab === 'routes') loadRoutes(false);
  372. if (state.activeTab === 'dynamic-routing' || state.activeTab === 'bgp' || state.activeTab === 'ospf') loadDynamicRouting(false);
  373. if (state.activeTab === 'ppp') loadPPP(false);
  374. if (state.activeTab === 'eoip') loadEoIP(false);
  375. if (state.activeTab === 'aerotun') loadAeroTUN(false);
  376. if (state.activeTab === 'pppoe') loadPPPoE(false);
  377. if (state.activeTab === 'wireguard') loadWireGuard(false);
  378. if (state.activeTab === 'ipsec') loadIPSec(false);
  379. if (state.activeTab === 'l2tp') loadL2TP(false);
  380. if (state.activeTab === 'pptp') loadPPTP(false);
  381. if (state.activeTab === 'dhcp-client') loadDHCPClients(false);
  382. if (state.activeTab === 'dhcp-server') loadDHCPServer(false);
  383. if (state.activeTab === 'vrrp') loadVRRP(false);
  384. if (state.activeTab === 'settings') loadSettingsData(false);
  385. fetchBwTestServerStatus();
  386. } catch (err) {
  387. console.error('Failed to fetch router state:', err);
  388. } finally {
  389. if (isManual && spinner) {
  390. setTimeout(() => spinner.classList.remove('animate-spin'), 300);
  391. }
  392. }
  393. }
  394. // Update Top KPI and Sidebar Telemetry
  395. function updateSystemMetrics() {
  396. const s = state.systemStatus;
  397. const v = state.vpnStatus;
  398. if (!s) return;
  399. // Sidebar Host & Uptime
  400. const sideHost = document.getElementById('side-hostname');
  401. if (sideHost) sideHost.innerText = s.hostname || 'debian-lxc';
  402. const sideUp = document.getElementById('side-uptime');
  403. if (sideUp) sideUp.innerText = s.uptime_human || '0m';
  404. const sideGw = document.getElementById('side-gateway-ip');
  405. if (sideGw) sideGw.innerText = s.default_gateway ? `GW: ${s.default_gateway}` : 'GW: Isolated';
  406. // Compute CPU Metrics
  407. let cpuPct = 0;
  408. if (s.cpu_pct !== undefined) {
  409. cpuPct = s.cpu_pct;
  410. } else if (s.cpu_load && s.cpu_load.length > 0) {
  411. const cores = s.cpu_cores || 1;
  412. cpuPct = Math.min(100, Math.round((parseFloat(s.cpu_load[0]) / cores) * 100));
  413. }
  414. const cpuPctStr = `${cpuPct.toFixed(1)}%`;
  415. const cpuWidth = `${Math.max(3, Math.min(100, cpuPct))}%`;
  416. const loadStr = s.cpu_load ? s.cpu_load.join(', ') : '-';
  417. // Sidebar CPU
  418. const sideCpuVal = document.getElementById('side-cpu-val');
  419. if (sideCpuVal) sideCpuVal.innerText = cpuPctStr;
  420. const sideCpuBar = document.getElementById('side-cpu-bar');
  421. if (sideCpuBar) {
  422. sideCpuBar.style.width = cpuWidth;
  423. sideCpuBar.title = `Container: ${cpuPctStr} | Host Loadavg: ${loadStr} (${s.cpu_cores || 1} cores)`;
  424. }
  425. // Dashboard CPU Card
  426. const dashCpuVal = document.getElementById('dash-cpu-val');
  427. if (dashCpuVal) dashCpuVal.innerText = cpuPctStr;
  428. const dashCpuBar = document.getElementById('dash-cpu-bar');
  429. if (dashCpuBar) {
  430. dashCpuBar.style.width = cpuWidth;
  431. if (cpuPct > 85) {
  432. dashCpuBar.className = 'h-full rounded-full bg-rose-500 transition-all duration-500';
  433. } else if (cpuPct > 65) {
  434. dashCpuBar.className = 'h-full rounded-full bg-amber-500 transition-all duration-500';
  435. } else {
  436. dashCpuBar.className = 'h-full rounded-full bg-emerald-500 transition-all duration-500';
  437. }
  438. }
  439. const dashCpuCores = document.getElementById('dash-cpu-cores');
  440. if (dashCpuCores) dashCpuCores.innerText = `${s.cpu_cores || 1} Cores`;
  441. const dashCpuLoad = document.getElementById('dash-cpu-load');
  442. if (dashCpuLoad) dashCpuLoad.innerText = loadStr;
  443. const dashCpuStatus = document.getElementById('dash-cpu-status');
  444. if (dashCpuStatus) {
  445. if (cpuPct > 85) {
  446. dashCpuStatus.innerText = 'High';
  447. dashCpuStatus.className = 'text-[11px] font-semibold text-rose-400 uppercase px-2 py-0.5 rounded bg-rose-500/10';
  448. } else if (cpuPct > 65) {
  449. dashCpuStatus.innerText = 'Heavy';
  450. dashCpuStatus.className = 'text-[11px] font-semibold text-amber-400 uppercase px-2 py-0.5 rounded bg-amber-500/10';
  451. } else {
  452. dashCpuStatus.innerText = 'Normal';
  453. dashCpuStatus.className = 'text-[11px] font-semibold text-emerald-400 uppercase px-2 py-0.5 rounded bg-emerald-500/10';
  454. }
  455. }
  456. // Compute RAM Metrics
  457. const memPct = Math.round(s.mem_usage_pct || 0);
  458. const memPctStr = `${memPct}%`;
  459. const memWidth = `${Math.max(3, Math.min(100, memPct))}%`;
  460. const usedMB = s.mem_used_mb || 0;
  461. const totalMB = s.mem_total_mb || 0;
  462. const freeMB = totalMB > usedMB ? totalMB - usedMB : 0;
  463. function fmtMemMB(mb) {
  464. if (mb >= 1024) {
  465. return `${(mb / 1024).toFixed(1)} GB`;
  466. }
  467. return `${mb} MB`;
  468. }
  469. // Sidebar RAM
  470. const sideRamVal = document.getElementById('side-ram-val');
  471. if (sideRamVal) sideRamVal.innerText = memPctStr;
  472. const sideRamBar = document.getElementById('side-ram-bar');
  473. if (sideRamBar) sideRamBar.style.width = memWidth;
  474. // Dashboard RAM Card
  475. const dashRamVal = document.getElementById('dash-ram-val');
  476. if (dashRamVal) dashRamVal.innerText = memPctStr;
  477. const dashRamBar = document.getElementById('dash-ram-bar');
  478. if (dashRamBar) {
  479. dashRamBar.style.width = memWidth;
  480. if (memPct > 85) {
  481. dashRamBar.className = 'h-full rounded-full bg-rose-500 transition-all duration-500';
  482. } else if (memPct > 70) {
  483. dashRamBar.className = 'h-full rounded-full bg-amber-500 transition-all duration-500';
  484. } else {
  485. dashRamBar.className = 'h-full rounded-full bg-indigo-500 transition-all duration-500';
  486. }
  487. }
  488. const dashRamUsedTotal = document.getElementById('dash-ram-used-total');
  489. if (dashRamUsedTotal) {
  490. dashRamUsedTotal.innerText = `${fmtMemMB(usedMB)} / ${fmtMemMB(totalMB)}`;
  491. }
  492. const dashRamFree = document.getElementById('dash-ram-free');
  493. if (dashRamFree) {
  494. dashRamFree.innerText = fmtMemMB(freeMB);
  495. }
  496. const dashRamStatus = document.getElementById('dash-ram-status');
  497. if (dashRamStatus) {
  498. if (memPct > 85) {
  499. dashRamStatus.innerText = 'High';
  500. dashRamStatus.className = 'text-[11px] font-semibold text-rose-400 uppercase px-2 py-0.5 rounded bg-rose-500/10';
  501. } else {
  502. dashRamStatus.innerText = 'Active';
  503. dashRamStatus.className = 'text-[11px] font-semibold text-indigo-400 uppercase px-2 py-0.5 rounded bg-indigo-500/10';
  504. }
  505. }
  506. // Legacy Dashboard Stats (Safe checks)
  507. const elIfacesUp = document.getElementById('stat-ifaces-up');
  508. if (elIfacesUp) elIfacesUp.innerText = s.up_ifaces || 0;
  509. const elIfacesTot = document.getElementById('stat-ifaces-total');
  510. if (elIfacesTot) elIfacesTot.innerText = `${s.total_ifaces || 0} Total`;
  511. const elIfacesDown = document.getElementById('stat-ifaces-down');
  512. if (elIfacesDown) elIfacesDown.innerText = `${s.down_ifaces || 0} DOWN`;
  513. const elVlans = document.getElementById('stat-vlans-count');
  514. if (elVlans) elVlans.innerText = s.vlan_ifaces || 0;
  515. // VPN Status Indicators
  516. if (v) {
  517. const totalActive = v.total_active_tunnels || 0;
  518. const statVpnActive = document.getElementById('stat-vpn-active');
  519. if (statVpnActive) statVpnActive.innerText = totalActive;
  520. const tunnelsDot = document.getElementById('tunnels-dot');
  521. const tunnelsLabel = document.getElementById('tunnels-label');
  522. if (tunnelsDot && tunnelsLabel) {
  523. if (totalActive > 0) {
  524. tunnelsDot.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  525. tunnelsLabel.innerText = `${totalActive} Active VPN Tunnel${totalActive > 1 ? 's' : ''}`;
  526. } else {
  527. tunnelsDot.className = 'w-2 h-2 rounded-full bg-slate-500';
  528. tunnelsLabel.innerText = '0 Active VPN Tunnels';
  529. }
  530. }
  531. setDotBadge('badge-pppoe-status', (v.active_pppoe || 0) > 0 || v.pppoe_connected);
  532. setDotBadge('badge-wg-status', (v.active_wireguard || 0) > 0 || v.wireguard_active);
  533. setDotBadge('badge-ipsec-status', (v.active_ipsec || 0) > 0 || v.ipsec_active);
  534. setDotBadge('badge-l2tp-status', (v.active_l2tp || 0) > 0 || v.l2tp_connected);
  535. setDotBadge('badge-pptp-status', (v.active_pptp || 0) > 0 || v.pptp_connected);
  536. }
  537. // Total Live Bandwidth Rate
  538. let totalRx = 0;
  539. let totalTx = 0;
  540. (state.interfaces || []).forEach(i => {
  541. if (i.rate) {
  542. totalRx += i.rate.rx_bytes_sec || 0;
  543. totalTx += i.rate.tx_bytes_sec || 0;
  544. }
  545. });
  546. document.getElementById('stat-traffic-rx').innerText = formatTraffic(totalRx);
  547. document.getElementById('stat-traffic-tx').innerText = formatTraffic(totalTx);
  548. }
  549. function setDotBadge(id, active) {
  550. const el = document.getElementById(id);
  551. if (!el) return;
  552. if (active) {
  553. el.className = 'w-2 h-2 rounded-full bg-emerald-400 shadow-sm shadow-emerald-400/80';
  554. } else {
  555. el.className = 'w-2 h-2 rounded-full bg-slate-600';
  556. }
  557. }
  558. function updateBadges() {
  559. const bIfaces = document.getElementById('badge-ifaces-count');
  560. if (bIfaces) bIfaces.innerText = (state.interfaces || []).length;
  561. const bVlans = document.getElementById('badge-vlans-count');
  562. if (bVlans) bVlans.innerText = (state.vlans || []).length;
  563. if (state.fwSummary) {
  564. const totalFwRules = (state.fwSummary.filter_rules_count || 0) + (state.fwSummary.nat_rules_count || 0) + (state.fwSummary.mangle_rules_count || 0);
  565. const badgeFw = document.getElementById('badge-firewall-count');
  566. if (badgeFw) badgeFw.innerText = totalFwRules;
  567. }
  568. if (state.vpnStatus) {
  569. const v = state.vpnStatus;
  570. const bEoIP = document.getElementById('badge-eoip-count');
  571. if (bEoIP) bEoIP.innerText = v.total_eoip || 0;
  572. const bAero = document.getElementById('badge-aerotun-count');
  573. if (bAero) bAero.innerText = v.total_aerotun || 0;
  574. const bPPPSess = document.getElementById('badge-ppp-sessions');
  575. if (bPPPSess) bPPPSess.innerText = v.total_ppp_sessions || 0;
  576. setDotBadge('badge-pppoe-status', v.active_pppoe > 0 || v.pppoe_server_running);
  577. setDotBadge('badge-wg-status', v.active_wireguard > 0);
  578. setDotBadge('badge-ipsec-status', v.active_ipsec > 0 || v.ipsec_server_running);
  579. setDotBadge('badge-l2tp-status', v.active_l2tp > 0 || v.l2tp_server_running);
  580. setDotBadge('badge-pptp-status', v.active_pptp > 0 || v.pptp_server_running);
  581. }
  582. if (state.dynSummary) {
  583. const d = state.dynSummary;
  584. setDotBadge('badge-bgp-dot', d.bgp_running);
  585. setDotBadge('badge-ospf-dot', d.ospf_running);
  586. const bBgp = document.getElementById('badge-bgp-count');
  587. if (bBgp) bBgp.innerText = (state.bgpPeers || []).length;
  588. const bOspf = document.getElementById('badge-ospf-count');
  589. if (bOspf) bOspf.innerText = (state.ospfInterfaces || []).length;
  590. const bFilters = document.getElementById('badge-filters-count');
  591. if (bFilters) bFilters.innerText = (state.routingFilters || []).length;
  592. }
  593. const bDhcpServer = document.getElementById('badge-dhcp-server-count');
  594. if (bDhcpServer) {
  595. bDhcpServer.innerText = state.dhcpServerSummary ? (state.dhcpServerSummary.active_leases || state.dhcpServerSummary.total_servers || 0) : (state.dhcpServers || []).length;
  596. }
  597. }
  598. // Render Dashboard View
  599. function renderDashboard() {
  600. const matrix = document.getElementById('port-matrix');
  601. if (!matrix) return;
  602. const ifaces = state.interfaces || [];
  603. const sig = ifaces.map(i => `${i.name}:${i.state}:${(i.ipv4 || []).join(',')}:${i.type}:${i.is_vlan}`).join(';');
  604. if (matrix.dataset.sig === sig) {
  605. return; // Structure & link states haven't changed! Do not rebuild or flicker!
  606. }
  607. matrix.dataset.sig = sig;
  608. matrix.innerHTML = '';
  609. (state.interfaces || []).forEach(iface => {
  610. const isUp = iface.state === 'UP';
  611. const isVlan = iface.is_vlan;
  612. const portCard = document.createElement('div');
  613. portCard.className = `p-3 rounded-xl border transition-all cursor-pointer select-none group ${
  614. isUp
  615. ? (isVlan ? 'bg-cyan-950/20 border-cyan-800/60 hover:border-cyan-500' : 'bg-slate-800/80 border-slate-700/80 hover:border-brand-500')
  616. : 'bg-slate-900/40 border-slate-800/60 opacity-60 hover:opacity-100 hover:border-slate-700'
  617. }`;
  618. portCard.onclick = () => openIfaceModal(iface.name);
  619. let statusPillClass = isUp ? 'bg-emerald-500 shadow-sm shadow-emerald-500/50' : 'bg-rose-500';
  620. if (isVlan) statusPillClass = isUp ? 'bg-cyan-400 shadow-sm shadow-cyan-400/50' : 'bg-rose-500';
  621. portCard.innerHTML = `
  622. <div class="flex items-center justify-between mb-2">
  623. <span class="font-bold text-xs font-mono text-white group-hover:text-brand-400 transition truncate">${iface.name}</span>
  624. <span class="w-2 h-2 rounded-full ${statusPillClass}"></span>
  625. </div>
  626. <div class="text-[11px] font-mono text-slate-300 truncate">${iface.ipv4 && iface.ipv4.length > 0 ? iface.ipv4[0] : (iface.mac || 'No IP')}</div>
  627. <div class="mt-2 flex items-center justify-between text-[10px] text-slate-400">
  628. <span class="uppercase tracking-wider font-semibold">${isVlan ? `VLAN ${iface.vlan_id}` : iface.type}</span>
  629. <span id="port-card-rate-${iface.name}">${iface.rate?.rx_human || '0 B/s'}</span>
  630. </div>
  631. `;
  632. matrix.appendChild(portCard);
  633. });
  634. const ifaceTbody = document.getElementById('quick-interfaces-table');
  635. if (ifaceTbody) {
  636. ifaceTbody.innerHTML = '';
  637. (state.interfaces || []).forEach(i => {
  638. const isUp = i.state === 'UP';
  639. const tr = document.createElement('tr');
  640. tr.className = 'hover:bg-slate-800/40 transition cursor-pointer';
  641. tr.onclick = () => openIfaceModal(i.name);
  642. const rxStr = i.rate?.rx_human || '0 B/s';
  643. const txStr = i.rate?.tx_human || '0 B/s';
  644. tr.innerHTML = `
  645. <td class="py-2.5 font-bold text-white flex items-center gap-2">
  646. <span class="w-2 h-2 rounded-full ${isUp ? 'bg-emerald-400 shadow-sm shadow-emerald-400/50' : 'bg-rose-400'}"></span>
  647. <span>${i.name}</span>
  648. </td>
  649. <td class="py-2.5 text-slate-300 font-sans">
  650. ${getRoleBadge(i.role || 'LAN')}
  651. </td>
  652. <td class="py-2.5 text-slate-400 text-[11px] font-mono">${i.mac || '-'}</td>
  653. <td class="py-2.5 text-slate-200 font-semibold">${i.ipv4 && i.ipv4.length > 0 ? i.ipv4.join(', ') : '<span class="text-slate-600 font-normal">Unassigned</span>'}</td>
  654. <td class="py-2.5 text-slate-300 text-[11px] font-mono">
  655. <span id="quick-rx-${i.name}" class="text-emerald-400">↓ ${rxStr}</span> <span class="text-slate-600">•</span> <span id="quick-tx-${i.name}" class="text-cyan-400">↑ ${txStr}</span>
  656. </td>
  657. <td class="py-2.5 text-right font-sans font-semibold">
  658. <span class="px-2 py-0.5 rounded text-[10px] ${isUp ? 'bg-emerald-500/10 text-emerald-400 border border-emerald-500/20' : 'bg-rose-500/10 text-rose-400 border border-rose-500/20'}">${i.state}</span>
  659. </td>
  660. `;
  661. ifaceTbody.appendChild(tr);
  662. });
  663. }
  664. const vlanTbody = document.getElementById('quick-vlans-table');
  665. if (vlanTbody) {
  666. vlanTbody.innerHTML = '';
  667. }
  668. }
  669. // Expand / Collapse Handlers
  670. function toggleExpand(parentName) {
  671. if (state.expandedParents.has(parentName)) {
  672. state.expandedParents.delete(parentName);
  673. } else {
  674. state.expandedParents.add(parentName);
  675. }
  676. renderInterfacesList();
  677. }
  678. // VLAN Support Checker: 802.1Q sub-interfaces are only supported on physical ethernet, veth, bridge, bond
  679. function supportsVLAN(iface) {
  680. if (!iface) return false;
  681. if (iface.is_vlan) return false;
  682. const name = (iface.name || '').toLowerCase();
  683. const type = (iface.type || '').toLowerCase();
  684. const role = (iface.role || '').toLowerCase();
  685. // Exclude loopback
  686. if (name === 'lo' || type === 'loopback' || role === 'loopback') return false;
  687. // Exclude WireGuard (Layer 3 tunnel, no 802.1Q support)
  688. if (type === 'wireguard' || name.startsWith('wg')) return false;
  689. // Exclude PPP / PPPoE
  690. if (type === 'ppp' || name.startsWith('ppp')) return false;
  691. // Exclude other Layer 3 tunnels and dummy devices
  692. if (type === 'dummy' || type === 'gre' || type === 'sit' || type === 'tun' || type === 'tap' ||
  693. name.startsWith('gre') || name.startsWith('sit') || name.startsWith('ipsec') || name.startsWith('xfrm') || name.startsWith('dummy')) {
  694. return false;
  695. }
  696. // If name already contains a dot, it's already a sub-interface
  697. if (name.includes('.')) return false;
  698. return true;
  699. }
  700. // DHCP Client Support Checker: Only broadcast-capable layer-2 interfaces (Ethernet, veth, VLAN, bridge, bond)
  701. function supportsDHCPClient(iface) {
  702. if (!iface) return false;
  703. const name = (iface.name || '').toLowerCase();
  704. const type = (iface.type || '').toLowerCase();
  705. const role = (iface.role || '').toLowerCase();
  706. // Exclude loopback
  707. if (name === 'lo' || type === 'loopback' || role === 'loopback') return false;
  708. // Exclude WireGuard (Layer 3 point-to-point tunnel, no broadcast/DHCP)
  709. if (type === 'wireguard' || name.startsWith('wg')) return false;
  710. // Exclude PPP / PPPoE / L2TP / PPTP tunnels
  711. if (type === 'ppp' || name.startsWith('ppp') || name.startsWith('l2tp') || name.startsWith('pptp')) return false;
  712. // Exclude other Layer 3 tunnels and dummy devices
  713. if (type === 'dummy' || type === 'gre' || type === 'sit' || type === 'tun' || type === 'tap' ||
  714. name.startsWith('gre') || name.startsWith('sit') || name.startsWith('ipsec') || name.startsWith('xfrm') || name.startsWith('dummy')) {
  715. return false;
  716. }
  717. // Exclude bridge member/slave ports (bridge itself handles IP / DHCP)
  718. const isBridgePort = (state.bridgePorts || []).some(bp => bp.interface === iface.name);
  719. if (isBridgePort) return false;
  720. return true;
  721. }
  722. // Expand / Collapse Handlers
  723. function toggleExpand(parentName) {
  724. const childVlans = (state.vlans || []).filter(v => v.parent_name === parentName || v.name.startsWith(parentName + '.'));
  725. if (childVlans.length === 0) {
  726. // Cannot expand an interface with no VLANs
  727. state.expandedParents.delete(parentName);
  728. return;
  729. }
  730. if (state.expandedParents.has(parentName)) {
  731. state.expandedParents.delete(parentName);
  732. } else {
  733. state.expandedParents.add(parentName);
  734. }
  735. renderInterfacesList();
  736. }
  737. function expandAllIfaces(expand) {
  738. if (expand) {
  739. (state.interfaces || []).forEach(i => {
  740. const hasVlans = (state.vlans || []).some(v => v.parent_name === i.name || v.name.startsWith(i.name + '.'));
  741. if (!i.is_vlan && hasVlans) state.expandedParents.add(i.name);
  742. });
  743. } else {
  744. state.expandedParents.clear();
  745. }
  746. renderInterfacesList();
  747. }
  748. // =========================================================================
  749. // INTERFACE ROLE TAGS MANAGEMENT
  750. // =========================================================================
  751. const ROLE_COLORS = {
  752. amber: { bg: 'bg-amber-500/20', text: 'text-amber-300', border: 'border-amber-500/30' },
  753. blue: { bg: 'bg-blue-500/20', text: 'text-blue-300', border: 'border-blue-500/30' },
  754. cyan: { bg: 'bg-cyan-500/20', text: 'text-cyan-300', border: 'border-cyan-500/30' },
  755. emerald: { bg: 'bg-emerald-500/20', text: 'text-emerald-300', border: 'border-emerald-500/30' },
  756. purple: { bg: 'bg-purple-500/20', text: 'text-purple-300', border: 'border-purple-500/30' },
  757. rose: { bg: 'bg-rose-500/20', text: 'text-rose-300', border: 'border-rose-500/30' },
  758. indigo: { bg: 'bg-indigo-500/20', text: 'text-indigo-300', border: 'border-indigo-500/30' },
  759. sky: { bg: 'bg-sky-500/20', text: 'text-sky-300', border: 'border-sky-500/30' },
  760. slate: { bg: 'bg-slate-800', text: 'text-slate-300', border: 'border-slate-700' }
  761. };
  762. function getRoleBadge(roleName) {
  763. const name = roleName || 'LAN';
  764. const role = (state.roles || []).find(r => r.name.toLowerCase() === name.toLowerCase() || r.id.toLowerCase() === name.toLowerCase());
  765. const colorKey = (role?.color || 'blue').toLowerCase();
  766. const theme = ROLE_COLORS[colorKey] || ROLE_COLORS.blue;
  767. return `<span class="px-2 py-0.5 rounded text-[10px] font-semibold ${theme.bg} ${theme.text} border ${theme.border}" title="Role Tag: ${escapeHtml(name)}">${escapeHtml(name)}</span>`;
  768. }
  769. function switchIfaceSubTab(subTab) {
  770. state.activeIfaceSubTab = subTab;
  771. const treeTab = document.getElementById('ifaces-subtab-tree');
  772. const rolesTab = document.getElementById('ifaces-subtab-roles');
  773. const btnTree = document.getElementById('ifaces-subtab-btn-tree');
  774. const btnRoles = document.getElementById('ifaces-subtab-btn-roles');
  775. if (subTab === 'roles') {
  776. treeTab?.classList.add('hidden');
  777. rolesTab?.classList.remove('hidden');
  778. if (btnRoles) {
  779. btnRoles.className = 'px-3.5 py-1.5 rounded-lg text-xs font-semibold bg-brand-500/10 text-brand-400 border border-brand-500/20 transition flex items-center gap-1.5';
  780. }
  781. if (btnTree) {
  782. btnTree.className = 'px-3.5 py-1.5 rounded-lg text-xs font-medium text-slate-400 hover:text-white hover:bg-slate-800 transition flex items-center gap-1.5';
  783. }
  784. loadRoles();
  785. } else {
  786. rolesTab?.classList.add('hidden');
  787. treeTab?.classList.remove('hidden');
  788. if (btnTree) {
  789. btnTree.className = 'px-3.5 py-1.5 rounded-lg text-xs font-semibold bg-brand-500/10 text-brand-400 border border-brand-500/20 transition flex items-center gap-1.5';
  790. }
  791. if (btnRoles) {
  792. btnRoles.className = 'px-3.5 py-1.5 rounded-lg text-xs font-medium text-slate-400 hover:text-white hover:bg-slate-800 transition flex items-center gap-1.5';
  793. }
  794. renderInterfacesList();
  795. }
  796. }
  797. async function loadRoles() {
  798. try {
  799. const res = await fetch(`${API_BASE}/roles`);
  800. if (res.ok) {
  801. state.roles = await res.json();
  802. const countEl = document.getElementById('badge-roles-count');
  803. if (countEl) countEl.innerText = (state.roles || []).length;
  804. renderRolesTable();
  805. populateRoleSelects();
  806. }
  807. } catch (err) {
  808. console.error('Failed to load role tags:', err);
  809. }
  810. }
  811. function renderRolesTable() {
  812. const tbody = document.getElementById('roles-table-body');
  813. const empty = document.getElementById('roles-empty-state');
  814. if (!tbody) return;
  815. const roles = state.roles || [];
  816. if (roles.length === 0) {
  817. tbody.innerHTML = '';
  818. empty?.classList.remove('hidden');
  819. return;
  820. }
  821. empty?.classList.add('hidden');
  822. const sig = roles.map(r => `${r.id}:${r.name}:${r.color}:${r.description}:${(r.interfaces||[]).join(',')}`).join(';');
  823. if (tbody.dataset.sig === sig) return;
  824. tbody.dataset.sig = sig;
  825. tbody.innerHTML = roles.map(r => {
  826. const colorKey = (r.color || 'blue').toLowerCase();
  827. const theme = ROLE_COLORS[colorKey] || ROLE_COLORS.blue;
  828. const ifaces = Array.isArray(r.interfaces) ? r.interfaces : [];
  829. const ifacesChips = ifaces.length > 0
  830. ? ifaces.map(name => `<span onclick="openIfaceModal('${escapeHtml(name)}')" class="cursor-pointer px-2 py-0.5 rounded text-[10px] font-mono bg-slate-800 text-slate-200 border border-slate-700 hover:border-cyan-500 transition mr-1 mb-1 inline-block" title="Click to view/edit ${escapeHtml(name)}">${escapeHtml(name)}</span>`).join('')
  831. : '<span class="text-slate-600 font-sans text-xs italic">Unassigned (0)</span>';
  832. return `
  833. <tr class="hover:bg-slate-800/40 transition">
  834. <td class="py-3 px-4">
  835. <span class="px-2.5 py-1 rounded text-xs font-semibold ${theme.bg} ${theme.text} border ${theme.border}">
  836. ${escapeHtml(r.name)}
  837. </span>
  838. </td>
  839. <td class="py-3 px-4 font-bold text-white font-mono flex items-center gap-2">
  840. <span>${escapeHtml(r.name)}</span>
  841. ${r.builtin ? '<span class="text-[9px] px-1.5 py-0.2 rounded bg-slate-800 text-slate-400 border border-slate-700 uppercase font-sans">Builtin</span>' : ''}
  842. </td>
  843. <td class="py-3 px-4 font-sans capitalize text-slate-300">
  844. <span class="inline-flex items-center gap-1.5">
  845. <span class="w-2 h-2 rounded-full ${theme.bg.replace('/20', '')}"></span>
  846. <span>${escapeHtml(r.color || 'blue')}</span>
  847. </span>
  848. </td>
  849. <td class="py-3 px-4 font-sans text-slate-400 text-xs">${escapeHtml(r.description || '-')}</td>
  850. <td class="py-3 px-4 font-sans">
  851. <div class="flex flex-wrap items-center">
  852. ${ifacesChips}
  853. </div>
  854. </td>
  855. <td class="py-3 px-4 text-right space-x-2 font-sans whitespace-nowrap">
  856. <button onclick="openRoleModal('${escapeHtml(r.id)}')"
  857. class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold px-2 py-1 rounded hover:bg-slate-800 transition">
  858. Edit
  859. </button>
  860. <button onclick="deleteRoleTag('${escapeHtml(r.id)}', '${escapeHtml(r.name)}')"
  861. class="text-xs text-rose-400 hover:text-rose-300 font-semibold px-2 py-1 rounded hover:bg-slate-800 transition">
  862. Delete
  863. </button>
  864. </td>
  865. </tr>
  866. `;
  867. }).join('');
  868. }
  869. function openRoleModal(id = null) {
  870. const modal = document.getElementById('role-modal');
  871. if (!modal) return;
  872. const idInput = document.getElementById('role-modal-id');
  873. const nameInput = document.getElementById('role-modal-name');
  874. const colorSelect = document.getElementById('role-modal-color');
  875. const descInput = document.getElementById('role-modal-desc');
  876. const title = document.getElementById('role-modal-title');
  877. if (id) {
  878. const role = (state.roles || []).find(r => r.id === id);
  879. if (role) {
  880. if (title) title.innerText = `Edit Role Tag: ${role.name}`;
  881. if (idInput) idInput.value = role.id;
  882. if (nameInput) nameInput.value = role.name;
  883. if (colorSelect) colorSelect.value = role.color || 'blue';
  884. if (descInput) descInput.value = role.description || '';
  885. }
  886. } else {
  887. if (title) title.innerText = 'Add Role Tag';
  888. if (idInput) idInput.value = '';
  889. if (nameInput) nameInput.value = '';
  890. if (colorSelect) colorSelect.value = 'blue';
  891. if (descInput) descInput.value = '';
  892. }
  893. updateRoleModalPreview();
  894. modal.classList.remove('hidden');
  895. }
  896. function closeRoleModal() {
  897. const modal = document.getElementById('role-modal');
  898. if (modal) modal.classList.add('hidden');
  899. }
  900. function updateRoleModalPreview() {
  901. const name = document.getElementById('role-modal-name')?.value.trim() || 'Preview';
  902. const colorKey = (document.getElementById('role-modal-color')?.value || 'blue').toLowerCase();
  903. const theme = ROLE_COLORS[colorKey] || ROLE_COLORS.blue;
  904. const preview = document.getElementById('role-modal-preview');
  905. if (preview) {
  906. preview.innerText = name;
  907. preview.className = `px-2.5 py-1 rounded text-xs font-semibold ${theme.bg} ${theme.text} border ${theme.border}`;
  908. }
  909. }
  910. async function submitSaveRole(e) {
  911. e.preventDefault();
  912. const id = document.getElementById('role-modal-id')?.value;
  913. const name = document.getElementById('role-modal-name')?.value.trim();
  914. const color = document.getElementById('role-modal-color')?.value;
  915. const desc = document.getElementById('role-modal-desc')?.value.trim();
  916. if (!name) return;
  917. try {
  918. const payload = { id, name, color, description: desc };
  919. const method = id ? 'PUT' : 'POST';
  920. const url = id ? `${API_BASE}/roles/${encodeURIComponent(id)}` : `${API_BASE}/roles`;
  921. const res = await fetch(url, {
  922. method,
  923. headers: { 'Content-Type': 'application/json' },
  924. body: JSON.stringify(payload)
  925. });
  926. if (res.ok) {
  927. showToast('Role Tag Saved', `Role tag "${name}" saved successfully`, 'success');
  928. closeRoleModal();
  929. await loadRoles();
  930. fetchData(false);
  931. } else {
  932. const err = await res.json();
  933. showToast('Error', err.error || err.message || 'Failed to save role tag', 'error');
  934. }
  935. } catch (err) {
  936. showToast('Error', err.message, 'error');
  937. }
  938. }
  939. async function deleteRoleTag(id, name) {
  940. if (!confirm(`Are you sure you want to delete role tag "${name}"?\nInterfaces assigned to this role will default to LAN.`)) return;
  941. try {
  942. const res = await fetch(`${API_BASE}/roles/${encodeURIComponent(id)}`, {
  943. method: 'DELETE'
  944. });
  945. if (res.ok) {
  946. showToast('Role Tag Deleted', `Role tag "${name}" removed`, 'success');
  947. await loadRoles();
  948. fetchData(false);
  949. } else {
  950. const err = await res.json();
  951. showToast('Error', err.error || err.message || 'Failed to delete role tag', 'error');
  952. }
  953. } catch (err) {
  954. showToast('Error', err.message, 'error');
  955. }
  956. }
  957. function populateRoleSelects(selectedRole = '') {
  958. const ifaceSelect = document.getElementById('modal-iface-role');
  959. const vlanSelect = document.getElementById('vlan-role');
  960. const roles = state.roles || [];
  961. const optionsHtml = roles.map(r => `<option value="${escapeHtml(r.name)}">${escapeHtml(r.name)}${r.description ? ` (${escapeHtml(r.description)})` : ''}</option>`).join('');
  962. if (ifaceSelect) {
  963. const currentVal = selectedRole || ifaceSelect.value || 'LAN';
  964. if (ifaceSelect.dataset.optionsSig !== optionsHtml) {
  965. ifaceSelect.innerHTML = optionsHtml;
  966. ifaceSelect.dataset.optionsSig = optionsHtml;
  967. }
  968. if (currentVal) ifaceSelect.value = currentVal;
  969. }
  970. if (vlanSelect) {
  971. const currentVal = selectedRole || vlanSelect.value || 'LAN';
  972. if (vlanSelect.dataset.optionsSig !== optionsHtml) {
  973. vlanSelect.innerHTML = optionsHtml;
  974. vlanSelect.dataset.optionsSig = optionsHtml;
  975. }
  976. if (currentVal) vlanSelect.value = currentVal;
  977. }
  978. }
  979. // Filter and Render Hierarchical Interfaces List
  980. function filterIfaces(filter) {
  981. state.ifaceFilter = filter || 'all';
  982. renderInterfacesList();
  983. }
  984. function renderInterfacesList() {
  985. const tbody = document.getElementById('interfaces-tree-tbody');
  986. const emptyState = document.getElementById('interfaces-empty-state');
  987. const summary = document.getElementById('ifaces-list-summary');
  988. const query = (document.getElementById('iface-search')?.value || '').trim().toLowerCase();
  989. const allIfaces = state.interfaces || [];
  990. const allVlans = state.vlans || [];
  991. const parentIfaces = allIfaces.filter(i => !i.is_vlan);
  992. const filteredParents = parentIfaces.filter(parent => {
  993. const childVlans = allVlans.filter(v => v.parent_name === parent.name || v.name.startsWith(parent.name + '.'));
  994. if (query) {
  995. const matchName = parent.name.toLowerCase().includes(query);
  996. const matchIp = (parent.ipv4 || []).some(ip => ip.toLowerCase().includes(query));
  997. const matchRole = (parent.role || '').toLowerCase().includes(query);
  998. const matchType = (parent.type || '').toLowerCase().includes(query);
  999. const matchVlan = childVlans.some(v =>
  1000. v.name.toLowerCase().includes(query) ||
  1001. String(v.vlan_id).includes(query) ||
  1002. (v.ipv4 || []).some(ip => ip.toLowerCase().includes(query)) ||
  1003. (v.description || '').toLowerCase().includes(query)
  1004. );
  1005. if (!matchName && !matchIp && !matchRole && !matchType && !matchVlan) return false;
  1006. }
  1007. if (state.ifaceFilter === 'has_vlans') return childVlans.length > 0;
  1008. if (state.ifaceFilter === 'physical') return parent.type !== 'loopback';
  1009. if (state.ifaceFilter === 'up') return parent.state === 'UP';
  1010. return true;
  1011. });
  1012. if (summary) {
  1013. summary.innerText = `${parentIfaces.length} Interfaces • ${allVlans.length} Active VLANs`;
  1014. }
  1015. if (filteredParents.length === 0) {
  1016. emptyState?.classList.remove('hidden');
  1017. tbody.innerHTML = '';
  1018. return;
  1019. }
  1020. emptyState?.classList.add('hidden');
  1021. const sig = `${state.ifaceFilter}|${query}|` + filteredParents.map(p => {
  1022. const cVlans = allVlans.filter(v => v.parent_name === p.name || v.name.startsWith(p.name + '.'));
  1023. const dhcp = (state.dhcpClients || []).find(dc => dc.interface === p.name);
  1024. return `${p.name}:${p.state}:${p.role||'LAN'}:${(p.ipv4||[]).join(',')}:${p.mtu}:${cVlans.length}:${state.expandedParents.has(p.name)}:${dhcp?.status || ''}`;
  1025. }).join(';');
  1026. if (tbody.dataset.sig === sig) {
  1027. return; // ZERO changes to structure, links, IPs or VLANs! Do not rebuild DOM!
  1028. }
  1029. tbody.dataset.sig = sig;
  1030. tbody.innerHTML = '';
  1031. filteredParents.forEach(parent => {
  1032. const isUp = parent.state === 'UP';
  1033. const childVlans = allVlans.filter(v => v.parent_name === parent.name || v.name.startsWith(parent.name + '.'));
  1034. const hasVlans = childVlans.length > 0;
  1035. const isExpanded = hasVlans && state.expandedParents.has(parent.name);
  1036. const canHaveVlan = supportsVLAN(parent);
  1037. const parentRow = document.createElement('tr');
  1038. parentRow.className = `hover:bg-slate-800/50 transition border-b border-slate-800/80 ${isExpanded ? 'bg-slate-900/80' : ''}`;
  1039. parentRow.innerHTML = `
  1040. <td class="py-3 px-3 text-center">
  1041. ${hasVlans ? `
  1042. <button onclick="toggleExpand('${parent.name}')" title="${isExpanded ? 'Collapse VLANs' : 'Expand VLANs'}"
  1043. class="w-6 h-6 rounded flex items-center justify-center hover:bg-slate-800 text-slate-400 hover:text-white transition">
  1044. <svg class="w-4 h-4 chevron-icon ${isExpanded ? 'chevron-open text-cyan-400' : 'text-slate-500'}" fill="none" stroke="currentColor" viewBox="0 0 24 24">
  1045. <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M9 5l7 7-7 7" />
  1046. </svg>
  1047. </button>
  1048. ` : `
  1049. <div class="w-6 h-6 flex items-center justify-center text-slate-700 select-none">
  1050. <span class="w-1.5 h-1.5 rounded-full bg-slate-800"></span>
  1051. </div>
  1052. `}
  1053. </td>
  1054. <td class="py-3 px-4">
  1055. <div class="flex items-center space-x-2.5">
  1056. <div class="w-7 h-7 rounded-lg bg-slate-800 border border-slate-700/80 flex items-center justify-center text-[10px] font-bold text-slate-300">
  1057. ${parent.type === 'loopback' ? 'LO' : (parent.type === 'wireguard' ? 'WG' : (parent.type === 'bridge' ? 'BR' : 'NIC'))}
  1058. </div>
  1059. <div>
  1060. <div class="flex items-center gap-2">
  1061. <span class="font-bold text-white text-sm cursor-pointer hover:text-cyan-400 flex items-center gap-1.5" onclick="${hasVlans ? `toggleExpand('${parent.name}')` : `openIfaceModal('${parent.name}')`}" title="${hasVlans ? 'Click to expand VLANs, or click pencil to rename' : 'Click to configure or rename interface'}">
  1062. <span>${parent.name}</span>
  1063. <svg onclick="event.stopPropagation(); openIfaceModal('${parent.name}')" class="w-3.5 h-3.5 text-slate-500 hover:text-cyan-400 opacity-60 hover:opacity-100 cursor-pointer" title="Configure / Rename ${parent.name}" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z"/></svg>
  1064. </span>
  1065. ${hasVlans ? `
  1066. <span onclick="toggleExpand('${parent.name}')" class="cursor-pointer text-[10px] bg-cyan-950 text-cyan-400 border border-cyan-800/60 px-2 py-0.5 rounded-full font-bold hover:bg-cyan-900 transition">${childVlans.length} VLAN${childVlans.length > 1 ? 's' : ''}</span>
  1067. ` : `
  1068. <span class="text-[10px] bg-slate-800/40 text-slate-500 px-1.5 py-0.5 rounded font-mono select-none">0 VLANs</span>
  1069. `}
  1070. </div>
  1071. <div class="text-[10px] text-slate-500 font-sans mt-0.5">${parent.type}</div>
  1072. </div>
  1073. </div>
  1074. </td>
  1075. <td class="py-3 px-4 font-sans">
  1076. <div class="flex items-center gap-1.5">
  1077. ${getRoleBadge(parent.role || 'LAN')}
  1078. <span class="text-xs text-slate-400 truncate max-w-[120px]">${parent.description || '-'}</span>
  1079. </div>
  1080. </td>
  1081. <td class="py-3 px-4">
  1082. ${parent.ipv4 && parent.ipv4.length > 0
  1083. ? `<div class="text-white font-medium">${parent.ipv4[0]}</div>`
  1084. : '<span class="text-slate-600 font-sans">Unassigned</span>'
  1085. }
  1086. ${(() => {
  1087. const c = (state.dhcpClients || []).find(dc => dc.interface === parent.name);
  1088. if (!c) return '';
  1089. const statusCls = c.status === 'bound' ? 'bg-amber-500/20 text-amber-300 border-amber-500/30' : (c.status === 'searching' ? 'bg-sky-500/20 text-sky-300 border-sky-500/30' : 'bg-slate-800 text-slate-400 border-slate-700');
  1090. return `<div class="mt-1"><span class="px-1.5 py-0.5 rounded text-[10px] font-mono border ${statusCls} cursor-pointer hover:underline" onclick="navigate('dhcp-client')" title="DHCP Client: ${c.status.toUpperCase()} (${c.ip_address || 'requesting...'})">⚡ DHCP: ${c.status.toUpperCase()}</span></div>`;
  1091. })()}
  1092. </td>
  1093. <td class="py-3 px-4 text-slate-400 text-[11px]">
  1094. <div>${parent.mac || 'N/A'}</div>
  1095. <div class="text-[10px] text-slate-500">MTU ${parent.mtu}</div>
  1096. </td>
  1097. <td class="py-3 px-4 text-[11px]">
  1098. <div class="flex items-center space-x-2">
  1099. <span id="iface-rate-rx-${parent.name}" class="text-emerald-400">↓ ${parent.rate?.rx_human || '0 B/s'}</span>
  1100. <span id="iface-rate-tx-${parent.name}" class="text-cyan-400">↑ ${parent.rate?.tx_human || '0 B/s'}</span>
  1101. </div>
  1102. </td>
  1103. <td class="py-3 px-4 font-sans">
  1104. <button onclick="toggleInterfaceState('${parent.name}', '${isUp ? 'down' : 'up'}')"
  1105. class="flex items-center gap-1.5 text-xs font-semibold px-2.5 py-1 rounded-full transition ${
  1106. isUp ? 'bg-emerald-500/10 text-emerald-400 border border-emerald-500/30 hover:bg-rose-500/10 hover:text-rose-400 hover:border-rose-500/30' : 'bg-rose-500/10 text-rose-400 border border-rose-500/30 hover:bg-emerald-500/10 hover:text-emerald-400'
  1107. }" title="Click to toggle link status">
  1108. <span class="w-1.5 h-1.5 rounded-full ${isUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  1109. <span>${parent.state}</span>
  1110. </button>
  1111. </td>
  1112. <td class="py-3 px-4 text-right space-x-2 font-sans">
  1113. ${(() => {
  1114. const c = (state.dhcpClients || []).find(dc => dc.interface === parent.name);
  1115. if (c) {
  1116. return `<button onclick="navigate('dhcp-client')" title="Manage DHCP Client (${c.status})" class="text-xs bg-amber-500/10 hover:bg-amber-500/20 text-amber-400 font-medium px-2.5 py-1 rounded-lg border border-amber-500/30 transition">⚡ DHCP</button>`;
  1117. }
  1118. if (!supportsDHCPClient(parent)) {
  1119. return '';
  1120. }
  1121. return `<button onclick="openDHCPClientModalForIface('${parent.name}')" title="Add DHCP Client on ${parent.name}" class="text-xs bg-slate-800/80 hover:bg-slate-700 text-slate-300 hover:text-amber-400 font-medium px-2 py-1 rounded-lg border border-slate-700 transition">+ DHCP</button>`;
  1122. })()}
  1123. ${canHaveVlan ? `
  1124. <button onclick="openVlanModal('${parent.name}')"
  1125. class="text-xs bg-cyan-950/60 hover:bg-cyan-900 text-cyan-300 font-semibold px-2.5 py-1 rounded-lg border border-cyan-800/70 shadow-sm transition">
  1126. + Add VLAN
  1127. </button>
  1128. ` : ''}
  1129. <button onclick="openIfaceModal('${parent.name}')"
  1130. class="text-xs bg-slate-800 hover:bg-slate-700 text-white font-medium px-2.5 py-1 rounded-lg border border-slate-700 transition">
  1131. Edit
  1132. </button>
  1133. </td>
  1134. `;
  1135. tbody.appendChild(parentRow);
  1136. if (isExpanded) {
  1137. const drawerRow = document.createElement('tr');
  1138. drawerRow.className = 'bg-slate-950/80 border-b border-slate-800/90';
  1139. const drawerCell = document.createElement('td');
  1140. drawerCell.colSpan = 8;
  1141. drawerCell.className = 'p-0';
  1142. drawerCell.innerHTML = `
  1143. <div class="py-4 pl-12 pr-6 border-l-4 border-cyan-500 bg-gradient-to-r from-cyan-950/20 via-slate-900/40 to-transparent">
  1144. <div class="flex items-center justify-between mb-3">
  1145. <div class="flex items-center space-x-3">
  1146. <span class="font-bold text-xs text-white uppercase tracking-wider flex items-center gap-1.5 font-sans">
  1147. <span>VLAN Sub-interfaces on <code class="text-cyan-300 lowercase">${parent.name}</code></span>
  1148. </span>
  1149. <span class="text-[11px] bg-cyan-950 text-cyan-400 px-2 py-0.5 rounded-full border border-cyan-800/60 font-mono">
  1150. ${childVlans.length} Attached
  1151. </span>
  1152. </div>
  1153. <button onclick="openVlanModal('${parent.name}')"
  1154. class="flex items-center space-x-1.5 text-xs bg-cyan-600 hover:bg-cyan-500 text-white font-semibold px-3 py-1.5 rounded-lg shadow-md shadow-cyan-500/20 transition font-sans">
  1155. <span>+ Create VLAN on ${parent.name}</span>
  1156. </button>
  1157. </div>
  1158. ${childVlans.length === 0 ? `
  1159. <div class="p-6 text-center border border-dashed border-slate-800 rounded-xl bg-slate-900/40 font-sans">
  1160. <p class="text-xs text-slate-400 mb-2">No 802.1Q tagged VLANs have been created under <strong class="text-white">${parent.name}</strong> yet.</p>
  1161. <button onclick="openVlanModal('${parent.name}')" class="inline-flex items-center space-x-1.5 text-xs text-cyan-400 hover:text-cyan-300 bg-cyan-950/60 border border-cyan-800/70 px-3 py-1.5 rounded-lg transition font-medium">
  1162. <span>+ Create Your First VLAN on ${parent.name}</span>
  1163. </button>
  1164. </div>
  1165. ` : `
  1166. <div class="overflow-x-auto rounded-lg border border-slate-800 bg-slate-900/90 shadow-inner">
  1167. <table class="w-full text-left text-xs font-mono">
  1168. <thead class="text-slate-400 bg-slate-950/70 border-b border-slate-800 uppercase tracking-wider text-[10px] font-sans">
  1169. <tr>
  1170. <th class="py-2.5 px-4">VLAN ID</th>
  1171. <th class="py-2.5 px-4">Interface Device</th>
  1172. <th class="py-2.5 px-4">Subnet Gateway</th>
  1173. <th class="py-2.5 px-4">Role / Alias</th>
  1174. <th class="py-2.5 px-4">MTU</th>
  1175. <th class="py-2.5 px-4">Throughput</th>
  1176. <th class="py-2.5 px-4">Status</th>
  1177. <th class="py-2.5 px-4 text-right">Actions</th>
  1178. </tr>
  1179. </thead>
  1180. <tbody class="divide-y divide-slate-800/70">
  1181. ${childVlans.map(v => {
  1182. const isVlanUp = v.state === 'UP';
  1183. return `
  1184. <tr class="hover:bg-slate-800/40 transition">
  1185. <td class="py-2.5 px-4">
  1186. <span class="px-2 py-0.5 rounded text-xs font-bold bg-cyan-950 text-cyan-300 border border-cyan-800 shadow-sm">
  1187. VLAN ${v.vlan_id}
  1188. </span>
  1189. </td>
  1190. <td class="py-2.5 px-4 font-bold text-white flex items-center gap-1.5">
  1191. <span class="text-cyan-500">└─</span>
  1192. <span class="cursor-pointer hover:text-cyan-400 flex items-center gap-1" onclick="openIfaceModal('${v.name}')" title="Configure / Rename ${v.name}">
  1193. <span>${v.name}</span>
  1194. <svg class="w-3 h-3 text-slate-500 hover:text-cyan-400 opacity-60 hover:opacity-100" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z"/></svg>
  1195. </span>
  1196. </td>
  1197. <td class="py-2.5 px-4 text-emerald-400 font-medium">
  1198. ${v.ipv4 && v.ipv4.length > 0 ? v.ipv4[0] : '<span class="text-slate-600 font-sans">Unassigned</span>'}
  1199. ${(() => {
  1200. const c = (state.dhcpClients || []).find(dc => dc.interface === v.name);
  1201. if (!c) return '';
  1202. const statusCls = c.status === 'bound' ? 'bg-amber-500/20 text-amber-300 border-amber-500/30' : 'bg-slate-800 text-slate-400 border-slate-700';
  1203. return `<div class="mt-0.5"><span class="px-1.5 py-0.2 rounded text-[9px] font-mono border ${statusCls} cursor-pointer hover:underline" onclick="navigate('dhcp-client')" title="DHCP Client: ${c.status.toUpperCase()}">⚡ DHCP: ${c.status.toUpperCase()}</span></div>`;
  1204. })()}
  1205. </td>
  1206. <td class="py-2.5 px-4 font-sans text-slate-300">
  1207. <div class="flex items-center gap-1.5">
  1208. ${getRoleBadge(v.role || 'LAN')}
  1209. <span class="text-slate-400 text-xs">${v.description || '-'}</span>
  1210. </div>
  1211. </td>
  1212. <td class="py-2.5 px-4 text-slate-400">${v.mtu}</td>
  1213. <td class="py-2.5 px-4 text-[11px]">
  1214. <span id="vlan-rate-rx-${v.name}" class="text-emerald-400">↓ ${v.rate?.rx_human || '0 B/s'}</span>
  1215. <span id="vlan-rate-tx-${v.name}" class="text-cyan-400 ml-1.5">↑ ${v.rate?.tx_human || '0 B/s'}</span>
  1216. </td>
  1217. <td class="py-2.5 px-4 font-sans">
  1218. <button onclick="toggleInterfaceState('${v.name}', '${isVlanUp ? 'down' : 'up'}')"
  1219. class="flex items-center gap-1 text-[11px] font-semibold px-2 py-0.5 rounded-full ${
  1220. isVlanUp ? 'bg-emerald-500/10 text-emerald-400 border border-emerald-500/30' : 'bg-rose-500/10 text-rose-400 border border-rose-500/30'
  1221. }">
  1222. <span class="w-1.5 h-1.5 rounded-full ${isVlanUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  1223. <span>${v.state}</span>
  1224. </button>
  1225. </td>
  1226. <td class="py-2.5 px-4 text-right space-x-1.5 font-sans">
  1227. ${(() => {
  1228. const c = (state.dhcpClients || []).find(dc => dc.interface === v.name);
  1229. if (c) {
  1230. return `<button onclick="navigate('dhcp-client')" class="text-xs text-amber-400 hover:text-amber-300 px-2 py-0.5 rounded bg-amber-950/40 border border-amber-800/50">⚡ DHCP</button>`;
  1231. }
  1232. if (!supportsDHCPClient(v)) {
  1233. return '';
  1234. }
  1235. return `<button onclick="openDHCPClientModalForIface('${v.name}')" class="text-xs text-slate-400 hover:text-amber-400 px-1.5 py-0.5 rounded border border-slate-700">+ DHCP</button>`;
  1236. })()}
  1237. <button onclick="openIfaceModal('${v.name}')" class="text-xs bg-slate-800 hover:bg-slate-700 text-slate-200 px-2 py-0.5 rounded border border-slate-700">Edit</button>
  1238. <button onclick="confirmDeleteVlan('${v.name}')" class="text-xs text-rose-400 hover:text-rose-300 hover:bg-rose-950/40 px-2 py-0.5 rounded transition">Delete</button>
  1239. </td>
  1240. </tr>
  1241. `;
  1242. }).join('')}
  1243. </tbody>
  1244. </table>
  1245. </div>
  1246. `}
  1247. </div>
  1248. `;
  1249. drawerRow.appendChild(drawerCell);
  1250. tbody.appendChild(drawerRow);
  1251. }
  1252. });
  1253. }
  1254. // Render VLANs Dedicated View
  1255. function renderVlansList() {
  1256. const tbody = document.getElementById('vlans-table-body');
  1257. if (!tbody) return;
  1258. const emptyState = document.getElementById('vlans-empty-state');
  1259. const countBadge = document.getElementById('vlans-table-count');
  1260. const query = (document.getElementById('vlan-search')?.value || '').toLowerCase();
  1261. const allVlans = state.vlans || [];
  1262. if (countBadge) countBadge.innerText = allVlans.length;
  1263. const filtered = allVlans.filter(v => {
  1264. if (!query) return true;
  1265. return v.name.toLowerCase().includes(query) ||
  1266. String(v.vlan_id).includes(query) ||
  1267. (v.description || '').toLowerCase().includes(query) ||
  1268. (v.ipv4 && v.ipv4.some(ip => ip.includes(query)));
  1269. });
  1270. if (allVlans.length === 0) {
  1271. emptyState.classList.remove('hidden');
  1272. tbody.innerHTML = '';
  1273. return;
  1274. }
  1275. emptyState.classList.add('hidden');
  1276. const sig = `${query}|` + filtered.map(v => `${v.name}:${v.state}:${(v.ipv4||[]).join(',')}:${v.vlan_id}:${v.mtu}`).join(';');
  1277. if (tbody.dataset.sig === sig) return;
  1278. tbody.dataset.sig = sig;
  1279. tbody.innerHTML = '';
  1280. filtered.forEach(v => {
  1281. const isUp = v.state === 'UP';
  1282. const tr = document.createElement('tr');
  1283. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  1284. tr.innerHTML = `
  1285. <td class="py-3 px-4">
  1286. <span class="px-2.5 py-1 rounded-md text-xs font-bold bg-cyan-950 text-cyan-300 border border-cyan-800/70 shadow-sm">
  1287. VLAN ${v.vlan_id}
  1288. </span>
  1289. </td>
  1290. <td class="py-3 px-4 font-bold text-white">
  1291. <span class="cursor-pointer hover:text-cyan-400 flex items-center gap-1.5" onclick="openIfaceModal('${v.name}')" title="Configure / Rename ${v.name}">
  1292. <span>${v.name}</span>
  1293. <svg class="w-3.5 h-3.5 text-slate-500 hover:text-cyan-400 opacity-60 hover:opacity-100" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z"/></svg>
  1294. </span>
  1295. </td>
  1296. <td class="py-3 px-4 text-slate-300">
  1297. <span class="bg-slate-800 text-slate-200 px-2 py-0.5 rounded text-[11px]">${v.parent_name || 'eth0'}</span>
  1298. </td>
  1299. <td class="py-3 px-4 text-emerald-400 font-medium">
  1300. ${v.ipv4 && v.ipv4.length > 0 ? v.ipv4[0] : '<span class="text-slate-600 font-sans">Unassigned</span>'}
  1301. </td>
  1302. <td class="py-3 px-4 text-slate-300 font-sans">
  1303. <span class="text-slate-400 text-xs">${v.description || v.role || '-'}</span>
  1304. </td>
  1305. <td class="py-3 px-4 text-slate-400">${v.mtu}</td>
  1306. <td class="py-3 px-4 font-sans">
  1307. <button onclick="toggleInterfaceState('${v.name}', '${isUp ? 'down' : 'up'}')"
  1308. class="flex items-center gap-1.5 text-xs font-semibold px-2 py-0.5 rounded-full ${
  1309. isUp ? 'bg-emerald-500/10 text-emerald-400 border border-emerald-500/30' : 'bg-rose-500/10 text-rose-400 border border-rose-500/30'
  1310. }">
  1311. <span class="w-1.5 h-1.5 rounded-full ${isUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  1312. <span>${v.state}</span>
  1313. </button>
  1314. </td>
  1315. <td class="py-3 px-4 text-right space-x-2 font-sans">
  1316. <button onclick="openIfaceModal('${v.name}')" class="text-xs bg-slate-800 hover:bg-slate-700 text-slate-200 px-2.5 py-1 rounded border border-slate-700">Edit</button>
  1317. <button onclick="confirmDeleteVlan('${v.name}')" class="text-xs text-rose-400 hover:text-rose-300 hover:bg-rose-950/40 px-2 py-1 rounded transition">Delete</button>
  1318. </td>
  1319. `;
  1320. tbody.appendChild(tr);
  1321. });
  1322. }
  1323. // Toggle interface UP / DOWN
  1324. async function toggleInterfaceState(name, newState) {
  1325. try {
  1326. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(name)}/state`, {
  1327. method: 'POST',
  1328. headers: { 'Content-Type': 'application/json' },
  1329. body: JSON.stringify({ state: newState })
  1330. });
  1331. const data = await res.json();
  1332. if (res.ok) {
  1333. showToast('Interface Updated', `Interface ${name} is now ${newState.toUpperCase()}`, 'success');
  1334. fetchData(false);
  1335. } else {
  1336. showToast('Error', data.message || 'Failed to toggle interface state', 'error');
  1337. }
  1338. } catch (err) {
  1339. showToast('Error', err.message, 'error');
  1340. }
  1341. }
  1342. // ---------------- MikroTik Flag & Utilities ----------------
  1343. function renderMikroTikFlag(running, disabled) {
  1344. if (running) {
  1345. return `<span class="inline-flex items-center justify-center w-5 h-5 rounded-md font-mono font-bold text-[11px] bg-emerald-500/20 text-emerald-400 border border-emerald-500/40 shadow-sm" title="Running (Connected)">R</span>`;
  1346. }
  1347. if (disabled) {
  1348. return `<span class="inline-flex items-center justify-center w-5 h-5 rounded-md font-mono font-bold text-[11px] bg-rose-500/20 text-rose-400 border border-rose-500/40 shadow-sm" title="Disabled">X</span>`;
  1349. }
  1350. return `<span class="inline-flex items-center justify-center w-5 h-5 rounded-md font-mono font-bold text-[11px] text-slate-500 bg-slate-800/80 border border-slate-700/60" title="Idle / Disconnected">-</span>`;
  1351. }
  1352. function copyToClipboard(text, label = 'Text') {
  1353. navigator.clipboard.writeText(text).then(() => {
  1354. showToast('Copied', `${label} copied to clipboard`, 'success');
  1355. }).catch(() => {
  1356. prompt('Copy value:', text);
  1357. });
  1358. }
  1359. // ======================== PPP Profiles Shared Helper ========================
  1360. async function fetchPPPProfilesList() {
  1361. try {
  1362. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`);
  1363. if (res.ok) {
  1364. state.pppProfiles = await res.json();
  1365. }
  1366. } catch (err) {
  1367. console.error('Failed to load PPP profiles:', err);
  1368. }
  1369. }
  1370. function populateProfileSelect(selectId, selectedVal, defaultVal = 'default') {
  1371. const sel = document.getElementById(selectId);
  1372. if (!sel) return;
  1373. const profiles = (state.pppProfiles && state.pppProfiles.length > 0) ? state.pppProfiles : [
  1374. { name: 'default', use_encryption: 'no' },
  1375. { name: 'default-encryption', use_encryption: 'required' }
  1376. ];
  1377. sel.innerHTML = '';
  1378. profiles.forEach(p => {
  1379. const opt = document.createElement('option');
  1380. opt.value = p.name;
  1381. const encBadge = p.use_encryption === 'required' ? ' (MPPE-128)' : (p.use_encryption === 'yes' ? ' (MPPE)' : '');
  1382. opt.innerText = `${p.name}${encBadge}`;
  1383. sel.appendChild(opt);
  1384. });
  1385. if (selectedVal) {
  1386. sel.value = selectedVal;
  1387. } else {
  1388. sel.value = defaultVal;
  1389. }
  1390. if (!sel.value && sel.options.length > 0) {
  1391. sel.selectedIndex = 0;
  1392. }
  1393. }
  1394. // ======================== PPPoE Multi-Instance ========================
  1395. async function loadPPPoE(populateInputs = true) {
  1396. try {
  1397. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  1398. await fetchPPPProfilesList();
  1399. }
  1400. const res = await fetch(`${API_BASE}/vpn/pppoe/clients`);
  1401. const list = await res.json();
  1402. state.pppoeList = Array.isArray(list) ? list : [];
  1403. const badge = document.getElementById('pppoe-count-badge');
  1404. if (badge) badge.innerText = `${state.pppoeList.length} Interface${state.pppoeList.length !== 1 ? 's' : ''}`;
  1405. const tbody = document.getElementById('pppoe-table-body');
  1406. const empty = document.getElementById('pppoe-empty');
  1407. if (!tbody) return;
  1408. tbody.innerHTML = '';
  1409. if (state.pppoeList.length === 0) {
  1410. if (empty) empty.classList.remove('hidden');
  1411. } else {
  1412. if (empty) empty.classList.add('hidden');
  1413. state.pppoeList.forEach(inst => {
  1414. const tr = document.createElement('tr');
  1415. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1416. tr.innerHTML = `
  1417. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  1418. <td class="py-2.5 px-3 font-bold text-white">${escapeHtml(inst.name)}</td>
  1419. <td class="py-2.5 px-3 text-cyan-400 font-mono">${escapeHtml(inst.interface)}</td>
  1420. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(inst.username || '-')}</td>
  1421. <td class="py-2.5 px-3 font-mono text-cyan-300"><span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 border border-slate-700">${escapeHtml(inst.profile || 'default')}</span></td>
  1422. <td class="py-2.5 px-3 font-mono ${inst.assigned_ip ? 'text-emerald-400 font-bold' : 'text-slate-500'}">${escapeHtml(inst.assigned_ip || '-')}</td>
  1423. <td class="py-2.5 px-3 text-slate-400 font-mono">${escapeHtml(inst.ppp_device || '-')}</td>
  1424. <td class="py-2.5 px-3 text-center">
  1425. <span class="px-2 py-0.5 rounded text-[10px] font-sans ${inst.default_route ? 'bg-blue-500/20 text-blue-300 border border-blue-500/30' : 'bg-slate-800 text-slate-500'}">
  1426. ${inst.default_route ? 'Yes' : 'No'}
  1427. </span>
  1428. </td>
  1429. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  1430. ${inst.running ? `
  1431. <button onclick="disconnectPPPoEInstance('${inst.name}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  1432. ` : `
  1433. <button onclick="connectPPPoEInstance('${inst.name}')" class="text-xs bg-blue-600/30 hover:bg-blue-600/50 text-blue-300 px-2 py-0.5 rounded border border-blue-500/30">Connect</button>
  1434. `}
  1435. <button onclick="togglePPPoEState('${inst.name}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  1436. ${inst.disabled ? 'Enable' : 'Disable'}
  1437. </button>
  1438. <button onclick="openEditPPPoEModal('${inst.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  1439. <button onclick="deletePPPoEInstance('${inst.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  1440. </td>
  1441. `;
  1442. tbody.appendChild(tr);
  1443. });
  1444. }
  1445. } catch (err) {
  1446. console.error('Failed to load PPPoE:', err);
  1447. }
  1448. }
  1449. function openAddPPPoEModal() {
  1450. document.getElementById('pppoe-modal-title').innerText = 'Add PPPoE Client Interface';
  1451. document.getElementById('pppoe-modal-edit-orig').value = '';
  1452. document.getElementById('pppoe-modal-name').value = `pppoe-out${(state.pppoeList || []).length + 1}`;
  1453. document.getElementById('pppoe-modal-name').readOnly = false;
  1454. document.getElementById('pppoe-modal-user').value = '';
  1455. document.getElementById('pppoe-modal-pass').value = '';
  1456. document.getElementById('pppoe-modal-service').value = '';
  1457. document.getElementById('pppoe-modal-mtu').value = '1492';
  1458. document.getElementById('pppoe-modal-defroute').checked = true;
  1459. document.getElementById('pppoe-modal-reconnect').checked = true;
  1460. document.getElementById('pppoe-modal-disabled').checked = false;
  1461. // Populate profiles
  1462. populateProfileSelect('pppoe-modal-profile', 'default', 'default');
  1463. // Populate interfaces
  1464. const sel = document.getElementById('pppoe-modal-iface');
  1465. sel.innerHTML = '';
  1466. (state.interfaces || []).forEach(i => {
  1467. if (i.name === 'lo') return;
  1468. const opt = document.createElement('option');
  1469. opt.value = i.name;
  1470. opt.innerText = `${i.name} (${i.role || i.type})`;
  1471. sel.appendChild(opt);
  1472. });
  1473. document.getElementById('pppoe-modal').classList.remove('hidden');
  1474. }
  1475. function openEditPPPoEModal(name) {
  1476. const inst = (state.pppoeList || []).find(i => i.name === name);
  1477. if (!inst) return;
  1478. document.getElementById('pppoe-modal-title').innerText = `Edit PPPoE Client: ${name}`;
  1479. document.getElementById('pppoe-modal-edit-orig').value = name;
  1480. document.getElementById('pppoe-modal-name').value = inst.name;
  1481. document.getElementById('pppoe-modal-name').readOnly = true;
  1482. document.getElementById('pppoe-modal-user').value = inst.username || '';
  1483. document.getElementById('pppoe-modal-pass').value = inst.password || '';
  1484. document.getElementById('pppoe-modal-service').value = inst.service_name || '';
  1485. document.getElementById('pppoe-modal-mtu').value = inst.mtu || 1492;
  1486. document.getElementById('pppoe-modal-defroute').checked = inst.default_route ?? true;
  1487. document.getElementById('pppoe-modal-reconnect').checked = inst.auto_reconnect ?? true;
  1488. document.getElementById('pppoe-modal-disabled').checked = !!inst.disabled;
  1489. // Populate profiles
  1490. populateProfileSelect('pppoe-modal-profile', inst.profile || 'default', 'default');
  1491. const sel = document.getElementById('pppoe-modal-iface');
  1492. sel.innerHTML = '';
  1493. (state.interfaces || []).forEach(i => {
  1494. if (i.name === 'lo') return;
  1495. const opt = document.createElement('option');
  1496. opt.value = i.name;
  1497. opt.innerText = `${i.name} (${i.role || i.type})`;
  1498. if (i.name === inst.interface) opt.selected = true;
  1499. sel.appendChild(opt);
  1500. });
  1501. document.getElementById('pppoe-modal').classList.remove('hidden');
  1502. }
  1503. function closePPPoEModal() {
  1504. document.getElementById('pppoe-modal').classList.add('hidden');
  1505. }
  1506. async function submitSavePPPoE(e) {
  1507. e.preventDefault();
  1508. const name = document.getElementById('pppoe-modal-name').value.trim();
  1509. const iface = document.getElementById('pppoe-modal-iface').value;
  1510. const user = document.getElementById('pppoe-modal-user').value.trim();
  1511. const pass = document.getElementById('pppoe-modal-pass').value;
  1512. const profile = document.getElementById('pppoe-modal-profile')?.value || 'default';
  1513. const service = document.getElementById('pppoe-modal-service').value.trim();
  1514. const mtu = parseInt(document.getElementById('pppoe-modal-mtu').value, 10) || 1492;
  1515. const defRoute = document.getElementById('pppoe-modal-defroute').checked;
  1516. const reconnect = document.getElementById('pppoe-modal-reconnect').checked;
  1517. const disabled = document.getElementById('pppoe-modal-disabled').checked;
  1518. try {
  1519. const res = await fetch(`${API_BASE}/vpn/pppoe/clients`, {
  1520. method: 'POST',
  1521. headers: { 'Content-Type': 'application/json' },
  1522. body: JSON.stringify({
  1523. name,
  1524. interface: iface,
  1525. username: user,
  1526. password: pass,
  1527. profile: profile,
  1528. service_name: service,
  1529. mtu,
  1530. default_route: defRoute,
  1531. auto_reconnect: reconnect,
  1532. disabled
  1533. })
  1534. });
  1535. if (res.ok) {
  1536. showToast('PPPoE Saved', `Configuration for ${name} saved`, 'success');
  1537. closePPPoEModal();
  1538. loadPPPoE(false);
  1539. fetchData(false);
  1540. } else {
  1541. const err = await res.json();
  1542. showToast('Error', err.message || 'Failed to save PPPoE', 'error');
  1543. }
  1544. } catch (err) {
  1545. showToast('Error', err.message, 'error');
  1546. }
  1547. }
  1548. async function connectPPPoEInstance(name) {
  1549. try {
  1550. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  1551. if (res.ok) {
  1552. showToast('Connecting', `Dialing ${name}...`, 'info');
  1553. setTimeout(() => loadPPPoE(false), 2000);
  1554. }
  1555. } catch (err) {
  1556. showToast('Error', err.message, 'error');
  1557. }
  1558. }
  1559. async function disconnectPPPoEInstance(name) {
  1560. try {
  1561. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  1562. if (res.ok) {
  1563. showToast('Disconnected', `${name} session terminated`, 'info');
  1564. setTimeout(() => loadPPPoE(false), 1000);
  1565. }
  1566. } catch (err) {
  1567. showToast('Error', err.message, 'error');
  1568. }
  1569. }
  1570. async function togglePPPoEState(name, enable) {
  1571. try {
  1572. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/state`, {
  1573. method: 'POST',
  1574. headers: { 'Content-Type': 'application/json' },
  1575. body: JSON.stringify({ enabled: enable })
  1576. });
  1577. if (res.ok) {
  1578. showToast(enable ? 'Enabled' : 'Disabled', `${name} is now ${enable ? 'enabled' : 'disabled'}`, 'info');
  1579. loadPPPoE(false);
  1580. }
  1581. } catch (err) {
  1582. showToast('Error', err.message, 'error');
  1583. }
  1584. }
  1585. async function deletePPPoEInstance(name) {
  1586. if (!confirm(`Are you sure you want to delete PPPoE client ${name}?`)) return;
  1587. try {
  1588. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1589. if (res.ok) {
  1590. showToast('Deleted', `PPPoE client ${name} removed`, 'success');
  1591. loadPPPoE(false);
  1592. fetchData(false);
  1593. }
  1594. } catch (err) {
  1595. showToast('Error', err.message, 'error');
  1596. }
  1597. }
  1598. // ======================== WireGuard Multi-Interface & Multi-Peer ========================
  1599. state.wgSubTab = 'ifaces';
  1600. function switchWGSubTab(tab) {
  1601. state.wgSubTab = tab;
  1602. const ifacesPanel = document.getElementById('wg-subtab-ifaces');
  1603. const peersPanel = document.getElementById('wg-subtab-peers');
  1604. const ifacesBtn = document.getElementById('wg-subtab-btn-ifaces');
  1605. const peersBtn = document.getElementById('wg-subtab-btn-peers');
  1606. if (tab === 'ifaces') {
  1607. ifacesPanel?.classList.remove('hidden');
  1608. peersPanel?.classList.add('hidden');
  1609. ifacesBtn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-rose-500 text-white transition flex items-center gap-2';
  1610. peersBtn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-transparent text-slate-400 hover:text-slate-200 transition flex items-center gap-2';
  1611. } else {
  1612. ifacesPanel?.classList.add('hidden');
  1613. peersPanel?.classList.remove('hidden');
  1614. ifacesBtn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-transparent text-slate-400 hover:text-slate-200 transition flex items-center gap-2';
  1615. peersBtn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-rose-500 text-white transition flex items-center gap-2';
  1616. renderWGPeers();
  1617. }
  1618. }
  1619. async function loadWireGuard(populateInputs = true) {
  1620. try {
  1621. const [ifacesRes, peersRes] = await Promise.all([
  1622. fetch(`${API_BASE}/vpn/wireguard/interfaces`),
  1623. fetch(`${API_BASE}/vpn/wireguard/peers`)
  1624. ]);
  1625. const ifaces = ifacesRes.ok ? await ifacesRes.json() : [];
  1626. const peers = peersRes.ok ? await peersRes.json() : [];
  1627. state.wgInterfaces = Array.isArray(ifaces) ? ifaces : [];
  1628. state.wgPeers = Array.isArray(peers) ? peers : [];
  1629. // Badges
  1630. const ifacesCountBadge = document.getElementById('wg-ifaces-count');
  1631. if (ifacesCountBadge) ifacesCountBadge.innerText = `${state.wgInterfaces.length} Interfaces`;
  1632. const peersCountBadge = document.getElementById('wg-peers-count');
  1633. if (peersCountBadge) peersCountBadge.innerText = `${state.wgPeers.length} Peers`;
  1634. const subTabIfaces = document.getElementById('wg-subtab-badge-ifaces');
  1635. if (subTabIfaces) subTabIfaces.innerText = state.wgInterfaces.length;
  1636. const subTabPeers = document.getElementById('wg-subtab-badge-peers');
  1637. if (subTabPeers) subTabPeers.innerText = state.wgPeers.length;
  1638. // Render Interfaces
  1639. const ifacesTbody = document.getElementById('wg-ifaces-table-body');
  1640. const ifacesEmpty = document.getElementById('wg-ifaces-empty');
  1641. if (ifacesTbody) {
  1642. ifacesTbody.innerHTML = '';
  1643. if (state.wgInterfaces.length === 0) {
  1644. if (ifacesEmpty) ifacesEmpty.classList.remove('hidden');
  1645. } else {
  1646. if (ifacesEmpty) ifacesEmpty.classList.add('hidden');
  1647. state.wgInterfaces.forEach(iface => {
  1648. const peersOnIface = state.wgPeers.filter(p => p.interface === iface.name).length;
  1649. const tr = document.createElement('tr');
  1650. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1651. tr.innerHTML = `
  1652. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(iface.running, iface.disabled)}</td>
  1653. <td class="py-2.5 px-3">
  1654. <div class="flex items-center gap-1.5">
  1655. <span class="font-bold text-white">${escapeHtml(iface.name)}</span>
  1656. ${iface.comment ? `<span class="text-[10px] text-slate-400 font-sans italic">(${escapeHtml(iface.comment)})</span>` : ''}
  1657. </div>
  1658. </td>
  1659. <td class="py-2.5 px-3 text-amber-400 font-mono">${iface.listen_port}</td>
  1660. <td class="py-2.5 px-3 text-emerald-400 font-mono">${iface.address || '<span class="text-slate-600 font-sans">--</span>'}</td>
  1661. <td class="py-2.5 px-3 text-slate-300 font-mono">
  1662. <span class="cursor-pointer hover:text-white" onclick="copyToClipboard('${iface.public_key}', 'Public Key')" title="Click to copy: ${iface.public_key}">
  1663. ${(iface.public_key || '').substring(0, 10)}... 📋
  1664. </span>
  1665. </td>
  1666. <td class="py-2.5 px-3 text-slate-400 font-mono">${iface.mtu || 1420}</td>
  1667. <td class="py-2.5 px-3 text-center">
  1668. <span class="px-2 py-0.5 rounded text-[10px] font-sans bg-slate-800 text-slate-300">${peersOnIface} peer${peersOnIface !== 1 ? 's' : ''}</span>
  1669. </td>
  1670. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  1671. ${iface.running ? `
  1672. <button onclick="stopWGInterface('${iface.name}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Stop</button>
  1673. ` : `
  1674. <button onclick="startWGInterface('${iface.name}')" class="text-xs bg-rose-600/30 hover:bg-rose-600/50 text-rose-300 px-2 py-0.5 rounded border border-rose-500/30 font-medium">Start</button>
  1675. `}
  1676. <button onclick="toggleWGInterfaceState('${iface.name}', ${iface.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white font-medium">
  1677. ${iface.disabled ? 'Enable' : 'Disable'}
  1678. </button>
  1679. <button onclick="openEditWGInterfaceModal('${iface.name}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Edit</button>
  1680. <button onclick="deleteWGInterface('${iface.name}')" class="text-xs text-slate-500 hover:text-rose-400 font-medium">Delete</button>
  1681. </td>
  1682. `;
  1683. ifacesTbody.appendChild(tr);
  1684. });
  1685. }
  1686. }
  1687. // Populate filter dropdown in peers tab
  1688. const filterSel = document.getElementById('wg-peers-filter-iface');
  1689. if (filterSel) {
  1690. const currentVal = filterSel.value;
  1691. filterSel.innerHTML = '<option value="">All Interfaces</option>';
  1692. state.wgInterfaces.forEach(i => {
  1693. const opt = document.createElement('option');
  1694. opt.value = i.name;
  1695. opt.innerText = i.name;
  1696. if (i.name === currentVal) opt.selected = true;
  1697. filterSel.appendChild(opt);
  1698. });
  1699. }
  1700. renderWGPeers();
  1701. } catch (err) {
  1702. console.error('Failed to load WireGuard:', err);
  1703. }
  1704. }
  1705. function formatWGPeerEndpoint(address, port) {
  1706. if (!address || address === '(none)') return '--';
  1707. let addr = address.trim();
  1708. let p = port || 0;
  1709. while (addr.includes(':') && !addr.startsWith('[')) {
  1710. const lastColon = addr.lastIndexOf(':');
  1711. const maybePort = addr.substring(lastColon + 1);
  1712. if (!isNaN(parseInt(maybePort, 10)) && parseInt(maybePort, 10) > 0) {
  1713. if (!p) p = parseInt(maybePort, 10);
  1714. addr = addr.substring(0, lastColon);
  1715. } else {
  1716. break;
  1717. }
  1718. }
  1719. return p ? `${addr}:${p}` : addr;
  1720. }
  1721. function renderWGPeers() {
  1722. const filterSel = document.getElementById('wg-peers-filter-iface');
  1723. const selectedIface = filterSel ? filterSel.value : '';
  1724. const tbody = document.getElementById('wg-peers-table-body');
  1725. const empty = document.getElementById('wg-peers-empty');
  1726. if (!tbody) return;
  1727. tbody.innerHTML = '';
  1728. const filtered = selectedIface ? state.wgPeers.filter(p => p.interface === selectedIface) : state.wgPeers;
  1729. if (filtered.length === 0) {
  1730. if (empty) empty.classList.remove('hidden');
  1731. } else {
  1732. if (empty) empty.classList.add('hidden');
  1733. filtered.forEach(p => {
  1734. const isOnline = p.latest_handshake && !p.latest_handshake.includes('Never');
  1735. const tr = document.createElement('tr');
  1736. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1737. tr.innerHTML = `
  1738. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(isOnline, p.disabled)}</td>
  1739. <td class="py-2.5 px-3 font-mono font-bold text-rose-400">${escapeHtml(p.interface)}</td>
  1740. <td class="py-2.5 px-3 font-bold text-white font-sans">${escapeHtml(p.name || 'Unnamed')}</td>
  1741. <td class="py-2.5 px-3 text-slate-300 font-mono">
  1742. <span class="cursor-pointer hover:text-white" onclick="copyToClipboard('${p.public_key}', 'Peer Public Key')" title="${p.public_key}">
  1743. ${(p.public_key || '').substring(0, 10)}... 📋
  1744. </span>
  1745. </td>
  1746. <td class="py-2.5 px-3 text-emerald-400 font-mono font-semibold">${(p.allowed_ips || []).join(', ')}</td>
  1747. <td class="py-2.5 px-3 text-slate-400 font-mono">${formatWGPeerEndpoint(p.endpoint_address, p.endpoint_port)}</td>
  1748. <td class="py-2.5 px-3 text-slate-300 font-sans">${p.latest_handshake || 'Never'}</td>
  1749. <td class="py-2.5 px-3 font-mono text-[11px]">
  1750. <span class="text-emerald-400">↓ ${p.transfer_rx_human || '0 B'}</span>
  1751. <span class="text-cyan-400 ml-1">↑ ${p.transfer_tx_human || '0 B'}</span>
  1752. </td>
  1753. <td class="py-2.5 px-3 text-right font-sans space-x-2 whitespace-nowrap">
  1754. <button onclick="toggleWGPeerState('${escapeHtml(p.interface)}', '${escapeHtml(p.public_key)}', ${p.disabled ? 'true' : 'false'})" class="text-xs ${p.disabled ? 'text-emerald-400 hover:text-emerald-300' : 'text-slate-400 hover:text-white'} font-medium">
  1755. ${p.disabled ? 'Enable' : 'Disable'}
  1756. </button>
  1757. <button onclick="openEditWGPeerModal('${escapeHtml(p.interface)}', '${escapeHtml(p.public_key)}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Edit</button>
  1758. <button onclick="openWGClientConfModal('${escapeHtml(p.interface)}', '${(p.allowed_ips || [])[0] || '10.10.0.2/32'}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold" title="Generate WireGuard Client Profile (.conf)">Config (.conf)</button>
  1759. <button onclick="deleteWGPeer('${escapeHtml(p.interface)}', '${escapeHtml(p.public_key)}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Delete</button>
  1760. </td>
  1761. `;
  1762. tbody.appendChild(tr);
  1763. });
  1764. }
  1765. }
  1766. function openAddWGInterfaceModal() {
  1767. document.getElementById('wg-iface-modal-title').innerText = 'Add WireGuard Interface';
  1768. document.getElementById('wg-iface-modal-edit-orig').value = '';
  1769. const nameEl = document.getElementById('wg-iface-modal-name');
  1770. nameEl.value = `wg${(state.wgInterfaces || []).length}`;
  1771. nameEl.readOnly = false;
  1772. document.getElementById('wg-iface-modal-port').value = 51820 + (state.wgInterfaces || []).length;
  1773. document.getElementById('wg-iface-modal-addr').value = `10.${10 + (state.wgInterfaces || []).length}.0.1/24`;
  1774. document.getElementById('wg-iface-modal-mtu').value = '1420';
  1775. document.getElementById('wg-iface-modal-comment').value = '';
  1776. document.getElementById('wg-iface-modal-pubkey').value = '';
  1777. document.getElementById('wg-iface-modal-privkey').value = '';
  1778. document.getElementById('wg-iface-modal-disabled').checked = false;
  1779. generateWGInterfaceKeys();
  1780. document.getElementById('wg-iface-modal').classList.remove('hidden');
  1781. }
  1782. function openEditWGInterfaceModal(name) {
  1783. const iface = (state.wgInterfaces || []).find(i => i.name === name);
  1784. if (!iface) return;
  1785. document.getElementById('wg-iface-modal-title').innerText = `Edit WireGuard Interface: ${name}`;
  1786. document.getElementById('wg-iface-modal-edit-orig').value = name;
  1787. const nameEl = document.getElementById('wg-iface-modal-name');
  1788. nameEl.value = iface.name;
  1789. nameEl.readOnly = false; // ALLOW RENAMING
  1790. document.getElementById('wg-iface-modal-port').value = iface.listen_port || 51820;
  1791. document.getElementById('wg-iface-modal-addr').value = iface.address || '';
  1792. document.getElementById('wg-iface-modal-mtu').value = iface.mtu || 1420;
  1793. document.getElementById('wg-iface-modal-comment').value = iface.comment || '';
  1794. document.getElementById('wg-iface-modal-pubkey').value = iface.public_key || '';
  1795. document.getElementById('wg-iface-modal-privkey').value = iface.private_key || '';
  1796. document.getElementById('wg-iface-modal-disabled').checked = !!iface.disabled;
  1797. document.getElementById('wg-iface-modal').classList.remove('hidden');
  1798. }
  1799. function closeAddWGInterfaceModal() {
  1800. document.getElementById('wg-iface-modal').classList.add('hidden');
  1801. }
  1802. async function generateWGInterfaceKeys() {
  1803. try {
  1804. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  1805. const keys = await res.json();
  1806. if (res.ok) {
  1807. document.getElementById('wg-iface-modal-privkey').value = keys.private_key;
  1808. document.getElementById('wg-iface-modal-pubkey').value = keys.public_key;
  1809. }
  1810. } catch (err) {
  1811. showToast('Error', 'Failed to generate keypair: ' + err.message, 'error');
  1812. }
  1813. }
  1814. async function onWGInterfacePrivKeyInput() {
  1815. const privKey = document.getElementById('wg-iface-modal-privkey').value.trim();
  1816. if (!privKey) return;
  1817. try {
  1818. const res = await fetch(`${API_BASE}/vpn/wireguard/calc-pubkey`, {
  1819. method: 'POST',
  1820. headers: { 'Content-Type': 'application/json' },
  1821. body: JSON.stringify({ private_key: privKey })
  1822. });
  1823. if (res.ok) {
  1824. const data = await res.json();
  1825. if (data.public_key) {
  1826. document.getElementById('wg-iface-modal-pubkey').value = data.public_key;
  1827. }
  1828. }
  1829. } catch (err) {
  1830. // Ignore while typing
  1831. }
  1832. }
  1833. function toggleWGPrivKeyVisibility() {
  1834. const el = document.getElementById('wg-iface-modal-privkey');
  1835. const btn = document.getElementById('btn-toggle-wg-privkey');
  1836. if (el.type === 'password') {
  1837. el.type = 'text';
  1838. btn.innerText = '🙈 Hide';
  1839. } else {
  1840. el.type = 'password';
  1841. btn.innerText = '👁️ Show';
  1842. }
  1843. }
  1844. function copyWGInterfacePubKey() {
  1845. const pub = document.getElementById('wg-iface-modal-pubkey').value;
  1846. if (pub) copyToClipboard(pub, 'Interface Public Key');
  1847. }
  1848. async function submitSaveWGInterface(e) {
  1849. e.preventDefault();
  1850. const origName = document.getElementById('wg-iface-modal-edit-orig').value.trim();
  1851. const name = document.getElementById('wg-iface-modal-name').value.trim();
  1852. const port = parseInt(document.getElementById('wg-iface-modal-port').value, 10) || 51820;
  1853. const addr = document.getElementById('wg-iface-modal-addr').value.trim();
  1854. const mtu = parseInt(document.getElementById('wg-iface-modal-mtu').value, 10) || 1420;
  1855. const comment = document.getElementById('wg-iface-modal-comment').value.trim();
  1856. const pub = document.getElementById('wg-iface-modal-pubkey').value.trim();
  1857. const priv = document.getElementById('wg-iface-modal-privkey').value.trim();
  1858. const disabled = document.getElementById('wg-iface-modal-disabled').checked;
  1859. try {
  1860. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces`, {
  1861. method: 'POST',
  1862. headers: { 'Content-Type': 'application/json' },
  1863. body: JSON.stringify({
  1864. orig_name: origName,
  1865. name,
  1866. listen_port: port,
  1867. address: addr,
  1868. mtu,
  1869. comment,
  1870. public_key: pub,
  1871. private_key: priv,
  1872. disabled
  1873. })
  1874. });
  1875. const data = await res.json();
  1876. if (res.ok) {
  1877. showToast('WireGuard Saved', `Interface ${name} configured successfully`, 'success');
  1878. closeAddWGInterfaceModal();
  1879. loadWireGuard(false);
  1880. fetchData(false);
  1881. } else {
  1882. showToast('Error', data.error || 'Failed to save interface', 'error');
  1883. }
  1884. } catch (err) {
  1885. showToast('Error', err.message, 'error');
  1886. }
  1887. }
  1888. async function startWGInterface(name) {
  1889. try {
  1890. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/start`, { method: 'POST' });
  1891. if (res.ok) {
  1892. showToast('Interface UP', `Started WireGuard interface ${name}`, 'success');
  1893. loadWireGuard(false);
  1894. fetchData(false);
  1895. }
  1896. } catch (err) {
  1897. showToast('Error', err.message, 'error');
  1898. }
  1899. }
  1900. async function stopWGInterface(name) {
  1901. try {
  1902. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/stop`, { method: 'POST' });
  1903. if (res.ok) {
  1904. showToast('Interface DOWN', `Stopped WireGuard interface ${name}`, 'info');
  1905. loadWireGuard(false);
  1906. fetchData(false);
  1907. }
  1908. } catch (err) {
  1909. showToast('Error', err.message, 'error');
  1910. }
  1911. }
  1912. async function toggleWGInterfaceState(name, enable) {
  1913. try {
  1914. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/state`, {
  1915. method: 'POST',
  1916. headers: { 'Content-Type': 'application/json' },
  1917. body: JSON.stringify({ enabled: enable })
  1918. });
  1919. if (res.ok) {
  1920. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  1921. loadWireGuard(false);
  1922. fetchData(false);
  1923. }
  1924. } catch (err) {
  1925. showToast('Error', err.message, 'error');
  1926. }
  1927. }
  1928. async function deleteWGInterface(name) {
  1929. if (!confirm(`Are you sure you want to delete WireGuard interface ${name}? All associated peers will also be removed.`)) return;
  1930. try {
  1931. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1932. if (res.ok) {
  1933. showToast('Deleted', `Interface ${name} removed`, 'success');
  1934. loadWireGuard(false);
  1935. fetchData(false);
  1936. }
  1937. } catch (err) {
  1938. showToast('Error', err.message, 'error');
  1939. }
  1940. }
  1941. function populateWGPeerIfaceSelect(selectedIface = '') {
  1942. const sel = document.getElementById('wg-peer-modal-iface');
  1943. if (!sel) return;
  1944. sel.innerHTML = '';
  1945. (state.wgInterfaces || []).forEach(i => {
  1946. const opt = document.createElement('option');
  1947. opt.value = i.name;
  1948. opt.innerText = `${i.name} (${i.address || 'No IP'})`;
  1949. if (i.name === selectedIface) opt.selected = true;
  1950. sel.appendChild(opt);
  1951. });
  1952. }
  1953. function openAddWGPeerModal() {
  1954. if ((state.wgInterfaces || []).length === 0) {
  1955. showToast('No Interfaces', 'Please add a WireGuard interface first before adding peers', 'warning');
  1956. openAddWGInterfaceModal();
  1957. return;
  1958. }
  1959. document.getElementById('wg-peer-modal-title').innerText = 'Add WireGuard Peer';
  1960. document.getElementById('wg-peer-modal-edit-orig-iface').value = '';
  1961. document.getElementById('wg-peer-modal-edit-orig-pubkey').value = '';
  1962. populateWGPeerIfaceSelect();
  1963. document.getElementById('wg-peer-modal-name').value = '';
  1964. document.getElementById('wg-peer-modal-pubkey').value = '';
  1965. document.getElementById('wg-peer-modal-allowedips').value = '10.10.0.2/32';
  1966. document.getElementById('wg-peer-modal-endpoint').value = '';
  1967. document.getElementById('wg-peer-modal-port').value = '';
  1968. document.getElementById('wg-peer-modal-keepalive').value = '25';
  1969. document.getElementById('wg-peer-modal-preshared').value = '';
  1970. document.getElementById('wg-peer-modal-disabled').checked = false;
  1971. document.getElementById('wg-peer-key-warning').classList.add('hidden');
  1972. document.getElementById('wg-peer-gen-key-box').classList.add('hidden');
  1973. document.getElementById('wg-peer-modal').classList.remove('hidden');
  1974. }
  1975. function openEditWGPeerModal(ifaceName, pubKey) {
  1976. const peer = (state.wgPeers || []).find(p => p.interface === ifaceName && p.public_key === pubKey);
  1977. if (!peer) {
  1978. showToast('Not Found', 'Peer not found', 'warning');
  1979. return;
  1980. }
  1981. document.getElementById('wg-peer-modal-title').innerText = `Edit WireGuard Peer (${peer.name || ifaceName})`;
  1982. document.getElementById('wg-peer-modal-edit-orig-iface').value = peer.interface;
  1983. document.getElementById('wg-peer-modal-edit-orig-pubkey').value = peer.public_key;
  1984. populateWGPeerIfaceSelect(peer.interface);
  1985. document.getElementById('wg-peer-modal-name').value = peer.name || '';
  1986. document.getElementById('wg-peer-modal-pubkey').value = peer.public_key || '';
  1987. document.getElementById('wg-peer-modal-allowedips').value = (peer.allowed_ips || []).join(', ');
  1988. let epHost = (peer.endpoint_address || '').trim();
  1989. let epPort = peer.endpoint_port || '';
  1990. while (epHost.includes(':') && !epHost.startsWith('[')) {
  1991. const lastColon = epHost.lastIndexOf(':');
  1992. const maybePort = epHost.substring(lastColon + 1);
  1993. if (!isNaN(parseInt(maybePort, 10)) && parseInt(maybePort, 10) > 0) {
  1994. if (!epPort) epPort = parseInt(maybePort, 10);
  1995. epHost = epHost.substring(0, lastColon);
  1996. } else {
  1997. break;
  1998. }
  1999. }
  2000. document.getElementById('wg-peer-modal-endpoint').value = epHost;
  2001. document.getElementById('wg-peer-modal-port').value = epPort;
  2002. document.getElementById('wg-peer-modal-keepalive').value = peer.persistent_keepalive ?? 25;
  2003. document.getElementById('wg-peer-modal-preshared').value = peer.preshared_key || '';
  2004. document.getElementById('wg-peer-modal-disabled').checked = !!peer.disabled;
  2005. document.getElementById('wg-peer-key-warning').classList.add('hidden');
  2006. document.getElementById('wg-peer-gen-key-box').classList.add('hidden');
  2007. document.getElementById('wg-peer-modal').classList.remove('hidden');
  2008. }
  2009. function closeAddWGPeerModal() {
  2010. document.getElementById('wg-peer-modal').classList.add('hidden');
  2011. }
  2012. async function generatePeerKeypairHelper() {
  2013. try {
  2014. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  2015. const keys = await res.json();
  2016. if (res.ok) {
  2017. document.getElementById('wg-peer-modal-pubkey').value = keys.public_key;
  2018. document.getElementById('wg-peer-gen-privkey').value = keys.private_key;
  2019. document.getElementById('wg-peer-gen-key-box').classList.remove('hidden');
  2020. checkWGPeerKeyValidity();
  2021. showToast('Keypair Generated', 'Public key inserted and client private key ready to copy', 'info');
  2022. }
  2023. } catch (err) {
  2024. showToast('Error', 'Failed to generate keypair: ' + err.message, 'error');
  2025. }
  2026. }
  2027. function copyGeneratedPeerPrivKey() {
  2028. const priv = document.getElementById('wg-peer-gen-privkey').value;
  2029. if (priv) copyToClipboard(priv, 'Client Private Key');
  2030. }
  2031. async function generatePeerPSK() {
  2032. try {
  2033. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  2034. const keys = await res.json();
  2035. if (res.ok && keys.private_key) {
  2036. document.getElementById('wg-peer-modal-preshared').value = keys.private_key;
  2037. showToast('PSK Generated', 'Generated 256-bit preshared key', 'info');
  2038. }
  2039. } catch (err) {
  2040. showToast('Error', err.message, 'error');
  2041. }
  2042. }
  2043. function checkWGPeerKeyValidity() {
  2044. const ifaceName = document.getElementById('wg-peer-modal-iface').value;
  2045. const peerPubKey = document.getElementById('wg-peer-modal-pubkey').value.trim();
  2046. const warningEl = document.getElementById('wg-peer-key-warning');
  2047. if (!warningEl) return;
  2048. const targetIface = (state.wgInterfaces || []).find(i => i.name === ifaceName);
  2049. if (targetIface && targetIface.public_key && peerPubKey && targetIface.public_key === peerPubKey) {
  2050. warningEl.classList.remove('hidden');
  2051. } else {
  2052. warningEl.classList.add('hidden');
  2053. }
  2054. }
  2055. async function submitSaveWGPeer(e) {
  2056. e.preventDefault();
  2057. const origIface = document.getElementById('wg-peer-modal-edit-orig-iface').value.trim();
  2058. const origPubKey = document.getElementById('wg-peer-modal-edit-orig-pubkey').value.trim();
  2059. const iface = document.getElementById('wg-peer-modal-iface').value;
  2060. const name = document.getElementById('wg-peer-modal-name').value.trim();
  2061. const pub = document.getElementById('wg-peer-modal-pubkey').value.trim();
  2062. const allowed = document.getElementById('wg-peer-modal-allowedips').value
  2063. .split(',')
  2064. .map(s => s.trim())
  2065. .filter(s => s.length > 0);
  2066. let epHost = document.getElementById('wg-peer-modal-endpoint').value.trim();
  2067. let epPort = parseInt(document.getElementById('wg-peer-modal-port').value, 10) || 0;
  2068. while (epHost.includes(':') && !epHost.startsWith('[')) {
  2069. const lastColon = epHost.lastIndexOf(':');
  2070. const maybePort = epHost.substring(lastColon + 1);
  2071. if (!isNaN(parseInt(maybePort, 10)) && parseInt(maybePort, 10) > 0) {
  2072. if (!epPort) epPort = parseInt(maybePort, 10);
  2073. epHost = epHost.substring(0, lastColon);
  2074. } else {
  2075. break;
  2076. }
  2077. }
  2078. const keepalive = parseInt(document.getElementById('wg-peer-modal-keepalive').value, 10) || 0;
  2079. const psk = document.getElementById('wg-peer-modal-preshared').value.trim();
  2080. const disabled = document.getElementById('wg-peer-modal-disabled').checked;
  2081. // Validation
  2082. const targetIface = (state.wgInterfaces || []).find(i => i.name === iface);
  2083. if (targetIface && targetIface.public_key === pub) {
  2084. showToast('Invalid Peer Key', 'Peer public key cannot be the same as the interface public key!', 'error');
  2085. return;
  2086. }
  2087. try {
  2088. const res = await fetch(`${API_BASE}/vpn/wireguard/peers`, {
  2089. method: 'POST',
  2090. headers: { 'Content-Type': 'application/json' },
  2091. body: JSON.stringify({
  2092. orig_interface: origIface,
  2093. orig_public_key: origPubKey,
  2094. interface: iface,
  2095. name,
  2096. public_key: pub,
  2097. allowed_ips: allowed,
  2098. endpoint_address: epHost,
  2099. endpoint_port: epPort,
  2100. persistent_keepalive: keepalive,
  2101. preshared_key: psk,
  2102. disabled
  2103. })
  2104. });
  2105. const data = await res.json();
  2106. if (res.ok) {
  2107. showToast('Peer Saved', `Peer ${name} saved on ${iface}`, 'success');
  2108. closeAddWGPeerModal();
  2109. loadWireGuard(false);
  2110. } else {
  2111. showToast('Error', data.error || 'Failed to save peer', 'error');
  2112. }
  2113. } catch (err) {
  2114. showToast('Error', err.message, 'error');
  2115. }
  2116. }
  2117. async function toggleWGPeerState(iface, pubkey, enable) {
  2118. try {
  2119. const res = await fetch(`${API_BASE}/vpn/wireguard/peers/state`, {
  2120. method: 'POST',
  2121. headers: { 'Content-Type': 'application/json' },
  2122. body: JSON.stringify({ interface: iface, public_key: pubkey, enabled: enable })
  2123. });
  2124. const data = await res.json();
  2125. if (res.ok) {
  2126. showToast(enable ? 'Peer Enabled' : 'Peer Disabled', `Peer state updated on ${iface}`, 'info');
  2127. loadWireGuard(false);
  2128. } else {
  2129. showToast('Error', data.error || 'Failed to update peer state', 'error');
  2130. }
  2131. } catch (err) {
  2132. showToast('Error', err.message, 'error');
  2133. }
  2134. }
  2135. async function deleteWGPeer(iface, pubkey) {
  2136. if (!confirm(`Are you sure you want to remove peer from ${iface}?`)) return;
  2137. try {
  2138. const res = await fetch(`${API_BASE}/vpn/wireguard/peers/delete`, {
  2139. method: 'POST',
  2140. headers: { 'Content-Type': 'application/json' },
  2141. body: JSON.stringify({ interface: iface, public_key: pubkey })
  2142. });
  2143. const data = await res.json();
  2144. if (res.ok) {
  2145. showToast('Peer Deleted', 'WireGuard peer removed', 'success');
  2146. loadWireGuard(false);
  2147. } else {
  2148. showToast('Error', data.error || 'Failed to remove peer', 'error');
  2149. }
  2150. } catch (err) {
  2151. showToast('Error', err.message, 'error');
  2152. }
  2153. }
  2154. // ======================== IPSec FortiGate Phase 1 & 2 Multi-Tunnel Engine ========================
  2155. function switchIpsecModalTab(tab) {
  2156. const p1Tab = document.getElementById('tab-btn-ipsec-p1');
  2157. const p2Tab = document.getElementById('tab-btn-ipsec-p2');
  2158. const p1Content = document.getElementById('ipsec-tab-content-p1');
  2159. const p2Content = document.getElementById('ipsec-tab-content-p2');
  2160. const stepBtn = document.getElementById('btn-ipsec-switch-step');
  2161. if (tab === 'p1') {
  2162. if (p1Tab) {
  2163. p1Tab.className = 'px-4 py-2 text-xs font-bold border-b-2 border-amber-500 text-amber-300 transition flex items-center gap-2';
  2164. }
  2165. if (p2Tab) {
  2166. p2Tab.className = 'px-4 py-2 text-xs font-bold border-b-2 border-transparent text-slate-400 hover:text-slate-200 transition flex items-center gap-2';
  2167. }
  2168. if (p1Content) p1Content.classList.remove('hidden');
  2169. if (p2Content) p2Content.classList.add('hidden');
  2170. if (stepBtn) stepBtn.innerHTML = 'Next: Phase 2 Selectors &rarr;';
  2171. } else {
  2172. if (p1Tab) {
  2173. p1Tab.className = 'px-4 py-2 text-xs font-bold border-b-2 border-transparent text-slate-400 hover:text-slate-200 transition flex items-center gap-2';
  2174. }
  2175. if (p2Tab) {
  2176. p2Tab.className = 'px-4 py-2 text-xs font-bold border-b-2 border-cyan-500 text-cyan-300 transition flex items-center gap-2';
  2177. }
  2178. if (p1Content) p1Content.classList.add('hidden');
  2179. if (p2Content) p2Content.classList.remove('hidden');
  2180. if (stepBtn) stepBtn.innerHTML = '&larr; Back: Phase 1 (IKE)';
  2181. }
  2182. }
  2183. function toggleIpsecPhaseStep() {
  2184. const p1Content = document.getElementById('ipsec-tab-content-p1');
  2185. if (p1Content && !p1Content.classList.contains('hidden')) {
  2186. switchIpsecModalTab('p2');
  2187. } else {
  2188. switchIpsecModalTab('p1');
  2189. }
  2190. }
  2191. function toggleIpsecPskVisibility() {
  2192. const pskInput = document.getElementById('ipsec-modal-psk');
  2193. if (!pskInput) return;
  2194. pskInput.type = pskInput.type === 'password' ? 'text' : 'password';
  2195. }
  2196. function addIpsecLocalSubnet(val = '') {
  2197. const container = document.getElementById('ipsec-modal-local-subnets-container');
  2198. if (!container) return;
  2199. const row = document.createElement('div');
  2200. row.className = 'flex items-center gap-2 ipsec-subnet-row';
  2201. row.innerHTML = `
  2202. <input type="text" value="${escapeHtml(val)}" placeholder="e.g. 192.168.10.0/24 or 10.0.1.0/24" class="flex-1 bg-slate-900 border border-slate-700 rounded-lg px-3 py-1.5 text-white font-mono text-xs focus:outline-none focus:border-cyan-500">
  2203. <button type="button" onclick="this.closest('.ipsec-subnet-row').remove()" class="w-7 h-7 flex items-center justify-center bg-slate-800 hover:bg-rose-950 text-slate-400 hover:text-rose-400 border border-slate-700 rounded-lg text-base font-bold transition" title="Remove local subnet">-</button>
  2204. `;
  2205. container.appendChild(row);
  2206. }
  2207. function addIpsecRemoteSubnet(val = '') {
  2208. const container = document.getElementById('ipsec-modal-remote-subnets-container');
  2209. if (!container) return;
  2210. const row = document.createElement('div');
  2211. row.className = 'flex items-center gap-2 ipsec-subnet-row';
  2212. row.innerHTML = `
  2213. <input type="text" value="${escapeHtml(val)}" placeholder="e.g. 192.168.20.0/24 or 10.0.2.0/24" class="flex-1 bg-slate-900 border border-slate-700 rounded-lg px-3 py-1.5 text-white font-mono text-xs focus:outline-none focus:border-purple-500">
  2214. <button type="button" onclick="this.closest('.ipsec-subnet-row').remove()" class="w-7 h-7 flex items-center justify-center bg-slate-800 hover:bg-rose-950 text-slate-400 hover:text-rose-400 border border-slate-700 rounded-lg text-base font-bold transition" title="Remove remote subnet">-</button>
  2215. `;
  2216. container.appendChild(row);
  2217. }
  2218. function updateIpsecEspProposalFromPFS(val) {
  2219. const prop = document.getElementById('ipsec-modal-espprop');
  2220. if (!prop) return;
  2221. if (val === 'none') {
  2222. prop.value = 'aes256-sha256,aes128-sha256,default';
  2223. } else {
  2224. prop.value = `aes256-sha256-${val},aes128-sha256-${val},default`;
  2225. }
  2226. }
  2227. function updateIpsecIkeProposalFromDH(dh) {
  2228. const el = document.getElementById('ipsec-modal-ikeprop');
  2229. if (el) {
  2230. el.value = `aes256-sha256-${dh},aes128-sha256-${dh},default`;
  2231. }
  2232. }
  2233. function safeSetVal(id, val) {
  2234. const el = document.getElementById(id);
  2235. if (el) el.value = val;
  2236. }
  2237. function safeSetChecked(id, val) {
  2238. const el = document.getElementById(id);
  2239. if (el) el.checked = !!val;
  2240. }
  2241. function safeGetVal(id, def = '') {
  2242. const el = document.getElementById(id);
  2243. return el ? el.value : def;
  2244. }
  2245. async function loadIPSec(populateInputs = true) {
  2246. try {
  2247. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels`);
  2248. const list = await res.json();
  2249. state.ipsecTunnels = Array.isArray(list) ? list : [];
  2250. const activeCount = state.ipsecTunnels.filter(t => t.running || t.status === 'ESTABLISHED').length;
  2251. const badge = document.getElementById('ipsec-sas-badge');
  2252. if (badge) badge.innerText = `${activeCount} Active SAs`;
  2253. const tbody = document.getElementById('ipsec-table-body');
  2254. const empty = document.getElementById('ipsec-empty');
  2255. if (!tbody) return;
  2256. tbody.innerHTML = '';
  2257. if (state.ipsecTunnels.length === 0) {
  2258. if (empty) empty.classList.remove('hidden');
  2259. } else {
  2260. if (empty) empty.classList.add('hidden');
  2261. state.ipsecTunnels.forEach(c => {
  2262. const isEstablished = c.running || c.status === 'ESTABLISHED';
  2263. const tr = document.createElement('tr');
  2264. tr.className = 'hover:bg-slate-800/40 transition text-xs select-none';
  2265. // Local subnets tags
  2266. const localList = (c.local_subnets && c.local_subnets.length > 0) ? c.local_subnets : (c.local_subnet ? [c.local_subnet] : ['0.0.0.0/0']);
  2267. const localBadges = localList.map(s => `<span class="px-1.5 py-0.5 rounded bg-cyan-950/60 border border-cyan-800/60 text-cyan-300 font-mono text-[10px] mr-1">${escapeHtml(s)}</span>`).join('');
  2268. // Remote subnets tags
  2269. const remoteList = (c.remote_subnets && c.remote_subnets.length > 0) ? c.remote_subnets : (c.remote_subnet ? [c.remote_subnet] : ['0.0.0.0/0']);
  2270. const remoteBadges = remoteList.map(s => `<span class="px-1.5 py-0.5 rounded bg-purple-950/60 border border-purple-800/60 text-purple-300 font-mono text-[10px] mr-1">${escapeHtml(s)}</span>`).join('');
  2271. const ikeVersionBadge = (c.ike_version || 'ikev2').toUpperCase();
  2272. const p2Name = c.phase2_name || `${c.name}_p2`;
  2273. tr.innerHTML = `
  2274. <td class="py-2.5 px-3 text-center">
  2275. ${isEstablished ? `
  2276. <span class="inline-flex items-center gap-1.5 text-emerald-400 font-mono font-bold text-[11px]" title="Active SA Established">
  2277. <span class="w-2.5 h-2.5 rounded-full bg-emerald-400 animate-pulse"></span>
  2278. <span>UP</span>
  2279. </span>
  2280. ` : (c.disabled ? `
  2281. <span class="inline-flex items-center gap-1.5 text-slate-500 font-mono text-[11px]" title="Tunnel Disabled">
  2282. <span class="w-2 h-2 rounded-full bg-rose-500"></span>
  2283. <span>DOWN</span>
  2284. </span>
  2285. ` : `
  2286. <span class="inline-flex items-center gap-1.5 text-amber-400 font-mono text-[11px]" title="Disconnected / Idle">
  2287. <span class="w-2 h-2 rounded-full bg-amber-400"></span>
  2288. <span>IDLE</span>
  2289. </span>
  2290. `)}
  2291. </td>
  2292. <td class="py-2.5 px-4 font-bold text-white">
  2293. <div class="flex items-center gap-2">
  2294. <span class="text-amber-400">🛡</span>
  2295. <div>
  2296. <div>${escapeHtml(c.name)}</div>
  2297. <div class="text-[10px] text-slate-500 font-normal">P2: ${escapeHtml(p2Name)}</div>
  2298. </div>
  2299. </div>
  2300. </td>
  2301. <td class="py-2.5 px-4 text-slate-300 font-mono font-medium">${escapeHtml(c.remote_addrs || '%any')}</td>
  2302. <td class="py-2.5 px-4 font-sans">
  2303. <div class="flex items-center gap-1.5">
  2304. <span class="px-1.5 py-0.5 rounded bg-amber-500/10 text-amber-300 border border-amber-500/30 font-mono text-[10px] font-semibold">${ikeVersionBadge}</span>
  2305. <span class="text-[10px] text-slate-400">${c.auth_method || 'PSK'}</span>
  2306. </div>
  2307. </td>
  2308. <td class="py-2.5 px-4">
  2309. <div class="space-y-1">
  2310. <div class="flex items-center flex-wrap gap-1">
  2311. <span class="text-[9px] text-cyan-400 uppercase font-bold mr-1">Local:</span>
  2312. ${localBadges}
  2313. </div>
  2314. <div class="flex items-center flex-wrap gap-1">
  2315. <span class="text-[9px] text-purple-400 uppercase font-bold mr-1">Remote:</span>
  2316. ${remoteBadges}
  2317. </div>
  2318. </div>
  2319. </td>
  2320. <td class="py-2.5 px-4 font-mono text-[11px] text-slate-400">
  2321. <div class="truncate max-w-[140px]" title="${escapeHtml(c.esp_proposals || '')}">
  2322. ${escapeHtml(c.esp_proposals || 'aes256-sha256')}
  2323. </div>
  2324. <div class="text-[10px] text-slate-500">PFS: ${escapeHtml(c.pfs_group || 'modp2048')}</div>
  2325. </td>
  2326. <td class="py-2.5 px-4 text-right space-x-2 font-sans">
  2327. ${isEstablished ? `
  2328. <button onclick="stopIPSecTunnel('${c.name}')" class="px-2 py-0.5 text-xs bg-rose-500/20 text-rose-400 hover:bg-rose-500/30 rounded border border-rose-500/30 font-medium">Bring Down</button>
  2329. ` : `
  2330. <button onclick="startIPSecTunnel('${c.name}')" class="px-2 py-0.5 text-xs bg-emerald-500/20 text-emerald-400 hover:bg-emerald-500/30 rounded border border-emerald-500/30 font-semibold">Bring Up</button>
  2331. `}
  2332. <button onclick="toggleIPSecState('${c.name}', ${c.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  2333. ${c.disabled ? 'Enable' : 'Disable'}
  2334. </button>
  2335. <button onclick="openEditIPSecModal('${c.name}')" class="text-xs text-amber-400 hover:text-amber-300">Edit</button>
  2336. <button onclick="deleteIPSecConn('${c.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2337. </td>
  2338. `;
  2339. tbody.appendChild(tr);
  2340. });
  2341. }
  2342. } catch (err) {
  2343. console.error('Failed to load IPSec:', err);
  2344. }
  2345. }
  2346. function openAddIPSecModal() {
  2347. const modal = document.getElementById('ipsec-modal');
  2348. if (!modal) return;
  2349. const title = document.getElementById('ipsec-modal-title');
  2350. if (title) title.innerText = 'Configure IPSec Site-to-Site Tunnel';
  2351. // Phase 1 Fields
  2352. safeSetVal('ipsec-modal-name', `tunnel-${(state.ipsecTunnels || []).length + 1}`);
  2353. const nameEl = document.getElementById('ipsec-modal-name');
  2354. if (nameEl) nameEl.readOnly = false;
  2355. safeSetVal('ipsec-modal-ikeversion', 'ikev2');
  2356. safeSetVal('ipsec-modal-ikever', 'ikev2');
  2357. safeSetVal('ipsec-modal-remotegw', '');
  2358. safeSetVal('ipsec-modal-localaddrs', '');
  2359. safeSetVal('ipsec-modal-comments', '');
  2360. safeSetVal('ipsec-modal-psk', '');
  2361. safeSetVal('ipsec-modal-ikeprop', 'aes256-sha256-modp2048,aes128-sha256-modp2048,default');
  2362. safeSetVal('ipsec-modal-dhgroup', 'modp2048');
  2363. safeSetVal('ipsec-modal-ikekeylife', '86400');
  2364. safeSetVal('ipsec-modal-localid', '');
  2365. safeSetVal('ipsec-modal-remoteid', '');
  2366. safeSetVal('ipsec-modal-dpd', 'on-demand');
  2367. // Phase 2 Fields
  2368. safeSetVal('ipsec-modal-p2name', `tunnel-${(state.ipsecTunnels || []).length + 1}_p2`);
  2369. safeSetVal('ipsec-modal-espkeylife', '28800');
  2370. safeSetVal('ipsec-modal-espprop', 'aes256-sha256-modp2048,aes128-sha256-modp2048,default');
  2371. safeSetVal('ipsec-modal-pfsgroup', 'modp2048');
  2372. safeSetChecked('ipsec-modal-autostart', true);
  2373. safeSetChecked('ipsec-modal-disabled', false);
  2374. // Clear & Populate default dynamic subnets
  2375. const localContainer = document.getElementById('ipsec-modal-local-subnets-container');
  2376. const remoteContainer = document.getElementById('ipsec-modal-remote-subnets-container');
  2377. if (localContainer) {
  2378. localContainer.innerHTML = '';
  2379. addIpsecLocalSubnet('192.168.10.0/24');
  2380. }
  2381. if (remoteContainer) {
  2382. remoteContainer.innerHTML = '';
  2383. addIpsecRemoteSubnet('192.168.20.0/24');
  2384. }
  2385. switchIpsecModalTab('p1');
  2386. modal.classList.remove('hidden');
  2387. }
  2388. function openEditIPSecModal(name) {
  2389. const modal = document.getElementById('ipsec-modal');
  2390. if (!modal) return;
  2391. const conn = (state.ipsecTunnels || []).find(c => c.name === name);
  2392. if (!conn) return;
  2393. const title = document.getElementById('ipsec-modal-title');
  2394. if (title) title.innerText = `Edit IPSec Tunnel: ${name}`;
  2395. // Phase 1 Fields
  2396. safeSetVal('ipsec-modal-name', conn.name);
  2397. const nameEl = document.getElementById('ipsec-modal-name');
  2398. if (nameEl) nameEl.readOnly = true;
  2399. safeSetVal('ipsec-modal-ikeversion', conn.ike_version || 'ikev2');
  2400. safeSetVal('ipsec-modal-ikever', conn.ike_version || 'ikev2');
  2401. safeSetVal('ipsec-modal-remotegw', conn.remote_addrs || '');
  2402. safeSetVal('ipsec-modal-localaddrs', conn.local_addrs || '');
  2403. safeSetVal('ipsec-modal-comments', conn.comment || '');
  2404. safeSetVal('ipsec-modal-psk', conn.preshared_key || '');
  2405. safeSetVal('ipsec-modal-ikeprop', conn.ike_proposals || 'aes256-sha256-modp2048,default');
  2406. safeSetVal('ipsec-modal-ikekeylife', conn.ike_keylife || 86400);
  2407. safeSetVal('ipsec-modal-localid', conn.local_id || '');
  2408. safeSetVal('ipsec-modal-remoteid', conn.remote_id || '');
  2409. safeSetVal('ipsec-modal-dpd', conn.dpd || 'on-demand');
  2410. // Phase 2 Fields
  2411. safeSetVal('ipsec-modal-p2name', conn.phase2_name || `${conn.name}_p2`);
  2412. safeSetVal('ipsec-modal-espkeylife', conn.esp_keylife || 28800);
  2413. safeSetVal('ipsec-modal-espprop', conn.esp_proposals || 'aes256-sha256-modp2048,default');
  2414. safeSetVal('ipsec-modal-pfsgroup', conn.pfs_group || 'modp2048');
  2415. safeSetChecked('ipsec-modal-autostart', conn.auto_start ?? true);
  2416. safeSetChecked('ipsec-modal-disabled', !!conn.disabled);
  2417. // Populate dynamic subnets
  2418. const localContainer = document.getElementById('ipsec-modal-local-subnets-container');
  2419. const remoteContainer = document.getElementById('ipsec-modal-remote-subnets-container');
  2420. if (localContainer) {
  2421. localContainer.innerHTML = '';
  2422. const locals = (conn.local_subnets && conn.local_subnets.length > 0) ? conn.local_subnets : (conn.local_subnet ? [conn.local_subnet] : ['192.168.10.0/24']);
  2423. locals.forEach(s => addIpsecLocalSubnet(s));
  2424. }
  2425. if (remoteContainer) {
  2426. remoteContainer.innerHTML = '';
  2427. const remotes = (conn.remote_subnets && conn.remote_subnets.length > 0) ? conn.remote_subnets : (conn.remote_subnet ? [conn.remote_subnet] : ['192.168.20.0/24']);
  2428. remotes.forEach(s => addIpsecRemoteSubnet(s));
  2429. }
  2430. switchIpsecModalTab('p1');
  2431. modal.classList.remove('hidden');
  2432. }
  2433. function closeAddIPSecModal() {
  2434. const modal = document.getElementById('ipsec-modal');
  2435. if (modal) modal.classList.add('hidden');
  2436. }
  2437. async function submitSaveIPSec(e) {
  2438. if (e) e.preventDefault();
  2439. const name = safeGetVal('ipsec-modal-name').trim();
  2440. if (!name) {
  2441. showToast('Error', 'Tunnel name is required', 'error');
  2442. return;
  2443. }
  2444. const ikeVersion = safeGetVal('ipsec-modal-ikeversion') || safeGetVal('ipsec-modal-ikever', 'ikev2');
  2445. const remotegw = safeGetVal('ipsec-modal-remotegw').trim();
  2446. const localAddrs = safeGetVal('ipsec-modal-localaddrs').trim() || '%any';
  2447. const comments = safeGetVal('ipsec-modal-comments').trim();
  2448. const psk = safeGetVal('ipsec-modal-psk');
  2449. const ikeProposals = safeGetVal('ipsec-modal-ikeprop', 'aes256-sha256-modp2048,default').trim();
  2450. const ikeKeylife = parseInt(safeGetVal('ipsec-modal-ikekeylife', '86400'), 10) || 86400;
  2451. const localId = safeGetVal('ipsec-modal-localid').trim();
  2452. const remoteId = safeGetVal('ipsec-modal-remoteid').trim();
  2453. const dpd = safeGetVal('ipsec-modal-dpd', 'on-demand');
  2454. const phase2Name = safeGetVal('ipsec-modal-p2name').trim() || `${name}_p2`;
  2455. const espProposals = safeGetVal('ipsec-modal-espprop', 'aes256-sha256-modp2048,default').trim();
  2456. const espKeylife = parseInt(safeGetVal('ipsec-modal-espkeylife', '28800'), 10) || 28800;
  2457. const pfsGroup = safeGetVal('ipsec-modal-pfsgroup', 'modp2048');
  2458. const autostart = document.getElementById('ipsec-modal-autostart')?.checked ?? true;
  2459. const disabled = document.getElementById('ipsec-modal-disabled')?.checked ?? false;
  2460. // Scrape dynamic local and remote subnets
  2461. const localInputs = document.querySelectorAll('#ipsec-modal-local-subnets-container input');
  2462. const localSubnets = [];
  2463. localInputs.forEach(inp => {
  2464. const v = inp.value.trim();
  2465. if (v) localSubnets.push(v);
  2466. });
  2467. const remoteInputs = document.querySelectorAll('#ipsec-modal-remote-subnets-container input');
  2468. const remoteSubnets = [];
  2469. remoteInputs.forEach(inp => {
  2470. const v = inp.value.trim();
  2471. if (v) remoteSubnets.push(v);
  2472. });
  2473. try {
  2474. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels`, {
  2475. method: 'POST',
  2476. headers: { 'Content-Type': 'application/json' },
  2477. body: JSON.stringify({
  2478. name,
  2479. comment: comments,
  2480. ike_version: ikeVersion,
  2481. local_addrs: localAddrs,
  2482. remote_addrs: remotegw,
  2483. preshared_key: psk,
  2484. ike_proposals: ikeProposals,
  2485. ike_keylife: ikeKeylife,
  2486. local_id: localId,
  2487. remote_id: remoteId,
  2488. dpd: dpd,
  2489. phase2_name: phase2Name,
  2490. esp_proposals: espProposals,
  2491. esp_keylife: espKeylife,
  2492. pfs_group: pfsGroup,
  2493. pfs: pfsGroup !== 'none',
  2494. local_subnets: localSubnets,
  2495. remote_subnets: remoteSubnets,
  2496. local_subnet: localSubnets[0] || '0.0.0.0/0',
  2497. remote_subnet: remoteSubnets[0] || '0.0.0.0/0',
  2498. auto_start: autostart,
  2499. disabled
  2500. })
  2501. });
  2502. if (res.ok) {
  2503. showToast('IPSec Saved', `FortiGate Tunnel ${name} configured`, 'success');
  2504. closeAddIPSecModal();
  2505. loadIPSec(false);
  2506. } else {
  2507. const err = await res.json();
  2508. showToast('Error', err.error || 'Failed to save IPSec tunnel', 'error');
  2509. }
  2510. } catch (err) {
  2511. showToast('Error', err.message, 'error');
  2512. }
  2513. }
  2514. async function startIPSecTunnel(name) {
  2515. try {
  2516. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/start`, { method: 'POST' });
  2517. if (res.ok) {
  2518. showToast('Initiating Tunnel', `Attempting SA handshake for ${name}...`, 'info');
  2519. setTimeout(() => loadIPSec(false), 2000);
  2520. }
  2521. } catch (err) {
  2522. showToast('Error', err.message, 'error');
  2523. }
  2524. }
  2525. async function stopIPSecTunnel(name) {
  2526. try {
  2527. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/stop`, { method: 'POST' });
  2528. if (res.ok) {
  2529. showToast('Terminated', `IPSec SA for ${name} closed`, 'info');
  2530. loadIPSec(false);
  2531. }
  2532. } catch (err) {
  2533. showToast('Error', err.message, 'error');
  2534. }
  2535. }
  2536. async function toggleIPSecState(name, enable) {
  2537. try {
  2538. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/state`, {
  2539. method: 'POST',
  2540. headers: { 'Content-Type': 'application/json' },
  2541. body: JSON.stringify({ enabled: enable })
  2542. });
  2543. if (res.ok) {
  2544. showToast(enable ? 'Enabled' : 'Disabled', `IPSec tunnel ${name} updated`, 'info');
  2545. loadIPSec(false);
  2546. }
  2547. } catch (err) {
  2548. showToast('Error', err.message, 'error');
  2549. }
  2550. }
  2551. async function deleteIPSecConn(name) {
  2552. if (!confirm(`Are you sure you want to delete IPSec tunnel ${name}?`)) return;
  2553. try {
  2554. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2555. if (res.ok) {
  2556. showToast('Deleted', `IPSec connection ${name} removed`, 'success');
  2557. loadIPSec(false);
  2558. fetchData(false);
  2559. }
  2560. } catch (err) {
  2561. showToast('Error', err.message, 'error');
  2562. }
  2563. }
  2564. // ======================== L2TP Multi-Instance ========================
  2565. async function loadL2TP(populateInputs = true) {
  2566. try {
  2567. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2568. await fetchPPPProfilesList();
  2569. }
  2570. const res = await fetch(`${API_BASE}/vpn/l2tp/clients`);
  2571. const list = await res.json();
  2572. state.l2tpList = Array.isArray(list) ? list : [];
  2573. const badge = document.getElementById('l2tp-count-badge');
  2574. if (badge) badge.innerText = `${state.l2tpList.length} Client${state.l2tpList.length !== 1 ? 's' : ''}`;
  2575. const tbody = document.getElementById('l2tp-table-body');
  2576. const empty = document.getElementById('l2tp-empty');
  2577. if (!tbody) return;
  2578. tbody.innerHTML = '';
  2579. if (state.l2tpList.length === 0) {
  2580. if (empty) empty.classList.remove('hidden');
  2581. } else {
  2582. if (empty) empty.classList.add('hidden');
  2583. state.l2tpList.forEach(inst => {
  2584. const tr = document.createElement('tr');
  2585. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  2586. tr.innerHTML = `
  2587. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  2588. <td class="py-2.5 px-3 font-bold text-white">${escapeHtml(inst.name)}</td>
  2589. <td class="py-2.5 px-3 text-cyan-400 font-mono">${escapeHtml(inst.connect_to)}</td>
  2590. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(inst.username || '-')}</td>
  2591. <td class="py-2.5 px-3 font-mono text-cyan-300"><span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 border border-slate-700">${escapeHtml(inst.profile || 'default-encryption')}</span></td>
  2592. <td class="py-2.5 px-3 font-mono ${inst.assigned_ip ? 'text-emerald-400 font-bold' : 'text-slate-500'}">${escapeHtml(inst.assigned_ip || '-')}</td>
  2593. <td class="py-2.5 px-3 text-slate-400 font-mono">${escapeHtml(inst.ppp_device || '-')}</td>
  2594. <td class="py-2.5 px-3 text-center">
  2595. <span class="px-2 py-0.5 rounded text-[10px] font-sans ${inst.default_route ? 'bg-cyan-500/20 text-cyan-300 border border-cyan-500/30' : 'bg-slate-800 text-slate-500'}">
  2596. ${inst.default_route ? 'Yes' : 'No'}
  2597. </span>
  2598. </td>
  2599. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  2600. ${inst.running ? `
  2601. <button onclick="disconnectL2TPInstance('${escapeHtml(inst.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  2602. ` : `
  2603. <button onclick="connectL2TPInstance('${escapeHtml(inst.name)}')" class="text-xs bg-cyan-600/30 hover:bg-cyan-600/50 text-cyan-300 px-2 py-0.5 rounded border border-cyan-500/30">Connect</button>
  2604. `}
  2605. <button onclick="toggleL2TPState('${escapeHtml(inst.name)}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  2606. ${inst.disabled ? 'Enable' : 'Disable'}
  2607. </button>
  2608. <button onclick="openEditL2TPModal('${escapeHtml(inst.name)}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2609. <button onclick="deleteL2TPInstance('${escapeHtml(inst.name)}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2610. </td>
  2611. `;
  2612. tbody.appendChild(tr);
  2613. });
  2614. }
  2615. } catch (err) {
  2616. console.error('Failed to load L2TP:', err);
  2617. }
  2618. }
  2619. async function openAddL2TPModal() {
  2620. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2621. await fetchPPPProfilesList();
  2622. }
  2623. document.getElementById('l2tp-modal-title').innerText = 'Add L2TP Client Interface';
  2624. document.getElementById('l2tp-modal-name').value = `l2tp-out${(state.l2tpList || []).length + 1}`;
  2625. document.getElementById('l2tp-modal-name').readOnly = false;
  2626. document.getElementById('l2tp-modal-server').value = '';
  2627. document.getElementById('l2tp-modal-user').value = '';
  2628. document.getElementById('l2tp-modal-pass').value = '';
  2629. document.getElementById('l2tp-modal-ipsec').value = '';
  2630. document.getElementById('l2tp-modal-defroute').checked = true;
  2631. document.getElementById('l2tp-modal-disabled').checked = false;
  2632. populateProfileSelect('l2tp-modal-profile', 'default-encryption', 'default-encryption');
  2633. document.getElementById('l2tp-modal').classList.remove('hidden');
  2634. }
  2635. async function openEditL2TPModal(name) {
  2636. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2637. await fetchPPPProfilesList();
  2638. }
  2639. const inst = (state.l2tpList || []).find(i => i.name === name);
  2640. if (!inst) return;
  2641. document.getElementById('l2tp-modal-title').innerText = `Edit L2TP Client: ${name}`;
  2642. document.getElementById('l2tp-modal-name').value = inst.name;
  2643. document.getElementById('l2tp-modal-name').readOnly = true;
  2644. document.getElementById('l2tp-modal-server').value = inst.connect_to || '';
  2645. document.getElementById('l2tp-modal-user').value = inst.username || '';
  2646. document.getElementById('l2tp-modal-pass').value = inst.password || '';
  2647. document.getElementById('l2tp-modal-ipsec').value = inst.ipsec_secret || '';
  2648. document.getElementById('l2tp-modal-defroute').checked = inst.default_route ?? true;
  2649. document.getElementById('l2tp-modal-disabled').checked = !!inst.disabled;
  2650. populateProfileSelect('l2tp-modal-profile', inst.profile || 'default-encryption', 'default-encryption');
  2651. document.getElementById('l2tp-modal').classList.remove('hidden');
  2652. }
  2653. function closeL2TPModal() {
  2654. document.getElementById('l2tp-modal').classList.add('hidden');
  2655. }
  2656. async function submitSaveL2TP(e) {
  2657. e.preventDefault();
  2658. const name = document.getElementById('l2tp-modal-name').value.trim();
  2659. const server = document.getElementById('l2tp-modal-server').value.trim();
  2660. const user = document.getElementById('l2tp-modal-user').value.trim();
  2661. const pass = document.getElementById('l2tp-modal-pass').value;
  2662. const profile = document.getElementById('l2tp-modal-profile')?.value || 'default-encryption';
  2663. const ipsec = document.getElementById('l2tp-modal-ipsec').value;
  2664. const defRoute = document.getElementById('l2tp-modal-defroute').checked;
  2665. const disabled = document.getElementById('l2tp-modal-disabled').checked;
  2666. try {
  2667. const res = await fetch(`${API_BASE}/vpn/l2tp/clients`, {
  2668. method: 'POST',
  2669. headers: { 'Content-Type': 'application/json' },
  2670. body: JSON.stringify({
  2671. name,
  2672. connect_to: server,
  2673. username: user,
  2674. password: pass,
  2675. profile: profile,
  2676. ipsec_secret: ipsec,
  2677. default_route: defRoute,
  2678. disabled
  2679. })
  2680. });
  2681. if (res.ok) {
  2682. showToast('L2TP Saved', `Client ${name} configuration saved`, 'success');
  2683. closeL2TPModal();
  2684. loadL2TP(false);
  2685. fetchData(false);
  2686. }
  2687. } catch (err) {
  2688. showToast('Error', err.message, 'error');
  2689. }
  2690. }
  2691. async function connectL2TPInstance(name) {
  2692. try {
  2693. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  2694. if (res.ok) {
  2695. showToast('Connecting', `Dialing L2TP ${name}...`, 'info');
  2696. setTimeout(() => loadL2TP(false), 2000);
  2697. }
  2698. } catch (err) {
  2699. showToast('Error', err.message, 'error');
  2700. }
  2701. }
  2702. async function disconnectL2TPInstance(name) {
  2703. try {
  2704. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  2705. if (res.ok) {
  2706. showToast('Disconnected', `L2TP tunnel ${name} terminated`, 'info');
  2707. loadL2TP(false);
  2708. }
  2709. } catch (err) {
  2710. showToast('Error', err.message, 'error');
  2711. }
  2712. }
  2713. async function toggleL2TPState(name, enable) {
  2714. try {
  2715. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/state`, {
  2716. method: 'POST',
  2717. headers: { 'Content-Type': 'application/json' },
  2718. body: JSON.stringify({ enabled: enable })
  2719. });
  2720. if (res.ok) {
  2721. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  2722. loadL2TP(false);
  2723. }
  2724. } catch (err) {
  2725. showToast('Error', err.message, 'error');
  2726. }
  2727. }
  2728. async function deleteL2TPInstance(name) {
  2729. if (!confirm(`Are you sure you want to delete L2TP client ${name}?`)) return;
  2730. try {
  2731. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2732. if (res.ok) {
  2733. showToast('Deleted', `L2TP client ${name} removed`, 'success');
  2734. loadL2TP(false);
  2735. fetchData(false);
  2736. }
  2737. } catch (err) {
  2738. showToast('Error', err.message, 'error');
  2739. }
  2740. }
  2741. // ======================== PPTP Multi-Instance ========================
  2742. async function loadPPTP(populateInputs = true) {
  2743. try {
  2744. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2745. await fetchPPPProfilesList();
  2746. }
  2747. const res = await fetch(`${API_BASE}/vpn/pptp/clients`);
  2748. const list = await res.json();
  2749. state.pptpList = Array.isArray(list) ? list : [];
  2750. const badge = document.getElementById('pptp-count-badge');
  2751. if (badge) badge.innerText = `${state.pptpList.length} Client${state.pptpList.length !== 1 ? 's' : ''}`;
  2752. const tbody = document.getElementById('pptp-table-body');
  2753. const empty = document.getElementById('pptp-empty');
  2754. if (!tbody) return;
  2755. tbody.innerHTML = '';
  2756. if (state.pptpList.length === 0) {
  2757. if (empty) empty.classList.remove('hidden');
  2758. } else {
  2759. if (empty) empty.classList.add('hidden');
  2760. state.pptpList.forEach(inst => {
  2761. const tr = document.createElement('tr');
  2762. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  2763. tr.innerHTML = `
  2764. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  2765. <td class="py-2.5 px-3 font-bold text-white">${escapeHtml(inst.name)}</td>
  2766. <td class="py-2.5 px-3 text-purple-400 font-mono">${escapeHtml(inst.connect_to)}</td>
  2767. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(inst.username || '-')}</td>
  2768. <td class="py-2.5 px-3 font-mono text-purple-300"><span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 border border-slate-700">${escapeHtml(inst.profile || 'default-encryption')}</span></td>
  2769. <td class="py-2.5 px-3 font-mono ${inst.assigned_ip ? 'text-emerald-400 font-bold' : 'text-slate-500'}">${escapeHtml(inst.assigned_ip || '-')}</td>
  2770. <td class="py-2.5 px-3 text-slate-400 font-mono">${escapeHtml(inst.ppp_device || '-')}</td>
  2771. <td class="py-2.5 px-3 text-center">
  2772. <span class="px-2 py-0.5 rounded text-[10px] font-sans ${inst.require_mppe ? 'bg-purple-500/20 text-purple-300 border border-purple-500/30' : 'bg-slate-800 text-slate-500'}">
  2773. ${inst.require_mppe ? 'MPPE-128' : 'None'}
  2774. </span>
  2775. </td>
  2776. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  2777. ${inst.running ? `
  2778. <button onclick="disconnectPPTPInstance('${escapeHtml(inst.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  2779. ` : `
  2780. <button onclick="connectPPTPInstance('${escapeHtml(inst.name)}')" class="text-xs bg-purple-600/30 hover:bg-purple-600/50 text-purple-300 px-2 py-0.5 rounded border border-purple-500/30">Connect</button>
  2781. `}
  2782. <button onclick="togglePPTPState('${escapeHtml(inst.name)}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  2783. ${inst.disabled ? 'Enable' : 'Disable'}
  2784. </button>
  2785. <button onclick="openEditPPTPModal('${escapeHtml(inst.name)}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2786. <button onclick="deletePPTPInstance('${escapeHtml(inst.name)}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2787. </td>
  2788. `;
  2789. tbody.appendChild(tr);
  2790. });
  2791. }
  2792. } catch (err) {
  2793. console.error('Failed to load PPTP:', err);
  2794. }
  2795. }
  2796. async function openAddPPTPModal() {
  2797. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2798. await fetchPPPProfilesList();
  2799. }
  2800. document.getElementById('pptp-modal-title').innerText = 'Add PPTP Client Interface';
  2801. document.getElementById('pptp-modal-name').value = `pptp-out${(state.pptpList || []).length + 1}`;
  2802. document.getElementById('pptp-modal-name').readOnly = false;
  2803. document.getElementById('pptp-modal-server').value = '';
  2804. document.getElementById('pptp-modal-user').value = '';
  2805. document.getElementById('pptp-modal-pass').value = '';
  2806. document.getElementById('pptp-modal-mppe').checked = true;
  2807. document.getElementById('pptp-modal-defroute').checked = true;
  2808. document.getElementById('pptp-modal-disabled').checked = false;
  2809. populateProfileSelect('pptp-modal-profile', 'default-encryption', 'default-encryption');
  2810. document.getElementById('pptp-modal').classList.remove('hidden');
  2811. }
  2812. async function openEditPPTPModal(name) {
  2813. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2814. await fetchPPPProfilesList();
  2815. }
  2816. const inst = (state.pptpList || []).find(i => i.name === name);
  2817. if (!inst) return;
  2818. document.getElementById('pptp-modal-title').innerText = `Edit PPTP Client: ${name}`;
  2819. document.getElementById('pptp-modal-name').value = inst.name;
  2820. document.getElementById('pptp-modal-name').readOnly = true;
  2821. document.getElementById('pptp-modal-server').value = inst.connect_to || '';
  2822. document.getElementById('pptp-modal-user').value = inst.username || '';
  2823. document.getElementById('pptp-modal-pass').value = inst.password || '';
  2824. document.getElementById('pptp-modal-mppe').checked = inst.require_mppe ?? true;
  2825. document.getElementById('pptp-modal-defroute').checked = inst.default_route ?? true;
  2826. document.getElementById('pptp-modal-disabled').checked = !!inst.disabled;
  2827. populateProfileSelect('pptp-modal-profile', inst.profile || 'default-encryption', 'default-encryption');
  2828. document.getElementById('pptp-modal').classList.remove('hidden');
  2829. }
  2830. function closePPTPModal() {
  2831. document.getElementById('pptp-modal').classList.add('hidden');
  2832. }
  2833. async function submitSavePPTP(e) {
  2834. e.preventDefault();
  2835. const name = document.getElementById('pptp-modal-name').value.trim();
  2836. const server = document.getElementById('pptp-modal-server').value.trim();
  2837. const user = document.getElementById('pptp-modal-user').value.trim();
  2838. const pass = document.getElementById('pptp-modal-pass').value;
  2839. const profile = document.getElementById('pptp-modal-profile')?.value || 'default-encryption';
  2840. const mppe = document.getElementById('pptp-modal-mppe').checked;
  2841. const defRoute = document.getElementById('pptp-modal-defroute').checked;
  2842. const disabled = document.getElementById('pptp-modal-disabled').checked;
  2843. try {
  2844. const res = await fetch(`${API_BASE}/vpn/pptp/clients`, {
  2845. method: 'POST',
  2846. headers: { 'Content-Type': 'application/json' },
  2847. body: JSON.stringify({
  2848. name,
  2849. connect_to: server,
  2850. username: user,
  2851. password: pass,
  2852. profile: profile,
  2853. require_mppe: mppe,
  2854. default_route: defRoute,
  2855. auto_reconnect: true,
  2856. disabled
  2857. })
  2858. });
  2859. if (res.ok) {
  2860. showToast('PPTP Saved', `Client ${name} configuration saved`, 'success');
  2861. closePPTPModal();
  2862. loadPPTP(false);
  2863. fetchData(false);
  2864. }
  2865. } catch (err) {
  2866. showToast('Error', err.message, 'error');
  2867. }
  2868. }
  2869. async function connectPPTPInstance(name) {
  2870. try {
  2871. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  2872. if (res.ok) {
  2873. showToast('Connecting', `Dialing PPTP ${name}...`, 'info');
  2874. setTimeout(() => loadPPTP(false), 2000);
  2875. }
  2876. } catch (err) {
  2877. showToast('Error', err.message, 'error');
  2878. }
  2879. }
  2880. async function disconnectPPTPInstance(name) {
  2881. try {
  2882. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  2883. if (res.ok) {
  2884. showToast('Disconnected', `PPTP tunnel ${name} terminated`, 'info');
  2885. loadPPTP(false);
  2886. }
  2887. } catch (err) {
  2888. showToast('Error', err.message, 'error');
  2889. }
  2890. }
  2891. async function togglePPTPState(name, enable) {
  2892. try {
  2893. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/state`, {
  2894. method: 'POST',
  2895. headers: { 'Content-Type': 'application/json' },
  2896. body: JSON.stringify({ enabled: enable })
  2897. });
  2898. if (res.ok) {
  2899. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  2900. loadPPTP(false);
  2901. }
  2902. } catch (err) {
  2903. showToast('Error', err.message, 'error');
  2904. }
  2905. }
  2906. async function deletePPTPInstance(name) {
  2907. if (!confirm(`Are you sure you want to delete PPTP client ${name}?`)) return;
  2908. try {
  2909. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2910. if (res.ok) {
  2911. showToast('Deleted', `PPTP client ${name} removed`, 'success');
  2912. loadPPTP(false);
  2913. fetchData(false);
  2914. }
  2915. } catch (err) {
  2916. showToast('Error', err.message, 'error');
  2917. }
  2918. }
  2919. // ---------------- Modal & Helper Functions ----------------
  2920. function openVlanModal(defaultParent = '') {
  2921. const select = document.getElementById('vlan-parent');
  2922. select.innerHTML = '';
  2923. const allIfaces = state.interfaces || [];
  2924. const eligible = allIfaces.filter(i => supportsVLAN(i));
  2925. if (eligible.length === 0) {
  2926. const opt = document.createElement('option');
  2927. opt.value = '';
  2928. opt.innerText = 'No VLAN-capable interfaces available';
  2929. select.appendChild(opt);
  2930. } else {
  2931. eligible.forEach(i => {
  2932. const opt = document.createElement('option');
  2933. opt.value = i.name;
  2934. opt.innerText = `${i.name} (${i.role || i.type || 'Ethernet'} - ${i.state})`;
  2935. if (i.name === defaultParent) opt.selected = true;
  2936. select.appendChild(opt);
  2937. });
  2938. }
  2939. document.getElementById('vlan-id').value = '';
  2940. document.getElementById('vlan-name').value = '';
  2941. document.getElementById('vlan-ip').value = '';
  2942. document.getElementById('vlan-desc').value = '';
  2943. populateRoleSelects('LAN');
  2944. autoSuggestVlanName();
  2945. document.getElementById('vlan-modal').classList.remove('hidden');
  2946. }
  2947. function closeVlanModal() {
  2948. document.getElementById('vlan-modal').classList.add('hidden');
  2949. }
  2950. function autoSuggestVlanName() {
  2951. const parent = document.getElementById('vlan-parent').value;
  2952. if (!parent) return;
  2953. const id = document.getElementById('vlan-id').value;
  2954. const nameInput = document.getElementById('vlan-name');
  2955. if (parent && id) nameInput.placeholder = `${parent}.${id}`;
  2956. }
  2957. function setSubnetPreset(cidr) {
  2958. const ipInput = document.getElementById('vlan-ip');
  2959. const id = document.getElementById('vlan-id').value || '10';
  2960. ipInput.value = `192.168.${id}.1${cidr}`;
  2961. }
  2962. async function submitCreateVlan(e) {
  2963. e.preventDefault();
  2964. const btn = document.getElementById('vlan-submit-btn');
  2965. btn.disabled = true;
  2966. btn.innerText = 'Creating...';
  2967. const parent = document.getElementById('vlan-parent').value;
  2968. if (!parent) {
  2969. showToast('Error', 'Please select a valid VLAN-capable parent interface', 'error');
  2970. btn.disabled = false;
  2971. btn.innerText = 'Create VLAN';
  2972. return;
  2973. }
  2974. const id = parseInt(document.getElementById('vlan-id').value, 10);
  2975. const name = document.getElementById('vlan-name').value.trim();
  2976. const ip = document.getElementById('vlan-ip').value.trim();
  2977. const role = document.getElementById('vlan-role').value;
  2978. const desc = document.getElementById('vlan-desc').value.trim();
  2979. try {
  2980. const res = await fetch(`${API_BASE}/vlans`, {
  2981. method: 'POST',
  2982. headers: { 'Content-Type': 'application/json' },
  2983. body: JSON.stringify({
  2984. parent_name: parent,
  2985. vlan_id: id,
  2986. name: name,
  2987. ip_address: ip,
  2988. role: role,
  2989. description: desc,
  2990. mtu: 1500,
  2991. auto_up: true
  2992. })
  2993. });
  2994. const data = await res.json();
  2995. if (res.ok) {
  2996. showToast('VLAN Created', `Created ${data.name} (VLAN ${data.vlan_id})`, 'success');
  2997. state.expandedParents.add(parent);
  2998. closeVlanModal();
  2999. await fetchData(true);
  3000. if (state.activeTab !== 'interfaces') navigate('interfaces');
  3001. } else {
  3002. showToast('Creation Failed', data.message || 'Failed to create VLAN', 'error');
  3003. }
  3004. } catch (err) {
  3005. showToast('Error', err.message, 'error');
  3006. } finally {
  3007. btn.disabled = false;
  3008. btn.innerText = 'Create VLAN';
  3009. }
  3010. }
  3011. async function confirmDeleteVlan(name) {
  3012. if (!confirm(`Delete VLAN interface ${name}?`)) return;
  3013. try {
  3014. const res = await fetch(`${API_BASE}/vlans/${encodeURIComponent(name)}`, { method: 'DELETE' });
  3015. if (res.ok) {
  3016. showToast('VLAN Deleted', `Interface ${name} removed`, 'success');
  3017. closeIfaceModal();
  3018. fetchData(true);
  3019. }
  3020. } catch (err) {
  3021. showToast('Error', err.message, 'error');
  3022. }
  3023. }
  3024. function openIfaceModal(name) {
  3025. const iface = (state.interfaces || []).find(i => i.name === name);
  3026. if (!iface) return;
  3027. state.currentModalIface = iface.name;
  3028. document.getElementById('modal-iface-name').innerText = iface.name;
  3029. document.getElementById('modal-iface-badge').innerText = iface.is_vlan ? `VLAN ${iface.vlan_id}` : iface.type;
  3030. document.getElementById('modal-iface-mtu').value = iface.mtu;
  3031. populateRoleSelects(iface.role || 'LAN');
  3032. document.getElementById('modal-iface-desc').value = iface.description || '';
  3033. const nameInput = document.getElementById('modal-iface-new-name');
  3034. const renameBtn = document.getElementById('modal-btn-rename');
  3035. const renameHelp = document.getElementById('modal-iface-rename-help');
  3036. if (nameInput) {
  3037. nameInput.value = iface.name;
  3038. if (iface.name === 'lo' || iface.type === 'loopback') {
  3039. nameInput.disabled = true;
  3040. if (renameBtn) renameBtn.disabled = true;
  3041. if (renameHelp) renameHelp.innerText = 'Loopback interface cannot be renamed.';
  3042. } else {
  3043. nameInput.disabled = false;
  3044. if (renameBtn) renameBtn.disabled = false;
  3045. if (renameHelp) renameHelp.innerText = 'Device name in Linux (max 15 characters). Automatically preserves operational link state and metadata.';
  3046. }
  3047. }
  3048. const delBtn = document.getElementById('modal-delete-vlan-btn');
  3049. if (iface.is_vlan) {
  3050. delBtn.classList.remove('hidden');
  3051. } else {
  3052. delBtn.classList.add('hidden');
  3053. }
  3054. renderModalIPs(iface);
  3055. document.getElementById('iface-modal').classList.remove('hidden');
  3056. }
  3057. function renderModalIPs(iface) {
  3058. const container = document.getElementById('modal-ip-list');
  3059. container.innerHTML = '';
  3060. const addrs = [...(iface.ipv4 || []), ...(iface.ipv6 || [])];
  3061. if (addrs.length === 0) {
  3062. container.innerHTML = `<span class="text-slate-500 text-xs font-sans">No IP addresses currently bound</span>`;
  3063. return;
  3064. }
  3065. addrs.forEach(addr => {
  3066. const row = document.createElement('div');
  3067. row.className = 'flex items-center justify-between p-2 rounded bg-slate-900 border border-slate-800';
  3068. row.innerHTML = `
  3069. <span class="text-white">${addr}</span>
  3070. <button onclick="removeInterfaceIP('${addr}')" class="text-[11px] text-rose-400 hover:text-rose-300 font-sans">Remove</button>
  3071. `;
  3072. container.appendChild(row);
  3073. });
  3074. }
  3075. function closeIfaceModal() {
  3076. document.getElementById('iface-modal').classList.add('hidden');
  3077. state.currentModalIface = null;
  3078. }
  3079. async function setIfaceState(name, newState) {
  3080. const target = name || state.currentModalIface;
  3081. if (!target) return;
  3082. await toggleInterfaceState(target, newState);
  3083. const updated = (state.interfaces || []).find(i => i.name === target);
  3084. if (updated) openIfaceModal(target);
  3085. }
  3086. async function applyMTU() {
  3087. const mtu = parseInt(document.getElementById('modal-iface-mtu').value, 10);
  3088. try {
  3089. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/mtu`, {
  3090. method: 'POST',
  3091. headers: { 'Content-Type': 'application/json' },
  3092. body: JSON.stringify({ mtu })
  3093. });
  3094. if (res.ok) {
  3095. showToast('MTU Applied', `Set MTU to ${mtu} on ${state.currentModalIface}`, 'success');
  3096. fetchData(false);
  3097. }
  3098. } catch (err) {
  3099. showToast('Error', err.message, 'error');
  3100. }
  3101. }
  3102. async function addInterfaceIP() {
  3103. const ip = document.getElementById('modal-new-ip').value.trim();
  3104. if (!ip) return;
  3105. try {
  3106. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/ip`, {
  3107. method: 'POST',
  3108. headers: { 'Content-Type': 'application/json' },
  3109. body: JSON.stringify({ ip })
  3110. });
  3111. if (res.ok) {
  3112. showToast('IP Added', `Bound ${ip} to ${state.currentModalIface}`, 'success');
  3113. document.getElementById('modal-new-ip').value = '';
  3114. await fetchData(false);
  3115. const iface = (state.interfaces || []).find(i => i.name === state.currentModalIface);
  3116. if (iface) renderModalIPs(iface);
  3117. } else {
  3118. const err = await res.json();
  3119. showToast('Error', err.error || err.message || 'Failed to add IP address', 'error');
  3120. }
  3121. } catch (err) {
  3122. showToast('Error', err.message, 'error');
  3123. }
  3124. }
  3125. async function removeInterfaceIP(ip) {
  3126. if (!confirm(`Remove IP ${ip}?`)) return;
  3127. try {
  3128. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/ip`, {
  3129. method: 'DELETE',
  3130. headers: { 'Content-Type': 'application/json' },
  3131. body: JSON.stringify({ ip })
  3132. });
  3133. if (res.ok) {
  3134. showToast('IP Removed', `Removed ${ip}`, 'success');
  3135. await fetchData(false);
  3136. const iface = (state.interfaces || []).find(i => i.name === state.currentModalIface);
  3137. if (iface) renderModalIPs(iface);
  3138. }
  3139. } catch (err) {
  3140. showToast('Error', err.message, 'error');
  3141. }
  3142. }
  3143. async function renameInterface() {
  3144. const oldName = state.currentModalIface;
  3145. const newNameInput = document.getElementById('modal-iface-new-name');
  3146. const newName = (newNameInput?.value || '').trim();
  3147. if (!oldName) return;
  3148. if (!newName) {
  3149. showToast('Warning', 'Interface name cannot be empty', 'warning');
  3150. return;
  3151. }
  3152. if (newName === oldName) {
  3153. showToast('Info', `Interface name is already "${oldName}"`, 'info');
  3154. return;
  3155. }
  3156. if (newName.length > 15) {
  3157. showToast('Validation Error', 'Interface name cannot exceed 15 characters (Linux IFNAMSIZ)', 'error');
  3158. return;
  3159. }
  3160. if (!/^[a-zA-Z0-9_][a-zA-Z0-9_.-]*$/.test(newName)) {
  3161. showToast('Validation Error', 'Name must contain only alphanumeric characters, underscores, hyphens or dots', 'error');
  3162. return;
  3163. }
  3164. const renameBtn = document.getElementById('modal-btn-rename');
  3165. if (renameBtn) {
  3166. renameBtn.disabled = true;
  3167. renameBtn.innerHTML = `<span class="animate-spin inline-block mr-1">⟳</span> Renaming...`;
  3168. }
  3169. try {
  3170. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(oldName)}/rename`, {
  3171. method: 'POST',
  3172. headers: { 'Content-Type': 'application/json' },
  3173. body: JSON.stringify({ new_name: newName })
  3174. });
  3175. const data = await res.json();
  3176. if (!res.ok) {
  3177. showToast('Rename Failed', data.error || data.message || 'Failed to rename interface', 'error');
  3178. return;
  3179. }
  3180. showToast('Interface Renamed', `Successfully renamed ${oldName} → ${newName}`, 'success');
  3181. state.currentModalIface = newName;
  3182. document.getElementById('modal-iface-name').innerText = newName;
  3183. // Refresh application state
  3184. await fetchData(false);
  3185. const updated = (state.interfaces || []).find(i => i.name === newName);
  3186. if (updated) {
  3187. openIfaceModal(newName);
  3188. } else {
  3189. closeIfaceModal();
  3190. }
  3191. } catch (err) {
  3192. showToast('Error', err.message, 'error');
  3193. } finally {
  3194. if (renameBtn) {
  3195. renameBtn.disabled = false;
  3196. renameBtn.innerHTML = `
  3197. <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z"/></svg>
  3198. <span>Rename</span>
  3199. `;
  3200. }
  3201. }
  3202. }
  3203. async function saveInterfaceMetadata() {
  3204. const oldName = state.currentModalIface;
  3205. const newName = (document.getElementById('modal-iface-new-name')?.value || '').trim();
  3206. const role = document.getElementById('modal-iface-role').value;
  3207. const desc = document.getElementById('modal-iface-desc').value.trim();
  3208. let targetName = oldName;
  3209. // If user changed the name before clicking Save Changes, execute rename first
  3210. if (newName && newName !== oldName && oldName !== 'lo') {
  3211. try {
  3212. const renameRes = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(oldName)}/rename`, {
  3213. method: 'POST',
  3214. headers: { 'Content-Type': 'application/json' },
  3215. body: JSON.stringify({ new_name: newName })
  3216. });
  3217. const data = await renameRes.json();
  3218. if (!renameRes.ok) {
  3219. showToast('Rename Failed', data.error || data.message || 'Could not rename interface', 'error');
  3220. return;
  3221. }
  3222. targetName = newName;
  3223. state.currentModalIface = newName;
  3224. showToast('Renamed', `Interface renamed from ${oldName} to ${newName}`, 'success');
  3225. } catch (err) {
  3226. showToast('Error', err.message, 'error');
  3227. return;
  3228. }
  3229. }
  3230. try {
  3231. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(targetName)}/metadata`, {
  3232. method: 'POST',
  3233. headers: { 'Content-Type': 'application/json' },
  3234. body: JSON.stringify({ role, description: desc })
  3235. });
  3236. if (res.ok) {
  3237. showToast('Saved', 'Interface configuration updated', 'success');
  3238. closeIfaceModal();
  3239. fetchData(false);
  3240. } else {
  3241. const err = await res.json();
  3242. showToast('Error', err.error || err.message || 'Failed to save metadata', 'error');
  3243. }
  3244. } catch (err) {
  3245. showToast('Error', err.message, 'error');
  3246. }
  3247. }
  3248. // ======================== MIKROTIK FIREWALL (/ip firewall) ========================
  3249. state.fwSubTab = 'filter';
  3250. state.routesSubTab = 'routes';
  3251. function renderRuleFlag(disabled, hasComment) {
  3252. let flags = '';
  3253. if (disabled) flags += '<span class="text-rose-400 font-bold" title="Disabled">X</span>';
  3254. if (hasComment) flags += '<span class="text-amber-400 font-bold ml-1" title="Has Comment">C</span>';
  3255. return flags || '<span class="text-slate-600">-</span>';
  3256. }
  3257. function renderActionBadge(action) {
  3258. const act = (action || '').toLowerCase();
  3259. let color = 'bg-slate-800 text-slate-300';
  3260. if (act === 'accept') color = 'bg-emerald-500/20 text-emerald-300 border border-emerald-500/30';
  3261. else if (act === 'drop' || act === 'reject') color = 'bg-rose-500/20 text-rose-300 border border-rose-500/30';
  3262. else if (act === 'masquerade' || act === 'src-nat' || act === 'dst-nat') color = 'bg-amber-500/20 text-amber-300 border border-amber-500/30';
  3263. else if (act.startsWith('mark-')) color = 'bg-purple-500/20 text-purple-300 border border-purple-500/30';
  3264. else if (act === 'log') color = 'bg-cyan-500/20 text-cyan-300 border border-cyan-500/30';
  3265. return `<span class="px-2 py-0.5 rounded text-[10px] font-mono font-semibold ${color}">${action}</span>`;
  3266. }
  3267. function switchFWSubTab(tab) {
  3268. state.fwSubTab = tab;
  3269. const tabs = ['filter', 'nat', 'mangle', 'addrlist', 'geo', 'connections'];
  3270. tabs.forEach(t => {
  3271. const panel = document.getElementById(`fw-subtab-${t}`);
  3272. const btn = document.getElementById(`fw-subtab-btn-${t}`);
  3273. if (panel) {
  3274. if (t === tab) panel.classList.remove('hidden');
  3275. else panel.classList.add('hidden');
  3276. }
  3277. if (btn) {
  3278. if (t === tab) {
  3279. btn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-emerald-500 text-white transition flex items-center gap-2 whitespace-nowrap';
  3280. } else {
  3281. btn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-transparent text-slate-400 hover:text-slate-200 transition flex items-center gap-2 whitespace-nowrap';
  3282. }
  3283. }
  3284. });
  3285. const addBtn = document.getElementById('fw-primary-add-btn');
  3286. if (addBtn) {
  3287. if (tab === 'filter') addBtn.innerHTML = '<span>+ Add Filter Rule</span>';
  3288. else if (tab === 'nat') addBtn.innerHTML = '<span>+ Add NAT Rule</span>';
  3289. else if (tab === 'mangle') addBtn.innerHTML = '<span>+ Add Mangle Rule</span>';
  3290. else if (tab === 'addrlist') addBtn.innerHTML = '<span>+ Add Address List</span>';
  3291. else if (tab === 'geo') addBtn.innerHTML = '<span>⚙️ Schedule Settings</span>';
  3292. else if (tab === 'connections') addBtn.innerHTML = '<span>Refresh Flows</span>';
  3293. }
  3294. if (tab === 'filter') renderFilterRules();
  3295. else if (tab === 'nat') renderNATRules();
  3296. else if (tab === 'mangle') renderMangleRules();
  3297. else if (tab === 'addrlist') renderAddressLists();
  3298. else if (tab === 'geo') loadGeoIP();
  3299. else if (tab === 'connections') loadConnections();
  3300. setTimeout(initTableSorting, 50);
  3301. }
  3302. function openCurrentFWModal() {
  3303. if (state.fwSubTab === 'filter') openAddFilterModal();
  3304. else if (state.fwSubTab === 'nat') openAddNATModal();
  3305. else if (state.fwSubTab === 'mangle') openAddMangleModal();
  3306. else if (state.fwSubTab === 'addrlist') openAddAddrListModal();
  3307. else if (state.fwSubTab === 'geo') openGeoIntervalModal();
  3308. else if (state.fwSubTab === 'connections') loadConnections();
  3309. }
  3310. async function loadFirewall(populateDropdowns = true) {
  3311. try {
  3312. const [summaryRes, filterRes, natRes, mangleRes, addrlistRes, geoStatusRes, geoCountriesRes] = await Promise.all([
  3313. fetch(`${API_BASE}/firewall/summary`),
  3314. fetch(`${API_BASE}/firewall/filter`),
  3315. fetch(`${API_BASE}/firewall/nat`),
  3316. fetch(`${API_BASE}/firewall/mangle`),
  3317. fetch(`${API_BASE}/firewall/address-lists`),
  3318. fetch(`${API_BASE}/firewall/geoip/status`),
  3319. fetch(`${API_BASE}/firewall/geoip/countries`)
  3320. ]);
  3321. if (summaryRes.ok) state.fwSummary = await summaryRes.json();
  3322. if (filterRes.ok) state.filterRules = await filterRes.json();
  3323. if (natRes.ok) state.natRules = await natRes.json();
  3324. if (mangleRes.ok) state.mangleRules = await mangleRes.json();
  3325. if (addrlistRes.ok) state.addressLists = await addrlistRes.json();
  3326. if (geoStatusRes.ok) state.geoStatus = await geoStatusRes.json();
  3327. if (geoCountriesRes.ok) state.geoCountries = await geoCountriesRes.json();
  3328. // Badges
  3329. const bFilter = document.getElementById('fw-badge-filter');
  3330. if (bFilter) bFilter.innerText = (state.filterRules || []).length;
  3331. const bNat = document.getElementById('fw-badge-nat');
  3332. if (bNat) bNat.innerText = (state.natRules || []).length;
  3333. const bMangle = document.getElementById('fw-badge-mangle');
  3334. if (bMangle) bMangle.innerText = (state.mangleRules || []).length;
  3335. const bAddr = document.getElementById('fw-badge-addrlist');
  3336. if (bAddr) bAddr.innerText = (state.addressLists || []).length;
  3337. const bGeo = document.getElementById('fw-badge-geo');
  3338. if (bGeo) bGeo.innerText = state.geoStatus?.enabled_count || 0;
  3339. const sigFilter = (state.filterRules || []).map(r => `${r.id}:${r.chain}:${r.action}:${r.disabled}`).join(';');
  3340. const sigNat = (state.natRules || []).map(r => `${r.id}:${r.chain}:${r.action}:${r.disabled}`).join(';');
  3341. const sigMangle = (state.mangleRules || []).map(r => `${r.id}:${r.chain}:${r.action}:${r.disabled}`).join(';');
  3342. const sigAddr = (state.addressLists || []).map(a => `${a.id}:${a.name}:${a.address}:${a.disabled}`).join(';');
  3343. const tbodyFilter = document.getElementById('filter-table-body');
  3344. if (tbodyFilter) {
  3345. if (populateDropdowns || tbodyFilter.dataset.sig !== sigFilter) {
  3346. tbodyFilter.dataset.sig = sigFilter;
  3347. renderFilterRules();
  3348. } else {
  3349. // In-place live stats update (ZERO flicker)
  3350. (state.filterRules || []).forEach(r => {
  3351. const p = document.getElementById(`filter-pkts-${r.id}`);
  3352. if (p) p.innerText = `${(r.packets || 0).toLocaleString()}p`;
  3353. const b = document.getElementById(`filter-bytes-${r.id}`);
  3354. if (b) b.innerText = formatTraffic(r.bytes || 0).replace('/s', '');
  3355. });
  3356. }
  3357. }
  3358. const tbodyNat = document.getElementById('nat-table-body');
  3359. if (tbodyNat) {
  3360. if (populateDropdowns || tbodyNat.dataset.sig !== sigNat) {
  3361. tbodyNat.dataset.sig = sigNat;
  3362. renderNATRules();
  3363. } else {
  3364. (state.natRules || []).forEach(r => {
  3365. const p = document.getElementById(`nat-pkts-${r.id}`);
  3366. if (p) p.innerText = `${(r.packets || 0).toLocaleString()}p`;
  3367. const b = document.getElementById(`nat-bytes-${r.id}`);
  3368. if (b) b.innerText = formatTraffic(r.bytes || 0).replace('/s', '');
  3369. });
  3370. }
  3371. }
  3372. const tbodyMangle = document.getElementById('mangle-table-body');
  3373. if (tbodyMangle) {
  3374. if (populateDropdowns || tbodyMangle.dataset.sig !== sigMangle) {
  3375. tbodyMangle.dataset.sig = sigMangle;
  3376. renderMangleRules();
  3377. } else {
  3378. (state.mangleRules || []).forEach(r => {
  3379. const p = document.getElementById(`mangle-pkts-${r.id}`);
  3380. if (p) p.innerText = `${(r.packets || 0).toLocaleString()}p`;
  3381. const b = document.getElementById(`mangle-bytes-${r.id}`);
  3382. if (b) b.innerText = formatTraffic(r.bytes || 0).replace('/s', '');
  3383. });
  3384. }
  3385. }
  3386. const tbodyAddr = document.getElementById('addrlist-table-body');
  3387. if (tbodyAddr && (populateDropdowns || tbodyAddr.dataset.sig !== sigAddr)) {
  3388. tbodyAddr.dataset.sig = sigAddr;
  3389. renderAddressLists();
  3390. }
  3391. renderGeoCountries();
  3392. if (state.fwSubTab === 'connections') {
  3393. loadConnections();
  3394. }
  3395. } catch (err) {
  3396. console.error('Failed to load firewall:', err);
  3397. }
  3398. }
  3399. // ----------------- Filter Rules -----------------
  3400. function renderFilterRules() {
  3401. const chainFilter = document.getElementById('filter-filter-chain')?.value || '';
  3402. const tbody = document.getElementById('filter-table-body');
  3403. const empty = document.getElementById('filter-empty');
  3404. if (!tbody) return;
  3405. tbody.innerHTML = '';
  3406. const rules = (state.filterRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  3407. document.getElementById('filter-count-badge').innerText = `${rules.length} Rules`;
  3408. if (rules.length === 0) {
  3409. empty?.classList.remove('hidden');
  3410. return;
  3411. }
  3412. empty?.classList.add('hidden');
  3413. rules.forEach((r, idx) => {
  3414. const tr = document.createElement('tr');
  3415. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  3416. const ports = [r.src_port ? 's:' + r.src_port : '', r.dst_port ? 'd:' + r.dst_port : ''].filter(Boolean).join(' ');
  3417. const ifaces = [r.in_interface ? 'in:' + r.in_interface : '', r.out_interface ? 'out:' + r.out_interface : ''].filter(Boolean).join(' ');
  3418. let actionExtra = '';
  3419. if (r.action === 'reject') {
  3420. actionExtra = `<span class="block text-[10px] text-rose-300 font-mono mt-0.5">(${r.reject_with || 'icmp-net-unreach'})</span>`;
  3421. } else if (r.action === 'jump') {
  3422. actionExtra = `<span class="block text-[10px] text-yellow-300 font-mono mt-0.5">&rarr; ${r.jump_target || '-'}</span>`;
  3423. } else if (r.action.includes('address-list') || r.action.includes('address list')) {
  3424. actionExtra = `<span class="block text-[10px] text-emerald-300 font-mono mt-0.5">&rarr; ${r.address_list || '-'}</span>`;
  3425. } else if (r.action === 'log' && r.log_prefix) {
  3426. actionExtra = `<span class="block text-[10px] text-slate-400 font-mono mt-0.5">${r.log_prefix}</span>`;
  3427. }
  3428. tr.innerHTML = `
  3429. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  3430. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  3431. <td class="py-2.5 px-3 font-bold text-white">${r.chain}</td>
  3432. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  3433. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  3434. <td class="py-2.5 px-3 text-cyan-400 uppercase">${r.protocol || 'all'}</td>
  3435. <td class="py-2.5 px-3 text-amber-400">${ports || '-'}</td>
  3436. <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
  3437. <td class="py-2.5 px-3">${renderActionBadge(r.action)}${actionExtra}</td>
  3438. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  3439. <span class="text-slate-300" id="filter-pkts-${r.id}">${(r.packets || 0).toLocaleString()}p</span> /
  3440. <span class="text-slate-500" id="filter-bytes-${r.id}">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  3441. </td>
  3442. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  3443. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  3444. <button onclick="moveFilterRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  3445. <button onclick="moveFilterRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  3446. <button onclick="toggleFilterRuleState('${r.id}', ${!r.disabled})" class="text-xs ${r.disabled ? 'text-emerald-400' : 'text-slate-400'} hover:underline">${r.disabled ? 'Enable' : 'Disable'}</button>
  3447. <button onclick="openEditFilterModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  3448. <button onclick="deleteFilterRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  3449. </td>
  3450. `;
  3451. tbody.appendChild(tr);
  3452. });
  3453. }
  3454. function formatTarget(addr, list, geo) {
  3455. const parts = [];
  3456. if (addr) parts.push(`<span>${addr}</span>`);
  3457. if (list) {
  3458. const inv = list.startsWith('!') ? '!' : '';
  3459. const clean = list.replace(/^!/, '');
  3460. parts.push(`<span class="px-1.5 py-0.5 rounded text-[10px] bg-amber-950/80 border border-amber-800/40 text-amber-300 font-mono" title="Address List: ${list}">${inv}list:${clean}</span>`);
  3461. }
  3462. if (geo) {
  3463. const inv = geo.startsWith('!') ? '!' : '';
  3464. const clean = geo.replace(/^!/, '').replace(/^geo:/, '');
  3465. parts.push(`<span class="px-1.5 py-0.5 rounded text-[10px] bg-emerald-950/80 border border-emerald-800/40 text-emerald-300 font-mono" title="Geo-Location: ${geo}">🌍 ${inv}${clean}</span>`);
  3466. }
  3467. if (parts.length === 0) return '<span class="text-slate-600">0.0.0.0/0</span>';
  3468. return parts.join(' ');
  3469. }
  3470. function populateInterfaceSelect(selectId, currentVal = '') {
  3471. const sel = document.getElementById(selectId);
  3472. if (!sel) return;
  3473. sel.innerHTML = '<option value="">(Any Interface)</option>';
  3474. (state.interfaces || []).forEach(i => {
  3475. const opt = document.createElement('option');
  3476. opt.value = i.name;
  3477. opt.innerText = `${i.name} (${i.role || i.type})`;
  3478. if (i.name === currentVal) opt.selected = true;
  3479. sel.appendChild(opt);
  3480. });
  3481. }
  3482. function populateAddressListSelect(selectId, currentVal = '') {
  3483. const sel = document.getElementById(selectId);
  3484. if (!sel) return;
  3485. sel.innerHTML = '<option value="">(None)</option>';
  3486. const cleanVal = (currentVal || '').replace(/^!/, '');
  3487. const customNames = Array.from(new Set((state.addressLists || []).map(a => a.name))).sort();
  3488. customNames.forEach(name => {
  3489. const count = (state.addressLists || []).filter(a => a.name === name).length;
  3490. const opt = document.createElement('option');
  3491. opt.value = name;
  3492. opt.innerText = `${name} (${count} entries)`;
  3493. if (name === cleanVal) opt.selected = true;
  3494. sel.appendChild(opt);
  3495. });
  3496. if (cleanVal && !sel.querySelector(`option[value="${cleanVal}"]`)) {
  3497. const opt = document.createElement('option');
  3498. opt.value = cleanVal;
  3499. opt.innerText = cleanVal;
  3500. opt.selected = true;
  3501. sel.appendChild(opt);
  3502. }
  3503. populateCommonAddrListDatalist();
  3504. }
  3505. function populateCommonAddrListDatalist() {
  3506. const dl = document.getElementById('fw-addrlist-datalist');
  3507. if (!dl) return;
  3508. dl.innerHTML = '';
  3509. const names = Array.from(new Set((state.addressLists || []).map(a => a.name).filter(Boolean))).sort();
  3510. names.forEach(name => {
  3511. const opt = document.createElement('option');
  3512. opt.value = name;
  3513. dl.appendChild(opt);
  3514. });
  3515. }
  3516. function populateGeoIPSelect(selectId, currentVal = '') {
  3517. const sel = document.getElementById(selectId);
  3518. if (!sel) return;
  3519. sel.innerHTML = '<option value="">(None)</option>';
  3520. const cleanVal = (currentVal || '').replace(/^!/, '').replace(/^geo:/, '').toUpperCase();
  3521. // Presets optgroup
  3522. const grpPresets = document.createElement('optgroup');
  3523. grpPresets.label = '⚡ Regional Presets';
  3524. const presets = [
  3525. { code: 'EU', label: '🇪🇺 European Union (EU - 27 countries)' },
  3526. { code: 'BALKANS', label: '🏛️ Balkans (GR, CY, BG, RO, AL, etc.)' },
  3527. { code: 'BLOCKLIST', label: '🛡️ High-Risk Blocklist (CN, RU, IR, KP, BY)' }
  3528. ];
  3529. presets.forEach(p => {
  3530. const opt = document.createElement('option');
  3531. opt.value = p.code;
  3532. opt.innerText = p.label;
  3533. if (p.code === cleanVal) opt.selected = true;
  3534. grpPresets.appendChild(opt);
  3535. });
  3536. sel.appendChild(grpPresets);
  3537. // All Countries optgroup
  3538. const grpCountries = document.createElement('optgroup');
  3539. grpCountries.label = '🌍 All Countries';
  3540. const countries = (state.geoCountries || []).slice().sort((a, b) => a.name.localeCompare(b.name));
  3541. countries.forEach(c => {
  3542. const opt = document.createElement('option');
  3543. opt.value = c.code;
  3544. const subnetsInfo = c.subnet_count ? ` [${c.subnet_count.toLocaleString()} subnets]` : '';
  3545. opt.innerText = `${c.name} (${c.code})${subnetsInfo}`;
  3546. if (c.code === cleanVal) opt.selected = true;
  3547. grpCountries.appendChild(opt);
  3548. });
  3549. sel.appendChild(grpCountries);
  3550. }
  3551. // ==================== FIREWALL FILTER MODAL (ROUTEROS WEBFIG / WINBOX V4) ====================
  3552. function switchFwRuleTab(tab) {
  3553. state.activeFwRuleTab = tab;
  3554. document.querySelectorAll('.fw-rule-tab-btn').forEach(btn => {
  3555. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  3556. btn.classList.add('text-slate-400', 'border-transparent');
  3557. });
  3558. const activeBtn = document.getElementById(`fw-tab-btn-${tab}`);
  3559. if (activeBtn) {
  3560. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  3561. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  3562. }
  3563. document.querySelectorAll('.fw-rule-pane').forEach(p => p.classList.add('hidden'));
  3564. const activePane = document.getElementById(`fw-pane-${tab}`);
  3565. if (activePane) activePane.classList.remove('hidden');
  3566. if (tab === 'statistics') {
  3567. startFwStatPolling();
  3568. } else {
  3569. stopFwStatPolling();
  3570. }
  3571. }
  3572. function toggleFwField(fieldKey, expand) {
  3573. const plusBtn = document.getElementById(`fw-plus-${fieldKey}`);
  3574. const fieldBox = document.getElementById(`fw-field-${fieldKey}`);
  3575. if (!plusBtn || !fieldBox) return;
  3576. if (expand) {
  3577. plusBtn.classList.add('hidden');
  3578. fieldBox.classList.remove('hidden');
  3579. const valInput = document.getElementById(`fw-val-${fieldKey}`);
  3580. if (valInput) valInput.focus();
  3581. } else {
  3582. fieldBox.classList.add('hidden');
  3583. plusBtn.classList.remove('hidden');
  3584. const valInput = document.getElementById(`fw-val-${fieldKey}`);
  3585. if (valInput) {
  3586. if (valInput.tagName === 'SELECT') {
  3587. valInput.selectedIndex = 0;
  3588. } else {
  3589. valInput.value = '';
  3590. }
  3591. }
  3592. const invInput = document.getElementById(`fw-inv-${fieldKey}`);
  3593. if (invInput) invInput.checked = false;
  3594. if (fieldKey === 'cs') {
  3595. ['filter-modal-cs-established', 'filter-modal-cs-related', 'filter-modal-cs-new', 'filter-modal-cs-invalid', 'filter-modal-cs-untracked'].forEach(id => {
  3596. const el = document.getElementById(id);
  3597. if (el) el.checked = false;
  3598. });
  3599. }
  3600. if (fieldKey === 'natstate') {
  3601. ['filter-modal-nat-srcnat', 'filter-modal-nat-dstnat'].forEach(id => {
  3602. const el = document.getElementById(id);
  3603. if (el) el.checked = false;
  3604. });
  3605. }
  3606. if (fieldKey === 'days') {
  3607. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  3608. const el = document.getElementById(`fw-day-${d}`);
  3609. if (el) el.checked = true;
  3610. });
  3611. }
  3612. }
  3613. }
  3614. function setFwFieldVal(fieldKey, value, hasInvert = false) {
  3615. if (value !== undefined && value !== null && value !== '' && value !== 'all') {
  3616. toggleFwField(fieldKey, true);
  3617. let strVal = String(value);
  3618. if (hasInvert) {
  3619. const inv = strVal.startsWith('!');
  3620. if (inv) strVal = strVal.slice(1);
  3621. const invEl = document.getElementById(`fw-inv-${fieldKey}`);
  3622. if (invEl) invEl.checked = inv;
  3623. }
  3624. const valEl = document.getElementById(`fw-val-${fieldKey}`);
  3625. if (valEl) valEl.value = strVal;
  3626. } else {
  3627. toggleFwField(fieldKey, false);
  3628. }
  3629. }
  3630. function getFwFieldVal(fieldKey, hasInvert = false) {
  3631. const fieldBox = document.getElementById(`fw-field-${fieldKey}`);
  3632. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  3633. const valEl = document.getElementById(`fw-val-${fieldKey}`);
  3634. let v = valEl ? valEl.value.trim() : '';
  3635. if (!v) return '';
  3636. if (hasInvert) {
  3637. const invEl = document.getElementById(`fw-inv-${fieldKey}`);
  3638. if (invEl && invEl.checked) {
  3639. v = '!' + v.replace(/^!/, '');
  3640. }
  3641. }
  3642. return v;
  3643. }
  3644. function toggleMaximizeFilterModal() {
  3645. const win = document.getElementById('filter-modal-window');
  3646. if (!win) return;
  3647. if (win.classList.contains('max-w-[720px]')) {
  3648. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  3649. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  3650. } else {
  3651. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  3652. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  3653. }
  3654. }
  3655. function openAddFilterModal() {
  3656. switchFwRuleTab('general');
  3657. const badge = document.getElementById('fw-modal-badge');
  3658. if (badge) badge.innerText = 'New...';
  3659. document.getElementById('filter-modal-id').value = '';
  3660. document.getElementById('filter-modal-enabled').checked = true;
  3661. document.getElementById('filter-modal-comment').value = '';
  3662. document.getElementById('filter-modal-chain').value = 'forward';
  3663. document.getElementById('filter-modal-action').value = 'accept';
  3664. document.getElementById('filter-modal-log').checked = false;
  3665. populateInterfaceSelect('fw-val-iniface');
  3666. populateInterfaceSelect('fw-val-outiface');
  3667. populateAddressListSelect('fw-val-srclist');
  3668. populateAddressListSelect('fw-val-dstlist');
  3669. populateGeoIPSelect('fw-val-srcgeo');
  3670. populateGeoIPSelect('fw-val-dstgeo');
  3671. const allFieldKeys = [
  3672. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  3673. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  3674. 'routingmark', 'conntype', 'cs', 'natstate',
  3675. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  3676. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  3677. 'ipsec', 'tlshost', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  3678. 'pktsize', 'random', 'tcpflags', 'icmpoptions', 'ipv4options', 'ttl',
  3679. 'time', 'days', 'limit', 'dstlimit', 'psd', 'logprefix'
  3680. ];
  3681. allFieldKeys.forEach(k => toggleFwField(k, false));
  3682. resetCurrentRuleCounters();
  3683. toggleFilterActionFields();
  3684. document.getElementById('filter-modal').classList.remove('hidden');
  3685. }
  3686. function openEditFilterModal(id) {
  3687. const r = (state.filterRules || []).find(rule => rule.id === id);
  3688. if (!r) return;
  3689. switchFwRuleTab('general');
  3690. const badge = document.getElementById('fw-modal-badge');
  3691. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  3692. document.getElementById('filter-modal-id').value = r.id;
  3693. document.getElementById('filter-modal-enabled').checked = !r.disabled;
  3694. document.getElementById('filter-modal-comment').value = r.comment || '';
  3695. document.getElementById('filter-modal-chain').value = r.chain || 'forward';
  3696. document.getElementById('filter-modal-action').value = r.action || 'accept';
  3697. document.getElementById('filter-modal-log').checked = !!r.log;
  3698. populateInterfaceSelect('fw-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  3699. populateInterfaceSelect('fw-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  3700. populateAddressListSelect('fw-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  3701. populateAddressListSelect('fw-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  3702. populateGeoIPSelect('fw-val-srcgeo', r.src_geoip || '');
  3703. populateGeoIPSelect('fw-val-dstgeo', r.dst_geoip || '');
  3704. setFwFieldVal('src', r.src_address, true);
  3705. setFwFieldVal('dst', r.dst_address, true);
  3706. setFwFieldVal('srclist', r.src_address_list, true);
  3707. setFwFieldVal('dstlist', r.dst_address_list, true);
  3708. setFwFieldVal('srcgeo', r.src_geoip, true);
  3709. setFwFieldVal('dstgeo', r.dst_geoip, true);
  3710. if (r.protocol && r.protocol !== 'all') {
  3711. setFwFieldVal('proto', r.protocol, true);
  3712. } else {
  3713. toggleFwField('proto', false);
  3714. }
  3715. setFwFieldVal('sport', r.src_port, true);
  3716. setFwFieldVal('dport', r.dst_port, true);
  3717. setFwFieldVal('anyport', r.any_port, true);
  3718. setFwFieldVal('iniface', r.in_interface, true);
  3719. setFwFieldVal('outiface', r.out_interface, true);
  3720. setFwFieldVal('inifacelist', r.in_interface_list, true);
  3721. setFwFieldVal('outifacelist', r.out_interface_list, true);
  3722. setFwFieldVal('pktmark', r.packet_mark, true);
  3723. setFwFieldVal('connmark', r.connection_mark, true);
  3724. setFwFieldVal('routingmark', r.routing_mark, true);
  3725. setFwFieldVal('conntype', r.connection_type, false);
  3726. const states = r.connection_state || [];
  3727. if (states.length > 0) {
  3728. toggleFwField('cs', true);
  3729. document.getElementById('filter-modal-cs-established').checked = states.includes('established');
  3730. document.getElementById('filter-modal-cs-related').checked = states.includes('related');
  3731. document.getElementById('filter-modal-cs-new').checked = states.includes('new');
  3732. document.getElementById('filter-modal-cs-invalid').checked = states.includes('invalid');
  3733. document.getElementById('filter-modal-cs-untracked').checked = states.includes('untracked');
  3734. } else {
  3735. toggleFwField('cs', false);
  3736. }
  3737. const natStates = r.connection_nat_state || [];
  3738. if (natStates.length > 0) {
  3739. toggleFwField('natstate', true);
  3740. document.getElementById('filter-modal-nat-srcnat').checked = natStates.includes('srcnat');
  3741. document.getElementById('filter-modal-nat-dstnat').checked = natStates.includes('dstnat');
  3742. } else {
  3743. toggleFwField('natstate', false);
  3744. }
  3745. // Advanced tab fields
  3746. setFwFieldVal('layer7', r.layer7_protocol, false);
  3747. setFwFieldVal('content', r.content, false);
  3748. setFwFieldVal('connbytes', r.connection_bytes, false);
  3749. setFwFieldVal('connrate', r.connection_rate, false);
  3750. setFwFieldVal('pcc', r.pcc, false);
  3751. setFwFieldVal('srcmac', r.src_mac_address, true);
  3752. setFwFieldVal('outbridgeport', r.out_bridge_port, false);
  3753. setFwFieldVal('inbridgeport', r.in_bridge_port, false);
  3754. setFwFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  3755. setFwFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  3756. setFwFieldVal('ipsec', r.ipsec_policy, false);
  3757. setFwFieldVal('tlshost', r.tls_host, false);
  3758. setFwFieldVal('ingresspriority', r.ingress_priority, false);
  3759. setFwFieldVal('priority', r.priority, false);
  3760. setFwFieldVal('dscp', r.dscp, false);
  3761. setFwFieldVal('tcpmss', r.tcp_mss, false);
  3762. if (r.tos) {
  3763. const tosEl = document.getElementById('fw-val-tos');
  3764. if (tosEl) tosEl.value = r.tos;
  3765. }
  3766. setFwFieldVal('pktsize', r.packet_size, false);
  3767. setFwFieldVal('random', r.random, false);
  3768. setFwFieldVal('tcpflags', r.tcp_flags, false);
  3769. setFwFieldVal('icmpoptions', r.icmp_options, false);
  3770. setFwFieldVal('ipv4options', r.ipv4_options, false);
  3771. setFwFieldVal('ttl', r.ttl, false);
  3772. // Extra tab fields
  3773. setFwFieldVal('time', r.time, false);
  3774. if (r.days) {
  3775. toggleFwField('days', true);
  3776. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  3777. const chk = document.getElementById(`fw-day-${d}`);
  3778. if (chk) chk.checked = r.days.includes(d);
  3779. });
  3780. } else {
  3781. toggleFwField('days', false);
  3782. }
  3783. setFwFieldVal('limit', r.limit, false);
  3784. setFwFieldVal('dstlimit', r.dst_limit, false);
  3785. setFwFieldVal('psd', r.psd, false);
  3786. // Action fields
  3787. if (r.reject_with) {
  3788. const rwEl = document.getElementById('filter-modal-rejectwith');
  3789. if (rwEl) rwEl.value = r.reject_with;
  3790. }
  3791. if (r.jump_target) {
  3792. const jtEl = document.getElementById('filter-modal-jumptarget');
  3793. if (jtEl) jtEl.value = r.jump_target;
  3794. }
  3795. if (r.address_list) {
  3796. const alEl = document.getElementById('filter-modal-action-addrlist');
  3797. if (alEl) alEl.value = r.address_list;
  3798. }
  3799. if (r.address_list_timeout) {
  3800. const toEl = document.getElementById('filter-modal-action-timeout');
  3801. if (toEl) toEl.value = r.address_list_timeout;
  3802. }
  3803. setFwFieldVal('logprefix', r.log_prefix, false);
  3804. // Statistics
  3805. const bEl = document.getElementById('fw-stat-bytes');
  3806. const pEl = document.getElementById('fw-stat-packets');
  3807. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  3808. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  3809. state.fwLastBytes = r.bytes || 0;
  3810. state.fwLastPackets = r.packets || 0;
  3811. state.fwLastTimestamp = Date.now();
  3812. state.fwStatRateHistory = new Array(30).fill(0);
  3813. state.fwStatPktHistory = new Array(30).fill(0);
  3814. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  3815. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  3816. toggleFilterActionFields();
  3817. document.getElementById('filter-modal').classList.remove('hidden');
  3818. }
  3819. function closeFilterModal() {
  3820. stopFwStatPolling();
  3821. document.getElementById('filter-modal').classList.add('hidden');
  3822. }
  3823. function toggleFilterActionFields() {
  3824. const act = document.getElementById('filter-modal-action')?.value || 'accept';
  3825. const rejectBox = document.getElementById('filter-action-reject-box');
  3826. const jumpBox = document.getElementById('filter-action-jump-box');
  3827. const addrBox = document.getElementById('filter-action-addrlist-box');
  3828. if (rejectBox) {
  3829. if (act === 'reject') rejectBox.classList.remove('hidden');
  3830. else rejectBox.classList.add('hidden');
  3831. }
  3832. if (jumpBox) {
  3833. if (act === 'jump') jumpBox.classList.remove('hidden');
  3834. else jumpBox.classList.add('hidden');
  3835. }
  3836. if (addrBox) {
  3837. if (act === 'add-dst-to-address-list' || act === 'add-src-to-address-list' || act.includes('address-list') || act.includes('address list')) {
  3838. addrBox.classList.remove('hidden');
  3839. } else {
  3840. addrBox.classList.add('hidden');
  3841. }
  3842. }
  3843. if (act === 'log') {
  3844. const logEl = document.getElementById('filter-modal-log');
  3845. if (logEl) logEl.checked = true;
  3846. toggleFwField('logprefix', true);
  3847. }
  3848. }
  3849. function toggleFwLogPrefix() {
  3850. const isLog = document.getElementById('filter-modal-log')?.checked;
  3851. toggleFwField('logprefix', !!isLog);
  3852. }
  3853. function copyFilterRule() {
  3854. document.getElementById('filter-modal-id').value = '';
  3855. const badge = document.getElementById('fw-modal-badge');
  3856. if (badge) badge.innerText = 'New...';
  3857. showToast('Rule Cloned', 'Ready to save as a new rule copy', 'info');
  3858. }
  3859. function resetCurrentRuleCounters() {
  3860. state.fwStatRateHistory = new Array(30).fill(0);
  3861. state.fwStatPktHistory = new Array(30).fill(0);
  3862. state.fwLastBytes = 0;
  3863. state.fwLastPackets = 0;
  3864. state.fwLastTimestamp = Date.now();
  3865. const bEl = document.getElementById('fw-stat-bytes');
  3866. const pEl = document.getElementById('fw-stat-packets');
  3867. const rEl = document.getElementById('fw-stat-rate');
  3868. const prEl = document.getElementById('fw-stat-pktrate');
  3869. if (bEl) bEl.value = '0 B';
  3870. if (pEl) pEl.value = '0';
  3871. if (rEl) rEl.value = '0 bps';
  3872. if (prEl) prEl.value = '0 p/s';
  3873. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  3874. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  3875. showToast('Counters Reset', 'Rule counter display reset to 0', 'info');
  3876. }
  3877. async function resetAllFwCounters() {
  3878. try {
  3879. const res = await fetch(`${API_BASE}/firewall/reset-counters`, { method: 'POST' });
  3880. if (res.ok) {
  3881. resetCurrentRuleCounters();
  3882. showToast('All Counters Reset', 'All firewall counters zeroed', 'success');
  3883. loadFirewall(false);
  3884. }
  3885. } catch (err) {
  3886. showToast('Error', err.message, 'error');
  3887. }
  3888. }
  3889. async function applyFilterRule(closeAfter = false) {
  3890. const id = document.getElementById('filter-modal-id').value;
  3891. const chain = document.getElementById('filter-modal-chain').value;
  3892. const action = document.getElementById('filter-modal-action').value;
  3893. const comment = document.getElementById('filter-modal-comment').value.trim();
  3894. const enabled = document.getElementById('filter-modal-enabled').checked;
  3895. const src = getFwFieldVal('src', true);
  3896. const dst = getFwFieldVal('dst', true);
  3897. const srclist = getFwFieldVal('srclist', true);
  3898. const dstlist = getFwFieldVal('dstlist', true);
  3899. const srcgeo = getFwFieldVal('srcgeo', true);
  3900. const dstgeo = getFwFieldVal('dstgeo', true);
  3901. const proto = getFwFieldVal('proto', true);
  3902. const sport = getFwFieldVal('sport', true);
  3903. const dport = getFwFieldVal('dport', true);
  3904. const anyport = getFwFieldVal('anyport', true);
  3905. const iniface = getFwFieldVal('iniface', true);
  3906. const outiface = getFwFieldVal('outiface', true);
  3907. const inifacelist = getFwFieldVal('inifacelist', true);
  3908. const outifacelist = getFwFieldVal('outifacelist', true);
  3909. const pktmark = getFwFieldVal('pktmark', true);
  3910. const connmark = getFwFieldVal('connmark', true);
  3911. const routingmark = getFwFieldVal('routingmark', true);
  3912. const conntype = getFwFieldVal('conntype', false);
  3913. const states = [];
  3914. const csBox = document.getElementById('fw-field-cs');
  3915. if (csBox && !csBox.classList.contains('hidden')) {
  3916. if (document.getElementById('filter-modal-cs-established')?.checked) states.push('established');
  3917. if (document.getElementById('filter-modal-cs-related')?.checked) states.push('related');
  3918. if (document.getElementById('filter-modal-cs-new')?.checked) states.push('new');
  3919. if (document.getElementById('filter-modal-cs-invalid')?.checked) states.push('invalid');
  3920. if (document.getElementById('filter-modal-cs-untracked')?.checked) states.push('untracked');
  3921. }
  3922. const natStates = [];
  3923. const natBox = document.getElementById('fw-field-natstate');
  3924. if (natBox && !natBox.classList.contains('hidden')) {
  3925. if (document.getElementById('filter-modal-nat-srcnat')?.checked) natStates.push('srcnat');
  3926. if (document.getElementById('filter-modal-nat-dstnat')?.checked) natStates.push('dstnat');
  3927. }
  3928. const payload = {
  3929. id,
  3930. chain,
  3931. action,
  3932. protocol: proto || 'all',
  3933. src_address: src,
  3934. dst_address: dst,
  3935. src_port: sport,
  3936. dst_port: dport,
  3937. any_port: anyport,
  3938. in_interface: iniface,
  3939. out_interface: outiface,
  3940. in_interface_list: inifacelist,
  3941. out_interface_list: outifacelist,
  3942. packet_mark: pktmark,
  3943. connection_mark: connmark,
  3944. routing_mark: routingmark,
  3945. connection_type: conntype,
  3946. connection_state: states,
  3947. connection_nat_state: natStates,
  3948. src_address_list: srclist,
  3949. dst_address_list: dstlist,
  3950. src_geoip: srcgeo,
  3951. dst_geoip: dstgeo,
  3952. comment,
  3953. disabled: !enabled,
  3954. // Advanced tab
  3955. layer7_protocol: getFwFieldVal('layer7', false),
  3956. content: getFwFieldVal('content', false),
  3957. connection_bytes: getFwFieldVal('connbytes', false),
  3958. connection_rate: getFwFieldVal('connrate', false),
  3959. pcc: getFwFieldVal('pcc', false),
  3960. src_mac_address: getFwFieldVal('srcmac', true),
  3961. out_bridge_port: getFwFieldVal('outbridgeport', false),
  3962. in_bridge_port: getFwFieldVal('inbridgeport', false),
  3963. in_bridge_port_list: getFwFieldVal('inbridgeportlist', false),
  3964. out_bridge_port_list: getFwFieldVal('outbridgeportlist', false),
  3965. ipsec_policy: getFwFieldVal('ipsec', false),
  3966. tls_host: getFwFieldVal('tlshost', false),
  3967. ingress_priority: getFwFieldVal('ingresspriority', false),
  3968. priority: getFwFieldVal('priority', false),
  3969. dscp: getFwFieldVal('dscp', false),
  3970. tcp_mss: getFwFieldVal('tcpmss', false),
  3971. tos: document.getElementById('fw-val-tos')?.value || '',
  3972. packet_size: getFwFieldVal('pktsize', false),
  3973. random: getFwFieldVal('random', false),
  3974. tcp_flags: getFwFieldVal('tcpflags', false),
  3975. icmp_options: getFwFieldVal('icmpoptions', false),
  3976. ipv4_options: getFwFieldVal('ipv4options', false),
  3977. ttl: getFwFieldVal('ttl', false),
  3978. // Extra tab
  3979. time: getFwFieldVal('time', false),
  3980. limit: getFwFieldVal('limit', false),
  3981. dst_limit: getFwFieldVal('dstlimit', false),
  3982. psd: getFwFieldVal('psd', false),
  3983. // Action tab
  3984. reject_with: action === 'reject' ? (document.getElementById('filter-modal-rejectwith')?.value || '') : '',
  3985. jump_target: action === 'jump' ? (document.getElementById('filter-modal-jumptarget')?.value || '') : '',
  3986. address_list: action.startsWith('add-') ? (document.getElementById('filter-modal-action-addrlist')?.value || '') : '',
  3987. address_list_timeout: action.startsWith('add-') ? (document.getElementById('filter-modal-action-timeout')?.value || '') : '',
  3988. log: document.getElementById('filter-modal-log')?.checked || false,
  3989. log_prefix: getFwFieldVal('logprefix', false)
  3990. };
  3991. try {
  3992. const res = await fetch(`${API_BASE}/firewall/filter`, {
  3993. method: 'POST',
  3994. headers: { 'Content-Type': 'application/json' },
  3995. body: JSON.stringify(payload)
  3996. });
  3997. if (res.ok) {
  3998. const data = await res.json();
  3999. showToast('Filter Rule Saved', 'Rule applied successfully to firewall', 'success');
  4000. loadFirewall(false);
  4001. if (closeAfter) {
  4002. closeFilterModal();
  4003. } else {
  4004. if (data.id) {
  4005. document.getElementById('filter-modal-id').value = data.id;
  4006. const badge = document.getElementById('fw-modal-badge');
  4007. if (badge) badge.innerText = `#${data.id}`;
  4008. }
  4009. }
  4010. } else {
  4011. const err = await res.json();
  4012. showToast('Error', err.message || 'Failed to save rule', 'error');
  4013. }
  4014. } catch (err) {
  4015. showToast('Error', err.message, 'error');
  4016. }
  4017. }
  4018. function submitSaveFilterRule(e) {
  4019. if (e && e.preventDefault) e.preventDefault();
  4020. return applyFilterRule(true);
  4021. }
  4022. function startFwStatPolling() {
  4023. stopFwStatPolling();
  4024. pollRuleStats();
  4025. state.fwStatInterval = setInterval(pollRuleStats, 1000);
  4026. }
  4027. function stopFwStatPolling() {
  4028. if (state.fwStatInterval) {
  4029. clearInterval(state.fwStatInterval);
  4030. state.fwStatInterval = null;
  4031. }
  4032. }
  4033. async function pollRuleStats() {
  4034. const id = document.getElementById('filter-modal-id')?.value;
  4035. if (!id) {
  4036. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory || new Array(30).fill(0), 'bps', 'fw-stat-legend-rate');
  4037. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory || new Array(30).fill(0), 'p/s', 'fw-stat-legend-pktrate');
  4038. return;
  4039. }
  4040. try {
  4041. const res = await fetch(`${API_BASE}/firewall/filter`);
  4042. if (!res.ok) return;
  4043. const rules = await res.json();
  4044. const r = rules.find(x => x.id === id);
  4045. if (!r) return;
  4046. const now = Date.now();
  4047. const dt = Math.max(0.2, (now - (state.fwLastTimestamp || now)) / 1000);
  4048. state.fwLastTimestamp = now;
  4049. const curBytes = r.bytes || 0;
  4050. const curPackets = r.packets || 0;
  4051. const deltaBytes = Math.max(0, curBytes - (state.fwLastBytes || curBytes));
  4052. const deltaPkts = Math.max(0, curPackets - (state.fwLastPackets || curPackets));
  4053. state.fwLastBytes = curBytes;
  4054. state.fwLastPackets = curPackets;
  4055. const rateBps = Math.round((deltaBytes * 8) / dt);
  4056. const ratePkt = Math.round(deltaPkts / dt);
  4057. if (!state.fwStatRateHistory) state.fwStatRateHistory = new Array(30).fill(0);
  4058. if (!state.fwStatPktHistory) state.fwStatPktHistory = new Array(30).fill(0);
  4059. state.fwStatRateHistory.push(rateBps);
  4060. if (state.fwStatRateHistory.length > 30) state.fwStatRateHistory.shift();
  4061. state.fwStatPktHistory.push(ratePkt);
  4062. if (state.fwStatPktHistory.length > 30) state.fwStatPktHistory.shift();
  4063. const bEl = document.getElementById('fw-stat-bytes');
  4064. const pEl = document.getElementById('fw-stat-packets');
  4065. const rEl = document.getElementById('fw-stat-rate');
  4066. const prEl = document.getElementById('fw-stat-pktrate');
  4067. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  4068. if (pEl) pEl.value = curPackets.toLocaleString();
  4069. if (rEl) rEl.value = formatBps(rateBps);
  4070. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  4071. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  4072. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  4073. } catch (e) {
  4074. console.error('Error polling rule stats', e);
  4075. }
  4076. }
  4077. function formatBps(bps) {
  4078. if (bps >= 1000000000) return (bps / 1000000000).toFixed(1) + ' Gbps';
  4079. if (bps >= 1000000) return (bps / 1000000).toFixed(1) + ' Mbps';
  4080. if (bps >= 1000) return (bps / 1000).toFixed(1) + ' kbps';
  4081. return bps + ' bps';
  4082. }
  4083. function renderFwSparkline(svgId, dataArray, unit, legendId) {
  4084. const svg = document.getElementById(svgId);
  4085. if (!svg) return;
  4086. const w = 500;
  4087. const h = 100;
  4088. const paddingRight = 45;
  4089. const graphWidth = w - paddingRight;
  4090. const maxVal = Math.max(5, ...dataArray);
  4091. const currentVal = dataArray[dataArray.length - 1] || 0;
  4092. const leg = document.getElementById(legendId);
  4093. if (leg) {
  4094. leg.innerText = unit === 'bps' ? formatBps(currentVal) : `${currentVal.toLocaleString()} p/s`;
  4095. }
  4096. let gridLines = '';
  4097. for (let i = 0; i <= 5; i++) {
  4098. const y = 8 + (i * (h - 18) / 5);
  4099. const valAtLevel = Math.round(maxVal * (5 - i) / 5);
  4100. const label = unit === 'bps' ? formatBps(valAtLevel) : `${valAtLevel} p/s`;
  4101. gridLines += `
  4102. <line x1="0" y1="${y.toFixed(1)}" x2="${graphWidth}" y2="${y.toFixed(1)}" stroke="#1e2c3e" stroke-width="1" />
  4103. <text x="${w - 2}" y="${(y + 3).toFixed(1)}" fill="#64748b" font-size="9" font-family="monospace" text-anchor="end">${label}</text>
  4104. `;
  4105. }
  4106. const step = graphWidth / (dataArray.length - 1);
  4107. const points = dataArray.map((val, idx) => {
  4108. const x = idx * step;
  4109. const y = (h - 10) - (val / maxVal) * (h - 20);
  4110. return `${x.toFixed(1)},${y.toFixed(1)}`;
  4111. });
  4112. const polylineStr = points.join(' ');
  4113. const areaPath = `M 0,${h - 10} L ${polylineStr} L ${graphWidth},${h - 10} Z`;
  4114. svg.innerHTML = `
  4115. ${gridLines}
  4116. <path d="${areaPath}" fill="rgba(14, 165, 233, 0.12)" />
  4117. <polyline fill="none" stroke="#38bdf8" stroke-width="1.8" stroke-linejoin="round" points="${polylineStr}" />
  4118. <circle cx="${graphWidth}" cy="${points[points.length - 1].split(',')[1]}" r="3" fill="#38bdf8" />
  4119. `;
  4120. }
  4121. async function moveFilterRule(id, dir) {
  4122. try {
  4123. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/move`, {
  4124. method: 'POST',
  4125. headers: { 'Content-Type': 'application/json' },
  4126. body: JSON.stringify({ direction: dir })
  4127. });
  4128. if (res.ok) loadFirewall(false);
  4129. } catch (err) {
  4130. showToast('Error', err.message, 'error');
  4131. }
  4132. }
  4133. async function toggleFilterRuleState(id, disabled) {
  4134. try {
  4135. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/state`, {
  4136. method: 'POST',
  4137. headers: { 'Content-Type': 'application/json' },
  4138. body: JSON.stringify({ disabled })
  4139. });
  4140. if (res.ok) loadFirewall(false);
  4141. } catch (err) {
  4142. showToast('Error', err.message, 'error');
  4143. }
  4144. }
  4145. async function deleteFilterRule(id) {
  4146. if (!confirm('Are you sure you want to delete this filter rule?')) return;
  4147. try {
  4148. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}`, { method: 'DELETE' });
  4149. if (res.ok) {
  4150. showToast('Deleted', 'Filter rule removed', 'success');
  4151. loadFirewall(false);
  4152. }
  4153. } catch (err) {
  4154. showToast('Error', err.message, 'error');
  4155. }
  4156. }
  4157. // ----------------- NAT Rules -----------------
  4158. function renderNATRules() {
  4159. const chainFilter = document.getElementById('nat-filter-chain')?.value || '';
  4160. const tbody = document.getElementById('nat-table-body');
  4161. const empty = document.getElementById('nat-empty');
  4162. if (!tbody) return;
  4163. tbody.innerHTML = '';
  4164. const rules = (state.natRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  4165. document.getElementById('nat-count-badge').innerText = `${rules.length} Rules`;
  4166. if (rules.length === 0) {
  4167. empty?.classList.remove('hidden');
  4168. return;
  4169. }
  4170. empty?.classList.add('hidden');
  4171. rules.forEach((r, idx) => {
  4172. const tr = document.createElement('tr');
  4173. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  4174. let toTarget = '-';
  4175. if (r.action === 'jump') {
  4176. toTarget = `<span class="text-yellow-300 font-mono font-bold">&rarr; ${r.jump_target || '-'}</span>`;
  4177. } else if (r.action.includes('address-list') || r.action.includes('address list')) {
  4178. toTarget = `<span class="text-emerald-300 font-mono font-bold">&rarr; ${r.address_list || '-'}</span>`;
  4179. } else if (r.action === 'redirect') {
  4180. toTarget = `<span class="text-amber-300 font-mono font-bold">ports:${r.to_ports || 'all'}</span>`;
  4181. } else if (r.action === 'masquerade') {
  4182. toTarget = r.to_ports ? `<span class="text-amber-300 font-mono font-bold">ports:${r.to_ports}</span>` : `<span class="text-slate-500 font-mono">-</span>`;
  4183. } else if (r.action === 'log') {
  4184. toTarget = `<span class="text-slate-400 font-mono font-bold">${r.log_prefix || 'log'}</span>`;
  4185. } else {
  4186. const parts = [r.to_addresses, r.to_ports].filter(Boolean);
  4187. toTarget = parts.length ? `<span class="text-amber-300 font-mono font-bold">${parts.join(':')}</span>` : '-';
  4188. }
  4189. const ifaces = [r.out_interface ? 'out:' + r.out_interface : '', r.in_interface ? 'in:' + r.in_interface : ''].filter(Boolean).join(' ');
  4190. tr.innerHTML = `
  4191. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  4192. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  4193. <td class="py-2.5 px-3 font-bold text-amber-400">${r.chain}</td>
  4194. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  4195. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  4196. <td class="py-2.5 px-3 text-cyan-400 uppercase">${r.protocol || 'all'}${r.dst_port ? ':' + r.dst_port : ''}</td>
  4197. <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
  4198. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  4199. <td class="py-2.5 px-3 font-mono text-xs">${toTarget}</td>
  4200. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  4201. <span class="text-slate-300" id="nat-pkts-${r.id}">${(r.packets || 0).toLocaleString()}p</span> /
  4202. <span class="text-slate-500" id="nat-bytes-${r.id}">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  4203. </td>
  4204. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  4205. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  4206. <button onclick="moveNATRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  4207. <button onclick="moveNATRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  4208. <button onclick="toggleNATRuleState('${r.id}', ${!r.disabled})" class="text-xs ${r.disabled ? 'text-emerald-400' : 'text-slate-400'} hover:underline">${r.disabled ? 'Enable' : 'Disable'}</button>
  4209. <button onclick="openEditNATModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  4210. <button onclick="deleteNATRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  4211. </td>
  4212. `;
  4213. tbody.appendChild(tr);
  4214. });
  4215. }
  4216. // ==================== FIREWALL NAT MODAL (ROUTEROS WEBFIG / WINBOX V4) ====================
  4217. function switchNATRuleTab(tab) {
  4218. state.activeNATRuleTab = tab;
  4219. document.querySelectorAll('.nat-rule-tab-btn').forEach(btn => {
  4220. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  4221. btn.classList.add('text-slate-400', 'border-transparent');
  4222. });
  4223. const activeBtn = document.getElementById(`nat-tab-btn-${tab}`);
  4224. if (activeBtn) {
  4225. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  4226. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  4227. }
  4228. document.querySelectorAll('.nat-rule-pane').forEach(p => p.classList.add('hidden'));
  4229. const activePane = document.getElementById(`nat-pane-${tab}`);
  4230. if (activePane) activePane.classList.remove('hidden');
  4231. if (tab === 'statistics') {
  4232. startNATStatPolling();
  4233. } else {
  4234. stopNATStatPolling();
  4235. }
  4236. }
  4237. function toggleNATField(fieldKey, expand) {
  4238. const plusBtn = document.getElementById(`nat-plus-${fieldKey}`);
  4239. const fieldBox = document.getElementById(`nat-field-${fieldKey}`);
  4240. if (!plusBtn || !fieldBox) return;
  4241. if (expand) {
  4242. plusBtn.classList.add('hidden');
  4243. fieldBox.classList.remove('hidden');
  4244. const valInput = document.getElementById(`nat-val-${fieldKey}`);
  4245. if (valInput) valInput.focus();
  4246. } else {
  4247. fieldBox.classList.add('hidden');
  4248. plusBtn.classList.remove('hidden');
  4249. const valInput = document.getElementById(`nat-val-${fieldKey}`);
  4250. if (valInput) {
  4251. if (valInput.tagName === 'SELECT') {
  4252. valInput.selectedIndex = 0;
  4253. } else {
  4254. valInput.value = '';
  4255. }
  4256. }
  4257. const invInput = document.getElementById(`nat-inv-${fieldKey}`);
  4258. if (invInput) invInput.checked = false;
  4259. if (fieldKey === 'days') {
  4260. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  4261. const el = document.getElementById(`nat-day-${d}`);
  4262. if (el) el.checked = true;
  4263. });
  4264. }
  4265. }
  4266. }
  4267. function setNATFieldVal(fieldKey, value, hasInvert = false) {
  4268. if (value !== undefined && value !== null && value !== '' && value !== 'all') {
  4269. toggleNATField(fieldKey, true);
  4270. let strVal = String(value);
  4271. if (hasInvert) {
  4272. const inv = strVal.startsWith('!');
  4273. if (inv) strVal = strVal.slice(1);
  4274. const invEl = document.getElementById(`nat-inv-${fieldKey}`);
  4275. if (invEl) invEl.checked = inv;
  4276. }
  4277. const valEl = document.getElementById(`nat-val-${fieldKey}`);
  4278. if (valEl) valEl.value = strVal;
  4279. } else {
  4280. toggleNATField(fieldKey, false);
  4281. }
  4282. }
  4283. function getNATFieldVal(fieldKey, hasInvert = false) {
  4284. const fieldBox = document.getElementById(`nat-field-${fieldKey}`);
  4285. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  4286. const valEl = document.getElementById(`nat-val-${fieldKey}`);
  4287. let v = valEl ? valEl.value.trim() : '';
  4288. if (!v) return '';
  4289. if (hasInvert) {
  4290. const invEl = document.getElementById(`nat-inv-${fieldKey}`);
  4291. if (invEl && invEl.checked) {
  4292. v = '!' + v.replace(/^!/, '');
  4293. }
  4294. }
  4295. return v;
  4296. }
  4297. function toggleMaximizeNATModal() {
  4298. const win = document.getElementById('nat-modal-window');
  4299. if (!win) return;
  4300. if (win.classList.contains('max-w-[720px]')) {
  4301. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  4302. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  4303. } else {
  4304. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  4305. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  4306. }
  4307. }
  4308. function handleNATChainChange() {
  4309. const ch = document.getElementById('nat-modal-chain')?.value || 'srcnat';
  4310. const actSel = document.getElementById('nat-modal-action');
  4311. if (actSel) {
  4312. if (ch === 'srcnat' && (actSel.value === 'dst-nat' || actSel.value === 'redirect')) {
  4313. actSel.value = 'masquerade';
  4314. } else if (ch === 'dstnat' && (actSel.value === 'masquerade' || actSel.value === 'src-nat')) {
  4315. actSel.value = 'dst-nat';
  4316. }
  4317. }
  4318. toggleNATActionFields();
  4319. }
  4320. function toggleNATActionFields() {
  4321. const act = document.getElementById('nat-modal-action')?.value || 'masquerade';
  4322. const rowAddr = document.getElementById('nat-row-toaddr');
  4323. const rowPort = document.getElementById('nat-row-toport');
  4324. const jumpBox = document.getElementById('nat-action-jump-box');
  4325. const addrBox = document.getElementById('nat-action-addrlist-box');
  4326. // Hide all dynamic rows first
  4327. if (rowAddr) rowAddr.classList.add('hidden');
  4328. if (rowPort) rowPort.classList.add('hidden');
  4329. if (jumpBox) jumpBox.classList.add('hidden');
  4330. if (addrBox) addrBox.classList.add('hidden');
  4331. if (['src-nat', 'dst-nat', 'netmap', 'same', 'socksify', 'endpoint-independent-nat'].includes(act)) {
  4332. if (rowAddr) rowAddr.classList.remove('hidden');
  4333. if (rowPort) rowPort.classList.remove('hidden');
  4334. } else if (act === 'redirect' || act === 'masquerade') {
  4335. if (rowPort) rowPort.classList.remove('hidden');
  4336. } else if (act === 'jump') {
  4337. if (jumpBox) jumpBox.classList.remove('hidden');
  4338. } else if (act.includes('address-list') || act.includes('address list')) {
  4339. if (addrBox) addrBox.classList.remove('hidden');
  4340. }
  4341. if (act === 'log') {
  4342. const logEl = document.getElementById('nat-modal-log');
  4343. if (logEl) logEl.checked = true;
  4344. toggleNATField('logprefix', true);
  4345. }
  4346. }
  4347. function toggleNATLogPrefix() {
  4348. const isLog = document.getElementById('nat-modal-log')?.checked;
  4349. toggleNATField('logprefix', !!isLog);
  4350. }
  4351. function openAddNATModal() {
  4352. switchNATRuleTab('general');
  4353. const badge = document.getElementById('nat-modal-badge');
  4354. if (badge) badge.innerText = 'New...';
  4355. document.getElementById('nat-modal-id').value = '';
  4356. document.getElementById('nat-modal-enabled').checked = true;
  4357. document.getElementById('nat-modal-comment').value = '';
  4358. document.getElementById('nat-modal-chain').value = 'srcnat';
  4359. document.getElementById('nat-modal-action').value = 'masquerade';
  4360. document.getElementById('nat-modal-toaddr').value = '';
  4361. document.getElementById('nat-modal-toport').value = '';
  4362. document.getElementById('nat-modal-log').checked = false;
  4363. populateInterfaceSelect('nat-val-iniface');
  4364. populateInterfaceSelect('nat-val-outiface');
  4365. populateAddressListSelect('nat-val-srclist');
  4366. populateAddressListSelect('nat-val-dstlist');
  4367. populateGeoIPSelect('nat-val-srcgeo');
  4368. populateGeoIPSelect('nat-val-dstgeo');
  4369. const allFieldKeys = [
  4370. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  4371. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  4372. 'routingmark', 'conntype',
  4373. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  4374. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  4375. 'ipsec', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  4376. 'pktsize', 'random', 'icmpoptions', 'ipv4options', 'ttl',
  4377. 'time', 'days', 'limit', 'dstlimit', 'psd', 'logprefix'
  4378. ];
  4379. allFieldKeys.forEach(k => toggleNATField(k, false));
  4380. resetCurrentNATRuleCounters();
  4381. toggleNATActionFields();
  4382. document.getElementById('nat-modal').classList.remove('hidden');
  4383. }
  4384. function openEditNATModal(id) {
  4385. const r = (state.natRules || []).find(rule => rule.id === id);
  4386. if (!r) return;
  4387. switchNATRuleTab('general');
  4388. const badge = document.getElementById('nat-modal-badge');
  4389. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  4390. document.getElementById('nat-modal-id').value = r.id;
  4391. document.getElementById('nat-modal-enabled').checked = !r.disabled;
  4392. document.getElementById('nat-modal-comment').value = r.comment || '';
  4393. document.getElementById('nat-modal-chain').value = r.chain || 'srcnat';
  4394. document.getElementById('nat-modal-action').value = r.action || 'masquerade';
  4395. document.getElementById('nat-modal-toaddr').value = r.to_addresses || '';
  4396. document.getElementById('nat-modal-toport').value = r.to_ports || '';
  4397. document.getElementById('nat-modal-log').checked = !!r.log;
  4398. populateInterfaceSelect('nat-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  4399. populateInterfaceSelect('nat-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  4400. populateAddressListSelect('nat-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  4401. populateAddressListSelect('nat-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  4402. populateGeoIPSelect('nat-val-srcgeo', r.src_geoip || '');
  4403. populateGeoIPSelect('nat-val-dstgeo', r.dst_geoip || '');
  4404. setNATFieldVal('src', r.src_address, true);
  4405. setNATFieldVal('dst', r.dst_address, true);
  4406. setNATFieldVal('srclist', r.src_address_list, true);
  4407. setNATFieldVal('dstlist', r.dst_address_list, true);
  4408. setNATFieldVal('srcgeo', r.src_geoip, true);
  4409. setNATFieldVal('dstgeo', r.dst_geoip, true);
  4410. if (r.protocol && r.protocol !== 'all') {
  4411. setNATFieldVal('proto', r.protocol, true);
  4412. } else {
  4413. toggleNATField('proto', false);
  4414. }
  4415. setNATFieldVal('sport', r.src_port, true);
  4416. setNATFieldVal('dport', r.dst_port, true);
  4417. setNATFieldVal('anyport', r.any_port, true);
  4418. setNATFieldVal('iniface', r.in_interface, true);
  4419. setNATFieldVal('outiface', r.out_interface, true);
  4420. setNATFieldVal('inifacelist', r.in_interface_list, true);
  4421. setNATFieldVal('outifacelist', r.out_interface_list, true);
  4422. setNATFieldVal('pktmark', r.packet_mark, true);
  4423. setNATFieldVal('connmark', r.connection_mark, true);
  4424. setNATFieldVal('routingmark', r.routing_mark, true);
  4425. setNATFieldVal('conntype', r.connection_type, false);
  4426. // Advanced tab fields
  4427. setNATFieldVal('layer7', r.layer7_protocol, false);
  4428. setNATFieldVal('content', r.content, false);
  4429. setNATFieldVal('connbytes', r.connection_bytes, false);
  4430. setNATFieldVal('connrate', r.connection_rate, false);
  4431. setNATFieldVal('pcc', r.pcc, false);
  4432. setNATFieldVal('srcmac', r.src_mac_address, true);
  4433. setNATFieldVal('outbridgeport', r.out_bridge_port, false);
  4434. setNATFieldVal('inbridgeport', r.in_bridge_port, false);
  4435. setNATFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  4436. setNATFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  4437. setNATFieldVal('ipsec', r.ipsec_policy, false);
  4438. setNATFieldVal('ingresspriority', r.ingress_priority, false);
  4439. setNATFieldVal('priority', r.priority, false);
  4440. setNATFieldVal('dscp', r.dscp, false);
  4441. setNATFieldVal('tcpmss', r.tcp_mss, false);
  4442. if (r.tos) {
  4443. const tosEl = document.getElementById('nat-val-tos');
  4444. if (tosEl) tosEl.value = r.tos;
  4445. }
  4446. setNATFieldVal('pktsize', r.packet_size, false);
  4447. setNATFieldVal('random', r.random, false);
  4448. setNATFieldVal('icmpoptions', r.icmp_options, false);
  4449. setNATFieldVal('ipv4options', r.ipv4_options, false);
  4450. setNATFieldVal('ttl', r.ttl, false);
  4451. // Extra tab fields
  4452. setNATFieldVal('time', r.time, false);
  4453. if (r.days) {
  4454. toggleNATField('days', true);
  4455. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  4456. const chk = document.getElementById(`nat-day-${d}`);
  4457. if (chk) chk.checked = r.days.includes(d);
  4458. });
  4459. } else {
  4460. toggleNATField('days', false);
  4461. }
  4462. setNATFieldVal('limit', r.limit, false);
  4463. setNATFieldVal('dstlimit', r.dst_limit, false);
  4464. setNATFieldVal('psd', r.psd, false);
  4465. // Action fields
  4466. if (r.jump_target) {
  4467. const jtEl = document.getElementById('nat-modal-jumptarget');
  4468. if (jtEl) jtEl.value = r.jump_target;
  4469. }
  4470. if (r.address_list) {
  4471. const alEl = document.getElementById('nat-modal-action-addrlist');
  4472. if (alEl) alEl.value = r.address_list;
  4473. }
  4474. if (r.address_list_timeout) {
  4475. const toEl = document.getElementById('nat-modal-action-timeout');
  4476. if (toEl) toEl.value = r.address_list_timeout;
  4477. }
  4478. setNATFieldVal('logprefix', r.log_prefix, false);
  4479. // Statistics
  4480. const bEl = document.getElementById('nat-stat-bytes');
  4481. const pEl = document.getElementById('nat-stat-packets');
  4482. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  4483. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  4484. state.natLastBytes = r.bytes || 0;
  4485. state.natLastPackets = r.packets || 0;
  4486. state.natLastTimestamp = Date.now();
  4487. state.natStatRateHistory = new Array(30).fill(0);
  4488. state.natStatPktHistory = new Array(30).fill(0);
  4489. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  4490. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  4491. toggleNATActionFields();
  4492. document.getElementById('nat-modal').classList.remove('hidden');
  4493. }
  4494. function closeNATModal() {
  4495. stopNATStatPolling();
  4496. document.getElementById('nat-modal').classList.add('hidden');
  4497. }
  4498. function copyNATRule() {
  4499. document.getElementById('nat-modal-id').value = '';
  4500. const badge = document.getElementById('nat-modal-badge');
  4501. if (badge) badge.innerText = 'New...';
  4502. showToast('Rule Cloned', 'Ready to save as a new NAT rule copy', 'info');
  4503. }
  4504. function resetCurrentNATRuleCounters() {
  4505. state.natStatRateHistory = new Array(30).fill(0);
  4506. state.natStatPktHistory = new Array(30).fill(0);
  4507. state.natLastBytes = 0;
  4508. state.natLastPackets = 0;
  4509. state.natLastTimestamp = Date.now();
  4510. const bEl = document.getElementById('nat-stat-bytes');
  4511. const pEl = document.getElementById('nat-stat-packets');
  4512. const rEl = document.getElementById('nat-stat-rate');
  4513. const prEl = document.getElementById('nat-stat-pktrate');
  4514. if (bEl) bEl.value = '0 B';
  4515. if (pEl) pEl.value = '0';
  4516. if (rEl) rEl.value = '0 bps';
  4517. if (prEl) prEl.value = '0 p/s';
  4518. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  4519. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  4520. showToast('Counters Reset', 'NAT rule counter display reset to 0', 'info');
  4521. }
  4522. async function applyNATRule(closeAfter = false) {
  4523. const id = document.getElementById('nat-modal-id').value;
  4524. const chain = document.getElementById('nat-modal-chain').value;
  4525. const action = document.getElementById('nat-modal-action').value;
  4526. const comment = document.getElementById('nat-modal-comment').value.trim();
  4527. const enabled = document.getElementById('nat-modal-enabled').checked;
  4528. const src = getNATFieldVal('src', true);
  4529. const dst = getNATFieldVal('dst', true);
  4530. const srclist = getNATFieldVal('srclist', true);
  4531. const dstlist = getNATFieldVal('dstlist', true);
  4532. const srcgeo = getNATFieldVal('srcgeo', true);
  4533. const dstgeo = getNATFieldVal('dstgeo', true);
  4534. const proto = getNATFieldVal('proto', true);
  4535. const sport = getNATFieldVal('sport', true);
  4536. const dport = getNATFieldVal('dport', true);
  4537. const anyport = getNATFieldVal('anyport', true);
  4538. const iniface = getNATFieldVal('iniface', true);
  4539. const outiface = getNATFieldVal('outiface', true);
  4540. const inifacelist = getNATFieldVal('inifacelist', true);
  4541. const outifacelist = getNATFieldVal('outifacelist', true);
  4542. const pktmark = getNATFieldVal('pktmark', true);
  4543. const connmark = getNATFieldVal('connmark', true);
  4544. const routingmark = getNATFieldVal('routingmark', true);
  4545. const conntype = getNATFieldVal('conntype', false);
  4546. const usesAddr = ['src-nat', 'dst-nat', 'netmap', 'same', 'socksify', 'endpoint-independent-nat'].includes(action);
  4547. const usesPort = ['src-nat', 'dst-nat', 'netmap', 'same', 'socksify', 'endpoint-independent-nat', 'redirect', 'masquerade'].includes(action);
  4548. const payload = {
  4549. id,
  4550. chain,
  4551. action,
  4552. to_addresses: usesAddr ? (document.getElementById('nat-modal-toaddr')?.value.trim() || '') : '',
  4553. to_ports: usesPort ? (document.getElementById('nat-modal-toport')?.value.trim() || '') : '',
  4554. protocol: proto || 'all',
  4555. src_address: src,
  4556. dst_address: dst,
  4557. src_port: sport,
  4558. dst_port: dport,
  4559. any_port: anyport,
  4560. in_interface: iniface,
  4561. out_interface: outiface,
  4562. in_interface_list: inifacelist,
  4563. out_interface_list: outifacelist,
  4564. packet_mark: pktmark,
  4565. connection_mark: connmark,
  4566. routing_mark: routingmark,
  4567. connection_type: conntype,
  4568. src_address_list: srclist,
  4569. dst_address_list: dstlist,
  4570. src_geoip: srcgeo,
  4571. dst_geoip: dstgeo,
  4572. comment,
  4573. disabled: !enabled,
  4574. // Advanced tab
  4575. layer7_protocol: getNATFieldVal('layer7', false),
  4576. content: getNATFieldVal('content', false),
  4577. connection_bytes: getNATFieldVal('connbytes', false),
  4578. connection_rate: getNATFieldVal('connrate', false),
  4579. pcc: getNATFieldVal('pcc', false),
  4580. src_mac_address: getNATFieldVal('srcmac', true),
  4581. out_bridge_port: getNATFieldVal('outbridgeport', false),
  4582. in_bridge_port: getNATFieldVal('inbridgeport', false),
  4583. in_bridge_port_list: getNATFieldVal('inbridgeportlist', false),
  4584. out_bridge_port_list: getNATFieldVal('outbridgeportlist', false),
  4585. ipsec_policy: getNATFieldVal('ipsec', false),
  4586. ingress_priority: getNATFieldVal('ingresspriority', false),
  4587. priority: getNATFieldVal('priority', false),
  4588. dscp: getNATFieldVal('dscp', false),
  4589. tcp_mss: getNATFieldVal('tcpmss', false),
  4590. tos: document.getElementById('nat-val-tos')?.value || '',
  4591. packet_size: getNATFieldVal('pktsize', false),
  4592. random: getNATFieldVal('random', false),
  4593. icmp_options: getNATFieldVal('icmpoptions', false),
  4594. ipv4_options: getNATFieldVal('ipv4options', false),
  4595. ttl: getNATFieldVal('ttl', false),
  4596. // Extra tab
  4597. time: getNATFieldVal('time', false),
  4598. limit: getNATFieldVal('limit', false),
  4599. dst_limit: getNATFieldVal('dstlimit', false),
  4600. psd: getNATFieldVal('psd', false),
  4601. // Action tab
  4602. jump_target: action === 'jump' ? (document.getElementById('nat-modal-jumptarget')?.value || '') : '',
  4603. address_list: action.includes('address') ? (document.getElementById('nat-modal-action-addrlist')?.value || '') : '',
  4604. address_list_timeout: action.includes('address') ? (document.getElementById('nat-modal-action-timeout')?.value || '') : '',
  4605. log: document.getElementById('nat-modal-log')?.checked || false,
  4606. log_prefix: getNATFieldVal('logprefix', false)
  4607. };
  4608. try {
  4609. const res = await fetch(`${API_BASE}/firewall/nat`, {
  4610. method: 'POST',
  4611. headers: { 'Content-Type': 'application/json' },
  4612. body: JSON.stringify(payload)
  4613. });
  4614. if (res.ok) {
  4615. const data = await res.json();
  4616. showToast('NAT Rule Saved', 'NAT mapping updated', 'success');
  4617. loadFirewall(false);
  4618. if (closeAfter) {
  4619. closeNATModal();
  4620. } else {
  4621. if (data.id) {
  4622. document.getElementById('nat-modal-id').value = data.id;
  4623. const badge = document.getElementById('nat-modal-badge');
  4624. if (badge) badge.innerText = `#${data.id}`;
  4625. }
  4626. }
  4627. } else {
  4628. const err = await res.json();
  4629. showToast('Error', err.message || 'Failed to save rule', 'error');
  4630. }
  4631. } catch (err) {
  4632. showToast('Error', err.message, 'error');
  4633. }
  4634. }
  4635. function submitSaveNATRule(e) {
  4636. if (e && e.preventDefault) e.preventDefault();
  4637. return applyNATRule(true);
  4638. }
  4639. function startNATStatPolling() {
  4640. stopNATStatPolling();
  4641. pollNATRuleStats();
  4642. state.natStatInterval = setInterval(pollNATRuleStats, 1000);
  4643. }
  4644. function stopNATStatPolling() {
  4645. if (state.natStatInterval) {
  4646. clearInterval(state.natStatInterval);
  4647. state.natStatInterval = null;
  4648. }
  4649. }
  4650. async function pollNATRuleStats() {
  4651. const id = document.getElementById('nat-modal-id')?.value;
  4652. if (!id) {
  4653. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory || new Array(30).fill(0), 'bps', 'nat-stat-legend-rate');
  4654. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory || new Array(30).fill(0), 'p/s', 'nat-stat-legend-pktrate');
  4655. return;
  4656. }
  4657. try {
  4658. const res = await fetch(`${API_BASE}/firewall/nat`);
  4659. if (!res.ok) return;
  4660. const rules = await res.json();
  4661. const r = rules.find(x => x.id === id);
  4662. if (!r) return;
  4663. const now = Date.now();
  4664. const dt = Math.max(0.2, (now - (state.natLastTimestamp || now)) / 1000);
  4665. state.natLastTimestamp = now;
  4666. const curBytes = r.bytes || 0;
  4667. const curPackets = r.packets || 0;
  4668. const deltaBytes = Math.max(0, curBytes - (state.natLastBytes || curBytes));
  4669. const deltaPkts = Math.max(0, curPackets - (state.natLastPackets || curPackets));
  4670. state.natLastBytes = curBytes;
  4671. state.natLastPackets = curPackets;
  4672. const rateBps = Math.round((deltaBytes * 8) / dt);
  4673. const ratePkt = Math.round(deltaPkts / dt);
  4674. if (!state.natStatRateHistory) state.natStatRateHistory = new Array(30).fill(0);
  4675. if (!state.natStatPktHistory) state.natStatPktHistory = new Array(30).fill(0);
  4676. state.natStatRateHistory.push(rateBps);
  4677. if (state.natStatRateHistory.length > 30) state.natStatRateHistory.shift();
  4678. state.natStatPktHistory.push(ratePkt);
  4679. if (state.natStatPktHistory.length > 30) state.natStatPktHistory.shift();
  4680. const bEl = document.getElementById('nat-stat-bytes');
  4681. const pEl = document.getElementById('nat-stat-packets');
  4682. const rEl = document.getElementById('nat-stat-rate');
  4683. const prEl = document.getElementById('nat-stat-pktrate');
  4684. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  4685. if (pEl) pEl.value = curPackets.toLocaleString();
  4686. if (rEl) rEl.value = formatBps(rateBps);
  4687. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  4688. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  4689. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  4690. } catch (e) {
  4691. console.error('Error polling NAT rule stats', e);
  4692. }
  4693. }
  4694. async function moveNATRule(id, dir) {
  4695. try {
  4696. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/move`, {
  4697. method: 'POST',
  4698. headers: { 'Content-Type': 'application/json' },
  4699. body: JSON.stringify({ direction: dir })
  4700. });
  4701. if (res.ok) loadFirewall(false);
  4702. } catch (err) {
  4703. showToast('Error', err.message, 'error');
  4704. }
  4705. }
  4706. async function toggleNATRuleState(id, disabled) {
  4707. try {
  4708. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/state`, {
  4709. method: 'POST',
  4710. headers: { 'Content-Type': 'application/json' },
  4711. body: JSON.stringify({ disabled })
  4712. });
  4713. if (res.ok) loadFirewall(false);
  4714. } catch (err) {
  4715. showToast('Error', err.message, 'error');
  4716. }
  4717. }
  4718. async function deleteNATRule(id) {
  4719. if (!confirm('Are you sure you want to delete this NAT rule?')) return;
  4720. try {
  4721. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}`, { method: 'DELETE' });
  4722. if (res.ok) {
  4723. showToast('Deleted', 'NAT rule removed', 'success');
  4724. loadFirewall(false);
  4725. }
  4726. } catch (err) {
  4727. showToast('Error', err.message, 'error');
  4728. }
  4729. }
  4730. // ----------------- Mangle Rules -----------------
  4731. function renderMangleRules() {
  4732. const chainFilter = document.getElementById('mangle-filter-chain')?.value || '';
  4733. const tbody = document.getElementById('mangle-table-body');
  4734. const empty = document.getElementById('mangle-empty');
  4735. if (!tbody) return;
  4736. tbody.innerHTML = '';
  4737. const rules = (state.mangleRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  4738. document.getElementById('mangle-count-badge').innerText = `${rules.length} Rules`;
  4739. if (rules.length === 0) {
  4740. empty?.classList.remove('hidden');
  4741. return;
  4742. }
  4743. empty?.classList.add('hidden');
  4744. rules.forEach((r, idx) => {
  4745. const tr = document.createElement('tr');
  4746. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  4747. let markVal = '<span class="text-slate-500">-</span>';
  4748. if (r.new_connection_mark) markVal = `<span class="text-cyan-300 font-mono font-bold">${r.new_connection_mark}</span>`;
  4749. else if (r.new_routing_mark) markVal = `<span class="text-amber-300 font-mono font-bold">${r.new_routing_mark}</span>`;
  4750. else if (r.new_packet_mark) markVal = `<span class="text-emerald-300 font-mono font-bold">${r.new_packet_mark}</span>`;
  4751. else if (r.new_mss) markVal = `<span class="text-sky-300 font-mono font-bold">mss:${r.new_mss}</span>`;
  4752. else if (r.new_dscp) markVal = `<span class="text-purple-300 font-mono font-bold">dscp:${r.new_dscp}</span>`;
  4753. else if (r.new_ttl) markVal = `<span class="text-blue-300 font-mono font-bold">ttl:${r.new_ttl}</span>`;
  4754. else if (r.new_priority) markVal = `<span class="text-indigo-300 font-mono font-bold">prio:${r.new_priority}</span>`;
  4755. else if (r.route) markVal = `<span class="text-orange-300 font-mono font-bold">route:${r.route}</span>`;
  4756. else if (r.sniff_target) markVal = `<span class="text-pink-300 font-mono font-bold">sniff:${r.sniff_target}</span>`;
  4757. else if (r.action === 'jump') markVal = `<span class="text-yellow-300 font-mono font-bold">&rarr; ${r.jump_target || '-'}</span>`;
  4758. else if (r.action.includes('address-list') || r.action.includes('address list')) markVal = `<span class="text-emerald-300 font-mono font-bold">&rarr; ${r.address_list || '-'}</span>`;
  4759. else if (r.action === 'log') markVal = `<span class="text-slate-400 font-mono font-bold">${r.log_prefix || 'log'}</span>`;
  4760. tr.innerHTML = `
  4761. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  4762. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  4763. <td class="py-2.5 px-3 font-bold text-purple-400">${r.chain}</td>
  4764. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  4765. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  4766. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  4767. <td class="py-2.5 px-3 font-mono text-xs">${markVal}</td>
  4768. <td class="py-2.5 px-3 text-center">${r.passthrough ? '<span class="text-emerald-400">yes</span>' : '<span class="text-slate-500">no</span>'}</td>
  4769. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  4770. <span class="text-slate-300" id="mangle-pkts-${r.id}">${(r.packets || 0).toLocaleString()}p</span> /
  4771. <span class="text-slate-500" id="mangle-bytes-${r.id}">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  4772. </td>
  4773. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  4774. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  4775. <button onclick="moveMangleRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  4776. <button onclick="moveMangleRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  4777. <button onclick="toggleMangleRuleState('${r.id}', ${!r.disabled})" class="text-xs ${r.disabled ? 'text-emerald-400' : 'text-slate-400'} hover:underline">${r.disabled ? 'Enable' : 'Disable'}</button>
  4778. <button onclick="openEditMangleModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  4779. <button onclick="deleteMangleRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  4780. </td>
  4781. `;
  4782. tbody.appendChild(tr);
  4783. });
  4784. }
  4785. // ==================== FIREWALL MANGLE MODAL (ROUTEROS WEBFIG / WINBOX V4) ====================
  4786. function switchMangleRuleTab(tab) {
  4787. state.activeMangleRuleTab = tab;
  4788. document.querySelectorAll('.mangle-rule-tab-btn').forEach(btn => {
  4789. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  4790. btn.classList.add('text-slate-400', 'border-transparent');
  4791. });
  4792. const activeBtn = document.getElementById(`mangle-tab-btn-${tab}`);
  4793. if (activeBtn) {
  4794. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  4795. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  4796. }
  4797. document.querySelectorAll('.mangle-rule-pane').forEach(p => p.classList.add('hidden'));
  4798. const activePane = document.getElementById(`mangle-pane-${tab}`);
  4799. if (activePane) activePane.classList.remove('hidden');
  4800. if (tab === 'statistics') {
  4801. startMangleStatPolling();
  4802. } else {
  4803. stopMangleStatPolling();
  4804. }
  4805. }
  4806. function toggleMangleField(fieldKey, expand) {
  4807. const plusBtn = document.getElementById(`mangle-plus-${fieldKey}`);
  4808. const fieldBox = document.getElementById(`mangle-field-${fieldKey}`);
  4809. if (!plusBtn || !fieldBox) return;
  4810. if (expand) {
  4811. plusBtn.classList.add('hidden');
  4812. fieldBox.classList.remove('hidden');
  4813. const valInput = document.getElementById(`mangle-val-${fieldKey}`);
  4814. if (valInput) valInput.focus();
  4815. } else {
  4816. fieldBox.classList.add('hidden');
  4817. plusBtn.classList.remove('hidden');
  4818. const valInput = document.getElementById(`mangle-val-${fieldKey}`);
  4819. if (valInput) {
  4820. if (valInput.tagName === 'SELECT') {
  4821. valInput.selectedIndex = 0;
  4822. } else {
  4823. valInput.value = '';
  4824. }
  4825. }
  4826. const invInput = document.getElementById(`mangle-inv-${fieldKey}`);
  4827. if (invInput) invInput.checked = false;
  4828. if (fieldKey === 'cs') {
  4829. ['mangle-modal-cs-established', 'mangle-modal-cs-related', 'mangle-modal-cs-new', 'mangle-modal-cs-invalid', 'mangle-modal-cs-untracked'].forEach(id => {
  4830. const el = document.getElementById(id);
  4831. if (el) el.checked = false;
  4832. });
  4833. }
  4834. if (fieldKey === 'natstate') {
  4835. ['mangle-modal-nat-srcnat', 'mangle-modal-nat-dstnat'].forEach(id => {
  4836. const el = document.getElementById(id);
  4837. if (el) el.checked = false;
  4838. });
  4839. }
  4840. }
  4841. }
  4842. function setMangleFieldVal(fieldKey, value, hasInvert = false) {
  4843. if (value !== undefined && value !== null && value !== '' && value !== 'all') {
  4844. toggleMangleField(fieldKey, true);
  4845. let strVal = String(value);
  4846. if (hasInvert) {
  4847. const inv = strVal.startsWith('!');
  4848. if (inv) strVal = strVal.slice(1);
  4849. const invEl = document.getElementById(`mangle-inv-${fieldKey}`);
  4850. if (invEl) invEl.checked = inv;
  4851. }
  4852. const valEl = document.getElementById(`mangle-val-${fieldKey}`);
  4853. if (valEl) valEl.value = strVal;
  4854. } else {
  4855. toggleMangleField(fieldKey, false);
  4856. }
  4857. }
  4858. function getMangleFieldVal(fieldKey, hasInvert = false) {
  4859. const fieldBox = document.getElementById(`mangle-field-${fieldKey}`);
  4860. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  4861. const valEl = document.getElementById(`mangle-val-${fieldKey}`);
  4862. let v = valEl ? valEl.value.trim() : '';
  4863. if (!v) return '';
  4864. if (hasInvert) {
  4865. const invEl = document.getElementById(`mangle-inv-${fieldKey}`);
  4866. if (invEl && invEl.checked) {
  4867. v = '!' + v.replace(/^!/, '');
  4868. }
  4869. }
  4870. return v;
  4871. }
  4872. function toggleMaximizeMangleModal() {
  4873. const win = document.getElementById('mangle-modal-window');
  4874. if (!win) return;
  4875. if (win.classList.contains('max-w-[720px]')) {
  4876. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  4877. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  4878. } else {
  4879. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  4880. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  4881. }
  4882. }
  4883. function toggleMangleActionFields() {
  4884. const act = document.getElementById('mangle-modal-action')?.value || 'mark-connection';
  4885. // Hide all dynamic rows first
  4886. ['newconnmark', 'newroutingmark', 'newpktmark', 'newmss', 'newdscp', 'newttl', 'newpriority', 'route', 'sniff', 'passthrough'].forEach(id => {
  4887. const el = document.getElementById(`mangle-row-${id}`);
  4888. if (el) el.classList.add('hidden');
  4889. });
  4890. const jumpBox = document.getElementById('mangle-action-jump-box');
  4891. const addrBox = document.getElementById('mangle-action-addrlist-box');
  4892. if (jumpBox) jumpBox.classList.add('hidden');
  4893. if (addrBox) addrBox.classList.add('hidden');
  4894. // Activate matching rows
  4895. if (act === 'mark-connection') {
  4896. document.getElementById('mangle-row-newconnmark')?.classList.remove('hidden');
  4897. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4898. } else if (act === 'mark-routing') {
  4899. document.getElementById('mangle-row-newroutingmark')?.classList.remove('hidden');
  4900. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4901. } else if (act === 'mark-packet') {
  4902. document.getElementById('mangle-row-newpktmark')?.classList.remove('hidden');
  4903. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4904. } else if (act === 'change-mss') {
  4905. document.getElementById('mangle-row-newmss')?.classList.remove('hidden');
  4906. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4907. } else if (act === 'change-dscp') {
  4908. document.getElementById('mangle-row-newdscp')?.classList.remove('hidden');
  4909. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4910. } else if (act === 'change-ttl') {
  4911. document.getElementById('mangle-row-newttl')?.classList.remove('hidden');
  4912. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4913. } else if (act === 'set-priority') {
  4914. document.getElementById('mangle-row-newpriority')?.classList.remove('hidden');
  4915. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4916. } else if (act === 'route') {
  4917. document.getElementById('mangle-row-route')?.classList.remove('hidden');
  4918. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4919. } else if (act === 'sniff-pc' || act === 'sniff-tzsp') {
  4920. document.getElementById('mangle-row-sniff')?.classList.remove('hidden');
  4921. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4922. } else if (act === 'clear-df' || act === 'strip-ipv4-options') {
  4923. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4924. } else if (act === 'jump') {
  4925. if (jumpBox) jumpBox.classList.remove('hidden');
  4926. } else if (act.includes('address-list') || act.includes('address list')) {
  4927. if (addrBox) addrBox.classList.remove('hidden');
  4928. }
  4929. if (act === 'log') {
  4930. const logEl = document.getElementById('mangle-modal-log');
  4931. if (logEl) logEl.checked = true;
  4932. toggleMangleField('logprefix', true);
  4933. }
  4934. }
  4935. function toggleMangleLogPrefix() {
  4936. const isLog = document.getElementById('mangle-modal-log')?.checked;
  4937. toggleMangleField('logprefix', !!isLog);
  4938. }
  4939. const allMangleFieldKeys = [
  4940. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  4941. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  4942. 'routingmark', 'conntype', 'cs', 'natstate',
  4943. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  4944. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  4945. 'ipsec', 'tlshost', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  4946. 'pktsize', 'random', 'tcpflags', 'icmpoptions', 'ipv4options', 'ttl',
  4947. 'nth', 'connlimit', 'srcaddrtype', 'dstaddrtype', 'hotspot', 'ipfragment',
  4948. 'limit', 'dstlimit', 'time', 'psd', 'logprefix'
  4949. ];
  4950. function openAddMangleModal() {
  4951. switchMangleRuleTab('general');
  4952. const badge = document.getElementById('mangle-modal-badge');
  4953. if (badge) badge.innerText = 'New...';
  4954. document.getElementById('mangle-modal-id').value = '';
  4955. document.getElementById('mangle-modal-enabled').checked = true;
  4956. document.getElementById('mangle-modal-comment').value = '';
  4957. document.getElementById('mangle-modal-chain').value = 'prerouting';
  4958. document.getElementById('mangle-modal-action').value = 'mark-connection';
  4959. if (document.getElementById('mangle-modal-newconnmark')) document.getElementById('mangle-modal-newconnmark').value = '';
  4960. if (document.getElementById('mangle-modal-newroutingmark')) document.getElementById('mangle-modal-newroutingmark').value = '';
  4961. if (document.getElementById('mangle-modal-newpktmark')) document.getElementById('mangle-modal-newpktmark').value = '';
  4962. if (document.getElementById('mangle-modal-newmss')) document.getElementById('mangle-modal-newmss').value = '';
  4963. if (document.getElementById('mangle-modal-newdscp')) document.getElementById('mangle-modal-newdscp').value = '';
  4964. if (document.getElementById('mangle-modal-newttl')) document.getElementById('mangle-modal-newttl').value = '';
  4965. if (document.getElementById('mangle-modal-newpriority')) document.getElementById('mangle-modal-newpriority').value = '';
  4966. if (document.getElementById('mangle-modal-route')) document.getElementById('mangle-modal-route').value = '';
  4967. if (document.getElementById('mangle-modal-sniff')) document.getElementById('mangle-modal-sniff').value = '';
  4968. if (document.getElementById('mangle-modal-jumptarget')) document.getElementById('mangle-modal-jumptarget').value = '';
  4969. if (document.getElementById('mangle-modal-action-addrlist')) document.getElementById('mangle-modal-action-addrlist').value = '';
  4970. if (document.getElementById('mangle-modal-action-timeout')) document.getElementById('mangle-modal-action-timeout').value = '';
  4971. if (document.getElementById('mangle-modal-passthrough')) document.getElementById('mangle-modal-passthrough').checked = true;
  4972. if (document.getElementById('mangle-modal-log')) document.getElementById('mangle-modal-log').checked = false;
  4973. populateInterfaceSelect('mangle-val-iniface');
  4974. populateInterfaceSelect('mangle-val-outiface');
  4975. populateAddressListSelect('mangle-val-srclist');
  4976. populateAddressListSelect('mangle-val-dstlist');
  4977. populateGeoIPSelect('mangle-val-srcgeo');
  4978. populateGeoIPSelect('mangle-val-dstgeo');
  4979. allMangleFieldKeys.forEach(k => toggleMangleField(k, false));
  4980. resetCurrentMangleRuleCounters();
  4981. toggleMangleActionFields();
  4982. document.getElementById('mangle-modal').classList.remove('hidden');
  4983. }
  4984. function openEditMangleModal(id) {
  4985. const r = (state.mangleRules || []).find(rule => rule.id === id);
  4986. if (!r) return;
  4987. switchMangleRuleTab('general');
  4988. const badge = document.getElementById('mangle-modal-badge');
  4989. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  4990. document.getElementById('mangle-modal-id').value = r.id;
  4991. document.getElementById('mangle-modal-enabled').checked = !r.disabled;
  4992. document.getElementById('mangle-modal-comment').value = r.comment || '';
  4993. document.getElementById('mangle-modal-chain').value = r.chain || 'prerouting';
  4994. document.getElementById('mangle-modal-action').value = r.action || 'mark-connection';
  4995. if (document.getElementById('mangle-modal-newconnmark')) document.getElementById('mangle-modal-newconnmark').value = r.new_connection_mark || '';
  4996. if (document.getElementById('mangle-modal-newroutingmark')) document.getElementById('mangle-modal-newroutingmark').value = r.new_routing_mark || '';
  4997. if (document.getElementById('mangle-modal-newpktmark')) document.getElementById('mangle-modal-newpktmark').value = r.new_packet_mark || '';
  4998. if (document.getElementById('mangle-modal-newmss')) document.getElementById('mangle-modal-newmss').value = r.new_mss || '';
  4999. if (document.getElementById('mangle-modal-newdscp')) document.getElementById('mangle-modal-newdscp').value = r.new_dscp != null ? r.new_dscp : '';
  5000. if (document.getElementById('mangle-modal-newttl')) document.getElementById('mangle-modal-newttl').value = r.new_ttl || '';
  5001. if (document.getElementById('mangle-modal-newpriority')) document.getElementById('mangle-modal-newpriority').value = r.new_priority || '';
  5002. if (document.getElementById('mangle-modal-route')) document.getElementById('mangle-modal-route').value = r.route || '';
  5003. if (document.getElementById('mangle-modal-sniff')) document.getElementById('mangle-modal-sniff').value = r.sniff_target || '';
  5004. if (document.getElementById('mangle-modal-jumptarget')) document.getElementById('mangle-modal-jumptarget').value = r.jump_target || '';
  5005. if (document.getElementById('mangle-modal-action-addrlist')) document.getElementById('mangle-modal-action-addrlist').value = r.address_list || '';
  5006. if (document.getElementById('mangle-modal-action-timeout')) document.getElementById('mangle-modal-action-timeout').value = r.address_list_timeout || '';
  5007. if (document.getElementById('mangle-modal-passthrough')) document.getElementById('mangle-modal-passthrough').checked = r.passthrough ?? true;
  5008. if (document.getElementById('mangle-modal-log')) document.getElementById('mangle-modal-log').checked = !!r.log;
  5009. populateInterfaceSelect('mangle-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  5010. populateInterfaceSelect('mangle-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  5011. populateAddressListSelect('mangle-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  5012. populateAddressListSelect('mangle-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  5013. populateGeoIPSelect('mangle-val-srcgeo', r.src_geoip || '');
  5014. populateGeoIPSelect('mangle-val-dstgeo', r.dst_geoip || '');
  5015. setMangleFieldVal('src', r.src_address, true);
  5016. setMangleFieldVal('dst', r.dst_address, true);
  5017. setMangleFieldVal('srclist', r.src_address_list, true);
  5018. setMangleFieldVal('dstlist', r.dst_address_list, true);
  5019. setMangleFieldVal('srcgeo', r.src_geoip, true);
  5020. setMangleFieldVal('dstgeo', r.dst_geoip, true);
  5021. if (r.protocol && r.protocol !== 'all') {
  5022. setMangleFieldVal('proto', r.protocol, true);
  5023. } else {
  5024. toggleMangleField('proto', false);
  5025. }
  5026. setMangleFieldVal('sport', r.src_port, true);
  5027. setMangleFieldVal('dport', r.dst_port, true);
  5028. setMangleFieldVal('anyport', r.any_port, true);
  5029. setMangleFieldVal('iniface', r.in_interface, true);
  5030. setMangleFieldVal('outiface', r.out_interface, true);
  5031. setMangleFieldVal('inifacelist', r.in_interface_list, true);
  5032. setMangleFieldVal('outifacelist', r.out_interface_list, true);
  5033. setMangleFieldVal('pktmark', r.packet_mark, true);
  5034. setMangleFieldVal('connmark', r.connection_mark, true);
  5035. setMangleFieldVal('routingmark', r.routing_mark, true);
  5036. setMangleFieldVal('conntype', r.connection_type, false);
  5037. // Connection State
  5038. const states = r.connection_state || [];
  5039. if (states.length > 0) {
  5040. toggleMangleField('cs', true);
  5041. ['established', 'related', 'new', 'invalid', 'untracked'].forEach(s => {
  5042. const el = document.getElementById(`mangle-modal-cs-${s}`);
  5043. if (el) el.checked = states.includes(s);
  5044. });
  5045. } else {
  5046. toggleMangleField('cs', false);
  5047. }
  5048. // Connection NAT State
  5049. const natStates = r.connection_nat_state || [];
  5050. if (natStates.length > 0) {
  5051. toggleMangleField('natstate', true);
  5052. ['srcnat', 'dstnat'].forEach(s => {
  5053. const el = document.getElementById(`mangle-modal-nat-${s}`);
  5054. if (el) el.checked = natStates.includes(s);
  5055. });
  5056. } else {
  5057. toggleMangleField('natstate', false);
  5058. }
  5059. // Advanced tab fields
  5060. setMangleFieldVal('layer7', r.layer7_protocol, false);
  5061. setMangleFieldVal('content', r.content, false);
  5062. setMangleFieldVal('connbytes', r.connection_bytes, false);
  5063. setMangleFieldVal('connrate', r.connection_rate, false);
  5064. setMangleFieldVal('pcc', r.pcc, false);
  5065. setMangleFieldVal('srcmac', r.src_mac_address, true);
  5066. setMangleFieldVal('outbridgeport', r.out_bridge_port, false);
  5067. setMangleFieldVal('inbridgeport', r.in_bridge_port, false);
  5068. setMangleFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  5069. setMangleFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  5070. setMangleFieldVal('ipsec', r.ipsec_policy, false);
  5071. setMangleFieldVal('tlshost', r.tls_host, false);
  5072. setMangleFieldVal('ingresspriority', r.ingress_priority, false);
  5073. setMangleFieldVal('priority', r.priority, false);
  5074. setMangleFieldVal('dscp', r.dscp, false);
  5075. setMangleFieldVal('tcpmss', r.tcp_mss, false);
  5076. if (r.tos) {
  5077. const tosEl = document.getElementById('mangle-val-tos');
  5078. if (tosEl) tosEl.value = r.tos;
  5079. }
  5080. setMangleFieldVal('pktsize', r.packet_size, false);
  5081. setMangleFieldVal('random', r.random, false);
  5082. setMangleFieldVal('tcpflags', r.tcp_flags, false);
  5083. setMangleFieldVal('icmpoptions', r.icmp_options, false);
  5084. setMangleFieldVal('ipv4options', r.ipv4_options, false);
  5085. setMangleFieldVal('ttl', r.ttl, false);
  5086. // Extra tab fields
  5087. setMangleFieldVal('nth', r.nth, false);
  5088. setMangleFieldVal('connlimit', r.connection_limit, false);
  5089. setMangleFieldVal('srcaddrtype', r.src_address_type, false);
  5090. setMangleFieldVal('dstaddrtype', r.dst_address_type, false);
  5091. setMangleFieldVal('hotspot', r.hotspot, false);
  5092. setMangleFieldVal('ipfragment', r.ip_fragment, false);
  5093. setMangleFieldVal('limit', r.limit, false);
  5094. setMangleFieldVal('dstlimit', r.dst_limit, false);
  5095. setMangleFieldVal('time', r.time, false);
  5096. setMangleFieldVal('psd', r.psd, false);
  5097. // Action fields
  5098. if (r.jump_target) {
  5099. const jtEl = document.getElementById('mangle-modal-jumptarget');
  5100. if (jtEl) jtEl.value = r.jump_target;
  5101. }
  5102. if (r.address_list) {
  5103. const alEl = document.getElementById('mangle-modal-action-addrlist');
  5104. if (alEl) alEl.value = r.address_list;
  5105. }
  5106. if (r.address_list_timeout) {
  5107. const toEl = document.getElementById('mangle-modal-action-timeout');
  5108. if (toEl) toEl.value = r.address_list_timeout;
  5109. }
  5110. setMangleFieldVal('logprefix', r.log_prefix, false);
  5111. // Statistics
  5112. const bEl = document.getElementById('mangle-stat-bytes');
  5113. const pEl = document.getElementById('mangle-stat-packets');
  5114. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  5115. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  5116. state.mangleLastBytes = r.bytes || 0;
  5117. state.mangleLastPackets = r.packets || 0;
  5118. state.mangleLastTimestamp = Date.now();
  5119. state.mangleStatRateHistory = new Array(30).fill(0);
  5120. state.mangleStatPktHistory = new Array(30).fill(0);
  5121. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  5122. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  5123. toggleMangleActionFields();
  5124. document.getElementById('mangle-modal').classList.remove('hidden');
  5125. }
  5126. function closeMangleModal() {
  5127. stopMangleStatPolling();
  5128. document.getElementById('mangle-modal').classList.add('hidden');
  5129. }
  5130. function copyMangleRule() {
  5131. document.getElementById('mangle-modal-id').value = '';
  5132. const badge = document.getElementById('mangle-modal-badge');
  5133. if (badge) badge.innerText = 'New...';
  5134. showToast('Rule Cloned', 'Ready to save as a new Mangle rule copy', 'info');
  5135. }
  5136. function resetCurrentMangleRuleCounters() {
  5137. state.mangleStatRateHistory = new Array(30).fill(0);
  5138. state.mangleStatPktHistory = new Array(30).fill(0);
  5139. state.mangleLastBytes = 0;
  5140. state.mangleLastPackets = 0;
  5141. state.mangleLastTimestamp = Date.now();
  5142. const bEl = document.getElementById('mangle-stat-bytes');
  5143. const pEl = document.getElementById('mangle-stat-packets');
  5144. const rEl = document.getElementById('mangle-stat-rate');
  5145. const prEl = document.getElementById('mangle-stat-pktrate');
  5146. if (bEl) bEl.value = '0 B';
  5147. if (pEl) pEl.value = '0';
  5148. if (rEl) rEl.value = '0 bps';
  5149. if (prEl) prEl.value = '0 p/s';
  5150. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  5151. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  5152. showToast('Counters Reset', 'Mangle rule counter display reset to 0', 'info');
  5153. }
  5154. async function applyMangleRule(closeAfter = false) {
  5155. const id = document.getElementById('mangle-modal-id').value;
  5156. const chain = document.getElementById('mangle-modal-chain').value;
  5157. const action = document.getElementById('mangle-modal-action').value;
  5158. const comment = document.getElementById('mangle-modal-comment').value.trim();
  5159. const enabled = document.getElementById('mangle-modal-enabled').checked;
  5160. const src = getMangleFieldVal('src', true);
  5161. const dst = getMangleFieldVal('dst', true);
  5162. const srclist = getMangleFieldVal('srclist', true);
  5163. const dstlist = getMangleFieldVal('dstlist', true);
  5164. const srcgeo = getMangleFieldVal('srcgeo', true);
  5165. const dstgeo = getMangleFieldVal('dstgeo', true);
  5166. const proto = getMangleFieldVal('proto', true);
  5167. const sport = getMangleFieldVal('sport', true);
  5168. const dport = getMangleFieldVal('dport', true);
  5169. const anyport = getMangleFieldVal('anyport', true);
  5170. const iniface = getMangleFieldVal('iniface', true);
  5171. const outiface = getMangleFieldVal('outiface', true);
  5172. const inifacelist = getMangleFieldVal('inifacelist', true);
  5173. const outifacelist = getMangleFieldVal('outifacelist', true);
  5174. const pktmark = getMangleFieldVal('pktmark', true);
  5175. const connmark = getMangleFieldVal('connmark', true);
  5176. const routingmark = getMangleFieldVal('routingmark', true);
  5177. const conntype = getMangleFieldVal('conntype', false);
  5178. const states = [];
  5179. const csBox = document.getElementById('mangle-field-cs');
  5180. if (csBox && !csBox.classList.contains('hidden')) {
  5181. ['established', 'related', 'new', 'invalid', 'untracked'].forEach(s => {
  5182. if (document.getElementById(`mangle-modal-cs-${s}`)?.checked) states.push(s);
  5183. });
  5184. }
  5185. const natStates = [];
  5186. const natBox = document.getElementById('mangle-field-natstate');
  5187. if (natBox && !natBox.classList.contains('hidden')) {
  5188. ['srcnat', 'dstnat'].forEach(s => {
  5189. if (document.getElementById(`mangle-modal-nat-${s}`)?.checked) natStates.push(s);
  5190. });
  5191. }
  5192. const payload = {
  5193. id,
  5194. chain,
  5195. action,
  5196. protocol: proto || 'all',
  5197. src_address: src,
  5198. dst_address: dst,
  5199. src_port: sport,
  5200. dst_port: dport,
  5201. any_port: anyport,
  5202. in_interface: iniface,
  5203. out_interface: outiface,
  5204. in_interface_list: inifacelist,
  5205. out_interface_list: outifacelist,
  5206. packet_mark: pktmark,
  5207. connection_mark: connmark,
  5208. routing_mark: routingmark,
  5209. connection_type: conntype,
  5210. connection_state: states,
  5211. connection_nat_state: natStates,
  5212. src_address_list: srclist,
  5213. dst_address_list: dstlist,
  5214. src_geoip: srcgeo,
  5215. dst_geoip: dstgeo,
  5216. comment,
  5217. disabled: !enabled,
  5218. // Advanced tab
  5219. layer7_protocol: getMangleFieldVal('layer7', false),
  5220. content: getMangleFieldVal('content', false),
  5221. connection_bytes: getMangleFieldVal('connbytes', false),
  5222. connection_rate: getMangleFieldVal('connrate', false),
  5223. pcc: getMangleFieldVal('pcc', false),
  5224. src_mac_address: getMangleFieldVal('srcmac', true),
  5225. out_bridge_port: getMangleFieldVal('outbridgeport', false),
  5226. in_bridge_port: getMangleFieldVal('inbridgeport', false),
  5227. in_bridge_port_list: getMangleFieldVal('inbridgeportlist', false),
  5228. out_bridge_port_list: getMangleFieldVal('outbridgeportlist', false),
  5229. ipsec_policy: getMangleFieldVal('ipsec', false),
  5230. tls_host: getMangleFieldVal('tlshost', false),
  5231. ingress_priority: getMangleFieldVal('ingresspriority', false),
  5232. priority: getMangleFieldVal('priority', false),
  5233. dscp: getMangleFieldVal('dscp', false),
  5234. tcp_mss: getMangleFieldVal('tcpmss', false),
  5235. tos: document.getElementById('mangle-val-tos')?.value || '',
  5236. packet_size: getMangleFieldVal('pktsize', false),
  5237. random: getMangleFieldVal('random', false),
  5238. tcp_flags: getMangleFieldVal('tcpflags', false),
  5239. icmp_options: getMangleFieldVal('icmpoptions', false),
  5240. ipv4_options: getMangleFieldVal('ipv4options', false),
  5241. ttl: getMangleFieldVal('ttl', false),
  5242. // Extra tab
  5243. nth: getMangleFieldVal('nth', false),
  5244. connection_limit: getMangleFieldVal('connlimit', false),
  5245. src_address_type: getMangleFieldVal('srcaddrtype', false),
  5246. dst_address_type: getMangleFieldVal('dstaddrtype', false),
  5247. hotspot: getMangleFieldVal('hotspot', false),
  5248. ip_fragment: getMangleFieldVal('ipfragment', false),
  5249. limit: getMangleFieldVal('limit', false),
  5250. dst_limit: getMangleFieldVal('dstlimit', false),
  5251. time: getMangleFieldVal('time', false),
  5252. psd: getMangleFieldVal('psd', false),
  5253. // Action tab
  5254. new_connection_mark: action === 'mark-connection' ? (document.getElementById('mangle-modal-newconnmark')?.value.trim() || '') : '',
  5255. new_routing_mark: action === 'mark-routing' ? (document.getElementById('mangle-modal-newroutingmark')?.value.trim() || '') : '',
  5256. new_packet_mark: action === 'mark-packet' ? (document.getElementById('mangle-modal-newpktmark')?.value.trim() || '') : '',
  5257. new_mss: action === 'change-mss' ? (document.getElementById('mangle-modal-newmss')?.value.trim() || '') : '',
  5258. new_dscp: action === 'change-dscp' ? parseInt(document.getElementById('mangle-modal-newdscp')?.value || '0', 10) : 0,
  5259. new_ttl: action === 'change-ttl' ? (document.getElementById('mangle-modal-newttl')?.value.trim() || '') : '',
  5260. new_priority: action === 'set-priority' ? (document.getElementById('mangle-modal-newpriority')?.value.trim() || '') : '',
  5261. route: action === 'route' ? (document.getElementById('mangle-modal-route')?.value.trim() || '') : '',
  5262. sniff_target: (action === 'sniff-pc' || action === 'sniff-tzsp') ? (document.getElementById('mangle-modal-sniff')?.value.trim() || '') : '',
  5263. passthrough: document.getElementById('mangle-modal-passthrough')?.checked ?? true,
  5264. jump_target: action === 'jump' ? (document.getElementById('mangle-modal-jumptarget')?.value || '') : '',
  5265. address_list: action.includes('address') ? (document.getElementById('mangle-modal-action-addrlist')?.value || '') : '',
  5266. address_list_timeout: action.includes('address') ? (document.getElementById('mangle-modal-action-timeout')?.value || '') : '',
  5267. log: document.getElementById('mangle-modal-log')?.checked || false,
  5268. log_prefix: getMangleFieldVal('logprefix', false)
  5269. };
  5270. try {
  5271. const res = await fetch(`${API_BASE}/firewall/mangle`, {
  5272. method: 'POST',
  5273. headers: { 'Content-Type': 'application/json' },
  5274. body: JSON.stringify(payload)
  5275. });
  5276. if (res.ok) {
  5277. const data = await res.json();
  5278. showToast('Mangle Rule Saved', 'Marking rule updated', 'success');
  5279. loadFirewall(false);
  5280. if (closeAfter) {
  5281. closeMangleModal();
  5282. } else {
  5283. if (data.id) {
  5284. document.getElementById('mangle-modal-id').value = data.id;
  5285. const badge = document.getElementById('mangle-modal-badge');
  5286. if (badge) badge.innerText = `#${data.id}`;
  5287. }
  5288. }
  5289. } else {
  5290. const err = await res.json();
  5291. showToast('Error', err.message || 'Failed to save mangle rule', 'error');
  5292. }
  5293. } catch (err) {
  5294. showToast('Error', err.message, 'error');
  5295. }
  5296. }
  5297. function submitSaveMangleRule(e) {
  5298. if (e && e.preventDefault) e.preventDefault();
  5299. return applyMangleRule(true);
  5300. }
  5301. function startMangleStatPolling() {
  5302. stopMangleStatPolling();
  5303. pollMangleRuleStats();
  5304. state.mangleStatInterval = setInterval(pollMangleRuleStats, 1000);
  5305. }
  5306. function stopMangleStatPolling() {
  5307. if (state.mangleStatInterval) {
  5308. clearInterval(state.mangleStatInterval);
  5309. state.mangleStatInterval = null;
  5310. }
  5311. }
  5312. async function pollMangleRuleStats() {
  5313. const id = document.getElementById('mangle-modal-id')?.value;
  5314. if (!id) {
  5315. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory || new Array(30).fill(0), 'bps', 'mangle-stat-legend-rate');
  5316. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory || new Array(30).fill(0), 'p/s', 'mangle-stat-legend-pktrate');
  5317. return;
  5318. }
  5319. try {
  5320. const res = await fetch(`${API_BASE}/firewall/mangle`);
  5321. if (!res.ok) return;
  5322. const rules = await res.json();
  5323. const r = rules.find(x => x.id === id);
  5324. if (!r) return;
  5325. const now = Date.now();
  5326. const dt = Math.max(0.2, (now - (state.mangleLastTimestamp || now)) / 1000);
  5327. state.mangleLastTimestamp = now;
  5328. const curBytes = r.bytes || 0;
  5329. const curPackets = r.packets || 0;
  5330. const deltaBytes = Math.max(0, curBytes - (state.mangleLastBytes || curBytes));
  5331. const deltaPkts = Math.max(0, curPackets - (state.mangleLastPackets || curPackets));
  5332. state.mangleLastBytes = curBytes;
  5333. state.mangleLastPackets = curPackets;
  5334. const rateBps = Math.round((deltaBytes * 8) / dt);
  5335. const ratePkt = Math.round(deltaPkts / dt);
  5336. if (!state.mangleStatRateHistory) state.mangleStatRateHistory = new Array(30).fill(0);
  5337. if (!state.mangleStatPktHistory) state.mangleStatPktHistory = new Array(30).fill(0);
  5338. state.mangleStatRateHistory.push(rateBps);
  5339. if (state.mangleStatRateHistory.length > 30) state.mangleStatRateHistory.shift();
  5340. state.mangleStatPktHistory.push(ratePkt);
  5341. if (state.mangleStatPktHistory.length > 30) state.mangleStatPktHistory.shift();
  5342. const bEl = document.getElementById('mangle-stat-bytes');
  5343. const pEl = document.getElementById('mangle-stat-packets');
  5344. const rEl = document.getElementById('mangle-stat-rate');
  5345. const prEl = document.getElementById('mangle-stat-pktrate');
  5346. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  5347. if (pEl) pEl.value = curPackets.toLocaleString();
  5348. if (rEl) rEl.value = formatBps(rateBps);
  5349. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  5350. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  5351. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  5352. } catch (e) {
  5353. console.error('Error polling Mangle rule stats', e);
  5354. }
  5355. }
  5356. async function moveMangleRule(id, dir) {
  5357. try {
  5358. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/move`, {
  5359. method: 'POST',
  5360. headers: { 'Content-Type': 'application/json' },
  5361. body: JSON.stringify({ direction: dir })
  5362. });
  5363. if (res.ok) loadFirewall(false);
  5364. } catch (err) {
  5365. showToast('Error', err.message, 'error');
  5366. }
  5367. }
  5368. async function toggleMangleRuleState(id, disabled) {
  5369. try {
  5370. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/state`, {
  5371. method: 'POST',
  5372. headers: { 'Content-Type': 'application/json' },
  5373. body: JSON.stringify({ disabled })
  5374. });
  5375. if (res.ok) loadFirewall(false);
  5376. } catch (err) {
  5377. showToast('Error', err.message, 'error');
  5378. }
  5379. }
  5380. async function deleteMangleRule(id) {
  5381. if (!confirm('Are you sure you want to delete this mangle rule?')) return;
  5382. try {
  5383. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5384. if (res.ok) {
  5385. showToast('Deleted', 'Mangle rule removed', 'success');
  5386. loadFirewall(false);
  5387. }
  5388. } catch (err) {
  5389. showToast('Error', err.message, 'error');
  5390. }
  5391. }
  5392. // ----------------- Address Lists -----------------
  5393. function renderAddressLists() {
  5394. const filterList = document.getElementById('addrlist-filter-name')?.value || '';
  5395. const tbody = document.getElementById('addrlist-table-body');
  5396. const empty = document.getElementById('addrlist-empty');
  5397. if (!tbody) return;
  5398. tbody.innerHTML = '';
  5399. const entries = (state.addressLists || []).filter(e => !filterList || e.name === filterList);
  5400. document.getElementById('addrlist-count-badge').innerText = `${entries.length} Entries`;
  5401. // Update filter select
  5402. const sel = document.getElementById('addrlist-filter-name');
  5403. if (sel) {
  5404. const cur = sel.value;
  5405. sel.innerHTML = '<option value="">All Lists</option>';
  5406. const set = new Set((state.addressLists || []).map(a => a.name));
  5407. set.forEach(n => {
  5408. const opt = document.createElement('option');
  5409. opt.value = n;
  5410. opt.innerText = n;
  5411. if (n === cur) opt.selected = true;
  5412. sel.appendChild(opt);
  5413. });
  5414. }
  5415. if (entries.length === 0) {
  5416. empty?.classList.remove('hidden');
  5417. return;
  5418. }
  5419. empty?.classList.add('hidden');
  5420. entries.forEach((e, idx) => {
  5421. const tr = document.createElement('tr');
  5422. tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${e.disabled ? 'opacity-50' : ''}`;
  5423. tr.setAttribute('ondblclick', `openEditAddrListModal('${e.id}')`);
  5424. tr.innerHTML = `
  5425. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  5426. <td class="py-2.5 px-3 text-center">${e.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '<span class="text-emerald-400 font-bold">✓</span>'}</td>
  5427. <td class="py-2.5 px-3 font-bold text-white font-mono">${e.name}</td>
  5428. <td class="py-2.5 px-3 font-mono font-bold text-emerald-400">${e.address}</td>
  5429. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[150px]">${e.comment || '-'}</td>
  5430. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  5431. <button onclick="toggleAddrListState('${e.id}', ${!e.disabled})" class="text-xs ${e.disabled ? 'text-emerald-400' : 'text-slate-400'} hover:underline">${e.disabled ? 'Enable' : 'Disable'}</button>
  5432. <button onclick="openEditAddrListModal('${e.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-medium">Edit</button>
  5433. <button onclick="deleteAddrList('${e.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  5434. </td>
  5435. `;
  5436. tbody.appendChild(tr);
  5437. });
  5438. populateCommonAddrListDatalist();
  5439. }
  5440. function openAddAddrListModal() {
  5441. document.getElementById('addrlist-modal-title').innerText = 'Add Address List Entry';
  5442. document.getElementById('addrlist-modal-id').value = '';
  5443. document.getElementById('addrlist-modal-name').value = '';
  5444. document.getElementById('addrlist-modal-addr').value = '';
  5445. document.getElementById('addrlist-modal-comment').value = '';
  5446. document.getElementById('addrlist-modal-disabled').checked = false;
  5447. const submitBtn = document.getElementById('addrlist-modal-submit-btn');
  5448. if (submitBtn) submitBtn.innerText = 'Add to List';
  5449. document.getElementById('addrlist-modal').classList.remove('hidden');
  5450. }
  5451. function openEditAddrListModal(id) {
  5452. const e = (state.addressLists || []).find(item => item.id === id);
  5453. if (!e) return;
  5454. document.getElementById('addrlist-modal-title').innerText = `Edit Address List Entry: ${e.name}`;
  5455. document.getElementById('addrlist-modal-id').value = e.id;
  5456. document.getElementById('addrlist-modal-name').value = e.name;
  5457. document.getElementById('addrlist-modal-addr').value = e.address;
  5458. document.getElementById('addrlist-modal-comment').value = e.comment || '';
  5459. document.getElementById('addrlist-modal-disabled').checked = !!e.disabled;
  5460. const submitBtn = document.getElementById('addrlist-modal-submit-btn');
  5461. if (submitBtn) submitBtn.innerText = 'Save Changes';
  5462. document.getElementById('addrlist-modal').classList.remove('hidden');
  5463. }
  5464. function closeAddrListModal() {
  5465. document.getElementById('addrlist-modal').classList.add('hidden');
  5466. }
  5467. async function submitSaveAddrList(e) {
  5468. e.preventDefault();
  5469. const id = document.getElementById('addrlist-modal-id').value;
  5470. const name = document.getElementById('addrlist-modal-name').value.trim();
  5471. const addr = document.getElementById('addrlist-modal-addr').value.trim();
  5472. const comment = document.getElementById('addrlist-modal-comment').value.trim();
  5473. const disabled = document.getElementById('addrlist-modal-disabled').checked;
  5474. try {
  5475. const res = await fetch(`${API_BASE}/firewall/address-lists`, {
  5476. method: 'POST',
  5477. headers: { 'Content-Type': 'application/json' },
  5478. body: JSON.stringify({ id, name, address: addr, comment, disabled })
  5479. });
  5480. if (res.ok) {
  5481. showToast('Address List Item Saved', `Saved ${addr} in ${name}`, 'success');
  5482. closeAddrListModal();
  5483. loadFirewall(false);
  5484. } else {
  5485. const err = await res.json();
  5486. showToast('Error', err.message || 'Failed to save address list', 'error');
  5487. }
  5488. } catch (err) {
  5489. showToast('Error', err.message, 'error');
  5490. }
  5491. }
  5492. async function toggleAddrListState(id, disabled) {
  5493. try {
  5494. const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}/state`, {
  5495. method: 'POST',
  5496. headers: { 'Content-Type': 'application/json' },
  5497. body: JSON.stringify({ disabled })
  5498. });
  5499. if (res.ok) {
  5500. loadFirewall(false);
  5501. }
  5502. } catch (err) {
  5503. showToast('Error', err.message, 'error');
  5504. }
  5505. }
  5506. async function deleteAddrList(id) {
  5507. if (!confirm('Are you sure you want to delete this address list item?')) return;
  5508. try {
  5509. const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5510. if (res.ok) {
  5511. showToast('Deleted', 'Address list item removed', 'info');
  5512. loadFirewall(false);
  5513. }
  5514. } catch (err) {
  5515. showToast('Error', err.message, 'error');
  5516. }
  5517. }
  5518. // ----------------- Geo-Location IP Management -----------------
  5519. async function loadGeoIP() {
  5520. try {
  5521. const [statusRes, countriesRes] = await Promise.all([
  5522. fetch(`${API_BASE}/firewall/geoip/status`),
  5523. fetch(`${API_BASE}/firewall/geoip/countries`)
  5524. ]);
  5525. if (statusRes.ok) state.geoStatus = await statusRes.json();
  5526. if (countriesRes.ok) state.geoCountries = await countriesRes.json();
  5527. updateGeoHeader();
  5528. renderGeoCountries();
  5529. } catch (err) {
  5530. console.error('Failed to load GeoIP:', err);
  5531. }
  5532. }
  5533. function getGeoUsageMap() {
  5534. const usage = {};
  5535. const checkRule = (r, type) => {
  5536. ['src_geoip', 'dst_geoip'].forEach(field => {
  5537. let val = (r && r[field]) || '';
  5538. let code = val.replace(/^!/, '').replace(/^geo:/, '').replace(/^geo_/, '').toUpperCase().trim();
  5539. if (code) {
  5540. if (!usage[code]) usage[code] = [];
  5541. const label = `${type} #${r.priority !== undefined ? r.priority : (r.id || '')}`;
  5542. if (!usage[code].includes(label)) usage[code].push(label);
  5543. }
  5544. });
  5545. };
  5546. (state.filterRules || []).forEach(r => checkRule(r, 'Filter'));
  5547. (state.natRules || []).forEach(r => checkRule(r, 'NAT'));
  5548. (state.mangleRules || []).forEach(r => checkRule(r, 'Mangle'));
  5549. return usage;
  5550. }
  5551. function updateGeoHeader() {
  5552. const s = state.geoStatus || {};
  5553. const statusBadge = document.getElementById('geo-status-badge');
  5554. if (statusBadge) {
  5555. statusBadge.innerText = s.auto_update ? 'Auto-Update ON' : 'Auto-Update OFF';
  5556. statusBadge.className = s.auto_update
  5557. ? 'px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-emerald-500/20 text-emerald-300 border border-emerald-500/30'
  5558. : 'px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-slate-800 text-slate-400';
  5559. }
  5560. const intervalLabel = document.getElementById('geo-interval-label');
  5561. if (intervalLabel) {
  5562. intervalLabel.innerText = `Every ${s.interval_hours || 24}h`;
  5563. }
  5564. const usageMap = getGeoUsageMap();
  5565. const inUseCount = Object.keys(usageMap).length;
  5566. const activeCountEl = document.getElementById('geo-stat-active-countries');
  5567. if (activeCountEl) activeCountEl.innerText = inUseCount.toLocaleString();
  5568. const totalSubnetsEl = document.getElementById('geo-stat-total-subnets');
  5569. if (totalSubnetsEl) totalSubnetsEl.innerText = (s.total_subnets || 0).toLocaleString();
  5570. const lastSyncEl = document.getElementById('geo-stat-last-sync');
  5571. if (lastSyncEl) {
  5572. if (s.last_updated && !s.last_updated.startsWith('0001')) {
  5573. const d = new Date(s.last_updated);
  5574. lastSyncEl.innerText = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  5575. } else {
  5576. lastSyncEl.innerText = 'Never (Sync Pending)';
  5577. }
  5578. }
  5579. const nextSyncEl = document.getElementById('geo-stat-next-sync');
  5580. if (nextSyncEl) {
  5581. if (s.next_update && !s.next_update.startsWith('0001')) {
  5582. const d = new Date(s.next_update);
  5583. nextSyncEl.innerText = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  5584. } else {
  5585. nextSyncEl.innerText = '-';
  5586. }
  5587. }
  5588. const badge = document.getElementById('fw-badge-geo');
  5589. if (badge) badge.innerText = inUseCount || (state.geoCountries || []).filter(c => c.subnet_count > 0).length || 0;
  5590. }
  5591. function renderGeoCountries() {
  5592. const tbody = document.getElementById('geo-table-body');
  5593. const empty = document.getElementById('geo-empty');
  5594. if (!tbody) return;
  5595. tbody.innerHTML = '';
  5596. const q = (document.getElementById('geo-search-input')?.value || '').trim().toLowerCase();
  5597. const continent = document.getElementById('geo-continent-filter')?.value || '';
  5598. const inUseOnly = document.getElementById('geo-filter-inuse-only')?.checked;
  5599. const cachedOnly = document.getElementById('geo-filter-cached-only')?.checked;
  5600. const usageMap = getGeoUsageMap();
  5601. const countries = (state.geoCountries || []).filter(c => {
  5602. const isUsed = !!usageMap[c.code];
  5603. if (inUseOnly && !isUsed) return false;
  5604. if (cachedOnly && (!c.subnet_count || c.subnet_count === 0)) return false;
  5605. if (continent && c.continent !== continent) return false;
  5606. if (q) {
  5607. const matchCode = c.code.toLowerCase().includes(q);
  5608. const matchName = c.name.toLowerCase().includes(q);
  5609. if (!matchCode && !matchName) return false;
  5610. }
  5611. return true;
  5612. });
  5613. if (countries.length === 0) {
  5614. empty?.classList.remove('hidden');
  5615. return;
  5616. }
  5617. empty?.classList.add('hidden');
  5618. countries.forEach(c => {
  5619. const tr = document.createElement('tr');
  5620. const isUsed = !!usageMap[c.code];
  5621. const rulesUsing = usageMap[c.code] || [];
  5622. tr.className = `hover:bg-slate-800/40 transition text-xs ${isUsed ? 'bg-emerald-950/20' : ''}`;
  5623. let statusHtml = '';
  5624. if (isUsed) {
  5625. statusHtml = `<span class="px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-emerald-500/20 text-emerald-300 border border-emerald-500/40" title="Assigned in: ${rulesUsing.join(', ')}">IN USE (${rulesUsing.length})</span>`;
  5626. } else if (c.subnet_count > 0) {
  5627. statusHtml = '<span class="px-2 py-0.5 rounded text-[10px] font-mono text-cyan-300 bg-cyan-950/40 border border-cyan-800/40">CACHED</span>';
  5628. } else {
  5629. statusHtml = '<span class="px-2 py-0.5 rounded text-[10px] font-mono text-slate-500 bg-slate-800/60">READY</span>';
  5630. }
  5631. tr.innerHTML = `
  5632. <td class="py-2.5 px-3 text-center">
  5633. <span class="px-2 py-0.5 rounded font-mono font-bold ${isUsed ? 'bg-emerald-500/20 text-emerald-300 border border-emerald-500/40' : 'bg-slate-800 text-cyan-300 border border-slate-700'}">
  5634. ${c.code}
  5635. </span>
  5636. </td>
  5637. <td class="py-2.5 px-3 font-bold text-white">${c.name}</td>
  5638. <td class="py-2.5 px-3 text-slate-400">${c.continent}</td>
  5639. <td class="py-2.5 px-3 font-mono ${c.subnet_count > 0 ? 'text-emerald-400 font-bold' : 'text-slate-500'}">
  5640. ${c.subnet_count > 0 ? c.subnet_count.toLocaleString() + ' CIDRs' : 'Not Cached'}
  5641. </td>
  5642. <td class="py-2.5 px-3 font-mono text-purple-300">${c.ipset_name}</td>
  5643. <td class="py-2.5 px-3">
  5644. ${statusHtml}
  5645. </td>
  5646. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  5647. <button onclick="updateGeoCountry('${c.code}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-medium" title="Re-download latest country IP blocks">Sync</button>
  5648. <button onclick="viewGeoSubnets('${c.code}')" class="text-xs text-slate-400 hover:text-white" title="Preview Subnet Ranges">View</button>
  5649. </td>
  5650. `;
  5651. tbody.appendChild(tr);
  5652. });
  5653. }
  5654. function quickFilterGeo(preset) {
  5655. const searchInput = document.getElementById('geo-search-input');
  5656. const continentSel = document.getElementById('geo-continent-filter');
  5657. const inUseCheck = document.getElementById('geo-filter-inuse-only');
  5658. const cachedCheck = document.getElementById('geo-filter-cached-only');
  5659. if (searchInput) searchInput.value = '';
  5660. if (continentSel) continentSel.value = '';
  5661. if (inUseCheck) inUseCheck.checked = false;
  5662. if (cachedCheck) cachedCheck.checked = false;
  5663. if (preset === 'GR') {
  5664. if (searchInput) searchInput.value = 'Greece';
  5665. } else if (preset === 'Europe') {
  5666. if (continentSel) continentSel.value = 'Europe';
  5667. } else if (preset === 'HIGHRISK') {
  5668. if (searchInput) searchInput.value = 'China';
  5669. }
  5670. renderGeoCountries();
  5671. }
  5672. async function toggleGeoCountry(code, enabled) {
  5673. try {
  5674. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/toggle`, {
  5675. method: 'POST',
  5676. headers: { 'Content-Type': 'application/json' },
  5677. body: JSON.stringify({ enabled })
  5678. });
  5679. if (res.ok) {
  5680. showToast(enabled ? 'Country Enabled' : 'Country Disabled', `${code} ${enabled ? 'active in firewall' : 'removed from firewall'}`, 'success');
  5681. loadGeoIP();
  5682. } else {
  5683. const err = await res.json();
  5684. showToast('Error', err.message || 'Failed to toggle country', 'error');
  5685. }
  5686. } catch (err) {
  5687. showToast('Error', err.message, 'error');
  5688. }
  5689. }
  5690. async function updateGeoCountry(code) {
  5691. try {
  5692. showToast('Syncing Country', `Downloading latest IP blocks for ${code}...`, 'info');
  5693. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/update`, { method: 'POST' });
  5694. if (res.ok) {
  5695. const data = await res.json();
  5696. showToast('Synced', `Loaded ${data.subnets} CIDR blocks for ${code}`, 'success');
  5697. loadGeoIP();
  5698. } else {
  5699. const err = await res.json();
  5700. showToast('Sync Error', err.message || 'Failed to sync country', 'error');
  5701. }
  5702. } catch (err) {
  5703. showToast('Error', err.message, 'error');
  5704. }
  5705. }
  5706. async function triggerGeoUpdateNow() {
  5707. const spinner = document.getElementById('geo-update-spinner');
  5708. if (spinner) spinner.classList.remove('hidden');
  5709. try {
  5710. const res = await fetch(`${API_BASE}/firewall/geoip/update-now`, { method: 'POST' });
  5711. if (res.ok) {
  5712. showToast('Update Started', 'Updating all active GeoIP country zones in background...', 'info');
  5713. setTimeout(() => {
  5714. loadGeoIP();
  5715. if (spinner) spinner.classList.add('hidden');
  5716. }, 2500);
  5717. } else {
  5718. const err = await res.json();
  5719. showToast('Notice', err.message || 'Update in progress', 'info');
  5720. if (spinner) spinner.classList.add('hidden');
  5721. }
  5722. } catch (err) {
  5723. showToast('Error', err.message, 'error');
  5724. if (spinner) spinner.classList.add('hidden');
  5725. }
  5726. }
  5727. async function applyGeoPreset(preset) {
  5728. try {
  5729. const res = await fetch(`${API_BASE}/firewall/geoip/batch-toggle`, {
  5730. method: 'POST',
  5731. headers: { 'Content-Type': 'application/json' },
  5732. body: JSON.stringify({ preset, enabled: preset !== 'NONE' })
  5733. });
  5734. if (res.ok) {
  5735. showToast('Preset Applied', `Preset ${preset} updated in firewall`, 'success');
  5736. loadGeoIP();
  5737. }
  5738. } catch (err) {
  5739. showToast('Error', err.message, 'error');
  5740. }
  5741. }
  5742. function openGeoIntervalModal() {
  5743. const s = state.geoStatus || {};
  5744. document.getElementById('geo-cfg-autoupdate').checked = s.auto_update !== false;
  5745. const sel = document.getElementById('geo-cfg-interval');
  5746. const customBox = document.getElementById('geo-cfg-custom-box');
  5747. const customHoursInput = document.getElementById('geo-cfg-custom-hours');
  5748. const curHours = s.interval_hours || 24;
  5749. const matchOption = Array.from(sel.options).find(o => parseInt(o.value, 10) === curHours);
  5750. if (matchOption) {
  5751. sel.value = String(curHours);
  5752. customBox.classList.add('hidden');
  5753. } else {
  5754. sel.value = 'custom';
  5755. customHoursInput.value = curHours;
  5756. customBox.classList.remove('hidden');
  5757. }
  5758. document.getElementById('geo-interval-modal').classList.remove('hidden');
  5759. }
  5760. function closeGeoIntervalModal() {
  5761. document.getElementById('geo-interval-modal').classList.add('hidden');
  5762. }
  5763. function toggleCustomGeoInterval() {
  5764. const val = document.getElementById('geo-cfg-interval').value;
  5765. const customBox = document.getElementById('geo-cfg-custom-box');
  5766. if (val === 'custom') {
  5767. customBox.classList.remove('hidden');
  5768. } else {
  5769. customBox.classList.add('hidden');
  5770. }
  5771. }
  5772. async function submitGeoIntervalSettings(e) {
  5773. e.preventDefault();
  5774. const autoUpdate = document.getElementById('geo-cfg-autoupdate').checked;
  5775. const intervalVal = document.getElementById('geo-cfg-interval').value;
  5776. let hours = 24;
  5777. if (intervalVal === 'custom') {
  5778. hours = parseInt(document.getElementById('geo-cfg-custom-hours').value, 10) || 24;
  5779. } else {
  5780. hours = parseInt(intervalVal, 10) || 24;
  5781. }
  5782. try {
  5783. const res = await fetch(`${API_BASE}/firewall/geoip/config`, {
  5784. method: 'POST',
  5785. headers: { 'Content-Type': 'application/json' },
  5786. body: JSON.stringify({ auto_update: autoUpdate, interval_hours: hours })
  5787. });
  5788. if (res.ok) {
  5789. showToast('Schedule Saved', `Auto-update set to every ${hours} hours`, 'success');
  5790. closeGeoIntervalModal();
  5791. loadGeoIP();
  5792. } else {
  5793. const err = await res.json();
  5794. showToast('Error', err.message || 'Failed to save schedule', 'error');
  5795. }
  5796. } catch (err) {
  5797. showToast('Error', err.message, 'error');
  5798. }
  5799. }
  5800. async function viewGeoSubnets(code, name) {
  5801. if (!name) {
  5802. const found = (state.geoCountries || []).find(x => x.code === code);
  5803. name = found ? found.name : code;
  5804. }
  5805. document.getElementById('geo-subnets-title').innerText = `${name} (${code}) Subnets`;
  5806. document.getElementById('geo-subnets-subtitle').innerText = `Kernel IPSet: mk_geo_${code}`;
  5807. const listEl = document.getElementById('geo-subnets-list');
  5808. listEl.innerHTML = '<span class="text-slate-500">Loading subnets...</span>';
  5809. document.getElementById('geo-subnets-modal').classList.remove('hidden');
  5810. try {
  5811. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/subnets`);
  5812. if (res.ok) {
  5813. const data = await res.json();
  5814. const subnets = data.subnets || [];
  5815. if (subnets.length === 0) {
  5816. listEl.innerHTML = '<span class="text-slate-500">No cached subnets found. Click Sync to download this zone.</span>';
  5817. } else {
  5818. listEl.innerHTML = subnets.map(s => `<div>${s}</div>`).join('');
  5819. }
  5820. } else {
  5821. listEl.innerHTML = '<span class="text-rose-400">Failed to load subnets.</span>';
  5822. }
  5823. } catch (err) {
  5824. listEl.innerHTML = `<span class="text-rose-400">Error: ${err.message}</span>`;
  5825. }
  5826. }
  5827. function closeGeoSubnetsModal() {
  5828. document.getElementById('geo-subnets-modal').classList.add('hidden');
  5829. }
  5830. // ----------------- Active Connections Tracking -----------------
  5831. async function loadConnections() {
  5832. try {
  5833. const res = await fetch(`${API_BASE}/firewall/connections`);
  5834. const data = await res.json();
  5835. state.connections = Array.isArray(data) ? data : [];
  5836. document.getElementById('fw-badge-connections').innerText = state.connections.length;
  5837. document.getElementById('conns-count-badge').innerText = `${state.connections.length} Flows`;
  5838. renderConnections();
  5839. } catch (err) {
  5840. console.error('Failed to load connections:', err);
  5841. }
  5842. }
  5843. function renderConnections() {
  5844. const search = (document.getElementById('conns-search-input')?.value || '').toLowerCase();
  5845. const protoFilter = document.getElementById('conns-filter-proto')?.value || '';
  5846. const tbody = document.getElementById('conns-table-body');
  5847. const empty = document.getElementById('conns-empty');
  5848. if (!tbody) return;
  5849. tbody.innerHTML = '';
  5850. const conns = (state.connections || []).filter(c => {
  5851. if (protoFilter && c.protocol !== protoFilter) return false;
  5852. if (search) {
  5853. const line = `${c.protocol} ${c.src_address} ${c.dst_address} ${c.src_port} ${c.dst_port} ${c.tcp_state} ${c.connection_mark}`.toLowerCase();
  5854. if (!line.includes(search)) return false;
  5855. }
  5856. return true;
  5857. });
  5858. if (conns.length === 0) {
  5859. empty?.classList.remove('hidden');
  5860. return;
  5861. }
  5862. empty?.classList.add('hidden');
  5863. conns.slice(0, 150).forEach(c => {
  5864. const tr = document.createElement('tr');
  5865. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  5866. let stateColor = 'text-slate-400';
  5867. if (c.tcp_state === 'ESTABLISHED') stateColor = 'text-emerald-400 font-bold';
  5868. else if (c.tcp_state === 'TIME_WAIT' || c.tcp_state === 'SYN_SENT') stateColor = 'text-amber-400';
  5869. tr.innerHTML = `
  5870. <td class="py-2.5 px-3 font-bold text-cyan-400">${c.protocol}</td>
  5871. <td class="py-2.5 px-3 font-mono text-white">${c.src_address}:${c.src_port}</td>
  5872. <td class="py-2.5 px-3 font-mono text-white">${c.dst_address}:${c.dst_port}</td>
  5873. <td class="py-2.5 px-3 font-mono text-slate-400">${c.reply_src_address ? c.reply_src_address + ':' + c.reply_src_port : '-'}</td>
  5874. <td class="py-2.5 px-3 font-mono text-slate-400">${c.reply_dst_address ? c.reply_dst_address + ':' + c.reply_dst_port : '-'}</td>
  5875. <td class="py-2.5 px-3 font-mono ${stateColor}">${c.tcp_state}</td>
  5876. <td class="py-2.5 px-3 font-mono text-purple-300">${c.connection_mark || '-'}</td>
  5877. <td class="py-2.5 px-3 text-slate-500">${c.timeout ? c.timeout + 's' : '-'}</td>
  5878. <td class="py-2.5 px-3 text-right font-sans">
  5879. <button onclick="killConnection('${c.protocol}', '${c.src_address}', ${c.src_port}, '${c.dst_address}', ${c.dst_port})" class="text-xs text-rose-400 hover:text-rose-300">Kill</button>
  5880. </td>
  5881. `;
  5882. tbody.appendChild(tr);
  5883. });
  5884. }
  5885. async function killConnection(protocol, src, sport, dst, dport) {
  5886. try {
  5887. const res = await fetch(`${API_BASE}/firewall/connections/kill`, {
  5888. method: 'POST',
  5889. headers: { 'Content-Type': 'application/json' },
  5890. body: JSON.stringify({ protocol, src, sport, dst, dport })
  5891. });
  5892. if (res.ok) {
  5893. showToast('Terminated', `Killed flow ${src}:${sport} -> ${dst}:${dport}`, 'info');
  5894. loadConnections();
  5895. }
  5896. } catch (err) {
  5897. showToast('Error', err.message, 'error');
  5898. }
  5899. }
  5900. async function resetFirewallCounters() {
  5901. if (!confirm('Reset all firewall packet and byte counters to zero?')) return;
  5902. try {
  5903. const res = await fetch(`${API_BASE}/firewall/reset-counters`, { method: 'POST' });
  5904. if (res.ok) {
  5905. showToast('Counters Reset', 'All rules counters reset to 0', 'success');
  5906. loadFirewall(false);
  5907. }
  5908. } catch (err) {
  5909. showToast('Error', err.message, 'error');
  5910. }
  5911. }
  5912. // ======================== MIKROTIK ROUTING & POLICY (/ip route) ========================
  5913. function switchRoutesSubTab(tab) {
  5914. state.routesSubTab = tab;
  5915. const tabs = ['routes', 'rules', 'tables'];
  5916. tabs.forEach(t => {
  5917. const panel = document.getElementById(`routes-subtab-${t}`);
  5918. const btn = document.getElementById(`routes-subtab-btn-${t}`);
  5919. if (panel) {
  5920. if (t === tab) panel.classList.remove('hidden');
  5921. else panel.classList.add('hidden');
  5922. }
  5923. if (btn) {
  5924. if (t === tab) {
  5925. btn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-cyan-500 text-white transition flex items-center gap-2';
  5926. } else {
  5927. btn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-transparent text-slate-400 hover:text-slate-200 transition flex items-center gap-2';
  5928. }
  5929. }
  5930. });
  5931. setTimeout(initTableSorting, 50);
  5932. }
  5933. async function loadRoutes() {
  5934. try {
  5935. const [routesRes, rulesRes, tablesRes] = await Promise.all([
  5936. fetch(`${API_BASE}/routes`),
  5937. fetch(`${API_BASE}/routing/rules`),
  5938. fetch(`${API_BASE}/routing/tables`)
  5939. ]);
  5940. if (routesRes.ok) state.routes = await routesRes.json();
  5941. if (rulesRes.ok) state.policyRules = await rulesRes.json();
  5942. if (tablesRes.ok) state.routingTables = await tablesRes.json();
  5943. const bRoutes = document.getElementById('routes-badge-routes');
  5944. if (bRoutes) bRoutes.innerText = (state.routes || []).length;
  5945. const showSystem = document.getElementById('prule-show-system')?.checked;
  5946. const userRules = (state.policyRules || []).filter(pr => showSystem || (!pr.is_default && !pr.is_system));
  5947. const bRules = document.getElementById('routes-badge-rules');
  5948. if (bRules) bRules.innerText = userRules.length;
  5949. const bTables = document.getElementById('routes-badge-tables');
  5950. if (bTables) bTables.innerText = (state.routingTables || []).length;
  5951. const bRoutesCount = document.getElementById('badge-routes-count');
  5952. if (bRoutesCount) bRoutesCount.innerText = (state.routes || []).length;
  5953. renderRoutesList();
  5954. renderPolicyRules();
  5955. renderRoutingTables();
  5956. } catch (err) {
  5957. console.error('Failed to load routing:', err);
  5958. }
  5959. }
  5960. function getRouteProtocolBadge(proto) {
  5961. const p = (proto || 'static').toLowerCase();
  5962. switch (p) {
  5963. case 'bgp':
  5964. return `<span class="px-2 py-0.5 rounded text-[10px] font-bold font-mono uppercase bg-amber-500/20 text-amber-300 border border-amber-500/30">bgp</span>`;
  5965. case 'ibgp':
  5966. return `<span class="px-2 py-0.5 rounded text-[10px] font-bold font-mono uppercase bg-yellow-500/20 text-yellow-300 border border-yellow-500/30">ibgp</span>`;
  5967. case 'ospf':
  5968. return `<span class="px-2 py-0.5 rounded text-[10px] font-bold font-mono uppercase bg-emerald-500/20 text-emerald-300 border border-emerald-500/30">ospf</span>`;
  5969. case 'rip':
  5970. return `<span class="px-2 py-0.5 rounded text-[10px] font-bold font-mono uppercase bg-orange-500/20 text-orange-300 border border-orange-500/30">rip</span>`;
  5971. case 'static':
  5972. return `<span class="px-2 py-0.5 rounded text-[10px] font-bold font-mono uppercase bg-blue-500/20 text-blue-300 border border-blue-500/30">static</span>`;
  5973. case 'connected':
  5974. return `<span class="px-2 py-0.5 rounded text-[10px] font-bold font-mono uppercase bg-slate-800 text-slate-300 border border-slate-700">connected</span>`;
  5975. case 'dhcp':
  5976. return `<span class="px-2 py-0.5 rounded text-[10px] font-bold font-mono uppercase bg-cyan-500/20 text-cyan-300 border border-cyan-500/30">dhcp</span>`;
  5977. case 'multicast':
  5978. return `<span class="px-2 py-0.5 rounded text-[10px] font-bold font-mono uppercase bg-purple-500/20 text-purple-300 border border-purple-500/30">igmp</span>`;
  5979. default:
  5980. return `<span class="px-2 py-0.5 rounded text-[10px] font-bold font-mono uppercase bg-slate-800 text-slate-400 border border-slate-700">${escapeHtml(p)}</span>`;
  5981. }
  5982. }
  5983. function renderRoutesList() {
  5984. const tableFilter = document.getElementById('routes-filter-table')?.value || '';
  5985. const typeFilter = document.getElementById('routes-filter-type')?.value || '';
  5986. const tbody = document.getElementById('routes-table-body');
  5987. const empty = document.getElementById('routes-empty');
  5988. if (!tbody) return;
  5989. // Update table filter select
  5990. const sel = document.getElementById('routes-filter-table');
  5991. if (sel) {
  5992. const cur = sel.value;
  5993. sel.innerHTML = '<option value="">All Tables</option>';
  5994. (state.routingTables || []).forEach(t => {
  5995. const opt = document.createElement('option');
  5996. opt.value = t.name;
  5997. opt.innerText = t.name;
  5998. if (t.name === cur) opt.selected = true;
  5999. sel.appendChild(opt);
  6000. });
  6001. }
  6002. const routes = (state.routes || []).filter(r => {
  6003. if (tableFilter && r.routing_table !== tableFilter) return false;
  6004. if (typeFilter === 'ecmp' && !r.ecmp) return false;
  6005. if (typeFilter === 'multicast' && !r.multicast) return false;
  6006. if (typeFilter === 'static' && !r.static) return false;
  6007. if (typeFilter === 'dynamic' && !r.dynamic) return false;
  6008. if (typeFilter === 'connected' && !r.connect) return false;
  6009. if (typeFilter === 'bgp' && (r.protocol || '').toLowerCase() !== 'bgp' && (r.protocol || '').toLowerCase() !== 'ibgp') return false;
  6010. if (typeFilter === 'ospf' && (r.protocol || '').toLowerCase() !== 'ospf') return false;
  6011. if (typeFilter === 'dhcp' && (r.protocol || '').toLowerCase() !== 'dhcp') return false;
  6012. return true;
  6013. });
  6014. const ecmpCount = (state.routes || []).filter(r => r.ecmp).length;
  6015. const mcCount = (state.routes || []).filter(r => r.multicast).length;
  6016. let summaryText = `${routes.length} Routes`;
  6017. if (ecmpCount > 0) summaryText += ` • ${ecmpCount} ECMP`;
  6018. if (mcCount > 0) summaryText += ` • ${mcCount} Multicast/IGMP`;
  6019. const badgeEl = document.getElementById('routes-count-badge');
  6020. if (badgeEl) badgeEl.innerText = summaryText;
  6021. if (routes.length === 0) {
  6022. empty?.classList.remove('hidden');
  6023. tbody.innerHTML = '';
  6024. return;
  6025. }
  6026. empty?.classList.add('hidden');
  6027. const sig = `${tableFilter}|${typeFilter}|` + routes.map(r => `${r.id}:${r.active}:${r.disabled}:${r.distance}:${r.protocol}:${r.health_status}:${(r.health_rtt_ms || 0).toFixed(0)}`).join(';');
  6028. if (tbody.dataset.sig === sig) {
  6029. return; // Routes table unchanged! Do not wipe DOM or flicker!
  6030. }
  6031. tbody.dataset.sig = sig;
  6032. tbody.innerHTML = '';
  6033. routes.forEach(r => {
  6034. const tr = document.createElement('tr');
  6035. tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${r.disabled ? 'opacity-50' : ''}`;
  6036. tr.setAttribute('ondblclick', `openEditRouteModal('${r.id}')`);
  6037. // Routing Flags string: D=Dynamic, A=Active, C=Connect, S=Static, E=ECMP, M=Multicast, X=Disabled
  6038. let flags = '';
  6039. if (r.dynamic) flags += 'D';
  6040. if (r.active) flags += 'A';
  6041. if (r.connect) flags += 'C';
  6042. if (r.static) flags += 'S';
  6043. if (r.ecmp) flags += 'E';
  6044. if (r.multicast) flags += 'M';
  6045. if (r.disabled) flags += 'X';
  6046. const isDefault = r.dst_address === 'default' || r.dst_address === '0.0.0.0/0';
  6047. let healthCell = `<span class="text-slate-600 font-mono text-[11px]">-</span>`;
  6048. if (r.check_gateway === 'internet') {
  6049. if (r.health_status === 'online') {
  6050. const ms = (r.health_rtt_ms || 0).toFixed(0);
  6051. healthCell = `
  6052. <span class="px-2 py-0.5 rounded text-[10px] font-mono bg-emerald-500/20 text-emerald-300 border border-emerald-500/30 font-semibold inline-flex items-center gap-1.5" title="Internet Verified via ${escapeHtml(r.check_target || '1.1.1.1')} (${r.health_loss_pct || 0}% loss)">
  6053. <span class="w-1.5 h-1.5 rounded-full bg-emerald-400 animate-pulse"></span>
  6054. <span>Internet OK (${ms}ms)</span>
  6055. </span>
  6056. `;
  6057. } else if (r.health_status === 'offline') {
  6058. healthCell = `
  6059. <span class="px-2 py-0.5 rounded text-[10px] font-mono bg-rose-500/20 text-rose-300 border border-rose-500/40 font-bold inline-flex items-center gap-1.5 animate-pulse" title="Internet probe to ${escapeHtml(r.check_target || '1.1.1.1')} failed! Route withdrawn for failover.">
  6060. <span class="w-1.5 h-1.5 rounded-full bg-rose-400"></span>
  6061. <span>Internet Down</span>
  6062. </span>
  6063. `;
  6064. } else {
  6065. healthCell = `
  6066. <span class="px-2 py-0.5 rounded text-[10px] font-mono bg-slate-800 text-slate-400 border border-slate-700 inline-flex items-center gap-1.5">
  6067. <span class="w-1.5 h-1.5 rounded-full bg-amber-400 animate-ping"></span>
  6068. <span>Checking...</span>
  6069. </span>
  6070. `;
  6071. }
  6072. } else if (r.check_gateway === 'ping') {
  6073. if (r.health_status === 'online') {
  6074. healthCell = `
  6075. <span class="px-2 py-0.5 rounded text-[10px] font-mono bg-cyan-500/20 text-cyan-300 border border-cyan-500/30 font-semibold inline-flex items-center gap-1.5">
  6076. <span class="w-1.5 h-1.5 rounded-full bg-cyan-400"></span>
  6077. <span>Gateway OK (${(r.health_rtt_ms || 0).toFixed(0)}ms)</span>
  6078. </span>
  6079. `;
  6080. } else if (r.health_status === 'offline') {
  6081. healthCell = `
  6082. <span class="px-2 py-0.5 rounded text-[10px] font-mono bg-rose-500/20 text-rose-300 border border-rose-500/40 font-bold inline-flex items-center gap-1.5">
  6083. <span class="w-1.5 h-1.5 rounded-full bg-rose-400"></span>
  6084. <span>Gateway Dead</span>
  6085. </span>
  6086. `;
  6087. }
  6088. }
  6089. const flagDescriptions = [];
  6090. if (r.dynamic) flagDescriptions.push('Dynamic (D)');
  6091. if (r.active) flagDescriptions.push('Active (A)');
  6092. if (r.connect) flagDescriptions.push('Connected (C)');
  6093. if (r.static) flagDescriptions.push('Static (S)');
  6094. if (r.ecmp) flagDescriptions.push('ECMP - Equal-Cost Multi-Path (E)');
  6095. if (r.multicast) flagDescriptions.push('Multicast / IGMP Group (M)');
  6096. if (r.disabled) flagDescriptions.push('Disabled (X)');
  6097. tr.innerHTML = `
  6098. <td class="py-2.5 px-3 text-center">
  6099. <span class="px-1.5 py-0.5 rounded text-[10px] font-mono font-bold bg-slate-800 ${
  6100. r.active ? (r.ecmp ? 'text-purple-300 border border-purple-500/40' : (r.multicast ? 'text-amber-300 border border-amber-500/40' : 'text-cyan-400 border border-cyan-800/40')) : (r.health_status === 'offline' ? 'text-rose-400 border border-rose-800/40' : 'text-slate-500')
  6101. }" title="Flags: ${flagDescriptions.join(', ')}">
  6102. ${flags || '-'}
  6103. </span>
  6104. </td>
  6105. <td class="py-2.5 px-3">
  6106. <div class="flex items-center gap-1.5 flex-wrap">
  6107. <span class="font-bold ${isDefault ? 'text-cyan-300' : 'text-white'}">${escapeHtml(r.dst_address)}</span>
  6108. ${r.ecmp ? `
  6109. <span class="px-1.5 py-0.2 rounded text-[9px] font-mono font-bold bg-purple-500/20 text-purple-300 border border-purple-500/30 inline-flex items-center gap-1" title="Equal-Cost Multi-Path (ECMP / Multi-gateway)">
  6110. <span>⚡ ECMP</span>
  6111. </span>
  6112. ` : ''}
  6113. ${r.multicast ? `
  6114. <span class="px-1.5 py-0.2 rounded text-[9px] font-mono font-bold bg-amber-500/20 text-amber-300 border border-amber-500/30 inline-flex items-center gap-1" title="Multicast / IGMP Group Route">
  6115. <span>IGMP</span>
  6116. </span>
  6117. ` : ''}
  6118. </div>
  6119. </td>
  6120. <td class="py-2.5 px-3">${getRouteProtocolBadge(r.protocol)}</td>
  6121. <td class="py-2.5 px-3 text-slate-300 font-mono">${r.gateway || '<span class="text-slate-600 font-sans">Direct link</span>'}</td>
  6122. <td class="py-2.5 px-3 text-slate-400 font-mono">${(r.distance !== undefined && r.distance !== null) ? r.distance : 0}</td>
  6123. <td class="py-2.5 px-3 font-mono font-semibold text-purple-300">${r.routing_table || 'main'}</td>
  6124. <td class="py-2.5 px-3 text-emerald-400 font-mono">${r.interface || '-'}</td>
  6125. <td class="py-2.5 px-3">${healthCell}</td>
  6126. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]">${r.comment || '-'}</td>
  6127. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  6128. ${r.static ? `
  6129. <button onclick="toggleRouteState('${r.id}', ${!r.disabled})" class="text-xs ${r.disabled ? 'text-emerald-400' : 'text-slate-400'} hover:underline">${r.disabled ? 'Enable' : 'Disable'}</button>
  6130. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold">Edit</button>
  6131. <button onclick="deleteRoute('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  6132. ` : `
  6133. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">View</button>
  6134. `}
  6135. </td>
  6136. `;
  6137. tbody.appendChild(tr);
  6138. });
  6139. }
  6140. function openAddRouteModal() {
  6141. document.getElementById('route-modal-title').innerText = 'Add Static Route';
  6142. document.getElementById('route-modal-id').value = '';
  6143. document.getElementById('route-modal-old-dst').value = '';
  6144. document.getElementById('route-modal-old-gw').value = '';
  6145. document.getElementById('route-modal-old-distance').value = '';
  6146. document.getElementById('route-modal-old-table').value = '';
  6147. document.getElementById('route-modal-old-iface').value = '';
  6148. const dstInput = document.getElementById('route-modal-dst');
  6149. const gwInput = document.getElementById('route-modal-gw');
  6150. const distInput = document.getElementById('route-modal-distance');
  6151. const ifaceSelect = document.getElementById('route-modal-iface');
  6152. const tableSelect = document.getElementById('route-modal-table');
  6153. const commentInput = document.getElementById('route-modal-comment');
  6154. const disCheck = document.getElementById('route-modal-disabled');
  6155. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  6156. dstInput.disabled = false;
  6157. dstInput.value = '0.0.0.0/0';
  6158. gwInput.disabled = false;
  6159. gwInput.value = '';
  6160. distInput.disabled = false;
  6161. distInput.value = '1';
  6162. ifaceSelect.disabled = false;
  6163. tableSelect.disabled = false;
  6164. commentInput.disabled = false;
  6165. commentInput.value = '';
  6166. disCheck.disabled = false;
  6167. disCheck.checked = false;
  6168. if (saveBtn) saveBtn.classList.remove('hidden');
  6169. const checkGw = document.getElementById('route-modal-check-gw');
  6170. if (checkGw) checkGw.value = 'internet';
  6171. const checkTarget = document.getElementById('route-modal-check-target');
  6172. if (checkTarget) checkTarget.value = '1.1.1.1';
  6173. const checkInterval = document.getElementById('route-modal-check-interval');
  6174. if (checkInterval) checkInterval.value = '5';
  6175. const checkThresh = document.getElementById('route-modal-check-threshold');
  6176. if (checkThresh) checkThresh.value = '3';
  6177. toggleRouteCheckModeUI();
  6178. populateInterfaceSelect('route-modal-iface');
  6179. // Populate tables
  6180. tableSelect.innerHTML = '';
  6181. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  6182. const opt = document.createElement('option');
  6183. opt.value = t.name;
  6184. opt.innerText = t.name;
  6185. if (t.name === 'main') opt.selected = true;
  6186. tableSelect.appendChild(opt);
  6187. });
  6188. document.getElementById('route-modal').classList.remove('hidden');
  6189. }
  6190. function openEditRouteModal(id) {
  6191. const r = (state.routes || []).find(route => route.id === id);
  6192. if (!r) return;
  6193. const isStatic = !!r.static;
  6194. document.getElementById('route-modal-title').innerText = isStatic
  6195. ? `Edit Route: ${r.dst_address}`
  6196. : `Route Properties (Read Only): ${r.dst_address}`;
  6197. document.getElementById('route-modal-id').value = r.id;
  6198. document.getElementById('route-modal-old-dst').value = r.dst_address || '';
  6199. document.getElementById('route-modal-old-gw').value = r.gateway || '';
  6200. document.getElementById('route-modal-old-distance').value = (r.distance !== undefined && r.distance !== null) ? r.distance : '';
  6201. document.getElementById('route-modal-old-table').value = r.routing_table || 'main';
  6202. document.getElementById('route-modal-old-iface').value = r.interface || '';
  6203. const dstInput = document.getElementById('route-modal-dst');
  6204. const gwInput = document.getElementById('route-modal-gw');
  6205. const distInput = document.getElementById('route-modal-distance');
  6206. const ifaceSelect = document.getElementById('route-modal-iface');
  6207. const tableSelect = document.getElementById('route-modal-table');
  6208. const commentInput = document.getElementById('route-modal-comment');
  6209. const disCheck = document.getElementById('route-modal-disabled');
  6210. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  6211. dstInput.value = r.dst_address;
  6212. gwInput.value = r.gateway || '';
  6213. distInput.value = (r.distance !== undefined && r.distance !== null) ? r.distance : 1;
  6214. commentInput.value = r.comment || '';
  6215. disCheck.checked = !!r.disabled;
  6216. const checkGw = document.getElementById('route-modal-check-gw');
  6217. if (checkGw) checkGw.value = r.check_gateway || 'none';
  6218. const checkTarget = document.getElementById('route-modal-check-target');
  6219. if (checkTarget) checkTarget.value = r.check_target || '1.1.1.1';
  6220. const checkInterval = document.getElementById('route-modal-check-interval');
  6221. if (checkInterval) checkInterval.value = r.check_interval || 5;
  6222. const checkThresh = document.getElementById('route-modal-check-threshold');
  6223. if (checkThresh) checkThresh.value = r.check_threshold || 3;
  6224. toggleRouteCheckModeUI();
  6225. dstInput.disabled = !isStatic;
  6226. gwInput.disabled = !isStatic;
  6227. distInput.disabled = !isStatic;
  6228. ifaceSelect.disabled = !isStatic;
  6229. tableSelect.disabled = !isStatic;
  6230. commentInput.disabled = !isStatic;
  6231. disCheck.disabled = !isStatic;
  6232. if (checkGw) checkGw.disabled = !isStatic;
  6233. if (checkTarget) checkTarget.disabled = !isStatic;
  6234. if (checkInterval) checkInterval.disabled = !isStatic;
  6235. if (checkThresh) checkThresh.disabled = !isStatic;
  6236. if (saveBtn) {
  6237. if (isStatic) {
  6238. saveBtn.classList.remove('hidden');
  6239. } else {
  6240. saveBtn.classList.add('hidden');
  6241. }
  6242. }
  6243. populateInterfaceSelect('route-modal-iface', r.interface);
  6244. tableSelect.innerHTML = '';
  6245. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  6246. const opt = document.createElement('option');
  6247. opt.value = t.name;
  6248. opt.innerText = t.name;
  6249. if (t.name === (r.routing_table || 'main')) opt.selected = true;
  6250. tableSelect.appendChild(opt);
  6251. });
  6252. document.getElementById('route-modal').classList.remove('hidden');
  6253. }
  6254. function closeRouteModal() {
  6255. document.getElementById('route-modal').classList.add('hidden');
  6256. }
  6257. function setRouteCheckTarget(ip) {
  6258. const inp = document.getElementById('route-modal-check-target');
  6259. if (inp) inp.value = ip;
  6260. }
  6261. function toggleRouteCheckModeUI() {
  6262. const mode = document.getElementById('route-modal-check-gw')?.value || 'none';
  6263. const targetRow = document.getElementById('route-row-check-target');
  6264. const paramsRow = document.getElementById('route-row-check-params');
  6265. if (mode === 'none') {
  6266. if (targetRow) targetRow.classList.add('opacity-40', 'pointer-events-none');
  6267. if (paramsRow) paramsRow.classList.add('opacity-40', 'pointer-events-none');
  6268. } else if (mode === 'ping') {
  6269. if (targetRow) targetRow.classList.add('opacity-40', 'pointer-events-none');
  6270. if (paramsRow) paramsRow.classList.remove('opacity-40', 'pointer-events-none');
  6271. } else { // internet
  6272. if (targetRow) targetRow.classList.remove('opacity-40', 'pointer-events-none');
  6273. if (paramsRow) paramsRow.classList.remove('opacity-40', 'pointer-events-none');
  6274. }
  6275. }
  6276. async function submitSaveRoute(e) {
  6277. e.preventDefault();
  6278. const id = document.getElementById('route-modal-id').value;
  6279. const oldDst = document.getElementById('route-modal-old-dst')?.value || '';
  6280. const oldGw = document.getElementById('route-modal-old-gw')?.value || '';
  6281. const oldDistStr = document.getElementById('route-modal-old-distance')?.value;
  6282. const oldTable = document.getElementById('route-modal-old-table')?.value || '';
  6283. const oldIface = document.getElementById('route-modal-old-iface')?.value || '';
  6284. const dst = document.getElementById('route-modal-dst').value.trim();
  6285. const gw = document.getElementById('route-modal-gw').value.trim();
  6286. const table = document.getElementById('route-modal-table').value;
  6287. const distance = parseInt(document.getElementById('route-modal-distance').value, 10) || 0;
  6288. const iface = document.getElementById('route-modal-iface').value;
  6289. const comment = document.getElementById('route-modal-comment').value.trim();
  6290. const disabled = document.getElementById('route-modal-disabled').checked;
  6291. const check_gateway = document.getElementById('route-modal-check-gw')?.value || 'none';
  6292. const check_target = document.getElementById('route-modal-check-target')?.value.trim() || '1.1.1.1';
  6293. const check_interval = parseInt(document.getElementById('route-modal-check-interval')?.value, 10) || 5;
  6294. const check_threshold = parseInt(document.getElementById('route-modal-check-threshold')?.value, 10) || 3;
  6295. if (!dst) {
  6296. showToast('Error', 'Destination address is required', 'error');
  6297. return;
  6298. }
  6299. if (!gw && !iface) {
  6300. showToast('Error', 'Either Gateway IP or Interface must be specified', 'error');
  6301. return;
  6302. }
  6303. const payload = {
  6304. id,
  6305. old_dst_address: oldDst,
  6306. old_gateway: oldGw,
  6307. old_routing_table: oldTable,
  6308. old_interface: oldIface,
  6309. dst_address: dst,
  6310. gateway: gw || iface,
  6311. routing_table: table,
  6312. distance,
  6313. interface: iface,
  6314. comment,
  6315. disabled,
  6316. check_gateway,
  6317. check_target,
  6318. check_interval,
  6319. check_threshold
  6320. };
  6321. if (oldDistStr !== undefined && oldDistStr !== '') {
  6322. payload.old_distance = parseInt(oldDistStr, 10);
  6323. }
  6324. try {
  6325. const res = await fetch(`${API_BASE}/routes`, {
  6326. method: 'POST',
  6327. headers: { 'Content-Type': 'application/json' },
  6328. body: JSON.stringify(payload)
  6329. });
  6330. if (res.ok) {
  6331. showToast('Route Saved', `Route to ${dst} installed`, 'success');
  6332. closeRouteModal();
  6333. loadRoutes();
  6334. } else {
  6335. const err = await res.json();
  6336. showToast('Error', err.message || 'Failed to save route', 'error');
  6337. }
  6338. } catch (err) {
  6339. showToast('Error', err.message, 'error');
  6340. }
  6341. }
  6342. async function toggleRouteState(id, disabled) {
  6343. try {
  6344. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}/state`, {
  6345. method: 'POST',
  6346. headers: { 'Content-Type': 'application/json' },
  6347. body: JSON.stringify({ disabled })
  6348. });
  6349. if (res.ok) loadRoutes();
  6350. } catch (err) {
  6351. showToast('Error', err.message, 'error');
  6352. }
  6353. }
  6354. async function deleteRoute(id) {
  6355. if (!confirm('Are you sure you want to delete this route?')) return;
  6356. try {
  6357. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6358. if (res.ok) {
  6359. showToast('Deleted', 'Route removed', 'success');
  6360. loadRoutes();
  6361. }
  6362. } catch (err) {
  6363. showToast('Error', err.message, 'error');
  6364. }
  6365. }
  6366. // ----------------- Policy Rules (/ip route rule) -----------------
  6367. function renderPolicyRules() {
  6368. const tbody = document.getElementById('rules-table-body');
  6369. const empty = document.getElementById('rules-empty');
  6370. if (!tbody) return;
  6371. const showSystem = document.getElementById('prule-show-system')?.checked;
  6372. const filtered = (state.policyRules || []).filter(pr => showSystem || (!pr.is_default && !pr.is_system));
  6373. const countBadge = document.getElementById('rules-count-badge');
  6374. if (countBadge) countBadge.innerText = `${filtered.length} Rules`;
  6375. const bRules = document.getElementById('routes-badge-rules');
  6376. if (bRules) bRules.innerText = filtered.length;
  6377. if (filtered.length === 0) {
  6378. empty?.classList.remove('hidden');
  6379. tbody.innerHTML = '';
  6380. return;
  6381. }
  6382. empty?.classList.add('hidden');
  6383. const sig = `${showSystem}|` + filtered.map(pr => `${pr.id}:${pr.priority}:${pr.src_address}:${pr.dst_address}:${pr.table}:${pr.routing_mark}`).join(';');
  6384. if (tbody.dataset.sig === sig) return;
  6385. tbody.dataset.sig = sig;
  6386. tbody.innerHTML = '';
  6387. filtered.forEach(pr => {
  6388. const isSys = pr.is_default || pr.is_system;
  6389. const tr = document.createElement('tr');
  6390. tr.className = `hover:bg-slate-800/40 transition text-xs ${isSys ? 'opacity-70 bg-slate-950/20' : ''}`;
  6391. tr.innerHTML = `
  6392. <td class="py-2.5 px-3 font-mono text-cyan-400 font-bold">${pr.priority}</td>
  6393. <td class="py-2.5 px-3 font-mono text-white">${pr.src_address || '<span class="text-slate-600">all</span>'}</td>
  6394. <td class="py-2.5 px-3 font-mono text-white">${pr.dst_address || '<span class="text-slate-600">all</span>'}</td>
  6395. <td class="py-2.5 px-3 font-mono font-bold text-purple-300">${pr.routing_mark || '<span class="text-slate-600">-</span>'}</td>
  6396. <td class="py-2.5 px-3 font-mono font-bold text-amber-300">${pr.table}</td>
  6397. <td class="py-2.5 px-3 font-mono text-slate-300">${pr.action}</td>
  6398. <td class="py-2.5 px-3 text-right font-sans">
  6399. ${!pr.is_default ? `
  6400. <button onclick="deletePolicyRule('${pr.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  6401. ` : `<span class="text-slate-600 text-[10px]">Default</span>`}
  6402. </td>
  6403. `;
  6404. tbody.appendChild(tr);
  6405. });
  6406. }
  6407. function openAddPolicyRuleModal() {
  6408. const userRules = (state.policyRules || []).filter(pr => !pr.is_default && !pr.is_system);
  6409. document.getElementById('prule-modal-pref').value = userRules.length * 10 + 1000;
  6410. document.getElementById('prule-modal-mark').value = '';
  6411. document.getElementById('prule-modal-src').value = '';
  6412. document.getElementById('prule-modal-dst').value = '';
  6413. const sel = document.getElementById('prule-modal-table');
  6414. sel.innerHTML = '';
  6415. (state.routingTables || []).forEach(t => {
  6416. const opt = document.createElement('option');
  6417. opt.value = t.name;
  6418. opt.innerText = t.name;
  6419. sel.appendChild(opt);
  6420. });
  6421. document.getElementById('prule-modal').classList.remove('hidden');
  6422. }
  6423. function closePolicyRuleModal() {
  6424. document.getElementById('prule-modal').classList.add('hidden');
  6425. }
  6426. async function submitSavePolicyRule(e) {
  6427. e.preventDefault();
  6428. const pref = parseInt(document.getElementById('prule-modal-pref').value, 10) || 1000;
  6429. const mark = document.getElementById('prule-modal-mark').value.trim();
  6430. const src = document.getElementById('prule-modal-src').value.trim();
  6431. const dst = document.getElementById('prule-modal-dst').value.trim();
  6432. const table = document.getElementById('prule-modal-table').value;
  6433. const action = document.getElementById('prule-modal-action').value;
  6434. try {
  6435. const res = await fetch(`${API_BASE}/routing/rules`, {
  6436. method: 'POST',
  6437. headers: { 'Content-Type': 'application/json' },
  6438. body: JSON.stringify({ priority: pref, routing_mark: mark, src_address: src, dst_address: dst, table, action })
  6439. });
  6440. if (res.ok) {
  6441. showToast('Rule Added', `Policy rule installed for table ${table}`, 'success');
  6442. closePolicyRuleModal();
  6443. loadRoutes();
  6444. } else {
  6445. const err = await res.json();
  6446. showToast('Error', err.message, 'error');
  6447. }
  6448. } catch (err) {
  6449. showToast('Error', err.message, 'error');
  6450. }
  6451. }
  6452. async function deletePolicyRule(id) {
  6453. if (!confirm('Are you sure you want to remove this policy rule?')) return;
  6454. try {
  6455. const res = await fetch(`${API_BASE}/routing/rules/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6456. if (res.ok) {
  6457. showToast('Rule Removed', 'Policy rule deleted', 'success');
  6458. loadRoutes();
  6459. }
  6460. } catch (err) {
  6461. showToast('Error', err.message, 'error');
  6462. }
  6463. }
  6464. // ----------------- Routing Tables -----------------
  6465. function renderRoutingTables() {
  6466. const tbody = document.getElementById('tables-table-body');
  6467. if (!tbody) return;
  6468. const tables = state.routingTables || [];
  6469. const sig = tables.map(t => `${t.table_id}:${t.name}:${t.comment}`).join(';');
  6470. if (tbody.dataset.sig === sig) return;
  6471. tbody.dataset.sig = sig;
  6472. tbody.innerHTML = '';
  6473. (state.routingTables || []).forEach(t => {
  6474. const tr = document.createElement('tr');
  6475. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  6476. tr.innerHTML = `
  6477. <td class="py-2.5 px-3 text-cyan-400 font-bold">${t.table_id}</td>
  6478. <td class="py-2.5 px-3 font-bold text-white">${t.name}</td>
  6479. <td class="py-2.5 px-3 text-slate-400 italic">${t.comment || '-'}</td>
  6480. `;
  6481. tbody.appendChild(tr);
  6482. });
  6483. }
  6484. function openAddTableModal() {
  6485. document.getElementById('table-modal-name').value = '';
  6486. document.getElementById('table-modal-id').value = '';
  6487. document.getElementById('table-modal-comment').value = '';
  6488. document.getElementById('table-modal').classList.remove('hidden');
  6489. }
  6490. function closeTableModal() {
  6491. document.getElementById('table-modal').classList.add('hidden');
  6492. }
  6493. async function submitSaveTable(e) {
  6494. e.preventDefault();
  6495. const name = document.getElementById('table-modal-name').value.trim();
  6496. const id = parseInt(document.getElementById('table-modal-id').value, 10) || 0;
  6497. const comment = document.getElementById('table-modal-comment').value.trim();
  6498. try {
  6499. const res = await fetch(`${API_BASE}/routing/tables`, {
  6500. method: 'POST',
  6501. headers: { 'Content-Type': 'application/json' },
  6502. body: JSON.stringify({ name, table_id: id, comment })
  6503. });
  6504. if (res.ok) {
  6505. showToast('Table Created', `Routing table ${name} registered`, 'success');
  6506. closeTableModal();
  6507. loadRoutes();
  6508. } else {
  6509. const err = await res.json();
  6510. showToast('Error', err.message, 'error');
  6511. }
  6512. } catch (err) {
  6513. showToast('Error', err.message, 'error');
  6514. }
  6515. }
  6516. async function loadDebianConfig() {
  6517. const view = document.getElementById('debian-config-view');
  6518. view.innerText = 'Generating live configuration...';
  6519. try {
  6520. const res = await fetch(`${API_BASE}/debian/config`);
  6521. const data = await res.json();
  6522. view.innerText = data.content || '# Empty config';
  6523. } catch (err) {
  6524. view.innerText = 'Failed to generate Debian network config.';
  6525. }
  6526. }
  6527. async function saveDebianConfig() {
  6528. try {
  6529. const res = await fetch(`${API_BASE}/debian/apply`, { method: 'POST' });
  6530. const data = await res.json();
  6531. if (res.ok) {
  6532. showToast('Configuration Saved', data.message || 'Saved to /etc/network/interfaces.d/vlans.cfg', 'success');
  6533. loadDebianConfig();
  6534. }
  6535. } catch (err) {
  6536. showToast('Error', err.message, 'error');
  6537. }
  6538. }
  6539. function showToast(title, message, type = 'info') {
  6540. const container = document.getElementById('toast-container');
  6541. const toast = document.createElement('div');
  6542. const borderColors = {
  6543. success: 'border-emerald-500/40 bg-slate-900/95 text-emerald-400',
  6544. error: 'border-rose-500/40 bg-slate-900/95 text-rose-400',
  6545. info: 'border-cyan-500/40 bg-slate-900/95 text-cyan-400'
  6546. };
  6547. toast.className = `pointer-events-auto border rounded-xl p-4 shadow-2xl backdrop-blur-md flex items-start space-x-3 w-80 transform transition-all duration-300 translate-y-2 opacity-0 ${borderColors[type] || borderColors.info}`;
  6548. toast.innerHTML = `
  6549. <div class="flex-1">
  6550. <div class="font-bold text-xs text-white">${title}</div>
  6551. <div class="text-[11px] text-slate-300 mt-0.5 leading-relaxed font-sans">${message}</div>
  6552. </div>
  6553. `;
  6554. container.appendChild(toast);
  6555. requestAnimationFrame(() => toast.classList.remove('translate-y-2', 'opacity-0'));
  6556. setTimeout(() => {
  6557. toast.classList.add('opacity-0', 'translate-y-2');
  6558. setTimeout(() => toast.remove(), 300);
  6559. }, 4000);
  6560. }
  6561. function formatTraffic(bytesPerSec) {
  6562. if (bytesPerSec < 1024) return `${Math.round(bytesPerSec)} B/s`;
  6563. const kb = bytesPerSec / 1024;
  6564. if (kb < 1024) return `${kb.toFixed(1)} KB/s`;
  6565. const mb = kb / 1024;
  6566. return `${mb.toFixed(2)} MB/s`;
  6567. }
  6568. function toggleSidebar() {
  6569. const sb = document.getElementById('sidebar');
  6570. sb.classList.toggle('-translate-x-full');
  6571. }
  6572. // ======================== EoIP (Ethernet over IP) ========================
  6573. async function loadEoIP(populate = true) {
  6574. try {
  6575. const res = await fetch(`${API_BASE}/vpn/eoip`);
  6576. const data = await res.json();
  6577. state.eoipTunnels = Array.isArray(data) ? data : [];
  6578. const badge = document.getElementById('eoip-count-badge');
  6579. if (badge) badge.innerText = `${state.eoipTunnels.length} Tunnels`;
  6580. const sideBadge = document.getElementById('badge-eoip-count');
  6581. if (sideBadge) sideBadge.innerText = state.eoipTunnels.length;
  6582. renderEoIPTunnels();
  6583. } catch (err) {
  6584. console.error('Failed to load EoIP:', err);
  6585. }
  6586. }
  6587. function renderEoIPTunnels() {
  6588. const tbody = document.getElementById('eoip-table-body');
  6589. const empty = document.getElementById('eoip-empty');
  6590. if (!tbody) return;
  6591. tbody.innerHTML = '';
  6592. const tunnels = state.eoipTunnels || [];
  6593. if (tunnels.length === 0) {
  6594. empty?.classList.remove('hidden');
  6595. return;
  6596. }
  6597. empty?.classList.add('hidden');
  6598. tunnels.forEach(t => {
  6599. const tr = document.createElement('tr');
  6600. tr.className = `hover:bg-slate-800/40 transition text-xs ${t.disabled ? 'opacity-50' : ''}`;
  6601. tr.innerHTML = `
  6602. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(t.running, t.disabled)}</td>
  6603. <td class="py-2.5 px-3 font-bold text-white font-mono">${t.name}</td>
  6604. <td class="py-2.5 px-3 font-bold text-emerald-400 font-mono">${t.tunnel_id}</td>
  6605. <td class="py-2.5 px-3 font-semibold text-emerald-400 font-mono">${t.ip_address || '<span class="text-slate-500 font-normal">Unassigned</span>'}</td>
  6606. <td class="py-2.5 px-3 text-cyan-300 font-mono">${t.remote_address}</td>
  6607. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.local_address || '(any)'}</td>
  6608. <td class="py-2.5 px-3 text-slate-300 font-mono text-[11px]">${t.mac_address || '-'}</td>
  6609. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.mtu || 1500}</td>
  6610. <td class="py-2.5 px-3 font-mono text-[11px]">
  6611. <span class="text-emerald-400">↓ ${t.rx_human || '0 B'}</span>
  6612. <span class="text-cyan-400 ml-1">↑ ${t.tx_human || '0 B'}</span>
  6613. </td>
  6614. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${t.comment || ''}">${t.comment || '-'}</td>
  6615. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  6616. <button onclick="toggleEoIPState('${t.id}', ${!t.disabled})" class="text-xs ${t.disabled ? 'text-emerald-400' : 'text-slate-400'} hover:underline">${t.disabled ? 'Enable' : 'Disable'}</button>
  6617. <button onclick="openEditEoIPModal('${t.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  6618. <button onclick="deleteEoIP('${t.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  6619. </td>
  6620. `;
  6621. tbody.appendChild(tr);
  6622. });
  6623. }
  6624. function openAddEoIPModal() {
  6625. document.getElementById('eoip-modal-title').innerText = 'Add EoIP Tunnel';
  6626. document.getElementById('eoip-modal-id').value = '';
  6627. document.getElementById('eoip-modal-name').value = `eoip-tunnel${(state.eoipTunnels || []).length + 1}`;
  6628. document.getElementById('eoip-modal-tunnelid').value = (state.eoipTunnels || []).length + 10;
  6629. document.getElementById('eoip-modal-remote').value = '';
  6630. document.getElementById('eoip-modal-ip').value = '';
  6631. document.getElementById('eoip-modal-local').value = '';
  6632. document.getElementById('eoip-modal-mac').value = '';
  6633. document.getElementById('eoip-modal-mtu').value = '1500';
  6634. document.getElementById('eoip-modal-comment').value = '';
  6635. document.getElementById('eoip-modal-clampmss').checked = true;
  6636. document.getElementById('eoip-modal-disabled').checked = false;
  6637. document.getElementById('eoip-modal').classList.remove('hidden');
  6638. }
  6639. function openEditEoIPModal(id) {
  6640. const t = (state.eoipTunnels || []).find(tun => tun.id === id);
  6641. if (!t) return;
  6642. document.getElementById('eoip-modal-title').innerText = `Edit EoIP Tunnel (${t.name})`;
  6643. document.getElementById('eoip-modal-id').value = t.id;
  6644. document.getElementById('eoip-modal-name').value = t.name;
  6645. document.getElementById('eoip-modal-tunnelid').value = t.tunnel_id;
  6646. document.getElementById('eoip-modal-remote').value = t.remote_address;
  6647. document.getElementById('eoip-modal-ip').value = t.ip_address || '';
  6648. document.getElementById('eoip-modal-local').value = t.local_address || '';
  6649. document.getElementById('eoip-modal-mac').value = t.mac_address || '';
  6650. document.getElementById('eoip-modal-mtu').value = t.mtu || 1500;
  6651. document.getElementById('eoip-modal-comment').value = t.comment || '';
  6652. document.getElementById('eoip-modal-clampmss').checked = !!t.clamp_mss;
  6653. document.getElementById('eoip-modal-disabled').checked = !!t.disabled;
  6654. document.getElementById('eoip-modal').classList.remove('hidden');
  6655. }
  6656. function closeEoIPModal() {
  6657. document.getElementById('eoip-modal').classList.add('hidden');
  6658. }
  6659. async function submitSaveEoIP(e) {
  6660. e.preventDefault();
  6661. const id = document.getElementById('eoip-modal-id').value;
  6662. const name = document.getElementById('eoip-modal-name').value.trim();
  6663. const tunnelId = parseInt(document.getElementById('eoip-modal-tunnelid').value);
  6664. const remote = document.getElementById('eoip-modal-remote').value.trim();
  6665. const ipAddress = document.getElementById('eoip-modal-ip').value.trim();
  6666. const local = document.getElementById('eoip-modal-local').value.trim();
  6667. const mac = document.getElementById('eoip-modal-mac').value.trim();
  6668. const mtu = parseInt(document.getElementById('eoip-modal-mtu').value) || 1500;
  6669. const comment = document.getElementById('eoip-modal-comment').value.trim();
  6670. const clampMss = document.getElementById('eoip-modal-clampmss').checked;
  6671. const disabled = document.getElementById('eoip-modal-disabled').checked;
  6672. try {
  6673. const res = await fetch(`${API_BASE}/vpn/eoip`, {
  6674. method: 'POST',
  6675. headers: { 'Content-Type': 'application/json' },
  6676. body: JSON.stringify({
  6677. id,
  6678. name,
  6679. tunnel_id: tunnelId,
  6680. remote_address: remote,
  6681. ip_address: ipAddress,
  6682. local_address: local,
  6683. mac_address: mac,
  6684. mtu,
  6685. clamp_mss: clampMss,
  6686. comment,
  6687. disabled
  6688. })
  6689. });
  6690. if (res.ok) {
  6691. showToast('EoIP Saved', `Tunnel ${name} configured successfully`, 'success');
  6692. closeEoIPModal();
  6693. loadEoIP(false);
  6694. fetchData(false);
  6695. } else {
  6696. const err = await res.json();
  6697. showToast('Error', err.message, 'error');
  6698. }
  6699. } catch (err) {
  6700. showToast('Error', err.message, 'error');
  6701. }
  6702. }
  6703. async function toggleEoIPState(id, disabled) {
  6704. try {
  6705. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}/state`, {
  6706. method: 'POST',
  6707. headers: { 'Content-Type': 'application/json' },
  6708. body: JSON.stringify({ disabled })
  6709. });
  6710. if (res.ok) {
  6711. showToast(disabled ? 'Disabled' : 'Enabled', 'EoIP tunnel state updated', 'info');
  6712. loadEoIP(false);
  6713. fetchData(false);
  6714. }
  6715. } catch (err) {
  6716. showToast('Error', err.message, 'error');
  6717. }
  6718. }
  6719. async function deleteEoIP(id) {
  6720. if (!confirm('Are you sure you want to delete this EoIP tunnel?')) return;
  6721. try {
  6722. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6723. if (res.ok) {
  6724. showToast('Deleted', 'EoIP tunnel removed', 'success');
  6725. loadEoIP(false);
  6726. fetchData(false);
  6727. }
  6728. } catch (err) {
  6729. showToast('Error', err.message, 'error');
  6730. }
  6731. }
  6732. // ======================== AeroTUN (Custom Encrypted VPN with Adaptive LZ4) ========================
  6733. async function loadAeroTUN(populate = true) {
  6734. try {
  6735. const [tunnelsRes, statsRes] = await Promise.all([
  6736. fetch(`${API_BASE}/vpn/aerotun/tunnels`),
  6737. fetch(`${API_BASE}/vpn/aerotun/stats`)
  6738. ]);
  6739. if (tunnelsRes.ok) {
  6740. const data = await tunnelsRes.json();
  6741. state.aerotunTunnels = Array.isArray(data) ? data : [];
  6742. }
  6743. if (statsRes.ok) {
  6744. state.aerotunStats = await statsRes.json();
  6745. }
  6746. const countBadge = document.getElementById('aerotun-count-badge');
  6747. if (countBadge) countBadge.innerText = `${(state.aerotunTunnels || []).length} Tunnels`;
  6748. const sideBadge = document.getElementById('badge-aerotun-count');
  6749. if (sideBadge) sideBadge.innerText = (state.aerotunTunnels || []).length;
  6750. renderAeroTUN();
  6751. } catch (err) {
  6752. console.error('Failed to load AeroTUN:', err);
  6753. }
  6754. }
  6755. function renderAeroTUN() {
  6756. const tbody = document.getElementById('aerotun-table-body');
  6757. const empty = document.getElementById('aerotun-empty');
  6758. // Update summary cards
  6759. const stats = state.aerotunStats || {};
  6760. const tunnels = state.aerotunTunnels || [];
  6761. const statActive = document.getElementById('aerotun-stat-active');
  6762. if (statActive) {
  6763. const activeCount = tunnels.filter(t => t.running).length;
  6764. statActive.innerText = `${activeCount} / ${tunnels.length}`;
  6765. }
  6766. const statSaved = document.getElementById('aerotun-stat-saved');
  6767. if (statSaved) {
  6768. statSaved.innerText = formatBytes(stats.total_saved_bytes || 0);
  6769. }
  6770. const statRatio = document.getElementById('aerotun-stat-ratio');
  6771. if (statRatio) {
  6772. statRatio.innerText = stats.average_ratio || '1.00x (0% saved)';
  6773. }
  6774. const statTraffic = document.getElementById('aerotun-stat-traffic');
  6775. if (statTraffic) {
  6776. statTraffic.innerText = `↓ ${formatBytes(stats.total_rx_bytes || 0)} / ↑ ${formatBytes(stats.total_tx_bytes || 0)}`;
  6777. }
  6778. if (!tbody) return;
  6779. tbody.innerHTML = '';
  6780. if (tunnels.length === 0) {
  6781. empty?.classList.remove('hidden');
  6782. return;
  6783. }
  6784. empty?.classList.add('hidden');
  6785. tunnels.forEach(t => {
  6786. const tr = document.createElement('tr');
  6787. tr.className = `hover:bg-slate-800/40 transition text-xs ${t.disabled ? 'opacity-50' : ''}`;
  6788. const modeBadge = t.mode === 'server'
  6789. ? `<span class="px-2 py-0.5 rounded text-[10px] font-mono bg-sky-500/20 text-sky-300 border border-sky-500/30 font-semibold uppercase">Server</span>`
  6790. : `<span class="px-2 py-0.5 rounded text-[10px] font-mono bg-indigo-500/20 text-indigo-300 border border-indigo-500/30 font-semibold uppercase">Client</span>`;
  6791. const endpointInfo = t.mode === 'server'
  6792. ? `<span class="text-sky-300 font-mono">Port :${t.listen_port || 51830}</span>`
  6793. : `<span class="text-indigo-300 font-mono">${escapeHtml(t.remote_endpoint || '(not set)')}</span>`;
  6794. const compBadge = t.compression
  6795. ? `<span class="px-1.5 py-0.5 rounded text-[10px] font-mono bg-emerald-500/20 text-emerald-300 border border-emerald-500/30 font-semibold" title="Adaptive LZ4 active">${t.compression_ratio || 'LZ4'}</span>`
  6796. : `<span class="text-slate-500 text-[10px]">Off</span>`;
  6797. const activePeer = t.active_peer_endpoint
  6798. ? `<span class="text-emerald-400 font-mono text-[11px]" title="Last seen: ${t.last_handshake || 'just now'}">● ${escapeHtml(t.active_peer_endpoint)}</span>`
  6799. : `<span class="text-slate-500 text-[11px]">${t.mode === 'server' ? 'Waiting for peer...' : 'Connecting...'}</span>`;
  6800. const rawRx = formatBytes(t.rx_bytes || 0);
  6801. const rawTx = formatBytes(t.tx_bytes || 0);
  6802. const wireRx = formatBytes(t.wire_bytes_in || 0);
  6803. const wireTx = formatBytes(t.wire_bytes_out || 0);
  6804. tr.innerHTML = `
  6805. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(t.running, t.disabled)}</td>
  6806. <td class="py-2.5 px-3 font-bold text-white font-mono flex items-center gap-1.5">
  6807. <span>${escapeHtml(t.name)}</span>
  6808. ${t.default_route ? '<span class="text-[9px] px-1 rounded bg-amber-500/20 text-amber-300 border border-amber-500/30">DEF</span>' : ''}
  6809. </td>
  6810. <td class="py-2.5 px-3">${modeBadge}</td>
  6811. <td class="py-2.5 px-3 text-xs font-mono">${endpointInfo}</td>
  6812. <td class="py-2.5 px-3 font-semibold text-emerald-400 font-mono">${escapeHtml(t.local_address || '-')}</td>
  6813. <td class="py-2.5 px-3">${compBadge}</td>
  6814. <td class="py-2.5 px-3">${activePeer}</td>
  6815. <td class="py-2.5 px-3 font-mono text-[11px]">
  6816. <span class="text-emerald-400">↓ ${rawRx}</span>
  6817. <span class="text-cyan-400 ml-1">↑ ${rawTx}</span>
  6818. </td>
  6819. <td class="py-2.5 px-3 font-mono text-[11px]">
  6820. <span class="text-slate-400">↓ ${wireRx}</span>
  6821. <span class="text-slate-400 ml-1">↑ ${wireTx}</span>
  6822. </td>
  6823. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(t.comment || '')}">${escapeHtml(t.comment || '-')}</td>
  6824. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  6825. ${t.running
  6826. ? `<button onclick="stopAeroTUNTunnel('${t.id}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Stop</button>`
  6827. : `<button onclick="startAeroTUNTunnel('${t.id}')" class="text-xs text-emerald-400 hover:text-emerald-300 font-medium">Start</button>`
  6828. }
  6829. <button onclick="toggleAeroTUNState('${t.id}', ${!t.disabled})" class="text-xs ${t.disabled ? 'text-emerald-400' : 'text-slate-400'} hover:underline">${t.disabled ? 'Enable' : 'Disable'}</button>
  6830. <button onclick="openEditAeroTUNModal('${t.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  6831. <button onclick="deleteAeroTUN('${t.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  6832. </td>
  6833. `;
  6834. tbody.appendChild(tr);
  6835. });
  6836. }
  6837. function onAeroTUNModeChange() {
  6838. const mode = document.getElementById('aerotun-modal-mode').value;
  6839. const endpointInput = document.getElementById('aerotun-modal-endpoint');
  6840. const portInput = document.getElementById('aerotun-modal-port');
  6841. if (mode === 'server') {
  6842. if (!portInput.value) portInput.value = '51830';
  6843. endpointInput.placeholder = 'Optional / learned roaming peer';
  6844. } else {
  6845. endpointInput.placeholder = 'vpn.example.com:51830 (required)';
  6846. if (!portInput.value) portInput.value = '';
  6847. }
  6848. }
  6849. async function generateAeroTUNKey() {
  6850. try {
  6851. const res = await fetch(`${API_BASE}/vpn/aerotun/genkey`);
  6852. if (res.ok) {
  6853. const data = await res.json();
  6854. document.getElementById('aerotun-modal-psk').value = data.key;
  6855. showToast('Key Generated', 'Cryptographic 256-bit PSK generated', 'success');
  6856. }
  6857. } catch (err) {
  6858. const arr = new Uint8Array(32);
  6859. crypto.getRandomValues(arr);
  6860. const hex = Array.from(arr).map(b => b.toString(16).padStart(2, '0')).join('');
  6861. document.getElementById('aerotun-modal-psk').value = hex;
  6862. }
  6863. }
  6864. function openAddAeroTUNModal() {
  6865. const tunnels = state.aerotunTunnels || [];
  6866. document.getElementById('aerotun-modal-title').innerText = 'Add AeroTUN Interface';
  6867. document.getElementById('aerotun-modal-id').value = '';
  6868. document.getElementById('aerotun-modal-name').value = `aerotun${tunnels.length}`;
  6869. document.getElementById('aerotun-modal-mode').value = 'server';
  6870. document.getElementById('aerotun-modal-port').value = 51830 + tunnels.length;
  6871. document.getElementById('aerotun-modal-endpoint').value = '';
  6872. document.getElementById('aerotun-modal-local').value = `10.99.${tunnels.length}.1/24`;
  6873. document.getElementById('aerotun-modal-peer').value = `10.99.${tunnels.length}.2/24`;
  6874. document.getElementById('aerotun-modal-psk').value = '';
  6875. document.getElementById('aerotun-modal-mtu').value = '1420';
  6876. document.getElementById('aerotun-modal-comment').value = '';
  6877. document.getElementById('aerotun-modal-compression').checked = true;
  6878. document.getElementById('aerotun-modal-defroute').checked = false;
  6879. document.getElementById('aerotun-modal-disabled').checked = false;
  6880. generateAeroTUNKey();
  6881. onAeroTUNModeChange();
  6882. document.getElementById('aerotun-modal').classList.remove('hidden');
  6883. }
  6884. function openEditAeroTUNModal(id) {
  6885. const t = (state.aerotunTunnels || []).find(tun => tun.id === id);
  6886. if (!t) return;
  6887. document.getElementById('aerotun-modal-title').innerText = `Edit AeroTUN Interface (${t.name})`;
  6888. document.getElementById('aerotun-modal-id').value = t.id;
  6889. document.getElementById('aerotun-modal-name').value = t.name;
  6890. document.getElementById('aerotun-modal-mode').value = t.mode || 'server';
  6891. document.getElementById('aerotun-modal-port').value = t.listen_port || '';
  6892. document.getElementById('aerotun-modal-endpoint').value = t.remote_endpoint || '';
  6893. document.getElementById('aerotun-modal-local').value = t.local_address || '';
  6894. document.getElementById('aerotun-modal-peer').value = t.peer_address || '';
  6895. document.getElementById('aerotun-modal-psk').value = t.psk || '';
  6896. document.getElementById('aerotun-modal-mtu').value = t.mtu || 1420;
  6897. document.getElementById('aerotun-modal-comment').value = t.comment || '';
  6898. document.getElementById('aerotun-modal-compression').checked = !!t.compression;
  6899. document.getElementById('aerotun-modal-defroute').checked = !!t.default_route;
  6900. document.getElementById('aerotun-modal-disabled').checked = !!t.disabled;
  6901. onAeroTUNModeChange();
  6902. document.getElementById('aerotun-modal').classList.remove('hidden');
  6903. }
  6904. function closeAeroTUNModal() {
  6905. document.getElementById('aerotun-modal').classList.add('hidden');
  6906. }
  6907. async function submitSaveAeroTUN(e) {
  6908. e.preventDefault();
  6909. const id = document.getElementById('aerotun-modal-id').value;
  6910. const name = document.getElementById('aerotun-modal-name').value.trim();
  6911. const mode = document.getElementById('aerotun-modal-mode').value;
  6912. const port = parseInt(document.getElementById('aerotun-modal-port').value) || 0;
  6913. const endpoint = document.getElementById('aerotun-modal-endpoint').value.trim();
  6914. const local = document.getElementById('aerotun-modal-local').value.trim();
  6915. const peer = document.getElementById('aerotun-modal-peer').value.trim();
  6916. const psk = document.getElementById('aerotun-modal-psk').value.trim();
  6917. const mtu = parseInt(document.getElementById('aerotun-modal-mtu').value) || 1420;
  6918. const comment = document.getElementById('aerotun-modal-comment').value.trim();
  6919. const compression = document.getElementById('aerotun-modal-compression').checked;
  6920. const defaultRoute = document.getElementById('aerotun-modal-defroute').checked;
  6921. const disabled = document.getElementById('aerotun-modal-disabled').checked;
  6922. if (mode === 'client' && !endpoint) {
  6923. showToast('Validation Error', 'Remote endpoint (host:port) is required in client mode', 'error');
  6924. return;
  6925. }
  6926. if (!psk) {
  6927. showToast('Validation Error', 'Pre-shared key (PSK) is required', 'error');
  6928. return;
  6929. }
  6930. try {
  6931. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels`, {
  6932. method: 'POST',
  6933. headers: { 'Content-Type': 'application/json' },
  6934. body: JSON.stringify({
  6935. id,
  6936. name,
  6937. mode,
  6938. listen_port: port,
  6939. remote_endpoint: endpoint,
  6940. local_address: local,
  6941. peer_address: peer,
  6942. psk,
  6943. mtu,
  6944. compression,
  6945. default_route: defaultRoute,
  6946. comment,
  6947. disabled
  6948. })
  6949. });
  6950. if (res.ok) {
  6951. showToast('AeroTUN Saved', `Tunnel ${name} configured successfully`, 'success');
  6952. closeAeroTUNModal();
  6953. loadAeroTUN(false);
  6954. fetchData(false);
  6955. } else {
  6956. const err = await res.text();
  6957. showToast('Error Saving Tunnel', err, 'error');
  6958. }
  6959. } catch (err) {
  6960. showToast('Network Error', err.message, 'error');
  6961. }
  6962. }
  6963. async function startAeroTUNTunnel(id) {
  6964. try {
  6965. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/start`, { method: 'POST' });
  6966. if (res.ok) {
  6967. showToast('AeroTUN Started', 'Tunnel interface is active', 'success');
  6968. loadAeroTUN(false);
  6969. fetchData(false);
  6970. } else {
  6971. const err = await res.text();
  6972. showToast('Failed to Start', err, 'error');
  6973. }
  6974. } catch (err) {
  6975. showToast('Error', err.message, 'error');
  6976. }
  6977. }
  6978. async function stopAeroTUNTunnel(id) {
  6979. try {
  6980. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/stop`, { method: 'POST' });
  6981. if (res.ok) {
  6982. showToast('AeroTUN Stopped', 'Tunnel stopped', 'info');
  6983. loadAeroTUN(false);
  6984. fetchData(false);
  6985. } else {
  6986. const err = await res.text();
  6987. showToast('Failed to Stop', err, 'error');
  6988. }
  6989. } catch (err) {
  6990. showToast('Error', err.message, 'error');
  6991. }
  6992. }
  6993. async function toggleAeroTUNState(id, disabled) {
  6994. try {
  6995. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/state`, {
  6996. method: 'POST',
  6997. headers: { 'Content-Type': 'application/json' },
  6998. body: JSON.stringify({ disabled })
  6999. });
  7000. if (res.ok) {
  7001. showToast('State Updated', disabled ? 'Tunnel disabled' : 'Tunnel enabled', 'info');
  7002. loadAeroTUN(false);
  7003. fetchData(false);
  7004. }
  7005. } catch (err) {
  7006. showToast('Error', err.message, 'error');
  7007. }
  7008. }
  7009. async function deleteAeroTUN(id) {
  7010. if (!confirm('Are you sure you want to delete this AeroTUN tunnel?')) return;
  7011. try {
  7012. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7013. if (res.ok) {
  7014. showToast('Deleted', 'AeroTUN tunnel removed', 'success');
  7015. loadAeroTUN(false);
  7016. fetchData(false);
  7017. }
  7018. } catch (err) {
  7019. showToast('Error', err.message, 'error');
  7020. }
  7021. }
  7022. // ======================== PPP Central Hub & Servers ========================
  7023. function switchPPPSubTab(tab) {
  7024. state.pppSubTab = tab;
  7025. const tabs = ['secrets', 'profiles', 'pppoe', 'pptp', 'l2tp', 'active'];
  7026. tabs.forEach(t => {
  7027. const panel = document.getElementById(`ppp-subtab-${t}`);
  7028. const btn = document.getElementById(`ppp-subtab-btn-${t}`);
  7029. if (panel) {
  7030. if (t === tab) panel.classList.remove('hidden');
  7031. else panel.classList.add('hidden');
  7032. }
  7033. if (btn) {
  7034. if (t === tab) {
  7035. btn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-violet-500 text-white transition flex items-center gap-2 whitespace-nowrap';
  7036. } else {
  7037. btn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-transparent text-slate-400 hover:text-slate-200 transition flex items-center gap-2 whitespace-nowrap';
  7038. }
  7039. }
  7040. });
  7041. const addBtn = document.getElementById('ppp-primary-add-btn');
  7042. if (addBtn) {
  7043. if (tab === 'secrets') addBtn.innerHTML = '<span>+ Add User (Secret)</span>';
  7044. else if (tab === 'profiles') addBtn.innerHTML = '<span>+ Add Profile</span>';
  7045. else if (tab === 'active') addBtn.innerHTML = '<span>Refresh Sessions</span>';
  7046. else addBtn.innerHTML = '<span>Save Config</span>';
  7047. }
  7048. if (tab === 'active') loadPPPSessions();
  7049. }
  7050. function openCurrentPPPModal() {
  7051. if (state.pppSubTab === 'secrets') openAddPPPSecretModal();
  7052. else if (state.pppSubTab === 'profiles') openAddPPPProfileModal();
  7053. else if (state.pppSubTab === 'active') loadPPPSessions();
  7054. else if (state.pppSubTab === 'pppoe') document.querySelector('#ppp-subtab-pppoe form')?.requestSubmit();
  7055. else if (state.pppSubTab === 'pptp') document.querySelector('#ppp-subtab-pptp form')?.requestSubmit();
  7056. else if (state.pppSubTab === 'l2tp') document.querySelector('#ppp-subtab-l2tp form')?.requestSubmit();
  7057. }
  7058. async function loadPPP(populateDropdowns = true) {
  7059. await Promise.all([
  7060. loadPPPSecrets(),
  7061. loadPPPProfiles(),
  7062. loadPPPServers(),
  7063. loadPPPSessions()
  7064. ]);
  7065. }
  7066. async function loadPPPSecrets() {
  7067. try {
  7068. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`);
  7069. const data = await res.json();
  7070. state.pppSecrets = Array.isArray(data) ? data : [];
  7071. const b = document.getElementById('ppp-badge-secrets');
  7072. if (b) b.innerText = state.pppSecrets.length;
  7073. const b2 = document.getElementById('secrets-count-badge');
  7074. if (b2) b2.innerText = `${state.pppSecrets.length} Users`;
  7075. renderPPPSecrets();
  7076. } catch (err) {
  7077. console.error('Failed to load PPP secrets:', err);
  7078. }
  7079. }
  7080. function renderPPPSecrets() {
  7081. const tbody = document.getElementById('secrets-table-body');
  7082. const empty = document.getElementById('secrets-empty');
  7083. if (!tbody) return;
  7084. tbody.innerHTML = '';
  7085. const secrets = state.pppSecrets || [];
  7086. if (secrets.length === 0) {
  7087. empty?.classList.remove('hidden');
  7088. return;
  7089. }
  7090. empty?.classList.add('hidden');
  7091. secrets.forEach(s => {
  7092. const tr = document.createElement('tr');
  7093. tr.className = `hover:bg-slate-800/40 transition text-xs ${s.disabled ? 'opacity-50' : ''}`;
  7094. tr.innerHTML = `
  7095. <td class="py-2.5 px-3 text-center">${renderRuleFlag(s.disabled, !!s.comment)}</td>
  7096. <td class="py-2.5 px-3 font-bold text-white font-mono">${s.name}</td>
  7097. <td class="py-2.5 px-3 text-purple-300 font-mono font-semibold">${s.service}</td>
  7098. <td class="py-2.5 px-3 text-amber-300 font-mono">${s.profile}</td>
  7099. <td class="py-2.5 px-3 text-slate-400 font-mono">${s.local_address || '(profile)'}</td>
  7100. <td class="py-2.5 px-3 text-cyan-400 font-mono font-bold">${s.remote_address || '(profile)'}</td>
  7101. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]">${s.comment || '-'}</td>
  7102. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  7103. <button onclick="togglePPPSecretState('${s.id}', ${!s.disabled})" class="text-xs ${s.disabled ? 'text-emerald-400' : 'text-slate-400'} hover:underline">${s.disabled ? 'Enable' : 'Disable'}</button>
  7104. <button onclick="openEditPPPSecretModal('${s.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  7105. <button onclick="deletePPPSecret('${s.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  7106. </td>
  7107. `;
  7108. tbody.appendChild(tr);
  7109. });
  7110. }
  7111. async function loadPPPProfiles() {
  7112. try {
  7113. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`);
  7114. const data = await res.json();
  7115. state.pppProfiles = Array.isArray(data) ? data : [];
  7116. const b = document.getElementById('ppp-badge-profiles');
  7117. if (b) b.innerText = state.pppProfiles.length;
  7118. const b2 = document.getElementById('profiles-count-badge');
  7119. if (b2) b2.innerText = `${state.pppProfiles.length} Profiles`;
  7120. // Populate profile selects across modals
  7121. const selects = ['secret-modal-profile', 'pppoe-server-profile', 'pptp-server-profile', 'l2tp-server-profile'];
  7122. selects.forEach(sid => {
  7123. const el = document.getElementById(sid);
  7124. if (!el) return;
  7125. const cur = el.value;
  7126. el.innerHTML = '';
  7127. state.pppProfiles.forEach(p => {
  7128. const opt = document.createElement('option');
  7129. opt.value = p.name;
  7130. opt.innerText = `${p.name} (${p.remote_address})`;
  7131. if (p.name === cur) opt.selected = true;
  7132. el.appendChild(opt);
  7133. });
  7134. });
  7135. renderPPPProfiles();
  7136. } catch (err) {
  7137. console.error('Failed to load PPP profiles:', err);
  7138. }
  7139. }
  7140. function renderPPPProfiles() {
  7141. const tbody = document.getElementById('profiles-table-body');
  7142. if (!tbody) return;
  7143. tbody.innerHTML = '';
  7144. (state.pppProfiles || []).forEach(p => {
  7145. const isDefault = p.name.startsWith('default');
  7146. const tr = document.createElement('tr');
  7147. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  7148. tr.innerHTML = `
  7149. <td class="py-2.5 px-3 font-bold text-white">${p.name}</td>
  7150. <td class="py-2.5 px-3 text-slate-300">${p.local_address}</td>
  7151. <td class="py-2.5 px-3 text-cyan-400 font-bold">${p.remote_address}</td>
  7152. <td class="py-2.5 px-3 text-slate-400">${p.dns_servers || '-'}</td>
  7153. <td class="py-2.5 px-3 text-purple-300 font-semibold">${p.use_encryption}</td>
  7154. <td class="py-2.5 px-3 text-center">${p.only_one ? '<span class="text-emerald-400">yes</span>' : '<span class="text-slate-500">no</span>'}</td>
  7155. <td class="py-2.5 px-3 text-slate-400 italic">${p.comment || '-'}</td>
  7156. <td class="py-2.5 px-3 text-right font-sans whitespace-nowrap">
  7157. ${!isDefault ? `<button onclick="deletePPPProfile('${p.name}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>` : `<span class="text-slate-600 text-[10px]">Built-in</span>`}
  7158. </td>
  7159. `;
  7160. tbody.appendChild(tr);
  7161. });
  7162. }
  7163. async function loadPPPServers() {
  7164. try {
  7165. const [pppoeRes, pptpRes, l2tpRes, ipsecRes] = await Promise.all([
  7166. fetch(`${API_BASE}/vpn/servers/pppoe`),
  7167. fetch(`${API_BASE}/vpn/servers/pptp`),
  7168. fetch(`${API_BASE}/vpn/servers/l2tp`),
  7169. fetch(`${API_BASE}/vpn/servers/ipsec`)
  7170. ]);
  7171. if (pppoeRes.ok) {
  7172. state.pppoeServer = await pppoeRes.json();
  7173. const s = state.pppoeServer;
  7174. document.getElementById('pppoe-server-enabled').checked = !!s.enabled;
  7175. document.getElementById('pppoe-server-name').value = s.service_name || 'proxmox-pppoe';
  7176. populateInterfaceSelect('pppoe-server-iface', s.interface || 'eth0');
  7177. document.getElementById('pppoe-server-profile').value = s.default_profile || 'default';
  7178. document.getElementById('pppoe-server-mtu').value = s.max_mtu || 1480;
  7179. document.getElementById('pppoe-server-onesession').checked = !!s.one_session_per_host;
  7180. const pill = document.getElementById('pppoe-server-status-pill');
  7181. if (pill) {
  7182. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  7183. pill.className = s.running ? 'px-2 py-0.5 rounded text-[10px] font-mono font-semibold bg-blue-500/20 text-blue-300 border border-blue-500/40' : 'px-2 py-0.5 rounded text-[10px] font-mono font-semibold bg-slate-800 text-slate-400';
  7184. }
  7185. setDotBadge('ppp-badge-pppoe-state', s.running);
  7186. }
  7187. if (pptpRes.ok) {
  7188. state.pptpServer = await pptpRes.json();
  7189. const s = state.pptpServer;
  7190. document.getElementById('pptp-server-enabled').checked = !!s.enabled;
  7191. document.getElementById('pptp-server-port').value = s.port || 1723;
  7192. document.getElementById('pptp-server-profile').value = s.default_profile || 'default-encryption';
  7193. document.getElementById('pptp-server-mppe').checked = s.require_mppe !== false;
  7194. const pill = document.getElementById('pptp-server-status-pill');
  7195. if (pill) {
  7196. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  7197. pill.className = s.running ? 'px-2 py-0.5 rounded text-[10px] font-mono font-semibold bg-purple-500/20 text-purple-300 border border-purple-500/40' : 'px-2 py-0.5 rounded text-[10px] font-mono font-semibold bg-slate-800 text-slate-400';
  7198. }
  7199. setDotBadge('ppp-badge-pptp-state', s.running);
  7200. }
  7201. if (l2tpRes.ok) {
  7202. state.l2tpServer = await l2tpRes.json();
  7203. const s = state.l2tpServer;
  7204. document.getElementById('l2tp-server-enabled').checked = !!s.enabled;
  7205. document.getElementById('l2tp-server-port').value = s.port || 1701;
  7206. document.getElementById('l2tp-server-profile').value = s.default_profile || 'default';
  7207. document.getElementById('l2tp-server-useipsec').value = s.use_ipsec || 'no';
  7208. document.getElementById('l2tp-server-ipsecsecret').value = s.ipsec_secret || '';
  7209. const pill = document.getElementById('l2tp-server-status-pill');
  7210. if (pill) {
  7211. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  7212. pill.className = s.running ? 'px-2 py-0.5 rounded text-[10px] font-mono font-semibold bg-cyan-500/20 text-cyan-300 border border-cyan-500/40' : 'px-2 py-0.5 rounded text-[10px] font-mono font-semibold bg-slate-800 text-slate-400';
  7213. }
  7214. setDotBadge('ppp-badge-l2tp-state', s.running);
  7215. }
  7216. if (ipsecRes.ok) {
  7217. state.ipsecServer = await ipsecRes.json();
  7218. const s = state.ipsecServer;
  7219. const modalEn = document.getElementById('modal-ipsec-server-enabled');
  7220. if (modalEn) modalEn.checked = !!s.enabled;
  7221. const modalPsk = document.getElementById('modal-ipsec-server-psk');
  7222. if (modalPsk) modalPsk.value = s.preshared_key || '';
  7223. const modalPool = document.getElementById('modal-ipsec-server-pool');
  7224. if (modalPool) modalPool.value = s.pool_address || '10.10.30.0/24';
  7225. const modalDns = document.getElementById('modal-ipsec-server-dns');
  7226. if (modalDns) modalDns.value = s.dns_servers || '1.1.1.1,8.8.8.8';
  7227. const modalSubnet = document.getElementById('modal-ipsec-server-subnet');
  7228. if (modalSubnet) modalSubnet.value = s.local_subnet || '0.0.0.0/0';
  7229. const pill = document.getElementById('modal-ipsec-server-status');
  7230. if (pill) {
  7231. pill.innerText = s.running ? 'ACTIVE RESPONDER' : 'STOPPED';
  7232. pill.className = s.running ? 'px-2 py-0.5 rounded text-[10px] font-mono font-semibold bg-amber-500/20 text-amber-300 border border-amber-500/40' : 'px-2 py-0.5 rounded text-[10px] font-mono font-semibold bg-slate-800 text-slate-400';
  7233. }
  7234. }
  7235. } catch (err) {
  7236. console.error('Failed to load VPN servers:', err);
  7237. }
  7238. }
  7239. async function loadPPPSessions() {
  7240. try {
  7241. const res = await fetch(`${API_BASE}/vpn/ppp/active`);
  7242. const data = await res.json();
  7243. state.pppActiveSessions = Array.isArray(data) ? data : [];
  7244. const b = document.getElementById('ppp-badge-active');
  7245. if (b) b.innerText = state.pppActiveSessions.length;
  7246. const sideB = document.getElementById('badge-ppp-sessions');
  7247. if (sideB) sideB.innerText = state.pppActiveSessions.length;
  7248. renderPPPSessions();
  7249. } catch (err) {
  7250. console.error('Failed to load active PPP sessions:', err);
  7251. }
  7252. }
  7253. function renderPPPSessions() {
  7254. const tbody = document.getElementById('active-ppp-table-body');
  7255. const empty = document.getElementById('active-ppp-empty');
  7256. if (!tbody) return;
  7257. tbody.innerHTML = '';
  7258. const list = state.pppActiveSessions || [];
  7259. if (list.length === 0) {
  7260. empty?.classList.remove('hidden');
  7261. return;
  7262. }
  7263. empty?.classList.add('hidden');
  7264. list.forEach(s => {
  7265. const tr = document.createElement('tr');
  7266. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  7267. tr.innerHTML = `
  7268. <td class="py-2.5 px-3 font-bold text-white">${s.interface}</td>
  7269. <td class="py-2.5 px-3 font-semibold text-violet-300">${s.username}</td>
  7270. <td class="py-2.5 px-3 text-cyan-400 uppercase">${s.service}</td>
  7271. <td class="py-2.5 px-3 text-emerald-400 font-bold">${s.address || '-'}</td>
  7272. <td class="py-2.5 px-3 text-slate-400">${s.uptime}</td>
  7273. <td class="py-2.5 px-3 text-[11px]">
  7274. <span class="text-emerald-400">↓ ${s.rx_human || '0 B'}</span>
  7275. <span class="text-cyan-400 ml-1">↑ ${s.tx_human || '0 B'}</span>
  7276. </td>
  7277. <td class="py-2.5 px-3 text-right font-sans">
  7278. <button onclick="disconnectPPPSession('${s.interface}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  7279. </td>
  7280. `;
  7281. tbody.appendChild(tr);
  7282. });
  7283. }
  7284. async function disconnectPPPSession(iface) {
  7285. if (!confirm(`Disconnect session ${iface}?`)) return;
  7286. try {
  7287. const res = await fetch(`${API_BASE}/vpn/ppp/active/${encodeURIComponent(iface)}`, { method: 'DELETE' });
  7288. if (res.ok) {
  7289. showToast('Disconnected', `Session ${iface} terminated`, 'info');
  7290. loadPPPSessions();
  7291. }
  7292. } catch (err) {
  7293. showToast('Error', err.message, 'error');
  7294. }
  7295. }
  7296. // PPP Secret Modal handlers
  7297. function openAddPPPSecretModal() {
  7298. document.getElementById('secret-modal-title').innerText = 'Add PPP Secret';
  7299. document.getElementById('secret-modal-id').value = '';
  7300. document.getElementById('secret-modal-name').value = '';
  7301. document.getElementById('secret-modal-password').value = '';
  7302. document.getElementById('secret-modal-service').value = 'any';
  7303. document.getElementById('secret-modal-profile').value = 'default';
  7304. document.getElementById('secret-modal-local').value = '';
  7305. document.getElementById('secret-modal-remote').value = '';
  7306. document.getElementById('secret-modal-comment').value = '';
  7307. document.getElementById('secret-modal-disabled').checked = false;
  7308. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  7309. }
  7310. function openEditPPPSecretModal(id) {
  7311. const s = (state.pppSecrets || []).find(sec => sec.id === id);
  7312. if (!s) return;
  7313. document.getElementById('secret-modal-title').innerText = `Edit PPP Secret (${s.name})`;
  7314. document.getElementById('secret-modal-id').value = s.id;
  7315. document.getElementById('secret-modal-name').value = s.name;
  7316. document.getElementById('secret-modal-password').value = s.password;
  7317. document.getElementById('secret-modal-service').value = s.service || 'any';
  7318. document.getElementById('secret-modal-profile').value = s.profile || 'default';
  7319. document.getElementById('secret-modal-local').value = s.local_address || '';
  7320. document.getElementById('secret-modal-remote').value = s.remote_address || '';
  7321. document.getElementById('secret-modal-comment').value = s.comment || '';
  7322. document.getElementById('secret-modal-disabled').checked = !!s.disabled;
  7323. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  7324. }
  7325. function closePPPSecretModal() {
  7326. document.getElementById('ppp-secret-modal').classList.add('hidden');
  7327. }
  7328. async function submitSavePPPSecret(e) {
  7329. e.preventDefault();
  7330. const id = document.getElementById('secret-modal-id').value;
  7331. const name = document.getElementById('secret-modal-name').value.trim();
  7332. const password = document.getElementById('secret-modal-password').value.trim();
  7333. const service = document.getElementById('secret-modal-service').value;
  7334. const profile = document.getElementById('secret-modal-profile').value;
  7335. const local = document.getElementById('secret-modal-local').value.trim();
  7336. const remote = document.getElementById('secret-modal-remote').value.trim();
  7337. const comment = document.getElementById('secret-modal-comment').value.trim();
  7338. const disabled = document.getElementById('secret-modal-disabled').checked;
  7339. try {
  7340. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`, {
  7341. method: 'POST',
  7342. headers: { 'Content-Type': 'application/json' },
  7343. body: JSON.stringify({
  7344. id,
  7345. name,
  7346. password,
  7347. service,
  7348. profile,
  7349. local_address: local,
  7350. remote_address: remote,
  7351. comment,
  7352. disabled
  7353. })
  7354. });
  7355. if (res.ok) {
  7356. showToast('Secret Saved', `User ${name} saved to PPP database`, 'success');
  7357. closePPPSecretModal();
  7358. loadPPPSecrets();
  7359. } else {
  7360. const err = await res.json();
  7361. showToast('Error', err.message, 'error');
  7362. }
  7363. } catch (err) {
  7364. showToast('Error', err.message, 'error');
  7365. }
  7366. }
  7367. async function togglePPPSecretState(id, disabled) {
  7368. try {
  7369. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}/state`, {
  7370. method: 'POST',
  7371. headers: { 'Content-Type': 'application/json' },
  7372. body: JSON.stringify({ disabled })
  7373. });
  7374. if (res.ok) {
  7375. showToast(disabled ? 'Disabled' : 'Enabled', 'Secret user state updated', 'info');
  7376. loadPPPSecrets();
  7377. }
  7378. } catch (err) {
  7379. showToast('Error', err.message, 'error');
  7380. }
  7381. }
  7382. async function deletePPPSecret(id) {
  7383. if (!confirm('Are you sure you want to delete this secret account?')) return;
  7384. try {
  7385. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7386. if (res.ok) {
  7387. showToast('Deleted', 'Secret account removed', 'success');
  7388. loadPPPSecrets();
  7389. }
  7390. } catch (err) {
  7391. showToast('Error', err.message, 'error');
  7392. }
  7393. }
  7394. // PPP Profile Modal handlers
  7395. function openAddPPPProfileModal() {
  7396. document.getElementById('profile-modal-name').value = '';
  7397. document.getElementById('profile-modal-local').value = '10.10.10.1';
  7398. document.getElementById('profile-modal-remote').value = '10.10.10.10-10.10.10.50';
  7399. document.getElementById('profile-modal-dns').value = '1.1.1.1,8.8.8.8';
  7400. document.getElementById('profile-modal-encryption').value = 'required';
  7401. document.getElementById('profile-modal-onlyone').checked = true;
  7402. document.getElementById('profile-modal-comment').value = '';
  7403. document.getElementById('ppp-profile-modal').classList.remove('hidden');
  7404. }
  7405. function closePPPProfileModal() {
  7406. document.getElementById('ppp-profile-modal').classList.add('hidden');
  7407. }
  7408. async function submitSavePPPProfile(e) {
  7409. e.preventDefault();
  7410. const name = document.getElementById('profile-modal-name').value.trim();
  7411. const local = document.getElementById('profile-modal-local').value.trim();
  7412. const remote = document.getElementById('profile-modal-remote').value.trim();
  7413. const dns = document.getElementById('profile-modal-dns').value.trim();
  7414. const enc = document.getElementById('profile-modal-encryption').value;
  7415. const onlyone = document.getElementById('profile-modal-onlyone').checked;
  7416. const comment = document.getElementById('profile-modal-comment').value.trim();
  7417. try {
  7418. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`, {
  7419. method: 'POST',
  7420. headers: { 'Content-Type': 'application/json' },
  7421. body: JSON.stringify({
  7422. id: name,
  7423. name,
  7424. local_address: local,
  7425. remote_address: remote,
  7426. dns_servers: dns,
  7427. use_encryption: enc,
  7428. only_one: onlyone,
  7429. comment
  7430. })
  7431. });
  7432. if (res.ok) {
  7433. showToast('Profile Saved', `PPP profile ${name} created`, 'success');
  7434. closePPPProfileModal();
  7435. loadPPPProfiles();
  7436. } else {
  7437. const err = await res.json();
  7438. showToast('Error', err.message, 'error');
  7439. }
  7440. } catch (err) {
  7441. showToast('Error', err.message, 'error');
  7442. }
  7443. }
  7444. async function deletePPPProfile(name) {
  7445. if (!confirm(`Delete PPP profile ${name}?`)) return;
  7446. try {
  7447. const res = await fetch(`${API_BASE}/vpn/ppp/profiles/${encodeURIComponent(name)}`, { method: 'DELETE' });
  7448. if (res.ok) {
  7449. showToast('Deleted', 'Profile removed', 'success');
  7450. loadPPPProfiles();
  7451. } else {
  7452. const err = await res.json();
  7453. showToast('Error', err.message, 'error');
  7454. }
  7455. } catch (err) {
  7456. showToast('Error', err.message, 'error');
  7457. }
  7458. }
  7459. // Server Config submissions
  7460. async function savePPPoEServerConfig(e) {
  7461. e.preventDefault();
  7462. const enabled = document.getElementById('pppoe-server-enabled').checked;
  7463. const name = document.getElementById('pppoe-server-name').value.trim();
  7464. const iface = document.getElementById('pppoe-server-iface').value;
  7465. const profile = document.getElementById('pppoe-server-profile').value;
  7466. const mtu = parseInt(document.getElementById('pppoe-server-mtu').value) || 1480;
  7467. const onesession = document.getElementById('pppoe-server-onesession').checked;
  7468. try {
  7469. const res = await fetch(`${API_BASE}/vpn/servers/pppoe`, {
  7470. method: 'POST',
  7471. headers: { 'Content-Type': 'application/json' },
  7472. body: JSON.stringify({
  7473. enabled,
  7474. service_name: name,
  7475. interface: iface,
  7476. default_profile: profile,
  7477. max_mtu: mtu,
  7478. max_mru: mtu,
  7479. one_session_per_host: onesession
  7480. })
  7481. });
  7482. if (res.ok) {
  7483. showToast('PPPoE Server', enabled ? 'PPPoE Server started' : 'PPPoE Server stopped', 'success');
  7484. loadPPPServers();
  7485. fetchData(false);
  7486. } else {
  7487. const err = await res.json();
  7488. showToast('Error', err.message, 'error');
  7489. }
  7490. } catch (err) {
  7491. showToast('Error', err.message, 'error');
  7492. }
  7493. }
  7494. async function savePPTPServerConfig(e) {
  7495. e.preventDefault();
  7496. const enabled = document.getElementById('pptp-server-enabled').checked;
  7497. const port = parseInt(document.getElementById('pptp-server-port').value) || 1723;
  7498. const profile = document.getElementById('pptp-server-profile').value;
  7499. const mppe = document.getElementById('pptp-server-mppe').checked;
  7500. try {
  7501. const res = await fetch(`${API_BASE}/vpn/servers/pptp`, {
  7502. method: 'POST',
  7503. headers: { 'Content-Type': 'application/json' },
  7504. body: JSON.stringify({
  7505. enabled,
  7506. port,
  7507. default_profile: profile,
  7508. require_mppe: mppe
  7509. })
  7510. });
  7511. if (res.ok) {
  7512. showToast('PPTP Server', enabled ? 'PPTP Server started' : 'PPTP Server stopped', 'success');
  7513. loadPPPServers();
  7514. fetchData(false);
  7515. } else {
  7516. const err = await res.json();
  7517. showToast('Error', err.message, 'error');
  7518. }
  7519. } catch (err) {
  7520. showToast('Error', err.message, 'error');
  7521. }
  7522. }
  7523. async function saveL2TPServerConfig(e) {
  7524. e.preventDefault();
  7525. const enabled = document.getElementById('l2tp-server-enabled').checked;
  7526. const port = parseInt(document.getElementById('l2tp-server-port').value) || 1701;
  7527. const profile = document.getElementById('l2tp-server-profile').value;
  7528. const useipsec = document.getElementById('l2tp-server-useipsec').value;
  7529. const psk = document.getElementById('l2tp-server-ipsecsecret').value.trim();
  7530. try {
  7531. const res = await fetch(`${API_BASE}/vpn/servers/l2tp`, {
  7532. method: 'POST',
  7533. headers: { 'Content-Type': 'application/json' },
  7534. body: JSON.stringify({
  7535. enabled,
  7536. port,
  7537. default_profile: profile,
  7538. use_ipsec: useipsec,
  7539. ipsec_secret: psk
  7540. })
  7541. });
  7542. if (res.ok) {
  7543. showToast('L2TP Server', enabled ? 'L2TP Server started' : 'L2TP Server stopped', 'success');
  7544. loadPPPServers();
  7545. fetchData(false);
  7546. } else {
  7547. const err = await res.json();
  7548. showToast('Error', err.message, 'error');
  7549. }
  7550. } catch (err) {
  7551. showToast('Error', err.message, 'error');
  7552. }
  7553. }
  7554. // IPSec Server Modal
  7555. function openIPSecServerModal() {
  7556. loadPPPServers();
  7557. document.getElementById('ipsec-server-modal').classList.remove('hidden');
  7558. }
  7559. function closeIPSecServerModal() {
  7560. document.getElementById('ipsec-server-modal').classList.add('hidden');
  7561. }
  7562. async function submitSaveIPSecServer(e) {
  7563. e.preventDefault();
  7564. const enabled = document.getElementById('modal-ipsec-server-enabled').checked;
  7565. const psk = document.getElementById('modal-ipsec-server-psk').value.trim();
  7566. const pool = document.getElementById('modal-ipsec-server-pool').value.trim();
  7567. const dns = document.getElementById('modal-ipsec-server-dns').value.trim();
  7568. const subnet = document.getElementById('modal-ipsec-server-subnet').value.trim();
  7569. try {
  7570. const res = await fetch(`${API_BASE}/vpn/servers/ipsec`, {
  7571. method: 'POST',
  7572. headers: { 'Content-Type': 'application/json' },
  7573. body: JSON.stringify({
  7574. enabled,
  7575. preshared_key: psk,
  7576. pool_address: pool,
  7577. dns_servers: dns,
  7578. local_subnet: subnet
  7579. })
  7580. });
  7581. if (res.ok) {
  7582. showToast('IPSec Server', enabled ? 'IKEv2 Roadwarrior responder active' : 'IPSec Server stopped', 'success');
  7583. closeIPSecServerModal();
  7584. loadPPPServers();
  7585. fetchData(false);
  7586. } else {
  7587. const err = await res.json();
  7588. showToast('Error', err.message, 'error');
  7589. }
  7590. } catch (err) {
  7591. showToast('Error', err.message, 'error');
  7592. }
  7593. }
  7594. // WireGuard Client Config Viewer
  7595. let currentWGClientConf = '';
  7596. async function openWGClientConfModal(iface, clientIP) {
  7597. try {
  7598. const res = await fetch(`${API_BASE}/vpn/wireguard/client-config`, {
  7599. method: 'POST',
  7600. headers: { 'Content-Type': 'application/json' },
  7601. body: JSON.stringify({
  7602. interface: iface,
  7603. address: clientIP || '10.10.0.2/32',
  7604. dns: '1.1.1.1, 8.8.8.8'
  7605. })
  7606. });
  7607. if (res.ok) {
  7608. const data = await res.json();
  7609. currentWGClientConf = data.config;
  7610. document.getElementById('wg-client-conf-text').value = currentWGClientConf;
  7611. document.getElementById('wg-client-conf-modal').classList.remove('hidden');
  7612. } else {
  7613. const err = await res.json();
  7614. showToast('Error', err.message, 'error');
  7615. }
  7616. } catch (err) {
  7617. showToast('Error', err.message, 'error');
  7618. }
  7619. }
  7620. function closeWGClientConfModal() {
  7621. document.getElementById('wg-client-conf-modal').classList.add('hidden');
  7622. }
  7623. function copyWGClientConf() {
  7624. if (!currentWGClientConf) return;
  7625. copyToClipboard(currentWGClientConf, 'WireGuard Client Profile');
  7626. }
  7627. function downloadWGClientConf() {
  7628. if (!currentWGClientConf) return;
  7629. const blob = new Blob([currentWGClientConf], { type: 'text/plain;charset=utf-8' });
  7630. const a = document.createElement('a');
  7631. a.href = URL.createObjectURL(blob);
  7632. a.download = 'wireguard-client.conf';
  7633. document.body.appendChild(a);
  7634. a.click();
  7635. document.body.removeChild(a);
  7636. showToast('Downloaded', 'wireguard-client.conf saved', 'success');
  7637. }
  7638. // =========================================================================
  7639. // DYNAMIC ROUTING (FRRouting BGP & OSPFv2)
  7640. // =========================================================================
  7641. state.activeDynSubTab = 'bgp-peers';
  7642. state.activeBgpSubTab = 'bgp-peers';
  7643. state.activeOspfTab = 'instances';
  7644. state.bgpInstance = null;
  7645. state.bgpPeers = [];
  7646. state.bgpNets = [];
  7647. state.bgpRoutes = [];
  7648. state.ospfInstance = null;
  7649. state.ospfInstances = [];
  7650. state.ospfAreas = [];
  7651. state.ospfAreaRanges = [];
  7652. state.ospfTemplates = [];
  7653. state.ospfLiveInterfaces = [];
  7654. state.ospfStaticNbrs = [];
  7655. state.ospfNeighbors = [];
  7656. state.ospfLSA = [];
  7657. state.ospfRoutes = [];
  7658. state.selectedOspfRow = {
  7659. instances: null,
  7660. areas: null,
  7661. 'area-ranges': null,
  7662. templates: null,
  7663. interfaces: null,
  7664. 'static-nbrs': null,
  7665. neighbors: null,
  7666. lsa: null,
  7667. };
  7668. state.ospfSort = {
  7669. instances: { col: 'name', asc: true },
  7670. areas: { col: 'name', asc: true },
  7671. ranges: { col: 'area', asc: true },
  7672. templates: { col: 'interfaces', asc: true },
  7673. live_ifaces: { col: 'interface', asc: true },
  7674. snbrs: { col: 'address', asc: true },
  7675. neighbors: { col: 'address', asc: true },
  7676. lsa: { col: 'instance', asc: true },
  7677. };
  7678. function switchBgpSubTab(subTab) {
  7679. state.activeBgpSubTab = subTab;
  7680. const tabs = ['bgp-peers', 'bgp-nets', 'bgp-routes'];
  7681. tabs.forEach(t => {
  7682. const el = document.getElementById(`dyn-subtab-${t}`);
  7683. const btn = document.getElementById(`bgp-subtab-btn-${t}`);
  7684. if (el) el.classList.toggle('hidden', t !== subTab);
  7685. if (btn) {
  7686. if (t === subTab) {
  7687. btn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-purple-500 text-white transition flex items-center gap-2 whitespace-nowrap';
  7688. } else {
  7689. btn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-transparent text-slate-400 hover:text-slate-200 transition flex items-center gap-2 whitespace-nowrap';
  7690. }
  7691. }
  7692. });
  7693. }
  7694. function switchOspfTab(tabName) {
  7695. state.activeOspfTab = tabName;
  7696. const tabs = ['instances', 'areas', 'area-ranges', 'templates', 'interfaces', 'static-nbrs', 'neighbors', 'lsa'];
  7697. tabs.forEach(t => {
  7698. const pane = document.getElementById(`ospf-pane-${t}`);
  7699. const btn = document.getElementById(`ospf-tab-btn-${t}`);
  7700. if (pane) pane.classList.toggle('hidden', t !== tabName);
  7701. if (btn) {
  7702. if (t === tabName) {
  7703. btn.className = 'px-3 py-2 text-xs font-semibold border-b-2 border-sky-500 text-white transition flex items-center gap-1.5 whitespace-nowrap';
  7704. } else {
  7705. btn.className = 'px-3 py-2 text-xs font-semibold border-b-2 border-transparent text-slate-400 hover:text-white transition flex items-center gap-1.5 whitespace-nowrap';
  7706. }
  7707. }
  7708. });
  7709. }
  7710. function switchOspfSubTab(tab) {
  7711. // Legacy alias
  7712. if (tab === 'ospf-ifaces') switchOspfTab('templates');
  7713. else if (tab === 'ospf-areas') switchOspfTab('areas');
  7714. else if (tab === 'ospf-nbrs') switchOspfTab('neighbors');
  7715. else switchOspfTab('instances');
  7716. }
  7717. function switchDynSubTab(subTab) {
  7718. if (subTab.startsWith('bgp')) {
  7719. if (state.activeTab !== 'bgp') navigate('bgp');
  7720. switchBgpSubTab(subTab);
  7721. } else if (subTab.startsWith('ospf')) {
  7722. if (state.activeTab !== 'ospf') navigate('ospf');
  7723. switchOspfTab('instances');
  7724. }
  7725. }
  7726. async function loadDynamicRouting(showToastMsg = false) {
  7727. try {
  7728. const fetchSafeJson = async (url) => {
  7729. try {
  7730. const r = await fetch(url);
  7731. return r.ok ? await r.json() : null;
  7732. } catch (e) {
  7733. return null;
  7734. }
  7735. };
  7736. const [
  7737. sum, bgpInst, bgpPeers, bgpNets, bgpRoutes,
  7738. ospfInsts, ospfAreas, ospfRanges, ospfTemplates, ospfLiveIfaces, ospfStaticNbrs, ospfNbrs, ospfLsa, filters,
  7739. selectRules, commLists, asLists
  7740. ] = await Promise.all([
  7741. fetchSafeJson(`${API_BASE}/routing/dynamic/summary`),
  7742. fetchSafeJson(`${API_BASE}/routing/bgp/instance`),
  7743. fetchSafeJson(`${API_BASE}/routing/bgp/peers`),
  7744. fetchSafeJson(`${API_BASE}/routing/bgp/networks`),
  7745. fetchSafeJson(`${API_BASE}/routing/bgp/routes`),
  7746. fetchSafeJson(`${API_BASE}/routing/ospf/instances`),
  7747. fetchSafeJson(`${API_BASE}/routing/ospf/areas`),
  7748. fetchSafeJson(`${API_BASE}/routing/ospf/area-ranges`),
  7749. fetchSafeJson(`${API_BASE}/routing/ospf/templates`),
  7750. fetchSafeJson(`${API_BASE}/routing/ospf/interfaces-live`),
  7751. fetchSafeJson(`${API_BASE}/routing/ospf/static-neighbors`),
  7752. fetchSafeJson(`${API_BASE}/routing/ospf/neighbors`),
  7753. fetchSafeJson(`${API_BASE}/routing/ospf/lsa`),
  7754. fetchSafeJson(`${API_BASE}/routing/filters`),
  7755. fetchSafeJson(`${API_BASE}/routing/filters/select-rules`),
  7756. fetchSafeJson(`${API_BASE}/routing/filters/community-lists`),
  7757. fetchSafeJson(`${API_BASE}/routing/filters/as-lists`)
  7758. ]);
  7759. if (sum) state.dynSummary = sum;
  7760. if (bgpInst) state.bgpInstance = bgpInst;
  7761. if (bgpPeers) state.bgpPeers = bgpPeers;
  7762. if (bgpNets) state.bgpNets = bgpNets;
  7763. if (bgpRoutes) state.bgpRoutes = bgpRoutes;
  7764. if (ospfInsts) state.ospfInstances = ospfInsts;
  7765. if (ospfAreas) state.ospfAreas = ospfAreas;
  7766. if (ospfRanges) state.ospfAreaRanges = ospfRanges;
  7767. if (ospfTemplates) state.ospfTemplates = ospfTemplates;
  7768. if (ospfLiveIfaces) state.ospfLiveInterfaces = ospfLiveIfaces;
  7769. if (ospfStaticNbrs) state.ospfStaticNbrs = ospfStaticNbrs;
  7770. if (ospfNbrs) state.ospfNeighbors = ospfNbrs;
  7771. if (ospfLsa) state.ospfLSA = ospfLsa;
  7772. if (filters) state.routingFilters = filters;
  7773. if (selectRules) state.routingSelectRules = selectRules;
  7774. if (commLists) state.routingCommunityLists = commLists;
  7775. if (asLists) state.routingASLists = asLists;
  7776. try { renderBgpStatusPill(); } catch(e) { console.error('renderBgpStatusPill error:', e); }
  7777. try { renderBgpPeers(); } catch(e) { console.error('renderBgpPeers error:', e); }
  7778. try { renderBgpNetworks(); } catch(e) { console.error('renderBgpNetworks error:', e); }
  7779. try { renderBgpRoutes(); } catch(e) { console.error('renderBgpRoutes error:', e); }
  7780. try { renderOspfInstances(); } catch(e) { console.error('renderOspfInstances error:', e); }
  7781. try { renderOspfAreas(); } catch(e) { console.error('renderOspfAreas error:', e); }
  7782. try { renderOspfAreaRanges(); } catch(e) { console.error('renderOspfAreaRanges error:', e); }
  7783. try { renderOspfTemplates(); } catch(e) { console.error('renderOspfTemplates error:', e); }
  7784. try { renderOspfLiveInterfaces(); } catch(e) { console.error('renderOspfLiveInterfaces error:', e); }
  7785. try { renderOspfStaticNbrs(); } catch(e) { console.error('renderOspfStaticNbrs error:', e); }
  7786. try { renderOspfNeighbors(); } catch(e) { console.error('renderOspfNeighbors error:', e); }
  7787. try { renderOspfLSA(); } catch(e) { console.error('renderOspfLSA error:', e); }
  7788. try { renderRoutingFilters(); } catch(e) { console.error('renderRoutingFilters error:', e); }
  7789. try { updateBadges(); } catch(e) { console.error('updateBadges error:', e); }
  7790. if (showToastMsg) showToast('Refreshed', 'Dynamic routing telemetry updated', 'info');
  7791. } catch (err) {
  7792. console.error('Failed to load dynamic routing:', err);
  7793. if (showToastMsg) showToast('Notice', 'Unable to refresh dynamic routing telemetry', 'warning');
  7794. }
  7795. }
  7796. async function loadOspfAll() {
  7797. await loadDynamicRouting(true);
  7798. }
  7799. function renderBgpStatusPill() {
  7800. const pill = document.getElementById('bgp-live-status-pill');
  7801. if (!pill) return;
  7802. const inst = state.bgpInstance;
  7803. if (!inst || !inst.enabled) {
  7804. pill.className = 'text-[10px] px-2 py-0.5 rounded font-mono bg-slate-800 text-slate-400 border border-slate-700';
  7805. pill.innerText = 'BGP DISABLED';
  7806. } else if (inst.running) {
  7807. pill.className = 'text-[10px] px-2 py-0.5 rounded font-mono bg-purple-950 text-purple-300 border border-purple-800/60 font-semibold';
  7808. pill.innerText = `BGP ACTIVE (AS ${inst.as})`;
  7809. } else {
  7810. pill.className = 'text-[10px] px-2 py-0.5 rounded font-mono bg-amber-950 text-amber-300 border border-amber-800/60 font-semibold';
  7811. pill.innerText = 'BGP STARTING...';
  7812. }
  7813. }
  7814. function renderBgpPeers() {
  7815. const tbody = document.getElementById('bgp-peers-table-body');
  7816. if (!tbody) return;
  7817. const empty = document.getElementById('bgp-peers-empty');
  7818. const countBadge = document.getElementById('bgp-peers-count-badge');
  7819. const navBadge = document.getElementById('dyn-badge-bgp-peers');
  7820. const peers = state.bgpPeers || [];
  7821. if (countBadge) countBadge.innerText = `${peers.length} Peers`;
  7822. if (navBadge) navBadge.innerText = peers.length;
  7823. if (peers.length === 0) {
  7824. tbody.innerHTML = '';
  7825. if (empty) empty.classList.remove('hidden');
  7826. return;
  7827. }
  7828. if (empty) empty.classList.add('hidden');
  7829. const sig = peers.map(p => `${p.name}:${p.state}:${p.uptime}:${p.prefix_received}:${p.prefix_sent}:${p.disabled}`).join(';');
  7830. if (tbody.dataset.sig === sig) return;
  7831. tbody.dataset.sig = sig;
  7832. tbody.innerHTML = peers.map(p => {
  7833. let flagA = !p.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  7834. let flagE = p.state === 'Established' ? '<span class="text-emerald-400 font-bold ml-1" title="Established">E</span>' : '';
  7835. let flagX = p.disabled ? '<span class="text-rose-400 font-bold ml-1" title="Disabled">X</span>' : '';
  7836. let stateBadge = '';
  7837. if (p.disabled) {
  7838. stateBadge = '<span class="px-2 py-0.5 rounded-full text-[10px] font-sans font-medium bg-slate-800 text-slate-400 border border-slate-700">Disabled</span>';
  7839. } else if (p.state === 'Established') {
  7840. stateBadge = '<span class="px-2 py-0.5 rounded-full text-[10px] font-sans font-medium bg-emerald-500/10 text-emerald-400 border border-emerald-500/20">Established</span>';
  7841. } else if (p.state === 'Connect' || p.state === 'Active') {
  7842. stateBadge = `<span class="px-2 py-0.5 rounded-full text-[10px] font-sans font-medium bg-amber-500/10 text-amber-400 border border-amber-500/20">${p.state}</span>`;
  7843. } else {
  7844. stateBadge = `<span class="px-2 py-0.5 rounded-full text-[10px] font-sans font-medium bg-slate-800 text-slate-400 border border-slate-700">${p.state || 'Idle'}</span>`;
  7845. }
  7846. return `
  7847. <tr class="hover:bg-slate-800/40 transition">
  7848. <td class="py-2.5 px-3 text-center tracking-wider">${flagA}${flagE}${flagX}</td>
  7849. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(p.name)}</td>
  7850. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(p.remote_address)}</td>
  7851. <td class="py-2.5 px-3">
  7852. <div class="font-bold text-slate-200">AS ${p.remote_as}</div>
  7853. ${p.local_as ? `<div class="text-[10px] text-purple-400 font-mono font-semibold" title="Custom Multi-Instance AS">Local: AS ${p.local_as}</div>` : `<div class="text-[10px] text-slate-500 font-mono">Global AS</div>`}
  7854. </td>
  7855. <td class="py-2.5 px-3">${stateBadge}</td>
  7856. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(p.uptime || '-')}</td>
  7857. <td class="py-2.5 px-3 text-slate-300">
  7858. <span class="text-emerald-400 font-bold">↓ ${p.prefix_received || 0}</span> /
  7859. <span class="text-blue-400 font-bold">↑ ${p.prefix_sent || 0}</span>
  7860. </td>
  7861. <td class="py-2.5 px-3 font-mono text-[11px] whitespace-nowrap">
  7862. ${p.in_filter ? `<span class="px-1.5 py-0.5 rounded bg-blue-950 text-blue-300 border border-blue-800/50" title="In Filter">IN: ${escapeHtml(p.in_filter)}</span> ` : ''}
  7863. ${p.out_filter ? `<span class="px-1.5 py-0.5 rounded bg-amber-950 text-amber-300 border border-amber-800/50" title="Out Filter">OUT: ${escapeHtml(p.out_filter)}</span>` : ''}
  7864. ${!p.in_filter && !p.out_filter ? '<span class="text-slate-600">-</span>' : ''}
  7865. </td>
  7866. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(p.comment || '')}</td>
  7867. <td class="py-2.5 px-3 text-right space-x-1.5 whitespace-nowrap font-sans">
  7868. <button onclick="toggleBgpPeerState('${p.id}', ${!p.disabled})" class="px-2 py-1 rounded text-[11px] ${p.disabled ? 'bg-emerald-950 hover:bg-emerald-900 text-emerald-400 border border-emerald-800/50' : 'bg-slate-800 hover:bg-slate-700 text-slate-300 border border-slate-700'}">
  7869. ${p.disabled ? 'Enable' : 'Disable'}
  7870. </button>
  7871. <button onclick="openEditBgpPeerModal('${p.id}')" class="px-2 py-1 rounded text-[11px] bg-slate-800 hover:bg-slate-700 text-purple-300 border border-slate-700">
  7872. Edit
  7873. </button>
  7874. <button onclick="deleteBgpPeer('${p.id}')" class="px-2 py-1 rounded text-[11px] bg-rose-950/60 hover:bg-rose-900 text-rose-300 border border-rose-900/50">
  7875. Delete
  7876. </button>
  7877. </td>
  7878. </tr>
  7879. `;
  7880. }).join('');
  7881. }
  7882. function renderBgpNetworks() {
  7883. const tbody = document.getElementById('bgp-nets-table-body');
  7884. if (!tbody) return;
  7885. const empty = document.getElementById('bgp-nets-empty');
  7886. const countBadge = document.getElementById('bgp-nets-count-badge');
  7887. const navBadge = document.getElementById('dyn-badge-bgp-nets');
  7888. const nets = state.bgpNets || [];
  7889. if (countBadge) countBadge.innerText = `${nets.length} Networks`;
  7890. if (navBadge) navBadge.innerText = nets.length;
  7891. if (nets.length === 0) {
  7892. tbody.innerHTML = '';
  7893. if (empty) empty.classList.remove('hidden');
  7894. return;
  7895. }
  7896. if (empty) empty.classList.add('hidden');
  7897. const sig = nets.map(n => `${n.network}:${n.disabled}:${n.comment}`).join(';');
  7898. if (tbody.dataset.sig === sig) return;
  7899. tbody.dataset.sig = sig;
  7900. tbody.innerHTML = nets.map(n => `
  7901. <tr class="hover:bg-slate-800/40 transition">
  7902. <td class="py-2.5 px-3 font-semibold text-purple-300 font-mono">${escapeHtml(n.network)}</td>
  7903. <td class="py-2.5 px-3">
  7904. ${n.disabled
  7905. ? '<span class="px-2 py-0.5 rounded-full text-[10px] bg-slate-800 text-slate-400 border border-slate-700">Disabled</span>'
  7906. : '<span class="px-2 py-0.5 rounded-full text-[10px] bg-emerald-500/10 text-emerald-400 border border-emerald-500/20">Announcing</span>'}
  7907. </td>
  7908. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(n.comment || '')}</td>
  7909. <td class="py-2.5 px-3 text-right space-x-1 font-sans">
  7910. <button onclick="deleteBgpNetwork('${n.id}')" class="px-2 py-1 rounded text-[11px] bg-rose-950/60 hover:bg-rose-900 text-rose-300 border border-rose-900/50">
  7911. Delete
  7912. </button>
  7913. </td>
  7914. </tr>
  7915. `).join('');
  7916. }
  7917. function renderBgpRoutes() {
  7918. const tbody = document.getElementById('bgp-routes-table-body');
  7919. if (!tbody) return;
  7920. const empty = document.getElementById('bgp-routes-empty');
  7921. const countBadge = document.getElementById('bgp-routes-count-badge');
  7922. const navBadge = document.getElementById('dyn-badge-bgp-routes');
  7923. const routes = state.bgpRoutes || [];
  7924. if (countBadge) countBadge.innerText = `${routes.length} Routes`;
  7925. if (navBadge) navBadge.innerText = routes.length;
  7926. if (routes.length === 0) {
  7927. tbody.innerHTML = '';
  7928. if (empty) empty.classList.remove('hidden');
  7929. return;
  7930. }
  7931. if (empty) empty.classList.add('hidden');
  7932. const sig = routes.map(r => `${r.prefix}:${r.next_hop}:${r.metric}:${r.path}`).join(';');
  7933. if (tbody.dataset.sig === sig) return;
  7934. tbody.dataset.sig = sig;
  7935. tbody.innerHTML = routes.map(r => `
  7936. <tr class="hover:bg-slate-800/40 transition">
  7937. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.prefix)}</td>
  7938. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(r.next_hop || '-')}</td>
  7939. <td class="py-2.5 px-3 text-slate-300">${r.metric}</td>
  7940. <td class="py-2.5 px-3 text-slate-300">${r.weight}</td>
  7941. <td class="py-2.5 px-3 text-amber-300">${escapeHtml(r.path || 'i')}</td>
  7942. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.origin || 'IGP')}</td>
  7943. </tr>
  7944. `).join('');
  7945. }
  7946. // =========================================================================
  7947. // ROUTEROS v7 OSPF TABLE RENDERING & SORTING
  7948. // =========================================================================
  7949. function sortOspfTable(tab, col) {
  7950. if (!state.ospfSort) state.ospfSort = {};
  7951. if (!state.ospfSort[tab]) state.ospfSort[tab] = { col: col, asc: true };
  7952. if (state.ospfSort[tab].col === col) {
  7953. state.ospfSort[tab].asc = !state.ospfSort[tab].asc;
  7954. } else {
  7955. state.ospfSort[tab].col = col;
  7956. state.ospfSort[tab].asc = true;
  7957. }
  7958. const asc = state.ospfSort[tab].asc;
  7959. let list = [];
  7960. if (tab === 'instances') list = state.ospfInstances || [];
  7961. else if (tab === 'areas') list = state.ospfAreas || [];
  7962. else if (tab === 'ranges') list = state.ospfAreaRanges || [];
  7963. else if (tab === 'templates') list = state.ospfTemplates || [];
  7964. else if (tab === 'live_ifaces') list = state.ospfLiveInterfaces || [];
  7965. else if (tab === 'snbrs') list = state.ospfStaticNbrs || [];
  7966. else if (tab === 'neighbors') list = state.ospfNeighbors || [];
  7967. else if (tab === 'lsa') list = state.ospfLSA || [];
  7968. list.sort((a, b) => {
  7969. let valA = a[col] ?? '';
  7970. let valB = b[col] ?? '';
  7971. if (typeof valA === 'number' && typeof valB === 'number') {
  7972. return asc ? valA - valB : valB - valA;
  7973. }
  7974. return asc ? String(valA).localeCompare(String(valB)) : String(valB).localeCompare(String(valA));
  7975. });
  7976. if (tab === 'instances') renderOspfInstances();
  7977. else if (tab === 'areas') renderOspfAreas();
  7978. else if (tab === 'ranges') renderOspfAreaRanges();
  7979. else if (tab === 'templates') renderOspfTemplates();
  7980. else if (tab === 'live_ifaces') renderOspfLiveInterfaces();
  7981. else if (tab === 'snbrs') renderOspfStaticNbrs();
  7982. else if (tab === 'neighbors') renderOspfNeighbors();
  7983. else if (tab === 'lsa') renderOspfLSA();
  7984. }
  7985. function selectOspfRow(tab, id) {
  7986. if (!state.selectedOspfRow) state.selectedOspfRow = {};
  7987. state.selectedOspfRow[tab] = id;
  7988. if (tab === 'instances') {
  7989. renderOspfInstances();
  7990. const btnEn = document.getElementById('btn-ospf-inst-enable');
  7991. const btnDis = document.getElementById('btn-ospf-inst-disable');
  7992. const btnRem = document.getElementById('btn-ospf-inst-remove');
  7993. const btnCom = document.getElementById('btn-ospf-inst-comment');
  7994. if (btnEn) btnEn.disabled = false;
  7995. if (btnDis) btnDis.disabled = false;
  7996. if (btnRem) btnRem.disabled = false;
  7997. if (btnCom) btnCom.disabled = false;
  7998. } else if (tab === 'areas') {
  7999. renderOspfAreas();
  8000. const btnEn = document.getElementById('btn-ospf-area-enable');
  8001. const btnDis = document.getElementById('btn-ospf-area-disable');
  8002. const btnRem = document.getElementById('btn-ospf-area-remove');
  8003. const btnCom = document.getElementById('btn-ospf-area-comment');
  8004. if (btnEn) btnEn.disabled = false;
  8005. if (btnDis) btnDis.disabled = false;
  8006. if (btnRem) btnRem.disabled = false;
  8007. if (btnCom) btnCom.disabled = false;
  8008. } else if (tab === 'ranges') {
  8009. renderOspfAreaRanges();
  8010. const btnEn = document.getElementById('btn-ospf-range-enable');
  8011. const btnDis = document.getElementById('btn-ospf-range-disable');
  8012. const btnRem = document.getElementById('btn-ospf-range-remove');
  8013. const btnCom = document.getElementById('btn-ospf-range-comment');
  8014. if (btnEn) btnEn.disabled = false;
  8015. if (btnDis) btnDis.disabled = false;
  8016. if (btnRem) btnRem.disabled = false;
  8017. if (btnCom) btnCom.disabled = false;
  8018. } else if (tab === 'templates') {
  8019. renderOspfTemplates();
  8020. const btnEn = document.getElementById('btn-ospf-tmpl-enable');
  8021. const btnDis = document.getElementById('btn-ospf-tmpl-disable');
  8022. const btnRem = document.getElementById('btn-ospf-tmpl-remove');
  8023. const btnCom = document.getElementById('btn-ospf-tmpl-comment');
  8024. if (btnEn) btnEn.disabled = false;
  8025. if (btnDis) btnDis.disabled = false;
  8026. if (btnRem) btnRem.disabled = false;
  8027. if (btnCom) btnCom.disabled = false;
  8028. } else if (tab === 'snbrs') {
  8029. renderOspfStaticNbrs();
  8030. const btnEn = document.getElementById('btn-ospf-snbr-enable');
  8031. const btnDis = document.getElementById('btn-ospf-snbr-disable');
  8032. const btnRem = document.getElementById('btn-ospf-snbr-remove');
  8033. const btnCom = document.getElementById('btn-ospf-snbr-comment');
  8034. if (btnEn) btnEn.disabled = false;
  8035. if (btnDis) btnDis.disabled = false;
  8036. if (btnRem) btnRem.disabled = false;
  8037. if (btnCom) btnCom.disabled = false;
  8038. }
  8039. }
  8040. // TAB 1: INSTANCES
  8041. function renderOspfInstances() {
  8042. const tbody = document.getElementById('ospf-instances-table-body');
  8043. if (!tbody) return;
  8044. const countEl = document.getElementById('ospf-instances-footer-count');
  8045. const filter = (document.getElementById('filter-ospf-instances')?.value || '').toLowerCase();
  8046. let list = state.ospfInstances || [];
  8047. if (filter) {
  8048. list = list.filter(i => (i.name || '').toLowerCase().includes(filter) || (i.router_id || '').toLowerCase().includes(filter) || (i.comment || '').toLowerCase().includes(filter));
  8049. }
  8050. if (countEl) countEl.innerText = list.length;
  8051. const selId = state.selectedOspfRow?.instances;
  8052. tbody.innerHTML = list.map((inst, idx) => {
  8053. const isSel = inst.id === selId;
  8054. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  8055. const flagD = inst.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  8056. return `
  8057. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('instances', '${inst.id}')" ondblclick="openEditOspfInstanceModal('${inst.id}')">
  8058. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  8059. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🔀'}</td>
  8060. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(inst.comment || '')}</td>
  8061. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  8062. <span class="text-sky-400">↳</span> <span>${escapeHtml(inst.name || 'Default')}</span>
  8063. </td>
  8064. <td class="py-1.5 px-3">${inst.version || 2}</td>
  8065. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(inst.vrf || 'main')}</td>
  8066. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(inst.router_id || '192.168.131.56')}</td>
  8067. </tr>
  8068. `;
  8069. }).join('');
  8070. }
  8071. // TAB 2: AREAS
  8072. function renderOspfAreas() {
  8073. const tbody = document.getElementById('ospf-areas-table-body');
  8074. if (!tbody) return;
  8075. const countEl = document.getElementById('ospf-areas-footer-count');
  8076. const filter = (document.getElementById('filter-ospf-areas')?.value || '').toLowerCase();
  8077. let list = state.ospfAreas || [];
  8078. if (filter) {
  8079. list = list.filter(a => (a.name || '').toLowerCase().includes(filter) || (a.area_id || '').toLowerCase().includes(filter) || (a.comment || '').toLowerCase().includes(filter));
  8080. }
  8081. if (countEl) countEl.innerText = list.length;
  8082. const selId = state.selectedOspfRow?.areas;
  8083. tbody.innerHTML = list.map((a, idx) => {
  8084. const isSel = a.id === selId;
  8085. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  8086. const flagD = a.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  8087. return `
  8088. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('areas', '${a.id}')" ondblclick="openEditOspfAreaModal('${a.id}')">
  8089. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  8090. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🌐'}</td>
  8091. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(a.comment || '')}</td>
  8092. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  8093. <span class="text-sky-400">↳</span> <span>${escapeHtml(a.name || 'Default')}</span>
  8094. </td>
  8095. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(a.instance || 'Default')}</td>
  8096. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(a.area_id || '0.0.0.0')}</td>
  8097. <td class="py-1.5 px-3 font-mono text-slate-400">${escapeHtml(a.area_type || 'default')}</td>
  8098. </tr>
  8099. `;
  8100. }).join('');
  8101. }
  8102. // TAB 3: AREA RANGES
  8103. function renderOspfAreaRanges() {
  8104. const tbody = document.getElementById('ospf-ranges-table-body');
  8105. if (!tbody) return;
  8106. const countEl = document.getElementById('ospf-ranges-footer-count');
  8107. const filter = (document.getElementById('filter-ospf-area-ranges')?.value || '').toLowerCase();
  8108. let list = state.ospfAreaRanges || [];
  8109. if (filter) {
  8110. list = list.filter(r => (r.prefix || '').toLowerCase().includes(filter) || (r.area || '').toLowerCase().includes(filter) || (r.comment || '').toLowerCase().includes(filter));
  8111. }
  8112. if (countEl) countEl.innerText = list.length;
  8113. const selId = state.selectedOspfRow?.['area-ranges'];
  8114. tbody.innerHTML = list.map((r, idx) => {
  8115. const isSel = r.id === selId;
  8116. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  8117. const flagD = r.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  8118. return `
  8119. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('ranges', '${r.id}')" ondblclick="openEditOspfAreaRangeModal('${r.id}')">
  8120. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  8121. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🏷'}</td>
  8122. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(r.comment || '')}</td>
  8123. <td class="py-1.5 px-3 font-semibold text-white">${escapeHtml(r.area || 'Default')}</td>
  8124. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(r.prefix || '')}</td>
  8125. <td class="py-1.5 px-3">${r.cost || 1}</td>
  8126. <td class="py-1.5 px-3">${r.advertise !== false ? 'yes' : 'no'}</td>
  8127. </tr>
  8128. `;
  8129. }).join('');
  8130. }
  8131. // TAB 4: INTERFACE TEMPLATES
  8132. function renderOspfTemplates() {
  8133. const tbody = document.getElementById('ospf-templates-table-body');
  8134. if (!tbody) return;
  8135. const countEl = document.getElementById('ospf-templates-footer-count');
  8136. const filter = (document.getElementById('filter-ospf-templates')?.value || '').toLowerCase();
  8137. let list = state.ospfTemplates || [];
  8138. if (filter) {
  8139. list = list.filter(t => (t.interfaces || t.interface || '').toLowerCase().includes(filter) || (t.networks || t.network || '').toLowerCase().includes(filter) || (t.comment || '').toLowerCase().includes(filter));
  8140. }
  8141. if (countEl) countEl.innerText = list.length;
  8142. const selId = state.selectedOspfRow?.templates;
  8143. tbody.innerHTML = list.map((t, idx) => {
  8144. const isSel = t.id === selId;
  8145. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  8146. const ifaces = t.interfaces || t.interface || 'all';
  8147. const nets = t.networks || t.network || '';
  8148. const flagD = t.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  8149. return `
  8150. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('templates', '${t.id}')" ondblclick="openEditOspfTemplateModal('${t.id}')">
  8151. <td class="py-1.5 px-3 w-8 text-center text-slate-500 font-bold">${idx}</td>
  8152. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🔀'}</td>
  8153. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(t.comment || '')}</td>
  8154. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  8155. <span class="text-sky-400">↳</span> <span>${escapeHtml(ifaces)}</span>
  8156. </td>
  8157. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(t.area || 'Default')}</td>
  8158. <td class="py-1.5 px-3 font-mono text-sky-300">${escapeHtml(nets)}</td>
  8159. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(t.network_type || 'broadcast')}</td>
  8160. <td class="py-1.5 px-3">${t.cost || 1}</td>
  8161. <td class="py-1.5 px-3">${t.priority || 128}</td>
  8162. <td class="py-1.5 px-3 text-slate-400">${escapeHtml(t.auth || t.auth_type || '')}</td>
  8163. </tr>
  8164. `;
  8165. }).join('');
  8166. }
  8167. // TAB 5: LIVE INTERFACES
  8168. function renderOspfLiveInterfaces() {
  8169. const tbody = document.getElementById('ospf-live-interfaces-table-body');
  8170. if (!tbody) return;
  8171. const countEl = document.getElementById('ospf-live-interfaces-footer-count');
  8172. const filter = (document.getElementById('filter-ospf-interfaces')?.value || '').toLowerCase();
  8173. let list = state.ospfLiveInterfaces || [];
  8174. if (filter) {
  8175. list = list.filter(i => (i.interface || '').toLowerCase().includes(filter) || (i.address || '').toLowerCase().includes(filter) || (i.state || '').toLowerCase().includes(filter));
  8176. }
  8177. if (countEl) countEl.innerText = list.length;
  8178. tbody.innerHTML = list.map(i => `
  8179. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  8180. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(i.flags || 'D')}</td>
  8181. <td class="py-1.5 px-3 font-semibold text-white">${escapeHtml(i.interface || '')}</td>
  8182. <td class="py-1.5 px-3 font-mono text-sky-300 font-medium">${escapeHtml(i.address || '')}</td>
  8183. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(i.area || 'Default')}</td>
  8184. <td class="py-1.5 px-3 text-center text-slate-400">${i.instance_id || 0}</td>
  8185. <td class="py-1.5 px-3 font-mono text-amber-300 lowercase">${escapeHtml(i.state || 'waiting')}</td>
  8186. <td class="py-1.5 px-3">${i.cost || 1}</td>
  8187. <td class="py-1.5 px-3">${i.priority || 128}</td>
  8188. </tr>
  8189. `).join('');
  8190. }
  8191. // TAB 6: STATIC NEIGHBORS
  8192. function renderOspfStaticNbrs() {
  8193. const tbody = document.getElementById('ospf-snbrs-table-body');
  8194. if (!tbody) return;
  8195. const countEl = document.getElementById('ospf-snbrs-footer-count');
  8196. const filter = (document.getElementById('filter-ospf-static-nbrs')?.value || '').toLowerCase();
  8197. let list = state.ospfStaticNbrs || [];
  8198. if (filter) {
  8199. list = list.filter(n => (n.address || '').toLowerCase().includes(filter) || (n.area || '').toLowerCase().includes(filter) || (n.comment || '').toLowerCase().includes(filter));
  8200. }
  8201. if (countEl) countEl.innerText = list.length;
  8202. const selId = state.selectedOspfRow?.['static-nbrs'];
  8203. tbody.innerHTML = list.map((n, idx) => {
  8204. const isSel = n.id === selId;
  8205. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  8206. const flagD = n.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  8207. return `
  8208. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('snbrs', '${n.id}')" ondblclick="openEditOspfStaticNbrModal('${n.id}')">
  8209. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  8210. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '📡'}</td>
  8211. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(n.comment || '')}</td>
  8212. <td class="py-1.5 px-3 font-semibold font-mono text-sky-300">${escapeHtml(n.address || '')}</td>
  8213. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(n.area || 'Default')}</td>
  8214. <td class="py-1.5 px-3">${n.poll_interval || 120}s</td>
  8215. <td class="py-1.5 px-3">${n.cost || 1}</td>
  8216. </tr>
  8217. `;
  8218. }).join('');
  8219. }
  8220. // TAB 7: LIVE NEIGHBORS
  8221. function renderOspfNeighbors() {
  8222. const tbody = document.getElementById('ospf-neighbors-table-body');
  8223. if (!tbody) return;
  8224. const countEl = document.getElementById('ospf-neighbors-footer-count');
  8225. const filter = (document.getElementById('filter-ospf-neighbors')?.value || '').toLowerCase();
  8226. let list = state.ospfNeighbors || [];
  8227. if (filter) {
  8228. list = list.filter(n => (n.address || '').toLowerCase().includes(filter) || (n.state || '').toLowerCase().includes(filter) || (n.instance || '').toLowerCase().includes(filter));
  8229. }
  8230. if (countEl) countEl.innerText = list.length;
  8231. tbody.innerHTML = list.map(n => `
  8232. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  8233. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(n.flags || 'D')}</td>
  8234. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(n.comment || '')}</td>
  8235. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  8236. <span class="text-sky-400">↳</span> <span>${escapeHtml(n.instance || 'Default')}</span>
  8237. </td>
  8238. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(n.area || 'Default')}</td>
  8239. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(n.address || '')}</td>
  8240. <td class="py-1.5 px-3 font-mono font-bold text-emerald-400">${escapeHtml(n.state || 'Full')}</td>
  8241. <td class="py-1.5 px-3 text-slate-400">${n.state_changes ?? 6}</td>
  8242. </tr>
  8243. `).join('');
  8244. }
  8245. // TAB 8: LINK-STATE DATABASE (LSA)
  8246. function renderOspfLSA() {
  8247. const tbody = document.getElementById('ospf-lsa-table-body');
  8248. if (!tbody) return;
  8249. const countEl = document.getElementById('ospf-lsa-footer-count');
  8250. const filter = (document.getElementById('filter-ospf-lsa')?.value || '').toLowerCase();
  8251. let list = state.ospfLSA || [];
  8252. if (filter) {
  8253. list = list.filter(l => (l.type || '').toLowerCase().includes(filter) || (l.originator || '').toLowerCase().includes(filter) || (l.id || '').toLowerCase().includes(filter));
  8254. }
  8255. if (countEl) countEl.innerText = list.length;
  8256. tbody.innerHTML = list.map(l => `
  8257. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  8258. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(l.flags || 'D')}</td>
  8259. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  8260. <span class="text-sky-400">↳</span> <span>${escapeHtml(l.instance || 'Default')}</span>
  8261. </td>
  8262. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(l.area || 'Default')}</td>
  8263. <td class="py-1.5 px-3 font-mono text-amber-300">${escapeHtml(l.type || 'router')}</td>
  8264. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(l.originator || '')}</td>
  8265. <td class="py-1.5 px-3 font-mono text-sky-300 font-medium">${escapeHtml(l.id || '')}</td>
  8266. <td class="py-1.5 px-3 text-slate-500">${escapeHtml(l.link || '')}</td>
  8267. <td class="py-1.5 px-3 text-slate-500">${l.link_index ?? 0}</td>
  8268. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(l.sequence || '')}</td>
  8269. <td class="py-1.5 px-3 text-slate-400">${l.age ?? 0}</td>
  8270. </tr>
  8271. `).join('');
  8272. }
  8273. function renderOspfStatusPill() {
  8274. // Maintained for backward compatibility
  8275. const pill = document.getElementById('ospf-live-status-pill');
  8276. if (!pill) return;
  8277. pill.className = 'text-[10px] px-2 py-0.5 rounded font-mono bg-indigo-950 text-indigo-300 border border-indigo-800/60 font-semibold';
  8278. pill.innerText = 'OSPF ACTIVE';
  8279. }
  8280. function renderOspfInterfaces() {
  8281. renderOspfTemplates();
  8282. }
  8283. function renderOspfRoutes() {
  8284. // Routes retained in background
  8285. }
  8286. // BGP Modals & Actions
  8287. function openBgpInstanceModal() {
  8288. const inst = state.bgpInstance || { enabled: false, as: 65001, router_id: '192.168.131.56', hold_time: 180, keepalive_time: 60 };
  8289. document.getElementById('modal-bgp-enabled').checked = !!inst.enabled;
  8290. document.getElementById('modal-bgp-as').value = inst.as || 65001;
  8291. document.getElementById('modal-bgp-router-id').value = inst.router_id || '';
  8292. document.getElementById('modal-bgp-keepalive').value = inst.keepalive_time || 60;
  8293. document.getElementById('modal-bgp-holdtime').value = inst.hold_time || 180;
  8294. document.getElementById('modal-bgp-redist-conn').checked = !!inst.redistribute_connected;
  8295. document.getElementById('modal-bgp-redist-static').checked = !!inst.redistribute_static;
  8296. document.getElementById('modal-bgp-redist-ospf').checked = !!inst.redistribute_ospf;
  8297. document.getElementById('bgp-instance-modal').classList.remove('hidden');
  8298. }
  8299. function closeBgpInstanceModal() {
  8300. document.getElementById('bgp-instance-modal').classList.add('hidden');
  8301. }
  8302. async function submitBgpInstance(e) {
  8303. e.preventDefault();
  8304. const payload = {
  8305. enabled: document.getElementById('modal-bgp-enabled').checked,
  8306. as: parseInt(document.getElementById('modal-bgp-as').value, 10),
  8307. router_id: document.getElementById('modal-bgp-router-id').value.trim(),
  8308. keepalive_time: parseInt(document.getElementById('modal-bgp-keepalive').value, 10),
  8309. hold_time: parseInt(document.getElementById('modal-bgp-holdtime').value, 10),
  8310. redistribute_connected: document.getElementById('modal-bgp-redist-conn').checked,
  8311. redistribute_static: document.getElementById('modal-bgp-redist-static').checked,
  8312. redistribute_ospf: document.getElementById('modal-bgp-redist-ospf').checked
  8313. };
  8314. try {
  8315. const res = await fetch(`${API_BASE}/routing/bgp/instance`, {
  8316. method: 'POST',
  8317. headers: { 'Content-Type': 'application/json' },
  8318. body: JSON.stringify(payload)
  8319. });
  8320. if (res.ok) {
  8321. closeBgpInstanceModal();
  8322. showToast('Success', 'BGP instance configuration updated', 'success');
  8323. loadDynamicRouting();
  8324. } else {
  8325. const err = await res.json();
  8326. showToast('Error', err.error || 'Failed to update BGP instance', 'error');
  8327. }
  8328. } catch (err) {
  8329. showToast('Error', err.message, 'error');
  8330. }
  8331. }
  8332. // ----------------- BGP Peer Connection Modal (RouterOS v7) -----------------
  8333. function switchBgpPeerModalTab(tab) {
  8334. const tabs = ['general', 'extra', 'attributes', 'filter'];
  8335. tabs.forEach(t => {
  8336. const pane = document.getElementById(`bgp-peer-tab-${t}`);
  8337. const btn = document.getElementById(`bgp-peer-tab-btn-${t}`);
  8338. if (t === tab) {
  8339. if (pane) pane.classList.remove('hidden');
  8340. if (btn) btn.className = 'px-4 py-2 text-xs font-bold border-b-2 border-cyan-500 text-white transition';
  8341. } else {
  8342. if (pane) pane.classList.add('hidden');
  8343. if (btn) btn.className = 'px-4 py-2 text-xs font-bold border-b-2 border-transparent text-slate-400 hover:text-slate-200 transition';
  8344. }
  8345. });
  8346. }
  8347. function addOutputNetworkRow(val = '') {
  8348. const container = document.getElementById('modal-bgp-output-networks-container');
  8349. if (!container) return;
  8350. const row = document.createElement('div');
  8351. row.className = 'flex items-center gap-2 output-net-row';
  8352. row.innerHTML = `
  8353. <input type="text" value="${escapeHtml(val)}" placeholder="e.g. 10.2.51.0/24 or BGP-AWMN" class="flex-1 bg-slate-900 border border-slate-700 rounded-lg px-3 py-1.5 text-white font-mono text-xs focus:outline-none focus:border-cyan-500">
  8354. <button type="button" onclick="this.closest('.output-net-row').remove()" class="w-7 h-7 flex items-center justify-center bg-slate-800 hover:bg-rose-950 text-slate-400 hover:text-rose-400 border border-slate-700 rounded-lg text-base font-bold transition" title="Remove network">-</button>
  8355. `;
  8356. container.appendChild(row);
  8357. }
  8358. function parseBgpTime(val) {
  8359. if (!val) return 0;
  8360. val = String(val).trim();
  8361. if (val.includes(':')) {
  8362. const parts = val.split(':').map(x => parseInt(x, 10) || 0);
  8363. if (parts.length === 3) return parts[0] * 3600 + parts[1] * 60 + parts[2];
  8364. if (parts.length === 2) return parts[0] * 60 + parts[1];
  8365. }
  8366. return parseInt(val, 10) || 0;
  8367. }
  8368. function formatBgpTime(secs) {
  8369. if (!secs || secs <= 0) return '00:00:00';
  8370. const h = Math.floor(secs / 3600);
  8371. const m = Math.floor((secs % 3600) / 60);
  8372. const s = secs % 60;
  8373. return `${String(h).padStart(2, '0')}:${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')}`;
  8374. }
  8375. function populateBgpRoutingTables() {
  8376. const sel = document.getElementById('modal-bgp-peer-routing-table');
  8377. if (!sel) return;
  8378. const cur = sel.value || 'main';
  8379. sel.innerHTML = '<option value="main">main</option>';
  8380. (state.routingTables || []).forEach(t => {
  8381. if (t.name !== 'main') {
  8382. const opt = document.createElement('option');
  8383. opt.value = t.name;
  8384. opt.innerText = t.name;
  8385. sel.appendChild(opt);
  8386. }
  8387. });
  8388. sel.value = cur;
  8389. }
  8390. function openAddBgpPeerModal() {
  8391. document.getElementById('bgp-peer-form').reset();
  8392. document.getElementById('modal-bgp-peer-id').value = '';
  8393. document.getElementById('bgp-peer-modal-title').innerText = 'New...';
  8394. // General Tab
  8395. document.getElementById('modal-bgp-peer-enabled').checked = true;
  8396. document.getElementById('modal-bgp-peer-comment').value = '';
  8397. document.getElementById('modal-bgp-peer-name').value = '';
  8398. if (document.getElementById('modal-bgp-peer-instance')) document.getElementById('modal-bgp-peer-instance').value = 'bgp-instance-1';
  8399. if (document.getElementById('modal-bgp-peer-template')) document.getElementById('modal-bgp-peer-template').value = '';
  8400. document.getElementById('modal-bgp-peer-local-as').value = '';
  8401. document.getElementById('modal-bgp-peer-afi-ip').checked = true;
  8402. document.getElementById('modal-bgp-peer-afi-ipv6').checked = false;
  8403. if (document.getElementById('modal-bgp-peer-afi-l2vpn')) document.getElementById('modal-bgp-peer-afi-l2vpn').checked = false;
  8404. if (document.getElementById('modal-bgp-peer-afi-vpnv4')) document.getElementById('modal-bgp-peer-afi-vpnv4').checked = false;
  8405. if (document.getElementById('modal-bgp-peer-afi-l2vpn-cisco')) document.getElementById('modal-bgp-peer-afi-l2vpn-cisco').checked = false;
  8406. document.getElementById('modal-bgp-peer-router-id').value = '';
  8407. document.getElementById('modal-bgp-peer-remote-addr').value = '';
  8408. document.getElementById('modal-bgp-peer-remote-port').value = '';
  8409. document.getElementById('modal-bgp-peer-remote-as').value = '';
  8410. if (document.getElementById('modal-bgp-peer-remote-allow-as')) document.getElementById('modal-bgp-peer-remote-allow-as').value = '';
  8411. document.getElementById('modal-bgp-peer-local-addr').value = '';
  8412. document.getElementById('modal-bgp-peer-local-port').value = '';
  8413. document.getElementById('modal-bgp-peer-local-role').value = 'ebgp';
  8414. document.getElementById('modal-bgp-peer-password').value = '';
  8415. document.getElementById('modal-bgp-peer-multihop').checked = false;
  8416. if (document.getElementById('modal-bgp-peer-tx-ttl')) document.getElementById('modal-bgp-peer-tx-ttl').value = '';
  8417. if (document.getElementById('modal-bgp-peer-rx-min-ttl')) document.getElementById('modal-bgp-peer-rx-min-ttl').value = '';
  8418. document.getElementById('modal-bgp-peer-connect').checked = true;
  8419. document.getElementById('modal-bgp-peer-listen').checked = true;
  8420. // Extra Tab
  8421. document.getElementById('modal-bgp-peer-holdtime').value = '00:00:30';
  8422. document.getElementById('modal-bgp-peer-keepalive').value = '00:00:10';
  8423. if (document.getElementById('modal-bgp-peer-use-bfd')) document.getElementById('modal-bgp-peer-use-bfd').checked = false;
  8424. if (document.getElementById('modal-bgp-peer-vrf')) document.getElementById('modal-bgp-peer-vrf').value = 'main';
  8425. if (document.getElementById('modal-bgp-peer-no-client-reflect')) document.getElementById('modal-bgp-peer-no-client-reflect').checked = true;
  8426. document.getElementById('modal-bgp-peer-redist-conn').checked = false;
  8427. document.getElementById('modal-bgp-peer-redist-static').checked = true;
  8428. if (document.getElementById('modal-bgp-peer-redist-rip')) document.getElementById('modal-bgp-peer-redist-rip').checked = false;
  8429. document.getElementById('modal-bgp-peer-redist-ospf').checked = false;
  8430. document.getElementById('modal-bgp-peer-redist-bgp').checked = false;
  8431. if (document.getElementById('modal-bgp-peer-redist-vpn')) document.getElementById('modal-bgp-peer-redist-vpn').checked = false;
  8432. if (document.getElementById('modal-bgp-peer-redist-dhcp')) document.getElementById('modal-bgp-peer-redist-dhcp').checked = false;
  8433. if (document.getElementById('modal-bgp-peer-redist-bgp-mpls-vpn')) document.getElementById('modal-bgp-peer-redist-bgp-mpls-vpn').checked = false;
  8434. if (document.getElementById('modal-bgp-peer-redist-slaac')) document.getElementById('modal-bgp-peer-redist-slaac').checked = false;
  8435. document.getElementById('modal-bgp-peer-default-orig').checked = false;
  8436. if (document.getElementById('modal-bgp-peer-network-blackhole')) document.getElementById('modal-bgp-peer-network-blackhole').checked = false;
  8437. if (document.getElementById('modal-bgp-peer-no-early-cut')) document.getElementById('modal-bgp-peer-no-early-cut').checked = false;
  8438. if (document.getElementById('modal-bgp-peer-keep-sent-attrs')) document.getElementById('modal-bgp-peer-keep-sent-attrs').checked = false;
  8439. if (document.getElementById('modal-bgp-peer-input-affinity')) document.getElementById('modal-bgp-peer-input-affinity').value = '';
  8440. if (document.getElementById('modal-bgp-peer-output-affinity')) document.getElementById('modal-bgp-peer-output-affinity').value = '';
  8441. // Attributes Tab
  8442. document.getElementById('modal-bgp-peer-nexthop-choice').value = 'force-self';
  8443. document.getElementById('modal-bgp-peer-default-prepend').value = 0;
  8444. document.getElementById('modal-bgp-peer-allow-as-in').value = 0;
  8445. if (document.getElementById('modal-bgp-peer-ignore-as-path-len')) document.getElementById('modal-bgp-peer-ignore-as-path-len').checked = false;
  8446. document.getElementById('modal-bgp-peer-remove-priv-as').checked = false;
  8447. document.getElementById('modal-bgp-peer-as-override').checked = false;
  8448. // Filter Tab
  8449. populateFilterChainsDatalist();
  8450. document.getElementById('modal-bgp-peer-in-filter').value = '';
  8451. if (document.getElementById('modal-bgp-peer-in-accept-nlri')) document.getElementById('modal-bgp-peer-in-accept-nlri').value = '';
  8452. if (document.getElementById('modal-bgp-peer-in-accept-comm')) document.getElementById('modal-bgp-peer-in-accept-comm').value = '';
  8453. if (document.getElementById('modal-bgp-peer-in-accept-ext-comm')) document.getElementById('modal-bgp-peer-in-accept-ext-comm').value = '';
  8454. if (document.getElementById('modal-bgp-peer-in-accept-large-comm')) document.getElementById('modal-bgp-peer-in-accept-large-comm').value = '';
  8455. if (document.getElementById('modal-bgp-peer-in-filter-comm')) document.getElementById('modal-bgp-peer-in-filter-comm').value = '';
  8456. if (document.getElementById('modal-bgp-peer-in-filter-ext-comm')) document.getElementById('modal-bgp-peer-in-filter-ext-comm').value = '';
  8457. if (document.getElementById('modal-bgp-peer-in-filter-large-comm')) document.getElementById('modal-bgp-peer-in-filter-large-comm').value = '';
  8458. if (document.getElementById('modal-bgp-peer-in-filter-unknown')) document.getElementById('modal-bgp-peer-in-filter-unknown').checked = false;
  8459. document.getElementById('modal-bgp-peer-out-filter').value = '';
  8460. if (document.getElementById('modal-bgp-peer-out-selection-policy')) document.getElementById('modal-bgp-peer-out-selection-policy').value = 'disabled';
  8461. if (document.getElementById('modal-bgp-peer-out-network-name')) document.getElementById('modal-bgp-peer-out-network-name').value = '';
  8462. populateBgpRoutingTables();
  8463. const container = document.getElementById('modal-bgp-output-networks-container');
  8464. if (container) {
  8465. container.innerHTML = '';
  8466. addOutputNetworkRow('');
  8467. }
  8468. const removeBtn = document.getElementById('modal-btn-remove-peer');
  8469. if (removeBtn) removeBtn.classList.add('hidden');
  8470. switchBgpPeerModalTab('general');
  8471. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  8472. }
  8473. function populateFilterChainsDatalist() {
  8474. const dl = document.getElementById('filter-chains-list');
  8475. if (!dl) return;
  8476. const chains = new Set();
  8477. (state.routingFilters || []).forEach(f => {
  8478. if (f.chain) chains.add(f.chain);
  8479. });
  8480. if (chains.size === 0) {
  8481. chains.add('awmn');
  8482. chains.add('bgp-in');
  8483. chains.add('bgp-out');
  8484. }
  8485. dl.innerHTML = '';
  8486. chains.forEach(c => {
  8487. const opt = document.createElement('option');
  8488. opt.value = c;
  8489. dl.appendChild(opt);
  8490. });
  8491. }
  8492. function openEditBgpPeerModal(id) {
  8493. const p = (state.bgpPeers || []).find(item => item.id === id);
  8494. if (!p) return;
  8495. populateBgpRoutingTables();
  8496. populateFilterChainsDatalist();
  8497. document.getElementById('modal-bgp-peer-id').value = p.id;
  8498. document.getElementById('bgp-peer-modal-title').innerText = p.name || p.id;
  8499. // General Tab
  8500. document.getElementById('modal-bgp-peer-enabled').checked = p.enabled !== false && !p.disabled;
  8501. document.getElementById('modal-bgp-peer-comment').value = p.comment || '';
  8502. document.getElementById('modal-bgp-peer-name').value = p.name || '';
  8503. if (document.getElementById('modal-bgp-peer-instance')) document.getElementById('modal-bgp-peer-instance').value = p.instance || 'bgp-instance-1';
  8504. if (document.getElementById('modal-bgp-peer-template')) document.getElementById('modal-bgp-peer-template').value = p.template || '';
  8505. document.getElementById('modal-bgp-peer-local-as').value = p.local_as || '';
  8506. document.getElementById('modal-bgp-peer-router-id').value = p.router_id || '';
  8507. document.getElementById('modal-bgp-peer-afi-ip').checked = true;
  8508. document.getElementById('modal-bgp-peer-afi-ipv6').checked = p.afi === 'ipv6';
  8509. document.getElementById('modal-bgp-peer-remote-addr').value = p.remote_address || '';
  8510. document.getElementById('modal-bgp-peer-remote-port').value = p.remote_port || '';
  8511. document.getElementById('modal-bgp-peer-remote-as').value = p.remote_as || '';
  8512. if (document.getElementById('modal-bgp-peer-remote-allow-as')) document.getElementById('modal-bgp-peer-remote-allow-as').value = p.remote_allow_as || '';
  8513. document.getElementById('modal-bgp-peer-local-addr').value = p.local_address || '';
  8514. document.getElementById('modal-bgp-peer-local-port').value = p.local_port || '';
  8515. document.getElementById('modal-bgp-peer-local-role').value = p.local_role || 'ebgp';
  8516. document.getElementById('modal-bgp-peer-password').value = p.password || '';
  8517. document.getElementById('modal-bgp-peer-multihop').checked = !!p.multihop;
  8518. if (document.getElementById('modal-bgp-peer-tx-ttl')) document.getElementById('modal-bgp-peer-tx-ttl').value = p.tx_ttl || '';
  8519. if (document.getElementById('modal-bgp-peer-rx-min-ttl')) document.getElementById('modal-bgp-peer-rx-min-ttl').value = p.rx_min_ttl || '';
  8520. document.getElementById('modal-bgp-peer-connect').checked = p.connect !== false;
  8521. document.getElementById('modal-bgp-peer-listen').checked = p.listen !== false;
  8522. // Extra Tab
  8523. document.getElementById('modal-bgp-peer-holdtime').value = p.hold_time ? formatBgpTime(p.hold_time) : '00:00:30';
  8524. document.getElementById('modal-bgp-peer-keepalive').value = p.keepalive_time ? formatBgpTime(p.keepalive_time) : '00:00:10';
  8525. if (document.getElementById('modal-bgp-peer-use-bfd')) document.getElementById('modal-bgp-peer-use-bfd').checked = !!p.use_bfd;
  8526. document.getElementById('modal-bgp-peer-routing-table').value = p.routing_table || 'main';
  8527. if (document.getElementById('modal-bgp-peer-vrf')) document.getElementById('modal-bgp-peer-vrf').value = p.vrf || 'main';
  8528. if (document.getElementById('modal-bgp-peer-no-client-reflect')) document.getElementById('modal-bgp-peer-no-client-reflect').checked = p.no_client_reflect !== false;
  8529. document.getElementById('modal-bgp-peer-redist-conn').checked = !!p.redist_connected;
  8530. document.getElementById('modal-bgp-peer-redist-static').checked = p.redist_static !== false;
  8531. if (document.getElementById('modal-bgp-peer-redist-rip')) document.getElementById('modal-bgp-peer-redist-rip').checked = !!p.redist_rip;
  8532. document.getElementById('modal-bgp-peer-redist-ospf').checked = !!p.redist_ospf;
  8533. document.getElementById('modal-bgp-peer-redist-bgp').checked = !!p.redist_bgp;
  8534. if (document.getElementById('modal-bgp-peer-redist-vpn')) document.getElementById('modal-bgp-peer-redist-vpn').checked = !!p.redist_vpn;
  8535. if (document.getElementById('modal-bgp-peer-redist-dhcp')) document.getElementById('modal-bgp-peer-redist-dhcp').checked = !!p.redist_dhcp;
  8536. if (document.getElementById('modal-bgp-peer-redist-bgp-mpls-vpn')) document.getElementById('modal-bgp-peer-redist-bgp-mpls-vpn').checked = !!p.redist_bgp_mpls_vpn;
  8537. if (document.getElementById('modal-bgp-peer-redist-slaac')) document.getElementById('modal-bgp-peer-redist-slaac').checked = !!p.redist_slaac;
  8538. document.getElementById('modal-bgp-peer-default-orig').checked = !!p.default_originate;
  8539. if (document.getElementById('modal-bgp-peer-network-blackhole')) document.getElementById('modal-bgp-peer-network-blackhole').checked = !!p.network_blackhole;
  8540. if (document.getElementById('modal-bgp-peer-no-early-cut')) document.getElementById('modal-bgp-peer-no-early-cut').checked = !!p.no_early_cut;
  8541. if (document.getElementById('modal-bgp-peer-keep-sent-attrs')) document.getElementById('modal-bgp-peer-keep-sent-attrs').checked = !!p.keep_sent_attrs;
  8542. if (document.getElementById('modal-bgp-peer-input-affinity')) document.getElementById('modal-bgp-peer-input-affinity').value = p.input_affinity || '';
  8543. if (document.getElementById('modal-bgp-peer-output-affinity')) document.getElementById('modal-bgp-peer-output-affinity').value = p.output_affinity || '';
  8544. // Attributes Tab
  8545. document.getElementById('modal-bgp-peer-nexthop-choice').value = p.nexthop_choice || (p.nexthop_self ? 'force-self' : 'default');
  8546. document.getElementById('modal-bgp-peer-default-prepend').value = p.default_prepend || 0;
  8547. document.getElementById('modal-bgp-peer-allow-as-in').value = p.allow_as_in || 0;
  8548. if (document.getElementById('modal-bgp-peer-ignore-as-path-len')) document.getElementById('modal-bgp-peer-ignore-as-path-len').checked = !!p.ignore_as_path_len;
  8549. document.getElementById('modal-bgp-peer-remove-priv-as').checked = !!p.remove_private_as;
  8550. document.getElementById('modal-bgp-peer-as-override').checked = !!p.as_override;
  8551. // Filter Tab
  8552. document.getElementById('modal-bgp-peer-in-filter').value = p.in_filter || '';
  8553. if (document.getElementById('modal-bgp-peer-in-accept-nlri')) document.getElementById('modal-bgp-peer-in-accept-nlri').value = p.in_accept_nlri || '';
  8554. if (document.getElementById('modal-bgp-peer-in-accept-comm')) document.getElementById('modal-bgp-peer-in-accept-comm').value = p.in_accept_communities || '';
  8555. if (document.getElementById('modal-bgp-peer-in-accept-ext-comm')) document.getElementById('modal-bgp-peer-in-accept-ext-comm').value = p.in_accept_ext_communities || '';
  8556. if (document.getElementById('modal-bgp-peer-in-accept-large-comm')) document.getElementById('modal-bgp-peer-in-accept-large-comm').value = p.in_accept_large_communities || '';
  8557. if (document.getElementById('modal-bgp-peer-in-filter-comm')) document.getElementById('modal-bgp-peer-in-filter-comm').value = p.in_filter_communities || '';
  8558. if (document.getElementById('modal-bgp-peer-in-filter-ext-comm')) document.getElementById('modal-bgp-peer-in-filter-ext-comm').value = p.in_filter_ext_communities || '';
  8559. if (document.getElementById('modal-bgp-peer-in-filter-large-comm')) document.getElementById('modal-bgp-peer-in-filter-large-comm').value = p.in_filter_large_communities || '';
  8560. if (document.getElementById('modal-bgp-peer-in-filter-unknown')) document.getElementById('modal-bgp-peer-in-filter-unknown').checked = !!p.in_filter_unknown;
  8561. document.getElementById('modal-bgp-peer-out-filter').value = p.out_filter || '';
  8562. if (document.getElementById('modal-bgp-peer-out-selection-policy')) document.getElementById('modal-bgp-peer-out-selection-policy').value = p.out_selection_policy || 'disabled';
  8563. if (document.getElementById('modal-bgp-peer-out-network-name')) document.getElementById('modal-bgp-peer-out-network-name').value = p.output_network || '';
  8564. // Output Networks
  8565. const container = document.getElementById('modal-bgp-output-networks-container');
  8566. if (container) {
  8567. container.innerHTML = '';
  8568. if (p.output_networks && p.output_networks.length > 0) {
  8569. p.output_networks.forEach(net => addOutputNetworkRow(net));
  8570. } else {
  8571. addOutputNetworkRow('');
  8572. }
  8573. }
  8574. const removeBtn = document.getElementById('modal-btn-remove-peer');
  8575. if (removeBtn) removeBtn.classList.remove('hidden');
  8576. switchBgpPeerModalTab('general');
  8577. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  8578. }
  8579. function copyCurrentBgpPeer() {
  8580. document.getElementById('modal-bgp-peer-id').value = '';
  8581. const nameEl = document.getElementById('modal-bgp-peer-name');
  8582. if (nameEl) nameEl.value = (nameEl.value || 'peer') + '-copy';
  8583. document.getElementById('bgp-peer-modal-title').innerText = 'New...';
  8584. const removeBtn = document.getElementById('modal-btn-remove-peer');
  8585. if (removeBtn) removeBtn.classList.add('hidden');
  8586. showToast('Cloned', 'BGP connection copied to new draft', 'info');
  8587. }
  8588. function removeCurrentBgpPeer() {
  8589. const id = document.getElementById('modal-bgp-peer-id')?.value;
  8590. if (!id) return;
  8591. deleteBgpPeer(id);
  8592. closeBgpPeerModal();
  8593. }
  8594. function closeBgpPeerModal() {
  8595. document.getElementById('bgp-peer-modal').classList.add('hidden');
  8596. }
  8597. function getBgpPeerFormData() {
  8598. const netInputs = document.querySelectorAll('#modal-bgp-output-networks-container .output-net-row input');
  8599. const outputNetworks = [];
  8600. netInputs.forEach(inp => {
  8601. const v = inp.value.trim();
  8602. if (v) outputNetworks.push(v);
  8603. });
  8604. const enabled = document.getElementById('modal-bgp-peer-enabled').checked;
  8605. return {
  8606. id: document.getElementById('modal-bgp-peer-id').value,
  8607. name: document.getElementById('modal-bgp-peer-name').value.trim(),
  8608. enabled: enabled,
  8609. disabled: !enabled,
  8610. comment: document.getElementById('modal-bgp-peer-comment').value.trim(),
  8611. instance: document.getElementById('modal-bgp-peer-instance')?.value.trim() || 'bgp-instance-1',
  8612. template: document.getElementById('modal-bgp-peer-template')?.value.trim() || '',
  8613. local_as: parseInt(document.getElementById('modal-bgp-peer-local-as')?.value, 10) || 0,
  8614. router_id: document.getElementById('modal-bgp-peer-router-id').value.trim(),
  8615. afi: document.getElementById('modal-bgp-peer-afi-ipv6').checked ? 'ipv6' : 'ip',
  8616. remote_address: document.getElementById('modal-bgp-peer-remote-addr').value.trim(),
  8617. remote_port: parseInt(document.getElementById('modal-bgp-peer-remote-port').value, 10) || 0,
  8618. remote_as: parseInt(document.getElementById('modal-bgp-peer-remote-as').value, 10) || 0,
  8619. remote_allow_as: document.getElementById('modal-bgp-peer-remote-allow-as')?.value.trim() || '',
  8620. local_address: document.getElementById('modal-bgp-peer-local-addr').value.trim(),
  8621. local_port: parseInt(document.getElementById('modal-bgp-peer-local-port').value, 10) || 0,
  8622. local_role: document.getElementById('modal-bgp-peer-local-role').value,
  8623. password: document.getElementById('modal-bgp-peer-password').value,
  8624. multihop: document.getElementById('modal-bgp-peer-multihop').checked,
  8625. tx_ttl: parseInt(document.getElementById('modal-bgp-peer-tx-ttl')?.value, 10) || 0,
  8626. rx_min_ttl: parseInt(document.getElementById('modal-bgp-peer-rx-min-ttl')?.value, 10) || 0,
  8627. connect: document.getElementById('modal-bgp-peer-connect').checked,
  8628. listen: document.getElementById('modal-bgp-peer-listen').checked,
  8629. hold_time: parseBgpTime(document.getElementById('modal-bgp-peer-holdtime').value),
  8630. keepalive_time: parseBgpTime(document.getElementById('modal-bgp-peer-keepalive').value),
  8631. use_bfd: document.getElementById('modal-bgp-peer-use-bfd')?.checked || false,
  8632. routing_table: document.getElementById('modal-bgp-peer-routing-table').value,
  8633. vrf: document.getElementById('modal-bgp-peer-vrf')?.value.trim() || 'main',
  8634. no_client_reflect: document.getElementById('modal-bgp-peer-no-client-reflect')?.checked || false,
  8635. redist_connected: document.getElementById('modal-bgp-peer-redist-conn').checked,
  8636. redist_static: document.getElementById('modal-bgp-peer-redist-static').checked,
  8637. redist_rip: document.getElementById('modal-bgp-peer-redist-rip')?.checked || false,
  8638. redist_ospf: document.getElementById('modal-bgp-peer-redist-ospf').checked,
  8639. redist_bgp: document.getElementById('modal-bgp-peer-redist-bgp').checked,
  8640. redist_vpn: document.getElementById('modal-bgp-peer-redist-vpn')?.checked || false,
  8641. redist_dhcp: document.getElementById('modal-bgp-peer-redist-dhcp')?.checked || false,
  8642. redist_bgp_mpls_vpn: document.getElementById('modal-bgp-peer-redist-bgp-mpls-vpn')?.checked || false,
  8643. redist_slaac: document.getElementById('modal-bgp-peer-redist-slaac')?.checked || false,
  8644. default_originate: document.getElementById('modal-bgp-peer-default-orig').checked,
  8645. network_blackhole: document.getElementById('modal-bgp-peer-network-blackhole')?.checked || false,
  8646. no_early_cut: document.getElementById('modal-bgp-peer-no-early-cut')?.checked || false,
  8647. keep_sent_attrs: document.getElementById('modal-bgp-peer-keep-sent-attrs')?.checked || false,
  8648. input_affinity: (document.getElementById('modal-bgp-peer-input-affinity')?.value || '').trim(),
  8649. output_affinity: (document.getElementById('modal-bgp-peer-output-affinity')?.value || '').trim(),
  8650. nexthop_choice: document.getElementById('modal-bgp-peer-nexthop-choice').value,
  8651. nexthop_self: document.getElementById('modal-bgp-peer-nexthop-choice').value === 'force-self',
  8652. default_prepend: parseInt(document.getElementById('modal-bgp-peer-default-prepend').value, 10) || 0,
  8653. allow_as_in: parseInt(document.getElementById('modal-bgp-peer-allow-as-in').value, 10) || 0,
  8654. ignore_as_path_len: document.getElementById('modal-bgp-peer-ignore-as-path-len')?.checked || false,
  8655. remove_private_as: document.getElementById('modal-bgp-peer-remove-priv-as').checked,
  8656. as_override: document.getElementById('modal-bgp-peer-as-override').checked,
  8657. in_filter: (document.getElementById('modal-bgp-peer-in-filter')?.value || '').trim(),
  8658. in_accept_nlri: (document.getElementById('modal-bgp-peer-in-accept-nlri')?.value || '').trim(),
  8659. in_accept_communities: (document.getElementById('modal-bgp-peer-in-accept-comm')?.value || '').trim(),
  8660. in_accept_ext_communities: (document.getElementById('modal-bgp-peer-in-accept-ext-comm')?.value || '').trim(),
  8661. in_accept_large_communities: (document.getElementById('modal-bgp-peer-in-accept-large-comm')?.value || '').trim(),
  8662. in_filter_communities: (document.getElementById('modal-bgp-peer-in-filter-comm')?.value || '').trim(),
  8663. in_filter_ext_communities: (document.getElementById('modal-bgp-peer-in-filter-ext-comm')?.value || '').trim(),
  8664. in_filter_large_communities: (document.getElementById('modal-bgp-peer-in-filter-large-comm')?.value || '').trim(),
  8665. in_filter_unknown: document.getElementById('modal-bgp-peer-in-filter-unknown')?.checked || false,
  8666. out_filter: (document.getElementById('modal-bgp-peer-out-filter')?.value || '').trim(),
  8667. out_selection_policy: document.getElementById('modal-bgp-peer-out-selection-policy')?.value || 'disabled',
  8668. output_network: (document.getElementById('modal-bgp-peer-out-network-name')?.value || '').trim(),
  8669. output_networks: outputNetworks
  8670. };
  8671. }
  8672. async function submitBgpPeer(e) {
  8673. if (e) e.preventDefault();
  8674. const payload = getBgpPeerFormData();
  8675. try {
  8676. const res = await fetch(`${API_BASE}/routing/bgp/peers`, {
  8677. method: 'POST',
  8678. headers: { 'Content-Type': 'application/json' },
  8679. body: JSON.stringify(payload)
  8680. });
  8681. if (res.ok) {
  8682. closeBgpPeerModal();
  8683. showToast('Success', 'BGP Connection saved', 'success');
  8684. loadDynamicRouting();
  8685. } else {
  8686. const err = await res.json();
  8687. showToast('Error', err.error || 'Failed to save peer', 'error');
  8688. }
  8689. } catch (err) {
  8690. showToast('Error', err.message, 'error');
  8691. }
  8692. }
  8693. async function applyBgpPeerModal(e) {
  8694. if (e) e.preventDefault();
  8695. const payload = getBgpPeerFormData();
  8696. try {
  8697. const res = await fetch(`${API_BASE}/routing/bgp/peers`, {
  8698. method: 'POST',
  8699. headers: { 'Content-Type': 'application/json' },
  8700. body: JSON.stringify(payload)
  8701. });
  8702. if (res.ok) {
  8703. const data = await res.json();
  8704. if (data.peer && data.peer.id) {
  8705. document.getElementById('modal-bgp-peer-id').value = data.peer.id;
  8706. document.getElementById('bgp-peer-modal-title').innerText = data.peer.name || data.peer.id;
  8707. document.getElementById('modal-btn-remove-peer')?.classList.remove('hidden');
  8708. }
  8709. showToast('Applied', 'BGP Connection applied', 'success');
  8710. loadDynamicRouting();
  8711. } else {
  8712. const err = await res.json();
  8713. showToast('Error', err.error || 'Failed to apply peer', 'error');
  8714. }
  8715. } catch (err) {
  8716. showToast('Error', err.message, 'error');
  8717. }
  8718. }
  8719. async function deleteBgpPeer(id) {
  8720. if (!confirm('Are you sure you want to delete this BGP peer connection?')) return;
  8721. try {
  8722. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8723. if (res.ok) {
  8724. showToast('Deleted', 'BGP peer removed', 'success');
  8725. loadDynamicRouting();
  8726. }
  8727. } catch (err) {
  8728. showToast('Error', err.message, 'error');
  8729. }
  8730. }
  8731. async function toggleBgpPeerState(id, disabled) {
  8732. try {
  8733. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}/state`, {
  8734. method: 'POST',
  8735. headers: { 'Content-Type': 'application/json' },
  8736. body: JSON.stringify({ disabled })
  8737. });
  8738. if (res.ok) {
  8739. showToast('Updated', `Peer ${disabled ? 'disabled' : 'enabled'}`, 'success');
  8740. loadDynamicRouting();
  8741. }
  8742. } catch (err) {
  8743. showToast('Error', err.message, 'error');
  8744. }
  8745. }
  8746. function openAddBgpNetworkModal() {
  8747. document.getElementById('bgp-network-form').reset();
  8748. document.getElementById('modal-bgp-net-id').value = '';
  8749. document.getElementById('bgp-network-modal').classList.remove('hidden');
  8750. }
  8751. function closeBgpNetworkModal() {
  8752. document.getElementById('bgp-network-modal').classList.add('hidden');
  8753. }
  8754. async function submitBgpNetwork(e) {
  8755. e.preventDefault();
  8756. const payload = {
  8757. id: document.getElementById('modal-bgp-net-id').value,
  8758. network: document.getElementById('modal-bgp-net-cidr').value.trim(),
  8759. comment: document.getElementById('modal-bgp-net-comment').value.trim(),
  8760. disabled: document.getElementById('modal-bgp-net-disabled').checked
  8761. };
  8762. try {
  8763. const res = await fetch(`${API_BASE}/routing/bgp/networks`, {
  8764. method: 'POST',
  8765. headers: { 'Content-Type': 'application/json' },
  8766. body: JSON.stringify(payload)
  8767. });
  8768. if (res.ok) {
  8769. closeBgpNetworkModal();
  8770. showToast('Success', 'BGP network advertisement saved', 'success');
  8771. loadDynamicRouting();
  8772. } else {
  8773. const err = await res.json();
  8774. showToast('Error', err.error || 'Failed to save network', 'error');
  8775. }
  8776. } catch (err) {
  8777. showToast('Error', err.message, 'error');
  8778. }
  8779. }
  8780. async function deleteBgpNetwork(id) {
  8781. if (!confirm('Are you sure you want to stop announcing this network?')) return;
  8782. try {
  8783. const res = await fetch(`${API_BASE}/routing/bgp/networks/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8784. if (res.ok) {
  8785. showToast('Deleted', 'Network advertisement removed', 'success');
  8786. loadDynamicRouting();
  8787. }
  8788. } catch (err) {
  8789. showToast('Error', err.message, 'error');
  8790. }
  8791. }
  8792. // =========================================================================
  8793. // ROUTEROS v7 OSPF MODALS & ACTIONS
  8794. // =========================================================================
  8795. // --- 1. OSPF INSTANCE ---
  8796. function openOspfInstanceModal(id = null) {
  8797. const isEdit = !!id;
  8798. const inst = (state.ospfInstances || []).find(i => i.id === id) || {
  8799. id: '',
  8800. name: 'Default',
  8801. version: 2,
  8802. vrf: 'main',
  8803. router_id: '192.168.131.56',
  8804. routing_table: 'main',
  8805. enabled: true,
  8806. redistribute_connected: false,
  8807. redistribute_static: true,
  8808. redistribute_bgp: false,
  8809. comment: ''
  8810. };
  8811. document.getElementById('ospf-instance-modal-title').innerText = isEdit ? inst.name : 'New...';
  8812. document.getElementById('modal-ospf-inst-id').value = isEdit ? inst.id : '';
  8813. document.getElementById('modal-ospf-inst-enabled').checked = !inst.disabled;
  8814. document.getElementById('modal-ospf-inst-comment').value = inst.comment || '';
  8815. document.getElementById('modal-ospf-inst-name').value = inst.name || 'Default';
  8816. document.getElementById('modal-ospf-inst-version').value = inst.version || 2;
  8817. document.getElementById('modal-ospf-inst-vrf').value = inst.vrf || 'main';
  8818. document.getElementById('modal-ospf-inst-router-id').value = inst.router_id || '';
  8819. document.getElementById('modal-ospf-inst-routing-table').value = inst.routing_table || 'main';
  8820. document.getElementById('modal-ospf-inst-redist-conn').checked = !!inst.redistribute_connected;
  8821. document.getElementById('modal-ospf-inst-redist-static').checked = inst.redistribute_static !== false;
  8822. document.getElementById('modal-ospf-inst-redist-bgp').checked = !!inst.redistribute_bgp;
  8823. const btnRem = document.getElementById('btn-ospf-inst-modal-remove');
  8824. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  8825. document.getElementById('ospf-instance-modal').classList.remove('hidden');
  8826. }
  8827. function openEditOspfInstanceModal(id) {
  8828. openOspfInstanceModal(id);
  8829. }
  8830. function closeOspfInstanceModal() {
  8831. document.getElementById('ospf-instance-modal').classList.add('hidden');
  8832. }
  8833. async function submitOspfInstance(e) {
  8834. if (e) e.preventDefault();
  8835. const payload = {
  8836. id: document.getElementById('modal-ospf-inst-id').value,
  8837. name: document.getElementById('modal-ospf-inst-name').value.trim() || 'Default',
  8838. version: parseInt(document.getElementById('modal-ospf-inst-version').value, 10) || 2,
  8839. vrf: document.getElementById('modal-ospf-inst-vrf').value.trim() || 'main',
  8840. router_id: document.getElementById('modal-ospf-inst-router-id').value.trim(),
  8841. routing_table: document.getElementById('modal-ospf-inst-routing-table').value.trim() || 'main',
  8842. enabled: document.getElementById('modal-ospf-inst-enabled').checked,
  8843. disabled: !document.getElementById('modal-ospf-inst-enabled').checked,
  8844. comment: document.getElementById('modal-ospf-inst-comment').value.trim(),
  8845. redistribute_connected: document.getElementById('modal-ospf-inst-redist-conn').checked,
  8846. redistribute_static: document.getElementById('modal-ospf-inst-redist-static').checked,
  8847. redistribute_bgp: document.getElementById('modal-ospf-inst-redist-bgp').checked
  8848. };
  8849. try {
  8850. const res = await fetch(`${API_BASE}/routing/ospf/instances`, {
  8851. method: 'POST',
  8852. headers: { 'Content-Type': 'application/json' },
  8853. body: JSON.stringify(payload)
  8854. });
  8855. if (res.ok) {
  8856. closeOspfInstanceModal();
  8857. showToast('Saved', 'OSPF instance updated', 'success');
  8858. loadDynamicRouting();
  8859. } else {
  8860. const err = await res.json();
  8861. showToast('Error', err.error || 'Failed to save OSPF instance', 'error');
  8862. }
  8863. } catch (err) {
  8864. showToast('Error', err.message, 'error');
  8865. }
  8866. }
  8867. function applyOspfInstanceForm() {
  8868. submitOspfInstance(null);
  8869. }
  8870. function copyOspfInstance() {
  8871. document.getElementById('modal-ospf-inst-id').value = '';
  8872. document.getElementById('modal-ospf-inst-name').value += '-copy';
  8873. document.getElementById('ospf-instance-modal-title').innerText = 'New...';
  8874. showToast('Copied', 'Duplicated as new OSPF instance', 'info');
  8875. }
  8876. async function deleteCurrentOspfInstance() {
  8877. const id = document.getElementById('modal-ospf-inst-id').value;
  8878. if (!id) return;
  8879. if (!confirm('Are you sure you want to remove this OSPF instance?')) return;
  8880. try {
  8881. const res = await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8882. if (res.ok) {
  8883. closeOspfInstanceModal();
  8884. showToast('Removed', 'OSPF instance deleted', 'success');
  8885. loadDynamicRouting();
  8886. }
  8887. } catch (err) {
  8888. showToast('Error', err.message, 'error');
  8889. }
  8890. }
  8891. async function enableSelectedOspfInstance() {
  8892. const id = state.selectedOspfRow?.instances;
  8893. if (!id) return;
  8894. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}/state`, {
  8895. method: 'POST',
  8896. headers: { 'Content-Type': 'application/json' },
  8897. body: JSON.stringify({ disabled: false })
  8898. });
  8899. loadDynamicRouting();
  8900. }
  8901. async function disableSelectedOspfInstance() {
  8902. const id = state.selectedOspfRow?.instances;
  8903. if (!id) return;
  8904. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}/state`, {
  8905. method: 'POST',
  8906. headers: { 'Content-Type': 'application/json' },
  8907. body: JSON.stringify({ disabled: true })
  8908. });
  8909. loadDynamicRouting();
  8910. }
  8911. async function removeSelectedOspfInstance() {
  8912. const id = state.selectedOspfRow?.instances;
  8913. if (!id) return;
  8914. if (!confirm('Delete selected OSPF instance?')) return;
  8915. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8916. loadDynamicRouting();
  8917. }
  8918. async function promptCommentOspfInstance() {
  8919. const id = state.selectedOspfRow?.instances;
  8920. if (!id) return;
  8921. const inst = (state.ospfInstances || []).find(i => i.id === id);
  8922. if (!inst) return;
  8923. const comment = prompt('Enter comment for OSPF instance:', inst.comment || '');
  8924. if (comment === null) return;
  8925. inst.comment = comment;
  8926. await fetch(`${API_BASE}/routing/ospf/instances`, {
  8927. method: 'POST',
  8928. headers: { 'Content-Type': 'application/json' },
  8929. body: JSON.stringify(inst)
  8930. });
  8931. loadDynamicRouting();
  8932. }
  8933. // --- 2. OSPF AREA ---
  8934. function populateOspfAreaDropdowns() {
  8935. const instSelect = document.getElementById('modal-ospf-area-instance');
  8936. if (instSelect) {
  8937. const cur = instSelect.value;
  8938. instSelect.innerHTML = (state.ospfInstances || []).map(i => `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)}</option>`).join('');
  8939. if (instSelect.innerHTML === '') instSelect.innerHTML = '<option value="Default">Default</option>';
  8940. if (cur) instSelect.value = cur;
  8941. }
  8942. }
  8943. function openOspfAreaModal(id = null) {
  8944. const isEdit = !!id;
  8945. populateOspfAreaDropdowns();
  8946. const area = (state.ospfAreas || []).find(a => a.id === id) || {
  8947. id: '',
  8948. name: 'Default',
  8949. instance: 'Default',
  8950. area_id: '0.0.0.0',
  8951. area_type: 'default',
  8952. default_cost: 1,
  8953. no_summaries: false,
  8954. disabled: false,
  8955. comment: ''
  8956. };
  8957. document.getElementById('ospf-area-modal-title').innerText = isEdit ? area.name : 'New...';
  8958. document.getElementById('modal-ospf-area-id').value = isEdit ? area.id : '';
  8959. document.getElementById('modal-ospf-area-enabled').checked = !area.disabled;
  8960. document.getElementById('modal-ospf-area-comment').value = area.comment || '';
  8961. document.getElementById('modal-ospf-area-name').value = area.name || 'Default';
  8962. document.getElementById('modal-ospf-area-instance').value = area.instance || 'Default';
  8963. document.getElementById('modal-ospf-area-areaid').value = area.area_id || '0.0.0.0';
  8964. document.getElementById('modal-ospf-area-type').value = area.area_type || 'default';
  8965. document.getElementById('modal-ospf-area-default-cost').value = area.default_cost || 1;
  8966. document.getElementById('modal-ospf-area-no-summaries').checked = !!area.no_summaries;
  8967. const btnRem = document.getElementById('btn-ospf-area-modal-remove');
  8968. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  8969. document.getElementById('ospf-area-modal').classList.remove('hidden');
  8970. }
  8971. function openEditOspfAreaModal(id) {
  8972. openOspfAreaModal(id);
  8973. }
  8974. function closeOspfAreaModal() {
  8975. document.getElementById('ospf-area-modal').classList.add('hidden');
  8976. }
  8977. async function submitOspfArea(e) {
  8978. if (e) e.preventDefault();
  8979. const payload = {
  8980. id: document.getElementById('modal-ospf-area-id').value,
  8981. name: document.getElementById('modal-ospf-area-name').value.trim() || 'Default',
  8982. instance: document.getElementById('modal-ospf-area-instance').value.trim() || 'Default',
  8983. area_id: document.getElementById('modal-ospf-area-areaid').value.trim() || '0.0.0.0',
  8984. area_type: document.getElementById('modal-ospf-area-type').value,
  8985. default_cost: parseInt(document.getElementById('modal-ospf-area-default-cost').value, 10) || 1,
  8986. no_summaries: document.getElementById('modal-ospf-area-no-summaries').checked,
  8987. disabled: !document.getElementById('modal-ospf-area-enabled').checked,
  8988. comment: document.getElementById('modal-ospf-area-comment').value.trim()
  8989. };
  8990. try {
  8991. const res = await fetch(`${API_BASE}/routing/ospf/areas`, {
  8992. method: 'POST',
  8993. headers: { 'Content-Type': 'application/json' },
  8994. body: JSON.stringify(payload)
  8995. });
  8996. if (res.ok) {
  8997. closeOspfAreaModal();
  8998. showToast('Saved', 'OSPF area saved', 'success');
  8999. loadDynamicRouting();
  9000. } else {
  9001. const err = await res.json();
  9002. showToast('Error', err.error || 'Failed to save area', 'error');
  9003. }
  9004. } catch (err) {
  9005. showToast('Error', err.message, 'error');
  9006. }
  9007. }
  9008. function applyOspfAreaForm() {
  9009. submitOspfArea(null);
  9010. }
  9011. function copyOspfArea() {
  9012. document.getElementById('modal-ospf-area-id').value = '';
  9013. document.getElementById('modal-ospf-area-name').value += '-copy';
  9014. document.getElementById('ospf-area-modal-title').innerText = 'New...';
  9015. showToast('Copied', 'Duplicated as new OSPF area', 'info');
  9016. }
  9017. async function deleteCurrentOspfArea() {
  9018. const id = document.getElementById('modal-ospf-area-id').value;
  9019. if (!id) return;
  9020. if (!confirm('Are you sure you want to remove this OSPF area?')) return;
  9021. try {
  9022. const res = await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9023. if (res.ok) {
  9024. closeOspfAreaModal();
  9025. showToast('Removed', 'OSPF area deleted', 'success');
  9026. loadDynamicRouting();
  9027. }
  9028. } catch (err) {
  9029. showToast('Error', err.message, 'error');
  9030. }
  9031. }
  9032. async function enableSelectedOspfArea() {
  9033. const id = state.selectedOspfRow?.areas;
  9034. if (!id) return;
  9035. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}/state`, {
  9036. method: 'POST',
  9037. headers: { 'Content-Type': 'application/json' },
  9038. body: JSON.stringify({ disabled: false })
  9039. });
  9040. loadDynamicRouting();
  9041. }
  9042. async function disableSelectedOspfArea() {
  9043. const id = state.selectedOspfRow?.areas;
  9044. if (!id) return;
  9045. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}/state`, {
  9046. method: 'POST',
  9047. headers: { 'Content-Type': 'application/json' },
  9048. body: JSON.stringify({ disabled: true })
  9049. });
  9050. loadDynamicRouting();
  9051. }
  9052. async function removeSelectedOspfArea() {
  9053. const id = state.selectedOspfRow?.areas;
  9054. if (!id) return;
  9055. if (!confirm('Delete selected OSPF area?')) return;
  9056. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9057. loadDynamicRouting();
  9058. }
  9059. async function promptCommentOspfArea() {
  9060. const id = state.selectedOspfRow?.areas;
  9061. if (!id) return;
  9062. const area = (state.ospfAreas || []).find(a => a.id === id);
  9063. if (!area) return;
  9064. const comment = prompt('Enter comment for OSPF area:', area.comment || '');
  9065. if (comment === null) return;
  9066. area.comment = comment;
  9067. await fetch(`${API_BASE}/routing/ospf/areas`, {
  9068. method: 'POST',
  9069. headers: { 'Content-Type': 'application/json' },
  9070. body: JSON.stringify(area)
  9071. });
  9072. loadDynamicRouting();
  9073. }
  9074. // --- 3. OSPF AREA RANGE ---
  9075. function populateAreaRangeDropdowns() {
  9076. const select = document.getElementById('modal-ospf-range-area');
  9077. if (select) {
  9078. const cur = select.value;
  9079. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  9080. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  9081. if (cur) select.value = cur;
  9082. }
  9083. }
  9084. function openOspfAreaRangeModal(id = null) {
  9085. const isEdit = !!id;
  9086. populateAreaRangeDropdowns();
  9087. const r = (state.ospfAreaRanges || []).find(it => it.id === id) || {
  9088. id: '',
  9089. area: 'Default',
  9090. prefix: '',
  9091. cost: 1,
  9092. advertise: true,
  9093. disabled: false,
  9094. comment: ''
  9095. };
  9096. document.getElementById('ospf-area-range-modal-title').innerText = isEdit ? r.prefix : 'New...';
  9097. document.getElementById('modal-ospf-range-id').value = isEdit ? r.id : '';
  9098. document.getElementById('modal-ospf-range-enabled').checked = !r.disabled;
  9099. document.getElementById('modal-ospf-range-comment').value = r.comment || '';
  9100. document.getElementById('modal-ospf-range-area').value = r.area || 'Default';
  9101. document.getElementById('modal-ospf-range-prefix').value = r.prefix || '';
  9102. document.getElementById('modal-ospf-range-cost').value = r.cost || 1;
  9103. document.getElementById('modal-ospf-range-advertise').checked = r.advertise !== false;
  9104. const btnRem = document.getElementById('btn-ospf-range-modal-remove');
  9105. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  9106. document.getElementById('ospf-area-range-modal').classList.remove('hidden');
  9107. }
  9108. function openEditOspfAreaRangeModal(id) {
  9109. openOspfAreaRangeModal(id);
  9110. }
  9111. function closeOspfAreaRangeModal() {
  9112. document.getElementById('ospf-area-range-modal').classList.add('hidden');
  9113. }
  9114. async function submitOspfAreaRange(e) {
  9115. if (e) e.preventDefault();
  9116. const payload = {
  9117. id: document.getElementById('modal-ospf-range-id').value,
  9118. area: document.getElementById('modal-ospf-range-area').value,
  9119. prefix: document.getElementById('modal-ospf-range-prefix').value.trim(),
  9120. cost: parseInt(document.getElementById('modal-ospf-range-cost').value, 10) || 1,
  9121. advertise: document.getElementById('modal-ospf-range-advertise').checked,
  9122. disabled: !document.getElementById('modal-ospf-range-enabled').checked,
  9123. comment: document.getElementById('modal-ospf-range-comment').value.trim()
  9124. };
  9125. try {
  9126. const res = await fetch(`${API_BASE}/routing/ospf/area-ranges`, {
  9127. method: 'POST',
  9128. headers: { 'Content-Type': 'application/json' },
  9129. body: JSON.stringify(payload)
  9130. });
  9131. if (res.ok) {
  9132. closeOspfAreaRangeModal();
  9133. showToast('Saved', 'Area range saved', 'success');
  9134. loadDynamicRouting();
  9135. } else {
  9136. const err = await res.json();
  9137. showToast('Error', err.error || 'Failed to save area range', 'error');
  9138. }
  9139. } catch (err) {
  9140. showToast('Error', err.message, 'error');
  9141. }
  9142. }
  9143. function applyOspfAreaRangeForm() {
  9144. submitOspfAreaRange(null);
  9145. }
  9146. async function deleteCurrentOspfAreaRange() {
  9147. const id = document.getElementById('modal-ospf-range-id').value;
  9148. if (!id) return;
  9149. if (!confirm('Delete this area range?')) return;
  9150. try {
  9151. await fetch(`${API_BASE}/routing/ospf/area-ranges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9152. closeOspfAreaRangeModal();
  9153. showToast('Removed', 'Area range removed', 'success');
  9154. loadDynamicRouting();
  9155. } catch (err) {
  9156. showToast('Error', err.message, 'error');
  9157. }
  9158. }
  9159. async function enableSelectedOspfAreaRange() {
  9160. const id = state.selectedOspfRow?.['area-ranges'];
  9161. if (!id) return;
  9162. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  9163. if (!r) return;
  9164. r.disabled = false;
  9165. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  9166. loadDynamicRouting();
  9167. }
  9168. async function disableSelectedOspfAreaRange() {
  9169. const id = state.selectedOspfRow?.['area-ranges'];
  9170. if (!id) return;
  9171. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  9172. if (!r) return;
  9173. r.disabled = true;
  9174. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  9175. loadDynamicRouting();
  9176. }
  9177. async function removeSelectedOspfAreaRange() {
  9178. const id = state.selectedOspfRow?.['area-ranges'];
  9179. if (!id) return;
  9180. if (!confirm('Delete selected area range?')) return;
  9181. await fetch(`${API_BASE}/routing/ospf/area-ranges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9182. loadDynamicRouting();
  9183. }
  9184. async function promptCommentOspfAreaRange() {
  9185. const id = state.selectedOspfRow?.['area-ranges'];
  9186. if (!id) return;
  9187. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  9188. if (!r) return;
  9189. const comment = prompt('Enter comment for area range:', r.comment || '');
  9190. if (comment === null) return;
  9191. r.comment = comment;
  9192. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  9193. loadDynamicRouting();
  9194. }
  9195. // --- 4. OSPF INTERFACE TEMPLATE ---
  9196. function switchOspfTemplateTab(tab) {
  9197. const tabGen = document.getElementById('ospf-tmpl-tab-general');
  9198. const tabAuth = document.getElementById('ospf-tmpl-tab-auth');
  9199. const btnGen = document.getElementById('ospf-tmpl-tab-btn-general');
  9200. const btnAuth = document.getElementById('ospf-tmpl-tab-btn-auth');
  9201. if (tab === 'general') {
  9202. if (tabGen) tabGen.classList.remove('hidden');
  9203. if (tabAuth) tabAuth.classList.add('hidden');
  9204. if (btnGen) btnGen.className = 'px-4 py-2 text-xs font-bold border-b-2 border-sky-500 text-white transition';
  9205. if (btnAuth) btnAuth.className = 'px-4 py-2 text-xs font-bold border-b-2 border-transparent text-slate-400 hover:text-slate-200 transition';
  9206. } else {
  9207. if (tabGen) tabGen.classList.add('hidden');
  9208. if (tabAuth) tabAuth.classList.remove('hidden');
  9209. if (btnGen) btnGen.className = 'px-4 py-2 text-xs font-bold border-b-2 border-transparent text-slate-400 hover:text-slate-200 transition';
  9210. if (btnAuth) btnAuth.className = 'px-4 py-2 text-xs font-bold border-b-2 border-sky-500 text-white transition';
  9211. }
  9212. }
  9213. function populateTemplateAreaDropdowns() {
  9214. const select = document.getElementById('modal-ospf-tmpl-area');
  9215. if (select) {
  9216. const cur = select.value;
  9217. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  9218. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  9219. if (cur) select.value = cur;
  9220. }
  9221. }
  9222. function openOspfTemplateModal(id = null) {
  9223. const isEdit = !!id;
  9224. populateTemplateAreaDropdowns();
  9225. switchOspfTemplateTab('general');
  9226. const tmpl = (state.ospfTemplates || []).find(t => t.id === id) || {
  9227. id: '',
  9228. interfaces: '',
  9229. area: 'Default',
  9230. networks: '',
  9231. network_type: 'broadcast',
  9232. cost: 1,
  9233. priority: 128,
  9234. passive: false,
  9235. hello_interval: 10,
  9236. dead_interval: 40,
  9237. auth: 'none',
  9238. auth_key: '',
  9239. disabled: false,
  9240. comment: ''
  9241. };
  9242. document.getElementById('ospf-template-modal-title').innerText = isEdit ? (tmpl.interfaces || tmpl.networks || 'Template') : 'New...';
  9243. document.getElementById('modal-ospf-tmpl-id').value = isEdit ? tmpl.id : '';
  9244. document.getElementById('modal-ospf-tmpl-enabled').checked = !tmpl.disabled;
  9245. document.getElementById('modal-ospf-tmpl-comment').value = tmpl.comment || '';
  9246. document.getElementById('modal-ospf-tmpl-interfaces').value = tmpl.interfaces || tmpl.interface || '';
  9247. document.getElementById('modal-ospf-tmpl-area').value = tmpl.area || 'Default';
  9248. document.getElementById('modal-ospf-tmpl-networks').value = tmpl.networks || tmpl.network || '';
  9249. document.getElementById('modal-ospf-tmpl-net-type').value = tmpl.network_type || 'broadcast';
  9250. document.getElementById('modal-ospf-tmpl-cost').value = tmpl.cost || 1;
  9251. document.getElementById('modal-ospf-tmpl-priority').value = tmpl.priority || 128;
  9252. document.getElementById('modal-ospf-tmpl-passive').checked = !!tmpl.passive;
  9253. document.getElementById('modal-ospf-tmpl-hello').value = tmpl.hello_interval || 10;
  9254. document.getElementById('modal-ospf-tmpl-dead').value = tmpl.dead_interval || 40;
  9255. document.getElementById('modal-ospf-tmpl-auth').value = tmpl.auth || tmpl.auth_type || 'none';
  9256. document.getElementById('modal-ospf-tmpl-auth-key').value = tmpl.auth_key || '';
  9257. const btnRem = document.getElementById('btn-ospf-tmpl-modal-remove');
  9258. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  9259. document.getElementById('ospf-template-modal').classList.remove('hidden');
  9260. }
  9261. function openEditOspfTemplateModal(id) {
  9262. openOspfTemplateModal(id);
  9263. }
  9264. function closeOspfTemplateModal() {
  9265. document.getElementById('ospf-template-modal').classList.add('hidden');
  9266. }
  9267. async function submitOspfTemplate(e) {
  9268. if (e) e.preventDefault();
  9269. const payload = {
  9270. id: document.getElementById('modal-ospf-tmpl-id').value,
  9271. interfaces: document.getElementById('modal-ospf-tmpl-interfaces').value.trim(),
  9272. interface: document.getElementById('modal-ospf-tmpl-interfaces').value.trim(),
  9273. area: document.getElementById('modal-ospf-tmpl-area').value,
  9274. networks: document.getElementById('modal-ospf-tmpl-networks').value.trim(),
  9275. network: document.getElementById('modal-ospf-tmpl-networks').value.trim(),
  9276. network_type: document.getElementById('modal-ospf-tmpl-net-type').value,
  9277. cost: parseInt(document.getElementById('modal-ospf-tmpl-cost').value, 10) || 1,
  9278. priority: parseInt(document.getElementById('modal-ospf-tmpl-priority').value, 10) || 128,
  9279. passive: document.getElementById('modal-ospf-tmpl-passive').checked,
  9280. hello_interval: parseInt(document.getElementById('modal-ospf-tmpl-hello').value, 10) || 10,
  9281. dead_interval: parseInt(document.getElementById('modal-ospf-tmpl-dead').value, 10) || 40,
  9282. auth: document.getElementById('modal-ospf-tmpl-auth').value,
  9283. auth_type: document.getElementById('modal-ospf-tmpl-auth').value,
  9284. auth_key: document.getElementById('modal-ospf-tmpl-auth-key').value,
  9285. disabled: !document.getElementById('modal-ospf-tmpl-enabled').checked,
  9286. comment: document.getElementById('modal-ospf-tmpl-comment').value.trim()
  9287. };
  9288. try {
  9289. const res = await fetch(`${API_BASE}/routing/ospf/templates`, {
  9290. method: 'POST',
  9291. headers: { 'Content-Type': 'application/json' },
  9292. body: JSON.stringify(payload)
  9293. });
  9294. if (res.ok) {
  9295. closeOspfTemplateModal();
  9296. showToast('Saved', 'Interface template saved', 'success');
  9297. loadDynamicRouting();
  9298. } else {
  9299. const err = await res.json();
  9300. showToast('Error', err.error || 'Failed to save interface template', 'error');
  9301. }
  9302. } catch (err) {
  9303. showToast('Error', err.message, 'error');
  9304. }
  9305. }
  9306. function applyOspfTemplateForm() {
  9307. submitOspfTemplate(null);
  9308. }
  9309. function copyOspfTemplate() {
  9310. document.getElementById('modal-ospf-tmpl-id').value = '';
  9311. document.getElementById('ospf-template-modal-title').innerText = 'New...';
  9312. showToast('Copied', 'Duplicated as new template', 'info');
  9313. }
  9314. async function deleteCurrentOspfTemplate() {
  9315. const id = document.getElementById('modal-ospf-tmpl-id').value;
  9316. if (!id) return;
  9317. if (!confirm('Delete this interface template?')) return;
  9318. try {
  9319. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9320. closeOspfTemplateModal();
  9321. showToast('Removed', 'Interface template deleted', 'success');
  9322. loadDynamicRouting();
  9323. } catch (err) {
  9324. showToast('Error', err.message, 'error');
  9325. }
  9326. }
  9327. async function enableSelectedOspfTemplate() {
  9328. const id = state.selectedOspfRow?.templates;
  9329. if (!id) return;
  9330. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  9331. method: 'POST',
  9332. headers: { 'Content-Type': 'application/json' },
  9333. body: JSON.stringify({ disabled: false })
  9334. });
  9335. loadDynamicRouting();
  9336. }
  9337. async function disableSelectedOspfTemplate() {
  9338. const id = state.selectedOspfRow?.templates;
  9339. if (!id) return;
  9340. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  9341. method: 'POST',
  9342. headers: { 'Content-Type': 'application/json' },
  9343. body: JSON.stringify({ disabled: true })
  9344. });
  9345. loadDynamicRouting();
  9346. }
  9347. async function removeSelectedOspfTemplate() {
  9348. const id = state.selectedOspfRow?.templates;
  9349. if (!id) return;
  9350. if (!confirm('Delete selected interface template?')) return;
  9351. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9352. loadDynamicRouting();
  9353. }
  9354. async function promptCommentOspfTemplate() {
  9355. const id = state.selectedOspfRow?.templates;
  9356. if (!id) return;
  9357. const tmpl = (state.ospfTemplates || []).find(t => t.id === id);
  9358. if (!tmpl) return;
  9359. const comment = prompt('Enter comment for template:', tmpl.comment || '');
  9360. if (comment === null) return;
  9361. tmpl.comment = comment;
  9362. await fetch(`${API_BASE}/routing/ospf/templates`, {
  9363. method: 'POST',
  9364. headers: { 'Content-Type': 'application/json' },
  9365. body: JSON.stringify(tmpl)
  9366. });
  9367. loadDynamicRouting();
  9368. }
  9369. // --- 5. OSPF STATIC NEIGHBOR ---
  9370. function populateStaticNbrAreaDropdowns() {
  9371. const select = document.getElementById('modal-ospf-snbr-area');
  9372. if (select) {
  9373. const cur = select.value;
  9374. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  9375. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  9376. if (cur) select.value = cur;
  9377. }
  9378. }
  9379. function openOspfStaticNbrModal(id = null) {
  9380. const isEdit = !!id;
  9381. populateStaticNbrAreaDropdowns();
  9382. const nbr = (state.ospfStaticNbrs || []).find(n => n.id === id) || {
  9383. id: '',
  9384. address: '',
  9385. area: 'Default',
  9386. poll_interval: 120,
  9387. cost: 1,
  9388. disabled: false,
  9389. comment: ''
  9390. };
  9391. document.getElementById('ospf-static-nbr-modal-title').innerText = isEdit ? nbr.address : 'New...';
  9392. document.getElementById('modal-ospf-snbr-id').value = isEdit ? nbr.id : '';
  9393. document.getElementById('modal-ospf-snbr-enabled').checked = !nbr.disabled;
  9394. document.getElementById('modal-ospf-snbr-comment').value = nbr.comment || '';
  9395. document.getElementById('modal-ospf-snbr-address').value = nbr.address || '';
  9396. document.getElementById('modal-ospf-snbr-area').value = nbr.area || 'Default';
  9397. document.getElementById('modal-ospf-snbr-poll').value = nbr.poll_interval || 120;
  9398. document.getElementById('modal-ospf-snbr-cost').value = nbr.cost || 1;
  9399. const btnRem = document.getElementById('btn-ospf-snbr-modal-remove');
  9400. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  9401. document.getElementById('ospf-static-nbr-modal').classList.remove('hidden');
  9402. }
  9403. function openEditOspfStaticNbrModal(id) {
  9404. openOspfStaticNbrModal(id);
  9405. }
  9406. function closeOspfStaticNbrModal() {
  9407. document.getElementById('ospf-static-nbr-modal').classList.add('hidden');
  9408. }
  9409. async function submitOspfStaticNbr(e) {
  9410. if (e) e.preventDefault();
  9411. const payload = {
  9412. id: document.getElementById('modal-ospf-snbr-id').value,
  9413. address: document.getElementById('modal-ospf-snbr-address').value.trim(),
  9414. area: document.getElementById('modal-ospf-snbr-area').value,
  9415. poll_interval: parseInt(document.getElementById('modal-ospf-snbr-poll').value, 10) || 120,
  9416. cost: parseInt(document.getElementById('modal-ospf-snbr-cost').value, 10) || 1,
  9417. disabled: !document.getElementById('modal-ospf-snbr-enabled').checked,
  9418. comment: document.getElementById('modal-ospf-snbr-comment').value.trim()
  9419. };
  9420. try {
  9421. const res = await fetch(`${API_BASE}/routing/ospf/static-neighbors`, {
  9422. method: 'POST',
  9423. headers: { 'Content-Type': 'application/json' },
  9424. body: JSON.stringify(payload)
  9425. });
  9426. if (res.ok) {
  9427. closeOspfStaticNbrModal();
  9428. showToast('Saved', 'Static neighbor saved', 'success');
  9429. loadDynamicRouting();
  9430. } else {
  9431. const err = await res.json();
  9432. showToast('Error', err.error || 'Failed to save static neighbor', 'error');
  9433. }
  9434. } catch (err) {
  9435. showToast('Error', err.message, 'error');
  9436. }
  9437. }
  9438. function applyOspfStaticNbrForm() {
  9439. submitOspfStaticNbr(null);
  9440. }
  9441. async function deleteCurrentOspfStaticNbr() {
  9442. const id = document.getElementById('modal-ospf-snbr-id').value;
  9443. if (!id) return;
  9444. if (!confirm('Delete this static neighbor?')) return;
  9445. try {
  9446. await fetch(`${API_BASE}/routing/ospf/static-neighbors/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9447. closeOspfStaticNbrModal();
  9448. showToast('Removed', 'Static neighbor removed', 'success');
  9449. loadDynamicRouting();
  9450. } catch (err) {
  9451. showToast('Error', err.message, 'error');
  9452. }
  9453. }
  9454. async function enableSelectedOspfStaticNbr() {
  9455. const id = state.selectedOspfRow?.['static-nbrs'];
  9456. if (!id) return;
  9457. const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
  9458. if (!n) return;
  9459. n.disabled = false;
  9460. await fetch(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(n) });
  9461. loadDynamicRouting();
  9462. }
  9463. async function disableSelectedOspfStaticNbr() {
  9464. const id = state.selectedOspfRow?.['static-nbrs'];
  9465. if (!id) return;
  9466. const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
  9467. if (!n) return;
  9468. n.disabled = true;
  9469. await fetch(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(n) });
  9470. loadDynamicRouting();
  9471. }
  9472. async function removeSelectedOspfStaticNbr() {
  9473. const id = state.selectedOspfRow?.['static-nbrs'];
  9474. if (!id) return;
  9475. if (!confirm('Delete selected static neighbor?')) return;
  9476. await fetch(`${API_BASE}/routing/ospf/static-neighbors/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9477. loadDynamicRouting();
  9478. }
  9479. async function promptCommentOspfStaticNbr() {
  9480. const id = state.selectedOspfRow?.['static-nbrs'];
  9481. if (!id) return;
  9482. const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
  9483. if (!n) return;
  9484. const comment = prompt('Enter comment for static neighbor:', n.comment || '');
  9485. if (comment === null) return;
  9486. n.comment = comment;
  9487. await fetch(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(n) });
  9488. loadDynamicRouting();
  9489. }
  9490. // Backward-compat aliases
  9491. function openAddOspfInterfaceModal() { openOspfTemplateModal(); }
  9492. function openEditOspfInterfaceModal(id) { openEditOspfTemplateModal(id); }
  9493. function closeOspfInterfaceModal() { closeOspfTemplateModal(); }
  9494. function submitOspfInterface(e) { submitOspfTemplate(e); }
  9495. function deleteOspfInterface(id) {
  9496. fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' }).then(() => loadDynamicRouting());
  9497. }
  9498. function toggleOspfInterfaceState(id, disabled) {
  9499. fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  9500. method: 'POST',
  9501. headers: { 'Content-Type': 'application/json' },
  9502. body: JSON.stringify({ disabled })
  9503. }).then(() => loadDynamicRouting());
  9504. }
  9505. function openAddOspfAreaModal() { openOspfAreaModal(); }
  9506. function deleteOspfArea(id) {
  9507. fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' }).then(() => loadDynamicRouting());
  9508. }
  9509. // ============================================================================
  9510. // ==================== MIKROTIK BRIDGE SUBSYSTEM ==============================
  9511. // ============================================================================
  9512. function switchBridgeSubTab(tab) {
  9513. state.bridgeSubTab = tab;
  9514. const tabs = ['bridges', 'ports', 'vlans', 'hosts'];
  9515. tabs.forEach(t => {
  9516. const panel = document.getElementById(`bridge-subtab-${t}`);
  9517. const btn = document.getElementById(`bridge-subtab-btn-${t}`);
  9518. if (panel) {
  9519. if (t === tab) panel.classList.remove('hidden');
  9520. else panel.classList.add('hidden');
  9521. }
  9522. if (btn) {
  9523. if (t === tab) {
  9524. btn.className = 'px-4 py-2 text-xs font-bold rounded-lg bg-slate-800 text-white shadow-sm transition flex items-center gap-2';
  9525. } else {
  9526. btn.className = 'px-4 py-2 text-xs font-bold rounded-lg text-slate-400 hover:text-slate-200 transition flex items-center gap-2';
  9527. }
  9528. }
  9529. });
  9530. const addBtn = document.getElementById('bridge-top-action-btn');
  9531. if (addBtn) {
  9532. if (tab === 'bridges') addBtn.innerHTML = '<span>+ Add Bridge</span>';
  9533. else if (tab === 'ports') addBtn.innerHTML = '<span>+ Add Port</span>';
  9534. else if (tab === 'vlans') addBtn.innerHTML = '<span>+ Add VLAN Entry</span>';
  9535. else if (tab === 'hosts') addBtn.innerHTML = '<span>🔄 Refresh MACs</span>';
  9536. }
  9537. if (tab === 'hosts') loadBridgeHosts();
  9538. setTimeout(initTableSorting, 50);
  9539. }
  9540. function openCurrentBridgeModal() {
  9541. if (state.bridgeSubTab === 'bridges') openAddBridgeModal();
  9542. else if (state.bridgeSubTab === 'ports') openAddBridgePortModal();
  9543. else if (state.bridgeSubTab === 'vlans') openAddBridgeVLANModal();
  9544. else if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  9545. }
  9546. async function loadBridge() {
  9547. try {
  9548. const [bridgesRes, portsRes, vlansRes, summaryRes, eoipRes, vlanIfacesRes] = await Promise.all([
  9549. fetch(`${API_BASE}/bridge/bridges`),
  9550. fetch(`${API_BASE}/bridge/ports`),
  9551. fetch(`${API_BASE}/bridge/vlans`),
  9552. fetch(`${API_BASE}/bridge/summary`),
  9553. fetch(`${API_BASE}/vpn/eoip`),
  9554. fetch(`${API_BASE}/vlans`)
  9555. ]);
  9556. if (bridgesRes.ok) state.bridges = await bridgesRes.json();
  9557. if (portsRes.ok) state.bridgePorts = await portsRes.json();
  9558. if (vlansRes.ok) state.bridgeVLANs = await vlansRes.json();
  9559. if (summaryRes.ok) state.bridgeSummary = await summaryRes.json();
  9560. if (eoipRes && eoipRes.ok) state.eoipTunnels = await eoipRes.json();
  9561. if (vlanIfacesRes && vlanIfacesRes.ok) state.vlans = await vlanIfacesRes.json();
  9562. // Badges & Stats
  9563. const bBridges = document.getElementById('bridge-badge-bridges');
  9564. if (bBridges) bBridges.innerText = (state.bridges || []).length;
  9565. const bPorts = document.getElementById('bridge-badge-ports');
  9566. if (bPorts) bPorts.innerText = (state.bridgePorts || []).length;
  9567. const bVlans = document.getElementById('bridge-badge-vlans');
  9568. if (bVlans) bVlans.innerText = (state.bridgeVLANs || []).length;
  9569. const bHosts = document.getElementById('bridge-badge-hosts');
  9570. if (bHosts) bHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  9571. const sBr = document.getElementById('bridge-stat-bridges');
  9572. if (sBr) sBr.innerText = (state.bridges || []).length;
  9573. const sPorts = document.getElementById('bridge-stat-ports');
  9574. if (sPorts) sPorts.innerText = (state.bridgePorts || []).length;
  9575. const sHosts = document.getElementById('bridge-stat-hosts');
  9576. if (sHosts) sHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  9577. renderBridges();
  9578. renderBridgePorts();
  9579. renderBridgeVLANs();
  9580. if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  9581. } catch (err) {
  9582. console.error('Failed to load bridge subsystem:', err);
  9583. }
  9584. }
  9585. // ----------------- Bridges -----------------
  9586. function renderBridges() {
  9587. const tbody = document.getElementById('bridge-table-body');
  9588. const empty = document.getElementById('bridge-empty-bridges');
  9589. const countBadge = document.getElementById('bridge-count-badge');
  9590. if (!tbody) return;
  9591. tbody.innerHTML = '';
  9592. const bridges = state.bridges || [];
  9593. if (countBadge) countBadge.innerText = `${bridges.length} Bridges`;
  9594. if (bridges.length === 0) {
  9595. empty?.classList.remove('hidden');
  9596. return;
  9597. }
  9598. empty?.classList.add('hidden');
  9599. bridges.forEach((b, idx) => {
  9600. const tr = document.createElement('tr');
  9601. tr.className = `hover:bg-slate-800/40 transition text-xs ${b.disabled ? 'opacity-50' : ''}`;
  9602. // Format IP addresses pill list
  9603. let ipsHtml = '<span class="text-slate-600 font-sans">None</span>';
  9604. if (b.ip_addresses && b.ip_addresses.length > 0) {
  9605. ipsHtml = b.ip_addresses.map(ip => `
  9606. <span class="inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px] font-mono bg-sky-950/80 border border-sky-800/40 text-sky-300">
  9607. <span>${ip}</span>
  9608. <button onclick="deleteBridgeIP('${b.id}', '${ip}')" class="text-slate-500 hover:text-rose-400 font-bold ml-0.5">×</button>
  9609. </span>
  9610. `).join(' ');
  9611. }
  9612. const runningFlag = b.running ? '<span class="text-emerald-400 font-bold" title="Running (R)">R</span>' : '<span class="text-slate-600">-</span>';
  9613. const disabledFlag = b.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '';
  9614. const flagDisplay = `${runningFlag}${disabledFlag ? ' ' + disabledFlag : ''}`;
  9615. tr.innerHTML = `
  9616. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  9617. <td class="py-2.5 px-3 text-center font-mono">${flagDisplay}</td>
  9618. <td class="py-2.5 px-3 font-bold text-white text-sm">
  9619. <span class="text-sky-400 mr-1.5">🌉</span>${b.name}
  9620. </td>
  9621. <td class="py-2.5 px-3 text-slate-300">${b.mtu}</td>
  9622. <td class="py-2.5 px-3 font-mono text-slate-300 text-[11px]">${b.mac_address || '-'}</td>
  9623. <td class="py-2.5 px-3">
  9624. <span class="px-1.5 py-0.5 rounded text-[10px] font-bold ${b.stp === 'none' ? 'bg-slate-800 text-slate-400' : 'bg-sky-950 text-sky-300 border border-sky-800/40'} uppercase">${b.stp}</span>
  9625. </td>
  9626. <td class="py-2.5 px-3 text-center">
  9627. ${b.vlan_filtering ? '<span class="text-emerald-400 font-bold">yes</span>' : '<span class="text-slate-500">no</span>'}
  9628. </td>
  9629. <td class="py-2.5 px-3 font-mono">${b.pvid || 1}</td>
  9630. <td class="py-2.5 px-3">
  9631. <span class="px-2 py-0.5 rounded-full text-[10px] font-bold ${b.ports_count > 0 ? 'bg-sky-950 text-sky-400 border border-sky-800/40' : 'bg-slate-800 text-slate-500'} font-mono">${b.ports_count}</span>
  9632. </td>
  9633. <td class="py-2.5 px-3">
  9634. <div class="flex items-center gap-1.5 flex-wrap">
  9635. ${ipsHtml}
  9636. <button onclick="openAddBridgeIPModal('${b.id}', '${b.name}')" class="px-1.5 py-0.2 rounded text-[10px] bg-slate-800 hover:bg-slate-700 text-slate-300 border border-slate-700 font-sans" title="Add IP to Bridge">+ IP</button>
  9637. </div>
  9638. </td>
  9639. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  9640. <span class="text-emerald-400">↓ ${b.rx_human || '0 B'}</span> / <span class="text-cyan-400">↑ ${b.tx_human || '0 B'}</span>
  9641. </td>
  9642. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${b.comment || ''}">${b.comment || '-'}</td>
  9643. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  9644. <button onclick="toggleBridgeState('${b.id}', ${!b.disabled})" class="text-xs ${b.disabled ? 'text-emerald-400' : 'text-slate-400'} hover:underline font-semibold">${b.disabled ? 'Enable' : 'Disable'}</button>
  9645. <button onclick="openEditBridgeModal('${b.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  9646. <button onclick="deleteBridge('${b.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  9647. </td>
  9648. `;
  9649. tbody.appendChild(tr);
  9650. });
  9651. }
  9652. function openAddBridgeModal() {
  9653. document.getElementById('bridge-modal-title').innerText = 'Add Bridge Interface';
  9654. document.getElementById('bridge-modal-id').value = '';
  9655. document.getElementById('bridge-modal-name').value = 'bridge1';
  9656. document.getElementById('bridge-modal-name').disabled = false;
  9657. document.getElementById('bridge-modal-mtu').value = '1500';
  9658. document.getElementById('bridge-modal-mac').value = '';
  9659. document.getElementById('bridge-modal-stp').value = 'rstp';
  9660. document.getElementById('bridge-modal-priority').value = '32768';
  9661. document.getElementById('bridge-modal-vlanfiltering').checked = false;
  9662. document.getElementById('bridge-modal-pvid').value = '1';
  9663. document.getElementById('bridge-modal-fastforward').checked = true;
  9664. document.getElementById('bridge-modal-comment').value = '';
  9665. document.getElementById('bridge-modal-disabled').checked = false;
  9666. toggleBridgeModalVlanFiltering();
  9667. document.getElementById('bridge-modal').classList.remove('hidden');
  9668. }
  9669. function openEditBridgeModal(id) {
  9670. const b = (state.bridges || []).find(x => x.id === id);
  9671. if (!b) return;
  9672. document.getElementById('bridge-modal-title').innerText = `Edit Bridge (${b.name})`;
  9673. document.getElementById('bridge-modal-id').value = b.id;
  9674. document.getElementById('bridge-modal-name').value = b.name;
  9675. document.getElementById('bridge-modal-name').disabled = true;
  9676. document.getElementById('bridge-modal-mtu').value = b.mtu || 1500;
  9677. document.getElementById('bridge-modal-mac').value = b.mac_address || '';
  9678. document.getElementById('bridge-modal-stp').value = b.stp || 'rstp';
  9679. document.getElementById('bridge-modal-priority').value = b.priority || 32768;
  9680. document.getElementById('bridge-modal-vlanfiltering').checked = !!b.vlan_filtering;
  9681. document.getElementById('bridge-modal-pvid').value = b.pvid || 1;
  9682. document.getElementById('bridge-modal-fastforward').checked = b.fast_forward !== false;
  9683. document.getElementById('bridge-modal-comment').value = b.comment || '';
  9684. document.getElementById('bridge-modal-disabled').checked = !!b.disabled;
  9685. toggleBridgeModalVlanFiltering();
  9686. document.getElementById('bridge-modal').classList.remove('hidden');
  9687. }
  9688. function closeBridgeModal() {
  9689. document.getElementById('bridge-modal').classList.add('hidden');
  9690. }
  9691. function toggleBridgeModalVlanFiltering() {
  9692. const chk = document.getElementById('bridge-modal-vlanfiltering').checked;
  9693. const pvidBox = document.getElementById('bridge-modal-pvid-box');
  9694. if (pvidBox) {
  9695. if (chk) pvidBox.classList.remove('opacity-40');
  9696. else pvidBox.classList.add('opacity-40');
  9697. }
  9698. }
  9699. async function submitSaveBridge(e) {
  9700. e.preventDefault();
  9701. const id = document.getElementById('bridge-modal-id').value;
  9702. const name = document.getElementById('bridge-modal-name').value.trim();
  9703. const mtu = parseInt(document.getElementById('bridge-modal-mtu').value, 10) || 1500;
  9704. const mac = document.getElementById('bridge-modal-mac').value.trim();
  9705. const stp = document.getElementById('bridge-modal-stp').value;
  9706. const priority = parseInt(document.getElementById('bridge-modal-priority').value, 10) || 32768;
  9707. const vlanFiltering = document.getElementById('bridge-modal-vlanfiltering').checked;
  9708. const pvid = parseInt(document.getElementById('bridge-modal-pvid').value, 10) || 1;
  9709. const fastForward = document.getElementById('bridge-modal-fastforward').checked;
  9710. const comment = document.getElementById('bridge-modal-comment').value.trim();
  9711. const disabled = document.getElementById('bridge-modal-disabled').checked;
  9712. try {
  9713. const res = await fetch(`${API_BASE}/bridge/bridges`, {
  9714. method: 'POST',
  9715. headers: { 'Content-Type': 'application/json' },
  9716. body: JSON.stringify({
  9717. id,
  9718. name,
  9719. mtu,
  9720. mac_address: mac,
  9721. stp,
  9722. priority,
  9723. vlan_filtering: vlanFiltering,
  9724. pvid,
  9725. fast_forward: fastForward,
  9726. comment,
  9727. disabled
  9728. })
  9729. });
  9730. if (res.ok) {
  9731. showToast('Bridge Saved', `Bridge ${name} configured`, 'success');
  9732. closeBridgeModal();
  9733. loadBridge();
  9734. fetchData(false);
  9735. } else {
  9736. const err = await res.json();
  9737. showToast('Error', err.error || err.message || 'Failed to save bridge', 'error');
  9738. }
  9739. } catch (err) {
  9740. showToast('Error', err.message, 'error');
  9741. }
  9742. }
  9743. async function toggleBridgeState(id, disabled) {
  9744. try {
  9745. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/state`, {
  9746. method: 'POST',
  9747. headers: { 'Content-Type': 'application/json' },
  9748. body: JSON.stringify({ disabled })
  9749. });
  9750. if (res.ok) {
  9751. loadBridge();
  9752. fetchData(false);
  9753. }
  9754. } catch (err) {
  9755. showToast('Error', err.message, 'error');
  9756. }
  9757. }
  9758. async function deleteBridge(id) {
  9759. const b = (state.bridges || []).find(x => x.id === id);
  9760. const name = b ? b.name : id;
  9761. if (!confirm(`Are you sure you want to delete bridge '${name}'? All member ports will be detached.`)) return;
  9762. try {
  9763. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9764. if (res.ok) {
  9765. showToast('Deleted', `Bridge ${name} deleted`, 'success');
  9766. loadBridge();
  9767. fetchData(false);
  9768. } else {
  9769. const err = await res.json();
  9770. showToast('Error', err.error || err.message || 'Failed to delete bridge', 'error');
  9771. }
  9772. } catch (err) {
  9773. showToast('Error', err.message, 'error');
  9774. }
  9775. }
  9776. // ----------------- Bridge IP Assignments -----------------
  9777. function openAddBridgeIPModal(id, name) {
  9778. document.getElementById('bridge-ip-modal-id').value = id;
  9779. document.getElementById('bridge-ip-modal-sub').innerText = name;
  9780. document.getElementById('bridge-ip-modal-cidr').value = '';
  9781. document.getElementById('bridge-ip-modal').classList.remove('hidden');
  9782. }
  9783. function closeBridgeIPModal() {
  9784. document.getElementById('bridge-ip-modal').classList.add('hidden');
  9785. }
  9786. async function submitAddBridgeIP(e) {
  9787. e.preventDefault();
  9788. const id = document.getElementById('bridge-ip-modal-id').value;
  9789. const ip = document.getElementById('bridge-ip-modal-cidr').value.trim();
  9790. try {
  9791. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  9792. method: 'POST',
  9793. headers: { 'Content-Type': 'application/json' },
  9794. body: JSON.stringify({ ip })
  9795. });
  9796. if (res.ok) {
  9797. showToast('IP Assigned', `${ip} assigned to bridge`, 'success');
  9798. closeBridgeIPModal();
  9799. loadBridge();
  9800. fetchData(false);
  9801. } else {
  9802. const err = await res.json();
  9803. showToast('Error', err.error || err.message || 'Failed to add IP', 'error');
  9804. }
  9805. } catch (err) {
  9806. showToast('Error', err.message, 'error');
  9807. }
  9808. }
  9809. async function deleteBridgeIP(id, ip) {
  9810. if (!confirm(`Remove IP address ${ip} from bridge?`)) return;
  9811. try {
  9812. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  9813. method: 'DELETE',
  9814. headers: { 'Content-Type': 'application/json' },
  9815. body: JSON.stringify({ ip })
  9816. });
  9817. if (res.ok) {
  9818. showToast('IP Removed', `${ip} removed from bridge`, 'success');
  9819. loadBridge();
  9820. fetchData(false);
  9821. }
  9822. } catch (err) {
  9823. showToast('Error', err.message, 'error');
  9824. }
  9825. }
  9826. // ----------------- Bridge Ports -----------------
  9827. function renderBridgePorts() {
  9828. const tbody = document.getElementById('bridge-ports-table-body');
  9829. const empty = document.getElementById('bridge-empty-ports');
  9830. const countBadge = document.getElementById('bridge-ports-count-badge');
  9831. const filterBridge = document.getElementById('bridge-ports-filter-bridge')?.value || '';
  9832. if (!tbody) return;
  9833. tbody.innerHTML = '';
  9834. // Update filter select
  9835. populateBridgeSelect('bridge-ports-filter-bridge', filterBridge, true);
  9836. const ports = (state.bridgePorts || []).filter(p => !filterBridge || p.bridge === filterBridge);
  9837. if (countBadge) countBadge.innerText = `${ports.length} Ports`;
  9838. if (ports.length === 0) {
  9839. empty?.classList.remove('hidden');
  9840. return;
  9841. }
  9842. empty?.classList.add('hidden');
  9843. ports.forEach((p, idx) => {
  9844. const tr = document.createElement('tr');
  9845. tr.className = `hover:bg-slate-800/40 transition text-xs ${p.disabled ? 'opacity-50' : ''}`;
  9846. const disabledFlag = p.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  9847. tr.innerHTML = `
  9848. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  9849. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  9850. <td class="py-2.5 px-3 font-bold text-white text-sm">
  9851. <span class="text-emerald-400 mr-1.5">🔌</span>${p.interface}
  9852. </td>
  9853. <td class="py-2.5 px-3 font-semibold text-sky-400">${p.bridge}</td>
  9854. <td class="py-2.5 px-3 font-mono">${p.pvid || 1}</td>
  9855. <td class="py-2.5 px-3 text-slate-300">${p.frame_types}</td>
  9856. <td class="py-2.5 px-3 text-center">${p.ingress_filtering ? '<span class="text-amber-400 font-bold">yes</span>' : '<span class="text-slate-500">no</span>'}</td>
  9857. <td class="py-2.5 px-3">
  9858. ${p.horizon > 0 ? `<span class="px-1.5 py-0.5 rounded text-[10px] bg-purple-950 text-purple-300 border border-purple-800/40 font-mono">domain ${p.horizon}</span>` : '<span class="text-slate-500">none</span>'}
  9859. </td>
  9860. <td class="py-2.5 px-3">
  9861. <span class="px-2 py-0.5 rounded text-[10px] font-bold ${p.status === 'forwarding' ? 'bg-emerald-950 text-emerald-400 border border-emerald-800/40' : 'bg-slate-800 text-slate-400'} uppercase font-mono">${p.status}</span>
  9862. </td>
  9863. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${p.comment || ''}">${p.comment || '-'}</td>
  9864. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  9865. <button onclick="toggleBridgePortState('${p.id}', ${!p.disabled})" class="text-xs ${p.disabled ? 'text-emerald-400' : 'text-slate-400'} hover:underline font-semibold">${p.disabled ? 'Enable' : 'Disable'}</button>
  9866. <button onclick="openEditBridgePortModal('${p.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  9867. <button onclick="deleteBridgePort('${p.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  9868. </td>
  9869. `;
  9870. tbody.appendChild(tr);
  9871. });
  9872. }
  9873. function openAddBridgePortModal() {
  9874. document.getElementById('bridge-port-modal-title').innerText = 'Add Port to Bridge';
  9875. document.getElementById('bridge-port-modal-id').value = '';
  9876. populateBridgeSelect('bridge-port-modal-bridge');
  9877. populateBridgePortCandidateSelect('bridge-port-modal-interface');
  9878. document.getElementById('bridge-port-modal-pvid').value = '1';
  9879. document.getElementById('bridge-port-modal-frametypes').value = 'admit-all';
  9880. document.getElementById('bridge-port-modal-ingressfiltering').checked = false;
  9881. document.getElementById('bridge-port-modal-horizon').value = '0';
  9882. document.getElementById('bridge-port-modal-pathcost').value = '10';
  9883. document.getElementById('bridge-port-modal-priority').value = '128';
  9884. document.getElementById('bridge-port-modal-learn').checked = true;
  9885. document.getElementById('bridge-port-modal-comment').value = '';
  9886. document.getElementById('bridge-port-modal-disabled').checked = false;
  9887. document.getElementById('bridge-port-modal').classList.remove('hidden');
  9888. }
  9889. function openEditBridgePortModal(id) {
  9890. const p = (state.bridgePorts || []).find(x => x.id === id);
  9891. if (!p) return;
  9892. document.getElementById('bridge-port-modal-title').innerText = `Edit Bridge Port (${p.interface})`;
  9893. document.getElementById('bridge-port-modal-id').value = p.id;
  9894. populateBridgeSelect('bridge-port-modal-bridge', p.bridge);
  9895. populateBridgePortCandidateSelect('bridge-port-modal-interface', p.interface);
  9896. document.getElementById('bridge-port-modal-pvid').value = p.pvid || 1;
  9897. document.getElementById('bridge-port-modal-frametypes').value = p.frame_types || 'admit-all';
  9898. document.getElementById('bridge-port-modal-ingressfiltering').checked = !!p.ingress_filtering;
  9899. document.getElementById('bridge-port-modal-horizon').value = p.horizon || 0;
  9900. document.getElementById('bridge-port-modal-pathcost').value = p.path_cost || 10;
  9901. document.getElementById('bridge-port-modal-priority').value = p.priority || 128;
  9902. document.getElementById('bridge-port-modal-learn').checked = p.learn !== false;
  9903. document.getElementById('bridge-port-modal-comment').value = p.comment || '';
  9904. document.getElementById('bridge-port-modal-disabled').checked = !!p.disabled;
  9905. document.getElementById('bridge-port-modal').classList.remove('hidden');
  9906. }
  9907. function closeBridgePortModal() {
  9908. document.getElementById('bridge-port-modal').classList.add('hidden');
  9909. }
  9910. async function submitSaveBridgePort(e) {
  9911. e.preventDefault();
  9912. const id = document.getElementById('bridge-port-modal-id').value;
  9913. const bridge = document.getElementById('bridge-port-modal-bridge').value;
  9914. const iface = document.getElementById('bridge-port-modal-interface').value;
  9915. const pvid = parseInt(document.getElementById('bridge-port-modal-pvid').value, 10) || 1;
  9916. const frameTypes = document.getElementById('bridge-port-modal-frametypes').value;
  9917. const ingressFiltering = document.getElementById('bridge-port-modal-ingressfiltering').checked;
  9918. const horizon = parseInt(document.getElementById('bridge-port-modal-horizon').value, 10) || 0;
  9919. const pathCost = parseInt(document.getElementById('bridge-port-modal-pathcost').value, 10) || 10;
  9920. const priority = parseInt(document.getElementById('bridge-port-modal-priority').value, 10) || 128;
  9921. const learn = document.getElementById('bridge-port-modal-learn').checked;
  9922. const comment = document.getElementById('bridge-port-modal-comment').value.trim();
  9923. const disabled = document.getElementById('bridge-port-modal-disabled').checked;
  9924. try {
  9925. const res = await fetch(`${API_BASE}/bridge/ports`, {
  9926. method: 'POST',
  9927. headers: { 'Content-Type': 'application/json' },
  9928. body: JSON.stringify({
  9929. id,
  9930. bridge,
  9931. interface: iface,
  9932. pvid,
  9933. frame_types: frameTypes,
  9934. ingress_filtering: ingressFiltering,
  9935. horizon,
  9936. path_cost: pathCost,
  9937. priority,
  9938. learn,
  9939. comment,
  9940. disabled
  9941. })
  9942. });
  9943. if (res.ok) {
  9944. showToast('Port Attached', `${iface} added to ${bridge}`, 'success');
  9945. closeBridgePortModal();
  9946. loadBridge();
  9947. fetchData(false);
  9948. } else {
  9949. const err = await res.json();
  9950. showToast('Error', err.error || err.message || 'Failed to save port', 'error');
  9951. }
  9952. } catch (err) {
  9953. showToast('Error', err.message, 'error');
  9954. }
  9955. }
  9956. async function toggleBridgePortState(id, disabled) {
  9957. try {
  9958. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}/state`, {
  9959. method: 'POST',
  9960. headers: { 'Content-Type': 'application/json' },
  9961. body: JSON.stringify({ disabled })
  9962. });
  9963. if (res.ok) {
  9964. loadBridge();
  9965. fetchData(false);
  9966. }
  9967. } catch (err) {
  9968. showToast('Error', err.message, 'error');
  9969. }
  9970. }
  9971. async function deleteBridgePort(id) {
  9972. const p = (state.bridgePorts || []).find(x => x.id === id);
  9973. const iface = p ? p.interface : id;
  9974. if (!confirm(`Detach interface '${iface}' from bridge?`)) return;
  9975. try {
  9976. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9977. if (res.ok) {
  9978. showToast('Port Detached', `${iface} removed from bridge`, 'success');
  9979. loadBridge();
  9980. fetchData(false);
  9981. }
  9982. } catch (err) {
  9983. showToast('Error', err.message, 'error');
  9984. }
  9985. }
  9986. // ----------------- Bridge VLANs -----------------
  9987. function renderBridgeVLANs() {
  9988. const tbody = document.getElementById('bridge-vlans-table-body');
  9989. const empty = document.getElementById('bridge-empty-vlans');
  9990. const countBadge = document.getElementById('bridge-vlans-count-badge');
  9991. const filterBridge = document.getElementById('bridge-vlans-filter-bridge')?.value || '';
  9992. if (!tbody) return;
  9993. tbody.innerHTML = '';
  9994. populateBridgeSelect('bridge-vlans-filter-bridge', filterBridge, true);
  9995. const vlans = (state.bridgeVLANs || []).filter(v => !filterBridge || v.bridge === filterBridge);
  9996. if (countBadge) countBadge.innerText = `${vlans.length} Entries`;
  9997. if (vlans.length === 0) {
  9998. empty?.classList.remove('hidden');
  9999. return;
  10000. }
  10001. empty?.classList.add('hidden');
  10002. vlans.forEach((v, idx) => {
  10003. const tr = document.createElement('tr');
  10004. tr.className = `hover:bg-slate-800/40 transition text-xs ${v.disabled ? 'opacity-50' : ''}`;
  10005. const taggedHtml = (v.tagged && v.tagged.length > 0)
  10006. ? v.tagged.map(p => `<span class="px-1.5 py-0.5 rounded text-[10px] bg-cyan-950/80 border border-cyan-800/40 text-cyan-300 font-mono">${p}</span>`).join(' ')
  10007. : '<span class="text-slate-600">none</span>';
  10008. const untaggedHtml = (v.untagged && v.untagged.length > 0)
  10009. ? v.untagged.map(p => `<span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 border border-slate-700/60 text-slate-300 font-mono">${p}</span>`).join(' ')
  10010. : '<span class="text-slate-600">none</span>';
  10011. const disabledFlag = v.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  10012. tr.innerHTML = `
  10013. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  10014. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  10015. <td class="py-2.5 px-3 font-semibold text-sky-400">${v.bridge}</td>
  10016. <td class="py-2.5 px-3 font-bold text-white font-mono text-sm">${v.vlan_ids}</td>
  10017. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${taggedHtml}</div></td>
  10018. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${untaggedHtml}</div></td>
  10019. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${v.comment || ''}">${v.comment || '-'}</td>
  10020. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  10021. <button onclick="toggleBridgeVLANState('${v.id}', ${!v.disabled})" class="text-xs ${v.disabled ? 'text-emerald-400' : 'text-slate-400'} hover:underline font-semibold">${v.disabled ? 'Enable' : 'Disable'}</button>
  10022. <button onclick="openEditBridgeVLANModal('${v.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  10023. <button onclick="deleteBridgeVLAN('${v.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  10024. </td>
  10025. `;
  10026. tbody.appendChild(tr);
  10027. });
  10028. }
  10029. function openAddBridgeVLANModal() {
  10030. document.getElementById('bridge-vlan-modal-title').innerText = 'Add Bridge VLAN Entry';
  10031. document.getElementById('bridge-vlan-modal-id').value = '';
  10032. populateBridgeSelect('bridge-vlan-modal-bridge');
  10033. document.getElementById('bridge-vlan-modal-vlanids').value = '';
  10034. document.getElementById('bridge-vlan-modal-comment').value = '';
  10035. document.getElementById('bridge-vlan-modal-disabled').checked = false;
  10036. updateBridgeVlanPortCheckboxes();
  10037. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  10038. }
  10039. function openEditBridgeVLANModal(id) {
  10040. const v = (state.bridgeVLANs || []).find(x => x.id === id);
  10041. if (!v) return;
  10042. document.getElementById('bridge-vlan-modal-title').innerText = `Edit Bridge VLAN (${v.vlan_ids})`;
  10043. document.getElementById('bridge-vlan-modal-id').value = v.id;
  10044. populateBridgeSelect('bridge-vlan-modal-bridge', v.bridge);
  10045. document.getElementById('bridge-vlan-modal-vlanids').value = v.vlan_ids;
  10046. document.getElementById('bridge-vlan-modal-comment').value = v.comment || '';
  10047. document.getElementById('bridge-vlan-modal-disabled').checked = !!v.disabled;
  10048. updateBridgeVlanPortCheckboxes(v.tagged || [], v.untagged || []);
  10049. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  10050. }
  10051. function closeBridgeVlanModal() {
  10052. document.getElementById('bridge-vlan-modal').classList.add('hidden');
  10053. }
  10054. function updateBridgeVlanPortCheckboxes(taggedSelected = [], untaggedSelected = []) {
  10055. const selBridge = document.getElementById('bridge-vlan-modal-bridge')?.value || '';
  10056. const taggedBox = document.getElementById('bridge-vlan-tagged-ports');
  10057. const untaggedBox = document.getElementById('bridge-vlan-untagged-ports');
  10058. if (!taggedBox || !untaggedBox) return;
  10059. // Ports belonging to the selected bridge
  10060. const memberPorts = (state.bridgePorts || []).filter(p => !selBridge || p.bridge === selBridge);
  10061. if (memberPorts.length === 0) {
  10062. taggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  10063. untaggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  10064. return;
  10065. }
  10066. taggedBox.innerHTML = memberPorts.map(p => `
  10067. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  10068. <input type="checkbox" name="bvlan-tagged" value="${p.interface}" ${taggedSelected.includes(p.interface) ? 'checked' : ''} class="rounded bg-slate-800 border-slate-700 text-cyan-500">
  10069. <span>${p.interface}</span>
  10070. </label>
  10071. `).join('');
  10072. untaggedBox.innerHTML = memberPorts.map(p => `
  10073. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  10074. <input type="checkbox" name="bvlan-untagged" value="${p.interface}" ${untaggedSelected.includes(p.interface) ? 'checked' : ''} class="rounded bg-slate-800 border-slate-700 text-slate-400">
  10075. <span>${p.interface}</span>
  10076. </label>
  10077. `).join('');
  10078. }
  10079. async function submitSaveBridgeVLAN(e) {
  10080. e.preventDefault();
  10081. const id = document.getElementById('bridge-vlan-modal-id').value;
  10082. const bridge = document.getElementById('bridge-vlan-modal-bridge').value;
  10083. const vlanIDs = document.getElementById('bridge-vlan-modal-vlanids').value.trim();
  10084. const comment = document.getElementById('bridge-vlan-modal-comment').value.trim();
  10085. const disabled = document.getElementById('bridge-vlan-modal-disabled').checked;
  10086. const tagged = Array.from(document.querySelectorAll('input[name="bvlan-tagged"]:checked')).map(x => x.value);
  10087. const untagged = Array.from(document.querySelectorAll('input[name="bvlan-untagged"]:checked')).map(x => x.value);
  10088. try {
  10089. const res = await fetch(`${API_BASE}/bridge/vlans`, {
  10090. method: 'POST',
  10091. headers: { 'Content-Type': 'application/json' },
  10092. body: JSON.stringify({
  10093. id,
  10094. bridge,
  10095. vlan_ids: vlanIDs,
  10096. tagged,
  10097. untagged,
  10098. comment,
  10099. disabled
  10100. })
  10101. });
  10102. if (res.ok) {
  10103. showToast('VLAN Entry Saved', `VLAN ${vlanIDs} configured on ${bridge}`, 'success');
  10104. closeBridgeVlanModal();
  10105. loadBridge();
  10106. } else {
  10107. const err = await res.json();
  10108. showToast('Error', err.error || err.message || 'Failed to save VLAN entry', 'error');
  10109. }
  10110. } catch (err) {
  10111. showToast('Error', err.message, 'error');
  10112. }
  10113. }
  10114. async function toggleBridgeVLANState(id, disabled) {
  10115. try {
  10116. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}/state`, {
  10117. method: 'POST',
  10118. headers: { 'Content-Type': 'application/json' },
  10119. body: JSON.stringify({ disabled })
  10120. });
  10121. if (res.ok) loadBridge();
  10122. } catch (err) {
  10123. showToast('Error', err.message, 'error');
  10124. }
  10125. }
  10126. async function deleteBridgeVLAN(id) {
  10127. if (!confirm('Delete this bridge VLAN entry?')) return;
  10128. try {
  10129. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10130. if (res.ok) {
  10131. showToast('Deleted', 'VLAN entry removed from bridge', 'success');
  10132. loadBridge();
  10133. }
  10134. } catch (err) {
  10135. showToast('Error', err.message, 'error');
  10136. }
  10137. }
  10138. // ----------------- Hosts / MAC Table -----------------
  10139. async function loadBridgeHosts() {
  10140. const filterBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || '';
  10141. populateBridgeSelect('bridge-hosts-filter-bridge', filterBridge, true);
  10142. try {
  10143. const url = filterBridge ? `${API_BASE}/bridge/hosts?bridge=${encodeURIComponent(filterBridge)}` : `${API_BASE}/bridge/hosts`;
  10144. const res = await fetch(url);
  10145. if (res.ok) {
  10146. state.bridgeHosts = await res.json();
  10147. renderBridgeHosts();
  10148. }
  10149. } catch (err) {
  10150. console.error('Failed to load bridge hosts:', err);
  10151. }
  10152. }
  10153. function renderBridgeHosts() {
  10154. const tbody = document.getElementById('bridge-hosts-table-body');
  10155. const empty = document.getElementById('bridge-empty-hosts');
  10156. const countBadge = document.getElementById('bridge-hosts-count-badge');
  10157. const search = (document.getElementById('bridge-hosts-search')?.value || '').toLowerCase().trim();
  10158. if (!tbody) return;
  10159. tbody.innerHTML = '';
  10160. const hosts = (state.bridgeHosts || []).filter(h => {
  10161. if (!search) return true;
  10162. return (h.mac || '').toLowerCase().includes(search) || (h.interface || '').toLowerCase().includes(search) || (h.bridge || '').toLowerCase().includes(search);
  10163. });
  10164. if (countBadge) countBadge.innerText = `${hosts.length} Hosts`;
  10165. if (hosts.length === 0) {
  10166. empty?.classList.remove('hidden');
  10167. return;
  10168. }
  10169. empty?.classList.add('hidden');
  10170. hosts.forEach(h => {
  10171. const tr = document.createElement('tr');
  10172. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  10173. let flagBadges = '';
  10174. if (h.local) flagBadges += '<span class="px-1.5 py-0.2 rounded text-[10px] bg-sky-950 text-sky-400 border border-sky-800/40 font-mono font-bold mr-1" title="Local router interface MAC">L</span>';
  10175. if (h.static) flagBadges += '<span class="px-1.5 py-0.2 rounded text-[10px] bg-purple-950 text-purple-400 border border-purple-800/40 font-mono font-bold mr-1" title="Static entry">S</span>';
  10176. if (!h.local && !h.static) flagBadges += '<span class="px-1.5 py-0.2 rounded text-[10px] bg-emerald-950 text-emerald-400 border border-emerald-800/40 font-mono font-bold mr-1" title="Dynamically learned">D</span>';
  10177. tr.innerHTML = `
  10178. <td class="py-2.5 px-3 font-mono font-bold text-white text-sm">${h.mac}</td>
  10179. <td class="py-2.5 px-3 font-semibold text-emerald-400 font-mono">${h.interface || '-'}</td>
  10180. <td class="py-2.5 px-3 font-mono text-sky-400">${h.bridge || '-'}</td>
  10181. <td class="py-2.5 px-3 font-mono">${h.vlan_id || 1}</td>
  10182. <td class="py-2.5 px-3 font-mono text-slate-400">${h.age ? h.age.toFixed(1) + 's' : '-'}</td>
  10183. <td class="py-2.5 px-3">${flagBadges}</td>
  10184. `;
  10185. tbody.appendChild(tr);
  10186. });
  10187. }
  10188. async function flushBridgeHosts() {
  10189. const selBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || (state.bridges[0] ? state.bridges[0].name : '');
  10190. if (!selBridge) {
  10191. showToast('Notice', 'Please select a bridge to flush dynamic MACs', 'info');
  10192. return;
  10193. }
  10194. if (!confirm(`Flush all dynamic learned MAC addresses on bridge '${selBridge}'?`)) return;
  10195. try {
  10196. const res = await fetch(`${API_BASE}/bridge/hosts/flush`, {
  10197. method: 'POST',
  10198. headers: { 'Content-Type': 'application/json' },
  10199. body: JSON.stringify({ bridge: selBridge })
  10200. });
  10201. if (res.ok) {
  10202. showToast('FDB Flushed', `Dynamic MACs flushed on ${selBridge}`, 'success');
  10203. loadBridgeHosts();
  10204. }
  10205. } catch (err) {
  10206. showToast('Error', err.message, 'error');
  10207. }
  10208. }
  10209. // ----------------- Helpers -----------------
  10210. function populateBridgeSelect(selectId, currentVal = '', includeAll = false) {
  10211. const sel = document.getElementById(selectId);
  10212. if (!sel) return;
  10213. const prevVal = currentVal || sel.value;
  10214. sel.innerHTML = includeAll ? '<option value="">All Bridges</option>' : '';
  10215. (state.bridges || []).forEach(b => {
  10216. const opt = document.createElement('option');
  10217. opt.value = b.name;
  10218. opt.innerText = `${b.name} (${b.ports_count} ports)`;
  10219. if (b.name === prevVal) opt.selected = true;
  10220. sel.appendChild(opt);
  10221. });
  10222. }
  10223. function populateBridgePortCandidateSelect(selectId, currentVal = '') {
  10224. const sel = document.getElementById(selectId);
  10225. if (!sel) return;
  10226. sel.innerHTML = '<option value="">(Select Interface...)</option>';
  10227. // 1. Physical Interfaces
  10228. const grpPhys = document.createElement('optgroup');
  10229. grpPhys.label = 'Physical Interfaces';
  10230. (state.interfaces || []).filter(i => i.type !== 'bridge' && i.type !== 'vlan' && i.type !== 'loopback').forEach(i => {
  10231. const opt = document.createElement('option');
  10232. opt.value = i.name;
  10233. opt.innerText = `${i.name} (${i.role || i.type})`;
  10234. if (i.name === currentVal) opt.selected = true;
  10235. grpPhys.appendChild(opt);
  10236. });
  10237. if (grpPhys.children.length > 0) sel.appendChild(grpPhys);
  10238. // 2. VLAN Sub-interfaces
  10239. const grpVlans = document.createElement('optgroup');
  10240. grpVlans.label = 'VLAN Sub-interfaces (802.1Q)';
  10241. (state.vlans || []).forEach(v => {
  10242. const opt = document.createElement('option');
  10243. opt.value = v.name;
  10244. opt.innerText = `${v.name} (VLAN ${v.vlan_id})`;
  10245. if (v.name === currentVal) opt.selected = true;
  10246. grpVlans.appendChild(opt);
  10247. });
  10248. if (grpVlans.children.length > 0) sel.appendChild(grpVlans);
  10249. // 3. EoIP Tunnels (MikroTik EoIP bridging!)
  10250. const grpEoip = document.createElement('optgroup');
  10251. grpEoip.label = 'EoIP Tunnels (Layer 2 VPN)';
  10252. (state.eoipTunnels || []).forEach(t => {
  10253. const opt = document.createElement('option');
  10254. opt.value = t.name;
  10255. opt.innerText = `${t.name} (Tunnel ID: ${t.tunnel_id} -> ${t.remote_address})`;
  10256. if (t.name === currentVal) opt.selected = true;
  10257. grpEoip.appendChild(opt);
  10258. });
  10259. if (grpEoip.children.length > 0) sel.appendChild(grpEoip);
  10260. }
  10261. // -------------------------------------------------------------
  10262. // RouterOS v7 Routing Filters Management (/routing filter)
  10263. // -------------------------------------------------------------
  10264. if (!state.activeRoutingFilterTab) state.activeRoutingFilterTab = 'rules';
  10265. if (!state.selectedFilterRow) state.selectedFilterRow = {};
  10266. if (!state.rfSort) state.rfSort = {};
  10267. function switchRoutingFilterTab(tab) {
  10268. state.activeRoutingFilterTab = tab;
  10269. const tabs = ['rules', 'select-rules', 'community-lists', 'as-lists'];
  10270. tabs.forEach(t => {
  10271. const btn = document.getElementById(`tab-rf-${t}`);
  10272. const content = document.getElementById(`tab-content-rf-${t}`);
  10273. if (btn) {
  10274. if (t === tab) {
  10275. btn.className = 'px-3 py-1 text-xs font-semibold rounded bg-emerald-600/20 text-emerald-300 border border-emerald-500/30 transition shadow-sm';
  10276. } else {
  10277. btn.className = 'px-3 py-1 text-xs font-semibold rounded text-slate-400 hover:text-white hover:bg-slate-800 transition';
  10278. }
  10279. }
  10280. if (content) {
  10281. if (t === tab) content.classList.remove('hidden');
  10282. else content.classList.add('hidden');
  10283. }
  10284. });
  10285. const chainContainer = document.getElementById('rf-chain-filter-container');
  10286. if (chainContainer) {
  10287. if (tab === 'rules' || tab === 'select-rules') chainContainer.classList.remove('hidden');
  10288. else chainContainer.classList.add('hidden');
  10289. }
  10290. renderRoutingFilters();
  10291. }
  10292. function selectFilterRow(tab, id) {
  10293. if (state.selectedFilterRow[tab] === id) {
  10294. delete state.selectedFilterRow[tab];
  10295. } else {
  10296. state.selectedFilterRow[tab] = id;
  10297. }
  10298. if (tab === 'rules') renderRoutingFilterRules();
  10299. else if (tab === 'select-rules') renderRoutingFilterSelectRules();
  10300. else if (tab === 'community-lists') renderRoutingFilterCommunityLists();
  10301. else if (tab === 'as-lists') renderRoutingFilterASLists();
  10302. }
  10303. function openRoutingFilterNewModal() {
  10304. const tab = state.activeRoutingFilterTab || 'rules';
  10305. if (tab === 'rules') openAddRoutingFilterModal();
  10306. else if (tab === 'select-rules') openAddSelectRuleModal();
  10307. else if (tab === 'community-lists') openAddCommunityListModal();
  10308. else if (tab === 'as-lists') openAddASListModal();
  10309. }
  10310. function toggleSelectedRoutingFilter(disabled) {
  10311. const tab = state.activeRoutingFilterTab || 'rules';
  10312. const id = state.selectedFilterRow[tab];
  10313. if (!id) {
  10314. showToast('Select Row', 'Please click on a row to select it first', 'info');
  10315. return;
  10316. }
  10317. if (tab === 'rules') toggleRoutingFilterState(id, disabled);
  10318. else if (tab === 'select-rules') toggleSelectRuleState(id, disabled);
  10319. else if (tab === 'community-lists') toggleCommunityListState(id, disabled);
  10320. else if (tab === 'as-lists') toggleASListState(id, disabled);
  10321. }
  10322. function removeSelectedRoutingFilter() {
  10323. const tab = state.activeRoutingFilterTab || 'rules';
  10324. const id = state.selectedFilterRow[tab];
  10325. if (!id) {
  10326. showToast('Select Row', 'Please click on a row to select it first', 'info');
  10327. return;
  10328. }
  10329. if (tab === 'rules') deleteRoutingFilter(id);
  10330. else if (tab === 'select-rules') deleteSelectRule(id);
  10331. else if (tab === 'community-lists') deleteCommunityList(id);
  10332. else if (tab === 'as-lists') deleteASList(id);
  10333. }
  10334. function searchRoutingFilters(q) {
  10335. state.rfSearchQuery = (q || '').trim().toLowerCase();
  10336. renderRoutingFilters();
  10337. }
  10338. function sortFilterTable(tab, col) {
  10339. if (!state.rfSort) state.rfSort = {};
  10340. if (!state.rfSort[tab]) state.rfSort[tab] = { col: col, asc: true };
  10341. if (state.rfSort[tab].col === col) {
  10342. state.rfSort[tab].asc = !state.rfSort[tab].asc;
  10343. } else {
  10344. state.rfSort[tab].col = col;
  10345. state.rfSort[tab].asc = true;
  10346. }
  10347. const asc = state.rfSort[tab].asc;
  10348. let list = [];
  10349. if (tab === 'rules') list = state.routingFilters || [];
  10350. else if (tab === 'select-rules') list = state.routingSelectRules || [];
  10351. else if (tab === 'community-lists') list = state.routingCommunityLists || [];
  10352. else if (tab === 'as-lists') list = state.routingASLists || [];
  10353. list.sort((a, b) => {
  10354. let valA = a[col] ?? '';
  10355. let valB = b[col] ?? '';
  10356. if (col === 'flags') {
  10357. valA = a.disabled ? 'X' : 'A';
  10358. valB = b.disabled ? 'X' : 'A';
  10359. }
  10360. if (typeof valA === 'number' && typeof valB === 'number') {
  10361. return asc ? valA - valB : valB - valA;
  10362. }
  10363. return asc ? String(valA).localeCompare(String(valB)) : String(valB).localeCompare(String(valA));
  10364. });
  10365. const allCols = ['flags', 'rule_order', 'chain', 'rule', 'name', 'communities', 'range', 'regexp', 'comment'];
  10366. allCols.forEach(c => {
  10367. const el = document.getElementById(`sort-icon-${tab}-${c}`);
  10368. if (el) el.innerText = (c === col) ? (asc ? '▲' : '▼') : '';
  10369. });
  10370. if (tab === 'rules') renderRoutingFilterRules();
  10371. else if (tab === 'select-rules') renderRoutingFilterSelectRules();
  10372. else if (tab === 'community-lists') renderRoutingFilterCommunityLists();
  10373. else if (tab === 'as-lists') renderRoutingFilterASLists();
  10374. }
  10375. function renderRoutingFilters() {
  10376. const navBadge = document.getElementById('badge-filters-count');
  10377. const allRules = state.routingFilters || [];
  10378. if (navBadge) navBadge.innerText = allRules.length;
  10379. // Populate chain filter select options and datalist
  10380. const chainSelect = document.getElementById('routing-filter-chain-select');
  10381. const chainDatalist = document.getElementById('dl-routing-chains');
  10382. const uniqueChains = Array.from(new Set(allRules.map(r => r.chain).filter(Boolean))).sort();
  10383. if (chainSelect) {
  10384. const currentVal = state.filterChainSelected || 'all';
  10385. chainSelect.innerHTML = `<option value="all">All Chains (${allRules.length})</option>` +
  10386. uniqueChains.map(ch => {
  10387. const count = allRules.filter(r => r.chain === ch).length;
  10388. return `<option value="${escapeHtml(ch)}"${currentVal === ch ? ' selected' : ''}>${escapeHtml(ch)} (${count})</option>`;
  10389. }).join('');
  10390. chainSelect.value = currentVal;
  10391. }
  10392. if (chainDatalist) {
  10393. chainDatalist.innerHTML = uniqueChains.map(ch => `<option value="${escapeHtml(ch)}">`).join('');
  10394. }
  10395. renderRoutingFilterRules();
  10396. renderRoutingFilterSelectRules();
  10397. renderRoutingFilterCommunityLists();
  10398. renderRoutingFilterASLists();
  10399. }
  10400. function filterRoutingFiltersByChain(chain) {
  10401. state.filterChainSelected = chain;
  10402. renderRoutingFilters();
  10403. }
  10404. // -------------------------------------------------------------
  10405. // TAB 1: RULES (/routing filter rule)
  10406. // -------------------------------------------------------------
  10407. function renderRoutingFilterRules() {
  10408. const tbody = document.getElementById('routing-filter-rules-tbody');
  10409. if (!tbody) return;
  10410. const empty = document.getElementById('rf-rules-empty');
  10411. const statusCount = document.getElementById('rf-status-count');
  10412. let list = (state.routingFilters || []).slice();
  10413. if (state.filterChainSelected && state.filterChainSelected !== 'all') {
  10414. list = list.filter(r => r.chain === state.filterChainSelected);
  10415. }
  10416. const q = state.rfSearchQuery;
  10417. if (q) {
  10418. list = list.filter(r =>
  10419. (r.chain && r.chain.toLowerCase().includes(q)) ||
  10420. (r.rule && r.rule.toLowerCase().includes(q)) ||
  10421. (r.prefix && r.prefix.toLowerCase().includes(q)) ||
  10422. (r.comment && r.comment.toLowerCase().includes(q))
  10423. );
  10424. }
  10425. if (!state.rfSort?.['rules']) {
  10426. list.sort((a, b) => {
  10427. if (a.chain !== b.chain) return (a.chain || '').localeCompare(b.chain || '');
  10428. return (a.rule_order || 0) - (b.rule_order || 0);
  10429. });
  10430. }
  10431. if (statusCount && (state.activeRoutingFilterTab === 'rules' || !state.activeRoutingFilterTab)) {
  10432. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  10433. }
  10434. if (list.length === 0) {
  10435. tbody.innerHTML = '';
  10436. if (empty) empty.classList.remove('hidden');
  10437. return;
  10438. }
  10439. if (empty) empty.classList.add('hidden');
  10440. tbody.innerHTML = list.map(r => {
  10441. const isSelected = state.selectedFilterRow?.['rules'] === r.id;
  10442. const flagA = !r.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  10443. const flagX = r.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  10444. const flagC = r.comment ? '<span class="text-amber-400 font-bold ml-1" title="Comment">C</span>' : '';
  10445. let ruleDisplay = '';
  10446. if (r.rule && r.rule.trim() !== '') {
  10447. ruleDisplay = `<span class="text-emerald-400 font-mono font-medium">${escapeHtml(r.rule)}</span>`;
  10448. } else {
  10449. let conds = [];
  10450. if (r.prefix) conds.push(`dst in ${escapeHtml(r.prefix)}`);
  10451. if (r.match_protocol && r.match_protocol !== 'any') conds.push(`protocol ${escapeHtml(r.match_protocol)}`);
  10452. let act = r.action || 'accept';
  10453. ruleDisplay = `<span class="text-slate-300 font-mono">if (${conds.length ? conds.join(' && ') : 'true'}) { ${escapeHtml(act)}; }</span>`;
  10454. }
  10455. return `
  10456. <tr onclick="selectFilterRow('rules', '${r.id}')" class="cursor-pointer transition select-none ${isSelected ? 'bg-emerald-950/40 ring-1 ring-emerald-500/40' : 'hover:bg-slate-800/40'}">
  10457. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}${flagC}</td>
  10458. <td class="py-2 px-2 font-mono text-slate-400 font-bold">${r.rule_order || 10}</td>
  10459. <td class="py-2 px-3">
  10460. <span class="px-2 py-0.5 rounded text-[11px] font-mono bg-slate-800 text-cyan-300 border border-slate-700 font-semibold">${escapeHtml(r.chain)}</span>
  10461. </td>
  10462. <td class="py-2 px-3 break-all max-w-xl">${ruleDisplay}</td>
  10463. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(r.comment || '')}</td>
  10464. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  10465. <button onclick="moveRoutingFilterOrder('${r.id}', -1)" title="Move Up" class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 hover:bg-slate-700 text-slate-300 border border-slate-700">▲</button>
  10466. <button onclick="moveRoutingFilterOrder('${r.id}', 1)" title="Move Down" class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 hover:bg-slate-700 text-slate-300 border border-slate-700">▼</button>
  10467. <button onclick="toggleRoutingFilterState('${r.id}', ${!r.disabled})" class="px-2 py-0.5 rounded text-[10px] ${r.disabled ? 'bg-emerald-950 hover:bg-emerald-900 text-emerald-400 border border-emerald-800/50' : 'bg-slate-800 hover:bg-slate-700 text-slate-300 border border-slate-700'}">
  10468. ${r.disabled ? 'Enable' : 'Disable'}
  10469. </button>
  10470. <button onclick="openEditRoutingFilterModal('${r.id}')" class="px-2 py-0.5 rounded text-[10px] bg-slate-800 hover:bg-slate-700 text-emerald-300 border border-slate-700">
  10471. Edit
  10472. </button>
  10473. <button onclick="deleteRoutingFilter('${r.id}')" class="px-2 py-0.5 rounded text-[10px] bg-rose-950/60 hover:bg-rose-900 text-rose-300 border border-rose-900/50">
  10474. ✕
  10475. </button>
  10476. </td>
  10477. </tr>
  10478. `;
  10479. }).join('');
  10480. }
  10481. // -------------------------------------------------------------
  10482. // TAB 2: SELECT RULES (/routing filter select-rule)
  10483. // -------------------------------------------------------------
  10484. function renderRoutingFilterSelectRules() {
  10485. const tbody = document.getElementById('routing-filter-select-rules-tbody');
  10486. if (!tbody) return;
  10487. const empty = document.getElementById('rf-select-rules-empty');
  10488. const statusCount = document.getElementById('rf-status-count');
  10489. let list = (state.routingSelectRules || []).slice();
  10490. if (state.filterChainSelected && state.filterChainSelected !== 'all') {
  10491. list = list.filter(r => r.chain === state.filterChainSelected);
  10492. }
  10493. const q = state.rfSearchQuery;
  10494. if (q) {
  10495. list = list.filter(r =>
  10496. (r.chain && r.chain.toLowerCase().includes(q)) ||
  10497. (r.rule && r.rule.toLowerCase().includes(q)) ||
  10498. (r.comment && r.comment.toLowerCase().includes(q))
  10499. );
  10500. }
  10501. if (statusCount && state.activeRoutingFilterTab === 'select-rules') {
  10502. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  10503. }
  10504. if (list.length === 0) {
  10505. tbody.innerHTML = '';
  10506. if (empty) empty.classList.remove('hidden');
  10507. return;
  10508. }
  10509. if (empty) empty.classList.add('hidden');
  10510. tbody.innerHTML = list.map(r => {
  10511. const isSelected = state.selectedFilterRow?.['select-rules'] === r.id;
  10512. const flagA = !r.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  10513. const flagX = r.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  10514. return `
  10515. <tr onclick="selectFilterRow('select-rules', '${r.id}')" class="cursor-pointer transition select-none ${isSelected ? 'bg-emerald-950/40 ring-1 ring-emerald-500/40' : 'hover:bg-slate-800/40'}">
  10516. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  10517. <td class="py-2 px-2 font-mono text-slate-400 font-bold">${r.rule_order || 10}</td>
  10518. <td class="py-2 px-3">
  10519. <span class="px-2 py-0.5 rounded text-[11px] font-mono bg-slate-800 text-cyan-300 border border-slate-700 font-semibold">${escapeHtml(r.chain)}</span>
  10520. </td>
  10521. <td class="py-2 px-3 break-all max-w-xl font-mono text-emerald-400">${escapeHtml(r.rule || '')}</td>
  10522. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(r.comment || '')}</td>
  10523. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  10524. <button onclick="toggleSelectRuleState('${r.id}', ${!r.disabled})" class="px-2 py-0.5 rounded text-[10px] ${r.disabled ? 'bg-emerald-950 hover:bg-emerald-900 text-emerald-400 border border-emerald-800/50' : 'bg-slate-800 hover:bg-slate-700 text-slate-300 border border-slate-700'}">
  10525. ${r.disabled ? 'Enable' : 'Disable'}
  10526. </button>
  10527. <button onclick="openEditSelectRuleModal('${r.id}')" class="px-2 py-0.5 rounded text-[10px] bg-slate-800 hover:bg-slate-700 text-emerald-300 border border-slate-700">
  10528. Edit
  10529. </button>
  10530. <button onclick="deleteSelectRule('${r.id}')" class="px-2 py-0.5 rounded text-[10px] bg-rose-950/60 hover:bg-rose-900 text-rose-300 border border-rose-900/50">
  10531. ✕
  10532. </button>
  10533. </td>
  10534. </tr>
  10535. `;
  10536. }).join('');
  10537. }
  10538. // -------------------------------------------------------------
  10539. // TAB 3: COMMUNITY LISTS (/routing filter community-list)
  10540. // -------------------------------------------------------------
  10541. function renderRoutingFilterCommunityLists() {
  10542. const tbody = document.getElementById('routing-filter-comm-lists-tbody');
  10543. if (!tbody) return;
  10544. const empty = document.getElementById('rf-comm-lists-empty');
  10545. const statusCount = document.getElementById('rf-status-count');
  10546. let list = (state.routingCommunityLists || []).slice();
  10547. const q = state.rfSearchQuery;
  10548. if (q) {
  10549. list = list.filter(cl =>
  10550. (cl.name && cl.name.toLowerCase().includes(q)) ||
  10551. (cl.comment && cl.comment.toLowerCase().includes(q)) ||
  10552. (cl.communities && cl.communities.some(c => c.toLowerCase().includes(q)))
  10553. );
  10554. }
  10555. if (statusCount && state.activeRoutingFilterTab === 'community-lists') {
  10556. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  10557. }
  10558. if (list.length === 0) {
  10559. tbody.innerHTML = '';
  10560. if (empty) empty.classList.remove('hidden');
  10561. return;
  10562. }
  10563. if (empty) empty.classList.add('hidden');
  10564. tbody.innerHTML = list.map(cl => {
  10565. const isSelected = state.selectedFilterRow?.['community-lists'] === cl.id;
  10566. const flagA = !cl.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  10567. const flagX = cl.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  10568. const commBadges = (cl.communities || []).map(c =>
  10569. `<span class="px-1.5 py-0.5 rounded text-[10px] bg-indigo-950 text-indigo-300 border border-indigo-800/40 font-mono">${escapeHtml(c)}</span>`
  10570. ).join(' ');
  10571. return `
  10572. <tr onclick="selectFilterRow('community-lists', '${cl.id}')" class="cursor-pointer transition select-none ${isSelected ? 'bg-emerald-950/40 ring-1 ring-emerald-500/40' : 'hover:bg-slate-800/40'}">
  10573. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  10574. <td class="py-2 px-3 font-mono font-bold text-white">${escapeHtml(cl.name)}</td>
  10575. <td class="py-2 px-3 space-x-1">${commBadges || '<span class="text-slate-600">-</span>'}</td>
  10576. <td class="py-2 px-3 font-mono text-slate-400">${escapeHtml(cl.regexp || '-')}</td>
  10577. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(cl.comment || '')}</td>
  10578. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  10579. <button onclick="toggleCommunityListState('${cl.id}', ${!cl.disabled})" class="px-2 py-0.5 rounded text-[10px] ${cl.disabled ? 'bg-emerald-950 hover:bg-emerald-900 text-emerald-400 border border-emerald-800/50' : 'bg-slate-800 hover:bg-slate-700 text-slate-300 border border-slate-700'}">
  10580. ${cl.disabled ? 'Enable' : 'Disable'}
  10581. </button>
  10582. <button onclick="openEditCommunityListModal('${cl.id}')" class="px-2 py-0.5 rounded text-[10px] bg-slate-800 hover:bg-slate-700 text-emerald-300 border border-slate-700">
  10583. Edit
  10584. </button>
  10585. <button onclick="deleteCommunityList('${cl.id}')" class="px-2 py-0.5 rounded text-[10px] bg-rose-950/60 hover:bg-rose-900 text-rose-300 border border-rose-900/50">
  10586. ✕
  10587. </button>
  10588. </td>
  10589. </tr>
  10590. `;
  10591. }).join('');
  10592. }
  10593. // -------------------------------------------------------------
  10594. // TAB 4: AS LISTS (/routing filter num-list)
  10595. // -------------------------------------------------------------
  10596. function renderRoutingFilterASLists() {
  10597. const tbody = document.getElementById('routing-filter-as-lists-tbody');
  10598. if (!tbody) return;
  10599. const empty = document.getElementById('rf-as-lists-empty');
  10600. const statusCount = document.getElementById('rf-status-count');
  10601. let list = (state.routingASLists || []).slice();
  10602. const q = state.rfSearchQuery;
  10603. if (q) {
  10604. list = list.filter(al =>
  10605. (al.name && al.name.toLowerCase().includes(q)) ||
  10606. (al.range && al.range.toLowerCase().includes(q)) ||
  10607. (al.comment && al.comment.toLowerCase().includes(q))
  10608. );
  10609. }
  10610. if (statusCount && state.activeRoutingFilterTab === 'as-lists') {
  10611. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  10612. }
  10613. if (list.length === 0) {
  10614. tbody.innerHTML = '';
  10615. if (empty) empty.classList.remove('hidden');
  10616. return;
  10617. }
  10618. if (empty) empty.classList.add('hidden');
  10619. tbody.innerHTML = list.map(al => {
  10620. const isSelected = state.selectedFilterRow?.['as-lists'] === al.id;
  10621. const flagA = !al.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  10622. const flagX = al.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  10623. return `
  10624. <tr onclick="selectFilterRow('as-lists', '${al.id}')" class="cursor-pointer transition select-none ${isSelected ? 'bg-emerald-950/40 ring-1 ring-emerald-500/40' : 'hover:bg-slate-800/40'}">
  10625. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  10626. <td class="py-2 px-3 font-mono font-bold text-white">${escapeHtml(al.name)}</td>
  10627. <td class="py-2 px-3 font-mono text-purple-300">${escapeHtml(al.range)}</td>
  10628. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(al.comment || '')}</td>
  10629. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  10630. <button onclick="toggleASListState('${al.id}', ${!al.disabled})" class="px-2 py-0.5 rounded text-[10px] ${al.disabled ? 'bg-emerald-950 hover:bg-emerald-900 text-emerald-400 border border-emerald-800/50' : 'bg-slate-800 hover:bg-slate-700 text-slate-300 border border-slate-700'}">
  10631. ${al.disabled ? 'Enable' : 'Disable'}
  10632. </button>
  10633. <button onclick="openEditASListModal('${al.id}')" class="px-2 py-0.5 rounded text-[10px] bg-slate-800 hover:bg-slate-700 text-emerald-300 border border-slate-700">
  10634. Edit
  10635. </button>
  10636. <button onclick="deleteASList('${al.id}')" class="px-2 py-0.5 rounded text-[10px] bg-rose-950/60 hover:bg-rose-900 text-rose-300 border border-rose-900/50">
  10637. ✕
  10638. </button>
  10639. </td>
  10640. </tr>
  10641. `;
  10642. }).join('');
  10643. }
  10644. // -------------------------------------------------------------
  10645. // SNIPPETS & WIZARD HELPERS
  10646. // -------------------------------------------------------------
  10647. function insertRuleSnippet(type) {
  10648. const textarea = document.getElementById('modal-rf-rule');
  10649. if (!textarea) return;
  10650. let snippet = '';
  10651. switch (type) {
  10652. case 'accept-default':
  10653. snippet = 'if (dst in 0.0.0.0/0) { accept; }';
  10654. break;
  10655. case 'drop-rfc1918':
  10656. snippet = 'if (dst in 10.0.0.0/8 || dst in 172.16.0.0/12 || dst in 192.168.0.0/16) { reject; }';
  10657. break;
  10658. case 'len-24':
  10659. snippet = 'if (dst-len > 24) { reject; }';
  10660. break;
  10661. case 'local-pref-150':
  10662. snippet = 'if (dst in 10.0.0.0/8) { set bgp-local-pref 150; accept; }';
  10663. break;
  10664. case 'as-prepend-2':
  10665. snippet = 'set bgp-path-prepend 2; accept;';
  10666. break;
  10667. case 'set-comm':
  10668. snippet = 'set bgp-communities.add 65000:100; accept;';
  10669. break;
  10670. case 'match-comm':
  10671. snippet = 'if (bgp-communities includes 65000:100) { accept; }';
  10672. break;
  10673. case 'reject-all':
  10674. snippet = 'reject;';
  10675. break;
  10676. }
  10677. if (!snippet) return;
  10678. if (!textarea.value.trim()) {
  10679. textarea.value = snippet;
  10680. } else {
  10681. textarea.value = textarea.value.trim() + '\n' + snippet;
  10682. }
  10683. }
  10684. function generateScriptFromWizard() {
  10685. const pfx = (document.getElementById('modal-rf-prefix')?.value || '').trim();
  10686. const pfxLen = (document.getElementById('modal-rf-prefix-len')?.value || '').trim();
  10687. const proto = document.getElementById('modal-rf-protocol')?.value || 'any';
  10688. const asp = (document.getElementById('modal-rf-as-path')?.value || '').trim();
  10689. const comm = (document.getElementById('modal-rf-community')?.value || '').trim();
  10690. const act = document.getElementById('modal-rf-action')?.value || 'accept';
  10691. const lp = parseInt(document.getElementById('modal-rf-set-local-pref')?.value, 10) || 0;
  10692. const prep = parseInt(document.getElementById('modal-rf-set-as-prepend')?.value, 10) || 0;
  10693. const conds = [];
  10694. if (pfx) {
  10695. if (pfxLen) {
  10696. if (pfxLen.includes('-')) {
  10697. const parts = pfxLen.split('-');
  10698. conds.push(`dst in ${pfx}{${parts[0].trim()},${parts[1].trim()}}`);
  10699. } else {
  10700. conds.push(`dst in ${pfx} && dst-len >= ${pfxLen}`);
  10701. }
  10702. } else {
  10703. conds.push(`dst in ${pfx}`);
  10704. }
  10705. }
  10706. if (proto && proto !== 'any') {
  10707. conds.push(`protocol ${proto}`);
  10708. }
  10709. if (asp) {
  10710. conds.push(`bgp-as-path "${asp}"`);
  10711. }
  10712. if (comm) {
  10713. conds.push(`bgp-communities includes ${comm}`);
  10714. }
  10715. const actions = [];
  10716. if (lp > 0) actions.push(`set bgp-local-pref ${lp};`);
  10717. if (prep > 0) actions.push(`set bgp-path-prepend ${prep};`);
  10718. actions.push(`${act};`);
  10719. let code = '';
  10720. if (conds.length > 0) {
  10721. code = `if (${conds.join(' && ')}) {\n ${actions.join(' ')}\n}`;
  10722. } else {
  10723. code = actions.join(' ');
  10724. }
  10725. const textarea = document.getElementById('modal-rf-rule');
  10726. if (textarea) textarea.value = code;
  10727. }
  10728. // -------------------------------------------------------------
  10729. // MODAL CRUD: RULES (/routing filter rule)
  10730. // -------------------------------------------------------------
  10731. function openAddRoutingFilterModal(defaultChain = '') {
  10732. const form = document.getElementById('routing-filter-form');
  10733. if (form) form.reset();
  10734. const idEl = document.getElementById('modal-rf-id');
  10735. if (idEl) idEl.value = '';
  10736. const titleEl = document.getElementById('modal-rf-title');
  10737. if (titleEl) titleEl.innerText = 'Add Routing Filter Rule';
  10738. const chainEl = document.getElementById('modal-rf-chain');
  10739. if (chainEl) chainEl.value = defaultChain || (state.filterChainSelected && state.filterChainSelected !== 'all' ? state.filterChainSelected : 'bgp-in');
  10740. const orderEl = document.getElementById('modal-rf-order');
  10741. if (orderEl) orderEl.value = ((state.routingFilters || []).length + 1) * 10;
  10742. const ruleEl = document.getElementById('modal-rf-rule');
  10743. if (ruleEl) ruleEl.value = 'if (dst in 10.0.0.0/8) { set bgp-local-pref 150; accept; }';
  10744. const disEl = document.getElementById('modal-rf-disabled');
  10745. if (disEl) disEl.checked = false;
  10746. const modal = document.getElementById('modal-routing-filter');
  10747. if (modal) modal.classList.remove('hidden');
  10748. }
  10749. function openEditRoutingFilterModal(id) {
  10750. const r = (state.routingFilters || []).find(item => item.id === id);
  10751. if (!r) return;
  10752. const idEl = document.getElementById('modal-rf-id');
  10753. if (idEl) idEl.value = r.id;
  10754. const titleEl = document.getElementById('modal-rf-title');
  10755. if (titleEl) titleEl.innerText = 'Edit Routing Filter Rule';
  10756. const chainEl = document.getElementById('modal-rf-chain');
  10757. if (chainEl) chainEl.value = r.chain || '';
  10758. const orderEl = document.getElementById('modal-rf-order');
  10759. if (orderEl) orderEl.value = r.rule_order || 10;
  10760. const ruleEl = document.getElementById('modal-rf-rule');
  10761. if (ruleEl) {
  10762. if (r.rule) {
  10763. ruleEl.value = r.rule;
  10764. } else {
  10765. let conds = [];
  10766. if (r.prefix) conds.push(`dst in ${r.prefix}`);
  10767. if (r.match_protocol && r.match_protocol !== 'any') conds.push(`protocol ${r.match_protocol}`);
  10768. let act = r.action || 'accept';
  10769. ruleEl.value = `if (${conds.length ? conds.join(' && ') : 'true'}) { ${act}; }`;
  10770. }
  10771. }
  10772. const comEl = document.getElementById('modal-rf-comment');
  10773. if (comEl) comEl.value = r.comment || '';
  10774. const disEl = document.getElementById('modal-rf-disabled');
  10775. if (disEl) disEl.checked = !!r.disabled;
  10776. const modal = document.getElementById('modal-routing-filter');
  10777. if (modal) modal.classList.remove('hidden');
  10778. }
  10779. function closeRoutingFilterModal() {
  10780. const modal = document.getElementById('modal-routing-filter');
  10781. if (modal) modal.classList.add('hidden');
  10782. }
  10783. async function submitRoutingFilter(e) {
  10784. if (e) e.preventDefault();
  10785. const payload = {
  10786. id: document.getElementById('modal-rf-id').value,
  10787. chain: document.getElementById('modal-rf-chain').value.trim(),
  10788. rule_order: parseInt(document.getElementById('modal-rf-order').value, 10) || 10,
  10789. rule: document.getElementById('modal-rf-rule').value.trim(),
  10790. comment: document.getElementById('modal-rf-comment').value.trim(),
  10791. disabled: document.getElementById('modal-rf-disabled').checked
  10792. };
  10793. try {
  10794. const res = await fetch(`${API_BASE}/routing/filters`, {
  10795. method: 'POST',
  10796. headers: { 'Content-Type': 'application/json' },
  10797. body: JSON.stringify(payload)
  10798. });
  10799. if (res.ok) {
  10800. closeRoutingFilterModal();
  10801. showToast('Success', 'Routing filter rule saved', 'success');
  10802. loadDynamicRouting();
  10803. } else {
  10804. const err = await res.json();
  10805. showToast('Error', err.error || 'Failed to save filter rule', 'error');
  10806. }
  10807. } catch (err) {
  10808. showToast('Error', err.message, 'error');
  10809. }
  10810. }
  10811. async function applyRoutingFilterForm() {
  10812. const payload = {
  10813. id: document.getElementById('modal-rf-id').value,
  10814. chain: document.getElementById('modal-rf-chain').value.trim(),
  10815. rule_order: parseInt(document.getElementById('modal-rf-order').value, 10) || 10,
  10816. rule: document.getElementById('modal-rf-rule').value.trim(),
  10817. comment: document.getElementById('modal-rf-comment').value.trim(),
  10818. disabled: document.getElementById('modal-rf-disabled').checked
  10819. };
  10820. try {
  10821. const res = await fetch(`${API_BASE}/routing/filters`, {
  10822. method: 'POST',
  10823. headers: { 'Content-Type': 'application/json' },
  10824. body: JSON.stringify(payload)
  10825. });
  10826. if (res.ok) {
  10827. const data = await res.json();
  10828. if (data.id) document.getElementById('modal-rf-id').value = data.id;
  10829. showToast('Applied', 'Routing filter configuration applied', 'success');
  10830. loadDynamicRouting();
  10831. } else {
  10832. const err = await res.json();
  10833. showToast('Error', err.error || 'Failed to apply filter rule', 'error');
  10834. }
  10835. } catch (err) {
  10836. showToast('Error', err.message, 'error');
  10837. }
  10838. }
  10839. async function moveRoutingFilterOrder(id, delta) {
  10840. const list = state.routingFilters || [];
  10841. const idx = list.findIndex(r => r.id === id);
  10842. if (idx < 0) return;
  10843. const targetIdx = idx + delta;
  10844. if (targetIdx < 0 || targetIdx >= list.length) return;
  10845. const currentOrder = list[idx].rule_order || 10;
  10846. const targetOrder = list[targetIdx].rule_order || 20;
  10847. list[idx].rule_order = targetOrder;
  10848. list[targetIdx].rule_order = currentOrder;
  10849. try {
  10850. await fetch(`${API_BASE}/routing/filters`, {
  10851. method: 'POST',
  10852. headers: { 'Content-Type': 'application/json' },
  10853. body: JSON.stringify(list[idx])
  10854. });
  10855. await fetch(`${API_BASE}/routing/filters`, {
  10856. method: 'POST',
  10857. headers: { 'Content-Type': 'application/json' },
  10858. body: JSON.stringify(list[targetIdx])
  10859. });
  10860. loadDynamicRouting();
  10861. } catch (e) {
  10862. console.error('Reorder error:', e);
  10863. }
  10864. }
  10865. async function deleteRoutingFilter(id) {
  10866. if (!confirm('Are you sure you want to delete this routing filter rule?')) return;
  10867. try {
  10868. const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10869. if (res.ok) {
  10870. showToast('Deleted', 'Routing filter rule removed', 'info');
  10871. loadDynamicRouting();
  10872. } else {
  10873. const err = await res.json();
  10874. showToast('Error', err.error || 'Failed to delete rule', 'error');
  10875. }
  10876. } catch (err) {
  10877. showToast('Error', err.message, 'error');
  10878. }
  10879. }
  10880. async function toggleRoutingFilterState(id, disabled) {
  10881. try {
  10882. const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}/state`, {
  10883. method: 'POST',
  10884. headers: { 'Content-Type': 'application/json' },
  10885. body: JSON.stringify({ disabled })
  10886. });
  10887. if (res.ok) {
  10888. showToast('Status Updated', `Rule ${disabled ? 'disabled' : 'enabled'}`, 'info');
  10889. loadDynamicRouting();
  10890. } else {
  10891. const err = await res.json();
  10892. showToast('Error', err.error || 'Failed to toggle rule state', 'error');
  10893. }
  10894. } catch (err) {
  10895. showToast('Error', err.message, 'error');
  10896. }
  10897. }
  10898. // -------------------------------------------------------------
  10899. // MODAL CRUD: SELECT RULES (/routing filter select-rule)
  10900. // -------------------------------------------------------------
  10901. function openAddSelectRuleModal() {
  10902. document.getElementById('modal-rf-sr-id').value = '';
  10903. document.getElementById('modal-rf-sr-title').innerText = 'Add Routing Select Rule';
  10904. document.getElementById('modal-rf-sr-chain').value = state.filterChainSelected && state.filterChainSelected !== 'all' ? state.filterChainSelected : 'bgp-out';
  10905. document.getElementById('modal-rf-sr-order').value = ((state.routingSelectRules || []).length + 1) * 10;
  10906. document.getElementById('modal-rf-sr-rule').value = 'if (protocol bgp && dst in 10.0.0.0/8) { accept; }';
  10907. document.getElementById('modal-rf-sr-comment').value = '';
  10908. document.getElementById('modal-rf-sr-disabled').checked = false;
  10909. document.getElementById('modal-rf-select-rule').classList.remove('hidden');
  10910. }
  10911. function openEditSelectRuleModal(id) {
  10912. const r = (state.routingSelectRules || []).find(item => item.id === id);
  10913. if (!r) return;
  10914. document.getElementById('modal-rf-sr-id').value = r.id;
  10915. document.getElementById('modal-rf-sr-title').innerText = 'Edit Routing Select Rule';
  10916. document.getElementById('modal-rf-sr-chain').value = r.chain || '';
  10917. document.getElementById('modal-rf-sr-order').value = r.rule_order || 10;
  10918. document.getElementById('modal-rf-sr-rule').value = r.rule || '';
  10919. document.getElementById('modal-rf-sr-comment').value = r.comment || '';
  10920. document.getElementById('modal-rf-sr-disabled').checked = !!r.disabled;
  10921. document.getElementById('modal-rf-select-rule').classList.remove('hidden');
  10922. }
  10923. function closeSelectRuleModal() {
  10924. document.getElementById('modal-rf-select-rule').classList.add('hidden');
  10925. }
  10926. async function submitSelectRule(e) {
  10927. e.preventDefault();
  10928. const payload = {
  10929. id: document.getElementById('modal-rf-sr-id').value,
  10930. chain: document.getElementById('modal-rf-sr-chain').value.trim(),
  10931. rule_order: parseInt(document.getElementById('modal-rf-sr-order').value, 10) || 10,
  10932. rule: document.getElementById('modal-rf-sr-rule').value.trim(),
  10933. comment: document.getElementById('modal-rf-sr-comment').value.trim(),
  10934. disabled: document.getElementById('modal-rf-sr-disabled').checked
  10935. };
  10936. try {
  10937. const res = await fetch(`${API_BASE}/routing/filters/select-rules`, {
  10938. method: 'POST',
  10939. headers: { 'Content-Type': 'application/json' },
  10940. body: JSON.stringify(payload)
  10941. });
  10942. if (res.ok) {
  10943. closeSelectRuleModal();
  10944. showToast('Success', 'Select rule saved', 'success');
  10945. loadDynamicRouting();
  10946. } else {
  10947. const err = await res.json();
  10948. showToast('Error', err.error || 'Failed to save select rule', 'error');
  10949. }
  10950. } catch (err) {
  10951. showToast('Error', err.message, 'error');
  10952. }
  10953. }
  10954. async function deleteSelectRule(id) {
  10955. if (!confirm('Are you sure you want to delete this select rule?')) return;
  10956. try {
  10957. const res = await fetch(`${API_BASE}/routing/filters/select-rules/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10958. if (res.ok) {
  10959. showToast('Deleted', 'Select rule removed', 'info');
  10960. loadDynamicRouting();
  10961. } else {
  10962. const err = await res.json();
  10963. showToast('Error', err.error || 'Failed to delete select rule', 'error');
  10964. }
  10965. } catch (err) {
  10966. showToast('Error', err.message, 'error');
  10967. }
  10968. }
  10969. async function toggleSelectRuleState(id, disabled) {
  10970. try {
  10971. const res = await fetch(`${API_BASE}/routing/filters/select-rules/${encodeURIComponent(id)}/state`, {
  10972. method: 'POST',
  10973. headers: { 'Content-Type': 'application/json' },
  10974. body: JSON.stringify({ disabled })
  10975. });
  10976. if (res.ok) {
  10977. showToast('Status Updated', `Select rule ${disabled ? 'disabled' : 'enabled'}`, 'info');
  10978. loadDynamicRouting();
  10979. } else {
  10980. const err = await res.json();
  10981. showToast('Error', err.error || 'Failed to update select rule state', 'error');
  10982. }
  10983. } catch (err) {
  10984. showToast('Error', err.message, 'error');
  10985. }
  10986. }
  10987. // -------------------------------------------------------------
  10988. // MODAL CRUD: COMMUNITY LISTS (/routing filter community-list)
  10989. // -------------------------------------------------------------
  10990. function openAddCommunityListModal() {
  10991. document.getElementById('modal-rf-cl-id').value = '';
  10992. document.getElementById('modal-rf-cl-title').innerText = 'Add BGP Community List';
  10993. document.getElementById('modal-rf-cl-name').value = '';
  10994. document.getElementById('modal-rf-cl-communities').value = '';
  10995. document.getElementById('modal-rf-cl-regexp').value = '';
  10996. document.getElementById('modal-rf-cl-comment').value = '';
  10997. document.getElementById('modal-rf-cl-disabled').checked = false;
  10998. document.getElementById('modal-rf-community-list').classList.remove('hidden');
  10999. }
  11000. function openEditCommunityListModal(id) {
  11001. const cl = (state.routingCommunityLists || []).find(item => item.id === id);
  11002. if (!cl) return;
  11003. document.getElementById('modal-rf-cl-id').value = cl.id;
  11004. document.getElementById('modal-rf-cl-title').innerText = 'Edit BGP Community List';
  11005. document.getElementById('modal-rf-cl-name').value = cl.name || '';
  11006. document.getElementById('modal-rf-cl-communities').value = (cl.communities || []).join(', ');
  11007. document.getElementById('modal-rf-cl-regexp').value = cl.regexp || '';
  11008. document.getElementById('modal-rf-cl-comment').value = cl.comment || '';
  11009. document.getElementById('modal-rf-cl-disabled').checked = !!cl.disabled;
  11010. document.getElementById('modal-rf-community-list').classList.remove('hidden');
  11011. }
  11012. function closeCommunityListModal() {
  11013. document.getElementById('modal-rf-community-list').classList.add('hidden');
  11014. }
  11015. async function submitCommunityList(e) {
  11016. e.preventDefault();
  11017. const rawComms = document.getElementById('modal-rf-cl-communities').value;
  11018. const comms = rawComms.split(',').map(c => c.trim()).filter(Boolean);
  11019. const payload = {
  11020. id: document.getElementById('modal-rf-cl-id').value,
  11021. name: document.getElementById('modal-rf-cl-name').value.trim(),
  11022. communities: comms,
  11023. regexp: document.getElementById('modal-rf-cl-regexp').value.trim(),
  11024. comment: document.getElementById('modal-rf-cl-comment').value.trim(),
  11025. disabled: document.getElementById('modal-rf-cl-disabled').checked
  11026. };
  11027. try {
  11028. const res = await fetch(`${API_BASE}/routing/filters/community-lists`, {
  11029. method: 'POST',
  11030. headers: { 'Content-Type': 'application/json' },
  11031. body: JSON.stringify(payload)
  11032. });
  11033. if (res.ok) {
  11034. closeCommunityListModal();
  11035. showToast('Success', 'Community list saved', 'success');
  11036. loadDynamicRouting();
  11037. } else {
  11038. const err = await res.json();
  11039. showToast('Error', err.error || 'Failed to save community list', 'error');
  11040. }
  11041. } catch (err) {
  11042. showToast('Error', err.message, 'error');
  11043. }
  11044. }
  11045. async function deleteCommunityList(id) {
  11046. if (!confirm('Are you sure you want to delete this community list?')) return;
  11047. try {
  11048. const res = await fetch(`${API_BASE}/routing/filters/community-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  11049. if (res.ok) {
  11050. showToast('Deleted', 'Community list removed', 'info');
  11051. loadDynamicRouting();
  11052. } else {
  11053. const err = await res.json();
  11054. showToast('Error', err.error || 'Failed to delete community list', 'error');
  11055. }
  11056. } catch (err) {
  11057. showToast('Error', err.message, 'error');
  11058. }
  11059. }
  11060. async function toggleCommunityListState(id, disabled) {
  11061. try {
  11062. const res = await fetch(`${API_BASE}/routing/filters/community-lists/${encodeURIComponent(id)}/state`, {
  11063. method: 'POST',
  11064. headers: { 'Content-Type': 'application/json' },
  11065. body: JSON.stringify({ disabled })
  11066. });
  11067. if (res.ok) {
  11068. showToast('Status Updated', `Community list ${disabled ? 'disabled' : 'enabled'}`, 'info');
  11069. loadDynamicRouting();
  11070. } else {
  11071. const err = await res.json();
  11072. showToast('Error', err.error || 'Failed to update community list state', 'error');
  11073. }
  11074. } catch (err) {
  11075. showToast('Error', err.message, 'error');
  11076. }
  11077. }
  11078. // -------------------------------------------------------------
  11079. // MODAL CRUD: AS LISTS (/routing filter num-list)
  11080. // -------------------------------------------------------------
  11081. function openAddASListModal() {
  11082. document.getElementById('modal-rf-al-id').value = '';
  11083. document.getElementById('modal-rf-al-title').innerText = 'Add AS Number List';
  11084. document.getElementById('modal-rf-al-name').value = '';
  11085. document.getElementById('modal-rf-al-range').value = '';
  11086. document.getElementById('modal-rf-al-comment').value = '';
  11087. document.getElementById('modal-rf-al-disabled').checked = false;
  11088. document.getElementById('modal-rf-as-list').classList.remove('hidden');
  11089. }
  11090. function openEditASListModal(id) {
  11091. const al = (state.routingASLists || []).find(item => item.id === id);
  11092. if (!al) return;
  11093. document.getElementById('modal-rf-al-id').value = al.id;
  11094. document.getElementById('modal-rf-al-title').innerText = 'Edit AS Number List';
  11095. document.getElementById('modal-rf-al-name').value = al.name || '';
  11096. document.getElementById('modal-rf-al-range').value = al.range || '';
  11097. document.getElementById('modal-rf-al-comment').value = al.comment || '';
  11098. document.getElementById('modal-rf-al-disabled').checked = !!al.disabled;
  11099. document.getElementById('modal-rf-as-list').classList.remove('hidden');
  11100. }
  11101. function closeASListModal() {
  11102. document.getElementById('modal-rf-as-list').classList.add('hidden');
  11103. }
  11104. async function submitASList(e) {
  11105. e.preventDefault();
  11106. const payload = {
  11107. id: document.getElementById('modal-rf-al-id').value,
  11108. name: document.getElementById('modal-rf-al-name').value.trim(),
  11109. range: document.getElementById('modal-rf-al-range').value.trim(),
  11110. comment: document.getElementById('modal-rf-al-comment').value.trim(),
  11111. disabled: document.getElementById('modal-rf-al-disabled').checked
  11112. };
  11113. try {
  11114. const res = await fetch(`${API_BASE}/routing/filters/as-lists`, {
  11115. method: 'POST',
  11116. headers: { 'Content-Type': 'application/json' },
  11117. body: JSON.stringify(payload)
  11118. });
  11119. if (res.ok) {
  11120. closeASListModal();
  11121. showToast('Success', 'AS number list saved', 'success');
  11122. loadDynamicRouting();
  11123. } else {
  11124. const err = await res.json();
  11125. showToast('Error', err.error || 'Failed to save AS list', 'error');
  11126. }
  11127. } catch (err) {
  11128. showToast('Error', err.message, 'error');
  11129. }
  11130. }
  11131. async function deleteASList(id) {
  11132. if (!confirm('Are you sure you want to delete this AS list?')) return;
  11133. try {
  11134. const res = await fetch(`${API_BASE}/routing/filters/as-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  11135. if (res.ok) {
  11136. showToast('Deleted', 'AS list removed', 'info');
  11137. loadDynamicRouting();
  11138. } else {
  11139. const err = await res.json();
  11140. showToast('Error', err.error || 'Failed to delete AS list', 'error');
  11141. }
  11142. } catch (err) {
  11143. showToast('Error', err.message, 'error');
  11144. }
  11145. }
  11146. async function toggleASListState(id, disabled) {
  11147. try {
  11148. const res = await fetch(`${API_BASE}/routing/filters/as-lists/${encodeURIComponent(id)}/state`, {
  11149. method: 'POST',
  11150. headers: { 'Content-Type': 'application/json' },
  11151. body: JSON.stringify({ disabled })
  11152. });
  11153. if (res.ok) {
  11154. showToast('Status Updated', `AS list ${disabled ? 'disabled' : 'enabled'}`, 'info');
  11155. loadDynamicRouting();
  11156. } else {
  11157. const err = await res.json();
  11158. showToast('Error', err.error || 'Failed to update AS list state', 'error');
  11159. }
  11160. } catch (err) {
  11161. showToast('Error', err.message, 'error');
  11162. }
  11163. }
  11164. // ==========================================
  11165. // TROUBLESHOOT & DIAGNOSTIC TOOLS (/tool)
  11166. // ==========================================
  11167. function loadToolsView() {
  11168. populateToolsInterfaces();
  11169. switchToolsSubTab(state.activeToolsSubTab || 'ping');
  11170. }
  11171. function populateToolsInterfaces() {
  11172. const pingSel = document.getElementById('tools-ping-iface');
  11173. const traceSel = document.getElementById('tools-tr-iface');
  11174. let opts = '<option value="">Auto (Default Route)</option>';
  11175. if (Array.isArray(state.interfaces)) {
  11176. state.interfaces.forEach(iface => {
  11177. if (iface.name) {
  11178. opts += `<option value="${escapeHtml(iface.name)}">${escapeHtml(iface.name)}${iface.ip_address ? ' (' + escapeHtml(iface.ip_address) + ')' : ''}</option>`;
  11179. }
  11180. });
  11181. }
  11182. if (pingSel) {
  11183. const cur = pingSel.value;
  11184. pingSel.innerHTML = opts;
  11185. if (cur) pingSel.value = cur;
  11186. }
  11187. if (traceSel) {
  11188. const cur = traceSel.value;
  11189. traceSel.innerHTML = opts;
  11190. if (cur) traceSel.value = cur;
  11191. }
  11192. }
  11193. function switchToolsSubTab(subTab) {
  11194. state.activeToolsSubTab = subTab;
  11195. const tabs = ['ping', 'traceroute', 'mtr', 'dns', 'port'];
  11196. tabs.forEach(t => {
  11197. const btn = document.getElementById(`tools-subtab-btn-${t}`);
  11198. const view = document.getElementById(`tools-view-${t}`);
  11199. if (btn) {
  11200. if (t === subTab) {
  11201. btn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-amber-400 text-amber-300 transition flex items-center gap-2 whitespace-nowrap';
  11202. } else {
  11203. btn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-transparent text-slate-400 hover:text-slate-200 transition flex items-center gap-2 whitespace-nowrap';
  11204. }
  11205. }
  11206. if (view) {
  11207. if (t === subTab) {
  11208. view.classList.remove('hidden');
  11209. } else {
  11210. view.classList.add('hidden');
  11211. }
  11212. }
  11213. });
  11214. }
  11215. function setPortPreset(port) {
  11216. const input = document.getElementById('tools-port-num');
  11217. if (input) input.value = port;
  11218. }
  11219. let pingAbortController = null;
  11220. let tracerouteAbortController = null;
  11221. function clearPingTable() {
  11222. const tbody = document.getElementById('tools-ping-tbody');
  11223. if (tbody) tbody.innerHTML = '';
  11224. const rawEl = document.getElementById('tools-ping-raw');
  11225. if (rawEl) rawEl.innerText = '';
  11226. const sentEl = document.getElementById('tools-ping-stat-sent');
  11227. if (sentEl) sentEl.innerText = '0';
  11228. const recvEl = document.getElementById('tools-ping-stat-recv');
  11229. if (recvEl) recvEl.innerText = '0';
  11230. const lossEl = document.getElementById('tools-ping-stat-loss');
  11231. if (lossEl) lossEl.innerText = '0%';
  11232. const avgEl = document.getElementById('tools-ping-stat-avg');
  11233. if (avgEl) avgEl.innerText = '0 ms';
  11234. const minMaxEl = document.getElementById('tools-ping-stat-minmax');
  11235. if (minMaxEl) minMaxEl.innerText = '-';
  11236. const badge = document.getElementById('tools-ping-status-badge');
  11237. if (badge) {
  11238. badge.className = '';
  11239. badge.innerText = '';
  11240. }
  11241. }
  11242. function clearTracerouteTable() {
  11243. const tbody = document.getElementById('tools-tr-tbody');
  11244. if (tbody) tbody.innerHTML = '';
  11245. const rawEl = document.getElementById('tools-tr-raw');
  11246. if (rawEl) rawEl.innerText = '';
  11247. const statHops = document.getElementById('tools-tr-hops-count');
  11248. if (statHops) statHops.innerText = '0 Hops';
  11249. }
  11250. function resetPingButton() {
  11251. const btn = document.getElementById('tools-ping-btn');
  11252. const btnText = document.getElementById('tools-ping-btn-text');
  11253. const spinner = document.getElementById('tools-ping-spinner');
  11254. if (btn) {
  11255. btn.disabled = false;
  11256. btn.className = 'px-5 py-2 rounded-lg font-semibold text-xs bg-amber-500 hover:bg-amber-400 text-slate-950 shadow-lg shadow-amber-500/20 transition flex items-center gap-2';
  11257. }
  11258. if (btnText) btnText.innerText = 'Start Ping';
  11259. if (spinner) spinner.classList.add('hidden');
  11260. }
  11261. function setPingRunningButton() {
  11262. const btn = document.getElementById('tools-ping-btn');
  11263. const btnText = document.getElementById('tools-ping-btn-text');
  11264. const spinner = document.getElementById('tools-ping-spinner');
  11265. if (btn) {
  11266. btn.disabled = false;
  11267. btn.className = 'px-5 py-2 rounded-lg font-semibold text-xs bg-rose-600 hover:bg-rose-500 text-white shadow-lg shadow-rose-600/30 transition flex items-center gap-2';
  11268. }
  11269. if (btnText) btnText.innerText = 'Stop Ping';
  11270. if (spinner) spinner.classList.remove('hidden');
  11271. }
  11272. function resetTracerouteButton() {
  11273. const btn = document.getElementById('tools-tr-btn');
  11274. const btnText = document.getElementById('tools-tr-btn-text');
  11275. const spinner = document.getElementById('tools-tr-spinner');
  11276. if (btn) {
  11277. btn.disabled = false;
  11278. btn.className = 'px-5 py-2 rounded-lg font-semibold text-xs bg-amber-500 hover:bg-amber-400 text-slate-950 shadow-lg shadow-amber-500/20 transition flex items-center gap-2';
  11279. }
  11280. if (btnText) btnText.innerText = 'Start Traceroute';
  11281. if (spinner) spinner.classList.add('hidden');
  11282. }
  11283. function setTracerouteRunningButton() {
  11284. const btn = document.getElementById('tools-tr-btn');
  11285. const btnText = document.getElementById('tools-tr-btn-text');
  11286. const spinner = document.getElementById('tools-tr-spinner');
  11287. if (btn) {
  11288. btn.disabled = false;
  11289. btn.className = 'px-5 py-2 rounded-lg font-semibold text-xs bg-rose-600 hover:bg-rose-500 text-white shadow-lg shadow-rose-600/30 transition flex items-center gap-2';
  11290. }
  11291. if (btnText) btnText.innerText = 'Stop Traceroute';
  11292. if (spinner) spinner.classList.remove('hidden');
  11293. }
  11294. async function executePing(e) {
  11295. if (e) e.preventDefault();
  11296. // If already running, clicking the button stops the stream!
  11297. if (pingAbortController) {
  11298. pingAbortController.abort();
  11299. pingAbortController = null;
  11300. resetPingButton();
  11301. showToast('Ping Stopped', 'Live ping stopped by user', 'info');
  11302. return;
  11303. }
  11304. const target = document.getElementById('tools-ping-target')?.value?.trim();
  11305. const count = parseInt(document.getElementById('tools-ping-count')?.value || '4', 10);
  11306. const size = parseInt(document.getElementById('tools-ping-size')?.value || '56', 10);
  11307. const timeout = parseInt(document.getElementById('tools-ping-timeout')?.value || '3', 10);
  11308. const iface = document.getElementById('tools-ping-iface')?.value || '';
  11309. const dontFrag = document.getElementById('tools-ping-df')?.checked || false;
  11310. if (!target) {
  11311. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  11312. return;
  11313. }
  11314. clearPingTable();
  11315. const resCard = document.getElementById('tools-ping-results');
  11316. if (resCard) resCard.classList.remove('hidden');
  11317. pingAbortController = new AbortController();
  11318. setPingRunningButton();
  11319. try {
  11320. const res = await fetch(`${API_BASE}/tools/ping/stream`, {
  11321. method: 'POST',
  11322. headers: { 'Content-Type': 'application/json' },
  11323. body: JSON.stringify({
  11324. target,
  11325. count,
  11326. size,
  11327. timeout,
  11328. interface: iface,
  11329. dont_frag: dontFrag
  11330. }),
  11331. signal: pingAbortController.signal
  11332. });
  11333. if (!res.ok) {
  11334. const errText = await res.text();
  11335. showToast('Ping Error', errText || 'Failed to start live ping', 'error');
  11336. resetPingButton();
  11337. pingAbortController = null;
  11338. return;
  11339. }
  11340. const reader = res.body.getReader();
  11341. const decoder = new TextDecoder('utf-8');
  11342. let buffer = '';
  11343. while (true) {
  11344. const { done, value } = await reader.read();
  11345. if (done) break;
  11346. buffer += decoder.decode(value, { stream: true });
  11347. const blocks = buffer.split('\n\n');
  11348. buffer = blocks.pop() || '';
  11349. for (const block of blocks) {
  11350. const trimmed = block.trim();
  11351. if (!trimmed) continue;
  11352. const line = trimmed.startsWith('data: ') ? trimmed.slice(6) : trimmed;
  11353. try {
  11354. const evt = JSON.parse(line);
  11355. handleLivePingEvent(evt);
  11356. } catch (parseErr) {
  11357. console.warn('Ping SSE parse error:', parseErr, line);
  11358. }
  11359. }
  11360. }
  11361. } catch (err) {
  11362. if (err.name === 'AbortError') {
  11363. // User aborted normally
  11364. } else {
  11365. showToast('Ping Error', err.message, 'error');
  11366. }
  11367. } finally {
  11368. pingAbortController = null;
  11369. resetPingButton();
  11370. }
  11371. }
  11372. function handleLivePingEvent(evt) {
  11373. const sentEl = document.getElementById('tools-ping-stat-sent');
  11374. const recvEl = document.getElementById('tools-ping-stat-recv');
  11375. const lossEl = document.getElementById('tools-ping-stat-loss');
  11376. const avgEl = document.getElementById('tools-ping-stat-avg');
  11377. const minMaxEl = document.getElementById('tools-ping-stat-minmax');
  11378. const badge = document.getElementById('tools-ping-status-badge');
  11379. const tbody = document.getElementById('tools-ping-tbody');
  11380. const rawEl = document.getElementById('tools-ping-raw');
  11381. if (evt.raw && rawEl) {
  11382. rawEl.innerText += (rawEl.innerText ? '\n' : '') + evt.raw;
  11383. rawEl.scrollTop = rawEl.scrollHeight;
  11384. }
  11385. if (evt.type === 'reply') {
  11386. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  11387. if (recvEl && evt.packets_recv !== undefined) recvEl.innerText = evt.packets_recv;
  11388. if (lossEl && evt.packet_loss_pct !== undefined) {
  11389. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  11390. lossEl.className = evt.packet_loss_pct === 0
  11391. ? 'text-base font-bold font-mono text-emerald-400 mt-1'
  11392. : (evt.packet_loss_pct < 50 ? 'text-base font-bold font-mono text-amber-400 mt-1' : 'text-base font-bold font-mono text-rose-400 mt-1');
  11393. }
  11394. if (avgEl && evt.avg_rtt_ms !== undefined) avgEl.innerText = `${evt.avg_rtt_ms.toFixed(2)} ms`;
  11395. if (minMaxEl && evt.min_rtt_ms !== undefined && evt.max_rtt_ms !== undefined) {
  11396. minMaxEl.innerText = `${evt.min_rtt_ms.toFixed(1)} / ${evt.max_rtt_ms.toFixed(1)} ms`;
  11397. }
  11398. if (badge) {
  11399. if (evt.packet_loss_pct === 0) {
  11400. badge.className = 'px-2 py-0.5 rounded text-[10px] font-mono font-semibold bg-emerald-950 text-emerald-300 border border-emerald-800/60';
  11401. badge.innerText = '100% OK';
  11402. } else {
  11403. badge.className = 'px-2 py-0.5 rounded text-[10px] font-mono font-semibold bg-amber-950 text-amber-300 border border-amber-800/60';
  11404. badge.innerText = `${evt.packet_loss_pct.toFixed(0)}% LOSS`;
  11405. }
  11406. }
  11407. if (tbody) {
  11408. const tr = document.createElement('tr');
  11409. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs';
  11410. tr.innerHTML = `
  11411. <td class="py-2 px-3 text-slate-300">#${evt.seq}</td>
  11412. <td class="py-2 px-3 font-semibold text-white">${escapeHtml(evt.from)}</td>
  11413. <td class="py-2 px-3 text-slate-400">${evt.bytes} bytes</td>
  11414. <td class="py-2 px-3 text-slate-300">${evt.ttl}</td>
  11415. <td class="py-2 px-3 font-bold text-amber-300">${evt.time_ms.toFixed(2)} ms</td>
  11416. <td class="py-2 px-3 text-right"><span class="px-2 py-0.5 rounded text-[10px] font-bold bg-emerald-950 text-emerald-300 border border-emerald-800/60">REPLY</span></td>
  11417. `;
  11418. tbody.appendChild(tr);
  11419. }
  11420. } else if (evt.type === 'timeout') {
  11421. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  11422. if (lossEl && evt.packet_loss_pct !== undefined) {
  11423. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  11424. lossEl.className = evt.packet_loss_pct < 50 ? 'text-base font-bold font-mono text-amber-400 mt-1' : 'text-base font-bold font-mono text-rose-400 mt-1';
  11425. }
  11426. if (badge) {
  11427. badge.className = 'px-2 py-0.5 rounded text-[10px] font-mono font-semibold bg-rose-950 text-rose-300 border border-rose-800/60';
  11428. badge.innerText = `${evt.packet_loss_pct?.toFixed(0) || 100}% LOSS`;
  11429. }
  11430. if (tbody) {
  11431. const tr = document.createElement('tr');
  11432. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs opacity-75';
  11433. tr.innerHTML = `
  11434. <td class="py-2 px-3 text-slate-400">#${evt.seq}</td>
  11435. <td class="py-2 px-3 font-semibold text-slate-500 italic">Request timed out</td>
  11436. <td class="py-2 px-3 text-slate-600">--</td>
  11437. <td class="py-2 px-3 text-slate-600">--</td>
  11438. <td class="py-2 px-3 font-bold text-slate-500">* * *</td>
  11439. <td class="py-2 px-3 text-right"><span class="px-2 py-0.5 rounded text-[10px] font-bold bg-slate-800 text-slate-400 border border-slate-700">TIMEOUT</span></td>
  11440. `;
  11441. tbody.appendChild(tr);
  11442. }
  11443. } else if (evt.type === 'unreach') {
  11444. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  11445. if (lossEl && evt.packet_loss_pct !== undefined) {
  11446. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  11447. lossEl.className = 'text-base font-bold font-mono text-rose-400 mt-1';
  11448. }
  11449. if (badge) {
  11450. badge.className = 'px-2 py-0.5 rounded text-[10px] font-mono font-semibold bg-rose-950 text-rose-300 border border-rose-800/60';
  11451. badge.innerText = 'UNREACHABLE';
  11452. }
  11453. if (tbody) {
  11454. const tr = document.createElement('tr');
  11455. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs';
  11456. tr.innerHTML = `
  11457. <td class="py-2 px-3 text-slate-400">#${evt.seq}</td>
  11458. <td class="py-2 px-3 font-semibold text-rose-400">${escapeHtml(evt.from || 'Gateway')}</td>
  11459. <td class="py-2 px-3 text-slate-600">--</td>
  11460. <td class="py-2 px-3 text-slate-600">--</td>
  11461. <td class="py-2 px-3 font-bold text-rose-400 text-xs">${escapeHtml(evt.message || 'Unreachable')}</td>
  11462. <td class="py-2 px-3 text-right"><span class="px-2 py-0.5 rounded text-[10px] font-bold bg-rose-950 text-rose-300 border border-rose-800/60">UNREACH</span></td>
  11463. `;
  11464. tbody.appendChild(tr);
  11465. }
  11466. } else if (evt.type === 'stats') {
  11467. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  11468. if (recvEl && evt.packets_recv !== undefined) recvEl.innerText = evt.packets_recv;
  11469. if (lossEl && evt.packet_loss_pct !== undefined) lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  11470. if (avgEl && evt.avg_rtt_ms !== undefined) avgEl.innerText = `${evt.avg_rtt_ms.toFixed(2)} ms`;
  11471. if (minMaxEl && evt.min_rtt_ms !== undefined && evt.max_rtt_ms !== undefined) {
  11472. minMaxEl.innerText = `${evt.min_rtt_ms.toFixed(1)} / ${evt.max_rtt_ms.toFixed(1)} ms`;
  11473. }
  11474. } else if (evt.type === 'done') {
  11475. showToast('Ping Finished', `Sent ${evt.packets_sent}, received ${evt.packets_recv} (${evt.packet_loss_pct?.toFixed(0)}% loss)`, evt.packet_loss_pct === 0 ? 'success' : 'info');
  11476. }
  11477. }
  11478. async function executeTraceroute(e) {
  11479. if (e) e.preventDefault();
  11480. if (tracerouteAbortController) {
  11481. tracerouteAbortController.abort();
  11482. tracerouteAbortController = null;
  11483. resetTracerouteButton();
  11484. showToast('Traceroute Stopped', 'Traceroute stopped by user', 'info');
  11485. return;
  11486. }
  11487. const target = document.getElementById('tools-tr-target')?.value?.trim();
  11488. const maxHops = parseInt(document.getElementById('tools-tr-maxhops')?.value || '15', 10);
  11489. const protocol = document.getElementById('tools-tr-proto')?.value || 'icmp';
  11490. const iface = document.getElementById('tools-tr-iface')?.value || '';
  11491. const resolve = document.getElementById('tools-tr-resolve')?.checked || false;
  11492. if (!target) {
  11493. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  11494. return;
  11495. }
  11496. clearTracerouteTable();
  11497. const resCard = document.getElementById('tools-tr-results');
  11498. if (resCard) resCard.classList.remove('hidden');
  11499. tracerouteAbortController = new AbortController();
  11500. setTracerouteRunningButton();
  11501. try {
  11502. const res = await fetch(`${API_BASE}/tools/traceroute/stream`, {
  11503. method: 'POST',
  11504. headers: { 'Content-Type': 'application/json' },
  11505. body: JSON.stringify({
  11506. target,
  11507. max_hops: maxHops,
  11508. protocol,
  11509. interface: iface,
  11510. resolve
  11511. }),
  11512. signal: tracerouteAbortController.signal
  11513. });
  11514. if (!res.ok) {
  11515. const errText = await res.text();
  11516. showToast('Traceroute Error', errText || 'Failed to start traceroute', 'error');
  11517. resetTracerouteButton();
  11518. tracerouteAbortController = null;
  11519. return;
  11520. }
  11521. const reader = res.body.getReader();
  11522. const decoder = new TextDecoder('utf-8');
  11523. let buffer = '';
  11524. while (true) {
  11525. const { done, value } = await reader.read();
  11526. if (done) break;
  11527. buffer += decoder.decode(value, { stream: true });
  11528. const blocks = buffer.split('\n\n');
  11529. buffer = blocks.pop() || '';
  11530. for (const block of blocks) {
  11531. const trimmed = block.trim();
  11532. if (!trimmed) continue;
  11533. const line = trimmed.startsWith('data: ') ? trimmed.slice(6) : trimmed;
  11534. try {
  11535. const evt = JSON.parse(line);
  11536. handleLiveTracerouteEvent(evt);
  11537. } catch (parseErr) {
  11538. console.warn('Traceroute SSE parse error:', parseErr, line);
  11539. }
  11540. }
  11541. }
  11542. } catch (err) {
  11543. if (err.name === 'AbortError') {
  11544. // User aborted normally
  11545. } else {
  11546. showToast('Traceroute Error', err.message, 'error');
  11547. }
  11548. } finally {
  11549. tracerouteAbortController = null;
  11550. resetTracerouteButton();
  11551. }
  11552. }
  11553. function handleLiveTracerouteEvent(evt) {
  11554. const statHops = document.getElementById('tools-tr-hops-count');
  11555. const tbody = document.getElementById('tools-tr-tbody');
  11556. const rawEl = document.getElementById('tools-tr-raw');
  11557. if (evt.raw && rawEl) {
  11558. rawEl.innerText += (rawEl.innerText ? '\n' : '') + evt.raw;
  11559. rawEl.scrollTop = rawEl.scrollHeight;
  11560. }
  11561. if (evt.hops_count !== undefined && statHops) {
  11562. statHops.innerText = `${evt.hops_count} Hops`;
  11563. }
  11564. if (evt.type === 'hop' && evt.hop && tbody) {
  11565. const h = evt.hop;
  11566. const isTimeout = h.status === 'timeout' || (!h.ip && !h.host);
  11567. const rtt1 = Array.isArray(h.times_ms) && h.times_ms[0] ? `${h.times_ms[0]} ms` : (isTimeout ? '*' : '--');
  11568. const rtt2 = Array.isArray(h.times_ms) && h.times_ms[1] ? `${h.times_ms[1]} ms` : (isTimeout ? '*' : '--');
  11569. const displayHost = h.host && h.host !== h.ip ? `${escapeHtml(h.host)} (${escapeHtml(h.ip || '')})` : escapeHtml(h.ip || (isTimeout ? 'Request timed out' : '--'));
  11570. const tr = document.createElement('tr');
  11571. tr.className = `hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs ${isTimeout ? 'opacity-60' : ''}`;
  11572. tr.innerHTML = `
  11573. <td class="py-2.5 px-3 text-slate-300 font-bold">${h.hop}</td>
  11574. <td class="py-2.5 px-3 font-semibold ${isTimeout ? 'text-slate-500 italic' : 'text-cyan-300'}">${displayHost}</td>
  11575. <td class="py-2.5 px-3 font-bold ${isTimeout ? 'text-slate-500' : 'text-amber-300'}">${escapeHtml(rtt1)}</td>
  11576. <td class="py-2.5 px-3 font-bold ${isTimeout ? 'text-slate-500' : 'text-amber-300'}">${escapeHtml(rtt2)}</td>
  11577. <td class="py-2.5 px-3 text-right">
  11578. ${isTimeout
  11579. ? '<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-slate-800 text-slate-400 border border-slate-700">TIMEOUT</span>'
  11580. : '<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-emerald-950 text-emerald-300 border border-emerald-800/60">OK</span>'}
  11581. </td>
  11582. `;
  11583. tbody.appendChild(tr);
  11584. } else if (evt.type === 'done') {
  11585. showToast('Traceroute Finished', `Traced ${evt.hops_count || 0} hops`, 'info');
  11586. }
  11587. }
  11588. async function executeMTR(e) {
  11589. if (e) e.preventDefault();
  11590. const target = document.getElementById('tools-mtr-target')?.value?.trim();
  11591. const cycles = parseInt(document.getElementById('tools-mtr-count')?.value || '3', 10);
  11592. if (!target) {
  11593. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  11594. return;
  11595. }
  11596. const btn = document.getElementById('tools-mtr-btn');
  11597. const spinner = document.getElementById('tools-mtr-spinner');
  11598. if (btn) btn.disabled = true;
  11599. if (spinner) spinner.classList.remove('hidden');
  11600. try {
  11601. const res = await fetch(`${API_BASE}/tools/mtr`, {
  11602. method: 'POST',
  11603. headers: { 'Content-Type': 'application/json' },
  11604. body: JSON.stringify({ target, count: cycles })
  11605. });
  11606. const data = await res.json();
  11607. if (!res.ok) {
  11608. showToast('MTR Error', data.error || 'Failed to execute MTR', 'error');
  11609. return;
  11610. }
  11611. const resCard = document.getElementById('tools-mtr-results');
  11612. if (resCard) resCard.classList.remove('hidden');
  11613. const hopsCount = Array.isArray(data.hops) ? data.hops.length : 0;
  11614. const statHops = document.getElementById('tools-mtr-hops-count');
  11615. if (statHops) statHops.innerText = `${hopsCount} Hops`;
  11616. const tbody = document.getElementById('tools-mtr-tbody');
  11617. if (tbody) {
  11618. if (hopsCount > 0) {
  11619. tbody.innerHTML = data.hops.map(h => {
  11620. const lossClass = h.loss_pct === 0 ? 'text-emerald-400 font-bold' : (h.loss_pct < 20 ? 'text-amber-400 font-bold' : 'text-rose-400 font-bold');
  11621. return `
  11622. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
  11623. <td class="py-2.5 px-3 text-slate-300 font-bold">${h.hop}</td>
  11624. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(h.host || '--')}</td>
  11625. <td class="py-2.5 px-3 ${lossClass}">${h.loss_pct.toFixed(1)}%</td>
  11626. <td class="py-2.5 px-3 text-slate-300">${h.sent}</td>
  11627. <td class="py-2.5 px-3 text-slate-300">${h.last_ms.toFixed(1)}</td>
  11628. <td class="py-2.5 px-3 font-bold text-amber-300">${h.avg_ms.toFixed(1)}</td>
  11629. <td class="py-2.5 px-3 text-emerald-400">${h.best_ms.toFixed(1)}</td>
  11630. <td class="py-2.5 px-3 text-rose-400">${h.wrst_ms.toFixed(1)}</td>
  11631. <td class="py-2.5 px-3 text-slate-400">${h.stdev_ms.toFixed(1)}</td>
  11632. </tr>
  11633. `;
  11634. }).join('');
  11635. } else {
  11636. tbody.innerHTML = `<tr><td colspan="9" class="p-4 text-center text-xs text-rose-400 font-mono">No MTR data collected</td></tr>`;
  11637. }
  11638. }
  11639. const rawEl = document.getElementById('tools-mtr-raw');
  11640. if (rawEl) rawEl.innerText = data.raw_output || 'No output';
  11641. showToast('MTR Finished', `Report completed (${hopsCount} hops discovered)`, 'info');
  11642. } catch (err) {
  11643. showToast('MTR Error', err.message, 'error');
  11644. } finally {
  11645. if (btn) btn.disabled = false;
  11646. if (spinner) spinner.classList.add('hidden');
  11647. }
  11648. }
  11649. async function executeDNS(e) {
  11650. if (e) e.preventDefault();
  11651. const domain = document.getElementById('tools-dns-domain')?.value?.trim();
  11652. const type = document.getElementById('tools-dns-type')?.value || 'A';
  11653. const server = document.getElementById('tools-dns-server')?.value?.trim() || '';
  11654. if (!domain) {
  11655. showToast('Input Required', 'Please enter a hostname or domain', 'warning');
  11656. return;
  11657. }
  11658. const btn = document.getElementById('tools-dns-btn');
  11659. const spinner = document.getElementById('tools-dns-spinner');
  11660. if (btn) btn.disabled = true;
  11661. if (spinner) spinner.classList.remove('hidden');
  11662. try {
  11663. const res = await fetch(`${API_BASE}/tools/dns`, {
  11664. method: 'POST',
  11665. headers: { 'Content-Type': 'application/json' },
  11666. body: JSON.stringify({ domain, type, server })
  11667. });
  11668. const data = await res.json();
  11669. if (!res.ok) {
  11670. showToast('DNS Error', data.error || 'Failed to resolve DNS query', 'error');
  11671. return;
  11672. }
  11673. const resCard = document.getElementById('tools-dns-results');
  11674. if (resCard) resCard.classList.remove('hidden');
  11675. const metaEl = document.getElementById('tools-dns-meta');
  11676. if (metaEl) metaEl.innerText = `Resolved in ${data.query_time_ms ?? 0} ms via ${escapeHtml(data.server || 'System DNS')}`;
  11677. const tbody = document.getElementById('tools-dns-tbody');
  11678. if (tbody) {
  11679. if (Array.isArray(data.records) && data.records.length > 0) {
  11680. tbody.innerHTML = data.records.map(r => `
  11681. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
  11682. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.name)}</td>
  11683. <td class="py-2.5 px-3 text-slate-400">${r.ttl}s</td>
  11684. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.class || 'IN')}</td>
  11685. <td class="py-2.5 px-3"><span class="px-2 py-0.5 rounded text-[10px] font-bold bg-cyan-950 text-cyan-300 border border-cyan-800/60">${escapeHtml(r.type)}</span></td>
  11686. <td class="py-2.5 px-3 font-bold text-amber-300 break-all">${escapeHtml(r.value)}</td>
  11687. </tr>
  11688. `).join('');
  11689. } else {
  11690. tbody.innerHTML = `<tr><td colspan="5" class="p-4 text-center text-xs text-amber-400 font-mono">No answer records returned for ${escapeHtml(type)} query</td></tr>`;
  11691. }
  11692. }
  11693. const rawEl = document.getElementById('tools-dns-raw');
  11694. if (rawEl) rawEl.innerText = data.raw_output || 'No output';
  11695. showToast('DNS Lookup Done', `Resolved ${domain} in ${data.query_time_ms} ms`, 'success');
  11696. } catch (err) {
  11697. showToast('DNS Error', err.message, 'error');
  11698. } finally {
  11699. if (btn) btn.disabled = false;
  11700. if (spinner) spinner.classList.add('hidden');
  11701. }
  11702. }
  11703. async function executePortProbe(e) {
  11704. if (e) e.preventDefault();
  11705. const target = document.getElementById('tools-port-target')?.value?.trim();
  11706. const port = parseInt(document.getElementById('tools-port-num')?.value || '80', 10);
  11707. const timeout = parseInt(document.getElementById('tools-port-timeout')?.value || '3', 10);
  11708. if (!target || !port) {
  11709. showToast('Input Required', 'Please enter a target host and TCP port', 'warning');
  11710. return;
  11711. }
  11712. const btn = document.getElementById('tools-port-btn');
  11713. const spinner = document.getElementById('tools-port-spinner');
  11714. if (btn) btn.disabled = true;
  11715. if (spinner) spinner.classList.remove('hidden');
  11716. try {
  11717. const res = await fetch(`${API_BASE}/tools/port-probe`, {
  11718. method: 'POST',
  11719. headers: { 'Content-Type': 'application/json' },
  11720. body: JSON.stringify({ target, port, timeout })
  11721. });
  11722. const data = await res.json();
  11723. if (!res.ok) {
  11724. showToast('Probe Error', data.error || 'Failed to probe TCP port', 'error');
  11725. return;
  11726. }
  11727. const resCard = document.getElementById('tools-port-results');
  11728. if (resCard) resCard.classList.remove('hidden');
  11729. const banner = document.getElementById('tools-port-banner');
  11730. const icon = document.getElementById('tools-port-icon');
  11731. const title = document.getElementById('tools-port-title');
  11732. const sub = document.getElementById('tools-port-sub');
  11733. const latency = document.getElementById('tools-port-latency');
  11734. if (data.open) {
  11735. if (banner) banner.className = 'rounded-xl p-5 border bg-emerald-950/30 border-emerald-800/50 flex items-center justify-between';
  11736. if (icon) {
  11737. icon.className = 'w-8 h-8 rounded-full flex items-center justify-center font-bold text-sm bg-emerald-500/20 text-emerald-400 border border-emerald-500/40';
  11738. icon.innerText = '✓';
  11739. }
  11740. if (title) {
  11741. title.className = 'text-sm font-bold text-emerald-300';
  11742. title.innerText = `PORT ${port} OPEN / LISTENING`;
  11743. }
  11744. if (sub) {
  11745. sub.className = 'text-xs mt-0.5 font-mono text-emerald-400/80';
  11746. sub.innerText = `TCP 3-way handshake established with ${escapeHtml(target)}:${port}${data.service ? ' (' + escapeHtml(data.service) + ')' : ''}`;
  11747. }
  11748. if (latency) {
  11749. latency.className = 'text-base font-bold font-mono text-emerald-300';
  11750. latency.innerText = `${data.latency_ms.toFixed(2)} ms`;
  11751. }
  11752. } else {
  11753. if (banner) banner.className = 'rounded-xl p-5 border bg-rose-950/30 border-rose-800/50 flex items-center justify-between';
  11754. if (icon) {
  11755. icon.className = 'w-8 h-8 rounded-full flex items-center justify-center font-bold text-sm bg-rose-500/20 text-rose-400 border border-rose-500/40';
  11756. icon.innerText = '✕';
  11757. }
  11758. if (title) {
  11759. title.className = 'text-sm font-bold text-rose-300';
  11760. title.innerText = `PORT ${port} CLOSED / FILTERED`;
  11761. }
  11762. if (sub) {
  11763. sub.className = 'text-xs mt-0.5 font-mono text-rose-400/80';
  11764. sub.innerText = `Connection failed or timed out to ${escapeHtml(target)}:${port}`;
  11765. }
  11766. if (latency) {
  11767. latency.className = 'text-base font-bold font-mono text-slate-500';
  11768. latency.innerText = '--';
  11769. }
  11770. }
  11771. const rawEl = document.getElementById('tools-port-raw');
  11772. if (rawEl) rawEl.innerText = data.raw_output || (data.open ? `Successfully connected to ${target}:${port} in ${data.latency_ms} ms` : `Connection failed: ${data.error || 'timed out or connection refused'}`);
  11773. showToast('Probe Complete', `Port ${port} is ${data.open ? 'OPEN' : 'CLOSED'}`, data.open ? 'success' : 'warning');
  11774. } catch (err) {
  11775. showToast('Probe Error', err.message, 'error');
  11776. } finally {
  11777. if (btn) btn.disabled = false;
  11778. if (spinner) spinner.classList.add('hidden');
  11779. }
  11780. }
  11781. // ==========================================
  11782. // DHCP CLIENT (/ip dhcp-client) CONTROLLER
  11783. // ==========================================
  11784. async function loadDHCPClients(showToastMsg = false) {
  11785. try {
  11786. const [clientsRes, sumRes] = await Promise.all([
  11787. fetch(`${API_BASE}/dhcp/clients`),
  11788. fetch(`${API_BASE}/dhcp/clients/summary`)
  11789. ]);
  11790. if (clientsRes.ok) {
  11791. state.dhcpClients = await clientsRes.json();
  11792. }
  11793. if (sumRes.ok) {
  11794. state.dhcpSummary = await sumRes.json();
  11795. }
  11796. renderDHCPClients();
  11797. updateDHCPSummaryCards();
  11798. const bDhcp = document.getElementById('badge-dhcp-client-count');
  11799. if (bDhcp && state.dhcpSummary) {
  11800. bDhcp.innerText = state.dhcpSummary.total_clients || 0;
  11801. }
  11802. if (showToastMsg) {
  11803. showToast('Refreshed', 'DHCP Client telemetry updated', 'info');
  11804. }
  11805. } catch (err) {
  11806. console.error('Failed to load DHCP clients:', err);
  11807. if (showToastMsg) {
  11808. showToast('Notice', 'Unable to fetch DHCP client status', 'warning');
  11809. }
  11810. }
  11811. }
  11812. function updateDHCPSummaryCards() {
  11813. const sum = state.dhcpSummary || {
  11814. total_clients: (state.dhcpClients || []).length,
  11815. bound_clients: (state.dhcpClients || []).filter(c => c.status === 'bound').length,
  11816. searching_clients: (state.dhcpClients || []).filter(c => c.status === 'searching').length,
  11817. disabled_clients: (state.dhcpClients || []).filter(c => !c.enabled).length
  11818. };
  11819. const totalEl = document.getElementById('dhcp-stat-total');
  11820. const boundEl = document.getElementById('dhcp-stat-bound');
  11821. const searchEl = document.getElementById('dhcp-stat-searching');
  11822. const disEl = document.getElementById('dhcp-stat-disabled');
  11823. if (totalEl) totalEl.innerText = sum.total_clients ?? 0;
  11824. if (boundEl) boundEl.innerText = sum.bound_clients ?? 0;
  11825. if (searchEl) searchEl.innerText = sum.searching_clients ?? 0;
  11826. if (disEl) disEl.innerText = sum.disabled_clients ?? 0;
  11827. }
  11828. function renderDHCPClients() {
  11829. const tbody = document.getElementById('dhcp-clients-tbody');
  11830. const emptyState = document.getElementById('dhcp-clients-empty');
  11831. if (!tbody) return;
  11832. const clients = Array.isArray(state.dhcpClients) ? state.dhcpClients : [];
  11833. if (clients.length === 0) {
  11834. tbody.innerHTML = '';
  11835. if (emptyState) emptyState.classList.remove('hidden');
  11836. return;
  11837. }
  11838. if (emptyState) emptyState.classList.add('hidden');
  11839. const sig = clients.map(c => `${c.id}:${c.status}:${c.ip_address}:${c.gateway}:${c.enabled}`).join(';');
  11840. if (tbody.dataset.sig === sig) return;
  11841. tbody.dataset.sig = sig;
  11842. tbody.innerHTML = clients.map(c => {
  11843. let statusBadge = '';
  11844. if (!c.enabled) {
  11845. statusBadge = '<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-slate-800 text-slate-400 border border-slate-700">DISABLED</span>';
  11846. } else if (c.status === 'bound') {
  11847. statusBadge = '<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-emerald-950 text-emerald-300 border border-emerald-800/60 inline-flex items-center gap-1.5"><span class="w-1.5 h-1.5 rounded-full bg-emerald-400 animate-pulse"></span>BOUND</span>';
  11848. } else if (c.status === 'searching') {
  11849. statusBadge = '<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-amber-950 text-amber-300 border border-amber-800/60 inline-flex items-center gap-1.5"><span class="w-1.5 h-1.5 rounded-full bg-amber-400 animate-ping"></span>SEARCHING...</span>';
  11850. } else if (c.status === 'stopped') {
  11851. statusBadge = '<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-slate-800 text-slate-400 border border-slate-700">STOPPED</span>';
  11852. } else {
  11853. statusBadge = `<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-rose-950 text-rose-300 border border-rose-800/60">${escapeHtml((c.status || 'UNKNOWN').toUpperCase())}</span>`;
  11854. }
  11855. const ipDisplay = c.ip_address ? `<span class="font-bold text-white">${escapeHtml(c.ip_address)}</span>` : '<span class="text-slate-500 italic">No lease</span>';
  11856. const gwDisplay = c.gateway ? `<span class="text-slate-300">${escapeHtml(c.gateway)}</span>` : '<span class="text-slate-600">--</span>';
  11857. const srvDisplay = c.dhcp_server ? `<span class="text-slate-300">${escapeHtml(c.dhcp_server)}</span>` : '<span class="text-slate-600">--</span>';
  11858. const dnsDisplay = (Array.isArray(c.dns_servers) && c.dns_servers.length > 0) ? `<span class="text-cyan-400">${c.dns_servers.map(d => escapeHtml(d)).join(', ')}</span>` : '<span class="text-slate-600">--</span>';
  11859. const expDisplay = c.expires_in ? `<span class="text-purple-300">${escapeHtml(c.expires_in)}</span>` : '<span class="text-slate-600">--</span>';
  11860. // Option flags
  11861. const flags = [];
  11862. if (c.add_default_route) flags.push('<span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 text-slate-300 border border-slate-700" title="Add Default Route">+GW</span>');
  11863. if (c.use_peer_dns) flags.push('<span class="px-1.5 py-0.5 rounded text-[10px] bg-cyan-950/60 text-cyan-300 border border-cyan-800/50" title="Use Peer DNS">+DNS</span>');
  11864. if (c.use_peer_ntp) flags.push('<span class="px-1.5 py-0.5 rounded text-[10px] bg-indigo-950/60 text-indigo-300 border border-indigo-800/50" title="Use Peer NTP">+NTP</span>');
  11865. flags.push(`<span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800/60 text-slate-400" title="Default Route Distance">dist:${c.default_route_distance || 1}</span>`);
  11866. return `
  11867. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 text-xs transition">
  11868. <td class="py-3 px-4">
  11869. <div class="flex items-center gap-2">
  11870. <span class="font-bold text-white text-sm">${escapeHtml(c.interface)}</span>
  11871. ${c.comment ? `<span class="text-[11px] text-slate-400 font-sans italic">(${escapeHtml(c.comment)})</span>` : ''}
  11872. </div>
  11873. </td>
  11874. <td class="py-3 px-4">${statusBadge}</td>
  11875. <td class="py-3 px-4 font-mono">${ipDisplay}</td>
  11876. <td class="py-3 px-4 font-mono">${gwDisplay}</td>
  11877. <td class="py-3 px-4 font-mono">${srvDisplay}</td>
  11878. <td class="py-3 px-4 font-mono text-[11px]">${dnsDisplay}</td>
  11879. <td class="py-3 px-4 font-mono text-[11px]">${expDisplay}</td>
  11880. <td class="py-3 px-4">
  11881. <div class="flex flex-wrap gap-1 font-mono">${flags.join('')}</div>
  11882. </td>
  11883. <td class="py-3 px-4 text-right space-x-1.5 font-sans whitespace-nowrap">
  11884. ${c.enabled ? `
  11885. <button onclick="renewDHCPClient('${c.id}')" class="px-2 py-1 rounded bg-slate-800 hover:bg-slate-700 text-amber-400 text-xs font-medium border border-slate-700 transition" title="Renew Lease">Renew</button>
  11886. <button onclick="releaseDHCPClient('${c.id}')" class="px-2 py-1 rounded bg-slate-800 hover:bg-slate-700 text-slate-300 text-xs font-medium border border-slate-700 transition" title="Release Lease">Release</button>
  11887. <button onclick="toggleDHCPClientState('${c.id}', false)" class="px-2 py-1 rounded bg-amber-500/10 hover:bg-amber-500/20 text-amber-400 text-xs font-medium border border-amber-500/30 transition" title="Disable DHCP Client">Disable</button>
  11888. ` : `
  11889. <button onclick="toggleDHCPClientState('${c.id}', true)" class="px-2.5 py-1 rounded bg-emerald-500/10 hover:bg-emerald-500/20 text-emerald-400 text-xs font-semibold border border-emerald-500/30 transition" title="Enable DHCP Client">Enable</button>
  11890. `}
  11891. <button onclick="openDHCPClientModal('${c.id}')" class="px-2 py-1 rounded bg-slate-800 hover:bg-slate-700 text-white text-xs font-medium border border-slate-700 transition" title="Edit Settings">Edit</button>
  11892. <button onclick="deleteDHCPClient('${c.id}', '${c.interface}')" class="px-2 py-1 rounded bg-rose-500/10 hover:bg-rose-500/20 text-rose-400 text-xs font-medium border border-rose-500/30 transition" title="Remove Client">✕</button>
  11893. </td>
  11894. </tr>
  11895. `;
  11896. }).join('');
  11897. }
  11898. function openDHCPClientModal(clientId = null) {
  11899. const modal = document.getElementById('modal-dhcp-client');
  11900. if (!modal) return;
  11901. const title = document.getElementById('modal-dhcp-title');
  11902. const idInput = document.getElementById('modal-dhcp-id');
  11903. const ifaceSelect = document.getElementById('modal-dhcp-iface');
  11904. const distInput = document.getElementById('modal-dhcp-distance');
  11905. const commentInput = document.getElementById('modal-dhcp-comment');
  11906. const defRouteCheck = document.getElementById('modal-dhcp-def-route');
  11907. const peerDnsCheck = document.getElementById('modal-dhcp-peer-dns');
  11908. const peerNtpCheck = document.getElementById('modal-dhcp-peer-ntp');
  11909. const enabledCheck = document.getElementById('modal-dhcp-enabled');
  11910. // Populate interfaces
  11911. if (ifaceSelect) {
  11912. let opts = '<option value="">Select interface...</option>';
  11913. const allIfaces = state.interfaces || [];
  11914. const allVlans = state.vlans || [];
  11915. const usedIfaces = new Set((state.dhcpClients || []).map(c => c.interface));
  11916. // Group 1: Physical & Bridge Interfaces
  11917. opts += '<optgroup label="Physical & Bridge Interfaces">';
  11918. allIfaces.filter(i => supportsDHCPClient(i)).forEach(i => {
  11919. const isConfigured = usedIfaces.has(i.name) ? ' (Configured)' : '';
  11920. opts += `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)} [${escapeHtml(i.role || i.type)}]${isConfigured}</option>`;
  11921. });
  11922. opts += '</optgroup>';
  11923. // Group 2: VLAN Interfaces
  11924. if (allVlans.length > 0) {
  11925. opts += '<optgroup label="802.1Q VLAN Sub-interfaces">';
  11926. allVlans.forEach(v => {
  11927. const isConfigured = usedIfaces.has(v.name) ? ' (Configured)' : '';
  11928. opts += `<option value="${escapeHtml(v.name)}">${escapeHtml(v.name)} (VLAN ${v.vlan_id})${isConfigured}</option>`;
  11929. });
  11930. opts += '</optgroup>';
  11931. }
  11932. ifaceSelect.innerHTML = opts;
  11933. }
  11934. if (clientId) {
  11935. const client = (state.dhcpClients || []).find(c => c.id === clientId);
  11936. if (client) {
  11937. if (title) title.innerText = `Edit DHCP Client: ${client.interface}`;
  11938. if (idInput) idInput.value = client.id;
  11939. if (ifaceSelect) {
  11940. ifaceSelect.value = client.interface;
  11941. ifaceSelect.disabled = true; // interface cannot be changed on edit
  11942. }
  11943. if (distInput) distInput.value = client.default_route_distance || 1;
  11944. if (commentInput) commentInput.value = client.comment || '';
  11945. if (defRouteCheck) defRouteCheck.checked = client.add_default_route !== false;
  11946. if (peerDnsCheck) peerDnsCheck.checked = client.use_peer_dns !== false;
  11947. if (peerNtpCheck) peerNtpCheck.checked = client.use_peer_ntp !== false;
  11948. if (enabledCheck) enabledCheck.checked = client.enabled !== false;
  11949. }
  11950. } else {
  11951. if (title) title.innerText = 'Add DHCP Client';
  11952. if (idInput) idInput.value = '';
  11953. if (ifaceSelect) {
  11954. ifaceSelect.value = '';
  11955. ifaceSelect.disabled = false;
  11956. }
  11957. if (distInput) distInput.value = 1;
  11958. if (commentInput) commentInput.value = '';
  11959. if (defRouteCheck) defRouteCheck.checked = true;
  11960. if (peerDnsCheck) peerDnsCheck.checked = true;
  11961. if (peerNtpCheck) peerNtpCheck.checked = true;
  11962. if (enabledCheck) enabledCheck.checked = true;
  11963. }
  11964. modal.classList.remove('hidden');
  11965. }
  11966. function openDHCPClientModalForIface(ifaceName) {
  11967. openDHCPClientModal();
  11968. const ifaceSelect = document.getElementById('modal-dhcp-iface');
  11969. if (ifaceSelect && ifaceName) {
  11970. ifaceSelect.value = ifaceName;
  11971. }
  11972. }
  11973. function closeDHCPClientModal() {
  11974. const modal = document.getElementById('modal-dhcp-client');
  11975. if (modal) modal.classList.add('hidden');
  11976. }
  11977. async function submitSaveDHCPClient(e) {
  11978. if (e) e.preventDefault();
  11979. const id = document.getElementById('modal-dhcp-id')?.value;
  11980. const iface = document.getElementById('modal-dhcp-iface')?.value?.trim();
  11981. const distance = parseInt(document.getElementById('modal-dhcp-distance')?.value || '1', 10);
  11982. const comment = document.getElementById('modal-dhcp-comment')?.value?.trim() || '';
  11983. const defRoute = document.getElementById('modal-dhcp-def-route')?.checked ?? true;
  11984. const peerDns = document.getElementById('modal-dhcp-peer-dns')?.checked ?? true;
  11985. const peerNtp = document.getElementById('modal-dhcp-peer-ntp')?.checked ?? true;
  11986. const enabled = document.getElementById('modal-dhcp-enabled')?.checked ?? true;
  11987. if (!id && !iface) {
  11988. showToast('Input Required', 'Please select an interface for the DHCP client', 'warning');
  11989. return;
  11990. }
  11991. try {
  11992. let res;
  11993. if (id) {
  11994. // PUT update
  11995. res = await fetch(`${API_BASE}/dhcp/clients/${id}`, {
  11996. method: 'PUT',
  11997. headers: { 'Content-Type': 'application/json' },
  11998. body: JSON.stringify({
  11999. enabled,
  12000. add_default_route: defRoute,
  12001. default_route_distance: distance,
  12002. use_peer_dns: peerDns,
  12003. use_peer_ntp: peerNtp,
  12004. comment
  12005. })
  12006. });
  12007. } else {
  12008. // POST create
  12009. res = await fetch(`${API_BASE}/dhcp/clients`, {
  12010. method: 'POST',
  12011. headers: { 'Content-Type': 'application/json' },
  12012. body: JSON.stringify({
  12013. interface: iface,
  12014. enabled,
  12015. add_default_route: defRoute,
  12016. default_route_distance: distance,
  12017. use_peer_dns: peerDns,
  12018. use_peer_ntp: peerNtp,
  12019. comment
  12020. })
  12021. });
  12022. }
  12023. const data = await res.json();
  12024. if (!res.ok) {
  12025. showToast('Error', data.error || 'Failed to save DHCP client', 'error');
  12026. return;
  12027. }
  12028. closeDHCPClientModal();
  12029. showToast('Success', id ? 'DHCP Client updated successfully' : `DHCP Client activated on ${iface}`, 'success');
  12030. await loadDHCPClients();
  12031. fetchData(); // refresh interfaces list with new lease/status
  12032. } catch (err) {
  12033. showToast('Error', err.message, 'error');
  12034. }
  12035. }
  12036. async function toggleDHCPClientState(id, enabled) {
  12037. try {
  12038. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/state`, {
  12039. method: 'POST',
  12040. headers: { 'Content-Type': 'application/json' },
  12041. body: JSON.stringify({ enabled })
  12042. });
  12043. const data = await res.json();
  12044. if (!res.ok) {
  12045. showToast('Error', data.error || 'Failed to toggle client state', 'error');
  12046. return;
  12047. }
  12048. showToast('Updated', `DHCP client ${enabled ? 'enabled' : 'disabled'}`, 'info');
  12049. await loadDHCPClients();
  12050. fetchData();
  12051. } catch (err) {
  12052. showToast('Error', err.message, 'error');
  12053. }
  12054. }
  12055. async function renewDHCPClient(id) {
  12056. try {
  12057. showToast('Renewing...', 'Requesting DHCP lease renewal from upstream server', 'info');
  12058. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/renew`, {
  12059. method: 'POST'
  12060. });
  12061. const data = await res.json();
  12062. if (!res.ok) {
  12063. showToast('Error', data.error || 'Failed to renew lease', 'error');
  12064. return;
  12065. }
  12066. showToast('Lease Renewed', 'DHCP renewal signal sent successfully', 'success');
  12067. setTimeout(() => {
  12068. loadDHCPClients();
  12069. fetchData();
  12070. }, 1500);
  12071. } catch (err) {
  12072. showToast('Error', err.message, 'error');
  12073. }
  12074. }
  12075. async function releaseDHCPClient(id) {
  12076. try {
  12077. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/release`, {
  12078. method: 'POST'
  12079. });
  12080. const data = await res.json();
  12081. if (!res.ok) {
  12082. showToast('Error', data.error || 'Failed to release lease', 'error');
  12083. return;
  12084. }
  12085. showToast('Lease Released', 'DHCP lease released from upstream server', 'info');
  12086. await loadDHCPClients();
  12087. fetchData();
  12088. } catch (err) {
  12089. showToast('Error', err.message, 'error');
  12090. }
  12091. }
  12092. async function deleteDHCPClient(id, ifaceName) {
  12093. if (!confirm(`Are you sure you want to remove the DHCP Client on ${ifaceName}? The interface will release its dynamic IP.`)) {
  12094. return;
  12095. }
  12096. try {
  12097. const res = await fetch(`${API_BASE}/dhcp/clients/${id}`, {
  12098. method: 'DELETE'
  12099. });
  12100. const data = await res.json();
  12101. if (!res.ok) {
  12102. showToast('Error', data.error || 'Failed to delete DHCP client', 'error');
  12103. return;
  12104. }
  12105. showToast('Deleted', `DHCP client removed from ${ifaceName}`, 'info');
  12106. await loadDHCPClients();
  12107. fetchData();
  12108. } catch (err) {
  12109. showToast('Error', err.message, 'error');
  12110. }
  12111. }
  12112. // ==================== DHCP SERVER (/ip dhcp-server) ====================
  12113. async function loadDHCPServer(populate = true) {
  12114. try {
  12115. const [sumRes, srvRes, netRes, leaseRes, optRes] = await Promise.all([
  12116. fetch(`${API_BASE}/dhcp-server/summary`),
  12117. fetch(`${API_BASE}/dhcp-server/servers`),
  12118. fetch(`${API_BASE}/dhcp-server/networks`),
  12119. fetch(`${API_BASE}/dhcp-server/leases`),
  12120. fetch(`${API_BASE}/dhcp-server/options`)
  12121. ]);
  12122. if (sumRes.ok) state.dhcpServerSummary = await sumRes.json();
  12123. if (srvRes.ok) state.dhcpServers = await srvRes.json();
  12124. if (netRes.ok) state.dhcpNetworks = await netRes.json();
  12125. if (leaseRes.ok) state.dhcpLeases = await leaseRes.json();
  12126. if (optRes.ok) state.dhcpOptions = await optRes.json();
  12127. const sum = state.dhcpServerSummary || {};
  12128. const srvs = state.dhcpServers || [];
  12129. const nets = state.dhcpNetworks || [];
  12130. const leases = state.dhcpLeases || [];
  12131. const opts = state.dhcpOptions || [];
  12132. // KPI Cards
  12133. const statActive = document.getElementById('dhcp-server-stat-active');
  12134. if (statActive) {
  12135. const activeCount = srvs.filter(s => s.running).length;
  12136. statActive.innerText = `${activeCount} / ${srvs.length}`;
  12137. }
  12138. const statLeases = document.getElementById('dhcp-server-stat-leases');
  12139. if (statLeases) {
  12140. statLeases.innerText = leases.length;
  12141. }
  12142. const statLeasesSub = document.getElementById('dhcp-server-stat-leases-sub');
  12143. if (statLeasesSub) {
  12144. const dyn = leases.filter(l => l.dynamic).length;
  12145. const st = leases.filter(l => !l.dynamic).length;
  12146. statLeasesSub.innerText = `${dyn} dynamic, ${st} static`;
  12147. }
  12148. const statNetworks = document.getElementById('dhcp-server-stat-networks');
  12149. if (statNetworks) {
  12150. statNetworks.innerText = nets.length;
  12151. }
  12152. // Subtab Badges
  12153. const bSrv = document.getElementById('dhcp-server-tab-badge-servers');
  12154. if (bSrv) bSrv.innerText = srvs.length;
  12155. const bNet = document.getElementById('dhcp-server-tab-badge-networks');
  12156. if (bNet) bNet.innerText = nets.length;
  12157. const bLease = document.getElementById('dhcp-server-tab-badge-leases');
  12158. if (bLease) bLease.innerText = leases.length;
  12159. const bOpt = document.getElementById('dhcp-server-tab-badge-options');
  12160. if (bOpt) bOpt.innerText = opts.length;
  12161. // Sidebar Badge
  12162. const sideBadge = document.getElementById('badge-dhcp-server-count');
  12163. if (sideBadge) sideBadge.innerText = leases.length || srvs.length;
  12164. renderCurrentDHCPServerTab();
  12165. } catch (err) {
  12166. console.error('Failed to load DHCP Server:', err);
  12167. }
  12168. }
  12169. function switchDHCPServerTab(tab) {
  12170. state.dhcpServerTab = tab;
  12171. const tabs = ['servers', 'networks', 'leases', 'options'];
  12172. tabs.forEach(t => {
  12173. const panel = document.getElementById(`dhcp-server-subtab-${t}`);
  12174. const btn = document.getElementById(`dhcp-server-tab-btn-${t}`);
  12175. if (panel) {
  12176. if (t === tab) panel.classList.remove('hidden');
  12177. else panel.classList.add('hidden');
  12178. }
  12179. if (btn) {
  12180. if (t === tab) {
  12181. btn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-emerald-500 text-white transition flex items-center gap-2 whitespace-nowrap';
  12182. } else {
  12183. btn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-transparent text-slate-400 hover:text-slate-200 transition flex items-center gap-2 whitespace-nowrap';
  12184. }
  12185. }
  12186. });
  12187. const addBtn = document.getElementById('dhcp-server-primary-add-btn');
  12188. if (addBtn) {
  12189. if (tab === 'servers') addBtn.innerHTML = '<span>+ Add Server</span>';
  12190. else if (tab === 'networks') addBtn.innerHTML = '<span>+ Add Network</span>';
  12191. else if (tab === 'leases') addBtn.innerHTML = '<span>+ Add Static Lease</span>';
  12192. else if (tab === 'options') addBtn.innerHTML = '<span>+ Add Option</span>';
  12193. }
  12194. renderCurrentDHCPServerTab();
  12195. }
  12196. function handleDHCPServerPrimaryAdd() {
  12197. const tab = state.dhcpServerTab || 'servers';
  12198. if (tab === 'servers') openAddDHCPServerModal();
  12199. else if (tab === 'networks') openAddDHCPNetworkModal();
  12200. else if (tab === 'leases') openAddDHCPStaticLeaseModal();
  12201. else if (tab === 'options') openAddDHCPOptionModal();
  12202. }
  12203. function renderCurrentDHCPServerTab() {
  12204. const tab = state.dhcpServerTab || 'servers';
  12205. if (tab === 'servers') renderDHCPServers();
  12206. else if (tab === 'networks') renderDHCPNetworks();
  12207. else if (tab === 'leases') renderDHCPLeases();
  12208. else if (tab === 'options') renderDHCPOptions();
  12209. }
  12210. function renderDHCPServers() {
  12211. const tbody = document.getElementById('dhcp-server-tbody');
  12212. const empty = document.getElementById('dhcp-server-empty');
  12213. if (!tbody) return;
  12214. const servers = state.dhcpServers || [];
  12215. if (servers.length === 0) {
  12216. tbody.innerHTML = '';
  12217. empty?.classList.remove('hidden');
  12218. return;
  12219. }
  12220. empty?.classList.add('hidden');
  12221. const sig = servers.map(s => `${s.id}:${s.running}:${s.disabled}:${s.active_leases}:${s.interface}`).join(';');
  12222. if (tbody.dataset.sig === sig) return;
  12223. tbody.dataset.sig = sig;
  12224. tbody.innerHTML = '';
  12225. servers.forEach(s => {
  12226. const tr = document.createElement('tr');
  12227. tr.className = `hover:bg-slate-800/40 transition text-xs ${s.disabled ? 'opacity-50' : ''}`;
  12228. tr.innerHTML = `
  12229. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(s.running, s.disabled)}</td>
  12230. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(s.name)}</td>
  12231. <td class="py-2.5 px-3 font-mono text-cyan-400 font-semibold">${escapeHtml(s.interface)}</td>
  12232. <td class="py-2.5 px-3 font-mono font-semibold">${s.network ? `<span class="px-2 py-0.5 rounded text-[11px] bg-emerald-500/10 text-emerald-300 border border-emerald-500/20 font-bold">${escapeHtml(s.network)}</span>` : '<span class="text-slate-500 italic text-[11px]">Unassigned</span>'}</td>
  12233. <td class="py-2.5 px-3 font-mono text-emerald-400">${escapeHtml(s.address_pool)}</td>
  12234. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(s.lease_time || '12h')}</td>
  12235. <td class="py-2.5 px-3 font-mono text-slate-300">${s.authoritative ? '<span class="text-emerald-400 font-bold">yes</span>' : '<span class="text-slate-500">no</span>'}</td>
  12236. <td class="py-2.5 px-3 font-mono text-cyan-300"><span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 border border-slate-700">${s.active_leases || 0}</span></td>
  12237. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]" title="${escapeHtml(s.comment || '')}">${escapeHtml(s.comment || '-')}</td>
  12238. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  12239. <button onclick="toggleDHCPServerState('${s.id}', ${!s.disabled})" class="text-xs ${s.disabled ? 'text-emerald-400' : 'text-slate-400'} hover:underline">${s.disabled ? 'Enable' : 'Disable'}</button>
  12240. <button onclick="openEditDHCPServerModal('${s.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  12241. <button onclick="deleteDHCPServer('${s.id}', '${escapeHtml(s.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  12242. </td>
  12243. `;
  12244. tbody.appendChild(tr);
  12245. });
  12246. }
  12247. function renderDHCPNetworks() {
  12248. const tbody = document.getElementById('dhcp-networks-tbody');
  12249. const empty = document.getElementById('dhcp-networks-empty');
  12250. if (!tbody) return;
  12251. tbody.innerHTML = '';
  12252. const networks = state.dhcpNetworks || [];
  12253. if (networks.length === 0) {
  12254. empty?.classList.remove('hidden');
  12255. return;
  12256. }
  12257. empty?.classList.add('hidden');
  12258. networks.forEach(n => {
  12259. const tr = document.createElement('tr');
  12260. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  12261. const dnsStr = (n.dns_servers || []).join(', ') || '-';
  12262. const optionsChips = (n.dhcp_options || []).map(optId => {
  12263. const opt = (state.dhcpOptions || []).find(o => o.id === optId);
  12264. if (!opt) return '';
  12265. return `<span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 text-cyan-300 border border-slate-700 inline-block mr-1 mb-0.5" title="${escapeHtml(opt.name)}: ${escapeHtml(opt.value)}">#${opt.code} ${escapeHtml(opt.name)}</span>`;
  12266. }).filter(Boolean).join('');
  12267. tr.innerHTML = `
  12268. <td class="py-2.5 px-3 font-bold text-emerald-400 font-mono">${escapeHtml(n.address)}</td>
  12269. <td class="py-2.5 px-3 font-mono text-cyan-300 font-semibold">${escapeHtml(n.gateway || '-')}</td>
  12270. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(n.netmask || '-')}</td>
  12271. <td class="py-2.5 px-3 font-mono text-slate-300 truncate max-w-[140px]" title="${escapeHtml(dnsStr)}">${escapeHtml(dnsStr)}</td>
  12272. <td class="py-2.5 px-3 font-mono text-slate-400">${escapeHtml(n.domain || '-')}</td>
  12273. <td class="py-2.5 px-3 font-mono">${optionsChips || '<span class="text-slate-600 font-sans">-</span>'}</td>
  12274. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(n.comment || '')}">${escapeHtml(n.comment || '-')}</td>
  12275. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  12276. <button onclick="openEditDHCPNetworkModal('${n.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  12277. <button onclick="deleteDHCPNetwork('${n.id}', '${escapeHtml(n.address)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  12278. </td>
  12279. `;
  12280. tbody.appendChild(tr);
  12281. });
  12282. }
  12283. function renderDHCPLeases() {
  12284. const tbody = document.getElementById('dhcp-leases-tbody');
  12285. const empty = document.getElementById('dhcp-leases-empty');
  12286. if (!tbody) return;
  12287. tbody.innerHTML = '';
  12288. const leases = state.dhcpLeases || [];
  12289. if (leases.length === 0) {
  12290. empty?.classList.remove('hidden');
  12291. return;
  12292. }
  12293. empty?.classList.add('hidden');
  12294. leases.forEach(l => {
  12295. const tr = document.createElement('tr');
  12296. tr.className = `hover:bg-slate-800/40 transition text-xs ${l.disabled ? 'opacity-50' : ''}`;
  12297. const flag = l.dynamic ? '<span class="text-sky-400 font-bold" title="Dynamic">D</span>' : '<span class="text-purple-400 font-bold" title="Static Reservation">S</span>';
  12298. const statusBadge = l.status === 'bound'
  12299. ? '<span class="px-1.5 py-0.5 rounded text-[10px] bg-emerald-500/20 text-emerald-300 border border-emerald-500/30 font-semibold font-mono">bound</span>'
  12300. : l.status === 'static'
  12301. ? '<span class="px-1.5 py-0.5 rounded text-[10px] bg-purple-500/20 text-purple-300 border border-purple-500/30 font-semibold font-mono">static</span>'
  12302. : '<span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 text-slate-400 border border-slate-700 font-mono">waiting</span>';
  12303. const makeStaticBtn = l.dynamic
  12304. ? `<button onclick="makeDHCPLeaseStatic('${escapeHtml(l.mac_address)}', '${escapeHtml(l.address)}', '${escapeHtml(l.hostname || '')}', '${escapeHtml(l.comment || '')}')" class="text-xs px-2 py-0.5 rounded bg-purple-500/20 text-purple-300 border border-purple-500/30 hover:bg-purple-500/30 font-medium">Make Static</button>`
  12305. : `<button onclick="deleteDHCPStaticLease('${l.id}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Remove</button>`;
  12306. tr.innerHTML = `
  12307. <td class="py-2.5 px-3 text-center">${flag}</td>
  12308. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(l.address)}</td>
  12309. <td class="py-2.5 px-3 font-mono text-cyan-300">${escapeHtml(l.mac_address)}</td>
  12310. <td class="py-2.5 px-3 font-sans text-slate-200 font-medium">${escapeHtml(l.hostname || '*')}</td>
  12311. <td class="py-2.5 px-3 font-mono text-slate-400">${escapeHtml(l.server || 'all')}</td>
  12312. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(l.expires_in || 'never')}</td>
  12313. <td class="py-2.5 px-3">${statusBadge}</td>
  12314. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(l.comment || '')}">${escapeHtml(l.comment || '-')}</td>
  12315. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  12316. ${makeStaticBtn}
  12317. </td>
  12318. `;
  12319. tbody.appendChild(tr);
  12320. });
  12321. }
  12322. function renderDHCPOptions() {
  12323. const tbody = document.getElementById('dhcp-options-tbody');
  12324. const empty = document.getElementById('dhcp-options-empty');
  12325. if (!tbody) return;
  12326. tbody.innerHTML = '';
  12327. const options = state.dhcpOptions || [];
  12328. if (options.length === 0) {
  12329. empty?.classList.remove('hidden');
  12330. return;
  12331. }
  12332. empty?.classList.add('hidden');
  12333. options.forEach(o => {
  12334. const tr = document.createElement('tr');
  12335. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  12336. tr.innerHTML = `
  12337. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(o.name)}</td>
  12338. <td class="py-2.5 px-3 font-bold text-cyan-400 font-mono">${o.code}</td>
  12339. <td class="py-2.5 px-3 font-mono text-emerald-400 break-all max-w-xs">${escapeHtml(o.value)}</td>
  12340. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-xs" title="${escapeHtml(o.comment || '')}">${escapeHtml(o.comment || '-')}</td>
  12341. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  12342. <button onclick="openEditDHCPOptionModal('${o.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  12343. <button onclick="deleteDHCPOption('${o.id}', '${escapeHtml(o.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  12344. </td>
  12345. `;
  12346. tbody.appendChild(tr);
  12347. });
  12348. }
  12349. // ==================== MODALS & ACTIONS: SERVER ====================
  12350. function populateDHCPNetworkSelect(elemId, selectedVal) {
  12351. const sel = document.getElementById(elemId);
  12352. if (!sel) return;
  12353. sel.innerHTML = '<option value="">Select network subnet...</option>';
  12354. const networks = state.dhcpNetworks || [];
  12355. networks.forEach(n => {
  12356. const opt = document.createElement('option');
  12357. opt.value = n.address;
  12358. opt.innerText = `${n.address} (Gateway: ${n.gateway || 'None'}${n.comment ? ' - ' + n.comment : ''})`;
  12359. if (selectedVal && (selectedVal === n.address || selectedVal === n.id)) {
  12360. opt.selected = true;
  12361. }
  12362. sel.appendChild(opt);
  12363. });
  12364. }
  12365. function onDHCPServerNetworkChange() {
  12366. const netSel = document.getElementById('dhcp-server-modal-network');
  12367. if (!netSel) return;
  12368. const netVal = netSel.value;
  12369. if (!netVal) return;
  12370. const poolInput = document.getElementById('dhcp-server-modal-pool');
  12371. if (!poolInput) return;
  12372. // Auto-calculate suggested address pool based on subnet CIDR
  12373. const parts = netVal.split('/');
  12374. const ip = parts[0];
  12375. const cidr = parseInt(parts[1] || '24', 10);
  12376. if (cidr === 24) {
  12377. const octets = ip.split('.');
  12378. if (octets.length === 4) {
  12379. const base = `${octets[0]}.${octets[1]}.${octets[2]}`;
  12380. poolInput.value = `${base}.10-${base}.254`;
  12381. }
  12382. }
  12383. }
  12384. function openAddDHCPServerModal() {
  12385. document.getElementById('dhcp-server-modal-title').innerText = 'Add DHCP Server';
  12386. document.getElementById('dhcp-server-modal-id').value = '';
  12387. document.getElementById('dhcp-server-modal-name').value = `dhcp${(state.dhcpServers || []).length + 1}`;
  12388. document.getElementById('dhcp-server-modal-pool').value = '192.168.88.10-192.168.88.254';
  12389. document.getElementById('dhcp-server-modal-leasetime').value = '12h';
  12390. document.getElementById('dhcp-server-modal-comment').value = '';
  12391. document.getElementById('dhcp-server-modal-authoritative').checked = true;
  12392. document.getElementById('dhcp-server-modal-disabled').checked = false;
  12393. populateDHCPIfaceSelect('dhcp-server-modal-iface', '');
  12394. const networks = state.dhcpNetworks || [];
  12395. const defaultNet = networks.length > 0 ? networks[0].address : '';
  12396. populateDHCPNetworkSelect('dhcp-server-modal-network', defaultNet);
  12397. if (defaultNet) {
  12398. onDHCPServerNetworkChange();
  12399. }
  12400. document.getElementById('dhcp-server-instance-modal').classList.remove('hidden');
  12401. }
  12402. function openEditDHCPServerModal(id) {
  12403. const s = (state.dhcpServers || []).find(item => item.id === id);
  12404. if (!s) return;
  12405. document.getElementById('dhcp-server-modal-title').innerText = `Edit DHCP Server (${s.name})`;
  12406. document.getElementById('dhcp-server-modal-id').value = s.id;
  12407. document.getElementById('dhcp-server-modal-name').value = s.name;
  12408. document.getElementById('dhcp-server-modal-pool').value = s.address_pool;
  12409. document.getElementById('dhcp-server-modal-leasetime').value = s.lease_time || '12h';
  12410. document.getElementById('dhcp-server-modal-comment').value = s.comment || '';
  12411. document.getElementById('dhcp-server-modal-authoritative').checked = s.authoritative !== false;
  12412. document.getElementById('dhcp-server-modal-disabled').checked = !!s.disabled;
  12413. populateDHCPIfaceSelect('dhcp-server-modal-iface', s.interface);
  12414. populateDHCPNetworkSelect('dhcp-server-modal-network', s.network || '');
  12415. document.getElementById('dhcp-server-instance-modal').classList.remove('hidden');
  12416. }
  12417. function closeDHCPServerModal() {
  12418. document.getElementById('dhcp-server-instance-modal').classList.add('hidden');
  12419. }
  12420. async function submitSaveDHCPServer(e) {
  12421. e.preventDefault();
  12422. const id = document.getElementById('dhcp-server-modal-id').value;
  12423. const name = document.getElementById('dhcp-server-modal-name').value.trim();
  12424. const iface = document.getElementById('dhcp-server-modal-iface').value;
  12425. const network = document.getElementById('dhcp-server-modal-network').value.trim();
  12426. const pool = document.getElementById('dhcp-server-modal-pool').value.trim();
  12427. const leaseTime = document.getElementById('dhcp-server-modal-leasetime').value.trim() || '12h';
  12428. const comment = document.getElementById('dhcp-server-modal-comment').value.trim();
  12429. const authoritative = document.getElementById('dhcp-server-modal-authoritative').checked;
  12430. const disabled = document.getElementById('dhcp-server-modal-disabled').checked;
  12431. try {
  12432. const res = await fetch(`${API_BASE}/dhcp-server/servers`, {
  12433. method: 'POST',
  12434. headers: { 'Content-Type': 'application/json' },
  12435. body: JSON.stringify({
  12436. id,
  12437. name,
  12438. interface: iface,
  12439. network,
  12440. address_pool: pool,
  12441. lease_time: leaseTime,
  12442. authoritative,
  12443. disabled,
  12444. comment
  12445. })
  12446. });
  12447. if (res.ok) {
  12448. showToast('DHCP Server Saved', `Server ${name} configured successfully`, 'success');
  12449. closeDHCPServerModal();
  12450. loadDHCPServer(false);
  12451. fetchData(false);
  12452. } else {
  12453. const err = await res.text();
  12454. showToast('Error', err, 'error');
  12455. }
  12456. } catch (err) {
  12457. showToast('Error', err.message, 'error');
  12458. }
  12459. }
  12460. async function toggleDHCPServerState(id, disabled) {
  12461. try {
  12462. const res = await fetch(`${API_BASE}/dhcp-server/servers/${encodeURIComponent(id)}/state`, {
  12463. method: 'POST',
  12464. headers: { 'Content-Type': 'application/json' },
  12465. body: JSON.stringify({ disabled })
  12466. });
  12467. if (res.ok) {
  12468. showToast('State Updated', disabled ? 'Server disabled' : 'Server enabled', 'info');
  12469. loadDHCPServer(false);
  12470. fetchData(false);
  12471. }
  12472. } catch (err) {
  12473. showToast('Error', err.message, 'error');
  12474. }
  12475. }
  12476. async function deleteDHCPServer(id, name) {
  12477. if (!confirm(`Are you sure you want to delete DHCP Server "${name}"?`)) return;
  12478. try {
  12479. const res = await fetch(`${API_BASE}/dhcp-server/servers/${encodeURIComponent(id)}`, { method: 'DELETE' });
  12480. if (res.ok) {
  12481. showToast('Deleted', `DHCP Server ${name} removed`, 'success');
  12482. loadDHCPServer(false);
  12483. fetchData(false);
  12484. }
  12485. } catch (err) {
  12486. showToast('Error', err.message, 'error');
  12487. }
  12488. }
  12489. // ==================== MODALS & ACTIONS: NETWORKS ====================
  12490. function openAddDHCPNetworkModal() {
  12491. document.getElementById('dhcp-network-modal-title').innerText = 'Add DHCP Network';
  12492. document.getElementById('dhcp-network-modal-id').value = '';
  12493. document.getElementById('dhcp-network-modal-address').value = '192.168.88.0/24';
  12494. document.getElementById('dhcp-network-modal-gateway').value = '192.168.88.1';
  12495. document.getElementById('dhcp-network-modal-dns').value = '192.168.88.1, 1.1.1.1, 8.8.8.8';
  12496. document.getElementById('dhcp-network-modal-domain').value = 'lan';
  12497. document.getElementById('dhcp-network-modal-netmask').value = '';
  12498. document.getElementById('dhcp-network-modal-comment').value = '';
  12499. renderDHCPNetworkOptionsCheckboxes([]);
  12500. document.getElementById('dhcp-network-modal').classList.remove('hidden');
  12501. }
  12502. function openEditDHCPNetworkModal(id) {
  12503. const n = (state.dhcpNetworks || []).find(item => item.id === id);
  12504. if (!n) return;
  12505. document.getElementById('dhcp-network-modal-title').innerText = `Edit DHCP Network (${n.address})`;
  12506. document.getElementById('dhcp-network-modal-id').value = n.id;
  12507. document.getElementById('dhcp-network-modal-address').value = n.address;
  12508. document.getElementById('dhcp-network-modal-gateway').value = n.gateway || '';
  12509. document.getElementById('dhcp-network-modal-dns').value = (n.dns_servers || []).join(', ');
  12510. document.getElementById('dhcp-network-modal-domain').value = n.domain || '';
  12511. document.getElementById('dhcp-network-modal-netmask').value = n.netmask || '';
  12512. document.getElementById('dhcp-network-modal-comment').value = n.comment || '';
  12513. renderDHCPNetworkOptionsCheckboxes(n.dhcp_options || []);
  12514. document.getElementById('dhcp-network-modal').classList.remove('hidden');
  12515. }
  12516. function renderDHCPNetworkOptionsCheckboxes(selectedIds) {
  12517. const container = document.getElementById('dhcp-network-modal-options-list');
  12518. if (!container) return;
  12519. container.innerHTML = '';
  12520. const opts = state.dhcpOptions || [];
  12521. if (opts.length === 0) {
  12522. container.innerHTML = '<span class="text-slate-500 text-[11px] col-span-2">No custom options configured. Add some in the "Options" tab.</span>';
  12523. return;
  12524. }
  12525. opts.forEach(o => {
  12526. const isChecked = selectedIds.includes(o.id);
  12527. const label = document.createElement('label');
  12528. label.className = 'flex items-center space-x-2 text-slate-300 hover:text-white cursor-pointer';
  12529. label.innerHTML = `
  12530. <input type="checkbox" name="dhcp-net-opt" value="${o.id}" ${isChecked ? 'checked' : ''} class="rounded bg-slate-800 border-slate-700 text-emerald-600">
  12531. <span class="truncate" title="${escapeHtml(o.name)} (Code ${o.code})">${escapeHtml(o.name)} <span class="text-cyan-400">#${o.code}</span></span>
  12532. `;
  12533. container.appendChild(label);
  12534. });
  12535. }
  12536. function closeDHCPNetworkModal() {
  12537. document.getElementById('dhcp-network-modal').classList.add('hidden');
  12538. }
  12539. async function submitSaveDHCPNetwork(e) {
  12540. e.preventDefault();
  12541. const id = document.getElementById('dhcp-network-modal-id').value;
  12542. const address = document.getElementById('dhcp-network-modal-address').value.trim();
  12543. const gateway = document.getElementById('dhcp-network-modal-gateway').value.trim();
  12544. const dnsStr = document.getElementById('dhcp-network-modal-dns').value.trim();
  12545. const domain = document.getElementById('dhcp-network-modal-domain').value.trim();
  12546. const netmask = document.getElementById('dhcp-network-modal-netmask').value.trim();
  12547. const comment = document.getElementById('dhcp-network-modal-comment').value.trim();
  12548. const selectedOpts = [];
  12549. document.querySelectorAll('input[name="dhcp-net-opt"]:checked').forEach(cb => selectedOpts.push(cb.value));
  12550. const dnsServers = dnsStr ? dnsStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  12551. try {
  12552. const res = await fetch(`${API_BASE}/dhcp-server/networks`, {
  12553. method: 'POST',
  12554. headers: { 'Content-Type': 'application/json' },
  12555. body: JSON.stringify({
  12556. id,
  12557. address,
  12558. gateway,
  12559. netmask,
  12560. dns_servers: dnsServers,
  12561. domain,
  12562. dhcp_options: selectedOpts,
  12563. comment
  12564. })
  12565. });
  12566. if (res.ok) {
  12567. showToast('Network Saved', `Subnet ${address} configured successfully`, 'success');
  12568. closeDHCPNetworkModal();
  12569. loadDHCPServer(false);
  12570. fetchData(false);
  12571. } else {
  12572. const err = await res.text();
  12573. showToast('Error', err, 'error');
  12574. }
  12575. } catch (err) {
  12576. showToast('Error', err.message, 'error');
  12577. }
  12578. }
  12579. async function deleteDHCPNetwork(id, addr) {
  12580. if (!confirm(`Are you sure you want to delete DHCP Network "${addr}"?`)) return;
  12581. try {
  12582. const res = await fetch(`${API_BASE}/dhcp-server/networks/${encodeURIComponent(id)}`, { method: 'DELETE' });
  12583. if (res.ok) {
  12584. showToast('Deleted', `Network ${addr} removed`, 'success');
  12585. loadDHCPServer(false);
  12586. fetchData(false);
  12587. }
  12588. } catch (err) {
  12589. showToast('Error', err.message, 'error');
  12590. }
  12591. }
  12592. // ==================== MODALS & ACTIONS: LEASES ====================
  12593. function openAddDHCPStaticLeaseModal() {
  12594. document.getElementById('dhcp-static-lease-modal-title').innerText = 'Add Static Lease Reservation';
  12595. document.getElementById('dhcp-static-lease-modal-id').value = '';
  12596. document.getElementById('dhcp-static-lease-modal-mac').value = '';
  12597. document.getElementById('dhcp-static-lease-modal-ip').value = '';
  12598. document.getElementById('dhcp-static-lease-modal-hostname').value = '';
  12599. document.getElementById('dhcp-static-lease-modal-server').value = 'all';
  12600. document.getElementById('dhcp-static-lease-modal-comment').value = '';
  12601. document.getElementById('dhcp-static-lease-modal-disabled').checked = false;
  12602. document.getElementById('dhcp-static-lease-modal').classList.remove('hidden');
  12603. }
  12604. function closeDHCPStaticLeaseModal() {
  12605. document.getElementById('dhcp-static-lease-modal').classList.add('hidden');
  12606. }
  12607. async function submitSaveDHCPStaticLease(e) {
  12608. e.preventDefault();
  12609. const id = document.getElementById('dhcp-static-lease-modal-id').value;
  12610. const mac = document.getElementById('dhcp-static-lease-modal-mac').value.trim();
  12611. const ip = document.getElementById('dhcp-static-lease-modal-ip').value.trim();
  12612. const hostname = document.getElementById('dhcp-static-lease-modal-hostname').value.trim();
  12613. const server = document.getElementById('dhcp-static-lease-modal-server').value.trim() || 'all';
  12614. const comment = document.getElementById('dhcp-static-lease-modal-comment').value.trim();
  12615. const disabled = document.getElementById('dhcp-static-lease-modal-disabled').checked;
  12616. try {
  12617. const res = await fetch(`${API_BASE}/dhcp-server/leases/static`, {
  12618. method: 'POST',
  12619. headers: { 'Content-Type': 'application/json' },
  12620. body: JSON.stringify({
  12621. id,
  12622. mac_address: mac,
  12623. address: ip,
  12624. hostname,
  12625. server,
  12626. comment,
  12627. disabled
  12628. })
  12629. });
  12630. if (res.ok) {
  12631. showToast('Static Lease Saved', `IP ${ip} reserved for ${mac}`, 'success');
  12632. closeDHCPStaticLeaseModal();
  12633. loadDHCPServer(false);
  12634. fetchData(false);
  12635. } else {
  12636. const err = await res.text();
  12637. showToast('Error', err, 'error');
  12638. }
  12639. } catch (err) {
  12640. showToast('Error', err.message, 'error');
  12641. }
  12642. }
  12643. async function deleteDHCPStaticLease(id) {
  12644. if (!confirm('Are you sure you want to remove this static reservation?')) return;
  12645. try {
  12646. const res = await fetch(`${API_BASE}/dhcp-server/leases/${encodeURIComponent(id)}`, { method: 'DELETE' });
  12647. if (res.ok) {
  12648. showToast('Deleted', 'Static lease removed', 'success');
  12649. loadDHCPServer(false);
  12650. fetchData(false);
  12651. }
  12652. } catch (err) {
  12653. showToast('Error', err.message, 'error');
  12654. }
  12655. }
  12656. async function makeDHCPLeaseStatic(mac, ip, hostname, comment) {
  12657. try {
  12658. const res = await fetch(`${API_BASE}/dhcp-server/leases/make-static`, {
  12659. method: 'POST',
  12660. headers: { 'Content-Type': 'application/json' },
  12661. body: JSON.stringify({
  12662. mac_address: mac,
  12663. address: ip,
  12664. hostname,
  12665. comment: comment || 'Converted to static'
  12666. })
  12667. });
  12668. if (res.ok) {
  12669. showToast('Lease Made Static', `IP ${ip} permanently reserved for ${mac}`, 'success');
  12670. loadDHCPServer(false);
  12671. fetchData(false);
  12672. } else {
  12673. const err = await res.text();
  12674. showToast('Error', err, 'error');
  12675. }
  12676. } catch (err) {
  12677. showToast('Error', err.message, 'error');
  12678. }
  12679. }
  12680. // ==================== MODALS & ACTIONS: OPTIONS ====================
  12681. function openAddDHCPOptionModal() {
  12682. document.getElementById('dhcp-option-modal-title').innerText = 'Add DHCP Option';
  12683. document.getElementById('dhcp-option-modal-id').value = '';
  12684. document.getElementById('dhcp-option-modal-name').value = '';
  12685. document.getElementById('dhcp-option-modal-code').value = '';
  12686. document.getElementById('dhcp-option-modal-value').value = '';
  12687. document.getElementById('dhcp-option-modal-comment').value = '';
  12688. document.getElementById('dhcp-option-modal').classList.remove('hidden');
  12689. }
  12690. function openEditDHCPOptionModal(id) {
  12691. const o = (state.dhcpOptions || []).find(item => item.id === id);
  12692. if (!o) return;
  12693. document.getElementById('dhcp-option-modal-title').innerText = `Edit DHCP Option (${o.name})`;
  12694. document.getElementById('dhcp-option-modal-id').value = o.id;
  12695. document.getElementById('dhcp-option-modal-name').value = o.name;
  12696. document.getElementById('dhcp-option-modal-code').value = o.code;
  12697. document.getElementById('dhcp-option-modal-value').value = o.value;
  12698. document.getElementById('dhcp-option-modal-comment').value = o.comment || '';
  12699. document.getElementById('dhcp-option-modal').classList.remove('hidden');
  12700. }
  12701. function closeDHCPOptionModal() {
  12702. document.getElementById('dhcp-option-modal').classList.add('hidden');
  12703. }
  12704. async function submitSaveDHCPOption(e) {
  12705. e.preventDefault();
  12706. const id = document.getElementById('dhcp-option-modal-id').value;
  12707. const name = document.getElementById('dhcp-option-modal-name').value.trim();
  12708. const code = parseInt(document.getElementById('dhcp-option-modal-code').value);
  12709. const value = document.getElementById('dhcp-option-modal-value').value.trim();
  12710. const comment = document.getElementById('dhcp-option-modal-comment').value.trim();
  12711. try {
  12712. const res = await fetch(`${API_BASE}/dhcp-server/options`, {
  12713. method: 'POST',
  12714. headers: { 'Content-Type': 'application/json' },
  12715. body: JSON.stringify({ id, name, code, value, comment })
  12716. });
  12717. if (res.ok) {
  12718. showToast('Option Saved', `DHCP option ${name} (#${code}) configured`, 'success');
  12719. closeDHCPOptionModal();
  12720. loadDHCPServer(false);
  12721. fetchData(false);
  12722. } else {
  12723. const err = await res.text();
  12724. showToast('Error', err, 'error');
  12725. }
  12726. } catch (err) {
  12727. showToast('Error', err.message, 'error');
  12728. }
  12729. }
  12730. async function deleteDHCPOption(id, name) {
  12731. if (!confirm(`Are you sure you want to delete DHCP Option "${name}"?`)) return;
  12732. try {
  12733. const res = await fetch(`${API_BASE}/dhcp-server/options/${encodeURIComponent(id)}`, { method: 'DELETE' });
  12734. if (res.ok) {
  12735. showToast('Deleted', `Option ${name} removed`, 'success');
  12736. loadDHCPServer(false);
  12737. fetchData(false);
  12738. }
  12739. } catch (err) {
  12740. showToast('Error', err.message, 'error');
  12741. }
  12742. }
  12743. // ==================== WIZARD: DHCP SETUP (MikroTik style) ====================
  12744. function openDHCPServerSetupModal() {
  12745. populateDHCPIfaceSelect('dhcp-wizard-iface', '');
  12746. onDHCPWizardIfaceChange();
  12747. document.getElementById('dhcp-setup-wizard-modal').classList.remove('hidden');
  12748. }
  12749. function closeDHCPServerSetupModal() {
  12750. document.getElementById('dhcp-setup-wizard-modal').classList.add('hidden');
  12751. }
  12752. function onDHCPWizardIfaceChange() {
  12753. const ifaceName = document.getElementById('dhcp-wizard-iface').value;
  12754. const iface = (state.interfaces || []).find(i => i.name === ifaceName);
  12755. let ip = '192.168.88.1';
  12756. let prefix = '24';
  12757. if (iface && iface.ip_address) {
  12758. const parts = iface.ip_address.split('/');
  12759. ip = parts[0];
  12760. if (parts.length > 1) prefix = parts[1];
  12761. }
  12762. // Calculate subnet base (e.g. 192.168.88.0/24)
  12763. const ipParts = ip.split('.');
  12764. if (ipParts.length === 4) {
  12765. const baseSpace = `${ipParts[0]}.${ipParts[1]}.${ipParts[2]}.0/${prefix}`;
  12766. const pool = `${ipParts[0]}.${ipParts[1]}.${ipParts[2]}.10-${ipParts[0]}.${ipParts[1]}.${ipParts[2]}.254`;
  12767. document.getElementById('dhcp-wizard-space').value = baseSpace;
  12768. document.getElementById('dhcp-wizard-gateway').value = ip;
  12769. document.getElementById('dhcp-wizard-pool').value = pool;
  12770. document.getElementById('dhcp-wizard-dns').value = `${ip}, 1.1.1.1, 8.8.8.8`;
  12771. document.getElementById('dhcp-wizard-ntp').value = `${ip}`;
  12772. }
  12773. }
  12774. async function submitDHCPServerSetupWizard(e) {
  12775. e.preventDefault();
  12776. const iface = document.getElementById('dhcp-wizard-iface').value;
  12777. const space = document.getElementById('dhcp-wizard-space').value.trim();
  12778. const gw = document.getElementById('dhcp-wizard-gateway').value.trim();
  12779. const pool = document.getElementById('dhcp-wizard-pool').value.trim();
  12780. const dnsStr = document.getElementById('dhcp-wizard-dns').value.trim();
  12781. const leaseTime = document.getElementById('dhcp-wizard-leasetime').value.trim() || '12h';
  12782. const ntpStr = document.getElementById('dhcp-wizard-ntp').value.trim();
  12783. const tftp = document.getElementById('dhcp-wizard-tftp').value.trim();
  12784. const dnsServers = dnsStr ? dnsStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  12785. const ntpServers = ntpStr ? ntpStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  12786. try {
  12787. const res = await fetch(`${API_BASE}/dhcp-server/setup`, {
  12788. method: 'POST',
  12789. headers: { 'Content-Type': 'application/json' },
  12790. body: JSON.stringify({
  12791. interface: iface,
  12792. address_space: space,
  12793. gateway: gw,
  12794. address_pool: pool,
  12795. dns_servers: dnsServers,
  12796. lease_time: leaseTime,
  12797. ntp_servers: ntpServers,
  12798. next_server: tftp
  12799. })
  12800. });
  12801. if (res.ok) {
  12802. showToast('DHCP Setup Complete', `DHCP Server setup finished on ${iface}`, 'success');
  12803. closeDHCPServerSetupModal();
  12804. loadDHCPServer(false);
  12805. fetchData(false);
  12806. } else {
  12807. const err = await res.text();
  12808. showToast('Error', err, 'error');
  12809. }
  12810. } catch (err) {
  12811. showToast('Error', err.message, 'error');
  12812. }
  12813. }
  12814. function populateDHCPIfaceSelect(elemId, selectedVal) {
  12815. const sel = document.getElementById(elemId);
  12816. if (!sel) return;
  12817. sel.innerHTML = '<option value="">Select interface...</option>';
  12818. const ifaces = state.interfaces || [];
  12819. ifaces.forEach(i => {
  12820. if (i.name === 'lo') return;
  12821. const opt = document.createElement('option');
  12822. opt.value = i.name;
  12823. const ipStr = i.ip_address ? ` (${i.ip_address})` : '';
  12824. opt.textContent = `${i.name}${ipStr} [${i.role || i.type || 'interface'}]`;
  12825. if (i.name === selectedVal) opt.selected = true;
  12826. sel.appendChild(opt);
  12827. });
  12828. }
  12829. // ==================== UNIVERSAL TABLE ORDERING / SORTING (WINBOX / WEBFIG STYLE) ====================
  12830. function initTableSorting() {
  12831. document.querySelectorAll('table').forEach(setupSortableTable);
  12832. }
  12833. function setupSortableTable(table) {
  12834. const thead = table.querySelector('thead');
  12835. const tbody = table.querySelector('tbody');
  12836. if (!thead || !tbody) return;
  12837. const headerRows = thead.querySelectorAll('tr');
  12838. if (headerRows.length === 0) return;
  12839. const ths = headerRows[headerRows.length - 1].querySelectorAll('th');
  12840. ths.forEach((th, colIdx) => {
  12841. if (th._sortBound) return;
  12842. th._sortBound = true;
  12843. const rawText = th.innerText.trim().toLowerCase();
  12844. const isActionsCol = rawText === 'actions' || (rawText === 'action' && th.classList.contains('text-right'));
  12845. const isCheckboxCol = !!th.querySelector('input[type="checkbox"]');
  12846. const isExpandCol = (th.classList.contains('w-8') || th.classList.contains('w-6')) && !rawText;
  12847. const isExplicitNoSort = th.classList.contains('no-sort') || th.getAttribute('data-sortable') === 'false';
  12848. if (isActionsCol || isCheckboxCol || isExpandCol || isExplicitNoSort) {
  12849. return;
  12850. }
  12851. th.classList.add('table-sortable', 'group');
  12852. if (!th.title) th.title = 'Click to sort (Ascending / Descending / Default)';
  12853. let icon = th.querySelector('.table-sort-icon');
  12854. if (!icon) {
  12855. icon = document.createElement('span');
  12856. icon.className = 'table-sort-icon opacity-0 group-hover:opacity-50 text-slate-400';
  12857. icon.innerHTML = '⇅';
  12858. th.appendChild(icon);
  12859. }
  12860. th.addEventListener('click', (e) => {
  12861. if (e.target.tagName === 'INPUT' || e.target.tagName === 'BUTTON' || e.target.closest('button, input')) return;
  12862. handleHeaderClick(table, th, colIdx);
  12863. });
  12864. });
  12865. if (!tbody._sortObserved) {
  12866. tbody._sortObserved = true;
  12867. let sortDebounceTimer = null;
  12868. const observer = new MutationObserver((mutations) => {
  12869. if (tbody._isSorting) return;
  12870. const hasChildChanges = mutations.some(m => m.type === 'childList' && m.addedNodes.length > 0);
  12871. if (!hasChildChanges) return;
  12872. clearTimeout(sortDebounceTimer);
  12873. sortDebounceTimer = setTimeout(() => {
  12874. if (tbody._isSorting) return;
  12875. if (table._activeSort && table._activeSort.dir !== 'none') {
  12876. applyTableSort(table, table._activeSort.colIdx, table._activeSort.dir, false);
  12877. } else {
  12878. tagOriginalRowOrder(tbody);
  12879. }
  12880. }, 50);
  12881. });
  12882. tbody._sortObserver = observer;
  12883. observer.observe(tbody, { childList: true });
  12884. }
  12885. tagOriginalRowOrder(tbody);
  12886. }
  12887. function tagOriginalRowOrder(tbody) {
  12888. let idx = 0;
  12889. Array.from(tbody.children).forEach(tr => {
  12890. if (!tr.querySelector('td[colspan]')) {
  12891. if (!tr.hasAttribute('data-orig-idx')) {
  12892. tr.setAttribute('data-orig-idx', idx++);
  12893. }
  12894. }
  12895. });
  12896. }
  12897. function handleHeaderClick(table, th, colIdx) {
  12898. const currentSort = table._activeSort || { colIdx: -1, dir: 'none' };
  12899. let newDir = 'asc';
  12900. if (currentSort.colIdx === colIdx) {
  12901. if (currentSort.dir === 'asc') newDir = 'desc';
  12902. else if (currentSort.dir === 'desc') newDir = 'none';
  12903. else newDir = 'asc';
  12904. } else {
  12905. newDir = 'asc';
  12906. }
  12907. table._activeSort = { colIdx, dir: newDir };
  12908. updateHeaderIcons(table, colIdx, newDir);
  12909. applyTableSort(table, colIdx, newDir, true);
  12910. }
  12911. function updateHeaderIcons(table, activeColIdx, dir) {
  12912. const thead = table.querySelector('thead');
  12913. if (!thead) return;
  12914. const ths = thead.querySelectorAll('th');
  12915. ths.forEach((th, idx) => {
  12916. const icon = th.querySelector('.table-sort-icon');
  12917. if (!icon) return;
  12918. if (idx === activeColIdx && dir !== 'none') {
  12919. icon.innerHTML = dir === 'asc' ? '▲' : '▼';
  12920. icon.className = 'table-sort-icon text-cyan-400 font-bold opacity-100';
  12921. th.classList.add('table-sorted-active');
  12922. } else {
  12923. icon.innerHTML = '⇅';
  12924. icon.className = 'table-sort-icon opacity-0 group-hover:opacity-50 text-slate-400';
  12925. th.classList.remove('table-sorted-active');
  12926. }
  12927. });
  12928. }
  12929. function applyTableSort(table, colIdx, dir, userInitiated) {
  12930. const tbody = table.querySelector('tbody');
  12931. if (!tbody || tbody.children.length <= 1) return;
  12932. tbody._isSorting = true;
  12933. tagOriginalRowOrder(tbody);
  12934. // Group parent rows and any attached drawer/sub-rows
  12935. const groups = [];
  12936. let currentGroup = null;
  12937. Array.from(tbody.children).forEach(tr => {
  12938. if (tr.querySelector('td[colspan]')) {
  12939. if (currentGroup) {
  12940. currentGroup.subRows.push(tr);
  12941. } else {
  12942. groups.push({ mainRow: tr, subRows: [] });
  12943. }
  12944. } else {
  12945. currentGroup = { mainRow: tr, subRows: [] };
  12946. groups.push(currentGroup);
  12947. }
  12948. });
  12949. if (dir === 'none') {
  12950. groups.sort((a, b) => {
  12951. const idxA = parseInt(a.mainRow.getAttribute('data-orig-idx') || '0', 10);
  12952. const idxB = parseInt(b.mainRow.getAttribute('data-orig-idx') || '0', 10);
  12953. return idxA - idxB;
  12954. });
  12955. } else {
  12956. groups.sort((a, b) => {
  12957. const cellA = a.mainRow.children[colIdx];
  12958. const cellB = b.mainRow.children[colIdx];
  12959. const res = compareTableCells(cellA, cellB);
  12960. return dir === 'asc' ? res : -res;
  12961. });
  12962. }
  12963. // Check if rows are already in correct order to avoid modifying DOM
  12964. let alreadyOrdered = true;
  12965. let childIdx = 0;
  12966. for (const g of groups) {
  12967. if (tbody.children[childIdx] !== g.mainRow) {
  12968. alreadyOrdered = false;
  12969. break;
  12970. }
  12971. childIdx++;
  12972. for (const sub of g.subRows) {
  12973. if (tbody.children[childIdx] !== sub) {
  12974. alreadyOrdered = false;
  12975. break;
  12976. }
  12977. childIdx++;
  12978. }
  12979. }
  12980. if (alreadyOrdered) {
  12981. tbody._isSorting = false;
  12982. return;
  12983. }
  12984. // Disconnect observer while re-ordering to prevent recursion and thrashing
  12985. if (tbody._sortObserver) {
  12986. tbody._sortObserver.disconnect();
  12987. }
  12988. // Re-append rows in sorted order
  12989. groups.forEach(g => {
  12990. tbody.appendChild(g.mainRow);
  12991. g.subRows.forEach(sub => tbody.appendChild(sub));
  12992. });
  12993. // Drain any queued mutations and re-connect observer
  12994. if (tbody._sortObserver) {
  12995. tbody._sortObserver.takeRecords();
  12996. tbody._sortObserver.observe(tbody, { childList: true });
  12997. }
  12998. tbody._isSorting = false;
  12999. }
  13000. function getCellRawText(cell) {
  13001. if (!cell) return '';
  13002. if (cell.hasAttribute('data-sort-value')) return cell.getAttribute('data-sort-value');
  13003. const input = cell.querySelector('input, select');
  13004. if (input) {
  13005. if (input.type === 'checkbox') return input.checked ? '1' : '0';
  13006. return input.value;
  13007. }
  13008. return cell.innerText.trim();
  13009. }
  13010. function parseTrafficToNumber(str) {
  13011. const m = str.match(/^([\d.,]+)\s*([KMGTkmgt]?[iI]?[Bb](?:ps|\/s)?)/);
  13012. if (!m) return null;
  13013. const num = parseFloat(m[1].replace(/,/g, ''));
  13014. if (isNaN(num)) return null;
  13015. const unit = m[2].toUpperCase();
  13016. let mult = 1;
  13017. if (unit.startsWith('K')) mult = 1024;
  13018. else if (unit.startsWith('M')) mult = 1024 * 1024;
  13019. else if (unit.startsWith('G')) mult = 1024 * 1024 * 1024;
  13020. else if (unit.startsWith('T')) mult = 1024 * 1024 * 1024 * 1024;
  13021. return num * mult;
  13022. }
  13023. function parseIpToNumber(str) {
  13024. const clean = str.replace(/^[!~]/, '').trim();
  13025. const m = clean.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})(?:\/(\d{1,2}))?/);
  13026. if (!m) return null;
  13027. const o1 = parseInt(m[1], 10);
  13028. const o2 = parseInt(m[2], 10);
  13029. const o3 = parseInt(m[3], 10);
  13030. const o4 = parseInt(m[4], 10);
  13031. if (o1 > 255 || o2 > 255 || o3 > 255 || o4 > 255) return null;
  13032. return ((o1 * 256 + o2) * 256 + o3) * 256 + o4;
  13033. }
  13034. function parseCompoundPackets(str) {
  13035. const m = str.match(/^([\d,]+)p/);
  13036. if (!m) return null;
  13037. return parseInt(m[1].replace(/,/g, ''), 10);
  13038. }
  13039. function compareTableCells(cellA, cellB) {
  13040. const a = getCellRawText(cellA);
  13041. const b = getCellRawText(cellB);
  13042. if (a === '' && b !== '') return 1;
  13043. if (b === '' && a !== '') return -1;
  13044. if (a === b) return 0;
  13045. // 1. IP Addresses / CIDR
  13046. const ipA = parseIpToNumber(a);
  13047. const ipB = parseIpToNumber(b);
  13048. if (ipA !== null && ipB !== null) return ipA - ipB;
  13049. // 2. Packet counts (e.g. "1,250p / 45 KB")
  13050. const pktA = parseCompoundPackets(a);
  13051. const pktB = parseCompoundPackets(b);
  13052. if (pktA !== null && pktB !== null) return pktA - pktB;
  13053. // 3. Traffic / Throughput / Bytes (e.g. "1.2 MB", "500 KiB", "10 Gbps")
  13054. const trafA = parseTrafficToNumber(a);
  13055. const trafB = parseTrafficToNumber(b);
  13056. if (trafA !== null && trafB !== null) return trafA - trafB;
  13057. // 4. Numbers with '#' or formatted with commas (e.g. "#1", "24", "1,200")
  13058. const cleanNumA = a.replace(/^[#\s]+/, '').replace(/,/g, '').trim();
  13059. const cleanNumB = b.replace(/^[#\s]+/, '').replace(/,/g, '').trim();
  13060. const numA = Number(cleanNumA);
  13061. const numB = Number(cleanNumB);
  13062. if (!isNaN(numA) && !isNaN(numB) && cleanNumA !== '' && cleanNumB !== '') {
  13063. return numA - numB;
  13064. }
  13065. // 5. Natural case-insensitive string compare
  13066. return a.localeCompare(b, undefined, { numeric: true, sensitivity: 'base' });
  13067. }
  13068. // ==================== VRRP HIGH AVAILABILITY CONTROLLER ====================
  13069. async function loadVRRP(showToastNotification = false) {
  13070. try {
  13071. const [instRes, sumRes] = await Promise.all([
  13072. fetch(`${API_BASE}/vrrp/instances`),
  13073. fetch(`${API_BASE}/vrrp/summary`)
  13074. ]);
  13075. if (instRes.ok) {
  13076. state.vrrpInstances = await instRes.json();
  13077. renderVRRP();
  13078. }
  13079. if (sumRes.ok) {
  13080. state.vrrpSummary = await sumRes.json();
  13081. renderVRRPSummary();
  13082. }
  13083. if (showToastNotification) {
  13084. showToast('Refreshed', 'VRRP telemetry refreshed', 'info');
  13085. }
  13086. } catch (err) {
  13087. console.error('Failed to load VRRP:', err);
  13088. }
  13089. }
  13090. function renderVRRPSummary() {
  13091. const s = state.vrrpSummary || { total_instances: 0, master_instances: 0, backup_instances: 0 };
  13092. const elTotal = document.getElementById('vrrp-stat-total');
  13093. if (elTotal) elTotal.innerText = s.total_instances || 0;
  13094. const elMaster = document.getElementById('vrrp-stat-master');
  13095. if (elMaster) elMaster.innerText = s.master_instances || 0;
  13096. const elBackup = document.getElementById('vrrp-stat-backup');
  13097. if (elBackup) elBackup.innerText = s.backup_instances || 0;
  13098. const bCount = document.getElementById('badge-vrrp-count');
  13099. if (bCount) bCount.innerText = s.total_instances || 0;
  13100. const dot = document.getElementById('badge-vrrp-dot');
  13101. if (dot) {
  13102. if (s.master_instances > 0) {
  13103. dot.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  13104. } else if (s.backup_instances > 0) {
  13105. dot.className = 'w-2 h-2 rounded-full bg-sky-400';
  13106. } else {
  13107. dot.className = 'w-2 h-2 rounded-full bg-slate-600';
  13108. }
  13109. }
  13110. }
  13111. function renderVRRP() {
  13112. const tbody = document.getElementById('vrrp-table-tbody');
  13113. const empty = document.getElementById('vrrp-table-empty');
  13114. if (!tbody) return;
  13115. tbody.innerHTML = '';
  13116. const instances = state.vrrpInstances || [];
  13117. if (instances.length === 0) {
  13118. empty?.classList.remove('hidden');
  13119. return;
  13120. }
  13121. empty?.classList.add('hidden');
  13122. instances.forEach(inst => {
  13123. const tr = document.createElement('tr');
  13124. tr.className = `hover:bg-slate-800/40 transition text-xs ${inst.disabled ? 'opacity-50' : ''}`;
  13125. // Render Flag: M (Master), B (Backup), F (Fault), X (Disabled)
  13126. let flagHtml = `<span class="inline-flex items-center justify-center w-5 h-5 rounded-md font-mono font-bold text-[11px] bg-slate-800 text-slate-500 border border-slate-700">-</span>`;
  13127. if (inst.disabled) {
  13128. flagHtml = `<span class="inline-flex items-center justify-center w-5 h-5 rounded-md font-mono font-bold text-[11px] bg-rose-500/20 text-rose-400 border border-rose-500/40 shadow-sm" title="Disabled">X</span>`;
  13129. } else if (inst.state === 'MASTER') {
  13130. flagHtml = `<span class="inline-flex items-center justify-center w-5 h-5 rounded-md font-mono font-bold text-[11px] bg-emerald-500/20 text-emerald-400 border border-emerald-500/40 shadow-sm" title="Master (Holding VIP)">M</span>`;
  13131. } else if (inst.state === 'BACKUP') {
  13132. flagHtml = `<span class="inline-flex items-center justify-center w-5 h-5 rounded-md font-mono font-bold text-[11px] bg-sky-500/20 text-sky-400 border border-sky-500/40 shadow-sm" title="Backup (Standby)">B</span>`;
  13133. } else if (inst.state === 'FAULT') {
  13134. flagHtml = `<span class="inline-flex items-center justify-center w-5 h-5 rounded-md font-mono font-bold text-[11px] bg-amber-500/20 text-amber-400 border border-amber-500/40 shadow-sm" title="Fault (Interface Down)">F</span>`;
  13135. }
  13136. // Render State Badge
  13137. let stateBadge = `<span class="px-2 py-0.5 rounded text-[10px] bg-slate-800 text-slate-400 border border-slate-700">DISABLED</span>`;
  13138. if (!inst.disabled) {
  13139. if (inst.state === 'MASTER') {
  13140. stateBadge = `<span class="px-2 py-0.5 rounded text-[10px] bg-emerald-500/20 text-emerald-300 border border-emerald-500/40 font-bold inline-flex items-center gap-1.5"><span class="w-1.5 h-1.5 rounded-full bg-emerald-400 animate-pulse"></span>MASTER</span>`;
  13141. } else if (inst.state === 'BACKUP') {
  13142. stateBadge = `<span class="px-2 py-0.5 rounded text-[10px] bg-sky-500/20 text-sky-300 border border-sky-500/40 font-bold inline-flex items-center gap-1.5"><span class="w-1.5 h-1.5 rounded-full bg-sky-400"></span>BACKUP</span>`;
  13143. } else if (inst.state === 'FAULT') {
  13144. stateBadge = `<span class="px-2 py-0.5 rounded text-[10px] bg-amber-500/20 text-amber-300 border border-amber-500/40 font-bold inline-flex items-center gap-1.5"><span class="w-1.5 h-1.5 rounded-full bg-amber-400"></span>FAULT</span>`;
  13145. }
  13146. }
  13147. const vipsStr = (inst.virtual_ips || []).join(', ') || '-';
  13148. tr.innerHTML = `
  13149. <td class="py-2.5 px-3 text-center">${flagHtml}</td>
  13150. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(inst.name)}</td>
  13151. <td class="py-2.5 px-3 font-mono text-cyan-400 font-semibold">${escapeHtml(inst.interface)}</td>
  13152. <td class="py-2.5 px-3 font-mono font-bold text-center text-white">${inst.vrid}</td>
  13153. <td class="py-2.5 px-3 font-mono text-center text-slate-300 font-semibold">${inst.priority}</td>
  13154. <td class="py-2.5 px-3 font-mono text-emerald-400 font-bold"><span class="px-2 py-0.5 rounded bg-emerald-500/10 border border-emerald-500/20">${escapeHtml(vipsStr)}</span></td>
  13155. <td class="py-2.5 px-3 font-mono text-center text-slate-300">${inst.preempt ? '<span class="text-emerald-400 font-semibold">yes</span>' : '<span class="text-slate-500">no</span>'}</td>
  13156. <td class="py-2.5 px-3 font-mono text-slate-400 text-[11px]">${escapeHtml(inst.virtual_mac || '-')}</td>
  13157. <td class="py-2.5 px-3 text-center">${stateBadge}</td>
  13158. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]" title="${escapeHtml(inst.comment || '')}">${escapeHtml(inst.comment || '-')}</td>
  13159. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  13160. <button onclick="toggleVRRPState('${inst.id}', ${!inst.disabled})" class="text-xs ${inst.disabled ? 'text-emerald-400' : 'text-slate-400'} hover:underline">${inst.disabled ? 'Enable' : 'Disable'}</button>
  13161. <button onclick="openEditVRRPModal('${inst.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  13162. <button onclick="deleteVRRP('${inst.id}', '${escapeHtml(inst.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  13163. </td>
  13164. `;
  13165. tbody.appendChild(tr);
  13166. });
  13167. }
  13168. function populateVRRPIfaceSelect(elemId, selectedIface) {
  13169. const sel = document.getElementById(elemId);
  13170. if (!sel) return;
  13171. sel.innerHTML = '<option value="">Select interface...</option>';
  13172. const ifaces = state.interfaces || [];
  13173. ifaces.forEach(i => {
  13174. const opt = document.createElement('option');
  13175. opt.value = i.name;
  13176. opt.innerText = `${i.name} (${i.type || 'net'}${i.ip ? ' - ' + i.ip : ''})`;
  13177. if (selectedIface && selectedIface === i.name) opt.selected = true;
  13178. sel.appendChild(opt);
  13179. });
  13180. }
  13181. function openAddVRRPModal() {
  13182. document.getElementById('modal-vrrp-title').innerText = 'Add VRRP Instance';
  13183. document.getElementById('modal-vrrp-id').value = '';
  13184. document.getElementById('modal-vrrp-name').value = `vrrp${(state.vrrpInstances || []).length + 1}`;
  13185. document.getElementById('modal-vrrp-vrid').value = 10 + (state.vrrpInstances || []).length;
  13186. document.getElementById('modal-vrrp-priority').value = 100;
  13187. document.getElementById('modal-vrrp-vip').value = '192.168.88.254/24';
  13188. document.getElementById('modal-vrrp-version').value = '3';
  13189. document.getElementById('modal-vrrp-interval').value = 1;
  13190. document.getElementById('modal-vrrp-authtype').value = 'none';
  13191. document.getElementById('modal-vrrp-authpass').value = '';
  13192. document.getElementById('modal-vrrp-comment').value = '';
  13193. document.getElementById('modal-vrrp-preempt').checked = true;
  13194. document.getElementById('modal-vrrp-disabled').checked = false;
  13195. populateVRRPIfaceSelect('modal-vrrp-iface', '');
  13196. document.getElementById('modal-vrrp-instance').classList.remove('hidden');
  13197. }
  13198. function openEditVRRPModal(id) {
  13199. const inst = (state.vrrpInstances || []).find(item => item.id === id);
  13200. if (!inst) return;
  13201. document.getElementById('modal-vrrp-title').innerText = `Edit VRRP Instance (${inst.name})`;
  13202. document.getElementById('modal-vrrp-id').value = inst.id;
  13203. document.getElementById('modal-vrrp-name').value = inst.name;
  13204. document.getElementById('modal-vrrp-vrid').value = inst.vrid;
  13205. document.getElementById('modal-vrrp-priority').value = inst.priority;
  13206. document.getElementById('modal-vrrp-vip').value = (inst.virtual_ips || []).join(', ');
  13207. document.getElementById('modal-vrrp-version').value = String(inst.version || 3);
  13208. document.getElementById('modal-vrrp-interval').value = inst.interval || 1;
  13209. document.getElementById('modal-vrrp-authtype').value = inst.auth_type || 'none';
  13210. document.getElementById('modal-vrrp-authpass').value = inst.auth_password || '';
  13211. document.getElementById('modal-vrrp-comment').value = inst.comment || '';
  13212. document.getElementById('modal-vrrp-preempt').checked = inst.preempt !== false;
  13213. document.getElementById('modal-vrrp-disabled').checked = !!inst.disabled;
  13214. populateVRRPIfaceSelect('modal-vrrp-iface', inst.interface);
  13215. document.getElementById('modal-vrrp-instance').classList.remove('hidden');
  13216. }
  13217. function closeVRRPModal() {
  13218. document.getElementById('modal-vrrp-instance').classList.add('hidden');
  13219. }
  13220. async function submitSaveVRRP(e) {
  13221. e.preventDefault();
  13222. const id = document.getElementById('modal-vrrp-id').value;
  13223. const name = document.getElementById('modal-vrrp-name').value.trim();
  13224. const iface = document.getElementById('modal-vrrp-iface').value;
  13225. const vrid = parseInt(document.getElementById('modal-vrrp-vrid').value, 10) || 1;
  13226. const priority = parseInt(document.getElementById('modal-vrrp-priority').value, 10) || 100;
  13227. const vipRaw = document.getElementById('modal-vrrp-vip').value.trim();
  13228. const version = parseInt(document.getElementById('modal-vrrp-version').value, 10) || 3;
  13229. const interval = parseInt(document.getElementById('modal-vrrp-interval').value, 10) || 1;
  13230. const authType = document.getElementById('modal-vrrp-authtype').value;
  13231. const authPass = document.getElementById('modal-vrrp-authpass').value.trim();
  13232. const comment = document.getElementById('modal-vrrp-comment').value.trim();
  13233. const preempt = document.getElementById('modal-vrrp-preempt').checked;
  13234. const disabled = document.getElementById('modal-vrrp-disabled').checked;
  13235. const vips = vipRaw.split(',').map(s => s.trim()).filter(Boolean);
  13236. try {
  13237. const res = await fetch(`${API_BASE}/vrrp/instances`, {
  13238. method: 'POST',
  13239. headers: { 'Content-Type': 'application/json' },
  13240. body: JSON.stringify({
  13241. id,
  13242. name,
  13243. interface: iface,
  13244. vrid,
  13245. priority,
  13246. virtual_ips: vips,
  13247. version,
  13248. interval,
  13249. auth_type: authType,
  13250. auth_password: authPass,
  13251. comment,
  13252. preempt,
  13253. disabled
  13254. })
  13255. });
  13256. if (res.ok) {
  13257. showToast('VRRP Saved', `VRRP instance ${name} configured`, 'success');
  13258. closeVRRPModal();
  13259. loadVRRP(false);
  13260. fetchData(false);
  13261. } else {
  13262. const err = await res.text();
  13263. showToast('Error', err, 'error');
  13264. }
  13265. } catch (err) {
  13266. showToast('Error', err.message, 'error');
  13267. }
  13268. }
  13269. async function deleteVRRP(id, name) {
  13270. if (!confirm(`Delete VRRP instance "${name}"?`)) return;
  13271. try {
  13272. const res = await fetch(`${API_BASE}/vrrp/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  13273. if (res.ok) {
  13274. showToast('Deleted', `VRRP instance ${name} removed`, 'info');
  13275. loadVRRP(false);
  13276. fetchData(false);
  13277. } else {
  13278. const err = await res.text();
  13279. showToast('Error', err, 'error');
  13280. }
  13281. } catch (err) {
  13282. showToast('Error', err.message, 'error');
  13283. }
  13284. }
  13285. async function toggleVRRPState(id, disabled) {
  13286. try {
  13287. const res = await fetch(`${API_BASE}/vrrp/instances/${encodeURIComponent(id)}/state`, {
  13288. method: 'POST',
  13289. headers: { 'Content-Type': 'application/json' },
  13290. body: JSON.stringify({ disabled })
  13291. });
  13292. if (res.ok) {
  13293. showToast('State Updated', disabled ? 'VRRP disabled' : 'VRRP enabled', 'info');
  13294. loadVRRP(false);
  13295. fetchData(false);
  13296. } else {
  13297. const err = await res.text();
  13298. showToast('Error', err, 'error');
  13299. }
  13300. } catch (err) {
  13301. showToast('Error', err.message, 'error');
  13302. }
  13303. }
  13304. // Global observer for dynamically injected tables (e.g. inside modals or drawers)
  13305. if (typeof MutationObserver !== 'undefined' && typeof document !== 'undefined') {
  13306. let docSortDebounce = null;
  13307. const docTableObserver = new MutationObserver((mutations) => {
  13308. let needsInit = false;
  13309. for (const m of mutations) {
  13310. for (const node of m.addedNodes) {
  13311. if (node.nodeType === 1) {
  13312. if (node.tagName === 'TABLE' && !node.closest('tbody, thead')) {
  13313. needsInit = true;
  13314. break;
  13315. } else if (node.querySelector && !node.closest('table') && node.querySelector('table')) {
  13316. needsInit = true;
  13317. break;
  13318. }
  13319. }
  13320. }
  13321. if (needsInit) break;
  13322. }
  13323. if (needsInit) {
  13324. clearTimeout(docSortDebounce);
  13325. docSortDebounce = setTimeout(initTableSorting, 100);
  13326. }
  13327. });
  13328. docTableObserver.observe(document.body || document.documentElement, { childList: true, subtree: true });
  13329. }
  13330. // =========================================================================
  13331. // BANDWIDTH TEST (BwTest) BENCHMARK ENGINE
  13332. // =========================================================================
  13333. const bwtestState = {
  13334. running: false,
  13335. pollTimer: null,
  13336. eventSource: null,
  13337. chartPoints: [],
  13338. maxChartPoints: 60,
  13339. serverConfig: null,
  13340. peakTx: 0,
  13341. peakRx: 0,
  13342. targetDuration: 10,
  13343. lastSampleIndex: 0
  13344. };
  13345. async function loadBwTestView() {
  13346. fetchBwTestServerStatus();
  13347. loadBwTestHistory();
  13348. resizeBwTestCanvas();
  13349. checkActiveBwTest();
  13350. }
  13351. async function fetchBwTestServerStatus() {
  13352. try {
  13353. const res = await fetch(`${API_BASE}/tools/bwtest/server`);
  13354. if (!res.ok) return;
  13355. const s = await res.json();
  13356. bwtestState.serverConfig = s;
  13357. // Update indicator and badges
  13358. const indicator = document.getElementById('bwtest-server-indicator');
  13359. const badge = document.getElementById('bwtest-server-badge');
  13360. const sideBadge = document.getElementById('badge-bwtest-server');
  13361. if (s.enabled && s.running) {
  13362. if (indicator) indicator.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  13363. if (badge) {
  13364. badge.innerText = `Port ${s.port} (Active)`;
  13365. badge.className = 'text-emerald-400 font-bold';
  13366. }
  13367. if (sideBadge) {
  13368. sideBadge.innerText = s.port;
  13369. sideBadge.className = 'text-[10px] bg-emerald-950 text-emerald-300 border border-emerald-800/40 px-1.5 py-0.2 rounded-full font-mono';
  13370. }
  13371. } else {
  13372. if (indicator) indicator.className = 'w-2 h-2 rounded-full bg-slate-600';
  13373. if (badge) {
  13374. badge.innerText = `Disabled`;
  13375. badge.className = 'text-slate-500 font-bold';
  13376. }
  13377. if (sideBadge) {
  13378. sideBadge.innerText = 'Off';
  13379. sideBadge.className = 'text-[10px] bg-slate-800 text-slate-500 border border-slate-700 px-1.5 py-0.2 rounded-full font-mono';
  13380. }
  13381. }
  13382. // Modal fields
  13383. const toggle = document.getElementById('bwtest-server-enable-toggle');
  13384. if (toggle) toggle.checked = !!s.enabled;
  13385. const portInp = document.getElementById('bwtest-server-port-input');
  13386. if (portInp) portInp.value = s.port || 2000;
  13387. const actSess = document.getElementById('bwtest-modal-active-sessions');
  13388. if (actSess) actSess.innerText = s.active_sessions || 0;
  13389. const totServ = document.getElementById('bwtest-modal-total-served');
  13390. if (totServ) totServ.innerText = s.total_sessions_served || 0;
  13391. const totBytes = document.getElementById('bwtest-modal-total-bytes');
  13392. if (totBytes) totBytes.innerText = formatBytes(s.total_bytes_processed || 0);
  13393. } catch (err) {
  13394. console.error('Failed to fetch BwTest server status:', err);
  13395. }
  13396. }
  13397. function openBwTestServerModal() {
  13398. fetchBwTestServerStatus();
  13399. document.getElementById('modal-bwtest-server')?.classList.remove('hidden');
  13400. }
  13401. function closeBwTestServerModal() {
  13402. document.getElementById('modal-bwtest-server')?.classList.add('hidden');
  13403. }
  13404. async function submitBwTestServerSettings(e) {
  13405. e.preventDefault();
  13406. const enabled = document.getElementById('bwtest-server-enable-toggle').checked;
  13407. const port = parseInt(document.getElementById('bwtest-server-port-input').value, 10) || 2000;
  13408. try {
  13409. const res = await fetch(`${API_BASE}/tools/bwtest/server`, {
  13410. method: 'POST',
  13411. headers: { 'Content-Type': 'application/json' },
  13412. body: JSON.stringify({ enabled, port, listen_addr: '0.0.0.0', allow_anonymous: true })
  13413. });
  13414. if (!res.ok) {
  13415. const err = await res.json();
  13416. throw new Error(err.error || 'Failed to update server configuration');
  13417. }
  13418. showToast('BwTest Server', `Bandwidth Test server updated (Port ${port})`, 'success');
  13419. closeBwTestServerModal();
  13420. fetchBwTestServerStatus();
  13421. } catch (err) {
  13422. showToast('Server Configuration Error', err.message, 'error');
  13423. }
  13424. }
  13425. function setBwTestTarget(target) {
  13426. const inp = document.getElementById('bwtest-input-target');
  13427. if (inp) inp.value = target;
  13428. }
  13429. function setBwTestProtocol(proto) {
  13430. const hiddenInp = document.getElementById('bwtest-input-protocol');
  13431. if (hiddenInp) hiddenInp.value = proto;
  13432. const btnUdp = document.getElementById('bwtest-proto-udp');
  13433. const btnTcp = document.getElementById('bwtest-proto-tcp');
  13434. const badge = document.getElementById('bwtest-proto-badge');
  13435. const pktField = document.getElementById('bwtest-field-pktsize');
  13436. const activeUdpCls = 'py-2.5 px-3 rounded-lg text-xs font-bold border transition text-center bg-emerald-600/20 border-emerald-500/50 text-emerald-300 shadow-sm flex items-center justify-center gap-2';
  13437. const activeTcpCls = 'py-2.5 px-3 rounded-lg text-xs font-bold border transition text-center bg-blue-600/20 border-blue-500/50 text-blue-300 shadow-sm flex items-center justify-center gap-2';
  13438. const inactiveCls = 'py-2.5 px-3 rounded-lg text-xs font-medium border border-slate-800 bg-slate-950 text-slate-400 hover:text-white transition text-center flex items-center justify-center gap-2';
  13439. if (proto === 'udp') {
  13440. if (btnUdp) {
  13441. btnUdp.className = activeUdpCls;
  13442. const dot = btnUdp.querySelector('span');
  13443. if (dot) dot.className = 'w-2 h-2 rounded-full bg-emerald-400';
  13444. }
  13445. if (btnTcp) {
  13446. btnTcp.className = inactiveCls;
  13447. const dot = btnTcp.querySelector('span');
  13448. if (dot) dot.className = 'w-2 h-2 rounded-full bg-slate-600';
  13449. }
  13450. if (badge) {
  13451. badge.innerText = 'UDP Mode (RFC 3550 Jitter + Loss %)';
  13452. badge.className = 'text-[10px] font-mono text-emerald-400 bg-emerald-500/10 px-2 py-0.5 rounded border border-emerald-500/20';
  13453. }
  13454. if (pktField) pktField.classList.remove('opacity-40');
  13455. } else {
  13456. if (btnUdp) {
  13457. btnUdp.className = inactiveCls;
  13458. const dot = btnUdp.querySelector('span');
  13459. if (dot) dot.className = 'w-2 h-2 rounded-full bg-slate-600';
  13460. }
  13461. if (btnTcp) {
  13462. btnTcp.className = activeTcpCls;
  13463. const dot = btnTcp.querySelector('span');
  13464. if (dot) dot.className = 'w-2 h-2 rounded-full bg-blue-400';
  13465. }
  13466. if (badge) {
  13467. badge.innerText = 'TCP Mode (Sliding Window Throughput)';
  13468. badge.className = 'text-[10px] font-mono text-blue-400 bg-blue-500/10 px-2 py-0.5 rounded border border-blue-500/20';
  13469. }
  13470. if (pktField) pktField.classList.add('opacity-40');
  13471. }
  13472. }
  13473. function setBwTestDirection(dir) {
  13474. const hiddenInp = document.getElementById('bwtest-input-direction');
  13475. if (hiddenInp) hiddenInp.value = dir;
  13476. const btnBoth = document.getElementById('bwtest-dir-both');
  13477. const btnTx = document.getElementById('bwtest-dir-tx');
  13478. const btnRx = document.getElementById('bwtest-dir-rx');
  13479. const activeCls = 'py-2 px-2 rounded-lg text-xs font-bold border transition text-center bg-emerald-600/20 border-emerald-500/50 text-emerald-300 shadow-sm';
  13480. const inactiveCls = 'py-2 px-2 rounded-lg text-xs font-medium border border-slate-800 bg-slate-950 text-slate-400 hover:text-white transition text-center';
  13481. if (btnBoth) btnBoth.className = dir === 'both' ? activeCls : inactiveCls;
  13482. if (btnTx) btnTx.className = dir === 'tx' ? activeCls : inactiveCls;
  13483. if (btnRx) btnRx.className = dir === 'rx' ? activeCls : inactiveCls;
  13484. }
  13485. function setBwTestLimit(bps) {
  13486. const sel = document.getElementById('bwtest-input-limit');
  13487. if (sel) sel.value = String(bps);
  13488. }
  13489. async function checkActiveBwTest() {
  13490. try {
  13491. const res = await fetch(`${API_BASE}/tools/bwtest/status`);
  13492. if (!res.ok) return;
  13493. const st = await res.json();
  13494. if (st.running) {
  13495. setBwTestRunningUI(true);
  13496. if (st.current_sample) handleBwTestSample(st.current_sample);
  13497. startBwTestTelemetry();
  13498. }
  13499. } catch (err) {
  13500. console.error('Failed to check active BwTest:', err);
  13501. }
  13502. }
  13503. async function startBwTest(e) {
  13504. if (e && e.preventDefault) e.preventDefault();
  13505. const target = document.getElementById('bwtest-input-target').value.trim() || '127.0.0.1';
  13506. const port = parseInt(document.getElementById('bwtest-input-port').value, 10) || 2000;
  13507. const direction = document.getElementById('bwtest-input-direction').value || 'both';
  13508. const protocol = document.getElementById('bwtest-input-protocol').value || 'udp';
  13509. const bandwidth_limit = parseInt(document.getElementById('bwtest-input-limit').value, 10) || 0;
  13510. const packet_size = parseInt(document.getElementById('bwtest-input-pktsize').value, 10) || 1472;
  13511. const streams = parseInt(document.getElementById('bwtest-input-streams').value, 10) || 1;
  13512. const duration = parseInt(document.getElementById('bwtest-input-duration').value, 10);
  13513. bwtestState.targetDuration = duration;
  13514. bwtestState.chartPoints = [];
  13515. bwtestState.peakTx = 0;
  13516. bwtestState.peakRx = 0;
  13517. bwtestState.lastSampleIndex = 0;
  13518. // Clear UI elements
  13519. document.getElementById('bwtest-stat-tx-mbps').innerText = '0.00';
  13520. document.getElementById('bwtest-stat-tx-peak').innerText = '0.00 Mbps';
  13521. document.getElementById('bwtest-stat-tx-pkts').innerText = '0';
  13522. document.getElementById('bwtest-stat-rx-mbps').innerText = '0.00';
  13523. document.getElementById('bwtest-stat-rx-peak').innerText = '0.00 Mbps';
  13524. document.getElementById('bwtest-stat-rx-pkts').innerText = '0';
  13525. document.getElementById('bwtest-stat-loss').innerText = '0.0%';
  13526. document.getElementById('bwtest-stat-jitter').innerText = '0.00 ms';
  13527. document.getElementById('bwtest-stat-time').innerText = '0.0s';
  13528. document.getElementById('bwtest-stat-data').innerText = '0.0 MB';
  13529. document.getElementById('bwtest-stat-target-dur').innerText = duration > 0 ? `/ ${duration}s` : '/ ∞';
  13530. const tbody = document.getElementById('bwtest-samples-tbody');
  13531. if (tbody) tbody.innerHTML = '';
  13532. document.getElementById('bwtest-sample-count').innerText = '0 samples';
  13533. setBwTestRunningUI(true);
  13534. try {
  13535. const res = await fetch(`${API_BASE}/tools/bwtest/start`, {
  13536. method: 'POST',
  13537. headers: { 'Content-Type': 'application/json' },
  13538. body: JSON.stringify({
  13539. target,
  13540. port,
  13541. direction,
  13542. protocol,
  13543. bandwidth_limit,
  13544. packet_size,
  13545. streams,
  13546. duration
  13547. })
  13548. });
  13549. if (!res.ok) {
  13550. const err = await res.json();
  13551. throw new Error(err.error || 'Failed to start bandwidth test');
  13552. }
  13553. showToast('Benchmark Started', `Target: ${target}:${port} (${direction.toUpperCase()}, ${protocol.toUpperCase()})`, 'info');
  13554. startBwTestTelemetry();
  13555. } catch (err) {
  13556. setBwTestRunningUI(false);
  13557. showToast('Start Failed', err.message, 'error');
  13558. }
  13559. }
  13560. function setBwTestRunningUI(running) {
  13561. bwtestState.running = running;
  13562. const startBtn = document.getElementById('bwtest-btn-start');
  13563. const stopBtn = document.getElementById('bwtest-btn-stop');
  13564. const badge = document.getElementById('bwtest-run-status-badge');
  13565. const ph = document.getElementById('bwtest-chart-placeholder');
  13566. if (running) {
  13567. if (startBtn) {
  13568. startBtn.disabled = true;
  13569. startBtn.classList.add('opacity-50', 'cursor-not-allowed');
  13570. }
  13571. if (stopBtn) {
  13572. stopBtn.disabled = false;
  13573. stopBtn.classList.remove('opacity-40');
  13574. }
  13575. if (badge) {
  13576. badge.innerText = 'TESTING...';
  13577. badge.className = 'px-2 py-0.5 rounded text-[10px] font-mono bg-emerald-500/20 text-emerald-300 border border-emerald-500/40 font-bold animate-pulse';
  13578. }
  13579. if (ph) ph.style.display = 'none';
  13580. } else {
  13581. if (startBtn) {
  13582. startBtn.disabled = false;
  13583. startBtn.classList.remove('opacity-50', 'cursor-not-allowed');
  13584. }
  13585. if (stopBtn) {
  13586. stopBtn.disabled = true;
  13587. stopBtn.classList.add('opacity-40');
  13588. }
  13589. if (badge) {
  13590. badge.innerText = 'IDLE';
  13591. badge.className = 'px-2 py-0.5 rounded text-[10px] font-mono bg-slate-800 text-slate-400 border border-slate-700 font-semibold';
  13592. }
  13593. }
  13594. }
  13595. async function stopBwTest() {
  13596. try {
  13597. await fetch(`${API_BASE}/tools/bwtest/stop`, { method: 'POST' });
  13598. showToast('Test Stopped', 'Bandwidth test terminated by user', 'info');
  13599. } catch (err) {
  13600. console.error('Failed to stop test:', err);
  13601. }
  13602. }
  13603. function startBwTestTelemetry() {
  13604. if (bwtestState.pollTimer) clearInterval(bwtestState.pollTimer);
  13605. bwtestState.pollTimer = setInterval(async () => {
  13606. try {
  13607. const res = await fetch(`${API_BASE}/tools/bwtest/status`);
  13608. if (!res.ok) return;
  13609. const st = await res.json();
  13610. if (st.recent_samples && st.recent_samples.length > 0) {
  13611. // Process new samples
  13612. const newSamples = st.recent_samples.slice(bwtestState.lastSampleIndex);
  13613. newSamples.forEach(s => handleBwTestSample(s));
  13614. bwtestState.lastSampleIndex = st.recent_samples.length;
  13615. }
  13616. if (!st.running) {
  13617. clearInterval(bwtestState.pollTimer);
  13618. bwtestState.pollTimer = null;
  13619. setBwTestRunningUI(false);
  13620. handleBwTestFinish(st.summary, st.error);
  13621. }
  13622. } catch (err) {
  13623. console.error('BwTest polling error:', err);
  13624. }
  13625. }, 400);
  13626. }
  13627. function handleBwTestSample(s) {
  13628. if (!s) return;
  13629. const txMbps = s.tx_mbps || 0;
  13630. const rxMbps = s.rx_mbps || 0;
  13631. if (txMbps > bwtestState.peakTx) bwtestState.peakTx = txMbps;
  13632. if (rxMbps > bwtestState.peakRx) bwtestState.peakRx = rxMbps;
  13633. // KPI updates
  13634. const elTx = document.getElementById('bwtest-stat-tx-mbps');
  13635. if (elTx) elTx.innerText = txMbps.toFixed(2);
  13636. const elTxPeak = document.getElementById('bwtest-stat-tx-peak');
  13637. if (elTxPeak) elTxPeak.innerText = `${bwtestState.peakTx.toFixed(2)} Mbps`;
  13638. const elTxPkts = document.getElementById('bwtest-stat-tx-pkts');
  13639. if (elTxPkts) elTxPkts.innerText = s.tx_packets || 0;
  13640. const elRx = document.getElementById('bwtest-stat-rx-mbps');
  13641. if (elRx) elRx.innerText = rxMbps.toFixed(2);
  13642. const elRxPeak = document.getElementById('bwtest-stat-rx-peak');
  13643. if (elRxPeak) elRxPeak.innerText = `${bwtestState.peakRx.toFixed(2)} Mbps`;
  13644. const elRxPkts = document.getElementById('bwtest-stat-rx-pkts');
  13645. if (elRxPkts) elRxPkts.innerText = s.rx_packets || 0;
  13646. const elLoss = document.getElementById('bwtest-stat-loss');
  13647. if (elLoss) {
  13648. elLoss.innerText = `${(s.loss_pct || 0).toFixed(1)}%`;
  13649. elLoss.className = (s.loss_pct > 1.0) ? 'text-2xl font-bold text-rose-400' : 'text-2xl font-bold text-emerald-400';
  13650. }
  13651. const elLostPkts = document.getElementById('bwtest-stat-lost-pkts');
  13652. if (elLostPkts) elLostPkts.innerText = s.lost_packets || 0;
  13653. const elJitter = document.getElementById('bwtest-stat-jitter');
  13654. if (elJitter) elJitter.innerText = `${(s.jitter_ms || 0).toFixed(2)} ms`;
  13655. const elTime = document.getElementById('bwtest-stat-time');
  13656. if (elTime) elTime.innerText = `${(s.elapsed_sec || 0).toFixed(1)}s`;
  13657. const elData = document.getElementById('bwtest-stat-data');
  13658. if (elData) elData.innerText = formatBytes((s.tx_bytes || 0) + (s.rx_bytes || 0));
  13659. const elGraphRate = document.getElementById('bwtest-graph-rate');
  13660. if (elGraphRate) elGraphRate.innerText = `TX: ${txMbps.toFixed(1)} Mbps • RX: ${rxMbps.toFixed(1)} Mbps`;
  13661. // Append point to chart buffer
  13662. bwtestState.chartPoints.push({
  13663. elapsed: s.elapsed_sec || 0,
  13664. tx: txMbps,
  13665. rx: rxMbps
  13666. });
  13667. if (bwtestState.chartPoints.length > bwtestState.maxChartPoints) {
  13668. bwtestState.chartPoints.shift();
  13669. }
  13670. drawBwTestChart();
  13671. // Add row to breakdown table
  13672. const tbody = document.getElementById('bwtest-samples-tbody');
  13673. if (tbody) {
  13674. const tr = document.createElement('tr');
  13675. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  13676. tr.innerHTML = `
  13677. <td class="py-1.5 px-3 font-semibold text-white">${(s.elapsed_sec || 0).toFixed(1)}s</td>
  13678. <td class="py-1.5 px-3 font-bold text-cyan-400">${txMbps.toFixed(2)} Mbps</td>
  13679. <td class="py-1.5 px-3 font-bold text-purple-400">${rxMbps.toFixed(2)} Mbps</td>
  13680. <td class="py-1.5 px-3 ${(s.loss_pct > 1.0) ? 'text-rose-400 font-bold' : 'text-emerald-400'}">${(s.loss_pct || 0).toFixed(1)}%</td>
  13681. <td class="py-1.5 px-3 text-slate-300">${(s.jitter_ms || 0).toFixed(2)} ms</td>
  13682. <td class="py-1.5 px-3 text-slate-400">${formatBytes((s.tx_bytes || 0) + (s.rx_bytes || 0))}</td>
  13683. `;
  13684. tbody.insertBefore(tr, tbody.firstChild);
  13685. const countEl = document.getElementById('bwtest-sample-count');
  13686. if (countEl) countEl.innerText = `${tbody.children.length} samples`;
  13687. }
  13688. }
  13689. function handleBwTestFinish(summary, error) {
  13690. const badge = document.getElementById('bwtest-run-status-badge');
  13691. if (error) {
  13692. showToast('Benchmark Error', error, 'error');
  13693. if (badge) {
  13694. badge.innerText = 'ERROR';
  13695. badge.className = 'px-2 py-0.5 rounded text-[10px] font-mono bg-rose-500/20 text-rose-300 border border-rose-500/40 font-bold';
  13696. }
  13697. } else if (summary) {
  13698. const avgTx = summary.avg_tx_mbps.toFixed(1);
  13699. const avgRx = summary.avg_rx_mbps.toFixed(1);
  13700. showToast('Benchmark Complete', `Average TX: ${avgTx} Mbps | RX: ${avgRx} Mbps (Loss: ${summary.avg_loss_pct.toFixed(1)}%)`, 'success');
  13701. if (badge) {
  13702. badge.innerText = 'COMPLETED';
  13703. badge.className = 'px-2 py-0.5 rounded text-[10px] font-mono bg-emerald-500/20 text-emerald-300 border border-emerald-500/40 font-bold';
  13704. }
  13705. }
  13706. loadBwTestHistory();
  13707. fetchBwTestServerStatus();
  13708. }
  13709. function resizeBwTestCanvas() {
  13710. const canvas = document.getElementById('bwtest-chart');
  13711. if (!canvas || !canvas.parentElement) return;
  13712. const rect = canvas.parentElement.getBoundingClientRect();
  13713. const dpr = window.devicePixelRatio || 1;
  13714. canvas.width = rect.width * dpr;
  13715. canvas.height = rect.height * dpr;
  13716. const ctx = canvas.getContext('2d');
  13717. ctx.scale(dpr, dpr);
  13718. drawBwTestChart();
  13719. }
  13720. window.addEventListener('resize', () => {
  13721. if (state.activeTab === 'bwtest') resizeBwTestCanvas();
  13722. });
  13723. function drawBwTestChart() {
  13724. const canvas = document.getElementById('bwtest-chart');
  13725. if (!canvas) return;
  13726. const ctx = canvas.getContext('2d');
  13727. const dpr = window.devicePixelRatio || 1;
  13728. const width = canvas.width / dpr;
  13729. const height = canvas.height / dpr;
  13730. ctx.clearRect(0, 0, width, height);
  13731. const points = bwtestState.chartPoints;
  13732. if (!points || points.length === 0) return;
  13733. // Determine scale ceiling
  13734. let maxRate = 10;
  13735. for (const p of points) {
  13736. if (p.tx > maxRate) maxRate = p.tx;
  13737. if (p.rx > maxRate) maxRate = p.rx;
  13738. }
  13739. maxRate = Math.ceil(maxRate * 1.25); // 25% headroom
  13740. const paddingLeft = 55;
  13741. const paddingBottom = 24;
  13742. const paddingTop = 12;
  13743. const paddingRight = 16;
  13744. const chartW = width - paddingLeft - paddingRight;
  13745. const chartH = height - paddingTop - paddingBottom;
  13746. // Grid Lines and Y-Axis labels
  13747. ctx.strokeStyle = 'rgba(51, 65, 85, 0.4)';
  13748. ctx.lineWidth = 1;
  13749. ctx.fillStyle = '#94a3b8';
  13750. ctx.font = '10px monospace';
  13751. ctx.textAlign = 'right';
  13752. const gridSteps = 4;
  13753. for (let i = 0; i <= gridSteps; i++) {
  13754. const val = (maxRate / gridSteps) * i;
  13755. const y = paddingTop + chartH - (i / gridSteps) * chartH;
  13756. ctx.beginPath();
  13757. ctx.moveTo(paddingLeft, y);
  13758. ctx.lineTo(width - paddingRight, y);
  13759. ctx.stroke();
  13760. ctx.fillText(`${Math.round(val)}M`, paddingLeft - 8, y + 3);
  13761. }
  13762. // Draw TX Line (Cyan #22d3ee)
  13763. drawSeries(ctx, points, p => p.tx, maxRate, paddingLeft, paddingTop, chartW, chartH, '#22d3ee', 'rgba(34, 211, 238, 0.15)');
  13764. // Draw RX Line (Purple #a855f7)
  13765. drawSeries(ctx, points, p => p.rx, maxRate, paddingLeft, paddingTop, chartW, chartH, '#a855f7', 'rgba(168, 85, 247, 0.15)');
  13766. }
  13767. function drawSeries(ctx, points, valFn, maxVal, left, top, w, h, strokeColor, fillColor) {
  13768. if (points.length < 2) return;
  13769. const stepX = w / Math.max(points.length - 1, 1);
  13770. // Gradient area fill
  13771. const grad = ctx.createLinearGradient(0, top, 0, top + h);
  13772. grad.addColorStop(0, fillColor);
  13773. grad.addColorStop(1, 'rgba(0, 0, 0, 0)');
  13774. ctx.beginPath();
  13775. points.forEach((p, idx) => {
  13776. const x = left + idx * stepX;
  13777. const val = valFn(p);
  13778. const y = top + h - (val / maxVal) * h;
  13779. if (idx === 0) {
  13780. ctx.moveTo(x, y);
  13781. } else {
  13782. ctx.lineTo(x, y);
  13783. }
  13784. });
  13785. // Complete path for fill
  13786. ctx.lineTo(left + (points.length - 1) * stepX, top + h);
  13787. ctx.lineTo(left, top + h);
  13788. ctx.closePath();
  13789. ctx.fillStyle = grad;
  13790. ctx.fill();
  13791. // Draw line stroke
  13792. ctx.beginPath();
  13793. ctx.lineWidth = 2.5;
  13794. ctx.strokeStyle = strokeColor;
  13795. points.forEach((p, idx) => {
  13796. const x = left + idx * stepX;
  13797. const val = valFn(p);
  13798. const y = top + h - (val / maxVal) * h;
  13799. if (idx === 0) {
  13800. ctx.moveTo(x, y);
  13801. } else {
  13802. ctx.lineTo(x, y);
  13803. }
  13804. });
  13805. ctx.stroke();
  13806. // Draw end point halo
  13807. const lastP = points[points.length - 1];
  13808. const lastX = left + (points.length - 1) * stepX;
  13809. const lastY = top + h - (valFn(lastP) / maxVal) * h;
  13810. ctx.fillStyle = strokeColor;
  13811. ctx.beginPath();
  13812. ctx.arc(lastX, lastY, 4, 0, 2 * Math.PI);
  13813. ctx.fill();
  13814. }
  13815. async function loadBwTestHistory() {
  13816. try {
  13817. const res = await fetch(`${API_BASE}/tools/bwtest/history`);
  13818. if (!res.ok) return;
  13819. const list = await res.json();
  13820. renderBwTestHistory(Array.isArray(list) ? list : []);
  13821. } catch (err) {
  13822. console.error('Failed to load BwTest history:', err);
  13823. }
  13824. }
  13825. function renderBwTestHistory(list) {
  13826. const tbody = document.getElementById('bwtest-history-tbody');
  13827. if (!tbody) return;
  13828. if (list.length === 0) {
  13829. tbody.innerHTML = `<tr><td colspan="10" class="p-6 text-center text-slate-500 text-xs font-sans">No past benchmark runs recorded yet.</td></tr>`;
  13830. return;
  13831. }
  13832. tbody.innerHTML = '';
  13833. list.forEach(item => {
  13834. const s = item.summary || {};
  13835. const tr = document.createElement('tr');
  13836. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  13837. const dirBadge = item.direction === 'both'
  13838. ? `<span class="px-1.5 py-0.5 rounded text-[10px] bg-emerald-500/20 text-emerald-300 border border-emerald-500/30 uppercase font-semibold">Both</span>`
  13839. : item.direction === 'tx'
  13840. ? `<span class="px-1.5 py-0.5 rounded text-[10px] bg-cyan-500/20 text-cyan-300 border border-cyan-500/30 uppercase font-semibold">TX Only</span>`
  13841. : `<span class="px-1.5 py-0.5 rounded text-[10px] bg-purple-500/20 text-purple-300 border border-purple-500/30 uppercase font-semibold">RX Only</span>`;
  13842. const protoBadge = item.protocol === 'tcp'
  13843. ? `<span class="px-1.5 py-0.5 rounded text-[10px] bg-blue-500/20 text-blue-300 border border-blue-500/30 font-semibold uppercase">TCP</span>`
  13844. : `<span class="px-1.5 py-0.5 rounded text-[10px] bg-amber-500/20 text-amber-300 border border-amber-500/30 font-semibold uppercase">UDP</span>`;
  13845. const dateStr = item.timestamp ? new Date(item.timestamp).toLocaleString() : '-';
  13846. tr.innerHTML = `
  13847. <td class="py-2.5 px-4 font-bold text-white font-mono text-[11px]">${escapeHtml(item.id || '-')}</td>
  13848. <td class="py-2.5 px-4 text-emerald-400 font-mono font-medium">${escapeHtml(item.target || '-')}</td>
  13849. <td class="py-2.5 px-4">${protoBadge}</td>
  13850. <td class="py-2.5 px-4">${dirBadge}</td>
  13851. <td class="py-2.5 px-4 text-slate-300">${(s.duration_sec || 0).toFixed(1)}s</td>
  13852. <td class="py-2.5 px-4 font-bold text-cyan-400 font-mono">${(s.avg_tx_mbps || 0).toFixed(1)} / ${(s.peak_tx_mbps || 0).toFixed(1)} <span class="text-[10px] text-slate-400 font-normal">Mbps</span></td>
  13853. <td class="py-2.5 px-4 font-bold text-purple-400 font-mono">${(s.avg_rx_mbps || 0).toFixed(1)} / ${(s.peak_rx_mbps || 0).toFixed(1)} <span class="text-[10px] text-slate-400 font-normal">Mbps</span></td>
  13854. <td class="py-2.5 px-4 ${(s.avg_loss_pct > 1.0) ? 'text-rose-400 font-bold' : 'text-emerald-400'} font-mono">${(s.avg_loss_pct || 0).toFixed(1)}% <span class="text-[10px] text-slate-400 font-normal">(${s.total_lost_packets || 0})</span></td>
  13855. <td class="py-2.5 px-4 text-slate-300 font-mono">${(s.avg_jitter_ms || 0).toFixed(2)} ms</td>
  13856. <td class="py-2.5 px-4 text-slate-400 text-[11px] font-sans">${escapeHtml(dateStr)}</td>
  13857. `;
  13858. tbody.appendChild(tr);
  13859. });
  13860. }
  13861. // ======================== SETTINGS & ROUTER DNS ========================
  13862. state.settingsSubTab = 'dns';
  13863. state.dnsSettings = null;
  13864. state.dnsStaticRecords = [];
  13865. state.dnsStatus = null;
  13866. function switchSettingsSubTab(sub) {
  13867. state.settingsSubTab = sub;
  13868. const btnDns = document.getElementById('btn-settings-subtab-dns');
  13869. const btnSys = document.getElementById('btn-settings-subtab-system');
  13870. const tabDns = document.getElementById('settings-subtab-dns');
  13871. const tabSys = document.getElementById('settings-subtab-system');
  13872. if (sub === 'dns') {
  13873. if (btnDns) {
  13874. btnDns.className = 'px-3.5 py-1.5 rounded-lg text-xs font-semibold bg-cyan-600 text-white transition flex items-center gap-1.5';
  13875. }
  13876. if (btnSys) {
  13877. btnSys.className = 'px-3.5 py-1.5 rounded-lg text-xs font-semibold bg-slate-800 text-slate-300 hover:text-white transition flex items-center gap-1.5';
  13878. }
  13879. tabDns?.classList.remove('hidden');
  13880. tabSys?.classList.add('hidden');
  13881. loadDNSSettings();
  13882. } else {
  13883. if (btnSys) {
  13884. btnSys.className = 'px-3.5 py-1.5 rounded-lg text-xs font-semibold bg-cyan-600 text-white transition flex items-center gap-1.5';
  13885. }
  13886. if (btnDns) {
  13887. btnDns.className = 'px-3.5 py-1.5 rounded-lg text-xs font-semibold bg-slate-800 text-slate-300 hover:text-white transition flex items-center gap-1.5';
  13888. }
  13889. tabSys?.classList.remove('hidden');
  13890. tabDns?.classList.add('hidden');
  13891. loadSystemSettings();
  13892. }
  13893. }
  13894. async function loadSettingsData(showLoading = false) {
  13895. if (state.settingsSubTab === 'system') {
  13896. await loadSystemSettings();
  13897. } else {
  13898. await loadDNSSettings();
  13899. }
  13900. }
  13901. async function loadDNSSettings() {
  13902. try {
  13903. const [settingsRes, staticRes, statusRes] = await Promise.all([
  13904. fetch(`${API_BASE}/dns/settings`),
  13905. fetch(`${API_BASE}/dns/static`),
  13906. fetch(`${API_BASE}/dns/status`)
  13907. ]);
  13908. if (settingsRes.ok) {
  13909. state.dnsSettings = await settingsRes.json();
  13910. populateDNSSettingsForm(state.dnsSettings);
  13911. }
  13912. if (staticRes.ok) {
  13913. state.dnsStaticRecords = await staticRes.json();
  13914. renderStaticDNSList();
  13915. }
  13916. if (statusRes.ok) {
  13917. state.dnsStatus = await statusRes.json();
  13918. updateDNSStatusView(state.dnsStatus);
  13919. }
  13920. } catch (err) {
  13921. console.error('Failed to load DNS settings:', err);
  13922. }
  13923. }
  13924. function populateDNSSettingsForm(s) {
  13925. if (!s) return;
  13926. const dnsForm = document.getElementById('form-dns-settings');
  13927. const isEditing = dnsForm && (dnsForm.contains(document.activeElement) || dnsForm.dataset.dirty === 'true');
  13928. const dynamicEl = document.getElementById('dns-dynamic-servers-list');
  13929. if (dynamicEl) {
  13930. if (Array.isArray(s.dynamic_servers) && s.dynamic_servers.length > 0) {
  13931. dynamicEl.innerHTML = s.dynamic_servers.map(d => `<span class="px-2 py-0.5 rounded bg-cyan-950 text-cyan-300 border border-cyan-800 font-mono">${escapeHtml(d)}</span>`).join(' ');
  13932. } else {
  13933. dynamicEl.innerText = 'None';
  13934. }
  13935. }
  13936. // If user is actively typing or editing in the form, do not overwrite their inputs!
  13937. if (isEditing) return;
  13938. const serversInput = document.getElementById('dns-servers-input');
  13939. if (serversInput) serversInput.value = (s.servers || []).join(', ');
  13940. const cacheSizeInput = document.getElementById('dns-cache-size-input');
  13941. if (cacheSizeInput) cacheSizeInput.value = s.cache_size || 2048;
  13942. const domainInput = document.getElementById('dns-domain-input');
  13943. if (domainInput) domainInput.value = s.domain || '';
  13944. const allowRemoteInput = document.getElementById('dns-allow-remote-input');
  13945. if (allowRemoteInput) allowRemoteInput.checked = s.allow_remote_requests !== false;
  13946. }
  13947. function updateDNSStatusView(st) {
  13948. if (!st) return;
  13949. const preview = document.getElementById('dns-resolv-preview');
  13950. if (preview) preview.innerText = st.resolv_conf_content || '(empty)';
  13951. const pillText = document.getElementById('dns-live-status-text');
  13952. const pill = document.getElementById('dns-live-status-pill');
  13953. if (pill && pillText) {
  13954. if (st.service_running) {
  13955. pill.className = 'px-2.5 py-1 rounded-full text-[11px] font-mono bg-emerald-500/10 text-emerald-400 border border-emerald-500/30 flex items-center gap-1.5';
  13956. pillText.innerText = 'DNS Service Active';
  13957. } else {
  13958. pill.className = 'px-2.5 py-1 rounded-full text-[11px] font-mono bg-rose-500/10 text-rose-400 border border-rose-500/30 flex items-center gap-1.5';
  13959. pillText.innerText = 'DNS Service Inactive';
  13960. }
  13961. }
  13962. }
  13963. function appendDNSPreset(preset) {
  13964. const input = document.getElementById('dns-servers-input');
  13965. if (!input) return;
  13966. const dnsForm = document.getElementById('form-dns-settings');
  13967. if (dnsForm) dnsForm.dataset.dirty = 'true';
  13968. const current = input.value.trim();
  13969. if (!current) {
  13970. input.value = preset;
  13971. } else {
  13972. const existing = current.split(/[,\s]+/).map(s => s.trim()).filter(Boolean);
  13973. const toAdd = preset.split(/[,\s]+/).map(s => s.trim()).filter(Boolean);
  13974. toAdd.forEach(ip => {
  13975. if (!existing.includes(ip)) existing.push(ip);
  13976. });
  13977. input.value = existing.join(', ');
  13978. }
  13979. }
  13980. async function saveDNSSettings(e) {
  13981. e.preventDefault();
  13982. const rawServers = document.getElementById('dns-servers-input')?.value || '';
  13983. const servers = rawServers.split(/[,\s]+/).map(s => s.trim()).filter(Boolean);
  13984. if (servers.length === 0) {
  13985. showToast('Validation Error', 'Please enter at least one upstream DNS server IP', 'error');
  13986. return;
  13987. }
  13988. const cacheSize = parseInt(document.getElementById('dns-cache-size-input')?.value || '2048', 10);
  13989. const domain = (document.getElementById('dns-domain-input')?.value || '').trim();
  13990. const allowRemote = document.getElementById('dns-allow-remote-input')?.checked ?? true;
  13991. try {
  13992. const res = await fetch(`${API_BASE}/dns/settings`, {
  13993. method: 'POST',
  13994. headers: { 'Content-Type': 'application/json' },
  13995. body: JSON.stringify({
  13996. servers: servers,
  13997. cache_size: cacheSize,
  13998. domain: domain,
  13999. allow_remote_requests: allowRemote
  14000. })
  14001. });
  14002. const data = await res.json();
  14003. if (res.ok) {
  14004. const dnsForm = document.getElementById('form-dns-settings');
  14005. if (dnsForm) dnsForm.dataset.dirty = 'false';
  14006. showToast('DNS Applied', 'Router DNS forwarders and resolver settings updated successfully', 'success');
  14007. loadDNSSettings();
  14008. } else {
  14009. showToast('Error', data.error || data.message || 'Failed to save DNS settings', 'error');
  14010. }
  14011. } catch (err) {
  14012. showToast('Error', err.message, 'error');
  14013. }
  14014. }
  14015. async function flushDNSCache() {
  14016. try {
  14017. const res = await fetch(`${API_BASE}/dns/flush`, { method: 'POST' });
  14018. if (res.ok) {
  14019. showToast('Cache Flushed', 'Router DNS cache cleared and static hosts reloaded', 'success');
  14020. loadDNSSettings();
  14021. } else {
  14022. const err = await res.json();
  14023. showToast('Error', err.error || 'Failed to flush cache', 'error');
  14024. }
  14025. } catch (err) {
  14026. showToast('Error', err.message, 'error');
  14027. }
  14028. }
  14029. function renderStaticDNSList() {
  14030. const tbody = document.getElementById('dns-static-tbody');
  14031. const empty = document.getElementById('dns-static-empty');
  14032. const badge = document.getElementById('dns-static-count-badge');
  14033. if (!tbody) return;
  14034. tbody.innerHTML = '';
  14035. const records = state.dnsStaticRecords || [];
  14036. if (badge) badge.innerText = `${records.length} Records`;
  14037. if (records.length === 0) {
  14038. empty?.classList.remove('hidden');
  14039. return;
  14040. }
  14041. empty?.classList.add('hidden');
  14042. records.forEach(rec => {
  14043. const tr = document.createElement('tr');
  14044. tr.className = `hover:bg-slate-800/40 transition text-xs ${rec.disabled ? 'opacity-50' : ''}`;
  14045. tr.innerHTML = `
  14046. <td class="py-2.5 px-4 font-bold text-white">${escapeHtml(rec.name)}</td>
  14047. <td class="py-2.5 px-4">
  14048. <span class="px-2 py-0.5 rounded text-[10px] font-bold ${
  14049. rec.type === 'CNAME' ? 'bg-purple-950 text-purple-300 border border-purple-800' :
  14050. (rec.type === 'AAAA' ? 'bg-blue-950 text-blue-300 border border-blue-800' : 'bg-cyan-950 text-cyan-300 border border-cyan-800')
  14051. }">
  14052. ${rec.type || 'A'}
  14053. </span>
  14054. </td>
  14055. <td class="py-2.5 px-4 text-emerald-400 font-mono">${escapeHtml(rec.address)}</td>
  14056. <td class="py-2.5 px-4 text-slate-400 font-mono">${rec.ttl || 3600}s</td>
  14057. <td class="py-2.5 px-4 text-slate-400 italic truncate max-w-[140px]">${escapeHtml(rec.comment || '-')}</td>
  14058. <td class="py-2.5 px-4">
  14059. <span class="px-1.5 py-0.5 rounded text-[10px] font-semibold ${rec.disabled ? 'bg-slate-800 text-slate-500' : 'bg-emerald-500/10 text-emerald-400 border border-emerald-500/30'}">
  14060. ${rec.disabled ? 'Disabled' : 'Active'}
  14061. </span>
  14062. </td>
  14063. <td class="py-2.5 px-4 text-right space-x-2 font-sans whitespace-nowrap">
  14064. <button onclick="toggleStaticDNS('${rec.id}', ${!rec.disabled})" class="text-xs ${rec.disabled ? 'text-emerald-400' : 'text-slate-400'} hover:underline">${rec.disabled ? 'Enable' : 'Disable'}</button>
  14065. <button onclick="openStaticDNSModal('${rec.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold">Edit</button>
  14066. <button onclick="deleteStaticDNS('${rec.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  14067. </td>
  14068. `;
  14069. tbody.appendChild(tr);
  14070. });
  14071. }
  14072. function openStaticDNSModal(id = null) {
  14073. const modal = document.getElementById('modal-static-dns');
  14074. const title = document.getElementById('modal-static-dns-title');
  14075. const form = document.getElementById('form-static-dns');
  14076. if (!modal || !form) return;
  14077. form.reset();
  14078. document.getElementById('modal-static-dns-id').value = '';
  14079. if (id) {
  14080. const rec = (state.dnsStaticRecords || []).find(r => r.id === id);
  14081. if (rec) {
  14082. if (title) title.innerText = 'Edit Static DNS Record';
  14083. document.getElementById('modal-static-dns-id').value = rec.id;
  14084. document.getElementById('modal-static-dns-name').value = rec.name;
  14085. document.getElementById('modal-static-dns-type').value = rec.type || 'A';
  14086. document.getElementById('modal-static-dns-addr').value = rec.address;
  14087. document.getElementById('modal-static-dns-ttl').value = rec.ttl || 3600;
  14088. document.getElementById('modal-static-dns-comment').value = rec.comment || '';
  14089. document.getElementById('modal-static-dns-disabled').checked = !!rec.disabled;
  14090. }
  14091. } else {
  14092. if (title) title.innerText = 'Add Static DNS Record';
  14093. }
  14094. modal.classList.remove('hidden');
  14095. }
  14096. function closeStaticDNSModal() {
  14097. document.getElementById('modal-static-dns')?.classList.add('hidden');
  14098. }
  14099. async function submitSaveStaticDNS(e) {
  14100. e.preventDefault();
  14101. const id = document.getElementById('modal-static-dns-id')?.value || '';
  14102. const name = (document.getElementById('modal-static-dns-name')?.value || '').trim();
  14103. const type = document.getElementById('modal-static-dns-type')?.value || 'A';
  14104. const address = (document.getElementById('modal-static-dns-addr')?.value || '').trim();
  14105. const ttl = parseInt(document.getElementById('modal-static-dns-ttl')?.value || '3600', 10);
  14106. const comment = (document.getElementById('modal-static-dns-comment')?.value || '').trim();
  14107. const disabled = document.getElementById('modal-static-dns-disabled')?.checked ?? false;
  14108. if (!name || !address) {
  14109. showToast('Validation Error', 'Name and Target Address are required', 'error');
  14110. return;
  14111. }
  14112. try {
  14113. const res = await fetch(`${API_BASE}/dns/static`, {
  14114. method: 'POST',
  14115. headers: { 'Content-Type': 'application/json' },
  14116. body: JSON.stringify({ id, name, type, address, ttl, comment, disabled })
  14117. });
  14118. const data = await res.json();
  14119. if (res.ok) {
  14120. showToast('Static DNS Saved', `Saved record ${name} -> ${address}`, 'success');
  14121. closeStaticDNSModal();
  14122. loadDNSSettings();
  14123. } else {
  14124. showToast('Error', data.error || data.message || 'Failed to save record', 'error');
  14125. }
  14126. } catch (err) {
  14127. showToast('Error', err.message, 'error');
  14128. }
  14129. }
  14130. async function deleteStaticDNS(id) {
  14131. if (!confirm('Are you sure you want to delete this static DNS entry?')) return;
  14132. try {
  14133. const res = await fetch(`${API_BASE}/dns/static/${encodeURIComponent(id)}`, { method: 'DELETE' });
  14134. if (res.ok) {
  14135. showToast('Deleted', 'Static DNS record deleted', 'success');
  14136. loadDNSSettings();
  14137. }
  14138. } catch (err) {
  14139. showToast('Error', err.message, 'error');
  14140. }
  14141. }
  14142. async function toggleStaticDNS(id, disabled) {
  14143. try {
  14144. const res = await fetch(`${API_BASE}/dns/static/${encodeURIComponent(id)}/state`, {
  14145. method: 'POST',
  14146. headers: { 'Content-Type': 'application/json' },
  14147. body: JSON.stringify({ disabled })
  14148. });
  14149. if (res.ok) {
  14150. showToast('Updated', `Record ${disabled ? 'disabled' : 'enabled'}`, 'success');
  14151. loadDNSSettings();
  14152. }
  14153. } catch (err) {
  14154. showToast('Error', err.message, 'error');
  14155. }
  14156. }
  14157. async function loadSystemSettings() {
  14158. try {
  14159. const sysForm = document.getElementById('form-system-settings');
  14160. const isEditing = sysForm && (sysForm.contains(document.activeElement) || sysForm.dataset.dirty === 'true');
  14161. const res = await fetch(`${API_BASE}/system/settings`);
  14162. if (res.ok) {
  14163. const data = await res.json();
  14164. if (!isEditing) {
  14165. const hostInput = document.getElementById('system-hostname-input');
  14166. if (hostInput) hostInput.value = data.hostname || '';
  14167. const tzInput = document.getElementById('system-timezone-input');
  14168. if (tzInput && data.timezone) tzInput.value = data.timezone;
  14169. }
  14170. }
  14171. } catch (err) {
  14172. console.error('Failed to load system settings:', err);
  14173. }
  14174. }
  14175. async function saveSystemSettings(e) {
  14176. e.preventDefault();
  14177. const hostname = (document.getElementById('system-hostname-input')?.value || '').trim();
  14178. const timezone = document.getElementById('system-timezone-input')?.value || 'UTC';
  14179. try {
  14180. const res = await fetch(`${API_BASE}/system/settings`, {
  14181. method: 'POST',
  14182. headers: { 'Content-Type': 'application/json' },
  14183. body: JSON.stringify({ hostname, timezone })
  14184. });
  14185. const data = await res.json();
  14186. if (res.ok) {
  14187. const sysForm = document.getElementById('form-system-settings');
  14188. if (sysForm) sysForm.dataset.dirty = 'false';
  14189. showToast('System Updated', 'Hostname and timezone saved successfully', 'success');
  14190. const sideH = document.getElementById('side-hostname');
  14191. if (sideH) sideH.innerText = data.hostname;
  14192. } else {
  14193. showToast('Error', data.error || 'Failed to save system settings', 'error');
  14194. }
  14195. } catch (err) {
  14196. showToast('Error', err.message, 'error');
  14197. }
  14198. }