Skip to content

Commit c012b8c

Browse files
authored
Merge pull request #340 from donaldzou/v4.0-alpine-linux
V4.0 alpine linux
2 parents 48f6c28 + fec20ed commit c012b8c

File tree

1 file changed

+103
-98
lines changed

1 file changed

+103
-98
lines changed

src/dashboard.py

+103-98
Original file line numberDiff line numberDiff line change
@@ -442,6 +442,8 @@ def __str__(self):
442442
return self.message
443443

444444
def __init__(self, name: str = None, data: dict = None):
445+
print(f"[WGDashboard] Initialized Configuration: {name}")
446+
445447
self.__parser: configparser.ConfigParser = configparser.ConfigParser(strict=False)
446448
self.__parser.optionxform = str
447449
self.__configFileModifiedTime = None
@@ -588,83 +590,93 @@ def __getRestrictedPeers(self):
588590
restricted = sqlSelect("SELECT * FROM '%s_restrict_access'" % self.Name).fetchall()
589591
for i in restricted:
590592
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+
592600
def __getPeers(self):
593601

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]
615628

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+
668680

669681
def addPeers(self, peers: list):
670682
for p in peers:
@@ -803,12 +815,11 @@ def getPeersLatestHandshake(self):
803815
else:
804816
status = "stopped"
805817
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
807819
, (str(minus).split(".", maxsplit=1)[0], status, latestHandshake[count],))
808820
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
810822
, (status, latestHandshake[count],))
811-
sqldb.commit()
812823
count += 2
813824

814825

@@ -1284,16 +1295,20 @@ def _regexMatch(regex, text):
12841295
return pattern.search(text) is not None
12851296

12861297

1287-
def _getConfigurationList() -> [WireguardConfiguration]:
1288-
configurations = {}
1298+
def _getConfigurationList():
1299+
# configurations = {}
12891300
for i in os.listdir(WG_CONF_PATH):
12901301
if _regexMatch("^(.{1,}).(conf)$", i):
12911302
i = i.replace('.conf', '')
12921303
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)
12941309
except WireguardConfiguration.InvalidConfigurationFileException as e:
12951310
print(f"{i} have an invalid configuration file.")
1296-
return configurations
1311+
12971312

12981313

12991314
def _checkIPWithRange(ip):
@@ -1354,8 +1369,7 @@ def _generatePrivateKey() -> [bool, str]:
13541369
except subprocess.CalledProcessError:
13551370
return False, None
13561371

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]:
13591373
if configName not in WireguardConfigurations.keys():
13601374
return False, None
13611375
configuration = WireguardConfigurations[configName]
@@ -1387,8 +1401,9 @@ def _getWireguardConfigurationAvailableIP(configName: str) -> tuple[bool, list[s
13871401
if h not in existedAddress:
13881402
availableAddress.append(ipaddress.ip_network(h).compressed)
13891403
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
13921407
return True, availableAddress
13931408

13941409
return False, None
@@ -1534,7 +1549,7 @@ def API_SignOut():
15341549

15351550
@app.route(f'{APP_PREFIX}/api/getWireguardConfigurations', methods=["GET"])
15361551
def API_getWireguardConfigurations():
1537-
# WireguardConfigurations = _getConfigurationList()
1552+
_getConfigurationList()
15381553
return ResponseObject(data=[wc for wc in WireguardConfigurations.values()])
15391554

15401555

@@ -1841,17 +1856,7 @@ def API_addPeers(configName):
18411856
if i not in availableIps[1]:
18421857
return ResponseObject(False, f"This IP is not available: {i}")
18431858

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)}])
18551860
found, peer = config.searchPeer(public_key)
18561861
if found:
18571862
return peer.updatePeer(name, private_key, preshared_key, dns_addresses, ",".join(allowed_ips),
@@ -2188,7 +2193,7 @@ def gunicornConfig():
21882193

21892194

21902195
WireguardConfigurations: dict[str, WireguardConfiguration] = {}
2191-
WireguardConfigurations = _getConfigurationList()
2196+
_getConfigurationList()
21922197

21932198
def startThreads():
21942199
bgThread = threading.Thread(target=backGroundThread)

0 commit comments

Comments
 (0)