Esempio n. 1
0
        /// <summary>
        /// Process message
        /// </summary>
        /// <param name="context"></param>
        /// <param name="message"></param>
        /// <remarks>
        /// Should always call either <see cref="IPipelineHandlerContext.SendDownstream"/> or <see cref="IPipelineHandlerContext.SendUpstream"/>
        /// unless the handler really wants to stop the processing.
        /// </remarks>
        public void HandleDownstream(IPipelineHandlerContext context, IPipelineMessage message)
        {
            var msg = message as SendResponse;

            if (msg == null)
            {
                context.SendDownstream(message);
                return;
            }

            var result = JsonConvert.SerializeObject(msg.Response, Formatting.None);

            // send header
            var header = new byte[5];

            header[0] = 1;
            var lengthBuffer = BitConverter.GetBytes(result.Length);

            Buffer.BlockCopy(lengthBuffer, 0, header, 1, lengthBuffer.Length);
            context.SendDownstream(new SendBuffer(header, 0, 5));

            // send JSON
            var slice = _bufferPool.PopSlice();

            Encoding.UTF8.GetBytes(result, 0, result.Length, slice.Buffer, slice.StartOffset);
            slice.Position = slice.StartOffset;
            slice.Count    = result.Length;
            context.SendDownstream(new SendSlice(slice));
        }
        /// <summary>
        /// Handle an message
        /// </summary>
        /// <param name="context">Context unique for this handler instance</param>
        /// <param name="message">Message to process</param>
        /// <remarks>
        /// All messages that can't be handled MUST be send up the chain using <see cref="IPipelineHandlerContext.SendUpstream"/>.
        /// </remarks>
        public void HandleUpstream(IPipelineHandlerContext context, IPipelineMessage message)
        {
            var msg = message as ReceivedHttpRequest;
            if (msg == null)
                return;

            if (!Thread.CurrentPrincipal.Identity.IsAuthenticated)
            {
                var authResponse = msg.HttpRequest.CreateResponse(HttpStatusCode.Unauthorized, "Authorize");
                context.SendDownstream(new SendHttpResponse(msg.HttpRequest, authResponse));
                return;
            }

            var request = msg.HttpRequest;
            var response = request.CreateResponse(HttpStatusCode.OK, "OK");

            if (request.Uri.AbsolutePath.Contains("submit.php") && request.Method == "POST")
            {
                Console.WriteLine(request.Form["arne"]);
            }
            var stream = new MemoryStream();
            var writer = new StreamWriter(stream);
            writer.WriteLine("Welcome " + Thread.CurrentPrincipal.Identity.Name);
            writer.WriteLine("the time is: " + DateTime.Now);

            writer.Flush();

            stream.Position = 0;
            response.Body = stream;
            context.SendDownstream(new SendHttpResponse(request, response));
        }
        /// <summary>
        /// Process message
        /// </summary>
        /// <param name="context"></param>
        /// <param name="message"></param>
        /// <remarks>
        /// Should always call either <see cref="IPipelineHandlerContext.SendDownstream"/> or <see cref="IPipelineHandlerContext.SendUpstream"/>
        /// unless the handler really wants to stop the processing.
        /// </remarks>
        public void HandleDownstream(IPipelineHandlerContext context, IPipelineMessage message)
        {
            var msg =  message as SendResponse;
            if (msg == null)
            {
                context.SendDownstream(message);
                return;
            }

            var buffer = _bufferPool.PopSlice();
            var stream = new BufferPoolStream(_bufferPool, buffer);
            _encoder.Encode(msg.Response, stream);
            stream.Position = 0;

            // send header
            var header = new byte[6];
            header[0] = 1;
            header[1] = _mapper.GetContentId(msg.Response);
            var lengthBuffer = BitConverter.GetBytes(buffer.Count);
            Buffer.BlockCopy(lengthBuffer, 0, header, 2, lengthBuffer.Length);
            context.SendDownstream(new SendBuffer(header, 0, 6));

            // send body
            context.SendDownstream(new SendStream(stream));
        }
Esempio n. 4
0
        /// <summary>
        /// Handle an message
        /// </summary>
        /// <param name="context">Context unique for this handler instance</param>
        /// <param name="message">Message to process</param>
        /// <remarks>
        /// All messages that can't be handled MUST be send up the chain using <see cref="IPipelineHandlerContext.SendUpstream"/>.
        /// </remarks>
        public void HandleUpstream(IPipelineHandlerContext context, IPipelineMessage message)
        {
            var msg = message as ReceivedHttpRequest;

            if (msg == null)
            {
                return;
            }

            if (!Thread.CurrentPrincipal.Identity.IsAuthenticated)
            {
                var authResponse = msg.HttpRequest.CreateResponse(HttpStatusCode.Unauthorized, "Authenticate");
                context.SendDownstream(new SendHttpResponse(msg.HttpRequest, authResponse));
                return;
            }

            var request  = msg.HttpRequest;
            var response = request.CreateResponse(HttpStatusCode.OK, "OK");

            if (request.Uri.AbsolutePath.Contains("submit.php") && request.Method == "POST")
            {
                Console.WriteLine(request.Form["arne"]);
            }
            var stream = new MemoryStream();
            var writer = new StreamWriter(stream);

            writer.WriteLine("Welcome " + Thread.CurrentPrincipal.Identity.Name);
            writer.WriteLine("the time is: " + DateTime.Now);

            writer.Flush();

            stream.Position = 0;
            response.Body   = stream;
            context.SendDownstream(new SendHttpResponse(request, response));
        }
Esempio n. 5
0
        /// <summary>
        /// Process message
        /// </summary>
        /// <param name="context"></param>
        /// <param name="message"></param>
        /// <remarks>
        /// Should always call either <see cref="IPipelineHandlerContext.SendDownstream"/> or <see cref="IPipelineHandlerContext.SendUpstream"/>
        /// unless the handler really wants to stop the processing.
        /// </remarks>
        public void HandleDownstream(IPipelineHandlerContext context, IPipelineMessage message)
        {
            var msg = message as SendResponse;

            if (msg == null)
            {
                context.SendDownstream(message);
                return;
            }

            var buffer = _bufferPool.PopSlice();
            var stream = new BufferPoolStream(_bufferPool, buffer);

            _encoder.Encode(msg.Response, stream);
            stream.Position = 0;

            // send header
            var header = new byte[6];

            header[0] = 1;
            header[1] = _mapper.GetContentId(msg.Response);
            var lengthBuffer = BitConverter.GetBytes(buffer.Count);

            Buffer.BlockCopy(lengthBuffer, 0, header, 2, lengthBuffer.Length);
            context.SendDownstream(new SendBuffer(header, 0, 6));

            // send body
            context.SendDownstream(new SendStream(stream));
        }
Esempio n. 6
0
        /// <summary>
        /// Process message
        /// </summary>
        /// <param name="context"></param>
        /// <param name="message"></param>
        public void HandleDownstream(IPipelineHandlerContext context, IPipelineMessage message)
        {
            var msg = message as SendHttpResponse;

            if (msg == null)
            {
                context.SendDownstream(message);
                return;
            }

            var slice      = _pool.Pop();
            var serializer = new HttpHeaderSerializer();
            var stream     = new SliceStream(slice);

            serializer.SerializeResponse(msg.Response, stream);
            context.SendDownstream(new SendSlice(slice, (int)stream.Length));
            if (msg.Response.Body != null)
            {
                context.SendDownstream(new SendStream(msg.Response.Body));
            }

            if (!msg.Response.KeepAlive)
            {
                context.SendDownstream(new Close());
            }
        }
Esempio n. 7
0
        public void HandleDownstream(IPipelineHandlerContext context, IPipelineMessage message)
        {
            var msg = message as SendHttpResponse;
            if (msg == null)
            {
                context.SendDownstream(message);
                return;
            }

            var stream = SerializeHeaders(msg.Response);
            context.SendDownstream(new SendStream(stream));
            context.SendDownstream(new SendStream(msg.Response.Body));
        }
        private void SendCommand(IPipelineHandlerContext context, SendCommandMessage msg)
        {
            if (msg.Command is AuthCmd || msg.Command is SubscribeOnEvents)
            {
                context.SendDownstream(msg);
                _current = msg.Command;
                return;
            }

            _current = new BgApiCmd(msg.Command);
            var message = new SendCommandMessage(_current);

            context.SendDownstream(message);
        }
Esempio n. 9
0
        /// <summary>
        /// Process message
        /// </summary>
        /// <param name="context"></param>
        /// <param name="message"></param>
        /// <remarks>
        /// Should always call either <see cref="IPipelineHandlerContext.SendDownstream"/> or <see cref="IPipelineHandlerContext.SendUpstream"/>
        /// unless the handler really wants to stop the processing.
        /// </remarks>
        public void HandleDownstream(IPipelineHandlerContext context, IPipelineMessage message)
        {
            var msg = message as SendSlice;

            if (msg != null)
            {
                var str = Encoding.UTF8.GetString(msg.BufferSlice.Buffer, msg.BufferSlice.Position, msg.BufferSlice.RemainingLength);
                var sb  = GetAlphaNumeric(str);
                _logger.Trace(sb.ToString());
            }

            var msg2 = message as SendStream;

            if (msg2 != null)
            {
                var buffer = new byte[msg2.Stream.Length];
                msg2.Stream.Read(buffer, 0, buffer.Length);
                msg2.Stream.Position = 0;
                var str = Encoding.UTF8.GetString(buffer, 0, buffer.Length);
                var sb  = GetAlphaNumeric(str);
                _logger.Trace(sb.ToString());
            }

            context.SendDownstream(message);
        }
        /// <summary>
        /// Handle an message
        /// </summary>
        /// <param name="context">Context unique for this handler instance</param>
        /// <param name="message">Message to process</param>
        /// <remarks>
        /// All messages that can't be handled MUST be send up the chain using <see cref="IPipelineHandlerContext.SendUpstream"/>.
        /// </remarks>
        public void HandleUpstream(IPipelineHandlerContext context, IPipelineMessage message)
        {
            var msg = message as ReceivedHttpRequest;

            if (msg == null)
            {
                context.SendUpstream(message);
                return;
            }

            var authHeader = msg.HttpRequest.Headers["Authorization"];

            if (authHeader == null)
            {
                context.SendUpstream(message);
                return;
            }

            var user = _authenticator.Authenticate(msg.HttpRequest);

            if (user == null)
            {
                var response = msg.HttpRequest.CreateResponse(HttpStatusCode.Unauthorized,
                                                              "Invalid username or password.");
                context.SendDownstream(new SendHttpResponse(msg.HttpRequest, response));
            }
            else
            {
                var principal =
                    _principalFactory.Create(new PrincipalFactoryContext {
                    Request = msg.HttpRequest, User = user
                });
                Thread.CurrentPrincipal = principal;
            }
        }
        /// <summary>
        /// Handle an message
        /// </summary>
        /// <param name="context">Context unique for this handler instance</param>
        /// <param name="message">Message to process</param>
        /// <remarks>
        /// All messages that can't be handled MUST be send up the chain using <see cref="IPipelineHandlerContext.SendUpstream"/>.
        /// </remarks>
        public void HandleUpstream(IPipelineHandlerContext context, IPipelineMessage message)
        {
            var msg = message as ReceivedHttpRequest;
            if (msg == null)
            {
                context.SendUpstream(message);
                return;
            }

            var authHeader = msg.HttpRequest.Headers["Authorization"];
            if (authHeader == null)
            {
                context.SendUpstream(message);
                return;
            }

            var user = _authenticator.Authenticate(msg.HttpRequest);
            if (user == null)
            {
                var response = msg.HttpRequest.CreateResponse(HttpStatusCode.Unauthorized,
                                                              "Invalid username or password.");
                context.SendDownstream(new SendHttpResponse(msg.HttpRequest, response));
            }
            else
            {
                var principal =
                    _principalFactory.Create(new PrincipalFactoryContext {Request = msg.HttpRequest, User = user});
                Thread.CurrentPrincipal = principal;
            }
        }
        public void HandleUpstream(IPipelineHandlerContext context, IPipelineMessage message)
        {
            var msg = message as ReceivedMessage;

            if (msg != null && msg.Message.Headers["Content-Type"] == "auth/request")
            {
                var api = new AuthCmd(Password);
                context.SendDownstream(new SendCommandMessage(api));
                return;
            }

            var reply = message as CommandReply;

            if (reply != null && reply.OriginalCommand is AuthCmd)
            {
                if (!reply.IsSuccessful)
                {
                    context.SendUpstream(new AuthenticationFailed(reply.Body));
                }
                else
                {
                    context.SendUpstream(new Authenticated());
                }

                return;
            }

            context.SendUpstream(message);
        }
Esempio n. 13
0
        /// <summary>
        /// Process message
        /// </summary>
        /// <param name="context"></param>
        /// <param name="message"></param>
        /// <remarks>
        /// Should always call either <see cref="IPipelineHandlerContext.SendDownstream"/> or <see cref="IPipelineHandlerContext.SendUpstream"/>
        /// unless the handler really wants to stop the processing.
        /// </remarks>
        public void HandleDownstream(IPipelineHandlerContext context, IPipelineMessage message)
        {
            var msg = message as SendSlice;

            if (msg != null)
            {
                var stream = new MemoryStream();
                stream.Write(msg.Slice.Buffer, msg.Slice.Offset, msg.Length);

                var reader = new StreamReader(stream);
                var str    = reader.ReadToEnd();

                var sb = GetAlphaNumeric(str);
                _logger.Trace(sb.ToString());
            }

            var msg2 = message as SendStream;

            if (msg2 != null)
            {
                var buffer = new byte[msg2.Stream.Length];
                msg2.Stream.Read(buffer, 0, buffer.Length);
                msg2.Stream.Position = 0;
                var str = Encoding.UTF8.GetString(buffer, 0, buffer.Length);
                var sb  = GetAlphaNumeric(str);
                _logger.Trace(sb.ToString());
            }

            context.SendDownstream(message);
        }
        /// <summary>
        /// Process message
        /// </summary>
        /// <param name="context"></param>
        /// <param name="message"></param>
        /// <remarks>
        /// Should always call either <see cref="IPipelineHandlerContext.SendDownstream"/> or <see cref="IPipelineHandlerContext.SendUpstream"/>
        /// unless the handler really wants to stop the processing.
        /// </remarks>
        public void HandleDownstream(IPipelineHandlerContext context, IPipelineMessage message)
        {
            var msg = message as SendHttpResponse;
            if (msg == null)
            {
                context.SendDownstream(message);
                return;
            }

            if (msg.Response.StatusCode == (int) HttpStatusCode.Unauthorized)
            {
                _authenticator.CreateChallenge(msg.Request, msg.Response);
            }

            context.SendDownstream(message);
        }
Esempio n. 15
0
        /// <summary>
        /// Process message
        /// </summary>
        /// <param name="context"></param>
        /// <param name="message"></param>
        /// <remarks>
        /// Should always call either <see cref="IPipelineHandlerContext.SendDownstream"/> or <see cref="IPipelineHandlerContext.SendUpstream"/>
        /// unless the handler really wants to stop the processing.
        /// </remarks>
        public void HandleDownstream(IPipelineHandlerContext context, IPipelineMessage message)
        {
            var msg = message as SendSlice;
            if (msg != null)
            {
                var str = Encoding.UTF8.GetString(msg.BufferSlice.Buffer, msg.BufferSlice.Position, msg.BufferSlice.RemainingLength);
                var sb = GetAlphaNumeric(str);
               _logger.Trace(sb.ToString());

            }

            var msg2 = message as SendStream;
            if (msg2 != null)
            {
                var buffer = new byte[msg2.Stream.Length];
                msg2.Stream.Read(buffer, 0, buffer.Length);
                msg2.Stream.Position = 0;
                var str = Encoding.UTF8.GetString(buffer, 0, buffer.Length);
                var sb = GetAlphaNumeric(str);
                _logger.Trace(sb.ToString());

            }

            context.SendDownstream(message);
        }
        /// <summary>
        /// Process message
        /// </summary>
        /// <param name="context"></param>
        /// <param name="message"></param>
        /// <remarks>
        /// Should always call either <see cref="IPipelineHandlerContext.SendDownstream"/> or <see cref="IPipelineHandlerContext.SendUpstream"/>
        /// unless the handler really wants to stop the processing.
        /// </remarks>
        public void HandleDownstream(IPipelineHandlerContext context, IPipelineMessage message)
        {
            var msg = message as SendSlice;
            if (msg != null)
            {
                var stream = new MemoryStream();
                stream.Write(msg.Slice.Buffer, msg.Slice.Offset, msg.Length);

                var reader = new StreamReader(stream);
                var str = reader.ReadToEnd();

                var sb = GetAlphaNumeric(str);
                _logger.Trace(sb.ToString());
            }

            var msg2 = message as SendStream;
            if (msg2 != null)
            {
                var buffer = new byte[msg2.Stream.Length];
                msg2.Stream.Read(buffer, 0, buffer.Length);
                msg2.Stream.Position = 0;
                var str = Encoding.UTF8.GetString(buffer, 0, buffer.Length);
                var sb = GetAlphaNumeric(str);
                _logger.Trace(sb.ToString());
            }

            context.SendDownstream(message);
        }
        /// <summary>
        /// Handle an message
        /// </summary>
        /// <param name="context">Context unique for this handler instance</param>
        /// <param name="message">Message to process</param>
        /// <remarks>
        /// All messages that can't be handled MUST be send up the chain using <see cref="IPipelineHandlerContext.SendUpstream"/>.
        /// </remarks>
        public void HandleUpstream(IPipelineHandlerContext context, IPipelineMessage message)
        {
            var msg = message as ReceivedRequest;
            if (msg == null)
                return;


            var parray = msg.Request.Parameters as object[];
            if (parray == null)
                return; // muhahaha, violating the API specification

            object result;
            switch (msg.Request.Method)
            {
                case "add":
                    result = int.Parse(parray[0].ToString()) + int.Parse(parray[0].ToString());
                    break;
                case "substract":
                    result = int.Parse(parray[0].ToString()) + int.Parse(parray[0].ToString());
                    break;
                default:
                    result = "Nothing useful.";
                    break;
            }

            var response = new Response(msg.Request.Id, result);
            context.SendDownstream(new SendResponse(response));
        }
        /// <summary>
        /// Process message
        /// </summary>
        /// <param name="context"></param>
        /// <param name="message"></param>
        public void HandleDownstream(IPipelineHandlerContext context, IPipelineMessage message)
        {
            var msg = message as SendHttpResponse;
            if (msg == null)
            {
                context.SendDownstream(message);
                return;
            }

            var stream = SerializeHeaders(msg.Response);
            stream.Position = 0;
            context.SendDownstream(new SendStream(stream));
            if (msg.Response.Body != null)
                context.SendDownstream(new SendStream(msg.Response.Body));
            if (!msg.Response.KeepAlive)
                context.SendDownstream(new Close());
        }
Esempio n. 19
0
        /// <summary>
        /// Process message
        /// </summary>
        /// <param name="context"></param>
        /// <param name="message"></param>
        /// <remarks>
        /// Should always call either <see cref="IPipelineHandlerContext.SendDownstream"/> or <see cref="IPipelineHandlerContext.SendUpstream"/>
        /// unless the handler really wants to stop the processing.
        /// </remarks>
        public void HandleDownstream(IPipelineHandlerContext context, IPipelineMessage message)
        {
            var msg = message as SendHttpResponse;

            if (msg == null)
            {
                context.SendDownstream(message);
                return;
            }

            if (msg.Response.StatusCode == (int)HttpStatusCode.Unauthorized)
            {
                _authenticator.CreateChallenge(msg.Request, msg.Response);
            }

            context.SendDownstream(message);
        }
        /// <summary>
        /// Handle an message
        /// </summary>
        /// <param name="context">Context unique for this handler instance</param>
        /// <param name="message">Message to process</param>
        /// <remarks>
        /// All messages that can't be handled MUST be send up the chain using <see cref="IPipelineHandlerContext.SendUpstream"/>.
        /// </remarks>
        public void HandleUpstream(IPipelineHandlerContext context, IPipelineMessage message)
        {
            var msg = message as ReceivedHttpRequest;

            if (msg == null)
            {
                context.SendUpstream(message);
                return;
            }

            var authHeader = msg.HttpRequest.Headers["Authorization"];

            if (authHeader == null)
            {
                context.SendUpstream(message);
                return;
            }

            IAuthenticationUser user;

            try
            {
                user = this._authenticator.Authenticate(msg.HttpRequest);
            }
            catch (HttpException err)
            {
                var response = msg.HttpRequest.CreateResponse(err.StatusCode, err.Message);
                context.SendDownstream(new SendHttpResponse(msg.HttpRequest, response));
                return;
            }

            if (user == null)
            {
                var response = msg.HttpRequest.CreateResponse(HttpStatusCode.Unauthorized,
                                                              "Invalid username or password.");
                context.SendDownstream(new SendHttpResponse(msg.HttpRequest, response));
            }
            else
            {
                var principal = this._principalFactory.Create(new PrincipalFactoryContext(msg.HttpRequest, user));
                //Thread.CurrentPrincipal = principal;
                context.SendUpstream(message);
            }
        }
        /// <summary>
        /// Takes a <see cref="Message"/> and converts it into a byte buffer.
        /// </summary>
        /// <param name="ctx"></param>
        /// <param name="message"></param>
        public void HandleDownstream(IPipelineHandlerContext ctx, IPipelineMessage message)
        {
            if (message is SendCommandMessage)
            {
                var evt = (SendCommandMessage) message;
                var slice = EncodeCommand(evt.Command);
                message = new SendSlice(slice);
            }

            ctx.SendDownstream(message);
        }
        /// <summary>
        /// Process message
        /// </summary>
        /// <param name="context"></param>
        /// <param name="message"></param>
        public void HandleDownstream(IPipelineHandlerContext context, IPipelineMessage message)
        {
            var msg = message as SendHttpResponse;
            if (msg == null)
            {
                context.SendDownstream(message);
                return;
            }

            var slice = _pool.Pop();
            var serializer = new HttpHeaderSerializer();
            var stream = new SliceStream(slice);
            serializer.SerializeResponse(msg.Response, stream);
            context.SendDownstream(new SendSlice(slice, (int) stream.Length));
            if (msg.Response.Body != null)
                context.SendDownstream(new SendStream(msg.Response.Body));

            if (!msg.Response.KeepAlive)
                context.SendDownstream(new Close());
        }
Esempio n. 23
0
        /// <summary>
        /// Takes a <see cref="Message"/> and converts it into a byte buffer.
        /// </summary>
        /// <param name="ctx"></param>
        /// <param name="message"></param>
        public void HandleDownstream(IPipelineHandlerContext ctx, IPipelineMessage message)
        {
            if (message is SendCommandMessage)
            {
                var evt   = (SendCommandMessage)message;
                var slice = EncodeCommand(evt.Command);
                message = new SendSlice(slice);
            }

            ctx.SendDownstream(message);
        }
Esempio n. 24
0
 /// <summary>
 ///   Send the response back to the remote client
 /// </summary>
 public void Send()
 {
     if (_httpResponse.Body != null)
     {
         _httpResponse.Body.Position = 0;
     }
     _httpContext.SendDownstream(new SendHttpResponse(_httpRequest, _httpResponse));
     if (_httpResponse.Body != null)
     {
         _httpResponse.Body.Dispose();
     }
 }
        /// <summary>
        /// Handle an message
        /// </summary>
        /// <param name="context">Context unique for this handler instance</param>
        /// <param name="message">Message to process</param>
        /// <remarks>
        /// All messages that can't be handled MUST be send up the chain using <see cref="IPipelineHandlerContext.SendUpstream"/>.
        /// </remarks>
        public void HandleUpstream(IPipelineHandlerContext context, IPipelineMessage message)
        {
            var failure = message as PipelineFailure;
            if (failure != null)
            {
                var response = new HttpResponse("HTTP/1.1", HttpStatusCode.InternalServerError, "Server failed!");
                response.Body = new MemoryStream();
                var buffer = Encoding.ASCII.GetBytes(failure.Exception.ToString());
                response.Body.Write(buffer, 0, buffer.Length);
                response.Body.Position = 0;
                context.SendDownstream(new SendHttpResponse(null, response));
                return;
            }

            var requestMsg = message as ReceivedHttpRequest;
            if(requestMsg != null)
            {
                var response = new HttpResponse("HTTP/1.1", HttpStatusCode.NotFound, "Failed to find " + requestMsg.HttpRequest.Uri.AbsolutePath);
                context.SendDownstream(new SendHttpResponse(null, response));
            }
        }
        /// <summary>
        /// Handle an message
        /// </summary>
        /// <param name="context">Context unique for this handler instance</param>
        /// <param name="message">Message to process</param>
        /// <remarks>
        /// All messages that can't be handled MUST be send up the chain using <see cref="IPipelineHandlerContext.SendUpstream"/>.
        /// </remarks>
        public void HandleUpstream(IPipelineHandlerContext context, IPipelineMessage message)
        {
            var msg = message as ReceivedRequest;
            if (msg == null)
            {
                context.SendUpstream(message);
                return;
            }

            var response = _rpcInvoker.Invoke(msg.Request);
            context.SendDownstream(new SendResponse(response));
        }
Esempio n. 27
0
        /// <summary>
        /// Process message
        /// </summary>
        /// <param name="context"></param>
        /// <param name="message"></param>
        public void HandleDownstream(IPipelineHandlerContext context, IPipelineMessage message)
        {
            var msg = message as SendHttpResponse;

            if (msg == null)
            {
                context.SendDownstream(message);
                return;
            }

            var stream = SerializeHeaders(msg.Response);

            stream.Position = 0;
            context.SendDownstream(new SendStream(stream));
            if (msg.Response.Body != null)
            {
                context.SendDownstream(new SendStream(msg.Response.Body));
            }
            if (!msg.Response.KeepAlive)
            {
                context.SendDownstream(new Close());
            }
        }
        /// <summary>
        /// Process message
        /// </summary>
        /// <param name="context"></param>
        /// <param name="message"></param>
        /// <remarks>
        /// Should always call either <see cref="IPipelineHandlerContext.SendDownstream"/> or <see cref="IPipelineHandlerContext.SendUpstream"/>
        /// unless the handler really wants to stop the processing.
        /// </remarks>
        public void HandleDownstream(IPipelineHandlerContext context, IPipelineMessage message)
        {
            var msg = message as SendResponse;
            if (msg == null)
            {
                context.SendDownstream(message);
                return;
            }

            var result = JsonConvert.SerializeObject(msg.Response, Formatting.None);

            // send header
            var header = new byte[5];
            header[0] = 1;
            var lengthBuffer = BitConverter.GetBytes(result.Length);
            Buffer.BlockCopy(lengthBuffer, 0, header, 1, lengthBuffer.Length);
            context.SendDownstream(new SendBuffer(header, 0, 5));

            // send JSON
            var slice = _bufferPool.Pop();
            Encoding.UTF8.GetBytes(result, 0, result.Length, slice.Buffer, slice.Offset);
            context.SendDownstream(new SendSlice(slice, result.Length));
        }
Esempio n. 29
0
        /// <summary>
        /// Handle an message
        /// </summary>
        /// <param name="context">Context unique for this handler instance</param>
        /// <param name="message">Message to process</param>
        /// <remarks>
        /// All messages that can't be handled MUST be send up the chain using <see cref="IPipelineHandlerContext.SendUpstream"/>.
        /// </remarks>
        public void HandleUpstream(IPipelineHandlerContext context, IPipelineMessage message)
        {
            var msg = message as ReceivedHttpRequest;

            if (msg == null)
            {
                context.SendUpstream(message);
                return;
            }

            var ifModifiedSince = DateTime.MinValue;
            var header          = msg.HttpRequest.Headers["If-Modified-Since"];

            if (header != null)
            {
                ifModifiedSince = DateTime.Parse(header.Value).ToUniversalTime();

                // Allow for file systems with subsecond time stamps
                ifModifiedSince = new DateTime(ifModifiedSince.Year, ifModifiedSince.Month, ifModifiedSince.Day,
                                               ifModifiedSince.Hour, ifModifiedSince.Minute, ifModifiedSince.Second,
                                               ifModifiedSince.Kind);
            }


            var fileContext = new FileContext(msg.HttpRequest, ifModifiedSince);

            _fileService.GetFile(fileContext);
            if (fileContext.LastModifiedAtUtc > DateTime.MinValue)
            {
                var response = msg.HttpRequest.CreateResponse(HttpStatusCode.OK, "File found");
                var filename = msg.HttpRequest.Uri.Segments[msg.HttpRequest.Uri.Segments.Length - 1];
                response.ContentType = _mimeTypeProvider.Get(filename);
                if (fileContext.FileStream == null)
                {
                    response.StatusDescription = "File have not changed since " + fileContext.LastModifiedAtUtc;
                    response.StatusCode        = (int)HttpStatusCode.NotModified;
                }
                else
                {
                    response.AddHeader("Last-Modified", fileContext.LastModifiedAtUtc.ToString("R"));
                    response.Body = fileContext.FileStream;
                }

                context.SendDownstream(new SendHttpResponse(msg.HttpRequest, response));
                return;
            }


            context.SendUpstream(message);
        }
Esempio n. 30
0
        /// <summary>
        /// Handle an message
        /// </summary>
        /// <param name="context">Context unique for this handler instance</param>
        /// <param name="message">Message to process</param>
        /// <remarks>
        /// All messages that can't be handled MUST be send up the chain using <see cref="IPipelineHandlerContext.SendUpstream"/>.
        /// </remarks>
        public void HandleUpstream(IPipelineHandlerContext context, IPipelineMessage message)
        {
            var msg = message as ReceivedRequest;

            if (msg == null)
            {
                context.SendUpstream(message);
                return;
            }

            var response = _rpcInvoker.Invoke(msg.Request);

            context.SendDownstream(new SendResponse(response));
        }
Esempio n. 31
0
        /// <summary>
        /// Handle an message
        /// </summary>
        /// <param name="context">Context unique for this handler instance</param>
        /// <param name="message">Message to process</param>
        /// <remarks>
        /// All messages that can't be handled MUST be send up the chain using <see cref="IPipelineHandlerContext.SendUpstream"/>.
        /// </remarks>
        public void HandleUpstream(IPipelineHandlerContext context, IPipelineMessage message)
        {
            var httpmsg = message as ReceivedHttpRequest;

            if (httpmsg != null)
            {
                if (httpmsg.HttpRequest.ContentLength > _sizeLimit)
                {
                    var response = httpmsg.HttpRequest.CreateResponse(HttpStatusCode.RequestEntityTooLarge,
                                                                      string.Format("Max body size is {0} bytes.",
                                                                                    _sizeLimit));
                    context.SendDownstream(new SendHttpResponse(httpmsg.HttpRequest, response));
                    return;
                }

                if (httpmsg.HttpRequest.ContentLength == 0)
                {
                    context.SendUpstream(message);
                    return;
                }

                _currentMessage = httpmsg.HttpRequest;
                return; // don't send the request upwards.
            }

            var msg = message as Received;

            if (msg != null)
            {
                if (_currentMessage == null)
                {
                    throw new InvalidOperationException("Current message is not set. We have no way of knowing when to stop decoding the body.");
                }

                var result = ParseBody(msg.BufferReader);
                if (!result)
                {
                    return;
                }

                _currentMessage.Body.Position = 0;
                _decoderService.Decode((IRequest)_currentMessage);
                context.SendUpstream(new ReceivedHttpRequest((HttpRequest)_currentMessage));
                _currentMessage = null;
                return;
            }

            // pass on all other messages
            context.SendUpstream(message);
        }
Esempio n. 32
0
        /// <summary>
        /// Handle an message
        /// </summary>
        /// <param name="context">Context unique for this handler instance</param>
        /// <param name="message">Message to process</param>
        /// <remarks>
        /// All messages that can't be handled MUST be send up the chain using <see cref="IPipelineHandlerContext.SendUpstream"/>.
        /// </remarks>
        public void HandleUpstream(IPipelineHandlerContext context, IPipelineMessage message)
        {
            var failure = message as PipelineFailure;

            if (failure != null)
            {
                var response = new HttpResponse("HTTP/1.1", HttpStatusCode.InternalServerError, "Server failed!");
                response.Body = new MemoryStream();
                var buffer = Encoding.ASCII.GetBytes(failure.Exception.ToString());
                response.Body.Write(buffer, 0, buffer.Length);
                response.Body.Position = 0;
                context.SendDownstream(new SendHttpResponse(null, response));
                return;
            }

            var requestMsg = message as ReceivedHttpRequest;

            if (requestMsg != null)
            {
                var response = new HttpResponse("HTTP/1.1", HttpStatusCode.NotFound, "Failed to find " + requestMsg.HttpRequest.Uri.AbsolutePath);
                context.SendDownstream(new SendHttpResponse(null, response));
            }
        }
        /// <summary>
        /// Process message
        /// </summary>
        /// <param name="context"></param>
        /// <param name="message"></param>
        /// <remarks>
        /// Should always call either <see cref="IPipelineHandlerContext.SendDownstream"/> or <see cref="IPipelineHandlerContext.SendUpstream"/>
        /// unless the handler really wants to stop the processing.
        /// </remarks>
        public void HandleDownstream(IPipelineHandlerContext context, IPipelineMessage message)
        {
            var msg = message as SendSlice;
            if (msg != null)
            {
                var bytes =
                    Encoding.ASCII.GetBytes("\r\nTo FreeSwitch ***************** " + DateTime.Now.ToShortDateString() +
                                            " " +
                                            DateTime.Now.ToString("HH:mm:ss.nnn") + " ******************\r\n\r\n");
                _destinationStream.Write(bytes, 0, bytes.Length);
                _destinationStream.Write(msg.BufferSlice.Buffer, 0, msg.BufferSlice.Count);
                _destinationStream.Flush();
            }

            context.SendDownstream(message);
        }
Esempio n. 34
0
        /// <summary>
        /// Process message
        /// </summary>
        /// <param name="context"></param>
        /// <param name="message"></param>
        /// <remarks>
        /// Should always call either <see cref="IPipelineHandlerContext.SendDownstream"/> or <see cref="IPipelineHandlerContext.SendUpstream"/>
        /// unless the handler really wants to stop the processing.
        /// </remarks>
        public void HandleDownstream(IPipelineHandlerContext context, IPipelineMessage message)
        {
            var msg = message as SendSlice;

            if (msg != null)
            {
                var bytes =
                    Encoding.ASCII.GetBytes("\r\nTo FreeSwitch ***************** " + DateTime.Now.ToShortDateString() +
                                            " " +
                                            DateTime.Now.ToString("HH:mm:ss.nnn") + " ******************\r\n\r\n");
                _destinationStream.Write(bytes, 0, bytes.Length);
                _destinationStream.Write(msg.BufferSlice.Buffer, 0, msg.BufferSlice.Count);
                _destinationStream.Flush();
            }

            context.SendDownstream(message);
        }
Esempio n. 35
0
        /// <summary>
        /// Handle an message
        /// </summary>
        /// <param name="context">Context unique for this handler instance</param>
        /// <param name="message">Message to process</param>
        public void HandleUpstream(IPipelineHandlerContext context, IPipelineMessage message)
        {
            var headerMsg = message as ReceivedHeader;

            if (headerMsg != null)
            {
                _header = headerMsg.Header;
                if (_header.Length > 65535)
                {
                    var error = new ErrorResponse("-9999", new RpcError
                    {
                        Code    = RpcErrorCode.InvalidRequest,
                        Message =
                            "Support requests which is at most 655355 bytes.",
                    });
                    context.SendDownstream(new SendResponse(error));
                }

                return;
            }

            var received = message as Received;

            if (received != null)
            {
                var count = Math.Min(received.BufferSlice.RemainingLength, _header.Length);
                _stream.Write(received.BufferSlice.Buffer, received.BufferSlice.Position, count);
                received.BufferSlice.Position += count;

                if (_stream.Length == _header.Length)
                {
                    _stream.Position = 0;
                    var request = DeserializeRequest(_stream);
                    context.SendUpstream(new ReceivedRequest(request));
                }

                return;
            }

            context.SendUpstream(message);
        }
Esempio n. 36
0
        /// <summary>
        /// Handle an message
        /// </summary>
        /// <param name="context">Context unique for this handler instance</param>
        /// <param name="message">Message to process</param>
        /// <remarks>
        /// All messages that can't be handled MUST be send up the chain using <see cref="IPipelineHandlerContext.SendUpstream"/>.
        /// </remarks>
        public void HandleUpstream(IPipelineHandlerContext context, IPipelineMessage message)
        {
            var httpmsg = message as ReceivedHttpRequest;
            if (httpmsg != null)
            {
                if (httpmsg.HttpRequest.ContentLength > _sizeLimit)
                {
                    var response = httpmsg.HttpRequest.CreateResponse(HttpStatusCode.RequestEntityTooLarge,
                                                                      string.Format("Max body size is {0} bytes.",
                                                                                    _sizeLimit));
                    context.SendDownstream(new SendHttpResponse(httpmsg.HttpRequest, response));
                    return;
                }

                if (httpmsg.HttpRequest.ContentLength == 0)
                {
                    context.SendUpstream(message);
                    return;
                }

                _currentMessage = httpmsg.HttpRequest;
                return; // don't send the request upwards.
            }

            var msg = message as Received;
            if (msg != null)
            {
                var result = ParseBody(msg.BufferReader);
                if (!result)
                    return;

                _currentMessage.Body.Position = 0;
                _decoderService.Decode((IRequest) _currentMessage);
                context.SendUpstream(new ReceivedHttpRequest((HttpRequest) _currentMessage));
                _currentMessage = null;
                return;
            }

            // pass on all other messages
            context.SendUpstream(message);
        }
        public void HandleUpstream(IPipelineHandlerContext context, IPipelineMessage message)
        {
            var msg = message as ReceivedMessage;
            if (msg != null && msg.Message.Headers["Content-Type"] == "auth/request")
            {
                var api = new AuthCmd(Password);
                context.SendDownstream(new SendCommandMessage(api));
                return;
            }

            var reply = message as CommandReply;
            if (reply != null && reply.OriginalCommand is AuthCmd)
            {
                if (!reply.IsSuccessful)
                    context.SendUpstream(new AuthenticationFailed(reply.Body));
                else
                    context.SendUpstream(new Authenticated());

                return;
            }

            context.SendUpstream(message);
        }
        /// <summary>
        /// Handle an message
        /// </summary>
        /// <param name="context">Context unique for this handler instance</param>
        /// <param name="message">Message to process</param>
        /// <remarks>
        /// All messages that can't be handled MUST be send up the chain using <see cref="IPipelineHandlerContext.SendUpstream"/>.
        /// </remarks>
        public void HandleUpstream(IPipelineHandlerContext context, IPipelineMessage message)
        {
            var msg = message as ReceivedHttpRequest;
            if (msg == null)
            {
                context.SendUpstream(message);
                return;
            }

            try
            {
                context.SendUpstream(message);
            }
            catch (HttpException err)
            {
                var response = msg.HttpRequest.CreateResponse(err.StatusCode, err.Message);

                FormatException(response, msg, err);
                response.Body.Position = 0;

                context.SendDownstream(new SendHttpResponse(msg.HttpRequest, response));
            }
        }
        /// <summary>
        /// Process message
        /// </summary>
        /// <param name="context"></param>
        /// <param name="message"></param>
        /// <remarks>
        /// Should always call either <see cref="IPipelineHandlerContext.SendDownstream"/> or <see cref="IPipelineHandlerContext.SendUpstream"/>
        /// unless the handler really wants to stop the processing.
        /// </remarks>
        public void HandleDownstream(IPipelineHandlerContext context, IPipelineMessage message)
        {
            if (!(message is SendCommandMessage))
            {
                context.SendDownstream(message);
                return;
            }

            lock (_outbound)
            {
                var cmd = (SendCommandMessage) message;
                if (_current == null)
                {
                    _logger.Trace("Passing command down " + cmd.Command);
                    SendCommand(context, cmd);
                }
                else
                {
                    _logger.Debug("Enqueueing command " + cmd.Command);
                    _outbound.Enqueue(cmd);
                }
            }
        }
Esempio n. 40
0
        /// <summary>
        /// Process message
        /// </summary>
        /// <param name="context"></param>
        /// <param name="message"></param>
        /// <remarks>
        /// Should always call either <see cref="IPipelineHandlerContext.SendDownstream"/> or <see cref="IPipelineHandlerContext.SendUpstream"/>
        /// unless the handler really wants to stop the processing.
        /// </remarks>
        public void HandleDownstream(IPipelineHandlerContext context, IPipelineMessage message)
        {
            if (!(message is SendCommandMessage))
            {
                context.SendDownstream(message);
                return;
            }

            lock (_outbound)
            {
                var cmd = (SendCommandMessage)message;
                if (_current == null)
                {
                    _logger.Trace("Passing command down " + cmd.Command);
                    SendCommand(context, cmd);
                }
                else
                {
                    _logger.Debug("Enqueueing command " + cmd.Command);
                    _outbound.Enqueue(cmd);
                }
            }
        }
Esempio n. 41
0
        /// <summary>
        /// Handle an message
        /// </summary>
        /// <param name="context">Context unique for this handler instance</param>
        /// <param name="message">Message to process</param>
        public void HandleUpstream(IPipelineHandlerContext context, IPipelineMessage message)
        {
            var headerMsg = message as ReceivedHeader;
            if (headerMsg != null)
            {
                _header = headerMsg.Header;
                if (_header.Length > 65535)
                {
                    var error = new ErrorResponse("-9999", new RpcError
                        {
                            Code = RpcErrorCode.InvalidRequest,
                            Message =
                                "Support requests which is at most 655355 bytes.",
                        });
                    context.SendDownstream(new SendResponse(error));
                }

                return;
            }

            var received = message as Received;
            if (received != null)
            {
                var count = Math.Min(received.BufferReader.Count, _header.Length);
                received.BufferReader.CopyTo(_stream, count);
                if (_stream.Length == _header.Length)
                {
                    _stream.Position = 0;
                    var request = DeserializeRequest(_stream);
                    context.SendUpstream(new ReceivedRequest(request));
                }

                return;
            }

            context.SendUpstream(message);
        }
Esempio n. 42
0
        /// <summary>
        /// Handle an message
        /// </summary>
        /// <param name="context">Context unique for this handler instance</param>
        /// <param name="message">Message to process</param>
        /// <remarks>
        /// All messages that can't be handled MUST be send up the chain using <see cref="IPipelineHandlerContext.SendUpstream"/>.
        /// </remarks>
        public void HandleUpstream(IPipelineHandlerContext context, IPipelineMessage message)
        {
            var msg = message as ReceivedRequest;

            if (msg == null)
            {
                return;
            }


            var parray = msg.Request.Parameters as object[];

            if (parray == null)
            {
                return; // muhahaha, violating the API specification
            }
            object result;

            switch (msg.Request.Method)
            {
            case "add":
                result = int.Parse(parray[0].ToString()) + int.Parse(parray[0].ToString());
                break;

            case "substract":
                result = int.Parse(parray[0].ToString()) + int.Parse(parray[0].ToString());
                break;

            default:
                result = "Nothing useful.";
                break;
            }

            var response = new Response(msg.Request.Id, result);

            context.SendDownstream(new SendResponse(response));
        }
Esempio n. 43
0
        /// <summary>
        /// Handle an message
        /// </summary>
        /// <param name="context">Context unique for this handler instance</param>
        /// <param name="message">Message to process</param>
        /// <remarks>
        /// All messages that can't be handled MUST be send up the chain using <see cref="IPipelineHandlerContext.SendUpstream"/>.
        /// </remarks>
        public void HandleUpstream(IPipelineHandlerContext context, IPipelineMessage message)
        {
            var msg = message as ReceivedHttpRequest;

            if (msg == null)
            {
                context.SendUpstream(message);
                return;
            }

            try
            {
                context.SendUpstream(message);
            }
            catch (HttpException err)
            {
                var response = msg.HttpRequest.CreateResponse(err.StatusCode, err.Message);

                FormatException(response, msg, err);
                response.Body.Position = 0;

                context.SendDownstream(new SendHttpResponse(msg.HttpRequest, response));
            }
        }
Esempio n. 44
0
 public void HandleDownstream(IPipelineHandlerContext context, IPipelineMessage message)
 {
     Assert.Equal(_index, CurrentIndex);
     CurrentIndex--;
     context.SendDownstream(message);
 }
Esempio n. 45
0
 /// <summary>
 /// Process message
 /// </summary>
 /// <param name="context"></param>
 /// <param name="message"></param>
 /// <remarks>
 /// Should always call either <see cref="IPipelineHandlerContext.SendDownstream"/> or <see cref="IPipelineHandlerContext.SendUpstream"/>
 /// unless the handler really wants to stop the processing.
 /// </remarks>
 public void HandleDownstream(IPipelineHandlerContext context, IPipelineMessage message)
 {
     context.SendDownstream(message);
 }
        private void SendCommand(IPipelineHandlerContext context, SendCommandMessage msg)
        {
            if (msg.Command is AuthCmd || msg.Command is SubscribeOnEvents)
            {
                context.SendDownstream(msg);
                _current = msg.Command;
                return;
            }

            _current = new BgApiCmd(msg.Command);
            var message = new SendCommandMessage(_current);
            context.SendDownstream(message);
        }
 /// <summary>
 /// Process message
 /// </summary>
 /// <param name="context"></param>
 /// <param name="message"></param>
 /// <remarks>
 /// Should always call either <see cref="IPipelineHandlerContext.SendDownstream"/> or <see cref="IPipelineHandlerContext.SendUpstream"/>
 /// unless the handler really wants to stop the processing.
 /// </remarks>
 public void HandleDownstream(IPipelineHandlerContext context, IPipelineMessage message)
 {
     context.SendDownstream(message);
 }
Esempio n. 48
0
        /// <summary>
        /// Handle an message
        /// </summary>
        /// <param name="context">Context unique for this handler instance</param>
        /// <param name="message">Message to process</param>
        /// <remarks>
        /// All messages that can't be handled MUST be send up the chain using <see cref="IPipelineHandlerContext.SendUpstream"/>.
        /// </remarks>
        public void HandleUpstream(IPipelineHandlerContext context, IPipelineMessage message)
        {
            var msg = message as ReceivedHttpRequest;
            if (msg == null)
            {
                context.SendUpstream(message);
                return;
            }

            var ifModifiedSince = DateTime.MinValue;
            var header = msg.HttpRequest.Headers["If-Modified-Since"];
            if (header != null)
            {
                ifModifiedSince = DateTime.Parse(header.Value).ToUniversalTime();

                // Allow for file systems with subsecond time stamps
                ifModifiedSince = new DateTime(ifModifiedSince.Year, ifModifiedSince.Month, ifModifiedSince.Day,
                                               ifModifiedSince.Hour, ifModifiedSince.Minute, ifModifiedSince.Second,
                                               ifModifiedSince.Kind);
            }

            
            var fileContext = new FileContext(msg.HttpRequest, ifModifiedSince);
            _fileService.GetFile(fileContext);
            if (fileContext.LastModifiedAtUtc > DateTime.MinValue)
            {
                var response = msg.HttpRequest.CreateResponse(HttpStatusCode.OK, "File found");
                var filename = msg.HttpRequest.Uri.Segments[msg.HttpRequest.Uri.Segments.Length - 1];
                response.ContentType = _mimeTypeProvider.Get(filename);
                if (fileContext.FileStream == null)
                {
                    response.StatusDescription = "File have not changed since " + fileContext.LastModifiedAtUtc;
                    response.StatusCode = (int) HttpStatusCode.NotModified;
                }
                else
                {
                    response.AddHeader("Last-Modified", fileContext.LastModifiedAtUtc.ToString("R"));
                    response.Body = fileContext.FileStream;
                }

                context.SendDownstream(new SendHttpResponse(msg.HttpRequest, response));
                return;
            }


            context.SendUpstream(message);
        }
 public void HandleDownstream(IPipelineHandlerContext context, IPipelineMessage message)
 {
     Assert.Equal(_index, CurrentIndex);
     CurrentIndex--;
     context.SendDownstream(message);
 }
Esempio n. 50
0
 private void OnReConnect(object state)
 {
     _upstreamContext.SendDownstream(new Connect(_endPoint));
     _timer.Change(Timeout.Infinite, Timeout.Infinite);
 }