atomicshop 3.2.13__py3-none-any.whl → 3.3.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of atomicshop might be problematic. Click here for more details.

@@ -3,6 +3,7 @@ import multiprocessing
3
3
  import time
4
4
  import datetime
5
5
  import os
6
+ import sys
6
7
  import logging
7
8
 
8
9
  import atomicshop # Importing atomicshop package to get the version of the package.
@@ -10,9 +11,10 @@ import atomicshop # Importing atomicshop package to get the version of the pac
10
11
  from .. import filesystem, on_exit, print_api, networks, dns
11
12
  from ..permissions import permissions
12
13
  from ..python_functions import get_current_python_version_string, check_python_version_compliance
13
- from ..wrappers.socketw import socket_wrapper, dns_server, base
14
+ from ..wrappers.socketw import socket_wrapper, dns_server, base, statistics_csv
14
15
  from ..wrappers.loggingw import loggingw
15
16
  from ..wrappers.ctyping import win_console
17
+ from ..basics import multiprocesses
16
18
 
17
19
  from .connection_thread_worker import thread_worker_main
18
20
  from . import config_static, recs_files
@@ -64,13 +66,16 @@ IS_SET_DNS_GATEWAY: bool = False
64
66
  RECS_PROCESS_INSTANCE: multiprocessing.Process = None
65
67
 
66
68
 
69
+ STATISTICS_LOGGER_NAME: str = 'statistics'
67
70
  EXCEPTIONS_CSV_LOGGER_NAME: str = 'exceptions'
68
71
  EXCEPTIONS_CSV_LOGGER_HEADER: str = 'time,exception'
69
72
  # noinspection PyTypeChecker
70
73
  MITM_ERROR_LOGGER: loggingw.ExceptionCsvLogger = None
71
74
 
72
- # Create logger's queue.
75
+ # Create logger queues.
73
76
  NETWORK_LOGGER_QUEUE: multiprocessing.Queue = multiprocessing.Queue()
77
+ STATISTICS_CSV_LOGGER_QUEUE: multiprocessing.Queue = multiprocessing.Queue()
78
+ EXCEPTIONS_CSV_LOGGER_QUEUE: multiprocessing.Queue = multiprocessing.Queue()
74
79
 
75
80
  # Create finalization queue for the rec archiving process.
76
81
  FINALIZE_RECS_ARCHIVE_QUEUE: multiprocessing.Queue = multiprocessing.Queue()
@@ -304,6 +309,7 @@ def get_ipv4s_for_tcp_server():
304
309
  if port in ports_to_create_ips_for:
305
310
  engine.port_target_dict[port]['ip'] = engine_ips.pop(0)
306
311
 
312
+
307
313
  def mitm_server(config_file_path: str, script_version: str):
308
314
  on_exit.register_exit_handler(exit_cleanup, at_exit=False, kill_signal=False)
309
315
 
@@ -323,7 +329,11 @@ def mitm_server(config_file_path: str, script_version: str):
323
329
 
324
330
  global MITM_ERROR_LOGGER
325
331
  MITM_ERROR_LOGGER = loggingw.ExceptionCsvLogger(
326
- logger_name=EXCEPTIONS_CSV_LOGGER_NAME, directory_path=config_static.LogRec.logs_path)
332
+ logger_name=EXCEPTIONS_CSV_LOGGER_NAME,
333
+ directory_path=config_static.LogRec.logs_path,
334
+ log_queue=EXCEPTIONS_CSV_LOGGER_QUEUE,
335
+ add_queue_handler_start_listener_multiprocessing=True,
336
+ )
327
337
 
328
338
  # Create folders.
329
339
  filesystem.create_directory(config_static.LogRec.logs_path)
@@ -334,10 +344,11 @@ def mitm_server(config_file_path: str, script_version: str):
334
344
 
335
345
  network_logger_name = config_static.MainConfig.LOGGER_NAME
336
346
 
337
- # If we exit the function, we need to stop the listener: network_logger_queue_listener.stop()
338
- network_logger_queue_listener = loggingw.create_logger(
339
- get_queue_listener=True,
347
+ # Start the network logger and its queue listener.
348
+ _ = loggingw.create_logger(
349
+ logger_name=network_logger_name,
340
350
  log_queue=NETWORK_LOGGER_QUEUE,
351
+ start_queue_listener_multiprocess_add_queue_handler=True,
341
352
  file_path=f'{config_static.LogRec.logs_path}{os.sep}{network_logger_name}.txt',
342
353
  add_stream=True,
343
354
  add_timedfile=True,
@@ -345,13 +356,16 @@ def mitm_server(config_file_path: str, script_version: str):
345
356
  formatter_filehandler='DEFAULT',
346
357
  backupCount=config_static.LogRec.store_logs_for_x_days)
347
358
 
348
- network_logger_with_queue_handler: logging.Logger = loggingw.create_logger(
349
- logger_name=network_logger_name,
359
+ """
360
+ # Create this in other multiprocesses (You need to pass only the logger_name and log_queue to the other process):
361
+ logger = loggingw.create_logger(
362
+ logger_name=logger_name,
350
363
  add_queue_handler=True,
351
- log_queue=NETWORK_LOGGER_QUEUE)
364
+ log_queue=NETWORK_LOGGER_QUEUE
365
+ )
366
+ """
352
367
 
353
368
  # Initiate Listener logger, which is a child of network logger, so he uses the same settings and handlers
354
- listener_logger: logging.Logger = loggingw.get_logger_with_level(f'{network_logger_name}.listener')
355
369
  system_logger: logging.Logger = loggingw.get_logger_with_level(f'{network_logger_name}.system')
356
370
 
357
371
  if config_static.LogRec.enable_request_response_recordings_in_logs:
@@ -372,7 +386,7 @@ def mitm_server(config_file_path: str, script_version: str):
372
386
  error_type=True, color="red", logger=system_logger, logger_method='critical')
373
387
  # Wait for the message to be printed and saved to file.
374
388
  time.sleep(1)
375
- network_logger_queue_listener.stop()
389
+ # network_logger_queue_listener.stop()
376
390
  return 1
377
391
 
378
392
  # Logging Startup information.
@@ -380,66 +394,100 @@ def mitm_server(config_file_path: str, script_version: str):
380
394
 
381
395
  print_api.print_api("Press [Ctrl]+[C] to stop.", color='blue')
382
396
 
397
+ multiprocess_list: list[multiprocessing.Process] = list()
398
+ # noinspection PyTypeHints
399
+ is_ready_multiprocessing_event_list: list[multiprocessing.Event] = list()
400
+
383
401
  # === Initialize DNS module ====================================================================================
384
402
  if config_static.DNSServer.enable:
403
+ is_dns_process_ready: multiprocessing.Event = multiprocessing.Event()
404
+ is_ready_multiprocessing_event_list.append(is_dns_process_ready)
405
+
406
+ dns_server_kwargs: dict = dict(
407
+ listening_address=config_static.DNSServer.listening_address,
408
+ log_directory_path=config_static.LogRec.logs_path,
409
+ backupCount_log_files_x_days=config_static.LogRec.store_logs_for_x_days,
410
+ forwarding_dns_service_ipv4=config_static.DNSServer.forwarding_dns_service_ipv4,
411
+ forwarding_dns_service_port=config_static.DNSServer.forwarding_dns_service_port,
412
+ resolve_by_engine=(
413
+ config_static.DNSServer.resolve_by_engine, config_static.ENGINES_LIST),
414
+ resolve_regular_pass_thru=config_static.DNSServer.resolve_regular_pass_thru,
415
+ resolve_all_domains_to_ipv4=(
416
+ config_static.DNSServer.resolve_all_domains_to_ipv4_enable, config_static.DNSServer.target_ipv4),
417
+ offline_mode=config_static.MainConfig.offline,
418
+ cache_timeout_minutes=config_static.DNSServer.cache_timeout_minutes,
419
+ logging_queue=NETWORK_LOGGER_QUEUE,
420
+ logger_name=network_logger_name,
421
+ is_ready_multiprocessing=is_dns_process_ready
422
+ )
423
+
385
424
  dns_process = multiprocessing.Process(
386
425
  target=dns_server.start_dns_server_multiprocessing_worker,
387
- kwargs={
388
- 'listening_address': config_static.DNSServer.listening_address,
389
- 'log_directory_path': config_static.LogRec.logs_path,
390
- 'backupCount_log_files_x_days': config_static.LogRec.store_logs_for_x_days,
391
- 'forwarding_dns_service_ipv4': config_static.DNSServer.forwarding_dns_service_ipv4,
392
- 'forwarding_dns_service_port': config_static.DNSServer.forwarding_dns_service_port,
393
- 'resolve_by_engine': (
394
- config_static.DNSServer.resolve_by_engine, config_static.ENGINES_LIST),
395
- 'resolve_regular_pass_thru': config_static.DNSServer.resolve_regular_pass_thru,
396
- 'resolve_all_domains_to_ipv4': (
397
- config_static.DNSServer.resolve_all_domains_to_ipv4_enable, config_static.DNSServer.target_ipv4),
398
- 'offline_mode': config_static.MainConfig.offline,
399
- 'cache_timeout_minutes': config_static.DNSServer.cache_timeout_minutes,
400
- 'logging_queue': NETWORK_LOGGER_QUEUE,
401
- 'logger_name': network_logger_name
402
- },
403
- name="dns_server")
404
- dns_process.daemon = True
426
+ kwargs=dns_server_kwargs,
427
+ name="dns_server",
428
+ daemon=True
429
+ )
405
430
  dns_process.start()
406
431
 
407
- # Wait for the DNS server to start and do the port test.
408
- is_alive: bool = False
409
- max_wait_time: int = 5
410
- while not is_alive:
411
- is_alive = dns_process.is_alive()
412
- time.sleep(1)
413
- max_wait_time -= 1
414
- if max_wait_time == 0:
415
- message = "DNS Server process didn't start."
416
- print_api.print_api(message, error_type=True, color="red", logger=system_logger)
417
- # Wait for the message to be printed and saved to file.
418
- time.sleep(1)
419
- network_logger_queue_listener.stop()
420
- return 1
421
-
422
- # Now we can check if the process wasn't terminated after the check.
423
- max_wait_time: int = 5
424
- while max_wait_time > 0:
425
- is_alive = dns_process.is_alive()
426
-
427
- if not is_alive:
428
- message = "DNS Server process terminated."
429
- print_api.print_api(message, error_type=True, color="red", logger=system_logger)
430
- # Wait for the message to be printed and saved to file.
431
- time.sleep(1)
432
- network_logger_queue_listener.stop()
433
- return 1
432
+ multiprocess_list.append(dns_process)
434
433
 
435
- time.sleep(1)
436
- max_wait_time -= 1
437
434
 
438
435
  # === EOF Initialize DNS module ================================================================================
439
436
  # === Initialize TCP Server ====================================================================================
440
437
  if config_static.TCPServer.enable:
441
- try:
442
- socket_wrapper_instance = socket_wrapper.SocketWrapper(
438
+ # Get the default network adapter configuration and set the one from config.
439
+ # We set the virtual IPs in the network adapter here, so the server multiprocessing processes can listen on them.
440
+ setting_result: int = _add_virtual_ips_set_default_dns_gateway(system_logger)
441
+ if setting_result != 0:
442
+ print_api.print_api("Failed to set the default DNS gateway.", error_type=True, color="red",
443
+ logger=system_logger)
444
+ # Wait for the message to be printed and saved to file.
445
+ time.sleep(1)
446
+ return setting_result
447
+
448
+ # Start statistics CSV Queue listener and the logger.
449
+ _ = statistics_csv.StatisticsCSVWriter(
450
+ directory_path=config_static.LogRec.logs_path,
451
+ log_queue=STATISTICS_CSV_LOGGER_QUEUE,
452
+ add_queue_handler_start_listener_multiprocessing=True)
453
+
454
+ no_engine_usage_enable: bool = config_static.TCPServer.no_engines_usage_to_listen_addresses_enable
455
+ no_engines_listening_address_list: list[str] = config_static.TCPServer.no_engines_listening_address_list
456
+
457
+ # If engines were passed, we will use the listening addresses from the engines.
458
+ listening_interfaces: list[dict] = list()
459
+ if not no_engine_usage_enable:
460
+ for engine in config_static.ENGINES_LIST:
461
+ # Combine the domain and port dicts.
462
+ connection_dict: dict = {**engine.domain_target_dict, **engine.port_target_dict}
463
+
464
+ # Start all the regular listening interfaces.
465
+ for domain_or_port, ip_port_dict in connection_dict.items():
466
+ current_interface_dict: dict = {
467
+ 'engine': engine,
468
+ 'process_name': f'tcp_server-{engine.engine_name}-{domain_or_port}',
469
+ 'ip': ip_port_dict['ip'],
470
+ 'port': int(ip_port_dict['port'])
471
+ }
472
+ listening_interfaces.append(current_interface_dict)
473
+ else:
474
+ # If no engines were passed, we will use the listening addresses from the configuration.
475
+ for address in no_engines_listening_address_list:
476
+ listening_ip_address, port_str = address.split(':')
477
+ current_interface_dict: dict = {
478
+ 'engine': None, # No engine for this address.
479
+ 'process_name': f'tcp_server-{listening_ip_address}_{port_str}',
480
+ 'ip': listening_ip_address,
481
+ 'port': int(port_str)
482
+ }
483
+ listening_interfaces.append(current_interface_dict)
484
+
485
+ # Starting the TCP server multiprocessing processes.
486
+ for interface_dict in listening_interfaces:
487
+ socket_wrapper_kwargs: dict = dict(
488
+ ip_address=interface_dict['ip'],
489
+ port=interface_dict['port'],
490
+ engine=interface_dict['engine'],
443
491
  ca_certificate_name=config_static.MainConfig.ca_certificate_name,
444
492
  ca_certificate_filepath=config_static.MainConfig.ca_certificate_filepath,
445
493
  ca_certificate_crt_filepath=config_static.MainConfig.ca_certificate_crt_filepath,
@@ -469,109 +517,179 @@ def mitm_server(config_file_path: str, script_version: str):
469
517
  ssh_user=config_static.ProcessName.ssh_user,
470
518
  ssh_pass=config_static.ProcessName.ssh_pass,
471
519
  ssh_script_to_execute=config_static.ProcessName.ssh_script_to_execute,
472
- logger=listener_logger,
473
- exceptions_logger=MITM_ERROR_LOGGER,
474
- statistics_logs_directory=config_static.LogRec.logs_path,
520
+ logs_directory=config_static.LogRec.logs_path,
521
+ logger_name=network_logger_name,
522
+ logger_queue=NETWORK_LOGGER_QUEUE,
523
+ statistics_logger_name=STATISTICS_LOGGER_NAME,
524
+ statistics_logger_queue=STATISTICS_CSV_LOGGER_QUEUE,
525
+ exceptions_logger_name=EXCEPTIONS_CSV_LOGGER_NAME,
526
+ exceptions_logger_queue=EXCEPTIONS_CSV_LOGGER_QUEUE,
475
527
  forwarding_dns_service_ipv4_list___only_for_localhost=[config_static.DNSServer.forwarding_dns_service_ipv4],
476
- skip_extension_id_list=config_static.SkipExtensions.SKIP_EXTENSION_ID_LIST,
477
- no_engine_usage_enable=config_static.TCPServer.no_engines_usage_to_listen_addresses_enable,
478
- no_engines_listening_address_list=config_static.TCPServer.no_engines_listening_address_list,
479
- engines_list=config_static.ENGINES_LIST
528
+ skip_extension_id_list=config_static.SkipExtensions.SKIP_EXTENSION_ID_LIST
480
529
  )
481
- except socket_wrapper.SocketWrapperPortInUseError as e:
482
- print_api.print_api(e, error_type=True, color="red", logger=system_logger)
483
- # Wait for the message to be printed and saved to file.
484
- time.sleep(1)
485
- network_logger_queue_listener.stop()
486
- return 1
487
- except socket_wrapper.SocketWrapperConfigurationValuesError as e:
488
- print_api.print_api(e, error_type=True, color="red", logger=system_logger, logger_method='critical')
489
- # Wait for the message to be printed and saved to file.
490
- time.sleep(1)
491
- network_logger_queue_listener.stop()
492
- return 1
493
530
 
494
- # ----------------------- Get the default network adapter configuration. --------------------------
495
- # This setting is needed only for the dns gateways configurations from the main config on localhost.
496
- set_local_dns_gateway: bool = False
497
- # Set the default gateway if specified.
498
- if config_static.DNSServer.set_default_dns_gateway:
499
- dns_gateway_server_list = config_static.DNSServer.set_default_dns_gateway
500
- set_local_dns_gateway = True
501
- elif config_static.DNSServer.set_default_dns_gateway_to_localhost:
502
- dns_gateway_server_list = [base.LOCALHOST_IPV4]
503
- set_local_dns_gateway = True
504
- elif config_static.DNSServer.set_default_dns_gateway_to_default_interface_ipv4:
505
- dns_gateway_server_list = [base.DEFAULT_IPV4]
506
- set_local_dns_gateway = True
507
- else:
508
- dns_gateway_server_list = NETWORK_INTERFACE_SETTINGS.dns_gateways
509
-
510
- if config_static.ENGINES_LIST[0].is_localhost:
511
- if set_local_dns_gateway:
512
- global IS_SET_DNS_GATEWAY
513
- IS_SET_DNS_GATEWAY = True
514
-
515
- # Get current network interface state.
516
- global NETWORK_INTERFACE_IS_DYNAMIC, NETWORK_INTERFACE_IPV4_ADDRESS_LIST
517
- NETWORK_INTERFACE_IS_DYNAMIC, NETWORK_INTERFACE_IPV4_ADDRESS_LIST = dns.get_default_dns_gateway()
518
-
519
- # Set the DNS gateway to the specified one only if the DNS gateway is dynamic, or it is static but different
520
- # from the one specified in the configuration file.
521
- if (NETWORK_INTERFACE_IS_DYNAMIC or (not NETWORK_INTERFACE_IS_DYNAMIC and
522
- NETWORK_INTERFACE_IPV4_ADDRESS_LIST != dns_gateway_server_list)):
523
- try:
524
- dns.set_connection_dns_gateway_static(
525
- dns_servers=dns_gateway_server_list,
526
- use_default_connection=True
527
- )
528
- except PermissionError as e:
529
- print_api.print_api(e, error_type=True, color="red", logger=system_logger)
530
- # Wait for the message to be printed and saved to file.
531
- time.sleep(1)
532
- network_logger_queue_listener.stop()
533
- return 1
534
- else:
535
- # Change the adapter settings and add the virtual IPs.
536
- try:
537
- networks.add_virtual_ips_to_default_adapter_by_current_setting(
538
- virtual_ipv4s_to_add=IPS_TO_ASSIGN, virtual_ipv4_masks_to_add=MASKS_TO_ASSIGN, dns_gateways=dns_gateway_server_list)
539
- except PermissionError as e:
540
- print_api.print_api(e, error_type=True, color="red", logger=system_logger)
531
+ is_tcp_process_ready: multiprocessing.Event = multiprocessing.Event()
532
+ is_ready_multiprocessing_event_list.append(is_tcp_process_ready)
533
+
534
+ tcp_process: multiprocessing.Process = multiprocessing.Process(
535
+ target=_create_tcp_server_process,
536
+ name=interface_dict['process_name'],
537
+ args=(
538
+ socket_wrapper_kwargs,
539
+ config_file_path,
540
+ network_logger_name,
541
+ NETWORK_LOGGER_QUEUE,
542
+ is_tcp_process_ready
543
+ ),
544
+ daemon=True
545
+ )
546
+ tcp_process.start()
547
+ multiprocess_list.append(tcp_process)
548
+
549
+ # Compress recordings each day in a separate process.
550
+ recs_archiver_thread = threading.Thread(target=_loop_at_midnight_recs_archive, args=(network_logger_name,), daemon=True)
551
+ recs_archiver_thread.start()
552
+
553
+ # Check that all the multiprocesses are ready.
554
+ for event in is_ready_multiprocessing_event_list:
555
+ if not event.wait(timeout=30):
556
+ print_api.print_api("One of the processes didn't start in time.", error_type=True, color="red",
557
+ logger=system_logger)
541
558
  # Wait for the message to be printed and saved to file.
542
559
  time.sleep(1)
543
- network_logger_queue_listener.stop()
544
560
  return 1
545
561
 
546
- statistics_writer = socket_wrapper_instance.statistics_writer
562
+ if config_static.DNSServer.enable or config_static.TCPServer.enable:
563
+ print_api.print_api("The Server is Ready for Operation!", color="green", logger=system_logger)
564
+ # Get al the queue listener processes (basically this is not necessary, since they're 'daemons', but this is a good practice).
565
+ multiprocess_list.extend(loggingw.get_listener_processes())
547
566
 
548
- socket_wrapper_instance.start_listening_sockets(
549
- reference_function_name=thread_worker_main,
550
- reference_function_args=(
551
- network_logger_with_queue_handler, statistics_writer, config_static.ENGINES_LIST,
552
- config_static.REFERENCE_MODULE)
553
- )
567
+ # This is needed for Keyboard Exception.
568
+ while True:
569
+ # If it is the first cycle and some process had an exception, we will exist before printing that the
570
+ # server is ready for operation.
571
+ result, process_name = multiprocesses.is_process_crashed(multiprocess_list)
572
+ # If result is None, all processes are still alive.
573
+ if result is not None:
574
+ # If result is 0 or 1, we can exit the loop.
575
+ print(f"Process [{process_name}] finished with exit code {result}.")
576
+ break
554
577
 
555
- # socket_thread = threading.Thread(
556
- # target=socket_wrapper_instance.loop_for_incoming_sockets,
557
- # kwargs={
558
- # 'reference_function_name': thread_worker_main,
559
- # 'reference_function_args': (network_logger_with_queue_handler, statistics_writer, engines_list, reference_module,)
560
- # },
561
- # name="accepting_loop"
562
- # )
563
- #
564
- # socket_thread.daemon = True
565
- # socket_thread.start()
578
+ time.sleep(1)
566
579
 
567
- # Compress recordings each day in a separate process.
568
- recs_archiver_thread = threading.Thread(target=_loop_at_midnight_recs_archive, args=(network_logger_name,), daemon=True)
569
- recs_archiver_thread.start()
570
580
 
571
- if config_static.DNSServer.enable or config_static.TCPServer.enable:
572
- # This is needed for Keyboard Exception.
581
+ def _create_tcp_server_process(
582
+ socket_wrapper_kwargs: dict,
583
+ config_file_path: str,
584
+ network_logger_name: str,
585
+ network_logger_queue: multiprocessing.Queue,
586
+ is_tcp_process_ready: multiprocessing.Event
587
+ ):
588
+ # Load config_static per process, since it is not shared between processes.
589
+ config_static.load_config(config_file_path, print_kwargs=dict(stdout=False))
590
+
591
+ # First create a network logger with a queue handler.
592
+ _ = loggingw.create_logger(
593
+ logger_name=network_logger_name,
594
+ add_queue_handler=True,
595
+ log_queue=network_logger_queue,
596
+ )
597
+
598
+ # Now get the system logger and listener loggers.
599
+ system_logger: logging.Logger = loggingw.get_logger_with_level(f'{network_logger_name}.system')
600
+ # If the listener logger is available in current process, the SocketWrapper will use it.
601
+ _ = loggingw.get_logger_with_level(f'{network_logger_name}.listener')
602
+
603
+ try:
604
+ # noinspection PyTypeChecker
605
+ socket_wrapper_instance = socket_wrapper.SocketWrapper(**socket_wrapper_kwargs)
606
+ except socket_wrapper.SocketWrapperPortInUseError as e:
607
+ print_api.print_api(e, error_type=True, color="red", logger=system_logger)
608
+ # Wait for the message to be printed and saved to file.
609
+ time.sleep(1)
610
+ # network_logger_queue_listener.stop()
611
+ sys.exit(1)
612
+ except socket_wrapper.SocketWrapperConfigurationValuesError as e:
613
+ print_api.print_api(e, error_type=True, color="red", logger=system_logger, logger_method='critical')
614
+ # Wait for the message to be printed and saved to file.
615
+ time.sleep(1)
616
+ # network_logger_queue_listener.stop()
617
+ sys.exit(1)
618
+
619
+ socket_wrapper_instance.start_listening_socket(
620
+ callable_function=thread_worker_main, callable_args=(config_static,))
621
+
622
+ # Notify that the TCP server is ready.
623
+ is_tcp_process_ready.set()
624
+
625
+ try:
573
626
  while True:
627
+ time.sleep(1) # Keep the process alive, since the listening socket is in an infinite loop.
628
+ except KeyboardInterrupt:
629
+ sys.exit(0)
630
+
631
+
632
+ def _add_virtual_ips_set_default_dns_gateway(system_logger: logging.Logger) -> int:
633
+ """
634
+ The function reads the current DNS gateway setting and sets the new one.
635
+
636
+ :param system_logger: The logger to use for logging messages.
637
+ :return: 0 if successful, 1 if there was an error.
638
+ """
639
+
640
+ # This setting is needed only for the dns gateways configurations from the main config on localhost.
641
+ set_local_dns_gateway: bool = False
642
+ # Set the default gateway if specified.
643
+ if config_static.DNSServer.set_default_dns_gateway:
644
+ dns_gateway_server_list = config_static.DNSServer.set_default_dns_gateway
645
+ set_local_dns_gateway = True
646
+ elif config_static.DNSServer.set_default_dns_gateway_to_localhost:
647
+ dns_gateway_server_list = [base.LOCALHOST_IPV4]
648
+ set_local_dns_gateway = True
649
+ elif config_static.DNSServer.set_default_dns_gateway_to_default_interface_ipv4:
650
+ dns_gateway_server_list = [base.DEFAULT_IPV4]
651
+ set_local_dns_gateway = True
652
+ else:
653
+ dns_gateway_server_list = NETWORK_INTERFACE_SETTINGS.dns_gateways
654
+
655
+ if config_static.ENGINES_LIST[0].is_localhost:
656
+ if set_local_dns_gateway:
657
+ global IS_SET_DNS_GATEWAY
658
+ IS_SET_DNS_GATEWAY = True
659
+
660
+ # Get current network interface state.
661
+ global NETWORK_INTERFACE_IS_DYNAMIC, NETWORK_INTERFACE_IPV4_ADDRESS_LIST
662
+ NETWORK_INTERFACE_IS_DYNAMIC, NETWORK_INTERFACE_IPV4_ADDRESS_LIST = dns.get_default_dns_gateway()
663
+
664
+ # Set the DNS gateway to the specified one only if the DNS gateway is dynamic, or it is static but different
665
+ # from the one specified in the configuration file.
666
+ if (NETWORK_INTERFACE_IS_DYNAMIC or (not NETWORK_INTERFACE_IS_DYNAMIC and
667
+ NETWORK_INTERFACE_IPV4_ADDRESS_LIST != dns_gateway_server_list)):
668
+ try:
669
+ dns.set_connection_dns_gateway_static(
670
+ dns_servers=dns_gateway_server_list,
671
+ use_default_connection=True
672
+ )
673
+ except PermissionError as e:
674
+ print_api.print_api(e, error_type=True, color="red", logger=system_logger)
675
+ # Wait for the message to be printed and saved to file.
676
+ time.sleep(1)
677
+ # network_logger_queue_listener.stop()
678
+ return 1
679
+ else:
680
+ # Change the adapter settings and add the virtual IPs.
681
+ try:
682
+ networks.add_virtual_ips_to_default_adapter_by_current_setting(
683
+ virtual_ipv4s_to_add=IPS_TO_ASSIGN, virtual_ipv4_masks_to_add=MASKS_TO_ASSIGN,
684
+ dns_gateways=dns_gateway_server_list)
685
+ except PermissionError as e:
686
+ print_api.print_api(e, error_type=True, color="red", logger=system_logger)
687
+ # Wait for the message to be printed and saved to file.
574
688
  time.sleep(1)
689
+ # network_logger_queue_listener.stop()
690
+ return 1
691
+
692
+ return 0
575
693
 
576
694
 
577
695
  def _loop_at_midnight_recs_archive(network_logger_name):