Пример #1
0
        public void Stop()
        {
            //_stopTokenSource?.Cancel();
            if (_stopTokenSource != null)
            {
                _stopTokenSource.Cancel();
            }

            if (_UdpListener != null)
            {
                _UdpListener.Close();
            }
            if (_UdpForwarder != null)
            {
                _UdpForwarder.Close();
            }
            //_udpListener?.Close();
            //_udpForwarder?.Close();


            /*try
             * {
             * _listeningTask?.Wait();
             * _forwardingTask?.Wait();*/

            if (_ListeningTask != null)
            {
                _ListeningTask.Abort();
            }
            if (_ForwardingTask != null)
            {
                _ForwardingTask.Abort();
            }

            /* }
             * catch (AggregateException)
             * {
             * }*/

            _stopTokenSource    = null;
            _UdpListener        = null;
            _UdpForwarder       = null;
            _ListeningTask      = null;
            _ForwardingTask     = null;
            _transactionClients = null;
            _transactionTimeoutCancellationTokenSources = null;

            OnStopped();
        }
Пример #2
0
        public bool Start()
        {
            _IPEndPoint = Utils.CreateIpEndPoint(_listenOn, 53);

            _stopTokenSource    = new MrTe.Threading.Tasks.CancellationTokenSource();
            _transactionClients = new System.Collections.Generic.Dictionary <ushort, IPEndPoint>();
            _transactionTimeoutCancellationTokenSources = new System.Collections.Generic.Dictionary <ushort, MrTe.Threading.Tasks.CancellationTokenSource>();
            try
            {
                _UdpListener  = new UdpClient(_IPEndPoint);
                _UdpForwarder = new UdpClient(0);
            }
            catch (SocketException e)
            {
                Logger.Error("[Listener] Failed to start DNSAgent:\n{0}", e);
                Stop();
                return(false);
            }


            /*_listeningTask = Task.Run(async () =>
             * {
             *
             * }, _stopTokenSource.Token);
             */

            _ListeningTask = new Thread(new ThreadStart(ListeningTask_Run));
            _ListeningTask.Start();

            /*
             * _forwardingTask = Task.Run(async () =>
             * {
             *
             * }, _stopTokenSource.Token);
             *
             */
            _ForwardingTask = new Thread(new ThreadStart(ForwardingTask_Run));
            _ForwardingTask.Start();

            Logger.Info("Listening on {0}...", _IPEndPoint);
            OnStarted();
            return(true);
        }
Пример #3
0
        private bool ForwardMessage(DnsMessage message, IPEndPoint revicepoint, byte[] buf,
                                    IPEndPoint targetNameServer, int queryTimeout,
                                    bool useCompressionMutation)
        {
            DnsQuestion question = null;

            if (message.Questions.Count > 0)
            {
                question = message.Questions[0];
            }

            byte[] responseBuffer = null;
            try
            {
                if ((Equals(targetNameServer.Address, IPAddress.Loopback) ||
                     Equals(targetNameServer.Address, IPAddress.IPv6Loopback)) &&
                    targetNameServer.Port == ((IPEndPoint)_UdpListener.Client.LocalEndPoint).Port)
                {
                    throw new InfiniteForwardingException(question);
                }

                byte[] sendBuffer;
                if (useCompressionMutation)
                {
                    message.Encode(false, out sendBuffer, true);
                }
                else
                {
                    sendBuffer = buf;
                }

                _transactionClients[message.TransactionID] = revicepoint;


                // Send to Forwarder
                /*await _udpForwarder.SendAsync(sendBuffer, sendBuffer.Length, targetNameServer);*/
                _UdpForwarder.Send(sendBuffer, sendBuffer.Length, targetNameServer);



                if (_transactionTimeoutCancellationTokenSources.ContainsKey(message.TransactionID))
                {
                    _transactionTimeoutCancellationTokenSources[message.TransactionID].Cancel();
                }
                MrTe.Threading.Tasks.CancellationTokenSource cancellationTokenSource = new MrTe.Threading.Tasks.CancellationTokenSource();

                _transactionTimeoutCancellationTokenSources[message.TransactionID] = cancellationTokenSource;


                return(true);

                // Timeout task to cancel the request

                /*try
                 * {*/
                /*await Task.Delay(queryTimeout, cancellationTokenSource.Token);*/

                Task.Delay(queryTimeout, cancellationTokenSource.Token);

                if (!_transactionClients.ContainsKey(message.TransactionID))
                {
                    return(false);
                }
                IPEndPoint ignoreEndPoint;
                MrTe.Threading.Tasks.CancellationTokenSource ignoreTokenSource;

                /*
                 *  _transactionClients.TryRemove(message.TransactionID, out ignoreEndPoint);
                 *  _transactionTimeoutCancellationTokenSources.TryRemove(message.TransactionID,
                 *      out ignoreTokenSource);
                 */
                ignoreEndPoint    = _transactionClients[message.TransactionID];
                ignoreTokenSource = _transactionTimeoutCancellationTokenSources[message.TransactionID];



                string warningText = message.Questions.Count > 0
                        ? message.Questions[0].Name + " (Type " + message.Questions[0].RecordType + ")"
                        : "Transaction #" + message.TransactionID + "";
                Logger.Warning("Query timeout for: {0}", warningText);
                _transactionClients.Remove(message.TransactionID);
                _transactionTimeoutCancellationTokenSources.Remove(message.TransactionID);

                /*
                 * }
                 * catch (TaskCanceledException)
                 * {
                 * }
                 */
            }
            catch (InfiniteForwardingException e)
            {
                Logger.Warning("[Forwarder.Send] Infinite forwarding detected for: {0} (Type {1})", e.Question.Name,
                               e.Question.RecordType);
                Utils.ReturnDnsMessageServerFailure(message, out responseBuffer);
            }
            catch (SocketException e)
            {
                if (e.SocketErrorCode == SocketError.ConnectionReset) // Target name server port unreachable
                {
                    Logger.Warning("[Forwarder.Send] Name server port unreachable: {0}", targetNameServer);
                }
                else
                {
                    Logger.Error("[Forwarder.Send] Unhandled socket error: {0}", e.Message);
                }
                Utils.ReturnDnsMessageServerFailure(message, out responseBuffer);
            }
            catch (Exception e)
            {
                Logger.Error("[Forwarder] Unexpected exception:\n{0}", e);
                Utils.ReturnDnsMessageServerFailure(message, out responseBuffer);
            }

            // If we got some errors

            if (responseBuffer != null)
            {
                /*await _udpListener.SendAsync(responseBuffer, responseBuffer.Length, originalUdpMessage.RemoteEndPoint);*/
                _UdpListener.Send(responseBuffer, responseBuffer.Length, revicepoint);
            }
            return(true);
        }