Пример #1
0
        private async Task ExecuteConnectModules(ITcpChannel channel, IClientContext context)
        {
            var result = ModuleResult.Continue;

            for (var i = 0; i < _modules.Length; i++)
            {
                var connectMod = _modules[i] as IConnectionEvents;
                if (connectMod == null)
                    continue;

                try
                {
                    result = await connectMod.OnClientConnected(context);
                }
                catch (Exception exception)
                {
                    context.Error = exception;
                    result = ModuleResult.SendResponse;
                }

                if (result != ModuleResult.Continue)
                    break;
            }

            switch (result)
            {
                case ModuleResult.Disconnect:
                    channel.Close();
                    break;
                case ModuleResult.SendResponse:
                    channel.Send(context.ResponseMessage);
                    break;
            }
        }
Пример #2
0
        private async void OnClientConnect(object sender, ClientConnectedEventArgs e)
        {
            ITcpChannel channel    = e.Channel;
            FreeSwitch  freeSwitch = new FreeSwitch(ref channel);

            try {
                var added = _clients.TryAdd(channel.ChannelId, freeSwitch);
                if (added)
                {
                    await freeSwitch.Connect();

                    bool ready = await freeSwitch.Resume() && await freeSwitch.MyEvents() && await freeSwitch.DivertEvents();

                    if (!ready)
                    {
                        await freeSwitch.Close();

                        return;
                    }
                }
                if (ClientReady != null)
                {
                    ClientReady(this, new InboundClientEventArgs(freeSwitch));
                }
            }
            catch (Exception) {
                if (channel != null)
                {
                    channel.Close();
                }
            }
        }
 private void OnDecoderFailure(ITcpChannel channel, Exception error)
 {
     var pos = error.Message.IndexOfAny(new[] {'\r', '\n'});
     var descr = pos == -1 ? error.Message : error.Message.Substring(0, pos);
     var response = new HttpResponseBase(HttpStatusCode.BadRequest, descr, "HTTP/1.1");
     channel.Send(response);
     channel.Close();
 }
Пример #4
0
        private void OnDecoderFailure(ITcpChannel channel, Exception error)
        {
            var pos      = error.Message.IndexOfAny(new[] { '\r', '\n' });
            var descr    = pos == -1 ? error.Message : error.Message.Substring(0, pos);
            var response = new HttpResponseBase(HttpStatusCode.BadRequest, descr, "HTTP/1.1");

            channel.Send(response);
            channel.Close();
        }
Пример #5
0
        /// <summary>
        ///     Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// </summary>
        public void Dispose()
        {
            if (_channel == null)
            {
                return;
            }

            _channel.Close();
            _channel = null;
        }
 private void OnDecoderFailure(ITcpChannel channel, Exception error)
 {
     var pos = error.Message.IndexOfAny(new[] {'\r', '\n'});
     var descr = pos == -1 ? error.Message : error.Message.Substring(0, pos);
     var response = new HttpResponse(HttpStatusCode.BadRequest, descr, "HTTP/1.1");
     var counter = (int)channel.Data.GetOrAdd(HttpMessage.PipelineIndexKey, x => 1);
     response.Headers[HttpMessage.PipelineIndexKey] = counter.ToString();
     channel.Send(response);
     channel.Close();
 }
Пример #7
0
        private void OnDecoderFailure(ITcpChannel channel, Exception error)
        {
            var pos      = error.Message.IndexOfAny(new[] { '\r', '\n' });
            var descr    = pos == -1 ? error.Message : error.Message.Substring(0, pos);
            var response = new HttpResponseBase(HttpStatusCode.BadRequest, descr, "HTTP/1.1");
            var counter  = (int)channel.Data.GetOrAdd(HttpMessage.PipelineIndexKey, x => 1);

            response.Headers[HttpMessage.PipelineIndexKey] = counter.ToString();
            channel.Send(response);
            channel.Close();
        }
Пример #8
0
        private static void OnMessage(ITcpChannel channel, object message)
        {
            var request  = (HttpRequest)message;
            var response = request.CreateResponse();


            if (request.Uri.AbsolutePath.StartsWith("/restricted"))
            {
                var user = _authenticator.Authenticate(request);
                if (user == null)
                {
                    _authenticator.CreateChallenge(request, response);
                    channel.Send(response);
                    return;
                }


                Console.WriteLine("Logged in: " + user);
            }

            if (request.Uri.AbsolutePath == "/favicon.ico")
            {
                response.StatusCode = 404;
                channel.Send(response);
                return;
            }

            var msg = Encoding.UTF8.GetBytes("Hello world");

            if (request.Uri.ToString().Contains(".jpg"))
            {
                response.Body        = new FileStream(@"C:\users\gaujon01\Pictures\DSC_0231.jpg", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                response.ContentType = "image/jpeg";
            }
            else
            {
                response.Body = new MemoryStream(msg);
                //response.Body.Write(msg, 0, msg.Length);
                response.ContentType = "text/plain";
            }
            channel.Send(response);
            if (request.HttpVersion == "HTTP/1.0")
            {
                channel.Close();
            }
        }
Пример #9
0
        private static void OnMessage(ITcpChannel channel, object message)
        {
            var request = (HttpRequestBase)message;
            var response = request.CreateResponse();


            if (request.Uri.AbsolutePath.StartsWith("/restricted"))
            {

                var user = _authenticator.Authenticate(request);
                if (user == null)
                {
                    _authenticator.CreateChallenge(request, response);
                    channel.Send(response);
                    return;
                }


                Console.WriteLine("Logged in: " + user);
            }

            if (request.Uri.AbsolutePath == "/favicon.ico")
            {
                response.StatusCode = 404;
                channel.Send(response);
                return;
            }

            var msg = Encoding.UTF8.GetBytes("Hello world");
            if (request.Uri.ToString().Contains(".jpg"))
            {
                response.Body = new FileStream(@"C:\users\gaujon01\Pictures\DSC_0231.jpg", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                response.ContentType = "image/jpeg";
            }
            else
            {
                response.Body = new MemoryStream(msg);
                //response.Body.Write(msg, 0, msg.Length);
                response.ContentType = "text/plain";
            }
            channel.Send(response);
            if (request.HttpVersion == "HTTP/1.0")
                channel.Close();

        }
Пример #10
0
 public Task CloseAsync()
 {
     // cc is not null if we opened the connection
     if (ChannelCreator != null)
     {
         Logger.Debug("Close connection {0}. We were the initiator.", _channel);
         // maybe done on arrival? set close future in any case
         ChannelCreator.ShutdownAsync().ContinueWith(delegate
         {
             _tcsClose.SetResult(null); // complete
         });
     }
     else
     {
         // cc is null if it is an incoming connection
         // we can close it here or it will be closed when the dispatcher is shut down
         Logger.Debug("Close connection {0}. We are not the initiator.", _channel);
         _channel.Close();
     }
     return(_tcsClose.Task);
 }
Пример #11
0
        private async Task ExecuteConnectModules(ITcpChannel channel, ClientContext context)
        {
            var result = ModuleResult.Continue;

            for (var i = 0; i < _modules.Length; i++)
            {
                var connectMod = _modules[i] as IConnectionEvents;
                if (connectMod == null)
                {
                    continue;
                }

                try
                {
                    result = await connectMod.OnClientConnected(context);
                }
                catch (Exception exception)
                {
                    context.Error = exception;
                    result        = ModuleResult.SendResponse;
                }

                if (result != ModuleResult.Continue)
                {
                    break;
                }
            }

            switch (result)
            {
            case ModuleResult.Disconnect:
                channel.Close();
                break;

            case ModuleResult.SendResponse:
                channel.Send(context.ResponseMessage);
                break;
            }
        }
Пример #12
0
        private void OnDecoderFailure(ITcpChannel channel, Exception error)
        {
            if (!channel.IsConnected || error is SocketException)
            {
                return;
            }

            try
            {
                var pos      = error.Message.IndexOfAny(new[] { '\r', '\n' });
                var descr    = pos == -1 ? error.Message : error.Message.Substring(0, pos);
                var response = new HttpResponse(HttpStatusCode.BadRequest, descr, "HTTP/1.1");
                var counter  = (int)channel.Data.GetOrAdd(HttpMessage.PipelineIndexKey, x => 1);
                response.Headers[HttpMessage.PipelineIndexKey] = counter.ToString();
                channel.Send(response);
                channel.Close();
            }
            catch (Exception ex)
            {
                OnListenerError(ex);
            }
        }
        private static void OnMessage(ITcpChannel channel, object message)
        {
            var request  = (IHttpRequest)message;
            var response = request.CreateResponse();

            if (request.Uri.AbsolutePath == "/favicon.ico")
            {
                response.StatusCode = 404;
                channel.Send(response);
                return;
            }

            var msg = Encoding.UTF8.GetBytes("Hello world");

            response.Body        = new MemoryStream(msg);
            response.ContentType = "text/plain";
            channel.Send(response);

            if (request.HttpVersion == "HTTP/1.0")
            {
                channel.Close();
            }
        }
Пример #14
0
        private async Task ExecuteModules(ITcpChannel channel, ClientContext context)
        {
            var result = ModuleResult.Continue;

            for (var i = 0; i < _modules.Length; i++)
            {
                try
                {
                    await _modules[i].BeginRequestAsync(context);
                }
                catch (Exception exception)
                {
                    context.Error = exception;
                    result = ModuleResult.SendResponse;
                }
            }


            if (result == ModuleResult.Continue)
            {
                for (var i = 0; i < _modules.Length; i++)
                {
                    try
                    {
                        result = await _modules[i].ProcessAsync(context);
                    }
                    catch (Exception exception)
                    {
                        context.Error = exception;
                        result = ModuleResult.SendResponse;
                    }

                    if (result != ModuleResult.Continue)
                        break;
                }
            }


            try
            {
                await EndRequestAsync(context);
            }
            catch (Exception exception)
            {
                if (context.ResponseMessage == null)
                    context.ResponseMessage = exception;
                result = ModuleResult.Disconnect;
            }

            if (context.ResponseMessage != null)
                channel.Send(context.ResponseMessage);

            if (result == ModuleResult.Disconnect)
            {
                channel.Close();
            }
        }
        /// <summary>
        /// Handles the upgrade
        /// </summary>
        /// <param name="source">Channel that we've received a request from</param>
        /// <param name="msg">Message received.</param>
        protected override void OnMessage(ITcpChannel source, object msg)
        {
            var httpMessage = msg as IHttpMessage;
            if (WebSocketUtils.IsWebSocketUpgrade(httpMessage))
            {
                if (httpMessage is IHttpRequest) // server mode
                {
                    var args = new WebSocketClientConnectEventArgs(source, (IHttpRequest) httpMessage);
                    WebSocketClientConnect(this, args);

                    if (args.MayConnect)
                    {
                        var webSocketKey = httpMessage.Headers["Sec-WebSocket-Key"];

                        // TODO: why not provide the response in the WebSocketClientConnectEventArgs event?
                        var response = new WebSocketUpgradeResponse(webSocketKey);

                        source.Send(response);

                        WebSocketClientConnected(this,
                            new WebSocketClientConnectedEventArgs(source, (IHttpRequest) httpMessage, response));
                    }
                    else if (args.SendResponse)
                    {
                        var response = new HttpResponseBase(HttpStatusCode.NotImplemented, "Not Implemented", "HTTP/1.1");
                        if (args.Response != null)
                            response.Body = args.Response;

                        source.Send(response);
                    }
                    return;
                }

                if (httpMessage is IHttpResponse) // client mode
                {
                    WebSocketClientConnected(this,
                        new WebSocketClientConnectedEventArgs(source, null, (IHttpResponse) httpMessage));
                }
            }

            var webSocketMessage = msg as IWebSocketMessage;
            if (webSocketMessage != null)
            {
                // standard message responses handled by listener
                switch (webSocketMessage.Opcode)
                {
                    case WebSocketOpcode.Ping:
                        source.Send(new WebSocketMessage(WebSocketOpcode.Pong, webSocketMessage.Payload));
                        return;
                    case WebSocketOpcode.Close:
                        source.Send(new WebSocketMessage(WebSocketOpcode.Close));
                        source.Close();

                        WebSocketClientDisconnected(this,
                            new ClientDisconnectedEventArgs(source, new Exception("WebSocket closed")));
                        return;
                }

                _webSocketMessageReceived(source, webSocketMessage);
                return;
            }

            base.OnMessage(source, msg);
        }
Пример #16
0
        private async Task ExecuteModules(ITcpChannel channel, ClientContext context)
        {
            var result = ModuleResult.Continue;

            for (var i = 0; i < _modules.Length; i++)
            {
                try
                {
                    await _modules[i].BeginRequestAsync(context);
                }
                catch (Exception exception)
                {
                    context.Error = exception;
                    result        = ModuleResult.SendResponse;
                }
            }


            if (result == ModuleResult.Continue)
            {
                for (var i = 0; i < _modules.Length; i++)
                {
                    try
                    {
                        result = await _modules[i].ProcessAsync(context);
                    }
                    catch (Exception exception)
                    {
                        context.Error = exception;
                        result        = ModuleResult.SendResponse;
                    }

                    if (result != ModuleResult.Continue)
                    {
                        break;
                    }
                }
            }


            try
            {
                await EndRequestAsync(context);
            }
            catch (Exception exception)
            {
                if (context.ResponseMessage == null)
                {
                    context.ResponseMessage = exception;
                }
                result = ModuleResult.Disconnect;
            }

            if (context.ResponseMessage != null)
            {
                channel.Send(context.ResponseMessage);
            }

            if (result == ModuleResult.Disconnect)
            {
                channel.Close();
            }
        }
Пример #17
0
        /// <summary>
        /// Handles the upgrade
        /// </summary>
        /// <param name="source">Channel that we've received a request from</param>
        /// <param name="msg">Message received.</param>
        protected override void OnMessage(ITcpChannel source, object msg)
        {
            var httpMessage = msg as IHttpMessage;

            if (WebSocketUtils.IsWebSocketUpgrade(httpMessage))
            {
                if (httpMessage is IHttpRequest) // server mode
                {
                    var args = new WebSocketClientConnectEventArgs(source, (IHttpRequest)httpMessage);
                    WebSocketClientConnect(this, args);

                    if (args.MayConnect)
                    {
                        var webSocketKey = httpMessage.Headers["Sec-WebSocket-Key"];

                        // TODO: why not provide the response in the WebSocketClientConnectEventArgs event?
                        var response = new WebSocketUpgradeResponse(webSocketKey);

                        source.Send(response);

                        WebSocketClientConnected(this,
                                                 new WebSocketClientConnectedEventArgs(source, (IHttpRequest)httpMessage, response));
                    }
                    else
                    {
                        var response = new HttpResponseBase(HttpStatusCode.NotImplemented, "Not Implemented", "HTTP/1.1");
                        if (args.Response != null)
                        {
                            response.Body = args.Response;
                        }

                        source.Send(response);
                    }
                    return;
                }

                if (httpMessage is IHttpResponse) // client mode
                {
                    WebSocketClientConnected(this,
                                             new WebSocketClientConnectedEventArgs(source, null, (IHttpResponse)httpMessage));
                }
            }

            var webSocketMessage = msg as IWebSocketMessage;

            if (webSocketMessage != null)
            {
                // standard message responses handled by listener
                switch (webSocketMessage.Opcode)
                {
                case WebSocketOpcode.Ping:
                    source.Send(new WebSocketMessage(WebSocketOpcode.Pong, webSocketMessage.Payload));
                    return;

                case WebSocketOpcode.Close:
                    source.Send(new WebSocketMessage(WebSocketOpcode.Close));
                    source.Close();

                    WebSocketClientDisconnected(this,
                                                new ClientDisconnectedEventArgs(source, new Exception("WebSocket closed")));
                    return;
                }

                _webSocketMessageReceived(source, webSocketMessage);
                return;
            }

            base.OnMessage(source, msg);
        }