@@ -442,6 +442,8 @@ def __str__(self):
442
442
return self .message
443
443
444
444
def __init__ (self , name : str = None , data : dict = None ):
445
+ print (f"[WGDashboard] Initialized Configuration: { name } " )
446
+
445
447
self .__parser : configparser .ConfigParser = configparser .ConfigParser (strict = False )
446
448
self .__parser .optionxform = str
447
449
self .__configFileModifiedTime = None
@@ -588,83 +590,93 @@ def __getRestrictedPeers(self):
588
590
restricted = sqlSelect ("SELECT * FROM '%s_restrict_access'" % self .Name ).fetchall ()
589
591
for i in restricted :
590
592
self .RestrictedPeers .append (Peer (i , self ))
591
-
593
+
594
+ def configurationFileChanged (self ) :
595
+ mt = os .path .getmtime (os .path .join (WG_CONF_PATH , f'{ self .Name } .conf' ))
596
+ changed = self .__configFileModifiedTime is None or self .__configFileModifiedTime != mt
597
+ self .__configFileModifiedTime = mt
598
+ return changed
599
+
592
600
def __getPeers (self ):
593
601
594
- mt = os .path .getmtime (os .path .join (WG_CONF_PATH , f'{ self .Name } .conf' ))
595
- # if self.__configFileModifiedTime is None or self.__configFileModifiedTime != mt:
596
- self .Peers = []
597
- with open (os .path .join (WG_CONF_PATH , f'{ self .Name } .conf' ), 'r' ) as configFile :
598
- p = []
599
- pCounter = - 1
600
- content = configFile .read ().split ('\n ' )
601
- try :
602
- peerStarts = content .index ("[Peer]" )
603
- content = content [peerStarts :]
604
- for i in content :
605
- if not regex_match ("#(.*)" , i ) and not regex_match (";(.*)" , i ):
606
- if i == "[Peer]" :
607
- pCounter += 1
608
- p .append ({})
609
- p [pCounter ]["name" ] = ""
610
- else :
611
- if len (i ) > 0 :
612
- split = re .split (r'\s*=\s*' , i , 1 )
613
- if len (split ) == 2 :
614
- p [pCounter ][split [0 ]] = split [1 ]
602
+ if self .configurationFileChanged ():
603
+ self .Peers = []
604
+ with open (os .path .join (WG_CONF_PATH , f'{ self .Name } .conf' ), 'r' ) as configFile :
605
+ p = []
606
+ pCounter = - 1
607
+ content = configFile .read ().split ('\n ' )
608
+ try :
609
+ peerStarts = content .index ("[Peer]" )
610
+ content = content [peerStarts :]
611
+ for i in content :
612
+ if not regex_match ("#(.*)" , i ) and not regex_match (";(.*)" , i ):
613
+ if i == "[Peer]" :
614
+ pCounter += 1
615
+ p .append ({})
616
+ p [pCounter ]["name" ] = ""
617
+ else :
618
+ if len (i ) > 0 :
619
+ split = re .split (r'\s*=\s*' , i , 1 )
620
+ if len (split ) == 2 :
621
+ p [pCounter ][split [0 ]] = split [1 ]
622
+
623
+ if regex_match ("#Name# = (.*)" , i ):
624
+ split = re .split (r'\s*=\s*' , i , 1 )
625
+ print (split )
626
+ if len (split ) == 2 :
627
+ p [pCounter ]["name" ] = split [1 ]
615
628
616
- if regex_match ("#Name# = (.*)" , i ):
617
- split = re .split (r'\s*=\s*' , i , 1 )
618
- print (split )
619
- if len (split ) == 2 :
620
- p [pCounter ]["name" ] = split [1 ]
621
-
622
- for i in p :
623
- if "PublicKey" in i .keys ():
624
- checkIfExist = sqlSelect ("SELECT * FROM '%s' WHERE id = ?" % self .Name ,
625
- ((i ['PublicKey' ]),)).fetchone ()
626
- if checkIfExist is None :
627
- newPeer = {
628
- "id" : i ['PublicKey' ],
629
- "private_key" : "" ,
630
- "DNS" : DashboardConfig .GetConfig ("Peers" , "peer_global_DNS" )[1 ],
631
- "endpoint_allowed_ip" : DashboardConfig .GetConfig ("Peers" , "peer_endpoint_allowed_ip" )[
632
- 1 ],
633
- "name" : i .get ("name" ),
634
- "total_receive" : 0 ,
635
- "total_sent" : 0 ,
636
- "total_data" : 0 ,
637
- "endpoint" : "N/A" ,
638
- "status" : "stopped" ,
639
- "latest_handshake" : "N/A" ,
640
- "allowed_ip" : i .get ("AllowedIPs" , "N/A" ),
641
- "cumu_receive" : 0 ,
642
- "cumu_sent" : 0 ,
643
- "cumu_data" : 0 ,
644
- "traffic" : [],
645
- "mtu" : DashboardConfig .GetConfig ("Peers" , "peer_mtu" )[1 ],
646
- "keepalive" : DashboardConfig .GetConfig ("Peers" , "peer_keep_alive" )[1 ],
647
- "remote_endpoint" : DashboardConfig .GetConfig ("Peers" , "remote_endpoint" )[1 ],
648
- "preshared_key" : i ["PresharedKey" ] if "PresharedKey" in i .keys () else ""
649
- }
650
- sqlUpdate (
651
- """
652
- INSERT INTO '%s'
653
- VALUES (:id, :private_key, :DNS, :endpoint_allowed_ip, :name, :total_receive, :total_sent,
654
- :total_data, :endpoint, :status, :latest_handshake, :allowed_ip, :cumu_receive, :cumu_sent,
655
- :cumu_data, :mtu, :keepalive, :remote_endpoint, :preshared_key);
656
- """ % self .Name
657
- , newPeer )
658
- # sqldb.commit()
659
- self .Peers .append (Peer (newPeer , self ))
660
- else :
661
- sqlUpdate ("UPDATE '%s' SET allowed_ip = ? WHERE id = ?" % self .Name ,
662
- (i .get ("AllowedIPs" , "N/A" ), i ['PublicKey' ],))
663
- # sqldb.commit()
664
- self .Peers .append (Peer (checkIfExist , self ))
665
- except Exception as e :
666
- print (f"[WGDashboard] { self .Name } Error: { str (e )} " )
667
- self .__configFileModifiedTime = mt
629
+ for i in p :
630
+ if "PublicKey" in i .keys ():
631
+ checkIfExist = sqlSelect ("SELECT * FROM '%s' WHERE id = ?" % self .Name ,
632
+ ((i ['PublicKey' ]),)).fetchone ()
633
+ if checkIfExist is None :
634
+ newPeer = {
635
+ "id" : i ['PublicKey' ],
636
+ "private_key" : "" ,
637
+ "DNS" : DashboardConfig .GetConfig ("Peers" , "peer_global_DNS" )[1 ],
638
+ "endpoint_allowed_ip" : DashboardConfig .GetConfig ("Peers" , "peer_endpoint_allowed_ip" )[
639
+ 1 ],
640
+ "name" : i .get ("name" ),
641
+ "total_receive" : 0 ,
642
+ "total_sent" : 0 ,
643
+ "total_data" : 0 ,
644
+ "endpoint" : "N/A" ,
645
+ "status" : "stopped" ,
646
+ "latest_handshake" : "N/A" ,
647
+ "allowed_ip" : i .get ("AllowedIPs" , "N/A" ),
648
+ "cumu_receive" : 0 ,
649
+ "cumu_sent" : 0 ,
650
+ "cumu_data" : 0 ,
651
+ "traffic" : [],
652
+ "mtu" : DashboardConfig .GetConfig ("Peers" , "peer_mtu" )[1 ],
653
+ "keepalive" : DashboardConfig .GetConfig ("Peers" , "peer_keep_alive" )[1 ],
654
+ "remote_endpoint" : DashboardConfig .GetConfig ("Peers" , "remote_endpoint" )[1 ],
655
+ "preshared_key" : i ["PresharedKey" ] if "PresharedKey" in i .keys () else ""
656
+ }
657
+ sqlUpdate (
658
+ """
659
+ INSERT INTO '%s'
660
+ VALUES (:id, :private_key, :DNS, :endpoint_allowed_ip, :name, :total_receive, :total_sent,
661
+ :total_data, :endpoint, :status, :latest_handshake, :allowed_ip, :cumu_receive, :cumu_sent,
662
+ :cumu_data, :mtu, :keepalive, :remote_endpoint, :preshared_key);
663
+ """ % self .Name
664
+ , newPeer )
665
+ # sqldb.commit()
666
+ self .Peers .append (Peer (newPeer , self ))
667
+ else :
668
+ sqlUpdate ("UPDATE '%s' SET allowed_ip = ? WHERE id = ?" % self .Name ,
669
+ (i .get ("AllowedIPs" , "N/A" ), i ['PublicKey' ],))
670
+ # sqldb.commit()
671
+ self .Peers .append (Peer (checkIfExist , self ))
672
+ except Exception as e :
673
+ print (f"[WGDashboard] { self .Name } Error: { str (e )} " )
674
+ else :
675
+ self .Peers .clear ()
676
+ checkIfExist = sqlSelect ("SELECT * FROM '%s'" % self .Name ).fetchall ()
677
+ for i in checkIfExist :
678
+ self .Peers .append (Peer (i , self ))
679
+
668
680
669
681
def addPeers (self , peers : list ):
670
682
for p in peers :
@@ -803,12 +815,11 @@ def getPeersLatestHandshake(self):
803
815
else :
804
816
status = "stopped"
805
817
if int (latestHandshake [count + 1 ]) > 0 :
806
- sqldb . execute ("UPDATE '%s' SET latest_handshake = ?, status = ? WHERE id= ?" % self .Name
818
+ sqlUpdate ("UPDATE '%s' SET latest_handshake = ?, status = ? WHERE id= ?" % self .Name
807
819
, (str (minus ).split ("." , maxsplit = 1 )[0 ], status , latestHandshake [count ],))
808
820
else :
809
- sqldb . execute ("UPDATE '%s' SET latest_handshake = 'No Handshake', status = ? WHERE id= ?" % self .Name
821
+ sqlUpdate ("UPDATE '%s' SET latest_handshake = 'No Handshake', status = ? WHERE id= ?" % self .Name
810
822
, (status , latestHandshake [count ],))
811
- sqldb .commit ()
812
823
count += 2
813
824
814
825
@@ -1284,16 +1295,20 @@ def _regexMatch(regex, text):
1284
1295
return pattern .search (text ) is not None
1285
1296
1286
1297
1287
- def _getConfigurationList () -> [ WireguardConfiguration ] :
1288
- configurations = {}
1298
+ def _getConfigurationList ():
1299
+ # configurations = {}
1289
1300
for i in os .listdir (WG_CONF_PATH ):
1290
1301
if _regexMatch ("^(.{1,}).(conf)$" , i ):
1291
1302
i = i .replace ('.conf' , '' )
1292
1303
try :
1293
- configurations [i ] = WireguardConfiguration (i )
1304
+ if i in WireguardConfigurations .keys ():
1305
+ if WireguardConfigurations [i ].configurationFileChanged ():
1306
+ WireguardConfigurations [i ] = WireguardConfiguration (i )
1307
+ else :
1308
+ WireguardConfigurations [i ] = WireguardConfiguration (i )
1294
1309
except WireguardConfiguration .InvalidConfigurationFileException as e :
1295
1310
print (f"{ i } have an invalid configuration file." )
1296
- return configurations
1311
+
1297
1312
1298
1313
1299
1314
def _checkIPWithRange (ip ):
@@ -1354,8 +1369,7 @@ def _generatePrivateKey() -> [bool, str]:
1354
1369
except subprocess .CalledProcessError :
1355
1370
return False , None
1356
1371
1357
-
1358
- def _getWireguardConfigurationAvailableIP (configName : str ) -> tuple [bool , list [str ]] | tuple [bool , None ]:
1372
+ def _getWireguardConfigurationAvailableIP (configName : str , all : bool = False ) -> tuple [bool , list [str ]] | tuple [bool , None ]:
1359
1373
if configName not in WireguardConfigurations .keys ():
1360
1374
return False , None
1361
1375
configuration = WireguardConfigurations [configName ]
@@ -1387,8 +1401,9 @@ def _getWireguardConfigurationAvailableIP(configName: str) -> tuple[bool, list[s
1387
1401
if h not in existedAddress :
1388
1402
availableAddress .append (ipaddress .ip_network (h ).compressed )
1389
1403
count += 1
1390
- if network .version == 6 and count > 255 :
1391
- break
1404
+ if not all :
1405
+ if network .version == 6 and count > 255 :
1406
+ break
1392
1407
return True , availableAddress
1393
1408
1394
1409
return False , None
@@ -1534,7 +1549,7 @@ def API_SignOut():
1534
1549
1535
1550
@app .route (f'{ APP_PREFIX } /api/getWireguardConfigurations' , methods = ["GET" ])
1536
1551
def API_getWireguardConfigurations ():
1537
- # WireguardConfigurations = _getConfigurationList()
1552
+ _getConfigurationList ()
1538
1553
return ResponseObject (data = [wc for wc in WireguardConfigurations .values ()])
1539
1554
1540
1555
@@ -1841,17 +1856,7 @@ def API_addPeers(configName):
1841
1856
if i not in availableIps [1 ]:
1842
1857
return ResponseObject (False , f"This IP is not available: { i } " )
1843
1858
1844
- config .addPeers ([{"id" : public_key , "allowed_ip" : '' .join (allowed_ips )}])
1845
- # subprocess.check_output(
1846
- # f"wg set {config.Name} peer {public_key} allowed-ips {''.join(allowed_ips)}",
1847
- # shell=True, stderr=subprocess.STDOUT)
1848
- # if len(preshared_key) > 0:
1849
- # subprocess.check_output(
1850
- # f"wg set {config.Name} peer {public_key} preshared-key {preshared_key}",
1851
- # shell=True, stderr=subprocess.STDOUT)
1852
- # subprocess.check_output(
1853
- # f"wg-quick save {config.Name}", shell=True, stderr=subprocess.STDOUT)
1854
- # config.getPeersList()
1859
+ config .addPeers ([{"id" : public_key , "allowed_ip" : ',' .join (allowed_ips )}])
1855
1860
found , peer = config .searchPeer (public_key )
1856
1861
if found :
1857
1862
return peer .updatePeer (name , private_key , preshared_key , dns_addresses , "," .join (allowed_ips ),
@@ -2188,7 +2193,7 @@ def gunicornConfig():
2188
2193
2189
2194
2190
2195
WireguardConfigurations : dict [str , WireguardConfiguration ] = {}
2191
- WireguardConfigurations = _getConfigurationList ()
2196
+ _getConfigurationList ()
2192
2197
2193
2198
def startThreads ():
2194
2199
bgThread = threading .Thread (target = backGroundThread )
0 commit comments