protected GateWith2Inputs(ICircuit inputA, ICircuit inputB, string label, FnTestDelegate fnTest) { _inputA = inputA; _inputB = inputB; _label = label; _fnTest = fnTest; }
/// <summary> /// Removes the given item from the collection /// </summary> /// <returns>True, if the item was removed, otherwise False</returns> /// <param name="item">The item that should be removed</param> public override bool Remove(IModelElement item) { ICircuit circuitItem = item.As <ICircuit>(); if (((circuitItem != null) && this._parent.Circuits.Remove(circuitItem))) { return(true); } INetworkDataSet networkDataSetItem = item.As <INetworkDataSet>(); if (((networkDataSetItem != null) && this._parent.NetworkDataSets.Remove(networkDataSetItem))) { return(true); } IPowerSystemResource powerSystemResourceItem = item.As <IPowerSystemResource>(); if (((powerSystemResourceItem != null) && this._parent.PowerSystemResources.Remove(powerSystemResourceItem))) { return(true); } IConductorAsset conductorAssetItem = item.As <IConductorAsset>(); if (((conductorAssetItem != null) && this._parent.ConductorAssets.Remove(conductorAssetItem))) { return(true); } return(false); }
private static Tuple <ICircuit, ISet <int> > NodesToCircuit(IReadOnlyList <Node> genes) { var circuit = new List <ICircuit>(); var usedIndexes = new List <ISet <int> >(); for (var i = 0; i < genes.Count; i++) { var node = genes[i]; var used = new HashSet <int> { i }; ICircuit inputA = null; ICircuit inputB = null; if (node.IndexA != null && i > node.IndexA) { inputA = circuit[(int)node.IndexA]; used.UnionWith(usedIndexes[(int)node.IndexA]); if (node.IndexB != null && i > node.IndexB) { inputB = circuit[(int)node.IndexB]; used.UnionWith(usedIndexes[(int)node.IndexB]); } } circuit.Add(node.CreateGate(inputA, inputB)); usedIndexes.Add(used); } return(new Tuple <ICircuit, ISet <int> >(circuit[circuit.Count - 1], usedIndexes[usedIndexes.Count - 1])); }
public CircuitWatcher(ICircuit circuit, CancellationToken cancellation) { _circuit = circuit; _cancellation = cancellation; _task = Task.Run(pingUntilConnected, _cancellation); }
/// <summary> /// Adds the given element to the collection /// </summary> /// <param name="item">The item to add</param> public override void Add(IModelElement item) { ICircuit circuitsCasted = item.As <ICircuit>(); if ((circuitsCasted != null)) { this._parent.Circuits.Add(circuitsCasted); } INetworkDataSet networkDataSetsCasted = item.As <INetworkDataSet>(); if ((networkDataSetsCasted != null)) { this._parent.NetworkDataSets.Add(networkDataSetsCasted); } IPowerSystemResource powerSystemResourcesCasted = item.As <IPowerSystemResource>(); if ((powerSystemResourcesCasted != null)) { this._parent.PowerSystemResources.Add(powerSystemResourcesCasted); } IConductorAsset conductorAssetsCasted = item.As <IConductorAsset>(); if ((conductorAssetsCasted != null)) { this._parent.ConductorAssets.Add(conductorAssetsCasted); } }
/// <summary> /// Do the authentication part of Tor's SOCKS5 protocol. /// </summary> /// <param name="circuit">Tor circuit we want to use in authentication.</param> /// <remarks>Tor process must be started with enabled <c>IsolateSOCKSAuth</c> option. It's ON by default.</remarks> /// <seealso href="https://www.torproject.org/docs/tor-manual.html.en"/> /// <seealso href="https://linux.die.net/man/1/tor">For <c>IsolateSOCKSAuth</c> option explanation.</seealso> /// <seealso href="https://gitweb.torproject.org/torspec.git/tree/socks-extensions.txt#n35"/> /// <exception cref="NotSupportedException">When authentication fails due to unsupported authentication method.</exception> /// <exception cref="InvalidOperationException">When authentication fails due to invalid credentials.</exception> private async Task HandshakeAsync(TcpClient tcpClient, ICircuit circuit, CancellationToken cancellationToken = default) { // https://github.com/torproject/torspec/blob/master/socks-extensions.txt // The "NO AUTHENTICATION REQUIRED" (SOCKS5) authentication method [00] is // supported; and as of Tor 0.2.3.2 - alpha, the "USERNAME/PASSWORD"(SOCKS5) // authentication method[02] is supported too, and used as a method to // implement stream isolation.As an extension to support some broken clients, // we allow clients to pass "USERNAME/PASSWORD" authentication message to us // even if no authentication was selected.Furthermore, we allow // username / password fields of this message to be empty. This technically // violates RFC1929[4], but ensures interoperability with somewhat broken // SOCKS5 client implementations. MethodsField methods = new(MethodField.UsernamePassword); byte[] receiveBuffer = await SendRequestAsync(tcpClient, new VersionMethodRequest(methods), cancellationToken).ConfigureAwait(false); MethodSelectionResponse methodSelection = new(receiveBuffer); if (methodSelection.Ver != VerField.Socks5) { throw new NotSupportedException($"SOCKS{methodSelection.Ver.Value} not supported. Only SOCKS5 is supported."); } else if (methodSelection.Method == MethodField.NoAcceptableMethods) { // https://www.ietf.org/rfc/rfc1928.txt // If the selected METHOD is X'FF', none of the methods listed by the // client are acceptable, and the client MUST close the connection. throw new NotSupportedException("Tor's SOCKS5 proxy does not support any of the client's authentication methods."); } else if (methodSelection.Method == MethodField.UsernamePassword) { // https://tools.ietf.org/html/rfc1929#section-2 // Once the SOCKS V5 server has started, and the client has selected the // Username / Password Authentication protocol, the Username / Password // sub-negotiation begins. This begins with the client producing a // Username / Password request: UNameField uName = new(uName : circuit.Name); PasswdField passwd = new(password : circuit.Name); UsernamePasswordRequest usernamePasswordRequest = new(uName, passwd); receiveBuffer = await SendRequestAsync(tcpClient, usernamePasswordRequest, cancellationToken).ConfigureAwait(false); UsernamePasswordResponse userNamePasswordResponse = new(receiveBuffer); if (userNamePasswordResponse.Ver != usernamePasswordRequest.Ver) { throw new NotSupportedException($"Authentication version {userNamePasswordResponse.Ver.Value} not supported. Only version {usernamePasswordRequest.Ver} is supported."); } if (!userNamePasswordResponse.Status.IsSuccess()) // Tor authentication is different, this will never happen; { // https://tools.ietf.org/html/rfc1929#section-2 // A STATUS field of X'00' indicates success. If the server returns a // `failure' (STATUS value other than X'00') status, it MUST close the // connection. throw new InvalidOperationException("Wrong username and/or password."); } } }
/// <param name="tcpClient">TCP client connected to Tor SOCKS5 endpoint.</param> /// <param name="transportStream">Transport stream to actually send the data to Tor SOCKS5 endpoint (the difference is SSL).</param> /// <param name="circuit">Tor circuit under which we operate with this TCP connection.</param> /// <param name="allowRecycling">Whether it is allowed to re-use this Tor TCP connection.</param> public TorTcpConnection(TcpClient tcpClient, Stream transportStream, ICircuit circuit, bool allowRecycling) { TcpClient = tcpClient; TransportStream = transportStream; Circuit = circuit; AllowRecycling = allowRecycling; Id = Interlocked.Increment(ref LastId); }
/// <summary> /// A breaker that will govern an ICircuit /// </summary> /// <param name="circuit"></param> public Breaker(ICircuit circuit) { Circuit = circuit; stateStore = CircuitBreakerStateStoreFactory .GetCircuitBreakerStateStore(Circuit); }
/// <summary> /// Creates a new connected TCP client connected to Tor SOCKS5 endpoint. /// </summary> /// <inheritdoc cref="ConnectAsync(string, int, bool, ICircuit, CancellationToken)"/> public virtual async Task <TorTcpConnection> ConnectAsync(Uri requestUri, ICircuit circuit, CancellationToken token = default) { bool useSsl = requestUri.Scheme == Uri.UriSchemeHttps; string host = requestUri.DnsSafeHost; int port = requestUri.Port; return(await ConnectAsync(host, port, useSsl, circuit, token).ConfigureAwait(false)); }
public RaceTrack( ICircuit circuit, bool[,] occupancyGrid, double tileSize) { Circuit = circuit; OccupancyGrid = occupancyGrid; TileSize = tileSize; Width = OccupancyGrid.GetLength(0) * tileSize; Height = OccupancyGrid.GetLength(1) * tileSize; }
/// <param name="tcpClient">TCP client connected to Tor SOCKS5 endpoint.</param> /// <param name="transportStream">Transport stream to actually send the data to Tor SOCKS5 endpoint (the difference is SSL).</param> /// <param name="circuit">Tor circuit under which we operate with this TCP connection.</param> /// <param name="allowRecycling">Whether it is allowed to re-use this Tor TCP connection.</param> public TorTcpConnection(TcpClient tcpClient, Stream transportStream, ICircuit circuit, bool allowRecycling) { long id = Interlocked.Increment(ref LastId); string prefix = circuit switch { DefaultCircuit _ => "DC", PersonCircuit _ => "PC", _ => "UC" // Unknown circuit type. }; Name = $"{prefix}#{id:0000}#{circuit.Name[0..10]}";
internal static ICircuitBreakerStateStore GetCircuitBreakerStateStore(ICircuit circuit) { // There is only one type of ICircuitBreakerStateStore to return... // The ConcurrentDictionary keeps track of ICircuitBreakerStateStore objects (across threads) // For example, a store for a db connection, web service client, and NAS storage could exist if (!_stateStores.ContainsKey(circuit.GetType())) { _stateStores.TryAdd(circuit.GetType(), new CircuitBreakerStateStore(circuit)); } return(_stateStores[circuit.GetType()]); }
private void button1_Click(object sender, EventArgs e) { NewComponentForm ff = new NewComponentForm(); ICircuit circuit = null; //ff.ShowDialog(); if (ff.ShowDialog() == DialogResult.OK) { circuit = ff.Circuit; ListElement.list.Add(circuit); var row = _datatable.NewRow(); row[0] = circuit.Name; row[1] = Convert.ToString(circuit.CalculateVolume(50)); _datatable.Rows.Add(row); dataGridView1.Update(); } }
/// <summary> /// Добавление нового элемента /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void newelement_Click(object sender, EventArgs e) { //Добавление через контроль NewElementControl GG = new NewElementControl(); //Добавление через форму //NewComponentForm ff = new NewComponentForm(); ICircuit circuit = null; if (GG.ShowDialog() == DialogResult.OK) { circuit = GG.Element; listCircuit.Add(circuit); var row = _datatable.NewRow(); row[0] = circuit.Name; row[1] = Convert.ToString(circuit.CalculateValue(Convert.ToDouble(FrequencyTextBox.Text))); _datatable.Rows.Add(row); dataGridView1.Update(); //Обновляем таблицу } }
public static SerializableTrack From(double tileSize, ICircuit circuit, bool[,] occupancyGrid) { var occupancyGridLines = new List <string>(); for (int i = 0; i < occupancyGrid.GetLength(0); i++) { var line = new StringBuilder(); for (int j = 0; j < occupancyGrid.GetLength(1); j++) { line.Append(occupancyGrid[i, j] ? ' ' : '#'); } occupancyGridLines.Add(line.ToString()); } return(new SerializableTrack { TileSize = tileSize, Circuit = new SerializableCircuit { Radius = circuit.Radius, Start = circuit.Start, WayPoints = circuit.WayPoints.Skip(1).Select(goal => goal.Position).ToList() }, OccupancyGrid = occupancyGridLines.ToArray(), StartingPosition = circuit.StartingPosition }); }
public static void Save(string path, ICircuit circuit, string svg, double tileSize) { Directory.CreateDirectory(path); // svg var svgFileName = $"{path}/visualization.svg"; File.WriteAllText(svgFileName, svg); // png var pngFileName = $"{path}/rasterized_visualization.png"; Images.Convert(svgFileName, pngFileName); // occupancy grid var occupancyGrid = Images.LoadOccupancyGrid(pngFileName, tileSize); // json var track = SerializableTrack.From(tileSize, circuit, occupancyGrid); var jsonFileName = $"{path}/circuit_definition.json"; var json = JsonConvert.SerializeObject(track, CustomJsonSerializationSettings.Default); File.WriteAllText(jsonFileName, json); }
/// <summary> /// Creates a new connected TCP client connected to Tor SOCKS5 endpoint. /// </summary> /// <param name="host">Tor SOCKS5 host.</param> /// <param name="port">Tor SOCKS5 port.</param> /// <param name="useSsl">Whether to use SSL to send the HTTP request over Tor.</param> /// <param name="circuit">Tor circuit we want to use in authentication.</param> /// <param name="cancellationToken">Cancellation token to cancel the asynchronous operation.</param> /// <returns>New <see cref="TorTcpConnection"/> instance.</returns> /// <exception cref="TorConnectionException">When <see cref="ConnectAsync(TcpClient, CancellationToken)"/> fails.</exception> public async Task <TorTcpConnection> ConnectAsync(string host, int port, bool useSsl, ICircuit circuit, CancellationToken cancellationToken = default) { TcpClient?tcpClient = null; Stream? transportStream = null; try { tcpClient = new(TorSocks5EndPoint.AddressFamily); tcpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true); try { tcpClient.Client.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveTime, 30); tcpClient.Client.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveInterval, 5); tcpClient.Client.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveRetryCount, 5); } catch (SocketException ex) when(ex.ErrorCode is 10042) { Logger.LogWarning("KeepAlive settings are not allowed by your OS. Ignoring."); } transportStream = await ConnectAsync(tcpClient, cancellationToken).ConfigureAwait(false); await HandshakeAsync(tcpClient, circuit, cancellationToken).ConfigureAwait(false); await ConnectToDestinationAsync(tcpClient, host, port, cancellationToken).ConfigureAwait(false); if (useSsl) { transportStream = await UpgradeToSslAsync(tcpClient, host).ConfigureAwait(false); } bool allowRecycling = !useSsl && (circuit is DefaultCircuit or PersonCircuit); TorTcpConnection result = new(tcpClient, transportStream, circuit, allowRecycling); transportStream = null; tcpClient = null; return(result); } finally { transportStream?.Dispose(); tcpClient?.Dispose(); } }
public TestExceptionCommand(ICircuit circuit) : base(circuit) { this.Action = DoSomethingAndFail; }
public AbstractCommand(ICircuit circuit) { Circuit = circuit; Breaker = new Breaker(Circuit); }
public And(ICircuit inputA, ICircuit inputB) : base(inputA, inputB, nameof(And), (a, b) => a && b) { }
public Not(ICircuit input) { _input = input; }
public void RemoveCircuit(ICircuit circuit) { throw new NotImplementedException(); }
public Or(ICircuit inputA, ICircuit inputB) : base(inputA, inputB, nameof(Or), (a, b) => a || b) { }
public Xor(ICircuit inputA, ICircuit inputB) : base(inputA, inputB, nameof(Xor), (a, b) => a != b) { }
public async Task UseCorrectIdentitiesAsync() { using CancellationTokenSource timeoutCts = new(TimeSpan.FromMinutes(1)); ICircuit defaultIdentity = DefaultCircuit.Instance; using PersonCircuit aliceIdentity = new(); using PersonCircuit bobIdentity = new(); using TorTcpConnection aliceConnection = new(null !, new MemoryStream(), aliceIdentity, true); using TorTcpConnection bobConnection = new(null !, new MemoryStream(), bobIdentity, true); using TorTcpConnection defaultConnection = new(null !, new MemoryStream(), defaultIdentity, true); Mock <TorTcpConnectionFactory> mockTcpConnectionFactory = new(MockBehavior.Strict, new IPEndPoint(IPAddress.Loopback, 7777)); _ = mockTcpConnectionFactory.Setup(c => c.ConnectAsync(It.IsAny <Uri>(), aliceIdentity, It.IsAny <CancellationToken>())).ReturnsAsync(aliceConnection); _ = mockTcpConnectionFactory.Setup(c => c.ConnectAsync(It.IsAny <Uri>(), bobIdentity, It.IsAny <CancellationToken>())).ReturnsAsync(bobConnection); _ = mockTcpConnectionFactory.Setup(c => c.ConnectAsync(It.IsAny <Uri>(), defaultIdentity, It.IsAny <CancellationToken>())).ReturnsAsync(defaultConnection); TorTcpConnectionFactory tcpConnectionFactory = mockTcpConnectionFactory.Object; // Use implementation of TorHttpPool and only replace SendCoreAsync behavior. Mock <TorHttpPool> mockTorHttpPool = new(MockBehavior.Loose, tcpConnectionFactory) { CallBase = true }; mockTorHttpPool.Setup(x => x.SendCoreAsync(It.IsAny <TorTcpConnection>(), It.IsAny <HttpRequestMessage>(), It.IsAny <CancellationToken>())) .Returns((TorTcpConnection tcpConnection, HttpRequestMessage request, CancellationToken cancellationToken) => { HttpResponseMessage httpResponse = new(HttpStatusCode.OK); if (tcpConnection == aliceConnection) { httpResponse.Content = new StringContent("Alice circuit!"); } else if (tcpConnection == bobConnection) { httpResponse.Content = new StringContent("Bob circuit!"); } else if (tcpConnection == defaultConnection) { httpResponse.Content = new StringContent("Default circuit!"); } else { throw new NotSupportedException(); } return(Task.FromResult(httpResponse)); }); using TorHttpPool pool = mockTorHttpPool.Object; using HttpRequestMessage request = new(HttpMethod.Get, "http://wasabi.backend"); using HttpResponseMessage aliceResponse = await pool.SendAsync(request, aliceIdentity); Assert.Equal("Alice circuit!", await aliceResponse.Content.ReadAsStringAsync(timeoutCts.Token)); using HttpResponseMessage bobResponse = await pool.SendAsync(request, bobIdentity); Assert.Equal("Bob circuit!", await bobResponse.Content.ReadAsStringAsync(timeoutCts.Token)); using HttpResponseMessage defaultResponse = await pool.SendAsync(request, defaultIdentity); Assert.Equal("Default circuit!", await defaultResponse.Content.ReadAsStringAsync(timeoutCts.Token)); mockTcpConnectionFactory.VerifyAll(); }
public async Task RequestAndReplyAsync() { using CancellationTokenSource timeoutCts = new(TimeSpan.FromMinutes(1)); ICircuit circuit = DefaultCircuit.Instance; // Set up FAKE transport stream, so Tor is not in play. await using TransportStream transportStream = new(nameof(RequestAndReplyAsync)); await transportStream.ConnectAsync(timeoutCts.Token); using TorTcpConnection connection = new(tcpClient : null !, transportStream.Client, circuit, allowRecycling : true); Mock <TorTcpConnectionFactory> mockFactory = new(MockBehavior.Strict, new IPEndPoint(IPAddress.Loopback, 7777)); mockFactory.Setup(c => c.ConnectAsync(It.IsAny <Uri>(), It.IsAny <ICircuit>(), It.IsAny <CancellationToken>())).ReturnsAsync(connection); using StreamReader serverReader = new(transportStream.Server); using StreamWriter serverWriter = new(transportStream.Server); using TorHttpPool pool = new(mockFactory.Object); using HttpRequestMessage request = new(HttpMethod.Get, "http://somesite.com"); Task sendTask = Task.Run(async() => { Debug.WriteLine("[client] About send HTTP request."); using HttpResponseMessage httpResponseMessage = await pool.SendAsync(request, circuit).ConfigureAwait(false); Assert.Equal(HttpStatusCode.OK, httpResponseMessage.StatusCode); Debug.WriteLine("[client] Done sending HTTP request."); }); // Server part follows. Debug.WriteLine("[server] About to read data."); // We expect to get this plaintext HTTP request headers from the client. string[] expectedResponse = new[] { "GET / HTTP/1.1", "Accept-Encoding:gzip", "Host:somesite.com", "" }; // Assert replies line by line. foreach (string expectedLine in expectedResponse) { Assert.Equal(expectedLine, await serverReader.ReadLineAsync().WithAwaitCancellationAsync(timeoutCts.Token)); } // We respond to the client with the following content. Debug.WriteLine("[server] Send response for the request."); await serverWriter.WriteAsync( string.Join( "\r\n", "HTTP/1.1 200 OK", "Date: Wed, 02 Dec 2020 18:20:54 GMT", "Content-Type: application/json; charset=utf-8", "Content-Length: 389", "Connection: keep-alive", "ETag: W/\"185-ck4yLFUDHZl9lYSDUF6oMrTCEss\"", "Vary: Accept-Encoding", "set-cookie: sails.sid=s%3AMPaQCDY1u1swPgAI5RhbPg2extVNNhjI.oby40NpOE2CpyzIdRlGhD7Uja%2BGX1WbBaFV13T0f4eA; Path=/; HttpOnly", "", "{\"args\":{},\"data\":\"This is expected to be sent back as part of response body.\",\"files\":{},\"form\":{},\"headers\":{\"x-forwarded-proto\":\"http\",\"x-forwarded-port\":\"80\",\"host\":\"postman-echo.com\",\"x-amzn-trace-id\":\"Root=1-5fc7db06-24adc2a91c86c14f2d63ea61\",\"content-length\":\"58\",\"accept-encoding\":\"gzip\",\"content-type\":\"text/plain; charset=utf-8\"},\"json\":null,\"url\":\"http://postman-echo.com/post\"}").AsMemory(), timeoutCts.Token); await serverWriter.FlushAsync().WithAwaitCancellationAsync(timeoutCts.Token); Debug.WriteLine("[server] Wait for the sendTask to finish."); await sendTask; Debug.WriteLine("[server] Send task finished."); }
public CircuitBreakerStateStore(ICircuit circuit) { this._exceptionsSinceLastStateChange = new ConcurrentStack <Exception>(); }
/// <summary> /// Creates a new connected TCP client connected to Tor SOCKS5 endpoint. /// </summary> /// <param name="host">Tor SOCKS5 host.</param> /// <param name="port">Tor SOCKS5 port.</param> /// <param name="useSsl">Whether to use SSL to send the HTTP request over Tor.</param> /// <param name="circuit">Tor circuit we want to use in authentication.</param> /// <param name="cancellationToken">Cancellation token to cancel the asynchronous operation.</param> /// <returns>New <see cref="TorTcpConnection"/> instance.</returns> /// <exception cref="TorConnectionException">When <see cref="ConnectAsync(TcpClient, CancellationToken)"/> fails.</exception> public async Task <TorTcpConnection> ConnectAsync(string host, int port, bool useSsl, ICircuit circuit, CancellationToken cancellationToken = default) { TcpClient?tcpClient = null; Stream? transportStream = null; try { tcpClient = new(TorSocks5EndPoint.AddressFamily); transportStream = await ConnectAsync(tcpClient, cancellationToken).ConfigureAwait(false); await HandshakeAsync(tcpClient, circuit, cancellationToken).ConfigureAwait(false); await ConnectToDestinationAsync(tcpClient, host, port, cancellationToken).ConfigureAwait(false); if (useSsl) { transportStream = await UpgradeToSslAsync(tcpClient, host).ConfigureAwait(false); } bool allowRecycling = !useSsl && (circuit is DefaultCircuit or PersonCircuit); TorTcpConnection result = new(tcpClient, transportStream, circuit, allowRecycling); transportStream = null; tcpClient = null; return(result); } finally { transportStream?.Dispose(); tcpClient?.Dispose(); } }
public TestCommand(ICircuit circuit) : base(circuit) { this.Action = DoSomething; }