示例#1
0
        /// <summary>
        /// Waits for tasks.
        /// </summary>
        /// <param name="tasks">The tasks.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <param name="onTaskComplete">The on task complete.</param>
        /// <param name="logger">The logger.</param>
        /// <param name="memberName">Name of the member.</param>
        /// <returns>Task.</returns>
        /// <autogeneratedoc />
        public static Task WaitForTasks(this List <Task> tasks, CancellationToken cancellationToken, Action <Task> onTaskComplete = null,
                                        IPureLogger logger = null, [CallerMemberName] string memberName = "")
        {
            Task t = Task.WhenAll(tasks);

            try
            {
                cancellationToken.ThrowIfCancellationRequested();
                t.Wait(cancellationToken);
            }
            catch (OperationCanceledException ex)
            {
                t = Task.FromCanceled(cancellationToken);
                logger?.LogError(ex, "Task {Method} timed out with {TaskStatus}", memberName, t.Status);
            }
            catch (Exception ex)
            {
                t = Task.FromException(ex);

                logger?.LogError(ex, "Task {Method} threw an exception with {TaskStatus}", memberName, t.Status);
            }
            finally
            {
                onTaskComplete?.Invoke(t);
            }

            return(t);
        }
示例#2
0
        /// <summary>
        /// Reads socket and processes packet
        /// </summary>
        /// <param name="socket">The active socket.</param>
        protected virtual void OnSocket(Socket socket)
        {
            try
            {
                if (socket.Poll(-1, SelectMode.SelectRead))
                {
                    var args = new ClientConnectedEventArgs(socket, Logger, _bufferSize);

                    EndPoint remoteEndPoint = new IPEndPoint(0, 0);

                    if (socket.Available == 0)
                    {
                        return;
                    }

                    args.ChannelBuffer.BytesTransferred = socket.ReceiveFrom(args.ChannelBuffer.Buffer,
                                                                             SocketFlags.None, ref remoteEndPoint);
                    args.Channel.RemoteEndpoint = remoteEndPoint;

                    if (args.ChannelBuffer.BytesTransferred > 0)
                    {
                        OnClientConnected(args);

                        if (args.AllowConnect == false)
                        {
                            if (args.Response != null)
                            {
                                int sentBytes;
                                while ((sentBytes = args.Response.Read(_sendBuffer, 0, _sendBuffer.Length)) > 0)
                                {
                                    socket.Send(_sendBuffer, sentBytes, SocketFlags.None);
                                }
                            }

                            Logger?.LogDebug(
                                "PACKET request on {LocalEndPoint} from {RemoteEndPoint} with channel id {ChannelId} was denied access to connect.",
                                socket.LocalEndPoint,
                                args.Channel.RemoteEndpoint,
                                args.Channel.ChannelId);
                        }
                    }
                }
                else
                {
                    Thread.Sleep(10);
                }
            }
            catch (SocketException ex)
            {
                if (ex.ErrorCode == (int)SocketError.ConnectionReset)
                {
                    Logger.LogError(ex, "SocketListener: socket connection reset");
                }
            }
            catch (Exception ex)
            {
                HandleDisconnect(SocketError.SocketError, ex);
            }
        }
示例#3
0
        /// <summary>
        /// Gets the default local address subnet.
        /// </summary>
        /// <returns>IPAddressSubnet.</returns>
        /// <autogeneratedoc />
        public IPAddressSubnet GetDefaultLocalAddressSubnet()
        {
            var ipAddressSubnet = new IPAddressSubnet(IPAddress.None, IPAddress.None);

            try
            {
                foreach (var networkInterface in GetAllNetworkInterfaces())
                {
                    ipAddressSubnet = IPv4AddressSubnetFromNetworkInterface(networkInterface);

                    // break if we  find an IPv4 Interface
                    if (!ipAddressSubnet.Equals(IPAddressSubnet.None))
                    {
                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                _logger?.LogError(ex, "GetDefaultLocalAddressSubnet failed");
            }

            return(ipAddressSubnet);
        }
示例#4
0
        /// <summary>
        /// Stops the service listener if in started state.
        /// </summary>
        /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
        /// <exception cref="InvalidOperationException">SocketListener is not active and must be started before stopping</exception>
        public bool Stop()
        {
            try
            {
                if (!IsActive)
                {
                    throw new InvalidOperationException(
                              "SocketListener is not active and must be started before stopping");
                }

                IsActive = false;

                Logger?.LogInformation("SocketListener stopped listening for requests on {LocalEndPoint}",
                                       Socket.LocalEndPoint);

                return(true);
            }
            catch (Exception ex)
            {
                Logger?.LogError(ex, "SocketLister stop failed");
            }

            return(false);
        }
示例#5
0
        /// <summary>
        /// Gets the DHCP option string.
        /// </summary>
        /// <param name="dhcpOption">The DHCP option.</param>
        /// <param name="dhcpOptionValue">The DHCP option value.</param>
        /// <param name="dhcpRequestListFormat">The DHCP request list format.</param>
        /// <param name="logger">The logger.</param>
        /// <returns>System.String.</returns>
        /// <autogeneratedoc />
        public static string GetDhcpOptionString(
            DhcpOption dhcpOption, byte[] dhcpOptionValue,
            DhcpRequestListFormat dhcpRequestListFormat = DhcpRequestListFormat.StringNewlineIndentedSeparated,
            IPureLogger logger = null
            )
        {
            try
            {
                if (dhcpOptionValue == null)
                {
                    return("Null");
                }

                if (dhcpOption == DhcpOption.ParamReqList)
                {
                    return(GetDhcpRequestListString(dhcpOptionValue, dhcpRequestListFormat, logger));
                }

                switch (DhcpOptionTypes[dhcpOption])
                {
                case DhcpOptionType.IPAddress:
                    return(new IPAddress(dhcpOptionValue).ToString());

                case DhcpOptionType.PhysicalAddressSkip1DashString:
                    return(new PhysicalAddress(dhcpOptionValue.Skip(1).ToArray()).ToDashString());

                case DhcpOptionType.PhysicalAddressSkip1ColonString:
                    return(new PhysicalAddress(dhcpOptionValue.Skip(1).ToArray()).ToColonString());

                case DhcpOptionType.PhysicalAddressDashString:
                    return(new PhysicalAddress(dhcpOptionValue).ToDashString());

                case DhcpOptionType.PhysicalAddressColonString:
                    return(new PhysicalAddress(dhcpOptionValue).ToColonString());

                case DhcpOptionType.MessageTypeString:
                    return(MessageTypeString.GetName((MessageType)dhcpOptionValue[0]));

                case DhcpOptionType.SafeString:
                    return(ByteUtility.GetSafeString(dhcpOptionValue));

                case DhcpOptionType.SafeBytes:
                    return(ByteUtility.PrintSafeBytes(dhcpOptionValue));

                case DhcpOptionType.UInt16:
                    return(BitConverter.ToUInt16(dhcpOptionValue, 0).ToString());

                case DhcpOptionType.UInt32:
                    return(BitConverter.ToUInt32(dhcpOptionValue, 0).ToString());

                case DhcpOptionType.UInt16Network:
                    return(IPAddress.NetworkToHostOrder(BitConverter.ToUInt16(dhcpOptionValue, 0)).ToString());

                case DhcpOptionType.UInt32Network:
                    return(IPAddress.NetworkToHostOrder(BitConverter.ToUInt32(dhcpOptionValue, 0)).ToString());
                }
            }
            catch (Exception ex)
            {
                logger?.LogError(ex, "Invalid DhcpOption: {dhcpOption}", dhcpOption);
            }

            return(string.Empty);
        }