예제 #1
0
        private void HandleHeader(IPipelineHandlerContext context, IPipelineMessage message, ReceivedHeader headerMsg)
        {
            _packetType = _mapper.GetPacketType(_header.ContentId);
            if (_packetType == null)
            {
                // not supported, let the rest of the pipeline
                // handle the packet.
                context.SendUpstream(message);
            }
            else
            {
                _header = headerMsg.Header;
                var buffer = _bufferPool.PopSlice();
                if (_header.ContentLength > buffer.Capacity)
                {
                    throw new InvalidOperationException(
                              string.Format(
                                  "Buffer ({0} bytes) is less than the packet content ({1} bytes). Sorry, that's not possible in the current version.",
                                  buffer.Capacity, _header.ContentLength));
                }

                _bytesLeft = _header.ContentLength;
                _stream    = new BufferPoolStream(_bufferPool, buffer);
            }
        }
예제 #2
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);
        }
예제 #3
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));
        }
        /// <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 virtual void HandleDownstream(IPipelineHandlerContext context, IPipelineMessage message)
        {
            var sendBuffer = message as SendBuffer;

            if (sendBuffer != null)
            {
                _context.Send(new BufferSlice(sendBuffer.Buffer, sendBuffer.Offset, sendBuffer.Count), sendBuffer.Count);
                return;
            }

            var sendSlice = message as SendSlice;

            if (sendSlice != null)
            {
                _context.Send(sendSlice.Slice, sendSlice.Length);
                return;
            }

            var send = message as SendStream;

            if (send != null)
            {
                _context.Send(send.Stream);
                return;
            }

            if (message is Disconnect)
            {
                _context.Close();
                return;
            }

            throw new InvalidOperationException("Unsupported pipeline message: " + message);
        }
예제 #6
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);
        }
예제 #7
0
        /// <summary>
        /// Handle an message
        /// </summary>
        /// <param name="context">Context unique for this handler instance</param>
        /// <param name="message">Message to process</param>
        void IUpstreamHandler.HandleUpstream(IPipelineHandlerContext context, IPipelineMessage message)
        {
            if (message is Connected)
            {
                IsConnected = true;
            }
            if (message is Disconnected)
            {
                OnDisconnect();
            }
            if (message is Authenticated)
            {
                IsAuthenticated = true;
                _pipeline.SendDownstream(
                    new SendCommandMessage(new SubscribeOnEvents(EventSubscriptionType.Plain, _eventCollection)));
            }
            if (message is CommandReply)
            {
                var reply = (CommandReply)message;
                _waitingObjects.Trigger(reply.OriginalCommand, reply);

                if (reply.OriginalCommand is SubscribeOnEvents)
                {
                    Initialized(this, EventArgs.Empty);
                }
            }
            if (message is EventRecieved)
            {
                var msg = (EventRecieved)message;
                EventReceived(this, new EventRecievedEventArgs(msg.FreeSwitchEvent));
            }
        }
        /// <summary>
        /// Handle an message
        /// </summary>
        /// <param name="context">Context unique for this handler instance</param>
        /// <param name="message">Message to process</param>
        void IUpstreamHandler.HandleUpstream(IPipelineHandlerContext context, IPipelineMessage message)
        {
            if (message is Connected)
                IsConnected = true;
            if (message is Disconnected)
            {
                OnDisconnect();
            }
            if (message is Authenticated)
            {
                IsAuthenticated = true;
                _pipeline.SendDownstream(
                    new SendCommandMessage(new SubscribeOnEvents(EventSubscriptionType.Plain, _eventCollection)));
            }
            if (message is CommandReply)
            {
                var reply = (CommandReply) message;
                _waitingObjects.Trigger(reply.OriginalCommand, reply);

                if (reply.OriginalCommand is SubscribeOnEvents)
                {
                    Initialized(this, EventArgs.Empty);                    
                }
            }
            if (message is EventRecieved)
            {
                var msg = (EventRecieved) message;
                EventReceived(this, new EventRecievedEventArgs(msg.FreeSwitchEvent));
            }
        }
예제 #9
0
        public OSHttpRequest(IPipelineHandlerContext context, IRequest req)
        {
            _httpContext = context;
            _httpRequest = req;

            _queryString = new NameValueCollection();
            _query       = new Hashtable();
            try
            {
                foreach (var item in req.QueryString)
                {
                    try
                    {
                        _queryString.Add(item.Name, item.Value);
                        _query[item.Name] = item.Value;
                    }
                    catch (InvalidCastException)
                    {
                        MainConsole.Instance.DebugFormat("[OSHttpRequest]: error parsing {0} query item, skipping it", item.Name);
                        continue;
                    }
                }
            }
            catch (Exception)
            {
                MainConsole.Instance.ErrorFormat("[OSHttpRequest]: Error parsing querystring");
            }

//            Form = new Hashtable();
//            foreach (HttpInputItem item in req.Form)
//            {
//                MainConsole.Instance.DebugFormat("[OSHttpRequest]: Got form item {0}={1}", item.Name, item.Value);
//                Form.Add(item.Name, item.Value);
//            }
        }
        /// <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>
        /// 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 virtual void HandleDownstream(IPipelineHandlerContext context, IPipelineMessage message)
        {
            var sendBuffer = message as SendBuffer;
            if (sendBuffer != null)
            {
                _context.Send(new BufferSlice(sendBuffer.Buffer, sendBuffer.Offset, sendBuffer.Count), sendBuffer.Count);
                return;
            }

            var sendSlice = message as SendSlice;
            if (sendSlice != null)
            {
                _context.Send(sendSlice.Slice, sendSlice.Length);
                return;
            }

            var send = message as SendStream;
            if (send != null)
            {
                _context.Send(send.Stream);
                return;
            }

            if (message is Disconnect)
            {
                _context.Close();
                return;
            }

            throw new InvalidOperationException("Unsupported pipeline message: " + 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 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));
        }
예제 #13
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));
        }
예제 #14
0
        private void HandleBackgroundCompletion(IPipelineHandlerContext context, EventRecieved message)
        {
            var msg = message.FreeSwitchEvent as BackgroundJob;

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

            BgApiCmd command;

            lock (_pending)
            {
                command = _pending.FirstOrDefault(x => x.Id == msg.JobUid);
                if (command == null)
                {
                    throw new InvalidOperationException("Got a command reply but no pending background job: " + msg);
                }

                _pending.Remove(command);
            }


            context.SendUpstream(new CommandReply(command.Inner, msg.CommandResult.StartsWith("+"), msg.CommandResult));
        }
예제 #15
0
        public OSHttpRequest(IPipelineHandlerContext context, IRequest req)
        {
            _httpContext = context;
            _httpRequest = req;

            _queryString = new NameValueCollection();
            _query = new Hashtable();
            try
            {
                foreach (var item in req.QueryString)
                {
                    try
                    {
                        _queryString.Add(item.Name, item.Value);
                        _query[item.Name] = item.Value;
                    }
                    catch (InvalidCastException)
                    {
                        MainConsole.Instance.DebugFormat("[OSHttpRequest]: error parsing {0} query item, skipping it", item.Name);
                        continue;
                    }
                }
            }
            catch (Exception)
            {
                MainConsole.Instance.ErrorFormat("[OSHttpRequest]: Error parsing querystring");
            }

//            Form = new Hashtable();
//            foreach (HttpInputItem item in req.Form)
//            {
//                MainConsole.Instance.DebugFormat("[OSHttpRequest]: Got form item {0}={1}", item.Name, item.Value);
//                Form.Add(item.Name, item.Value);
//            }
        }
예제 #16
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());
            }
        }
예제 #17
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));
        }
예제 #18
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);
        }
예제 #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 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 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;
            }
        }
예제 #21
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 msg = message as Received;
            if (msg == null)
            {
                context.SendUpstream(message);
                return;
            }

            var bytesToCopy = Math.Min(msg.BufferReader.Count, _bytesLeft);
            msg.BufferReader.Read(_header, _position, bytesToCopy);
            _position += bytesToCopy;
            _bytesLeft -= bytesToCopy;

            if (_bytesLeft > 0)
            {
                return;
            }

            var header = new SimpleHeader
                {
                    Version = _header[0],
                    Length = BitConverter.ToInt32(_header, 1)
                };

            _bytesLeft = 5;
            _position = 0;
            context.SendUpstream(new ReceivedHeader(header));

            if (msg.BufferReader.Position < msg.BufferReader.Count)
                context.SendUpstream(msg);
        }
예제 #22
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 Received;
            if (msg == null)
            {
                context.SendUpstream(message);
                return;
            }

            // byte + byte + int
            if (msg.BufferSlice.RemainingLength < 6)
            {
                return;
            }

            var header = new SimpleHeader
            {
                Version = msg.BufferSlice.Buffer[msg.BufferSlice.Position++],
                ContentId = msg.BufferSlice.Buffer[msg.BufferSlice.Position++],
                ContentLength = BitConverter.ToInt32(msg.BufferSlice.Buffer, msg.BufferSlice.Position)
            };
            msg.BufferSlice.Position += 4;
            context.SendUpstream(new ReceivedHeader(header));

            if (msg.BufferSlice.RemainingLength > 0)
                context.SendUpstream(msg);            
        }
예제 #23
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 Received;

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

            // byte + byte + int
            if (msg.BufferSlice.RemainingLength < 6)
            {
                return;
            }

            var header = new SimpleHeader
            {
                Version       = msg.BufferSlice.Buffer[msg.BufferSlice.Position++],
                ContentId     = msg.BufferSlice.Buffer[msg.BufferSlice.Position++],
                ContentLength = BitConverter.ToInt32(msg.BufferSlice.Buffer, msg.BufferSlice.Position)
            };

            msg.BufferSlice.Position += 4;
            context.SendUpstream(new ReceivedHeader(header));

            if (msg.BufferSlice.RemainingLength > 0)
            {
                context.SendUpstream(msg);
            }
        }
        /// <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));
        }
        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);
        }
예제 #26
0
        public void HandleUpstream(IPipelineHandlerContext ctx, IPipelineMessage message)
        {
            if (message is Connected)
            {
                _context = new DecoderContext {
                    ParserMethod = ParseBeforeHeader
                };
            }
            else if (message is Closed)
            {
                _context = null;
            }
            if (!(message is Received))
            {
                ctx.SendUpstream(message);
                return;
            }


            var evt    = (Received)message;
            var buffer = evt.BufferSlice;

            _logger.Trace("Pos: " + buffer.Position);
            _context.Reader.Assign(buffer);


            try
            {
                var canrun = true;
                while (canrun)
                {
                    _logger.Trace("Parsing using " + _context.ParserMethod.Method.Name);
                    canrun = _context.ParserMethod();
                }
            }
            catch (Exception err)
            {
                _logger.Error("Failed to parse message.", err);
                ctx.SendUpstream(new PipelineFailure(err));
                return;
            }

            if (!_context.IsComplete)
            {
                //_leftOvers = Encoding.UTF8.GetString(buffer.Buffer, buffer.Offset, buffer.RemainingLength);
                return; // Need more data from the channel
            }

            _context.ParserMethod = ParseBeforeHeader;
            _logger.Debug("Got message " + _context.Message.Headers["Content-Type"]);
            if (string.IsNullOrEmpty(_context.Message.Headers["Content-Type"]))
            {
                _logger.Warning("Malformed message\r\n" +
                                Encoding.ASCII.GetString(buffer.Buffer, buffer.StartOffset, buffer.Count));
                Debugger.Break();
            }

            ctx.SendUpstream(new ReceivedMessage(_context.Message));
            _context.Message = new Message();
        }
예제 #27
0
 public void Dispose()
 {
     _httpResponse.Body = null;
     _httpResponse      = null;
     _httpRequest.Body  = null;
     _httpRequest       = null;
     _httpContext       = null;
 }
예제 #28
0
 public void Dispose()
 {
     _query.Clear();
     _queryString.Clear();
     _remoteIPEndPoint = null;
     _httpRequest.Body = null;
     _httpRequest      = null;
     _httpContext      = null;
 }
예제 #29
0
        public OSHttpResponse(IPipelineHandlerContext context, IRequest request, IResponse response)
        {
            _httpContext = context;
            _httpRequest = request;
            _httpResponse = response;

            _httpResponse.AddHeader("remote_addr", MainServer.Instance.HostName);
            _httpResponse.AddHeader("remote_port", MainServer.Instance.Port.ToString());
        }
 /// <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 Received;
     if (msg == null)
     {
         context.SendUpstream(message);
         return;
     }
 }
예제 #31
0
        public OSHttpResponse(IPipelineHandlerContext context, IRequest request, IResponse response)
        {
            _httpContext  = context;
            _httpRequest  = request;
            _httpResponse = response;

            _httpResponse.AddHeader("remote_addr", MainServer.Instance.HostName);
            _httpResponse.AddHeader("remote_port", MainServer.Instance.Port.ToString());
        }
 public PollServiceHttpRequest(PollServiceEventArgs pPollServiceArgs, IPipelineHandlerContext pHttpContext,
                               IRequest pRequest)
 {
     PollServiceArgs = pPollServiceArgs;
     HttpContext = pHttpContext;
     Request = pRequest;
     RequestTime = Environment.TickCount;
     RequestID = UUID.Random();
 }
 public PollServiceHttpRequest(PollServiceEventArgs pPollServiceArgs, IPipelineHandlerContext pHttpContext,
                               IRequest pRequest)
 {
     PollServiceArgs = pPollServiceArgs;
     HttpContext     = pHttpContext;
     Request         = pRequest;
     RequestTime     = Environment.TickCount;
     RequestID       = UUID.Random();
 }
예제 #34
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 PipelineFailure;

            if (msg != null)
            {
                throw new TargetInvocationException("Pipeline failed", msg.Exception);
            }
        }
        public void HandleUpstream(IPipelineHandlerContext ctx, IPipelineMessage message)
        {
            if (message is Connected)
            {
                _context = new DecoderContext {ParserMethod = ParseBeforeHeader};
            }
            else if (message is Closed)
            {
                _context = null;
            }
            if (!(message is Received))
            {
                ctx.SendUpstream(message);
                return;
            }


            var evt = (Received) message;
            var buffer = evt.BufferReader;
            _logger.Trace("Pos: " + buffer.Position);
            _context.Reader.Assign(buffer);


            try
            {
                var canrun = true;
                while (canrun)
                {
                    _logger.Trace("Parsing using " + _context.ParserMethod.Method.Name);
                    canrun = _context.ParserMethod();
                }
            }
            catch (Exception err)
            {
                _logger.Error("Failed to parse message.", err);
                ctx.SendUpstream(new PipelineFailure(err));
                return;
            }

            if (!_context.IsComplete)
            {
                //_leftOvers = Encoding.UTF8.GetString(buffer.Buffer, buffer.Offset, buffer.RemainingLength);
                return; // Need more data from the channel
            }

            _context.ParserMethod = ParseBeforeHeader;
            _logger.Debug("Got message " + _context.Message.Headers["Content-Type"]);
            if (string.IsNullOrEmpty(_context.Message.Headers["Content-Type"]))
            {
                _logger.Warning("Malformed message\r\n" +
                                Encoding.ASCII.GetString(buffer.Buffer, buffer.StartOffset, buffer.Count));
                Debugger.Break();
            }

            ctx.SendUpstream(new ReceivedMessage(_context.Message));
            _context.Message = new Message();
        }
예제 #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)
        {
            if (message is EventRecieved)
            {
                HandleBackgroundCompletion(context, (EventRecieved)message);
                return;
            }
            if (!(message is ReceivedMessage))
            {
                context.SendUpstream(message);
                return;
            }


            var msg  = (ReceivedMessage)message;
            var type = msg.Message.Headers["Content-Type"];

            if (type == null || type != "command/reply")
            {
                context.SendUpstream(message);
                return;
            }

            SendCommandMessage nextCommand = null;
            ICommand           curMsg;

            lock (_outbound)
            {
                if (_current == null)
                {
                    throw new InvalidOperationException("No active command set.");
                }
                _logger.Trace("Got reply for " + _current);
                curMsg      = _current;
                nextCommand = _outbound.Count > 0 ? _outbound.Dequeue() : null;
                _current    = null;
            }

            if (curMsg is BgApiCmd)
            {
                HandleBgApi(context, msg.Message, (BgApiCmd)curMsg);
            }
            else
            {
                var result = msg.Message.Headers["Reply-Text"].StartsWith("+");
                var body   = msg.Message.Headers["Reply-Text"];
                var reply  = new CommandReply(curMsg, result, body);
                _logger.Debug("Sending reply " + body);
                context.SendUpstream(reply);
            }

            if (nextCommand != null)
            {
                _logger.Trace("Sending next command down: " + nextCommand.Command);
                SendCommand(context, nextCommand);
            }
        }
예제 #37
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 Received;

            if (msg == null)
            {
                context.SendUpstream(message);
                return;
            }
        }
        /// <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)
        {
            if (message is EventRecieved)
            {
                HandleBackgroundCompletion(context, (EventRecieved) message);
                return;
            }
            if (!(message is ReceivedMessage))
            {
                context.SendUpstream(message);
                return;
            }


            var msg = (ReceivedMessage) message;
            var type = msg.Message.Headers["Content-Type"];
            if (type == null || type != "command/reply")
            {
                context.SendUpstream(message);
                return;
            }

            SendCommandMessage nextCommand = null;
            ICommand curMsg;
            lock (_outbound)
            {
                if (_current == null)
                {
                    throw new InvalidOperationException("No active command set.");
                }
                _logger.Trace("Got reply for " + _current);
                curMsg = _current;
                nextCommand = _outbound.Count > 0 ? _outbound.Dequeue() : null;
                _current = null;
            }

            if (curMsg is BgApiCmd)
            {
                HandleBgApi(context, msg.Message, (BgApiCmd) curMsg);
            }
            else
            {
                var result = msg.Message.Headers["Reply-Text"].StartsWith("+");
                var body = msg.Message.Headers["Reply-Text"];
                var reply = new CommandReply(curMsg, result, body);
                _logger.Debug("Sending reply " + body);
                context.SendUpstream(reply);
            }

            if (nextCommand != null)
            {
                _logger.Trace("Sending next command down: " + nextCommand.Command);
                SendCommand(context, nextCommand);
            }
        }
        /// <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);
        }
예제 #40
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);
        }
        public void Read(IPipelineHandlerContext context, ref PacketReader reader)
        {
            ushort header = reader.ReadUInt16();

            PlatformRacing3Server.BytePacketManager.HandleIncomingData(header, this.Session, context, ref reader);

            if (reader.Remaining > 0)
            {
                reader.Skip(reader.Remaining); //Skip extra bytes and head to the next packet
            }
        }
예제 #42
0
        private void HandleBgApi(IPipelineHandlerContext context, Message response, BgApiCmd curMsg)
        {
            if (response.Headers["Reply-Text"][0] != '+')
            {
                context.SendUpstream(new CommandReply(curMsg.Inner, false, response.Headers["Reply-Text"]));
                return;
            }

            curMsg.Id = response.Headers["Job-UUID"];
            _pending.AddLast(curMsg);
        }
예제 #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)
 {
     try
     {
         _listener.ScopeStarted(_id);
     }
     catch (Exception)
     {
         _listener.ScopeEnded(_id);
         throw;
     }
 }
예제 #44
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)
 {
     try
     {
         _listener.ScopeStarted(_id);
     }
     catch (Exception)
     {
         _listener.ScopeEnded(_id);
         throw;
     }
 }
        /// <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));
        }
예제 #46
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 Received;
            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());
            }

            context.SendUpstream(message);
        }
예제 #47
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));
        }
예제 #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 Received;

            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());
            }

            context.SendUpstream(message);
        }
예제 #49
0
        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);
        }
예제 #50
0
        /// <summary>
        /// Handles an upstream message in a request pipeline.
        /// </summary>
        /// <param name="context">Context.</param>
        /// <param name="message">Message.</param>
        void IUpstreamHandler.HandleUpstream(IPipelineHandlerContext context, IPipelineMessage message)
        {
            var msg = message as Received;

            // if we don't know what we got, then send it
            // up stream
            if (msg == null)
            {
                context.SendUpstream(message);
                return;
            }


        }
예제 #51
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));
        }
예제 #52
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);
        }
예제 #53
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 Received;
            if (msg != null)
            {
                var bytes =
                    Encoding.ASCII.GetBytes("\r\nFrom 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.SendUpstream(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);
        }
예제 #55
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)
 {
     if (message is Connect)
     {
         _endPoint = (IPEndPoint) ((Connect) message).RemoteEndPoint;
         if (_timer != null)
         {
             _timer.Dispose();
             _timer = null;
         }
         _forcedDisconnect = false;
     }
     if (message is Disconnect)
     {
         _forcedDisconnect = true;
     }
 }
예제 #57
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 Received;
            if (msg != null)
            {
                var stream = new MemoryStream();
                msg.BufferReader.CopyTo(stream, msg.BufferReader.Count);
                msg.BufferReader.Position = 0;

                var reader = new StreamReader(stream);
                var str = reader.ReadToEnd();
                var sb = GetAlphaNumeric(str);
                _logger.Trace(sb.ToString());
            }

            context.SendUpstream(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 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());
        }
예제 #59
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)
        {
            if (message is Closed)
            {
                _bodyBytesLeft = 0;
                _headerParser.Reset();
            }
            else if (message is Received)
            {
                var msg = (Received) message;

                // complete the body
                if (_bodyBytesLeft > 0)
                {
                    var bytesToSend = Math.Min(_bodyBytesLeft, msg.BufferReader.RemainingLength);
                    _bodyBytesLeft -= bytesToSend;
                    context.SendUpstream(message);
                    return;
                }

                _headerParser.Parse(msg.BufferReader);
                if (_headerCompleted)
                {
                    var request = (IRequest) _message;

                    var ourRequest = _message as HttpRequest;
                    if (ourRequest != null)
                        ourRequest.RemoteEndPoint = msg.RemoteEndPoint as IPEndPoint;
                    request.AddHeader("RemoteAddress", msg.RemoteEndPoint.ToString());

                    var receivedHttpRequest = new ReceivedHttpRequest(request);

                    _headerParser.Reset();
                    _headerCompleted = false;

                    context.SendUpstream(receivedHttpRequest);
                    if (msg.BufferReader.RemainingLength > 0)
                        context.SendUpstream(msg);
                }

                return;
            }

            context.SendUpstream(message);
        }
예제 #60
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);
        }