public void HandlePowerEvents(object sender, PowerModeChangedEventArgs e) { switch (e.Mode) { case PowerModes.Suspend: Running = false; Link.Close(); Tun.Close(); break; case PowerModes.Resume: Tun = Tun.Reopen(); Running = true; break; } }
public void ConnectLoop(string host) { int seconds_to_wait = 0; while (Link == null || Link.Closed) { ManualResetEvent closed = new ManualResetEvent(false); Uri uri = new Uri(host); try { switch (uri.Scheme) { case "ws": Log.Info("Connecting to {0} over Websocket", uri); var spoofed_host = Config.GetString("network.websocket.spoof_host"); var spoofed_origin = Config.GetString("network.websocket.spoof_origin"); spoofed_host = string.IsNullOrWhiteSpace(spoofed_host) ? uri.Host : spoofed_host; spoofed_origin = string.IsNullOrWhiteSpace(spoofed_origin) ? uri.Host : spoofed_origin; Link = new ClientLink(new WebSocketTunnel(new TcpClient(uri.Host, uri.Port), spoofed_host, spoofed_origin, false)); break; case "udp": Log.Info("Connecting to {0} over UDP", uri); Link = new ClientLink(new UdpTunnel(IPAddress.Parse(uri.Host), uri.Port, Config.GetInt("network.udp.force_mtu"))); break; } Link.OnLinkClosed += (sender) => { closed.Set(); }; Link.LoadCertificatesFromFiles( CertificateAuthority, Certificate, Signature); Link.AttestationToken = Identifier.Value; var result = Link.PerformHandshake(); if (result.Type != HandshakeResultType.Successful) { Log.Error("Failed handshake: {0}", result.Message); Link = null; throw new Exception(result.Message); } Link.BufferedWrite = false; } catch (Exception ex) { seconds_to_wait += 3; Log.Error(ex, "Failed to connect, retrying in {0} seconds...", seconds_to_wait); Log.Error(ex); Thread.Sleep(seconds_to_wait * 1000); continue; } seconds_to_wait = 0; Utilities.StartThread(delegate { while (Link != null && Link.Tunnel != null && !Link.Tunnel.Closed) { try { var data = Tun.Read(); if (data == null) { continue; } if (data[0] == 0x60) { Log.Trace("Dropping IPv6 packet"); continue; } Log.Trace("Received {0} bytes", data.Length); Link.SendData(data); } catch (Exception ex) { if (ex.Message == "A device attached to the system is not functioning.") // temp hack { Tun.Close(); Tun = Tun.Reopen(); } Log.Error("Error while reading from tun. HResult: {0}", ex.HResult); Log.Error(ex); } } try { Link?.Close(); } catch { } closed.Set(); }); Link.OnDataReceived += (sender, data) => { Tun.Write(data); Log.Trace("Wrote {0} bytes", data.Length); }; closed.WaitOne(); Thread.Sleep(5000); } }