1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
|
import threading
from ctypes import c_int
from typing import Any, Callable, Dict, Iterator, List, Optional, Tuple
from eduvpn_common.discovery import DiscoOrganizations, DiscoServers, get_disco_organizations, get_disco_servers
from eduvpn_common.event import EventHandler
from eduvpn_common.loader import initialize_functions, load_lib
from eduvpn_common.server import Profiles, Server, get_transition_server, get_servers
from eduvpn_common.state import State, StateType
from eduvpn_common.types import ReadRxBytes, VPNStateChange, decode_res, encode_args, get_data_error, get_bool
class EduVPN(object):
"""The main class used to communicate with the Go library.
It registers the client with the library and then calls the needed appropriate functions
:param name: str: The name of the client. For commonly used names, see https://git.sr.ht/~fkooman/vpn-user-portal/tree/v3/item/src/OAuth/ClientDb.php. E.g. org.eduvpn.app.linux, if this name has "letsconnect" in it, then it is a Let's Connect! variant
:param config_directory: str: The directory (absolute/relative) where to store the files
:param language: str: The language of the client, e.g. en
"""
def __init__(self, name: str, config_directory: str, language: str):
self.name = name
self.config_directory = config_directory
self.language = language
# Load the library
self.lib = load_lib()
initialize_functions(self.lib)
self.event_handler = EventHandler(self.lib)
# Callbacks that need to wait for specific events
# The ask profile callback needs to wait for the UI thread to select a profile
# This is stored in the profile_event
self.profile_event: Optional[threading.Event] = None
self.location_event: Optional[threading.Event] = None
@self.event.on(State.ASK_PROFILE, StateType.WAIT)
def wait_profile_event(old_state: int, profiles: Profiles):
"""This functions waits until the ask location thread event is finished
:param old_state: int: The old state of the profiles event
:param profiles: Profiles: The profiles
"""
if self.profile_event:
self.profile_event.wait()
@self.event.on(State.ASK_LOCATION, StateType.WAIT)
def wait_location_event(old_state: int, locations: List[str]):
"""This functions waits until the location thread event is finished
:param old_state: int: The old state of the location event
:param locations: List[str]: The locations
"""
if self.location_event:
self.location_event.wait()
def go_function(self, func: Any, *args: Iterator, decode_func: Optional[Callable] = None) -> Any:
"""Call an internal go function and properly forward the arguments.
Also handles decoding the result
:param func: Any: The Go function to call from the shared library
:param \*args: Iterator: The arguments to call the function with
:param decode_func: Optional[Callable]: (Default value = None): The function to decode the result into a Python type
:meta private:
"""
# The functions all have at least one arg type which is the name of the client
args_gen = encode_args(list(args), func.argtypes[1:])
res = func(self.name.encode("utf-8"), *(args_gen))
if decode_func is None:
return decode_res(func.restype)(self.lib, res)
else:
return decode_func(self.lib, res)
def cancel_oauth(self) -> None:
"""Cancel the OAuth process"""
cancel_oauth_err = self.go_function(self.lib.CancelOAuth)
if cancel_oauth_err:
raise cancel_oauth_err
def deregister(self) -> None:
"""Deregister the Go shared library.
This removes the object from internal bookkeeping and saves the configuration
"""
self.go_function(self.lib.Deregister)
remove_as_global_object(self)
def register(self, debug: bool = False) -> None:
"""Register the Go shared library.
This makes sure the FSM is initialized and that we can call Go functions
:param debug: bool: (Default value = False): Whether or not we want to enable debug logging
"""
if not add_as_global_object(self):
raise Exception("Already registered")
register_err = self.go_function(
self.lib.Register,
self.config_directory,
self.language,
state_callback,
debug,
)
if register_err:
raise register_err
def get_disco_servers(self) -> Optional[DiscoServers]:
"""Get the discovery servers
:raises WrappedError: An error by the Go library
:return: The disco Servers if any
:rtype: Optional[DiscoServers]
"""
servers, servers_err = self.go_function(
self.lib.GetDiscoServers,
decode_func=lambda lib, x: get_data_error(lib, x, get_disco_servers),
)
if servers_err:
raise servers_err
return servers
def get_disco_organizations(self) -> Optional[DiscoOrganizations]:
"""Get the discovery organizations
:raises WrappedError: An error by the Go library
:return: The discovery Organizations if any
:rtype: Optional[DiscoOrganizations]
"""
organizations, organizations_err = self.go_function(
self.lib.GetDiscoOrganizations,
decode_func=lambda lib, x: get_data_error(lib, x, get_disco_organizations),
)
if organizations_err:
raise organizations_err
return organizations
def add_institute_access(self, url: str) -> None:
"""Add an institute access server
:param url: str: The URL for the institute access server. Use the exact base_url as returned by Discovery
:raises WrappedError: An error by the Go library
"""
add_err = self.go_function(self.lib.AddInstituteAccess, url)
if add_err:
raise add_err
def add_secure_internet_home(self, org_id: str) -> None:
"""Add a secure internet server
:param org_id: str: The organization ID of the secure internet server. Use the exact organization as returned by Discovery
:raises WrappedError: An error by the Go library
"""
self.location_event = threading.Event()
add_err = self.go_function(self.lib.AddSecureInternetHomeServer, org_id)
if add_err:
raise add_err
def add_custom_server(self, url: str) -> None:
"""Add a custom server
:param url: str: The base URL of the server
:raises WrappedError: An error by the Go library
"""
add_err = self.go_function(self.lib.AddCustomServer, url)
if add_err:
raise add_err
def remove_secure_internet(self) -> None:
"""Remove the secure internet server
:raises WrappedError: An error by the Go library
"""
remove_err = self.go_function(self.lib.RemoveSecureInternet)
if remove_err:
raise remove_err
def remove_institute_access(self, url: str) -> None:
"""Remove an institute access server
:param url: str: The URL for the institute access server. Use the exact base_url as returned by Discovery
:raises WrappedError: An error by the Go library
"""
remove_err = self.go_function(self.lib.RemoveInstituteAccess, url)
if remove_err:
raise remove_err
def remove_custom_server(self, url: str) -> None:
"""Remove a custom server
:param url: str: The base URL of the server
:raises WrappedError: An error by the Go library
"""
remove_err = self.go_function(self.lib.RemoveCustomServer, url)
if remove_err:
raise remove_err
def get_config(self, identifier: str, func: Any, prefer_tcp: bool = False) -> Tuple[str, str]:
"""Get an OpenVPN/WireGuard configuration from the server
:param identifier: str: The identifier of the server, e.g. URL or ORG ID
:param func: Any: The Go function to call
:param prefer_tcp: bool: (Default value = False): Whether or not to prefer TCP
:meta private:
:raises WrappedError: An error by the Go library
:return: The configuration and configuration type ('openvpn' or 'wireguard')
:rtype: Tuple[str, str]
"""
# Because it could be the case that a profile callback is started, store a threading event
# In the constructor, we have defined a wait event for Ask_Profile, this waits for this event to be set
# The event is set in self.set_profile
self.profile_event = threading.Event()
config, config_type, config_err = self.go_function(func, identifier, prefer_tcp)
self.profile_event = None
self.location_event = None
if config_err:
raise config_err
return config, config_type
def get_config_custom_server(
self, url: str, prefer_tcp: bool = False
) -> Tuple[str, str]:
"""Get an OpenVPN/WireGuard configuration from a custom server
:param url: str: The URL of the custom server
:param prefer_tcp: bool: (Default value = False): Whether or not to prefer TCP
:raises WrappedError: An error by the Go library
:return: The configuration and configuration type ('openvpn' or 'wireguard')
:rtype: Tuple[str, str]
"""
return self.get_config(url, self.lib.GetConfigCustomServer, prefer_tcp)
def get_config_institute_access(
self, url: str, prefer_tcp: bool = False
) -> Tuple[str, str]:
"""Get an OpenVPN/WireGuard configuration from an institute access server
:param url: str: The URL of the institute access server. Use the one from Discovery
:param prefer_tcp: bool: (Default value = False): Whether or not to prefer TCP
:raises WrappedError: An error by the Go library
:return: The configuration and configuration type ('openvpn' or 'wireguard')
:rtype: Tuple[str, str]
"""
return self.get_config(url, self.lib.GetConfigInstituteAccess, prefer_tcp)
def get_config_secure_internet(
self, org_id: str, prefer_tcp: bool = False
) -> Tuple[str, str]:
"""Get an OpenVPN/WireGuard configuration from a secure internet server
:param org_id: str: The organization ID of the secure internet server. Use the one from Discovery
:param prefer_tcp: bool: (Default value = False): Whether or not to prefer TCP
:raises WrappedError: An error by the Go library
"""
return self.get_config(org_id, self.lib.GetConfigSecureInternet, prefer_tcp)
def go_back(self) -> None:
"""Go back in the FSM"""
# Ignore the error
self.go_function(self.lib.GoBack)
def set_connected(self) -> None:
"""Set the FSM to connected
:raises WrappedError: An error by the Go library
"""
connect_err = self.go_function(self.lib.SetConnected)
if connect_err:
raise connect_err
def set_disconnecting(self) -> None:
"""Set the FSM to disconnecting
:raises WrappedError: An error by the Go library
"""
disconnecting_err = self.go_function(self.lib.SetDisconnecting)
if disconnecting_err:
raise disconnecting_err
def set_connecting(self) -> None:
"""Set the FSM to connecting
:raises WrappedError: An error by the Go library
"""
connecting_err = self.go_function(self.lib.SetConnecting)
if connecting_err:
raise connecting_err
def set_disconnected(self, cleanup: bool = True) -> None:
"""Set the FSM to disconnected
:param cleanup: bool: (Default value = True): Whether or not to call /disconnect to the server. This invalidates the OpenVPN/WireGuard configuration
:raises WrappedError: An error by the Go library
"""
disconnect_err = self.go_function(self.lib.SetDisconnected, cleanup)
if disconnect_err:
raise disconnect_err
def set_search_server(self) -> None:
"""Set the FSM to search server
:raises WrappedError: An error by the Go library
"""
search_err = self.go_function(self.lib.SetSearchServer)
if search_err:
raise search_err
def remove_class_callbacks(self, cls: Any) -> None:
"""Remove class callbacks
:param cls: Any: The class to remove callbacks for
"""
self.event_handler.change_class_callbacks(cls, add=False)
def register_class_callbacks(self, cls: Any) -> None:
"""Register class callbacks
:param cls: Any: The class to register callbacks for
"""
self.event_handler.change_class_callbacks(cls)
@property
def event(self) -> EventHandler:
"""The property that gets the event handler
:return: The event handler
:rtype: EventHandler
"""
return self.event_handler
def callback(self, old_state: State, new_state: State, data: Any) -> bool:
"""Run an event callback
:param old_state: State: The previous state
:param new_state: State: The new state
:param data: Any: The data to pass to the event
"""
return self.event.run(old_state, new_state, data)
def set_profile(self, profile_id: str) -> None:
"""Set the profile of the current server
:param profile_id: str: The profile id of the chosen profile for the server
:raises WrappedError: An error by the Go library
"""
# Set the profile id
profile_err = self.go_function(self.lib.SetProfileID, profile_id)
# If there is a profile event, set it so that the wait callback finishes
# And so that the Go code can move to the next state
if self.profile_event:
self.profile_event.set()
if profile_err:
raise profile_err
def change_secure_location(self) -> None:
"""Change the secure location. This calls the necessary events
:raises WrappedError: An error by the Go library
"""
# Set the location by country code
self.location_event = threading.Event()
location_err = self.go_function(self.lib.ChangeSecureLocation)
if location_err:
raise location_err
def set_secure_location(self, country_code: str) -> None:
"""Set the secure location
:param country_code: str: The country code of the new location
:raises WrappedError: An error by the Go library
"""
# Set the location by country code
location_err = self.go_function(self.lib.SetSecureLocation, country_code)
# If there is a location event, set it so that the wait callback finishes
# And so that the Go code can move to the next state
if self.location_event:
self.location_event.set()
if location_err:
raise location_err
def renew_session(self) -> None:
"""Renew the session. This invalidates the tokens and runs the necessary callbacks to log back in
:raises WrappedError: An error by the Go library
"""
renew_err = self.go_function(self.lib.RenewSession)
if renew_err:
raise renew_err
def set_support_wireguard(self, support: bool) -> None:
"""Indicates whether or not the OS supports WireGuard connections.
:param support: bool: whether or not wireguard is supported
:raises WrappedError: An error by the Go library
"""
support_err = self.go_function(self.lib.SetSupportWireguard, support)
if support_err:
raise support_err
def should_renew_button(self) -> bool:
"""Whether or not the UI should show the renew button
:return: Whether or not the return button should be shown
:rtype: bool
"""
return self.go_function(self.lib.ShouldRenewButton)
def in_fsm_state(self, state_id: State) -> bool:
"""Check whether or not the FSM is in the provided state
:param state_id: State: The state to check for
:return: Whether or not the FSM is in the provided state
:rtype: bool
"""
return self.go_function(self.lib.InFSMState, state_id)
def get_current_server(self) -> Optional[Server]:
"""Get the current server
:return: The current servers if there is any
:rtype: Optional[List[Servers]]
"""
server, server_err = self.go_function(
self.lib.GetCurrentServer,
decode_func=lambda lib, x: get_data_error(lib, x, get_transition_server),
)
if server_err:
raise server_err
return server
def get_saved_servers(self) -> Optional[List[Server]]:
"""Get a list of saved servers
:return: The list of Servers if there are any
:rtype: Optional[List[Servers]]
"""
servers, servers_err = self.go_function(
self.lib.GetSavedServers,
decode_func=lambda lib, x: get_data_error(lib, x, get_servers),
)
if servers_err:
raise servers_err
return servers
def start_failover(self, gateway: str, wg_mtu: int, readrxbytes: ReadRxBytes) -> bool:
dropped, dropped_err = self.go_function(
self.lib.StartFailover, gateway, wg_mtu, readrxbytes,
decode_func=lambda lib, x: get_data_error(lib, x, get_bool),
)
if dropped_err:
raise dropped_err
return dropped
def cancel_failover(self):
cancel_err = self.go_function(self.lib.CancelFailover)
if cancel_err:
raise cancel_err
eduvpn_objects: Dict[str, EduVPN] = {}
@VPNStateChange
def state_callback(name: bytes, old_state: int, new_state: int, data: Any) -> int:
"""The internal callback that is passed to the Go library
:param name: bytes: The name of the client
:param old_state: int: The old state
:param new_state: int: The new state
:param data: Any: The data that still needs to be converted
:meta private:
"""
name_decoded = name.decode()
if name_decoded not in eduvpn_objects:
return 0
handled = eduvpn_objects[name_decoded].callback(State(old_state), State(new_state), data)
if handled:
return 1
return 0
def add_as_global_object(eduvpn: EduVPN) -> bool:
"""Add the provided parameter to the global objects lists so we can call the callback
:param eduvpn: EduVPN: The class to add
:meta private:
:return: Whether or not the object was added
:rtype: bool
"""
global eduvpn_objects
if eduvpn.name not in eduvpn_objects:
eduvpn_objects[eduvpn.name] = eduvpn
return True
return False
def remove_as_global_object(eduvpn: EduVPN) -> None:
"""Remove the provided parameter from the global objects list
:param eduvpn: EduVPN: The class to remove
:meta private:
"""
global eduvpn_objects
eduvpn_objects.pop(eduvpn.name, None)
|