Exemple #1
0
        private static HttpResponse OnServeFiles(ITcpChannel channel, HttpRequest request)
        {
            //do not do anything, lib will handle it.
            if (request.Uri.AbsolutePath.StartsWith("/cqs"))
                return null;

            var response = request.CreateResponse();

            var uriWithoutTrailingSlash = request.Uri.AbsolutePath.TrimEnd('/');
            var path = Debugger.IsAttached
                ? Path.GetFullPath(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "..\\..\\public\\", uriWithoutTrailingSlash))
                : Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "public\\", uriWithoutTrailingSlash);
            if (path.EndsWith("\\"))
                path = Path.Combine(path, "index.html");

            if (!File.Exists(path))
            {
                response.StatusCode = 404;
                return response;
            }

            var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            var extension = Path.GetExtension(path).TrimStart('.');
            response.ContentType = ApacheMimeTypes.Apache.MimeTypes[extension];
            response.Body = stream;
            return response;
        }
 /// <summary>
 ///     Initializes a new instance of the <see cref="ClientConnectedEventArgs" /> class.
 /// </summary>
 /// <param name="channel">The channel.</param>
 public ClientConnectedEventArgs(ITcpChannel channel)
 {
     if (channel == null) throw new ArgumentNullException("channel");
     Channel = channel;
     MayConnect = true;
     SendResponse = true;
 }
        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;
            }
        }
        /// <summary>
        ///     A client has connected (nothing has been sent or received yet)
        /// </summary>
        /// <param name="channel">Channel which we created for the remote socket.</param>
        /// <returns></returns>
        protected virtual ClientConnectedEventArgs OnClientConnected(ITcpChannel channel)
        {
            var args = new ClientConnectedEventArgs(channel);

            this.ClientConnected(this, args);
            return(args);
        }
        /// <summary>
        /// Build a new SSL steam.
        /// </summary>
        /// <param name="channel">Channel which will use the stream</param>
        /// <param name="socket">Socket to wrap</param>
        /// <returns>Stream which is ready to be used (must have been validated)</returns>
        public SslStream Build(ITcpChannel channel, Socket socket)
        {
            var ns     = new NetworkStream(socket);
            var stream = new SslStream(ns, true, OnRemoteCertifiateValidation);

            try
            {
                var t = stream.AuthenticateAsServerAsync(Certificate, UseClientCertificate, Protocols, CheckCertificateRevocation);
                t.Wait(HandshakeTimeout);
                if (t.Status == TaskStatus.WaitingForActivation)
                {
                    throw new InvalidOperationException("Handshake was not completed within the given interval '" + HandshakeTimeout + "'.");
                }
            }
            catch (IOException err)
            {
                throw new InvalidOperationException("Failed to authenticate " + socket.RemoteEndPoint, err);
            }
            catch (ObjectDisposedException err)
            {
                throw new InvalidOperationException("Failed to create stream, did client disconnect directly?", err);
            }
            catch (AuthenticationException err)
            {
                throw new InvalidOperationException("Failed to authenticate " + socket.RemoteEndPoint, err);
            }

            return(stream);
        }
        /// <summary>
        /// Build a new SSL steam.
        /// </summary>
        /// <param name="channel">Channel which will use the stream</param>
        /// <param name="socket">Socket to wrap</param>
        /// <returns>Stream which is ready to be used (must have been validated)</returns>
        public SslStream Build(ITcpChannel channel, Socket socket)
        {
            var ns = new NetworkStream(socket);
            var stream = new SslStream(ns, true, OnRemoteCertifiateValidation);

            try
            {
                X509CertificateCollection certificates = null;
                if (Certificate != null)
                {
                    certificates = new X509CertificateCollection(new[] { Certificate });
                }

                stream.AuthenticateAsClient(CommonName, certificates, Protocols, false);
            }
            catch (IOException err)
            {
                throw new InvalidOperationException("Failed to authenticate " + socket.RemoteEndPoint, err);
            }
            catch (ObjectDisposedException err)
            {
                throw new InvalidOperationException("Failed to create stream, did client disconnect directly?", err);
            }
            catch (AuthenticationException err)
            {
                throw new InvalidOperationException("Failed to authenticate " + socket.RemoteEndPoint, err);
            }

            return stream;
        }
Exemple #7
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();
                }
            }
        }
Exemple #8
0
        private static HttpResponseBase OnServeFiles(ITcpChannel channel, HttpRequestBase request)
        {
            //do not do anything, lib will handle it.
            if (request.Uri.AbsolutePath.StartsWith("/cqs"))
            {
                return(null);
            }

            var response = request.CreateResponse();

            var uriWithoutTrailingSlash = request.Uri.AbsolutePath.TrimEnd('/');
            var path = Debugger.IsAttached
                ? Path.GetFullPath(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "..\\..\\public\\", uriWithoutTrailingSlash))
                : Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "public\\", uriWithoutTrailingSlash);

            if (path.EndsWith("\\"))
            {
                path = Path.Combine(path, "index.html");
            }

            if (!File.Exists(path))
            {
                response.StatusCode = 404;
                return(response);
            }

            var stream    = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            var extension = Path.GetExtension(path).TrimStart('.');

            response.ContentType = ApacheMimeTypes.Apache.MimeTypes[extension];
            response.Body        = stream;
            return(response);
        }
        /// <summary>
        /// Build a new SSL steam.
        /// </summary>
        /// <param name="channel">Channel which will use the stream</param>
        /// <param name="socket">Socket to wrap</param>
        /// <returns>Stream which is ready to be used (must have been validated)</returns>
        public SslStream Build(ITcpChannel channel, Socket socket)
        {
            var ns     = new NetworkStream(socket);
            var stream = new SslStream(ns, true, OnRemoteCertifiateValidation);

            try
            {
                X509CertificateCollection certificates = null;
                if (Certificate != null)
                {
                    certificates = new X509CertificateCollection(new[] { Certificate });
                }

                stream.AuthenticateAsClient(CommonName, certificates, Protocols, false);
            }
            catch (IOException err)
            {
                throw new InvalidOperationException("Failed to authenticate " + socket.RemoteEndPoint, err);
            }
            catch (ObjectDisposedException err)
            {
                throw new InvalidOperationException("Failed to create stream, did client disconnect directly?", err);
            }
            catch (AuthenticationException err)
            {
                throw new InvalidOperationException("Failed to authenticate " + socket.RemoteEndPoint, err);
            }

            return(stream);
        }
        private void OnConnect(object sender, SocketAsyncEventArgs e)
        {
            if (e.SocketError != SocketError.Success)
            {
                _connectCompletionSource.SetException(new SocketException((int)e.SocketError));
                _connectCompletionSource = null;
                return;
            }

            try
            {
                if (_channel == null)
                {
                    _channel = CreateChannel();
                }

                _channel.Assign(_socket);
            }
            catch (Exception exception)
            {
                _connectCompletionSource.SetException(exception);
                _connectCompletionSource = null;
                return;
            }

            _connectCompletionSource.SetResult((IPEndPoint)_socket.RemoteEndPoint);
            _connectCompletionSource = null;
        }
Exemple #11
0
 private void AddCloseListener(ITcpChannel channel)
 {
     channel.Closed += sender =>
     {
         Logger.Debug("About to close the connection {0}, {1}.", channel, _initiator ? "initiator" : "from-dispatcher");
         _tcsClose.SetResult(null); // complete
     };
 }
 public FreeSwitch(ref ITcpChannel channel) {
     _channel = channel;
     _channel.MessageSent += OnMessageSent;
     _channel.ChannelFailure += OnError;
     _requestsQueue = new ConcurrentQueue<CommandAsyncEvent>();
     Error += OnError;
     MessageReceived += OnMessageReceived;
 }
        /// <summary>
        ///     Initializes a new instance of the <see cref="ClientDisconnectedEventArgs" /> class.
        /// </summary>
        /// <param name="channel">The channel that disconnected.</param>
        /// <param name="exception">The exception that was caught.</param>
        public ChannelErrorEventArgs(ITcpChannel channel, Exception exception)
        {
            if (channel == null) throw new ArgumentNullException("channel");
            if (exception == null) throw new ArgumentNullException("exception");

            Channel = channel;
            Exception = exception;
        }
 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();
 }
        /// <summary>
        /// </summary>
        /// <param name="channel"></param>
        /// <param name="transactionManager">
        ///     Must be unique for this client. i.e. the transaction ids used in this client is not
        ///     globally unique
        /// </param>
        public StompClient(ITcpChannel channel, ITransactionManager transactionManager)
        {
            if (channel == null) throw new ArgumentNullException("channel");
            if (transactionManager == null) throw new ArgumentNullException("transactionManager");

            Channel = channel;
            _transactionManager = transactionManager;
        }
Exemple #16
0
    private static void OnServerReceivedMessage(ITcpChannel channel, object message)
    {
        var file         = (Stream)message;
        var reader       = new StreamReader(file);
        var fileContents = reader.ReadToEnd();

        Console.WriteLine(fileContents);
    }
        /// <summary>
        /// authenticate using serialized messages
        /// </summary>
        /// <param name="channel">channel to authenticate</param>
        /// <param name="message">Received message, will be <see cref="AuthenticationRequiredException" /> first time and then responses to your authentication messages</param>
        /// <returns>
        ///   <c>true</c> if authentication process completed.
        /// </returns>
        public bool Process(ITcpChannel channel, object message)
        {
            if (message is AuthenticationRequiredException)
            {
                var handshake = _authenticationMessageFactory.CreateHandshake(_credentials.UserName);
                channel.Send(handshake);
                _state = 1;
                AuthenticationFailed = false;
                return(false);
            }

            if (message is AuthenticationHandshakeReply)
            {
                if (_state != 1)
                {
                    AuthenticationFailed = true;
                    return(true);
                }

                _state = 2;
                var handshakeReply = (AuthenticationHandshakeReply)message;
                _passwordHash = _passwordHasher.HashPassword(_credentials.Password, handshakeReply.AccountSalt);
                var token = _passwordHasher.HashPassword(_passwordHash, handshakeReply.SessionSalt);
                var auth  = _authenticationMessageFactory.CreateAuthentication(token);
                _clientSalt = auth.ClientSalt;
                channel.Send(auth);
                return(false);
            }

            if (message is AuthenticateReply)
            {
                if (_state != 2)
                {
                    AuthenticationFailed = true;
                    return(true);
                }

                var result = (AuthenticateReply)message;
                AuthenticationFailed = true;
                if (result.State == AuthenticateReplyState.Success)
                {
                    var ourToken = _passwordHasher.HashPassword(_passwordHash, _clientSalt);
                    if (!_passwordHasher.Compare(ourToken, result.AuthenticationToken))
                    {
                        return(true);
                    }
                }
                else
                {
                    return(true);
                }

                AuthenticationFailed = false;
                return(true);
            }

            return(false);
        }
        protected override void OnMessage(ITcpChannel source, object msg)
        {
            var message = (IHttpMessage) msg;

            // used to be able to send back all
            message.Headers["X-Pipeline-index"] = (_pipelineIndex++).ToString();

            base.OnMessage(source, msg);
        }
        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();
        }
        private void OnChannelDisconnect(ITcpChannel source, Exception exception)
        {
            ITcpChannel removed;

            _usedChannels.TryRemove(source.ChannelId, out removed);
            OnClientDisconnected(source, exception);
            source.Cleanup();
            _channels.Push(source);
        }
 private void OnMessageSent(ITcpChannel channel, object message)
 {
     if (_log.IsDebugEnabled)
     {
         var cmd = message as BaseCommand;
         _log.Debug("command sent to freeSwitch <<{0}>>", cmd.ToString());
     }
     _sendCompletedSemaphore.Release();
 }
 /// <summary>
 ///     Disconnection event handler
 /// </summary>
 /// <param name="arg1"></param>
 /// <param name="arg2"></param>
 private void OnDisconnect(ITcpChannel arg1, Exception arg2)
 {
     _socket = null;
     if (_sendCompletedSemaphore.CurrentCount == 0)
     {
         _sendException = arg2;
         _sendCompletedSemaphore.Release();
     }
 }
 /// <summary>
 /// Create a new instance of <see cref="WebSocketClientConnectEventArgs"/>
 /// </summary>
 /// <param name="channel">Channel that connected</param>
 /// <param name="request">Request that we received</param>
 public WebSocketClientConnectEventArgs(ITcpChannel channel, IHttpRequest request)
     : base(channel)
 {
     if (request == null)
     {
         throw new ArgumentNullException("request");
     }
     Request = request;
 }
 public ClientContext(ITcpChannel channel, object message)
 {
     if (channel == null) throw new ArgumentNullException("channel");
     _channel = channel;
     RequestMessage = message;
     ChannelData = Channel.Data;
     RemoteEndPoint = channel.RemoteEndpoint;
     RequestData = new DictionaryContextData();
 }
 public FreeSwitch(ref ITcpChannel channel)
 {
     _channel                 = channel;
     _channel.MessageSent    += OnMessageSent;
     _channel.ChannelFailure += OnError;
     _requestsQueue           = new ConcurrentQueue <CommandAsyncEvent>();
     Error           += OnError;
     MessageReceived += OnMessageReceived;
 }
 /// <summary>
 ///     Initializes a new instance of the <see cref="ClientConnectedEventArgs" /> class.
 /// </summary>
 /// <param name="channel">The channel.</param>
 public ClientConnectedEventArgs(ITcpChannel channel)
 {
     if (channel == null)
     {
         throw new ArgumentNullException("channel");
     }
     Channel    = channel;
     MayConnect = true;
 }
 private void OnMessage(ITcpChannel channel, object message)
 {
     if (channel.Data["lock"] == null)
     {
         Thread.Sleep(2000);
         channel.Data["lock"] = new object();
     }
     else
         _eventToTriggerBySecond.Set();
 }
 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();
 }
Exemple #29
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 int AuthenticateBytes(ITcpChannel channel, ISocketBuffer buffer)
        {
            bool completed;
            var  bytesProcessed = Authenticator.Process(channel, buffer, out completed);

            if (completed)
            {
                channel.BufferPreProcessor = null;
            }
            return(bytesProcessed);
        }
Exemple #31
0
        private static void OnMessage(ITcpChannel channel, object message)
        {
            var ping = (Ping)message;

            Console.WriteLine("Server received: " + message);
            channel.Send(new Pong
            {
                From = "Server",
                To   = ping.Name
            });
        }
        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();
        }
Exemple #33
0
 /// <summary>
 /// If we already have an open TCP connection, we don't need a channel creator.
 /// </summary>
 /// <param name="remotePeer">The remote peer to connect to.</param>
 /// <param name="channel">The already open TCP channel.</param>
 /// <param name="heartBeatMillis"></param>
 public PeerConnection(PeerAddress remotePeer, ITcpChannel channel, int heartBeatMillis)
 {
     RemotePeer = remotePeer;
     _channel   = channel;
     AddCloseListener(channel);
     ChannelCreator  = null;
     HeartBeatMillis = heartBeatMillis;
     _initiator      = false;
     _oneConnection  = new Semaphore(1, 1);
     _map            = new Dictionary <TaskCompletionSource <ChannelCreator>, TaskCompletionSource <Message.Message> >();
     _tcsClose       = new TaskCompletionSource <object>();
 }
Exemple #34
0
 private void OnMessage(ITcpChannel channel, object message)
 {
     if (channel.Data["lock"] == null)
     {
         Thread.Sleep(2000);
         channel.Data["lock"] = new object();
     }
     else
     {
         _eventToTriggerBySecond.Set();
     }
 }
Exemple #35
0
 public ClientContext(ITcpChannel channel, object message)
 {
     if (channel == null)
     {
         throw new ArgumentNullException("channel");
     }
     _channel       = channel;
     RequestMessage = message;
     ChannelData    = Channel.Data;
     RemoteEndPoint = channel.RemoteEndpoint;
     RequestData    = new DictionaryContextData();
 }
        private bool RespondWithRaw(Stream body, int statusCode, string mimeType, Dictionary <string, string> headers = null)
        {
            ITcpChannel _channel;

            lock (lockObject)
            {
                if (channel == null)
                {
                    return(false);
                }
                _channel = channel;
                channel  = null;
            }

            try
            {
                IHttpResponse response = request.CreateResponse();
                request = null;

                response.ContentLength = (int)body.Length;
                response.StatusCode    = statusCode;
                response.ContentType   = mimeType;

                if (currentUser != null)
                {
                    response.AddHeader("X-User-Name", currentUser.Value.name);
                    response.AddHeader("X-User-Readonly", currentUser.Value.readOnly ? "Yes" : "No");
                }

                response.AddHeader("Access-Control-Allow-Origin", "*");
                response.AddHeader("Access-Control-Allow-Headers", "Authorization");
                response.AddHeader("Access-Control-Allow-Methods", "POST, HEAD, PUT, DELETE, GET, OPTIONS");
                if (headers != null)
                {
                    foreach (KeyValuePair <string, string> kvp in headers)
                    {
                        response.AddHeader(kvp.Key, kvp.Value);
                    }
                }

                body.Position = 0;
                response.Body = body;

                _channel.Send(response);
            }
            catch
            {
                return(false);
            }

            return(true);
        }
        private void OnError(ITcpChannel channel, Exception exception)
        {
            var socketException = exception as SocketException;
            var soke            = socketException;

            if (soke?.SocketErrorCode == SocketError.Shutdown)
            {
                _log.Warn("Channel [#{0}--Address={1}] Socket already closed", channel.ChannelId,
                          channel.RemoteEndpoint);
                return;
            }
            _log.Error(exception);
        }
Exemple #38
0
 private PeerConnection(Semaphore oneConnection, PeerAddress remotePeer, ChannelCreator cc, bool initiator,
                        IDictionary <TaskCompletionSource <ChannelCreator>, TaskCompletionSource <Message.Message> > map,
                        TaskCompletionSource <object> tcsClose, int heartBeatMillis, ITcpChannel channel)
 {
     _oneConnection  = oneConnection;
     RemotePeer      = remotePeer;
     ChannelCreator  = cc;
     _initiator      = initiator;
     _map            = map;
     _tcsClose       = tcsClose;
     HeartBeatMillis = heartBeatMillis;
     _channel        = channel;
 }
Exemple #39
0
        /// <summary>
        ///     Initializes a new instance of the <see cref="ClientDisconnectedEventArgs" /> class.
        /// </summary>
        /// <param name="channel">The channel that disconnected.</param>
        /// <param name="exception">The exception that was caught.</param>
        public ClientDisconnectedEventArgs(ITcpChannel channel, Exception exception)
        {
            if (channel == null)
            {
                throw new ArgumentNullException("channel");
            }
            if (exception == null)
            {
                throw new ArgumentNullException("exception");
            }

            Channel   = channel;
            Exception = exception;
        }
        /// <summary>
        /// </summary>
        /// <param name="channel"></param>
        /// <param name="transactionManager">
        ///     Must be unique for this client. i.e. the transaction ids used in this client is not
        ///     globally unique
        /// </param>
        public StompClient(ITcpChannel channel, ITransactionManager transactionManager)
        {
            if (channel == null)
            {
                throw new ArgumentNullException("channel");
            }
            if (transactionManager == null)
            {
                throw new ArgumentNullException("transactionManager");
            }

            Channel             = channel;
            _transactionManager = transactionManager;
        }
Exemple #41
0
        private bool AuthenticateUser(ITcpChannel channel, HttpRequest request)
        {
            if (channel.Data["Principal"] != null)
            {
                Thread.CurrentPrincipal = (IPrincipal)channel.Data["Principal"];
                return(true);
            }

            try
            {
                var user = Authenticator.Authenticate(request);
                if (user == null)
                {
                    return(true);
                }

                if (PrincipalFactory != null)
                {
                    var ctx = new PrincipalFactoryContext(request, user);
                    Thread.CurrentPrincipal   = PrincipalFactory.Create(ctx);
                    channel.Data["Principal"] = Thread.CurrentPrincipal;
                    return(true);
                }

                var roles = user as IUserWithRoles;
                if (roles == null)
                {
                    throw new InvalidOperationException(
                              "You must specify a PrincipalFactory if you do not return a IUserWithRoles from your IAccountService.");
                }

                Thread.CurrentPrincipal   = new GenericPrincipal(new GenericIdentity(user.Username), roles.RoleNames);
                channel.Data["Principal"] = Thread.CurrentPrincipal;
            }
            catch (HttpException ex)
            {
                if (Logger != null)
                {
                    Logger("Authentication failed.\r\nException:\r\n" + ex.ToString());
                }
                var response = request.CreateResponse();
                response.StatusCode   = ex.HttpCode;
                response.ReasonPhrase = FirstLine(ex.Message);
                channel.Send(response);
                return(false);
            }

            return(true);
        }
 private void OnChannelDisconnect(ITcpChannel source, Exception exception)
 {
     OnClientDisconnected(source, exception);
     source.Cleanup();
     try
     {
         if (_channels != null &&
             _channels.ContainsKey(source.ChannelId))
         {
             ITcpChannel channel;
             _channels.TryRemove(source.ChannelId, out channel);
         }
     }
     catch (Exception) { }
 }
        /// <summary>
        ///     Receive a new message from the specified client
        /// </summary>
        /// <param name="source">Channel for the client</param>
        /// <param name="msg">Message (as decoded by the specified <see cref="IMessageDecoder" />).</param>
        protected override void OnMessage(ITcpChannel source, object msg)
        {
            var message = (IHttpMessage) msg;

            //TODO: Try again if we fail to update
            var counter = (int) source.Data.GetOrAdd(HttpMessage.PipelineIndexKey, x => 0) + 1;
            source.Data.TryUpdate(HttpMessage.PipelineIndexKey, counter, counter - 1);

            message.Headers[HttpMessage.PipelineIndexKey] = counter.ToString();

            var request = msg as IHttpRequest;
            if (request != null)
                request.RemoteEndPoint = source.RemoteEndpoint;

            base.OnMessage(source, msg);
        }
        private void OnDisconnect(ITcpChannel arg1, Exception arg2)
        {
            _socket = null;

            if (_sendCompletionSource != null)
            {
                _sendCompletionSource.SetException(arg2);
                _sendCompletionSource = null;
            }
                
            if (_readCompletionSource != null)
            {
                _readCompletionSource.SetException(arg2);
                _readCompletionSource = null;
            }
            
        }
        private bool RespondWithRaw(Stream body, int statusCode, string mimeType, Dictionary<string, string> headers = null)
        {
            ITcpChannel _channel;
            lock (lockObject)
            {
                if (channel == null)
                    return false;
                _channel = channel;
                channel = null;
            }

            try
            {
                IHttpResponse response = request.CreateResponse();
                request = null;

                response.ContentLength = (int)body.Length;
                response.StatusCode = statusCode;
                response.ContentType = mimeType;

                if (currentUser != null)
                {
                    response.AddHeader("X-User-Name", currentUser.Value.name);
                    response.AddHeader("X-User-Readonly", currentUser.Value.readOnly ? "Yes" : "No");
                }

                response.AddHeader("Access-Control-Allow-Origin", "*");
                response.AddHeader("Access-Control-Allow-Headers", "Authorization");
                response.AddHeader("Access-Control-Allow-Methods", "POST, HEAD, PUT, DELETE, GET, OPTIONS");
                if (headers != null)
                    foreach (KeyValuePair<string, string> kvp in headers)
                        response.AddHeader(kvp.Key, kvp.Value);

                body.Position = 0;
                response.Body = body;

                _channel.Send(response);
            }
            catch
            {
                return false;
            }

            return true;
        }
Exemple #46
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();

        }
        /// <summary>
        ///     Build a new SSL steam.
        /// </summary>
        /// <param name="channel">Channel which will use the stream</param>
        /// <param name="socket">Socket to wrap</param>
        /// <returns>Stream which is ready to be used (must have been validated)</returns>
        public SslStream Build(ITcpChannel channel, Socket socket) {
            var ns = new NetworkStream(socket);
            var stream = new SslStream(ns, true, OnRemoteCertifiateValidation);

            try {
                stream.AuthenticateAsServer(Certificate, UseClientCertificate, Protocols, CheckCertificateRevocation);
            }
            catch (IOException err) {
                throw new InvalidOperationException("Failed to authenticate " + socket.RemoteEndPoint, err);
            }
            catch (ObjectDisposedException err) {
                throw new InvalidOperationException("Failed to create stream, did client disconnect directly?", err);
            }
            catch (AuthenticationException err) {
                throw new InvalidOperationException("Failed to authenticate " + socket.RemoteEndPoint, err);
            }

            return stream;
        }
        private ITcpChannel CreateChannel()
        {
            if (_channel != null)
                return _channel;

            if (_sslStreamBuilder != null)
            {
                _channel = new SecureTcpChannel(new BufferSlice(new byte[65535], 0, 65535), _encoder, _decoder,
                    _sslStreamBuilder);
            }
            else
            {
                _channel = new TcpChannel(new BufferSlice(new byte[65535], 0, 65535), _encoder, _decoder);
            }

            _channel.Disconnected = OnDisconnect;
            _channel.MessageSent = OnSendCompleted;
            _channel.MessageReceived = OnChannelMessageReceived;
            return _channel;
        }
 private void OnChannelDisconnect(ITcpChannel source, Exception exception)
 {
     OnClientDisconnected(source, exception);
     source.Cleanup();
     _channels.Push(source);
 }
 /// <summary>
 ///     Receive a new message from the specified client
 /// </summary>
 /// <param name="source">Channel for the client</param>
 /// <param name="msg">Message (as decoded by the specified <see cref="IMessageDecoder" />).</param>
 protected virtual void OnMessage(ITcpChannel source, object msg)
 {
     _messageReceived(source, msg);
 }
 /// <summary>
 ///     A client have disconnected
 /// </summary>
 /// <param name="channel">Channel representing the client that disconnected</param>
 /// <param name="exception">
 ///     Exception which was used to detect disconnect (<c>SocketException</c> with status
 ///     <c>Success</c> is created for graceful disconnects)
 /// </param>
 protected virtual void OnClientDisconnected(ITcpChannel channel, Exception exception)
 {
     ClientDisconnected(this, new ClientDisconnectedEventArgs(channel, exception));
 }
 /// <summary>
 ///     A client have connected (nothing have been sent or received yet)
 /// </summary>
 /// <param name="channel">Channel which we created for the remote socket.</param>
 /// <returns></returns>
 protected virtual ClientConnectedEventArgs OnClientConnected(ITcpChannel channel)
 {
     var args = new ClientConnectedEventArgs(channel);
     ClientConnected(this, args);
     return args;
 }
 private void OnClientMessage(ITcpChannel channel, object message)
 {
     var context = new ClientContext(channel, message);
     ExecuteModules(channel, context).Wait();
 }
 public bool IsForChannel(ITcpChannel channel)
 {
     return ReferenceEquals(channel, Channel);
 }
 private void OnChannelMessageReceived(ITcpChannel channel, object message)
 {
     _readCompletionSource.SetResult(message);
     _readCompletionSource = null;
 }
        private void OnConnect(object sender, SocketAsyncEventArgs e)
        {
            if (e.SocketError != SocketError.Success)
            {
                _connectCompletionSource.SetException(new SocketException((int) e.SocketError));
                _connectCompletionSource = null;
                return;
            }

            try
            {
                if (_channel == null)
                    _channel = CreateChannel();

                _channel.Assign(_socket);
            }
            catch (Exception exception)
            {
                _connectCompletionSource.SetException(exception);
                _connectCompletionSource = null;
                return;
            }

            _connectCompletionSource.SetResult((IPEndPoint) _socket.RemoteEndPoint);
            _connectCompletionSource = null;
        }
 private void OnSendCompleted(ITcpChannel channel, object sentMessage)
 {
     _sendCompletionSource.SetResult(sentMessage);
     _sendCompletionSource = null;
 }
        /// <summary>
        ///     Completed Send request event handler. Good for logging.
        /// </summary>
        /// <param name="channel">the Tcp channel used to send the request</param>
        /// <param name="sentMessage">the message sent</param>
        private void OnSendCompleted(ITcpChannel channel, object sentMessage) {
            if (_log.IsDebugEnabled) {
                var cmd = sentMessage as BaseCommand;
                _log.Debug("command sent to freeSwitch <<{0}>>", cmd.ToString());
            }

            _sendCompletedSemaphore.Release();
        }
        /// <summary>
        ///     Fired when a decoded message is received by the channel.
        /// </summary>
        /// <param name="channel">Receiving channel</param>
        /// <param name="message">Decoded message received</param>
        private async void OnMessageReceived(ITcpChannel channel, object message) {
            var decodedMessage = message as EslDecodedMessage;
            // Handle decoded message.
            if (decodedMessage?.Headers == null
                || !decodedMessage.Headers.HasKeys())
                return;
            var headers = decodedMessage.Headers;
            object response = null;
            var contentType = headers["Content-Type"];
            if (string.IsNullOrEmpty(contentType)) return;
            contentType = contentType.ToLowerInvariant();
            switch (contentType) {
                case "auth/request":
                    if (OnAuthentication != null) await OnAuthentication(this, EventArgs.Empty).ConfigureAwait(false);
                    break;
                case "command/reply":
                    var reply = new CommandReply(headers, decodedMessage.OriginalMessage);
                    response = reply;
                    break;
                case "api/response":
                    var apiResponse = new ApiResponse(decodedMessage.BodyText);
                    response = apiResponse;
                    break;
                case "text/event-plain":
                    var parameters = decodedMessage.BodyLines.AllKeys.ToDictionary(key => key,
                        key => decodedMessage.BodyLines[key]);
                    var @event = new EslEvent(parameters);
                    response = @event;
                    break;
                case "log/data":
                    var logdata = new LogData(headers, decodedMessage.BodyText);
                    response = logdata;
                    break;
                case "text/rude-rejection":
                    await _channel.CloseAsync();
                    var reject = new RudeRejection(decodedMessage.BodyText);
                    response = reject;
                    break;
                case "text/disconnect-notice":
                    var notice = new DisconnectNotice(decodedMessage.BodyText);
                    response = notice;
                    break;
                default:
                    // Here we are handling an unknown message
                    var msg = new EslMessage(decodedMessage.Headers, decodedMessage.OriginalMessage);
                    response = msg;
                    break;
            }

            await HandleResponse(response).ConfigureAwait(false);
        }
 /// <summary>
 ///     Disconnection event handler
 /// </summary>
 /// <param name="arg1"></param>
 /// <param name="arg2"></param>
 private void OnDisconnect(ITcpChannel arg1, Exception arg2) {
     _socket = null;
     if (_sendCompletedSemaphore.CurrentCount == 0) {
         _sendException = arg2;
         _sendCompletedSemaphore.Release();
     }
 }