elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.


Tema destacado: ¿Eres nuevo? ¿Tienes dudas acerca del funcionamiento de la comunidad? Lee las Reglas Generales


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación General
| | |-+  .NET (C#, VB.NET, ASP) (Moderador: kub0x)
| | | |-+  Librería de Snippets para VB.NET !! (Compartan aquí sus snippets)
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: 1 ... 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 [63] Ir Abajo Respuesta Imprimir
Autor Tema: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets)  (Leído 667,601 veces)
Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.989



Ver Perfil
Re: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets)
« Respuesta #620 en: Ayer a las 15:47 »

Indagando más profundo en la automatización de Proton VPN, descubrí tres formas adicionales para alternar entre servidores, de las cuales he llegado a implementar las dos primeras:

 1- Una forma consiste en automatizar el menú contextual de la bandeja del sistema (System Tray), haciendo click en los comandos "Conectar" y "Desconectar" de dicho menú según sea el estado actual de la conexión VPN. Esto es una técnica bastante más eficiente que la estrategia de automatización de la GUI que compartí para la versión de pago en el post anterior aquí arriba, ya que no depende de coordenadas ni de averiguar el color del botón "Conectar/Desconectar", pero de todas formas si la barra de tareas estuviese oculta/colapsada o si el icono de ProtonVPN estuviese oculto en el área de notificación colapsado, supondría una barrera que requeriría implementar más lógica adicional de automatización para la barra de tareas. Al menos el método de automatización que ya compartí no tiene esas barreras.

 2- La otra forma, la cual descubrí investigando en un hilo de Reddit, y la cual considero que es la forma más efectiva de todas (o al menos la menos invasiva), consiste en enviar una señal de detención al servicio de Windows de ProtonVPN. Esto provocará una reconexión de la interfaz de red de Proton (y con ello un cambio aleatorio de servidor). El único requisito es estar corriendo ProtonVPN y tener activado el modo "País aleatorio" para que al reiniciar el servicio la nueva conexión se establezca alternando a otro servidor diferente.

 3- Existiría una tercera vía mediante la comunicación directa con la canalización con nombre (Named Pipe) de Proton. En teoría se podría lograr importando las librerías DLL necesarias de la aplicación (NET 8+), pero es una opción poco viable para poder compartirlo como solución de distribución general en un foro. En su defecto se supone que se podría implementar un proxy WCF (Windows Communication Foundation), pero esta opción tampoco sería muy viable, aparte del ingente esfuerzo para implementar todas las interfaces necesarias (ver aquí), la solución sería extremadamente frágil, ya que cualquier modificación en los contratos de interfaz del código fuente original de Proton invalidaría el proxy por completo. No llegué a implementar esta solución y, para ser sinceros, tampoco es que tenga experiencia en hacerlo.

En fin. Teniendo todo esto en cuenta, considero que llevar a cabo el "reinicio" del servicio de ProtonVPN es la solución que tiene el "trade-off" más factible entre todas las demás soluciones que descubrí. Aquí les dejo el código fuente:

Código
  1. ''' <summary>
  2. ''' Restarts the Proton VPN Windows Service to force a server reconnection.
  3. ''' </summary>
  4. '''
  5. ''' <remarks>
  6. ''' This method validates that a connection is active by checking the
  7. ''' "ProtonVPN" network interface status before attempting to restart the service.
  8. ''' </remarks>
  9. '''
  10. ''' <exception cref="InvalidOperationException">
  11. ''' Thrown when the Proton VPN network interface is not found or is not connected,
  12. ''' or if the <b>ProtonVPN</b> Windows service fails to complete the restart sequence.
  13. ''' </exception>
  14. '''
  15. ''' <exception cref="Exception">
  16. ''' Thrown when the <b>ProtonVPN</b> Windows service service restarted and network interface is UP,
  17. ''' but no data flow (Bytes Received) was detected.
  18. ''' </exception>
  19. <EditorBrowsable(EditorBrowsableState.Advanced)>
  20. <DebuggerStepThrough>
  21. Private Sub ChangeProtonVpnServerByWindowsService()
  22.  
  23.    Const ProtonVPN_NetworkInterfaceName As String = "ProtonVPN"
  24.    Const ProtonVPN_WindowsServiceName As String = "ProtonVPN Service"
  25.  
  26.    Dim isProtonVpnConnected As Boolean = False
  27.  
  28.    Dim interfaces As NetworkInterface() = NetworkInterface.GetAllNetworkInterfaces()
  29.    For Each ni As NetworkInterface In interfaces
  30.        ' We look for the specific name Proton uses for its virtual adapters
  31.        If ni.Name.Equals(ProtonVPN_NetworkInterfaceName, StringComparison.OrdinalIgnoreCase) Then
  32.            If ni.OperationalStatus = OperationalStatus.Up Then
  33.                isProtonVpnConnected = True
  34.                Exit For
  35.            End If
  36.        End If
  37.    Next ni
  38.  
  39.    If Not isProtonVpnConnected Then
  40.        Throw New InvalidOperationException(
  41.            $"The {ProtonVPN_NetworkInterfaceName} network interface is not connected to a server." & Environment.NewLine &
  42.            "The reconnection logic requires an active VPN connection to be present.")
  43.    End If
  44.  
  45.    ' Restart the ProtonVPN Windows service.
  46.    Using sc As New ServiceController(ProtonVPN_WindowsServiceName)
  47.  
  48.        Select Case sc.Status
  49.  
  50.            Case ServiceControllerStatus.StartPending, ServiceControllerStatus.Running
  51.                sc.Stop()
  52.                sc.WaitForStatus(ServiceControllerStatus.StopPending, TimeSpan.FromSeconds(10))
  53.  
  54.            Case ServiceControllerStatus.Stopped
  55.                sc.Start()
  56.  
  57.            Case Else
  58.                Throw New InvalidOperationException(
  59.                    $"The {ProtonVPN_WindowsServiceName} Windows service is in a unexpected state: {sc.Status}")
  60.        End Select
  61.  
  62.        sc.WaitForStatus(ServiceControllerStatus.Running, TimeSpan.FromSeconds(10))
  63.    End Using
  64.  
  65.    ' Wait for the ProtonVPN network interface to return to 'Up' status and has verified data flow (bytes received).
  66.    Dim retryTimeout As TimeSpan = TimeSpan.FromSeconds(30)
  67.    Dim startTime As Date = Date.Now
  68.    Dim isDataFlowEstablished As Boolean = False
  69.    Dim initialBytes As Long = -1
  70.  
  71.    Do While (Date.Now - startTime) < retryTimeout
  72.        Dim protonVpnInterface As NetworkInterface = NetworkInterface.GetAllNetworkInterfaces().
  73.            SingleOrDefault(Function(ni) ni.Name.Equals(ProtonVPN_NetworkInterfaceName, StringComparison.OrdinalIgnoreCase))
  74.  
  75.        If (protonVpnInterface IsNot Nothing) AndAlso
  76.           (protonVpnInterface.OperationalStatus = OperationalStatus.Up) Then
  77.  
  78.            Dim stats As IPv4InterfaceStatistics = protonVpnInterface.GetIPv4Statistics()
  79.  
  80.            ' On first detection of 'Up' status, capture baseline.
  81.            If initialBytes = -1 Then
  82.                initialBytes = stats.BytesReceived
  83.            End If
  84.  
  85.            ' Check if we have received new data since being 'Up'.
  86.            If stats.BytesReceived > initialBytes Then
  87.                isDataFlowEstablished = True
  88.                Exit Do
  89.            End If
  90.        End If
  91.  
  92.        Thread.Sleep(500)
  93.    Loop
  94.  
  95.    If Not isDataFlowEstablished Then
  96.        Throw New Exception(
  97.            $"The {ProtonVPN_WindowsServiceName} Windows service restarted " & Environment.NewLine &
  98.            $"and {ProtonVPN_NetworkInterfaceName} network interface is UP, " & Environment.NewLine &
  99.            $"but no data flow (bytes received) was detected within {retryTimeout.TotalSeconds} seconds.")
  100.    End If
  101.  
  102.    Thread.Sleep(1000) ' Additional delay to ensure connection has established with a VPN server before return.
  103. End Sub

Simplemente llamar al método ChangeProtonVpnServerViaWindowsService, esperar a que termine su ejecución, y listo.



« Última modificación: Ayer a las 16:26 por Eleкtro » En línea



Páginas: 1 ... 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 [63] Ir Arriba Respuesta Imprimir 

Ir a:  

WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines