Debian Codegraph @

asusrouter/modules/vpnc.py

raw
1 """VPNC module. This module is compatible with VPN Fusion in AsusWRT 388+."""
2
3 from __future__ import annotations
4
5 from collections.abc import Awaitable, Callable
6 from enum import Enum, IntEnum
7 import logging
8 from typing import Any
9
10 from asusrouter.modules.data import AsusData, AsusDataState
11 from asusrouter.modules.openvpn import AsusOVPNClient
12 from asusrouter.modules.wireguard import AsusWireGuardClient
13 from asusrouter.tools.converters import get_arguments
14
15 _LOGGER = logging.getLogger(__name__)
16
17
18 REQUIRE_STATE = True
19
20
21 class AsusVPNC(IntEnum):
22 """Asus VPN Fusion state."""
23
24 UNKNOWN = -999
25 CONNECTING = 1
26 CONNECTED = 2
27 ERROR = 4
28 DISCONNECTED = 5
29
30 OFF = DISCONNECTED
31 ON = CONNECTING
32
33
34 class AsusVPNType(str, Enum):
35 """Asus VPN Fusion type."""
36
37 UNKNOWN = "Unknown"
38 L2TP = "L2TP"
39 OPENVPN = "OpenVPN"
40 PPTP = "PPTP"
41 SURFSHARK = "Surfshark"
42 WIREGUARD = "WireGuard"
43
44
45 async def set_state(
46 callback: Callable[..., Awaitable[bool]],
47 state: AsusVPNC | AsusOVPNClient | AsusWireGuardClient,
48 **kwargs: Any,
49 ) -> bool:
50 """Set the VPN state."""
51
52 # Match the state to call the correct function
53 match state:
54 case a if isinstance(a, AsusVPNC):
55 return await set_state_vpnc(callback, a, **kwargs)
56 case a if isinstance(a, AsusOVPNClient | AsusWireGuardClient):
57 return await set_state_other(callback, a, **kwargs)
58 case _:
59 try:
60 _LOGGER.debug(
61 "Unknown state %s. Cannot find proper handler", state.name
62 )
63 except AttributeError:
64 _LOGGER.debug(
65 "Unknown state %s. Cannot find proper handler", state
66 )
67 return False
68
69
70 VPNC_STATE_MAPPING = {
71 AsusVPNC.ON: ("restart_vpnc", 1),
72 AsusVPNC.OFF: ("stop_vpnc", 0),
73 }
74
75
76 async def set_state_vpnc(
77 callback: Callable[..., Awaitable[bool]],
78 state: AsusVPNC | None,
79 **kwargs: Any,
80 ) -> bool:
81 """Set the VPN Fusion state."""
82
83 # Check if state is available
84 if not isinstance(state, AsusVPNC):
85 _LOGGER.debug("No state found in arguments")
86 return False
87
88 # Get the arguments
89 vpnc_unit = get_arguments("vpnc_unit", **kwargs)
90
91 if not isinstance(vpnc_unit, int):
92 _LOGGER.debug("No VPN Fusion unit found in arguments")
93 return False
94
95 # Service arguments
96 service_arguments: dict[str, Any] = {"vpnc_unit": vpnc_unit}
97
98 # Get the raw state from router
99 router_state = kwargs.get("router_state", {})
100
101 # Clientlist is needed to update the state (all clients are in the list).
102 # If not available, we cannot update the state.
103 vpnc_clientlist = router_state.get(
104 AsusData.VPNC_CLIENTLIST, AsusDataState()
105 ).data
106 if not vpnc_clientlist or vpnc_clientlist == "":
107 _LOGGER.debug("No VPN Fusion client list found in router state")
108 return False
109
110 # Get service and binary state
111 service, binary_state = VPNC_STATE_MAPPING.get(state, (None, None))
112 if service is None:
113 _LOGGER.debug("Unknown state %s", state)
114 return False
115
116 # Update the clientlist
117 vpnc_clientlist = _get_argument_clientlist(
118 vpnc_clientlist, vpnc_unit, binary_state
119 )
120 if not vpnc_clientlist:
121 _LOGGER.debug("Something went wrong with creating a new clientlist")
122 return False
123
124 service_arguments["vpnc_clientlist"] = vpnc_clientlist
125
126 _LOGGER.debug(
127 "Triggering state set with parameters: service=%s, arguments=%s",
128 service,
129 service_arguments,
130 )
131
132 # Call the service
133 return await callback(
134 service=service,
135 arguments=service_arguments,
136 apply=True,
137 expect_modify=kwargs.get("expect_modify", False),
138 )
139
140
141 OTHER_STATE_MAPPING = {
142 AsusOVPNClient.ON: AsusVPNC.ON,
143 AsusOVPNClient.OFF: AsusVPNC.OFF,
144 AsusWireGuardClient.ON: AsusVPNC.ON,
145 AsusWireGuardClient.OFF: AsusVPNC.OFF,
146 }
147
148
149 async def set_state_other(
150 callback: Callable[..., Awaitable[bool]],
151 state: AsusOVPNClient | AsusWireGuardClient,
152 **kwargs: Any,
153 ) -> bool:
154 """Set the Open VPN state."""
155
156 # Check if state is available
157 if not isinstance(
158 state, AsusOVPNClient | AsusWireGuardClient
159 ) or state.value not in (0, 1):
160 _LOGGER.debug("No state found in arguments")
161 return False
162
163 # Get the arguments
164 vpn_id = get_arguments("id", **kwargs)
165
166 if not isinstance(vpn_id, int):
167 _LOGGER.debug("No VPN id found in arguments")
168 return False
169
170 # Get the raw state from router
171 router_state = kwargs.get("router_state", {})
172
173 # Clientlist is needed to update the state (all clients are in the list).
174 # If not available, we cannot update the state.
175 vpnc_data = router_state.get(AsusData.VPNC, AsusDataState()).data
176
177 vpnc_unit = _find_vpnc_unit(
178 vpnc_data=vpnc_data, client_type=state, client_id=vpn_id
179 )
180
181 # Convert state
182 vpnc_state = OTHER_STATE_MAPPING.get(state)
183
184 return await set_state_vpnc(
185 callback=callback,
186 state=vpnc_state,
187 vpnc_unit=vpnc_unit,
188 expect_modify=kwargs.get("expect_modify", False),
189 router_state=router_state,
190 )
191
192
193 def _get_argument_clientlist(
194 clientlist: str | None, vpnc_unit: int | None, state: int | None
195 ) -> str | None:
196 """Generate the clientlist argument."""
197
198 if (
199 not clientlist
200 or clientlist == ""
201 or vpnc_unit is None
202 or state is None
203 ):
204 return None
205
206 # Split clientlist properly
207 clients: list[str] = clientlist.split("<")
208 if len(clients) <= vpnc_unit:
209 return None
210 client = clients[vpnc_unit]
211
212 # In the client data get the 6th parameter which is the state
213 client_param = client.split(">")
214 client_param[5] = str(state)
215
216 # Assemble client
217 client = ">".join(client_param)
218 # Assemble clientlist
219 clients[vpnc_unit] = client
220 return "<".join(clients)
221
222
223 def _find_vpnc_unit(
224 vpnc_data: dict[AsusVPNType, dict[int, dict[str, Any]]] | None,
225 client_type: AsusOVPNClient | AsusWireGuardClient,
226 client_id: int,
227 ) -> int | None:
228 """Find vpnc unit by VPN client_id."""
229
230 if vpnc_data is None:
231 return None
232
233 match client_type:
234 case a if isinstance(a, AsusOVPNClient):
235 search_type = AsusVPNType.OPENVPN
236 case a if isinstance(a, AsusWireGuardClient):
237 search_type = AsusVPNType.WIREGUARD
238 case _:
239 _LOGGER.debug("Unknown client type %s", client_type)
240 return None
241
242 if search_type not in vpnc_data:
243 return None
244
245 if client_id not in vpnc_data[search_type]:
246 return None
247
248 return vpnc_data[search_type][client_id].get("vpnc_unit")