private bool ValidateIdentity() { byte[] buffer; byte ep = 0xFF; string username = string.Empty, password = string.Empty; //报文格式:0x01 | 用户名长度(1字节)| 用户名(长度根据用户名长度域指定) | 口令长度(1字节) | 口令(长度由口令长度域指定) if (SocketUtils.Receive(this.Client, 2, out buffer)) { if (buffer.Length == 2) { //用户名为空 if (buffer[1] == 0x00) { if (string.IsNullOrEmpty(this.Server.UserName)) { ep = 0x00; //用户名为空 } } else { if (SocketUtils.Receive(this.Client, (uint)buffer[1], out buffer)) { username = Encoding.ASCII.GetString(buffer); if (!string.IsNullOrEmpty(this.Server.UserName)) { ep = (byte)(username.Equals(this.Server.UserName) ? 0x00 : 0xFF); } } } if (ep == 0x00) { ep = 0xFF; //判断密码 if (SocketUtils.Receive(this.Client, 1, out buffer)) { if (buffer[0] == 0x00) { if (!string.IsNullOrEmpty(this.Server.Password)) { ep = 0x00; //密码为空 } } else { if (SocketUtils.Receive(this.Client, (uint)buffer[0], out buffer)) { password = Encoding.ASCII.GetString(buffer); if (!string.IsNullOrEmpty(this.Server.Password)) { ep = (byte)(password.Equals(this.Server.Password) ? 0x00 : 0xFF); } } } } } } } //输出应答 SocketUtils.Send(this.Client, new byte[] { 0x01, ep }); return(ep == 0x00); }
public SocketRemotingServer() : this("Server", new IPEndPoint(SocketUtils.GetLocalIPV4(), 5000)) { }
private object SendMessageToServer(MethodBase methodInfo, List <object> parameters) { Socket socketListener = InitializeSocket(); try { socketListener.Connect(ep); } catch { throw new ConnectionFailedException(); } // Create request RequestMessageContent request = new RequestMessageContent() { Command = new CommandHeader() { MethodName = methodInfo.Name, ParameterAssemblyQualifiedNames = methodInfo.GetParameters().Select(p => p.ParameterType.AssemblyQualifiedName).ToList() }, Parameters = parameters }; // Serialize the request MemoryStream msRequest = new MemoryStream(); BinaryFormatter bf = new BinaryFormatter(); bf.Serialize(msRequest, request); // Frame in message Message message = new Message() { Type = MessageType.Request, Content = msRequest.ToArray() }; // Send over socket SocketUtils.SendMessage(socketListener, message); // Wait for server reply Message response = null; try { response = SocketUtils.ReceiveMessage(socketListener, 30000, 30000); } catch (NoNewMessageException) { throw new ServerTimeoutException(); } catch (MessageInterruptedException) { throw new ServerTimeoutException(); } object result = null; if (response != null && response.Type == MessageType.Response && response.Length > 0) { // When server reply complete and valid, unpack the response MemoryStream ms = new MemoryStream(response.Content); result = bf.Deserialize(ms); // If the response is an exception, return exception bool isException = result.GetType().IsSubclassOf(typeof(Exception)); if (isException) { // Release the socket. socketListener.Shutdown(SocketShutdown.Both); socketListener.Close(); throw (Exception)result; } } // Release the socket. socketListener.Shutdown(SocketShutdown.Both); socketListener.Close(); // Return the response return(result); }
async Task <Stream> ConnectAsync(string host, int port, bool doAsync, CancellationToken cancellationToken) { Socks5AddressType addrType; ValidateArguments(host, port); addrType = GetAddressType(host, out var ip); cancellationToken.ThrowIfCancellationRequested(); var socket = await SocketUtils.ConnectAsync(ProxyHost, ProxyPort, LocalEndPoint, doAsync, cancellationToken).ConfigureAwait(false); byte[] domain = null, addr = null; if (addrType == Socks5AddressType.Domain) { domain = Encoding.UTF8.GetBytes(host); } try { Socks5AuthMethod method; if (ProxyCredentials != null) { method = await NegotiateAuthMethodAsync(socket, doAsync, cancellationToken, Socks5AuthMethod.UserPassword, Socks5AuthMethod.Anonymous).ConfigureAwait(false); } else { method = await NegotiateAuthMethodAsync(socket, doAsync, cancellationToken, Socks5AuthMethod.Anonymous).ConfigureAwait(false); } switch (method) { case Socks5AuthMethod.UserPassword: await AuthenticateAsync(socket, doAsync, cancellationToken).ConfigureAwait(false); break; case Socks5AuthMethod.Anonymous: break; default: throw new ProxyProtocolException("Failed to negotiate authentication method with the proxy server."); } // +----+-----+-------+------+----------+----------+ // |VER | CMD | RSV | ATYP | DST.ADDR | DST.PORT | // +----+-----+-------+------+----------+----------+ // | 1 | 1 | X'00' | 1 | Variable | 2 | // +----+-----+-------+------+----------+----------+ var buffer = new byte[4 + 257 + 2]; int nread, n = 0; buffer[n++] = (byte)SocksVersion; buffer[n++] = (byte)Socks5Command.Connect; buffer[n++] = 0x00; buffer[n++] = (byte)addrType; switch (addrType) { case Socks5AddressType.Domain: buffer[n++] = (byte)domain.Length; Buffer.BlockCopy(domain, 0, buffer, n, domain.Length); n += domain.Length; break; case Socks5AddressType.IPv6: addr = ip.GetAddressBytes(); Buffer.BlockCopy(addr, 0, buffer, n, addr.Length); n += 16; break; case Socks5AddressType.IPv4: addr = ip.GetAddressBytes(); Buffer.BlockCopy(addr, 0, buffer, n, addr.Length); n += 4; break; } buffer[n++] = (byte)(port >> 8); buffer[n++] = (byte)port; await SendAsync(socket, buffer, 0, n, doAsync, cancellationToken).ConfigureAwait(false); // +-----+-----+-------+------+----------+----------+ // | VER | REP | RSV | ATYP | BND.ADDR | BND.PORT | // +-----+-----+-------+------+----------+----------+ // | 1 | 1 | X'00' | 1 | Variable | 2 | // +-----+-----+-------+------+----------+----------+ // Note: We know we'll need at least 4 bytes of header + a minimum of 1 byte // to determine the length of the BND.ADDR field if ATYP is a domain. int need = 5; n = 0; do { if ((nread = await ReceiveAsync(socket, buffer, 0 + n, need - n, doAsync, cancellationToken).ConfigureAwait(false)) > 0) { n += nread; } } while (n < need); VerifySocksVersion(buffer[0]); if (buffer[1] != (byte)Socks5Reply.Success) { throw new ProxyProtocolException(string.Format(CultureInfo.InvariantCulture, "Failed to connect to {0}:{1}: {2}", host, port, GetFailureReason(buffer[1]))); } addrType = (Socks5AddressType)buffer[3]; switch (addrType) { case Socks5AddressType.Domain: need += buffer[4] + 2; break; case Socks5AddressType.IPv6: need += (16 - 1) + 2; break; case Socks5AddressType.IPv4: need += (4 - 1) + 2; break; default: throw new ProxyProtocolException("Proxy server returned unknown address type."); } do { if ((nread = await ReceiveAsync(socket, buffer, 0 + n, need - n, doAsync, cancellationToken).ConfigureAwait(false)) > 0) { n += nread; } } while (n < need); // TODO: do we care about BND.ADDR and BND.PORT? return(new NetworkStream(socket, true)); } catch { #if !NETSTANDARD1_3 && !NETSTANDARD1_6 if (socket.Connected) { socket.Disconnect(false); } #endif socket.Dispose(); throw; } }
internal bool IsConnected() { return(SocketUtils.IsConnected(Socket)); }
private ISCSIPDU GetLogoutResponsePDU(LogoutRequestPDU request, ConnectionParameters connection) { Log(Severity.Verbose, "[{0}] Logout Request", connection.ConnectionIdentifier); if (connection.Session.IsDiscovery && request.ReasonCode != LogoutReasonCode.CloseTheSession) { // RFC 3720: Discovery-session: The target MUST ONLY accept [..] logout request with the reason "close the session" RejectPDU reject = new RejectPDU(); reject.Reason = RejectReason.ProtocolError; reject.Data = ByteReader.ReadBytes(request.GetBytes(), 0, 48); return(reject); } else { List <ConnectionState> connectionsToClose = new List <ConnectionState>(); if (request.ReasonCode == LogoutReasonCode.CloseTheSession) { connectionsToClose = m_connectionManager.GetSessionConnections(connection.Session); } else if (request.ReasonCode == LogoutReasonCode.CloseTheConnection) { // RFC 3720: A Logout for a CID may be performed on a different transport connection when the TCP connection for the CID has already been terminated. ConnectionState existingConnection = m_connectionManager.FindConnection(connection.Session, request.CID); if (existingConnection != null) { connectionsToClose.Add(existingConnection); } else { return(ServerResponseHelper.GetLogoutResponsePDU(request, LogoutResponse.CIDNotFound)); } } else if (request.ReasonCode == LogoutReasonCode.RemoveTheConnectionForRecovery) { return(ServerResponseHelper.GetLogoutResponsePDU(request, LogoutResponse.ConnectionRecoveryNotSupported)); } else { // Unknown LogoutRequest ReasonCode RejectPDU reject = new RejectPDU(); reject.Reason = RejectReason.ProtocolError; reject.Data = ByteReader.ReadBytes(request.GetBytes(), 0, 48); return(reject); } foreach (ConnectionState connectionToClose in connectionsToClose) { // Wait for pending I/O to complete. connectionToClose.RunningSCSICommands.WaitUntilZero(); if (connectionToClose.ConnectionParameters != connection) { SocketUtils.ReleaseSocket(connectionToClose.ClientSocket); } m_connectionManager.RemoveConnection(connectionToClose); } if (request.ReasonCode == LogoutReasonCode.CloseTheSession) { Log(Severity.Verbose, "[{0}] Session has been closed", connection.Session.SessionIdentifier); m_sessionManager.RemoveSession(connection.Session, SessionTerminationReason.Logout); } return(ServerResponseHelper.GetLogoutResponsePDU(request, LogoutResponse.ClosedSuccessfully)); // connection will be closed after a LogoutResponsePDU has been sent. } }
public static ENodeConfiguration UseEQueue(this ENodeConfiguration enodeConfiguration, bool useMockDomainEventPublisher = false, bool useMockApplicationMessagePublisher = false, bool useMockPublishableExceptionPublisher = false) { var configuration = enodeConfiguration.GetCommonConfiguration(); var brokerStorePath = @"c:\equeue-store"; var brokerSetting = new BrokerSetting(brokerStorePath); if (Directory.Exists(brokerStorePath)) { Directory.Delete(brokerStorePath, true); } configuration.RegisterEQueueComponents(); _broker = BrokerController.Create(brokerSetting); _commandService = new CommandService(new CommandResultProcessor(new IPEndPoint(SocketUtils.GetLocalIPV4(), 9001))); _eventPublisher = new DomainEventPublisher(); _applicationMessagePublisher = new ApplicationMessagePublisher(); _publishableExceptionPublisher = new PublishableExceptionPublisher(); if (useMockDomainEventPublisher) { configuration.SetDefault <IMessagePublisher <DomainEventStreamMessage>, MockDomainEventPublisher>(); } else { configuration.SetDefault <IMessagePublisher <DomainEventStreamMessage>, DomainEventPublisher>(_eventPublisher); } if (useMockApplicationMessagePublisher) { configuration.SetDefault <IMessagePublisher <IApplicationMessage>, MockApplicationMessagePublisher>(); } else { configuration.SetDefault <IMessagePublisher <IApplicationMessage>, ApplicationMessagePublisher>(_applicationMessagePublisher); } if (useMockPublishableExceptionPublisher) { configuration.SetDefault <IMessagePublisher <IPublishableException>, MockPublishableExceptionPublisher>(); } else { configuration.SetDefault <IMessagePublisher <IPublishableException>, PublishableExceptionPublisher>(_publishableExceptionPublisher); } configuration.SetDefault <ICommandService, CommandService>(_commandService); _commandConsumer = new CommandConsumer(setting: new ConsumerSetting { ConsumeFromWhere = ConsumeFromWhere.FirstOffset }).Subscribe("CommandTopic"); _eventConsumer = new DomainEventConsumer(setting: new ConsumerSetting { ConsumeFromWhere = ConsumeFromWhere.FirstOffset }).Subscribe("EventTopic"); _applicationMessageConsumer = new ApplicationMessageConsumer(setting: new ConsumerSetting { ConsumeFromWhere = ConsumeFromWhere.FirstOffset }).Subscribe("ApplicationMessageTopic"); _publishableExceptionConsumer = new PublishableExceptionConsumer(setting: new ConsumerSetting { ConsumeFromWhere = ConsumeFromWhere.FirstOffset }).Subscribe("PublishableExceptionTopic"); return(enodeConfiguration); }
public ProducerSetting() { BrokerAddress = new IPEndPoint(SocketUtils.GetLocalIPV4(), 5000); UpdateTopicQueueCountInterval = 1000 * 5; }
public NRpcServer(int port) : this(SocketUtils.GetLocalIPV4(), port) { }
public static ENodeConfiguration UseEQueue(this ENodeConfiguration enodeConfiguration) { var configuration = enodeConfiguration.GetCommonConfiguration(); var brokerStorePath = @"d:\equeue-store"; if (Directory.Exists(brokerStorePath)) { Directory.Delete(brokerStorePath, true); } configuration.RegisterEQueueComponents(); _broker = BrokerController.Create(); _commandService = new CommandService(new CommandResultProcessor(new IPEndPoint(SocketUtils.GetLocalIPV4(), 9001))); configuration.SetDefault <ICommandService, CommandService>(_commandService); _commandConsumer = new CommandConsumer(setting: new ConsumerSetting { ConsumeFromWhere = ConsumeFromWhere.FirstOffset }).Subscribe("NoteCommandTopic"); return(enodeConfiguration); }
public BrokerSetting(bool isMessageStoreMemoryMode = false, string chunkFileStoreRootPath = @"c:\equeue-store", int messageChunkDataSize = 1024 * 1024 * 1024, int chunkFlushInterval = 100, int chunkCacheMaxCount = 10, int chunkCacheMinCount = 2, int maxLogRecordSize = 5 * 1024 * 1024, int chunkWriteBuffer = 128 * 1024, int chunkReadBuffer = 128 * 1024, bool syncFlush = false, FlushOption flushOption = FlushOption.FlushToOS, bool enableCache = true, int messageChunkLocalCacheSize = 300000, int queueChunkLocalCacheSize = 10000) { BrokerInfo = new BrokerInfo( "DefaultBroker", "DefaultGroup", "DefaultCluster", BrokerRole.Master, new IPEndPoint(SocketUtils.GetLocalIPV4(), 5000).ToAddress(), new IPEndPoint(SocketUtils.GetLocalIPV4(), 5001).ToAddress(), new IPEndPoint(SocketUtils.GetLocalIPV4(), 5002).ToAddress()); NameServerList = new List <IPEndPoint>() { new IPEndPoint(SocketUtils.GetLocalIPV4(), 9493) }; IsDebugMode = false; NotifyWhenMessageArrived = true; RegisterBrokerToNameServerInterval = 1000 * 5; DeleteMessagesInterval = 1000 * 10; DeleteQueueMessagesInterval = 1000 * 10; DeleteMessageIgnoreUnConsumed = true; PersistConsumeOffsetInterval = 1000 * 1; CheckBlockingPullRequestMilliseconds = 1000 * 1; ProducerExpiredTimeout = 1000 * 30; ConsumerExpiredTimeout = 1000 * 30; RemoveConsumerWhenDisconnect = true; AutoCreateTopic = true; TopicDefaultQueueCount = 4; TopicMaxQueueCount = 256; MessageMaxSize = 1024 * 1024 * 4; MessageWriteQueueThreshold = 2 * 10000; BatchMessageWriteQueueThreshold = 1 * 10000; IsMessageStoreMemoryMode = isMessageStoreMemoryMode; FileStoreRootPath = chunkFileStoreRootPath; LatestMessageShowCount = 100; MessageChunkConfig = new ChunkManagerConfig( Path.Combine(chunkFileStoreRootPath, @"message-chunks"), new DefaultFileNamingStrategy("message-chunk-"), messageChunkDataSize, 0, 0, chunkFlushInterval, enableCache, syncFlush, flushOption, Environment.ProcessorCount * 8, maxLogRecordSize, chunkWriteBuffer, chunkReadBuffer, chunkCacheMaxCount, chunkCacheMinCount, 1, 5, messageChunkLocalCacheSize, true); QueueChunkConfig = new ChunkManagerConfig( Path.Combine(chunkFileStoreRootPath, @"queue-chunks"), new DefaultFileNamingStrategy("queue-chunk-"), 0, 12, 1000000, chunkFlushInterval, enableCache, syncFlush, flushOption, Environment.ProcessorCount * 2, 12, chunkWriteBuffer, chunkReadBuffer, chunkCacheMaxCount, chunkCacheMinCount, 1, 5, queueChunkLocalCacheSize, false); }
async Task <Stream> ConnectAsync(string host, int port, bool doAsync, CancellationToken cancellationToken) { ValidateArguments(host, port); cancellationToken.ThrowIfCancellationRequested(); var socket = await SocketUtils.ConnectAsync(ProxyHost, ProxyPort, LocalEndPoint, doAsync, cancellationToken).ConfigureAwait(false); var command = GetConnectCommand(host, port, ProxyCredentials); try { await SendAsync(socket, command, 0, command.Length, doAsync, cancellationToken).ConfigureAwait(false); var buffer = ArrayPool <byte> .Shared.Rent(BufferSize); var builder = new StringBuilder(); try { var endOfHeaders = false; var newline = false; // read until we consume the end of the headers (it's ok if we read some of the content) do { int nread = await ReceiveAsync(socket, buffer, 0, BufferSize, doAsync, cancellationToken).ConfigureAwait(false); if (nread > 0) { int n = nread; for (int i = 0; i < nread && !endOfHeaders; i++) { switch ((char)buffer[i]) { case '\r': break; case '\n': endOfHeaders = newline; newline = true; if (endOfHeaders) { n = i + 1; } break; default: newline = false; break; } } builder.Append(Encoding.UTF8.GetString(buffer, 0, n)); } } while (!endOfHeaders); } finally { ArrayPool <byte> .Shared.Return(buffer); } int index = 0; while (builder[index] != '\n') { index++; } if (index > 0 && builder[index - 1] == '\r') { index--; } // trim everything beyond the "HTTP/1.1 200 ..." part of the response builder.Length = index; var response = builder.ToString(); if (response.Length >= 15 && response.StartsWith("HTTP/1.", StringComparison.OrdinalIgnoreCase) && (response[7] == '1' || response[7] == '0') && response[8] == ' ' && response[9] == '2' && response[10] == '0' && response[11] == '0' && response[12] == ' ') { return(new NetworkStream(socket, true)); } throw new ProxyProtocolException(string.Format(CultureInfo.InvariantCulture, "Failed to connect to {0}:{1}: {2}", host, port, response)); } catch { #if !NETSTANDARD1_3 && !NETSTANDARD1_6 if (socket.Connected) { socket.Disconnect(false); } #endif socket.Dispose(); throw; } }
protected void Reply(TResponse response, Socket client) { byte[] data = SerializationUtils.SerializeToStreamWithLength(response); SocketUtils.SendAll(client, data); }
private bool DoProtocolRequest() { //取前4字节 byte[] buffer; IPAddress ipAddress = null; byte rep = 0x07; //不支持的命令 if (SocketUtils.Receive(this.Client, 4, out buffer)) { if (buffer.Length == 4) { //判断地址类型 switch (buffer[3]) { case 0x01: this.Type = 1; //IPV4 if (SocketUtils.Receive(this.Client, 4, out buffer)) { ipAddress = new IPAddress(buffer); } break; case 0x03: this.Type = 3; //域名 if (SocketUtils.Receive(this.Client, 1, out buffer)) { //取得域名的长度 if (SocketUtils.Receive(this.Client, (uint)(buffer[0]), out buffer)) { //取得域名地址 string address = Encoding.ASCII.GetString(buffer); try { IPAddress[] addresses = Dns.GetHostAddresses(address); if (addresses.Length != 0) { ipAddress = addresses[0]; this.Address = address; } else { rep = 0x04; //主机不可达 } } catch (Exception e) { LogController.Error("Dns error: " + e.Message); } } } break; case 0x04: this.Type = 4; //IPV6; if (SocketUtils.Receive(this.Client, 16, out buffer)) { ipAddress = new IPAddress(buffer); } break; default: rep = 0x08; //不支持的地址类型 break; } } } if (ipAddress != null && rep == 0x07) { //取得端口号 if (SocketUtils.Receive(this.Client, 2, out buffer)) { Array.Reverse(buffer); //反转端口值 if (this.Type == 1 || this.Type == 4) { this.RemoteEndPoint = new IPEndPoint(ipAddress, BitConverter.ToUInt16(buffer, 0)); } else { this.RemotePort = BitConverter.ToUInt16(buffer, 0); } rep = 0x00; } } //输出应答 MemoryStream stream = new MemoryStream(); stream.WriteByte(0x05); stream.WriteByte(rep); stream.WriteByte(0x00); stream.WriteByte(0x01); IPEndPoint localEP = (IPEndPoint)Client.LocalEndPoint; byte[] localIP = localEP.Address.GetAddressBytes(); stream.Write(localIP, 0, localIP.Length); byte[] localPort = BitConverter.GetBytes((ushort)IPAddress.HostToNetworkOrder(localEP.Port)); stream.Write(localPort, 0, localPort.Length); SocketUtils.Send(this.Client, stream.ToArray()); return(this.RemoteEndPoint != null || this.Address != null); }
async Task <Socket> ConnectAsync(string host, int port, bool doAsync, CancellationToken cancellationToken) { ValidateArguments(host, port); cancellationToken.ThrowIfCancellationRequested(); var socket = await SocketUtils.ConnectAsync(ProxyHost, ProxyPort, LocalEndPoint, doAsync, cancellationToken).ConfigureAwait(false); var builder = new StringBuilder(); builder.AppendFormat(CultureInfo.InvariantCulture, "CONNECT {0}:{1} HTTP/1.1\r\n", host, port); builder.AppendFormat(CultureInfo.InvariantCulture, "Host: {0}:{1}\r\n", host, port); if (ProxyCredentials != null) { var token = Encoding.UTF8.GetBytes(string.Format(CultureInfo.InvariantCulture, "{0}:{1}", ProxyCredentials.UserName, ProxyCredentials.Password)); var base64 = Convert.ToBase64String(token); builder.AppendFormat(CultureInfo.InvariantCulture, "Proxy-Authorization: Basic {0}\r\n", base64); } builder.Append("\r\n"); var command = Encoding.UTF8.GetBytes(builder.ToString()); try { await SendAsync(socket, command, 0, command.Length, doAsync, cancellationToken).ConfigureAwait(false); var buffer = new byte[1024]; var endOfHeaders = false; var newline = false; builder.Clear(); // read until we consume the end of the headers (it's ok if we read some of the content) do { int nread = await ReceiveAsync(socket, buffer, 0, buffer.Length, doAsync, cancellationToken).ConfigureAwait(false); if (nread > 0) { int n = nread; for (int i = 0; i < nread && !endOfHeaders; i++) { switch ((char)buffer[i]) { case '\r': break; case '\n': endOfHeaders = newline; newline = true; if (endOfHeaders) { n = i + 1; } break; default: newline = false; break; } } builder.Append(Encoding.UTF8.GetString(buffer, 0, n)); } } while (!endOfHeaders); int index = 0; while (builder[index] != '\n') { index++; } if (index > 0 && builder[index - 1] == '\r') { index--; } // trim everything beyond the "HTTP/1.1 200 ..." part of the response builder.Length = index; var response = builder.ToString(); if (response.Length >= 15 && response.StartsWith("HTTP/1.", StringComparison.OrdinalIgnoreCase) && (response[7] == '1' || response[7] == '0') && response[8] == ' ' && response[9] == '2' && response[10] == '0' && response[11] == '0' && response[12] == ' ') { return(socket); } throw new ProxyProtocolException(string.Format(CultureInfo.InvariantCulture, "Failed to connect to {0}:{1}: {2}", host, port, response)); } catch { #if !NETSTANDARD1_3 && !NETSTANDARD1_6 if (socket.Connected) { socket.Disconnect(false); } #endif socket.Dispose(); throw; } }
public static ENodeConfiguration StartEQueue(this ENodeConfiguration enodeConfiguration) { var nameServerEndpoint = new IPEndPoint(SocketUtils.GetLocalIPV4(), ConfigSettings.NameServerPort); var nameServerEndpoints = new List <IPEndPoint> { nameServerEndpoint }; var commandResultProcessor = new CommandResultProcessor().Initialize(new IPEndPoint(SocketUtils.GetLocalIPV4(), ConfigSettings.TimerTaskPort)); _commandService.Initialize(commandResultProcessor, new ProducerSetting { NameServerList = nameServerEndpoints }); _commandService.Start(); return(enodeConfiguration); }
public ClientChannel(IChannelPipeline pipeline, IByteBuffer buffer, IFramer framer) : base(buffer, framer) { this.pipeline = pipeline; base.SetSocket(SocketUtils.CreateSocket()); }
public Boolean ShouldReturnWhetherExceptionIsSocketError(Exception exception, SocketError[] errors) { return(SocketUtils.IsSocketException(exception, errors)); }
// This method accepts new connections private void ConnectRequestCallback(IAsyncResult ar) { Socket listenerSocket = (Socket)ar.AsyncState; Socket clientSocket; try { clientSocket = listenerSocket.EndAccept(ar); } catch (ObjectDisposedException) { return; } catch (SocketException ex) { const int WSAECONNRESET = 10054; // The client may have closed the connection before we start to process the connection request. const int WSAETIMEDOUT = 10060; // The client did not properly respond after a period of time. // When we get WSAECONNRESET or WSAETIMEDOUT, we have to continue to accept other connection requests. // See http://stackoverflow.com/questions/7704417/socket-endaccept-error-10054 if (ex.ErrorCode == WSAECONNRESET || ex.ErrorCode == WSAETIMEDOUT) { listenerSocket.BeginAccept(ConnectRequestCallback, listenerSocket); } Log(Severity.Debug, "Connection request error {0}", ex.ErrorCode); return; } // Windows will set the TCP keepalive timeout to 120 seconds for an SMB connection SocketUtils.SetKeepAlive(clientSocket, TimeSpan.FromMinutes(2)); // Disable the Nagle Algorithm for this tcp socket: clientSocket.NoDelay = true; IPEndPoint clientEndPoint = (IPEndPoint)clientSocket.RemoteEndPoint; EventHandler <ConnectionRequestEventArgs> handler = ConnectionRequested; bool acceptConnection = true; if (handler != null) { ConnectionRequestEventArgs connectionRequestArgs = new ConnectionRequestEventArgs(clientEndPoint); handler(this, connectionRequestArgs); acceptConnection = connectionRequestArgs.Accept; } if (acceptConnection) { ConnectionState state = new ConnectionState(clientSocket, clientEndPoint, Log); state.LogToServer(Severity.Verbose, "New connection request accepted"); Thread senderThread = new Thread(delegate() { ProcessSendQueue(state); }); senderThread.IsBackground = true; senderThread.Start(); try { // Direct TCP transport packet is actually an NBT Session Message Packet, // So in either case (NetBios over TCP or Direct TCP Transport) we will receive an NBT packet. clientSocket.BeginReceive(state.ReceiveBuffer.Buffer, state.ReceiveBuffer.WriteOffset, state.ReceiveBuffer.AvailableLength, 0, ReceiveCallback, state); } catch (ObjectDisposedException) { } catch (SocketException) { } } else { Log(Severity.Verbose, "[{0}:{1}] New connection request rejected", clientEndPoint.Address, clientEndPoint.Port); clientSocket.Close(); } listenerSocket.BeginAccept(ConnectRequestCallback, listenerSocket); }
public void Stop() { Log(Severity.Information, "Stopping server"); m_listening = false; SocketUtils.ReleaseSocket(m_listenerSocket); }
public SocketRemotingClient() : this(new IPEndPoint(SocketUtils.GetLocalIPV4(), 5000)) { }
public static ENodeConfiguration StartEQueue(this ENodeConfiguration enodeConfiguration) { var brokerStorePath = ConfigurationManager.AppSettings["equeue-store-path"]; if (Directory.Exists(brokerStorePath)) { Directory.Delete(brokerStorePath, true); } _commandService.InitializeEQueue(new CommandResultProcessor().Initialize(new IPEndPoint(SocketUtils.GetLocalIPV4(), 9000))); _applicationMessagePublisher.InitializeEQueue(); _domainEventPublisher.InitializeEQueue(); _exceptionPublisher.InitializeEQueue(); _nameServerController = new NameServerController(); _broker = BrokerController.Create(new BrokerSetting(chunkFileStoreRootPath: brokerStorePath)); _commandConsumer = new CommandConsumer().InitializeEQueue().Subscribe(Constants.CommandTopic); _applicationMessageConsumer = new ApplicationMessageConsumer().InitializeEQueue().Subscribe(Constants.ApplicationMessageTopic); _eventConsumer = new DomainEventConsumer().InitializeEQueue().Subscribe(Constants.EventTopic); _exceptionConsumer = new PublishableExceptionConsumer().InitializeEQueue().Subscribe(Constants.ExceptionTopic); _nameServerSocketRemotingClient = new SocketRemotingClient("NameServerRemotingClient", new IPEndPoint(SocketUtils.GetLocalIPV4(), 9493)); _nameServerController.Start(); _broker.Start(); _exceptionConsumer.Start(); _eventConsumer.Start(); _applicationMessageConsumer.Start(); _commandConsumer.Start(); _applicationMessagePublisher.Start(); _domainEventPublisher.Start(); _exceptionPublisher.Start(); _commandService.Start(); _nameServerSocketRemotingClient.Start(); //生产环境不需要以下这段代码 CreateTopic(Constants.CommandTopic); CreateTopic(Constants.EventTopic); CreateTopic(Constants.ApplicationMessageTopic); CreateTopic(Constants.ExceptionTopic); WaitAllProducerTopicQueuesAvailable(); WaitAllConsumerLoadBalanceComplete(); return enodeConfiguration; }
public static ENodeConfiguration StartEQueue(this ENodeConfiguration enodeConfiguration) { if (_isEQueueStarted) { _commandService.InitializeENode(); _eventPublisher.InitializeENode(); _applicationMessagePublisher.InitializeENode(); _domainExceptionPublisher.InitializeENode(); _commandConsumer.InitializeENode(); _eventConsumer.InitializeENode(); _applicationMessageConsumer.InitializeENode(); _domainExceptionConsumer.InitializeENode(); return(enodeConfiguration); } var localIp = SocketUtils.GetLocalIPV4(); var nameserverPoint = 9493; var nameserverSetting = new NameServerSetting { BindingAddress = new IPEndPoint(localIp, nameserverPoint), IsDebugMode = true }; var brokerStorePath = @"d:\equeue-store-enode-ut"; var brokerSetting = new BrokerSetting(chunkFileStoreRootPath: brokerStorePath) { NameServerList = new List <IPEndPoint> { new IPEndPoint(localIp, nameserverPoint) }, IsDebugMode = true }; brokerSetting.BrokerInfo.ProducerAddress = new IPEndPoint(localIp, 5000).ToAddress(); brokerSetting.BrokerInfo.ConsumerAddress = new IPEndPoint(localIp, 5001).ToAddress(); brokerSetting.BrokerInfo.AdminAddress = new IPEndPoint(localIp, 5002).ToAddress(); var producerSetting = new ProducerSetting { NameServerList = new List <IPEndPoint> { new IPEndPoint(localIp, nameserverPoint) } }; var consumerSetting = new ConsumerSetting { NameServerList = new List <IPEndPoint> { new IPEndPoint(localIp, nameserverPoint) }, ConsumeFromWhere = ConsumeFromWhere.LastOffset }; if (Directory.Exists(brokerStorePath)) { Directory.Delete(brokerStorePath, true); } _nameServerController = new NameServerController(nameserverSetting); _broker = BrokerController.Create(brokerSetting); var commandResultProcessor = new CommandResultProcessor().Initialize(new IPEndPoint(localIp, 9001)); _commandService.InitializeEQueue(commandResultProcessor, producerSetting); _eventPublisher.InitializeEQueue(producerSetting); _applicationMessagePublisher.InitializeEQueue(producerSetting); _domainExceptionPublisher.InitializeEQueue(producerSetting); _commandConsumer = new CommandConsumer().InitializeEQueue(setting: consumerSetting).Subscribe("CommandTopic"); _eventConsumer = new DomainEventConsumer().InitializeEQueue(setting: consumerSetting).Subscribe("EventTopic"); _applicationMessageConsumer = new ApplicationMessageConsumer().InitializeEQueue(setting: consumerSetting).Subscribe("ApplicationMessageTopic"); _domainExceptionConsumer = new DomainExceptionConsumer().InitializeEQueue(setting: consumerSetting).Subscribe("DomainExceptionTopic"); _nameServerSocketRemotingClient = new SocketRemotingClient("NameServerRemotingClient", new IPEndPoint(localIp, nameserverPoint)); _nameServerController.Start(); _broker.Start(); _eventConsumer.Start(); _commandConsumer.Start(); _applicationMessageConsumer.Start(); _domainExceptionConsumer.Start(); _applicationMessagePublisher.Start(); _domainExceptionPublisher.Start(); _eventPublisher.Start(); _commandService.Start(); _nameServerSocketRemotingClient.Start(); CreateTopic(Constants.CommandTopic); CreateTopic(Constants.EventTopic); CreateTopic(Constants.ApplicationMessageTopic); CreateTopic(Constants.ExceptionTopic); WaitAllProducerTopicQueuesAvailable(); WaitAllConsumerLoadBalanceComplete(); _isEQueueStarted = true; return(enodeConfiguration); }
public static ENodeConfiguration StartKafka(this ENodeConfiguration enodeConfiguration) { var kafkaConfig = ObjectContainer.Resolve <Jane.ENode.IKafkaConfiguration>(); var producerSetting = new ProducerSetting { BrokerEndPoints = kafkaConfig.BrokerEndPoints }; var commandConsumerSetting = new ConsumerSetting { BrokerEndPoints = kafkaConfig.BrokerEndPoints, GroupName = "BoundedContextCommandConsumerGroup" }; var eventConsumerSetting = new ConsumerSetting { BrokerEndPoints = kafkaConfig.BrokerEndPoints, GroupName = "BoundedContextDomainEventConsumerGroup" }; var applicationMessageConsumerSetting = new ConsumerSetting { BrokerEndPoints = kafkaConfig.BrokerEndPoints, GroupName = "BoundedContextApplicationMessageConsumerGroup" }; var domainExceptionConsumerSetting = new ConsumerSetting { BrokerEndPoints = kafkaConfig.BrokerEndPoints, GroupName = "BoundedContextDomainExceptionConsumerGroup" }; _commandConsumer = new CommandConsumer() .InitializeKafka(commandConsumerSetting) .Subscribe(new List <string>() { BoundedContextTopics.BoundedContextDomainCommandTopic }); _eventConsumer = new DomainEventConsumer() .InitializeKafka(eventConsumerSetting) .Subscribe(new List <string>() { BoundedContextTopics.BoundedContextDomainDomainEventTopic }); _applicationMessageConsumer = new ApplicationMessageConsumer() .InitializeKafka(applicationMessageConsumerSetting) .Subscribe(new List <string>() { BoundedContextTopics.BoundedContextDomainApplicationMessageTopic }); _domainExceptionConsumer = new DomainExceptionConsumer() .InitializeKafka(domainExceptionConsumerSetting) .Subscribe(new List <string>() { BoundedContextTopics.BoundedContextDomainExceptionTopic }); _commandResultProcessor = new CommandResultProcessor() .Initialize(new IPEndPoint(SocketUtils.GetLocalIPV4(), 9003)); _commandService.InitializeKafka(producerSetting, _commandResultProcessor); _eventPublisher.InitializeKafka(producerSetting); _applicationMessagePublisher.InitializeKafka(producerSetting); _domainExceptionPublisher.InitializeKafka(producerSetting); _commandConsumer.Start(); _eventConsumer.Start(); _applicationMessageConsumer.Start(); _domainExceptionConsumer.Start(); _commandResultProcessor.Start(); _commandService.Start(); _eventPublisher.Start(); _applicationMessagePublisher.Start(); _domainExceptionPublisher.Start(); return(enodeConfiguration); }
async Task <Socket> ConnectAsync(string host, int port, bool doAsync, CancellationToken cancellationToken) { byte[] addr, domain = null; IPAddress ip; ValidateArguments(host, port); if (!IPAddress.TryParse(host, out ip)) { if (IsSocks4a) { domain = Encoding.UTF8.GetBytes(host); addr = InvalidIPAddress; } else { ip = await ResolveAsync(host, doAsync, cancellationToken).ConfigureAwait(false); addr = ip.GetAddressBytes(); } } else { if (ip.AddressFamily != AddressFamily.InterNetwork) { throw new ArgumentException("The specified host address must be IPv4.", nameof(host)); } addr = ip.GetAddressBytes(); } cancellationToken.ThrowIfCancellationRequested(); var socket = await SocketUtils.ConnectAsync(ProxyHost, ProxyPort, LocalEndPoint, doAsync, cancellationToken).ConfigureAwait(false); var user = ProxyCredentials != null?Encoding.UTF8.GetBytes(ProxyCredentials.UserName) : new byte[0]; try { // +----+-----+----------+----------+----------+-------+--------------+-------+ // |VER | CMD | DST.PORT | DST.ADDR | USERID | NULL | DST.DOMAIN | NULL | // +----+-----+----------+----------+----------+-------+--------------+-------+ // | 1 | 1 | 2 | 4 | VARIABLE | X'00' | VARIABLE | X'00' | // +----+-----+----------+----------+----------+-------+--------------+-------+ int bufferSize = 9 + user.Length + (domain != null ? domain.Length + 1 : 0); var buffer = new byte[bufferSize]; int nread, n = 0; buffer[n++] = (byte)SocksVersion; buffer[n++] = (byte)Socks4Command.Connect; buffer[n++] = (byte)(port >> 8); buffer[n++] = (byte)port; Buffer.BlockCopy(addr, 0, buffer, n, 4); n += 4; Buffer.BlockCopy(user, 0, buffer, n, user.Length); n += user.Length; buffer[n++] = 0x00; if (domain != null) { Buffer.BlockCopy(domain, 0, buffer, n, domain.Length); n += domain.Length; buffer[n++] = 0x00; } await SendAsync(socket, buffer, 0, n, doAsync, cancellationToken).ConfigureAwait(false); // +-----+-----+----------+----------+ // | VER | REP | BND.PORT | BND.ADDR | // +-----+-----+----------+----------+ // | 1 | 1 | 2 | 4 | // +-----+-----+----------+----------+ n = 0; do { if ((nread = await ReceiveAsync(socket, buffer, 0 + n, 8 - n, doAsync, cancellationToken).ConfigureAwait(false)) > 0) { n += nread; } } while (n < 8); if (buffer[1] != (byte)Socks4Reply.RequestGranted) { throw new ProxyProtocolException(string.Format(CultureInfo.InvariantCulture, "Failed to connect to {0}:{1}: {2}", host, port, GetFailureReason(buffer[1]))); } // TODO: do we care about BND.ADDR and BND.PORT? return(socket); } catch { #if !NETSTANDARD1_3 && !NETSTANDARD1_6 if (socket.Connected) { socket.Disconnect(false); } #endif socket.Dispose(); throw; } }
public static ENodeConfiguration UseEQueue(this ENodeConfiguration enodeConfiguration) { var configuration = enodeConfiguration.GetCommonConfiguration(); configuration.RegisterEQueueComponents(); _commandService = new CommandService(new CommandResultProcessor(new IPEndPoint(SocketUtils.GetLocalIPV4(), 9001)), new ProducerSetting { NameServerList = new List <IPEndPoint> { new IPEndPoint(SocketUtils.GetLocalIPV4(), ConfigSettings.NameServerPort) } }); configuration.SetDefault <ICommandService, CommandService>(_commandService); return(enodeConfiguration); }
public static ENodeConfiguration StartEQueue(this ENodeConfiguration enodeConfiguration) { if (_isEQueueStarted) { _commandService.InitializeENode(); _eventPublisher.InitializeENode(); _applicationMessagePublisher.InitializeENode(); _publishableExceptionPublisher.InitializeENode(); _commandConsumer.InitializeENode(); _eventConsumer.InitializeENode(); _applicationMessageConsumer.InitializeENode(); _publishableExceptionConsumer.InitializeENode(); return(enodeConfiguration); } var brokerStorePath = @"d:\equeue-store-enode-ut"; var brokerSetting = new BrokerSetting(chunkFileStoreRootPath: brokerStorePath); if (Directory.Exists(brokerStorePath)) { Directory.Delete(brokerStorePath, true); } _nameServerController = new NameServerController(); _broker = BrokerController.Create(brokerSetting); _commandService.InitializeEQueue(new CommandResultProcessor().Initialize(new IPEndPoint(SocketUtils.GetLocalIPV4(), 9001))); _eventPublisher.InitializeEQueue(); _applicationMessagePublisher.InitializeEQueue(); _publishableExceptionPublisher.InitializeEQueue(); _commandConsumer = new CommandConsumer().InitializeEQueue(setting: new ConsumerSetting { ConsumeFromWhere = ConsumeFromWhere.LastOffset }).Subscribe("CommandTopic"); _eventConsumer = new DomainEventConsumer().InitializeEQueue(setting: new ConsumerSetting { ConsumeFromWhere = ConsumeFromWhere.LastOffset }).Subscribe("EventTopic"); _applicationMessageConsumer = new ApplicationMessageConsumer().InitializeEQueue(setting: new ConsumerSetting { ConsumeFromWhere = ConsumeFromWhere.LastOffset }).Subscribe("ApplicationMessageTopic"); _publishableExceptionConsumer = new PublishableExceptionConsumer().InitializeEQueue(setting: new ConsumerSetting { ConsumeFromWhere = ConsumeFromWhere.LastOffset }).Subscribe("PublishableExceptionTopic"); _nameServerSocketRemotingClient = new SocketRemotingClient("NameServerRemotingClient", new IPEndPoint(SocketUtils.GetLocalIPV4(), 9493)); _nameServerController.Start(); _broker.Start(); _eventConsumer.Start(); _commandConsumer.Start(); _applicationMessageConsumer.Start(); _publishableExceptionConsumer.Start(); _applicationMessagePublisher.Start(); _publishableExceptionPublisher.Start(); _eventPublisher.Start(); _commandService.Start(); _nameServerSocketRemotingClient.Start(); CreateTopic(Constants.CommandTopic); CreateTopic(Constants.EventTopic); CreateTopic(Constants.ApplicationMessageTopic); CreateTopic(Constants.ExceptionTopic); WaitAllProducerTopicQueuesAvailable(); WaitAllConsumerLoadBalanceComplete(); _isEQueueStarted = true; return(enodeConfiguration); }
protected override async Task <Socket> ClientCommandReceived(Stream client, byte[] buffer, int length, CancellationToken cancellationToken) { byte[] response = null; Socket server = null; Buffer.BlockCopy(buffer, 0, request, requestLength, length); requestLength += length; switch (state) { case Socks5ListenerState.NegotiateAuthMethod: response = NegotiateAuthMethod(); break; case Socks5ListenerState.Authenticate: response = Authenticate(); break; case Socks5ListenerState.Command: var result = Parse(request, requestLength, out Socks5Command cmd, out string host, out int port); switch (result) { case Socks5ParseResult.Success: try { server = await SocketUtils.ConnectAsync(host, port, null, true, cancellationToken).ConfigureAwait(false); var remote = (IPEndPoint)server.RemoteEndPoint; response = GetCommandResponse(Socks5Reply.Success, remote); } catch (OperationCanceledException) { throw; } catch (SocketException ex) { response = GetCommandResponse(ex.SocketErrorCode); } catch { response = GetCommandResponse(Socks5Reply.GeneralServerFailure, null); } break; case Socks5ParseResult.InvalidAddrType: response = GetCommandResponse(Socks5Reply.AddressTypeNotSupported, null); break; case Socks5ParseResult.InvalidCommand: response = GetCommandResponse(Socks5Reply.CommandNotSupported, null); break; case Socks5ParseResult.NotEnoughData: response = null; break; case Socks5ParseResult.InvalidRequest: default: response = GetCommandResponse(Socks5Reply.GeneralServerFailure, null); break; } break; } if (response == null) { return(null); } await client.WriteAsync(response, 0, response.Length, cancellationToken).ConfigureAwait(false); requestLength = 0; return(server); }
public static ENodeConfiguration StartEQueue(this ENodeConfiguration enodeConfiguration) { var commandResultPort = ConfigHelper.ValueInt("CommandResultPort"); var commandResultProcessor = new CommandResultProcessor().Initialize(new IPEndPoint(SocketUtils.GetLocalIPV4(), commandResultPort)); _commandService.Initialize(commandResultProcessor, new ProducerSetting { NameServerList = ServiceConfigSettings.NameServerEndpoints }); _commandService.Start(); return(enodeConfiguration); }
private void CreateProxyBridge() { if (this.Client.Connected) { TcpClient proxyClient = null; try { proxyClient = new TcpClient(TunnelConfig.Host, TunnelConfig.Port); proxyClient.Client.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, 1); } catch (Exception e) { LogController.Error("A error occured when creating a tunnel: " + e.Message); this.Close(); return; } if (proxyClient != null) { this.Proxy = proxyClient; try { //this.Proxy.Connect(TunnelConfig.Host, TunnelConfig.Port); if (this.Proxy.Connected) {// Send Bind Message // // 0 1 2 4 5 - ? // 0x07 0x02 CMD TYPE VARIABLE // 3 Type of Message: // // 0 1 2 3 4-7 8-9 // 0x07 0x02 CMD 0x01 DESTIP PORT // 0 1 2 3 4-5 6-7 8-? // 0x07 0x02 CMD 0x03 DOMAINLEN PORT DOMAIN // 0 1 2 3 4 - 19 20-21 // 0x07 0x02 CMD 0x04 DESTIP PORT // CMD = 0x02 - Bind Request // TYPE = 0x01 - IPv4 // TYPE = 0x03 - Domain // TYPE = 0x04 - IPv6 //构造数据包 byte[] sendBuffer = new byte[0]; byte[] b_domain = new byte[0]; switch (this.Type) { case 1: sendBuffer = new byte[12]; break; case 3: b_domain = Encoding.UTF8.GetBytes(this.Address); sendBuffer = new byte[10 + b_domain.Length]; break; case 4: sendBuffer = new byte[24]; break; default: this.Close(); break; } sendBuffer[0] = 0x07; sendBuffer[1] = 0x02; sendBuffer[2] = 0x02; byte[] b_ip; byte[] b_port; switch (this.Type) { case 1: sendBuffer[3] = 0x01; b_ip = RemoteEndPoint.Address.GetAddressBytes(); b_ip.CopyTo(sendBuffer, 4); b_port = BitConverter.GetBytes(this.RemotePort); sendBuffer[8] = b_port[0]; sendBuffer[9] = b_port[1]; break; case 3: sendBuffer[3] = 0x03; //little endian byte[] b_domainlen = BitConverter.GetBytes(b_domain.Length); sendBuffer[4] = b_domainlen[0]; sendBuffer[5] = b_domainlen[1]; b_port = BitConverter.GetBytes(this.RemotePort); sendBuffer[6] = b_port[0]; sendBuffer[7] = b_port[1]; b_domain.CopyTo(sendBuffer, 8); break; case 4: sendBuffer[3] = 0x04; b_ip = RemoteEndPoint.Address.GetAddressBytes(); b_ip.CopyTo(sendBuffer, 4); b_port = BitConverter.GetBytes(this.RemotePort); sendBuffer[20] = b_port[0]; sendBuffer[21] = b_port[1]; break; } //发送数据包 SocketUtils.Send(this.Proxy.Client, sendBuffer, 0, sendBuffer.Length); _ClientBuffer = new byte[this.Client.ReceiveBufferSize]; _ProxyBuffer = new byte[this.Proxy.ReceiveBufferSize]; this.Client.BeginReceive(_ClientBuffer, 0, _ClientBuffer.Length, SocketFlags.None, this.OnClientReceive, this.Client); this.Proxy.Client.BeginReceive(_ProxyBuffer, 0, _ProxyBuffer.Length, SocketFlags.None, this.OnProxyReceive, this.Proxy.Client); } else { this.Close(); } } catch (Exception e) { LogController.Error("Find some error on start receive: " + e.Message); this.Close(); } } else { LogController.Error("Failed to establish proxy tunnel."); this.Close(); } } else { this.Close(); } }