internal static Socket CreateSocket(IPMode ipMode) { Socket socket; if (ipMode == IPMode.IPv4) { socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); } else { if (!Socket.OSSupportsIPv6) { throw new InvalidOperationException("IPV6 not supported!"); } socket = new Socket(AddressFamily.InterNetworkV6, SocketType.Dgram, ProtocolType.Udp); socket.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.IPv6Only, false); } try { socket.DontFragment = false; } catch { } try { const int SIO_UDP_CONNRESET = -1744830452; socket.IOControl(SIO_UDP_CONNRESET, new byte[1], null); } catch { } // Only necessary on Windows return(socket); }
/// <summary> /// Creates a new UdpConnectionListener for the given <see cref="IPAddress"/>, port and <see cref="IPMode"/>. /// </summary> /// <param name="endPoint">The endpoint to listen on.</param> public UdpConnectionListener(IPEndPoint endPoint, IPMode ipMode = IPMode.IPv4, Action <string> logger = null) { this.Logger = logger; this.EndPoint = endPoint; this.IPMode = ipMode; if (this.IPMode == IPMode.IPv4) { this.socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); } else { if (!Socket.OSSupportsIPv6) { throw new HazelException("IPV6 not supported!"); } this.socket = new Socket(AddressFamily.InterNetworkV6, SocketType.Dgram, ProtocolType.Udp); this.socket.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.IPv6Only, false); } socket.ReceiveBufferSize = BufferSize; socket.SendBufferSize = BufferSize; reliablePacketTimer = new Timer(ManageReliablePackets, null, 100, Timeout.Infinite); }
public async Task Deliver_Message_Only_When_Referenced_Payloads_Are_Delivered() { AS4Message as4Message = await CreateAS4MessageFrom(deliveragent_message); string deliverLocation = DeliverPayloadLocationOf(as4Message.Attachments.First()); CleanDirectoryAt(Path.GetDirectoryName(deliverLocation)); // Act IPMode pmode = CreateReceivedPMode( deliverMessageLocation: DeliveryRoot, deliverPayloadLocation: @"%# \ (+_O) / -> Not a valid path"); InMessage inMessage = CreateInMessageRepresentingUserMessage(as4Message.GetPrimaryMessageId(), as4Message, pmode); await InsertInMessageAsync(inMessage); // Assert var spy = DatabaseSpy.Create(_as4Msh.GetConfiguration()); InMessage actual = await PollUntilPresent( () => spy.GetInMessageFor(im => im.Id == inMessage.Id && im.Status == InStatus.Exception.ToString()), TimeSpan.FromSeconds(10)); Assert.Empty(Directory.EnumerateFiles(DeliveryRoot)); Assert.Equal(InStatus.Exception, actual.Status.ToEnum <InStatus>()); Assert.Equal(Operation.DeadLettered, actual.Operation); }
/// <summary> /// Converts CommandLineArgument values to an IP address if possible. /// Throws Exception if not. /// </summary> /// <param name="ipmode"></param> /// <param name="v6"></param> /// <param name="ipString"></param> /// <returns></returns> /// <exception cref="CassiniException">If IPMode is invalid</exception> /// <exception cref="CassiniException">If IPMode is 'Specific' and ipString is invalid</exception> public static IPAddress ParseIP(IPMode ipmode, bool v6, string ipString) { IPAddress ip; switch (ipmode) { case IPMode.Loopback: ip = v6 ? System.Net.IPAddress.IPv6Loopback : System.Net.IPAddress.Loopback; break; case IPMode.Any: ip = v6 ? System.Net.IPAddress.IPv6Any : System.Net.IPAddress.Any; break; case IPMode.Specific: if (!System.Net.IPAddress.TryParse(ipString, out ip)) { throw new CassiniException(SR.ErrInvalidIPAddress, ErrorField.IPAddress); } break; default: throw new CassiniException(SR.ErrInvalidIPMode, ErrorField.None); } return(ip); }
/// <summary> /// Creates a new UdpConnectionListener for the given <see cref="IPAddress"/>, port and <see cref="IPMode"/>. /// </summary> /// <param name="endPoint">The endpoint to listen on.</param> /// <param name="ipMode"></param> public UdpConnectionListener(IPEndPoint endPoint, ObjectPool <MessageReader> readerPool, IPMode ipMode = IPMode.IPv4) { EndPoint = endPoint; IPMode = ipMode; _readerPool = readerPool; _pool = MemoryPool <byte> .Shared; _socket = new UdpClient(endPoint); try { _socket.DontFragment = false; } catch (SocketException) { } _reliablePacketTimer = new Timer(ManageReliablePackets, null, 100, Timeout.Infinite); _allConnections = new ConcurrentDictionary <EndPoint, UdpServerConnection>(); _stoppingCts = new CancellationTokenSource(); _stoppingCts.Token.Register(() => { _socket.Dispose(); }); _connectionRateLimit = new UdpConnectionRateLimit(); }
private static InvalidDataException CreateInvalidPModeException(IPMode pmode, ValidationResult result) { var errorMessage = result.AppendValidationErrorsToErrorMessage($"Receiving PMode {pmode.Id} is not valid"); Logger.Error(errorMessage); return(new InvalidDataException(errorMessage)); }
public UnityUdpClientConnection(IPEndPoint remoteEndPoint, IPMode ipMode = IPMode.IPv4) : base() { this.EndPoint = remoteEndPoint; this.RemoteEndPoint = remoteEndPoint; this.IPMode = ipMode; this.socket = CreateSocket(ipMode); }
public Client(String host, int port, IPMode ipMode, int rate, int totalEvents, int mtu) { this.host = host; this.port = port; this.rate = rate; this.ipMode = ipMode; this.totalEvents = totalEvents; this.mtu = mtu; }
public UnityUdpClientConnection(IPEndPoint remoteEndPoint, IPMode ipMode = IPMode.IPv4) : base() { this.EndPoint = remoteEndPoint; this.IPMode = ipMode; this.socket = CreateSocket(ipMode); this.socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ExclusiveAddressUse, true); }
/// <summary> /// Creates a new UdpClientConnection. /// </summary> /// <param name="remoteEndPoint">A <see cref="NetworkEndPoint"/> to connect to.</param> public UdpClientConnection(IPEndPoint remoteEndPoint, IPMode ipMode = IPMode.IPv4) : base() { this.EndPoint = remoteEndPoint; this.RemoteEndPoint = remoteEndPoint; this.IPMode = ipMode; this.socket = CreateSocket(ipMode); reliablePacketTimer = new Timer(ManageReliablePacketsInternal, null, 100, Timeout.Infinite); }
/// <summary> /// Create a new instance of the DTLS connection /// </summary> /// <inheritdoc /> public DtlsUnityConnection(ILogger logger, IPEndPoint remoteEndPoint, IPMode ipMode = IPMode.IPv4) : base(remoteEndPoint, ipMode) { this.logger = logger; this.nextEpoch.ServerRandom = new byte[Random.Size]; this.nextEpoch.ClientRandom = new byte[Random.Size]; this.nextEpoch.ServerVerification = new byte[Finished.Size]; this.nextEpoch.CertificateFragments = new List <FragmentRange>(); this.ResetConnectionState(); }
private async Task InsertToBeDeliveredMessagesAsync(AS4Message as4Message) { IPMode pmode = CreateReceivedPMode( deliverMessageLocation: DeliveryRoot, deliverPayloadLocation: DeliveryRoot); foreach (UserMessage userMessage in as4Message.UserMessages) { await InsertInMessageAsync( CreateInMessageRepresentingUserMessage(userMessage.MessageId, as4Message, pmode)); } }
/// <summary> /// Creates a new UdpConnectionListener for the given <see cref="IPAddress"/>, port and <see cref="IPMode"/>. /// </summary> /// <param name="endPoint">The endpoint to listen on.</param> public UdpConnectionListener(IPEndPoint endPoint, IPMode ipMode = IPMode.IPv4, Action <string> logger = null) { this.Logger = logger; this.EndPoint = endPoint; this.IPMode = ipMode; this.socket = UdpConnection.CreateSocket(this.IPMode); socket.ReceiveBufferSize = SendReceiveBufferSize; socket.SendBufferSize = SendReceiveBufferSize; reliablePacketTimer = new Timer(ManageReliablePackets, null, 100, Timeout.Infinite); }
/// <summary> /// Creates a new UdpConnectionListener for the given <see cref="IPAddress"/>, port and <see cref="IPMode"/>. /// </summary> /// <param name="endPoint">The endpoint to listen on.</param> public UdpConnectionListener(IPEndPoint endPoint, IPMode ipMode = IPMode.IPv4, ILogger logger = null) { this.Logger = logger; this.EndPoint = endPoint; this.IPMode = ipMode; this.socket = UdpConnection.CreateSocket(this.IPMode); socket.ReceiveBufferSize = SendReceiveBufferSize; socket.SendBufferSize = SendReceiveBufferSize; reliablePacketTimer = new Thread(ManageReliablePackets); reliablePacketTimer.Start(); }
/// <summary> /// Creates a new UdpClientConnection. /// </summary> /// <param name="remoteEndPoint">A <see cref="NetworkEndPoint"/> to connect to.</param> public UdpClientConnection(IPEndPoint remoteEndPoint, ObjectPool <MessageReader> readerPool, IPMode ipMode = IPMode.IPv4) : base(null, readerPool) { EndPoint = remoteEndPoint; RemoteEndPoint = remoteEndPoint; IPMode = ipMode; _socket = new UdpClient { DontFragment = false }; _reliablePacketTimer = new Timer(ManageReliablePacketsInternal, null, 100, Timeout.Infinite); _connectWaitLock = new SemaphoreSlim(1, 1); }
/// <summary> /// Creates a new ConnectionListener for the given <see cref="IPAddress"/>, port and <see cref="IPMode"/>. /// </summary> /// <param name="IPAddress">The IPAddress to listen on.</param> /// <param name="port">The port to listen on.</param> /// <param name="mode">The <see cref="IPMode"/> to listen with.</param> public UdpConnectionListener(IPAddress IPAddress, int port, IPMode mode = IPMode.IPv4AndIPv6) { this.IPAddress = IPAddress; this.Port = port; if (mode == IPMode.IPv4) { this.listener = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); } else { this.listener = new Socket(AddressFamily.InterNetworkV6, SocketType.Dgram, ProtocolType.Udp); this.listener.DualMode = true; } }
private void InsertRelatedSignedUserMessage(IPMode nrrPMode, AS4Message signedUserMessage) { string location = Registry.Instance.MessageBodyStore .SaveAS4Message(_as4Msh.GetConfiguration().OutMessageStoreLocation, signedUserMessage); var outMessage = new OutMessage(signedUserMessage.GetPrimaryMessageId()) { ContentType = signedUserMessage.ContentType, MessageLocation = location, }; outMessage.SetPModeInformation(nrrPMode); _databaseSpy.InsertOutMessage(outMessage); }
public async ValueTask StartAsync(IPEndPoint ipEndPoint) { IPMode mode = ipEndPoint.AddressFamily switch { AddressFamily.InterNetwork => IPMode.IPv4, AddressFamily.InterNetworkV6 => IPMode.IPv6, _ => throw new InvalidOperationException(), }; _connection = new UdpConnectionListener(ipEndPoint, _readerPool, mode) { NewConnection = OnNewConnection, }; await _connection.StartAsync(); }
private void SetIpMode(IPMode value) { switch (value) { case IPMode.Loopback: IPModeLoopBackRadioButton.Checked = true; break; case IPMode.Any: IPModeAnyRadioButton.Checked = true; break; case IPMode.Specific: RadioButtonIPSpecific.Checked = true; break; } }
public UdpConnectionListener2(IPEndPoint endPoint, ILogger logger, IPMode ipMode = IPMode.IPv4) { this.Logger = logger; this.EndPoint = endPoint; this.IPMode = ipMode; this.socket = UdpConnection.CreateSocket(this.IPMode); this.socket.Blocking = false; this.socket.ReceiveBufferSize = SendReceiveBufferSize; this.socket.SendBufferSize = SendReceiveBufferSize; this.reliablePacketThread = new Thread(ManageReliablePackets); this.sendThread = new Thread(SendLoop); this.receiveThread = new Thread(ReceiveLoop); this.processThreads = new HazelThreadPool(4, ProcessingLoop); }
/// <summary> /// Inserts all the message units of the specified <paramref name="as4Message"/> as <see cref="OutMessage"/> records /// each containing the appropriate Status and Operation. /// User messages will be set to <see cref="Operation.ToBeProcessed"/> /// Signal messages that must be async returned will be set to <see cref="Operation.ToBeSent"/>. /// </summary> /// <param name="as4Message">The message for which the containing message units will be inserted.</param> /// <param name="sendingPMode">The processing mode that will be stored with each message unit if present.</param> /// <param name="receivingPMode">The processing mode that will be used to determine if the signal messages must be async returned, this pmode will be stored together with the message units.</param> public IEnumerable <OutMessage> InsertAS4Message( AS4Message as4Message, SendingProcessingMode sendingPMode, ReceivingProcessingMode receivingPMode) { if (as4Message == null) { throw new ArgumentNullException(nameof(as4Message)); } if (!as4Message.MessageUnits.Any()) { Logger.Trace("Incoming AS4Message hasn't got any message units to insert"); return(Enumerable.Empty <OutMessage>()); } string messageBodyLocation = _messageBodyStore.SaveAS4Message( _configuration.OutMessageStoreLocation, as4Message); IDictionary <string, MessageExchangePattern> relatedInMessageMeps = GetEbsmsMessageIdsOfRelatedSignals(as4Message); var results = new Collection <OutMessage>(); foreach (MessageUnit messageUnit in as4Message.MessageUnits) { IPMode pmode = SendingOrReceivingPMode(messageUnit, sendingPMode, receivingPMode); (OutStatus st, Operation op) = DetermineReplyPattern(messageUnit, relatedInMessageMeps, receivingPMode); OutMessage outMessage = OutMessageBuilder .ForMessageUnit(messageUnit, as4Message.ContentType, pmode) .BuildForSending(messageBodyLocation, st, op); Logger.Debug($"Insert OutMessage {outMessage.EbmsMessageType} with {{Operation={outMessage.Operation}, Status={outMessage.Status}}}"); _repository.InsertOutMessage(outMessage); results.Add(outMessage); } return(results.AsEnumerable()); }
public async Task StartAsync(CancellationToken cancellationToken) { var endpoint = new IPEndPoint(IPAddress.Parse(_config.ResolveListenIp()), _config.ListenPort); IPMode mode = endpoint.AddressFamily switch { AddressFamily.InterNetwork => IPMode.IPv4, AddressFamily.InterNetworkV6 => IPMode.IPv6, _ => throw new InvalidOperationException(), }; _connection = new UdpConnectionListener(endpoint, _readerPool, mode) { NewConnection = OnNewConnection, }; await _connection.StartAsync(); _logger.LogInformation("Announcements server is listening on {Address}:{Port}", endpoint.Address, endpoint.Port); }
private static InMessage CreateInMessageRepresentingUserMessage( string ebmsMessageId, AS4Message as4Message, IPMode pmode) { var inMessage = new InMessage(ebmsMessageId) { ContentType = as4Message.ContentType, EbmsMessageType = MessageType.UserMessage, MEP = MessageExchangePattern.Push, Operation = Operation.ToBeDelivered, MessageLocation = Registry.Instance .MessageBodyStore .SaveAS4Message(@"file:///.\database\as4messages\in", as4Message) }; inMessage.SetPModeInformation(pmode); return(inMessage); }
void SetConnector(System.Net.IPEndPoint inServerAddress) { IPMode mode = IPMode.IPv4; if (inServerAddress.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6) { mode = IPMode.IPv6; } // tcp connect NetworkEndPoint ep = new NetworkEndPoint(inServerAddress.Address, inServerAddress.Port, mode); connection = new Hazel.Tcp.TcpConnection(ep); connection.Connect(); connection.DataReceived += delegate(object innerSender, DataReceivedEventArgs innerArgs) { NetIncomingMessage msg = GetClient().CreateIncomingMessage(NetIncomingMessageType.Data, innerArgs.Bytes.Length); msg.isTcp = true; msg.m_TcpConnecton = (TcpConnection)innerSender; msg.m_senderEndPoint = ((NetworkEndPoint)((Connection)innerSender).EndPoint).EndPoint as IPEndPoint; Buffer.BlockCopy(innerArgs.Bytes, 2, msg.m_data, 0, innerArgs.Bytes.Length - 2); msg.m_bitLength = (ushort)((innerArgs.Bytes[0] << 8) | innerArgs.Bytes[1]); //core.LogHelper.LogInfo($"TCP recv message length {msg.m_bitLength}"); GetClient().ReleaseMessage(msg); }; connection.Disconnected += delegate(object sender2, DisconnectedEventArgs args2) { NetIncomingMessage msg = GetClient().CreateIncomingMessage(NetIncomingMessageType.TcpStatusChanged, 4 + 1); msg.isTcp = true; msg.m_senderEndPoint = ((NetworkEndPoint)((Connection)sender2).EndPoint).EndPoint as IPEndPoint; msg.Write((byte)NetConnectionStatus.Disconnected); msg.Write(string.Empty); //core.LogHelper.LogInfo($"TCP disconnected"); GetClient().ReleaseMessage(msg); }; }
public Server(string mode, string hostOrAddr, int port, IPMode ipMode, Executor executor, int sleep, int statSec, int simulationThread, int simulationRate, int simulationIterations) { _thread = new Thread(Run); _thread.Name = "EsperServer-main"; if (!string.IsNullOrEmpty(hostOrAddr)) { _address = ResolveHostOrAddress(hostOrAddr); } _mode = mode; _port = port; _ipMode = ipMode; _executor = executor; _sleepListenerMillis = sleep; _statSec = statSec; _simulationThread = simulationThread; _simulationRate = simulationRate; _simulationIterations = simulationIterations; // turn on stat dump _timer = new Timer(DisplayStatistics, null, 0L, statSec * 1000); }
public Server(String mode, String hostOrAddr, int port, IPMode ipMode, Executor executor, int sleep, int statSec, int simulationThread, int simulationRate, int simulationIterations) { thread = new Thread(Run); thread.Name = "EsperServer-main"; if (!String.IsNullOrEmpty(hostOrAddr)) { address = ResolveHostOrAddress(hostOrAddr); } this.mode = mode; this.port = port; this.ipMode = ipMode; this.executor = executor; this.sleepListenerMillis = sleep; this.statSec = statSec; this.simulationThread = simulationThread; this.simulationRate = simulationRate; this.simulationIterations = simulationIterations; // turn on stat dump timer = new Timer(DisplayStatistics, null, 0L, statSec * 1000); }
/// <summary> /// Set the PMode that is used to process the message. /// </summary> /// <param name="pmode"></param> public void SetPModeInformation(IPMode pmode) { if (pmode != null) { PModeId = pmode.Id; // The Xml Serializer is not able to serialize an interface, therefore // the argument must first be cast to a correct implementation. if (pmode is SendingProcessingMode sp) { PMode = AS4XmlSerializer.ToString(sp); } else if (pmode is ReceivingProcessingMode rp) { PMode = AS4XmlSerializer.ToString(rp); } else { throw new NotImplementedException("Unable to serialize the the specified IPMode"); } } }
/// <summary> /// Creates a new UdpClientConnection. /// </summary> /// <param name="remoteEndPoint">A <see cref="NetworkEndPoint"/> to connect to.</param> public UdpClientConnection(IPEndPoint remoteEndPoint, IPMode ipMode = IPMode.IPv4) : base() { this.EndPoint = remoteEndPoint; this.RemoteEndPoint = remoteEndPoint; this.IPMode = ipMode; if (this.IPMode == IPMode.IPv4) { socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); } else { if (!Socket.OSSupportsIPv6) { throw new InvalidOperationException("IPV6 not supported!"); } socket = new Socket(AddressFamily.InterNetworkV6, SocketType.Dgram, ProtocolType.Udp); socket.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.IPv6Only, false); } reliablePacketTimer = new Timer(ManageReliablePacketsInternal, null, 100, Timeout.Infinite); }
/// <summary> /// Creates a new TcpConnectionListener for the given <see cref="IPAddress"/>, port and <see cref="IPMode"/>. /// </summary> /// <param name="IPAddress">The IPAddress to listen on.</param> /// <param name="port">The port to listen on.</param> /// <param name="mode">The <see cref="IPMode"/> to listen with.</param> public TcpConnectionListener(IPAddress IPAddress, int port, IPMode mode = IPMode.IPv4AndIPv6) { this.IPAddress = IPAddress; this.Port = port; if (mode == IPMode.IPv4) { this.listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); } else { if (!Socket.OSSupportsIPv6) { throw new HazelException("IPV6 not supported!"); } this.listener = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp); } if (mode == IPMode.IPv4AndIPv6) { this.listener.DualMode = true; } }
public async Task StartAsync(CancellationToken cancellationToken) { var endpoint = new IPEndPoint(IPAddress.Parse(_config.ResolveListenIp()), _config.ListenPort); IPMode mode = endpoint.AddressFamily switch { AddressFamily.InterNetwork => IPMode.IPv4, AddressFamily.InterNetworkV6 => IPMode.IPv6, _ => throw new InvalidOperationException(), }; var rsa = RSA.Create(); rsa.ImportPkcs8PrivateKey(Convert.FromBase64String(string.Join(string.Empty, (await File.ReadAllLinesAsync(_config.PrivateKey, cancellationToken)).Where(x => !x.StartsWith("-----")))), out _); var cert = new X509Certificate2(_config.Certificate).CopyWithPrivateKey(rsa); _connection = new DtlsConnectionListener(endpoint, _readerPool, mode); _connection.SetCertificate(cert); _connection.NewConnection = ConnectionOnNewConnection; await _connection.StartAsync(); _logger.LogInformation("Auth server is listening on {Address}:{Port}", endpoint.Address, endpoint.Port); }
/// <summary> /// Converts CommandLineArgument values to an IP address if possible. /// Throws Exception if not. /// </summary> /// <param name="ipmode"></param> /// <param name="v6"></param> /// <param name="ipString"></param> /// <returns></returns> /// <exception cref="CassiniException">If IPMode is invalid</exception> /// <exception cref="CassiniException">If IPMode is 'Specific' and ipString is invalid</exception> public static IPAddress ParseIP(IPMode ipmode, bool v6, string ipString) { IPAddress ip; switch (ipmode) { case IPMode.Loopback: ip = v6 ? System.Net.IPAddress.IPv6Loopback : System.Net.IPAddress.Loopback; break; case IPMode.Any: ip = v6 ? System.Net.IPAddress.IPv6Any : System.Net.IPAddress.Any; break; case IPMode.Specific: if (!System.Net.IPAddress.TryParse(ipString, out ip)) { throw new CassiniException(SR.ErrInvalidIPAddress, ErrorField.IPAddress); } break; default: throw new CassiniException(SR.ErrInvalidIPMode, ErrorField.None); } return ip; }