Exemplo n.º 1
0
        private void OnHandleRequestIOCPThread(IHttpClientContext context, IHttpRequest request)
        {
            OSHttpRequest req = new OSHttpRequest(context, request);

            WebSocketRequestDelegate dWebSocketRequestDelegate = null;

            lock (m_WebSocketHandlers)
            {
                if (m_WebSocketHandlers.ContainsKey(req.RawUrl))
                {
                    dWebSocketRequestDelegate = m_WebSocketHandlers[req.RawUrl];
                }
            }
            if (dWebSocketRequestDelegate != null)
            {
                dWebSocketRequestDelegate(req.Url.AbsolutePath, new WebSocketHttpServerHandler(req, context, 8192));
                return;
            }

            if (req.ContentType != null && req.ContentType.ToLowerInvariant() == "application/x-www-form-urlencoded")
            {
                IHttpClientContext  postcontext = (IHttpClientContext)context;
                FormDecoderProvider provider    = new FormDecoderProvider();
                provider.Add(new UrlDecoder());
            }
            OSHttpResponse resp = new OSHttpResponse(new HttpResponse(context, request), context);

            HandleRequest(req, resp);
        }
Exemplo n.º 2
0
 public PollServiceHttpRequest(PollServiceEventArgs pPollServiceArgs, IHttpClientContext pHttpContext, IHttpRequest pRequest)
 {
     PollServiceArgs = pPollServiceArgs;
     HttpContext = pHttpContext;
     Request = pRequest;
     RequestTime = System.Environment.TickCount;
 }
 public ProfileServiceRepository(IHttpClientContext httpClient,
                                 ICacheManager cacheManager
                                 )
 {
     _httpClient   = httpClient;
     _cacheManager = cacheManager;
 }
Exemplo n.º 4
0
        public static async Task <HttpRequestMessage> PrepareRequestWithContextAsync(IHttpClientContext httpClientContext, HttpMethod method, string ServicePartUrl)
        {
            try
            {
                HttpRequestMessage httpRequest = null;
                // préparation REQ
                httpRequest = PrepareRequest(method, httpClientContext.RootUrl, ServicePartUrl);

                //gestion du token
                string tokenGenerated = await GenerateTokenAsync(httpClientContext);

                if (!string.IsNullOrEmpty(tokenGenerated))
                {
                    if (httpClientContext.TokenMode == HttpClientTokenModeEnum.BASIC)
                    {
                        httpRequest.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("basic", tokenGenerated);
                    }
                    else
                    {
                        httpRequest.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("bearer", tokenGenerated);
                    }
                }



                return(httpRequest);
            }
            catch (Exception ex)
            {
                throw new Exception("PrepareRequestWithContext " + ex.Message, ex);
            }
        }
Exemplo n.º 5
0
        public OSHttpRequest(IHttpRequest req)
        {
            m_request = req;
            m_context = req.Context;

            if (null != req.Headers["content-encoding"])
            {
                try
                {
                    m_contentEncoding = Encoding.GetEncoding(m_request.Headers["content-encoding"]);
                }
                catch
                {
                    // ignore
                }
            }

            if (null != req.Headers["content-type"])
            {
                m_contentType = m_request.Headers["content-type"];
            }
            if (null != req.Headers["user-agent"])
            {
                m_userAgent = req.Headers["user-agent"];
            }

//            Form = new Hashtable();
//            foreach (HttpInputItem item in req.Form)
//            {
//                _log.DebugFormat("[OSHttpRequest]: Got form item {0}={1}", item.Name, item.Value);
//                Form.Add(item.Name, item.Value);
//            }
        }
Exemplo n.º 6
0
        private void UploadBakedTextureDataHandler(Capability cap, IHttpClientContext context, IHttpRequest request, IHttpResponse response)
        {
            byte[] textureData = request.GetBody();
            UUID   assetID     = UUID.Zero;

            m_log.Debug("Received baked texture upload from " + cap.OwnerID + " (" + textureData.Length + " bytes)");

            if (textureData != null && textureData.Length > 0)
            {
                if (!m_assetClient.StoreAsset("image/x-j2c", true, true, textureData, cap.OwnerID, out assetID))
                {
                    m_log.WarnFormat("Failed to store uploaded texture bake ({0} bytes)", textureData.Length);
                }
            }
            else
            {
                m_log.Warn("Texture bake upload contained no data");
            }

            UploadBakedTextureMessage reply      = new UploadBakedTextureMessage();
            UploaderRequestComplete   replyBlock = new UploaderRequestComplete();

            replyBlock.AssetID = assetID;
            reply.Request      = replyBlock;

            LLUtil.SendLLSDXMLResponse(response, reply.Serialize());
        }
Exemplo n.º 7
0
        void CopyHandler(IHttpClientContext context, IHttpRequest request, IHttpResponse response)
        {
            string username;
            if (server.AuthenticateRequest(request, response, out username))
            {
                //parse Destination from header
                //this is required for the copy command
                string[] destinations = request.Headers.GetValues("destination");
                if (destinations == null)
                {
                    response.Status = HttpStatusCode.BadRequest;
                    return;
                }
                string destination = destinations[0];

                //If the client includes a Depth header with an illegal value, the server should return 400 Bad Request.
                //this means that if the resource is a collection, then depth should be infinity
                //and if resource is not a collection, then the depth should be 0
                //if the depth doesn't exist, then proceed normally
                DepthHeader depth = DepthHeader.Infinity; //this is the standard default
                if (request.Headers["depth"] != null)
                {
                    depth = Depth.ParseDepth(request);
                }

                //parse Overwrite header
                //possible values: 'T' or 'F' (true or false)
                //otherwise return 400 Bad Request
                //if value is F and destination already exists, fail with response 412 Precondition Failed
                //default for this value is T
                bool overwrite = true;
                string[] overwrites = request.Headers.GetValues("overwrite");
                if (overwrites != null)
                {
                    if (overwrites[0].ToLower() == "t")
                        overwrite = true;
                    else if (overwrites[0].ToLower() == "f")
                        overwrite = false;
                    else
                    {
                        response.Status = HttpStatusCode.BadRequest;
                        return;
                    }
                }

                //If header might contain lock tokens, we need to pass them forward too
                string[] ifHeaders = request.Headers.GetValues("if");

                Dictionary<String, HttpStatusCode> multiStatusValues = null;
                HttpStatusCode status = server.OnCopyConnector(username, request.Uri, destination, depth, overwrite, ifHeaders, out multiStatusValues);
                response.Status = status;
                if (status == (HttpStatusCode)207 && multiStatusValues != null) //multiple status
                {
                    byte[] bytes = XmlResponse.WriteMultiStatusResponseBody(multiStatusValues);
                    response.ContentLength = bytes.Length;
                    //Console.WriteLine(Encoding.UTF8.GetString(bytes));
                    response.Body.Write(bytes, 0, bytes.Length);
                }
            }
        }
        public void Dispose()
        {
            if (_initialMsgTimeout > 0)
            {
                _receiveDone.Set();
                _initialMsgTimeout = 0;
            }
            if (_networkContext != null && _networkContext.Stream != null)
            {
                if (_networkContext.Stream.CanWrite)
                {
                    _networkContext.Stream.Flush();
                }
                _networkContext.Stream.Close();
                _networkContext.Stream.Dispose();
                _networkContext.Stream = null;
            }

            if (_request != null && _request.InputStream != null)
            {
                _request.InputStream.Close();
                _request.InputStream.Dispose();
                _request = null;
            }

            if (_clientContext != null)
            {
                _clientContext.Close();
                _clientContext = null;
            }
        }
        public HttpClientContextTest()
        {
            _listenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            _listenSocket.Bind(new IPEndPoint(IPAddress.Any, 14862));
            _listenSocket.Listen(0);
            IAsyncResult res = _listenSocket.BeginAccept(null, null);

            _client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            _client.Connect("localhost", 14862);
            _remoteSocket = _listenSocket.EndAccept(res);

            _disconnectEvent.Reset();
            _event.Reset();
            _counter = 0;

            var requestParserFactory = new RequestParserFactory();

            _factory = new HttpContextFactory(NullLogWriter.Instance, 8192, requestParserFactory);
            _factory.RequestReceived += OnRequest;
            _context = _factory.CreateContext(_client);
            _context.Disconnected += OnDisconnect;
            //_context = new HttpClientContext(false, new IPEndPoint(IPAddress.Loopback, 21111), OnRequest, OnDisconnect, _client.GetStream(), ConsoleLogWriter.Instance);

            _request      = null;
            _disconnected = false;
        }
Exemplo n.º 10
0
        private void ChildAvatarUpdateHandler(IHttpClientContext context, IHttpRequest request, IHttpResponse response)
        {
            OSDMap requestMap = null;

            try { requestMap = OSDParser.Deserialize(request.Body) as OSDMap; }
            catch { }

            if (requestMap != null)
            {
                IScenePresence child;
                if (m_scene.TryGetPresence(requestMap["agent_id"].AsUUID(), out child) && child.IsChildPresence)
                {
                    child.RelativePosition = requestMap["position"].AsVector3();
                    child.RelativeRotation = requestMap["rotation"].AsQuaternion();

                    if (child is LLAgent)
                    {
                        LLAgent childAgent = (LLAgent)child;

                        childAgent.CameraPosition = requestMap["camera_center"].AsVector3();
                        childAgent.CameraAtAxis   = requestMap["camera_at"].AsVector3();
                        childAgent.CameraLeftAxis = requestMap["camera_left"].AsVector3();
                        childAgent.CameraUpAxis   = requestMap["camera_up"].AsVector3();
                        childAgent.DrawDistance   = (float)requestMap["draw_distance"].AsReal();
                    }
                }
            }
        }
        public void Dispose()
        {
            if (_networkContext != null && _networkContext.Stream != null)
            {
                if (_networkContext.Stream.CanWrite)
                {
                    _networkContext.Stream.Flush();
                }
                _networkContext.Stream.Close();
                _networkContext.Stream.Dispose();
                _networkContext.Stream = null;
            }

            if (_request != null && _request.InputStream != null)
            {
                _request.InputStream.Close();
                _request.InputStream.Dispose();
                _request = null;
            }

            if (_clientContext != null)
            {
                _clientContext.Close();
                _clientContext = null;
            }
        }
Exemplo n.º 12
0
        private void NewFileAgentInventoryUploadHandler(NewFileAgentInventoryMessage message, Capability cap,
                                                        IHttpClientContext context, IHttpRequest request, IHttpResponse response)
        {
            byte[] assetData = request.GetBody();
            UUID   assetID   = UUID.Zero;
            UUID   itemID    = UUID.Zero;

            m_log.Debug("Received inventory asset upload from " + cap.OwnerID + " (" + assetData.Length + " bytes)");

            if (assetData != null && assetData.Length > 0)
            {
                string contentType = LLUtil.LLAssetTypeToContentType((int)message.AssetType);

                // Create the asset
                if (m_assetClient.StoreAsset(contentType, false, false, assetData, cap.OwnerID, out assetID))
                {
                    // Create the inventory item
                    LLInventoryItem item = new LLInventoryItem();
                    item.AssetID      = assetID;
                    item.ContentType  = contentType;
                    item.CreationDate = DateTime.UtcNow;
                    item.CreatorID    = cap.OwnerID;
                    item.Description  = message.Description;
                    item.ID           = UUID.Random();
                    item.Name         = message.Name;
                    item.OwnerID      = cap.OwnerID;
                    item.ParentID     = message.FolderID;
                    item.Permissions  = (m_permissions != null) ? m_permissions.GetDefaultPermissions() : Permissions.FullPermissions;
                    item.SalePrice    = 10;
                    item.SaleType     = SaleType.Not;

                    if (m_inventoryClient.TryCreateItem(cap.OwnerID, item))
                    {
                        itemID = item.ID;
                    }
                    else
                    {
                        m_log.Warn("Failed to create inventory item for uploaded asset " + assetID);
                    }
                }
                else
                {
                    m_log.WarnFormat("Failed to store uploaded inventory asset ({0} bytes)", assetData.Length);
                }
            }
            else
            {
                m_log.Warn("Inventory asset upload contained no data");
            }

            // Build the response message
            OSDMap reply = new OSDMap
            {
                { "state", OSD.FromString("complete") },
                { "new_asset", OSD.FromUUID(assetID) },
                { "new_inventory_item", OSD.FromUUID(itemID) }
            };

            LLUtil.SendLLSDXMLResponse(response, reply);
        }
Exemplo n.º 13
0
        private void RegionOnlineHandler(IHttpClientContext context, IHttpRequest request, IHttpResponse response)
        {
            OSDMap requestMap = null;

            try { requestMap = OSDParser.Deserialize(request.Body) as OSDMap; }
            catch { }

            if (requestMap != null)
            {
                Vector3d minPosition = new Vector3d(requestMap["region_x"].AsReal(), requestMap["region_y"].AsReal(), 0.0d);
                Vector3d maxPosition = new Vector3d(minPosition.X + 256.0d, minPosition.Y + 256.0d, 4096.0d);

                SceneInfo scene = new SceneInfo
                {
                    ID                   = requestMap["region_id"].AsUUID(),
                    Name                 = requestMap["region_name"].AsString(),
                    MinPosition          = minPosition,
                    MaxPosition          = maxPosition,
                    PublicSeedCapability = requestMap["public_region_seed_capability"].AsUri()
                };

                //m_log.Debug(m_scene.Name + " adding neighbor " + scene.Name);
                m_scene.AddNeighbor(scene);
            }
            else
            {
                m_log.Warn("Failed to parse region/online request");
            }
        }
Exemplo n.º 14
0
 /// <summary>
 /// Initializes a new instance of the <see cref="IHttpResponse"/> class.
 /// </summary>
 /// <param name="context">Client that send the <see cref="IHttpRequest"/>.</param>
 /// <param name="httpVersion">Version of HTTP protocol that the client uses.</param>
 /// <param name="connectionType">Type of HTTP connection used.</param>
 internal HttpResponse(IHttpClientContext context, string httpVersion, ConnectionType connectionType)
 {
     Status        = HttpStatusCode.OK;
     m_context     = context;
     m_httpVersion = httpVersion;
     m_Connetion   = connectionType;
 }
Exemplo n.º 15
0
        /// <summary>
        /// Routes an incoming HTTP capability request to an internal method or a remote resource
        /// </summary>
        /// <param name="context">HTTP context</param>
        /// <param name="request">HTTP request</param>
        /// <param name="response">HTTP response</param>
        public void RouteCapability(IHttpClientContext context, IHttpRequest request, IHttpResponse response)
        {
            UUID   capabilityID;
            string path = request.Uri.AbsolutePath.TrimEnd('/');

            if (UUID.TryParse(path.Substring(path.Length - 36), out capabilityID))
            {
                Capability         cap      = null;
                CapabilityCallback callback = null;

                m_capSyncRoot.EnterReadLock();
                try
                {
                    if (m_capabilities.TryGetValue(capabilityID, out cap))
                    {
                        if (cap.OneTimeResource != null)
                        {
                            callback = cap.OneTimeResource;
                        }
                        else
                        {
                            m_protectedResources.TryGetValue(cap.Resource, out callback);
                        }
                    }
                }
                finally { m_capSyncRoot.ExitReadLock(); }

                if (cap != null)
                {
                    if (callback != null)
                    {
                        RouteLocalCapability(cap, callback, context, request, response);

                        if (cap.OneTimeResource != null)
                        {
                            // This was a one time resource, destroy it
                            RemoveCapability(cap.ID);
                        }

                        return;
                    }
                    else if (cap.Resource.StartsWith("https://") || cap.Resource.StartsWith("http://"))
                    {
                        RouteRemoteCapability(cap, context, request, response);
                        return;
                    }
                    else
                    {
                        m_log.Warn("Capability " + cap.ID + " owned by " + cap.OwnerID + " maps to missing resource " + cap.ResourceDisplayName);
                    }
                }
            }

            // Return a 404
            m_log.Warn("Returning 404 for capability request to " + request.Uri);
            response.Status = System.Net.HttpStatusCode.NotFound;
            try { response.Send(); }
            catch (Exception ex) { m_log.ErrorFormat("Failed to send HTTP response for request to (missing) capability {0}: {1}", request.Uri, ex.Message); }
        }
 public PollServiceHttpRequest(PollServiceEventArgs pPollServiceArgs, IHttpClientContext pHttpContext, IHttpRequest pRequest)
 {
     PollServiceArgs = pPollServiceArgs;
     HttpContext = pHttpContext;
     Request = pRequest;
     RequestTime = System.Environment.TickCount;
     RequestID = UUID.Random();
 }
Exemplo n.º 17
0
 public ControllerModuleTest()
 {
     _controller = new TestController();
     _request = new HttpTestRequest {HttpVersion = "HTTP/1.1"};
 	_context = new HttpResponseContext();
 	_response = _request.CreateResponse(_context);
     _module = new ControllerModule();
 }
Exemplo n.º 18
0
        private void XmlRpcHandler(IHttpClientContext client, IHttpRequest request, IHttpResponse response)
        {
            XmlRpcRequest  rpcRequest  = null;
            XmlRpcResponse rpcResponse = null;

            try
            { rpcRequest = m_xmlrpcDeserializer.Deserialize(new StreamReader(request.Body)) as XmlRpcRequest; }
            catch (SystemException ex)
            { m_log.Warn("Failed to deserialize incoming XML-RPC request: " + ex.Message); }

            if (rpcRequest != null)
            {
                response.ContentType = "text/xml";
                response.Encoding    = Encoding.UTF8;
                response.Chunked     = false;

                XmlRpcCallback callback;
                if (m_xmlrpcCallbacks.TryGetValue(rpcRequest.MethodName, out callback))
                {
                    // TODO: Add IHttpClientContext.RemoteEndPoint
                    rpcRequest.Params.Add(null); //rpcRequest.Params.Add(client.RemoteEndPoint);
                    rpcRequest.Params.Add(request.Uri);

                    try
                    {
                        rpcResponse = callback(rpcRequest, request);

                        string responseString = XmlRpcResponseSerializer.Singleton.Serialize(rpcResponse);
                        byte[] buffer         = Encoding.UTF8.GetBytes(responseString);
                        // Set the content-length, otherwise the LL viewer freaks out
                        response.ContentLength = buffer.Length;
                        response.Body.Write(buffer, 0, buffer.Length);
                        response.Body.Flush();
                    }
                    catch (Exception ex)
                    {
                        m_log.ErrorFormat("XML-RPC method [{0}] threw exception: {1}", rpcRequest.MethodName, ex);

                        rpcResponse = new XmlRpcResponse();
                        rpcResponse.SetFault(INTERNAL_ERROR, String.Format("Requested method [{0}] threw exception: {1}", rpcRequest.MethodName, ex.Message));
                        XmlRpcResponseSerializer.Singleton.Serialize(new XmlTextWriter(response.Body, Encoding.UTF8), rpcResponse);
                    }
                }
                else
                {
                    m_log.WarnFormat("XML-RPC method [{0}] not found", rpcRequest.MethodName);

                    rpcResponse = new XmlRpcResponse();
                    rpcResponse.SetFault(METHOD_NOT_FOUND, String.Format("Requested method [{0}] not found", rpcRequest.MethodName));
                    XmlRpcResponseSerializer.Singleton.Serialize(new XmlTextWriter(response.Body, Encoding.UTF8), rpcResponse);
                }
            }
            else
            {
                m_log.Warn("Bad XML-RPC request");
                response.Status = HttpStatusCode.BadRequest;
            }
        }
Exemplo n.º 19
0
        public void Enqueue(IHttpClientContext context, IHttpRequest request)
        {
            QueueItem item = new QueueItem {
                Context = context, Request = request
            };

            lock (_queue)
                _queue.Enqueue(item);
        }
Exemplo n.º 20
0
        private void GetTextureHandler(Capability cap, IHttpClientContext context, IHttpRequest request, IHttpResponse response)
        {
            // TODO: Change this to a config option
            const string REDIRECT_URL = null;

            // Try to parse the texture ID from the request URL
            NameValueCollection query = HttpUtility.ParseQueryString(request.Uri.Query);
            string textureStr         = query.GetOne("texture_id");

            UUID textureID;

            if (!String.IsNullOrEmpty(textureStr) && UUID.TryParse(textureStr, out textureID))
            {
                Asset texture;

                if (!String.IsNullOrEmpty(REDIRECT_URL))
                {
                    // Only try to fetch locally cached textures. Misses are redirected
                    if (m_assetClient.TryGetCachedAsset(textureID, "image/x-j2c", out texture))
                    {
                        SendTexture(request, response, texture);
                    }
                    else
                    {
                        string textureUrl = REDIRECT_URL + textureID.ToString();
                        m_log.Debug("Redirecting texture request to " + textureUrl);
                        response.Redirect(textureUrl);
                    }
                }
                else
                {
                    // Fetch locally or remotely. Misses return a 404
                    if (m_assetClient.TryGetAsset(textureID, "image/x-j2c", out texture))
                    {
                        SendTexture(request, response, texture);
                    }
                    else
                    {
                        m_log.Warn("Texture " + textureID + " not found");

                        if (m_assetClient.TryGetCachedAsset(MISSING_IMAGE, "image/x-j2c", out texture))
                        {
                            SendTexture(request, response, texture);
                        }
                        else
                        {
                            m_log.Warn("Missing image texture " + MISSING_IMAGE + " not found, returning a 404");
                            response.Status = System.Net.HttpStatusCode.NotFound;
                        }
                    }
                }
            }
            else
            {
                m_log.Warn("Failed to parse a texture_id from GetTexture request: " + request.Uri);
            }
        }
        private void OnIncomingRequest(object source, RequestEventArgs args)
        {
            IHttpClientContext client  = (IHttpClientContext)source;
            IHttpRequest       request = args.Request;

            client.Respond("Hello world!");
            ++_currentThreadCount;
            _testEvent.Set();
        }
Exemplo n.º 22
0
		/// <summary>
		/// Initializes a new instance of the <see cref="IHttpResponse"/> class.
		/// </summary>
		/// <param name="context">Client that send the <see cref="IHttpRequest"/>.</param>
		/// <param name="httpVersion">Version of HTTP protocol that the client uses.</param>
		/// <param name="connectionType">Type of HTTP connection used.</param>
		internal HttpResponse(IHttpClientContext context, string httpVersion, ConnectionType connectionType)
		{
			Check.NotEmpty(httpVersion, "httpVersion");

			Status = HttpStatusCode.OK;
			_context = context;
			_httpVersion = httpVersion;
			Connection = connectionType;
		}
 public WebSocketHttpServerHandler(OSHttpRequest preq, IHttpClientContext pContext, int bufferlen)
     : base(preq.HttpMethod, preq.Url.OriginalString)
 {
     _request        = preq;
     _networkContext = pContext.GiveMeTheNetworkStreamIKnowWhatImDoing();
     _clientContext  = pContext;
     _bufferLength   = bufferlen;
     _buffer         = new byte[_bufferLength];
 }
Exemplo n.º 24
0
 void MkcolHandler(IHttpClientContext context, IHttpRequest request, IHttpResponse response)
 {
     string username;
     if (server.AuthenticateRequest(request, response, out username))
     {
         System.Net.HttpStatusCode status = server.CreateCollection(request.UriPath, username);
         response.Status = status;
     }
 }
Exemplo n.º 25
0
        /// <summary>
        /// Initializes a new instance of the <see cref="IHttpResponse"/> class.
        /// </summary>
        /// <param name="context">Client that send the <see cref="IHttpRequest"/>.</param>
        /// <param name="httpVersion">Version of HTTP protocol that the client uses.</param>
        /// <param name="connectionType">Type of HTTP connection used.</param>
        internal HttpResponse(IHttpClientContext context, string httpVersion, ConnectionType connectionType)
        {
            Check.NotEmpty(httpVersion, "httpVersion");

            Status       = HttpStatusCode.OK;
            _context     = context;
            _httpVersion = httpVersion;
            Connection   = connectionType;
        }
        private void OnRequest(object source, RequestEventArgs args)
        {
            IHttpClientContext client  = (IHttpClientContext)source;
            IHttpRequest       request = args.Request;

            ++_counter;
            _request = (IHttpRequest)request.Clone();
            _event.Set();
        }
Exemplo n.º 27
0
 public PollServiceHttpRequest(PollServiceEventArgs pPollServiceArgs, IHttpClientContext pHttpContext,
                               IHttpRequest pRequest)
 {
     PollServiceArgs = pPollServiceArgs;
     HttpContext = pHttpContext;
     Request = pRequest;
     RequestTime = Environment.TickCount;
     RequestID = UUID.Random();
 }
Exemplo n.º 28
0
 public ControllerModuleTest()
 {
     _controller = new TestController();
     _request    = new HttpTestRequest {
         HttpVersion = "HTTP/1.1"
     };
     _context  = new HttpResponseContext();
     _response = _request.CreateResponse(_context);
     _module   = new ControllerModule();
 }
Exemplo n.º 29
0
    private void OnRequest(object source, RequestEventArgs args)
    {
        IHttpClientContext context  = (IHttpClientContext)source;
        IHttpRequest       request  = args.Request;
        IHttpResponse      response = request.CreateResponse(context);

        response.Body        = new FileStream("Path\\to\\file.jpg");
        response.ContentType = "image\jpeg";
        response.Send();
    }
Exemplo n.º 30
0
        public ReverseProxyTest()
        {
            _request = new HttpTestRequest {HttpVersion = "HTTP/1.1"};
        	_stream = new MyStream();
            _context = new HttpResponseContext();
        	_response = _request.CreateResponse(_context);
            _module = new ReverseProxyModule("http://localhost/", "http://localhost:4210/");
			_server = new HttpServer();
            
        }
Exemplo n.º 31
0
        private void ProvisionVoiceAccountRequestHandler(Capability cap, IHttpClientContext context, IHttpRequest request, IHttpResponse response)
        {
            ProvisionVoiceAccountRequestMessage reply = new ProvisionVoiceAccountRequestMessage();

            reply.Username = String.Empty;
            reply.Password = String.Empty;

            // TODO: Implement this once we have Freeswitch support
            //LLUtil.SendLLSDXMLResponse(response, reply.Serialize());
        }
Exemplo n.º 32
0
        private void Default404Handler(IHttpClientContext client, IHttpRequest request, IHttpResponse response)
        {
            const string NOT_FOUND_RESPONSE = "<html><head><title>Page Not Found</title></head><body><h1>Page Not Found</h1></body></html>";

            m_log.Debug("Returning 404 for request to " + request.Uri);

            response.Status = HttpStatusCode.NotFound;
            byte[] buffer = System.Text.Encoding.ASCII.GetBytes(NOT_FOUND_RESPONSE);
            response.Body.Write(buffer, 0, buffer.Length);
        }
Exemplo n.º 33
0
 public ReverseProxyTest()
 {
     _request = new HttpTestRequest {
         HttpVersion = "HTTP/1.1"
     };
     _stream   = new MyStream();
     _context  = new HttpResponseContext();
     _response = _request.CreateResponse(_context);
     _module   = new ReverseProxyModule("http://localhost/", "http://localhost:4210/");
     _server   = new HttpServer();
 }
Exemplo n.º 34
0
        private void OnHttpListenerRequestReceived(object sender, RequestEventArgs e)
        {
            IHttpClientContext context = (IHttpClientContext)sender;

            lock (_serverData.SyncObj)
                if (!_serverData.IsActive)
                {
                    return;
                }
            HandleHTTPRequest_NoLock(context, e.Request);
        }
Exemplo n.º 35
0
 private void TextureStatsHandler(Capability cap, IHttpClientContext context, IHttpRequest request, IHttpResponse response)
 {
     try
     {
         OSD osd = OSDParser.Deserialize(request.Body);
         m_log.Info("Received a TextureStats message: " + osd.ToString());
     }
     catch (Exception)
     {
         m_log.Warn("Failed to decode TextureStats message");
     }
 }
Exemplo n.º 36
0
 private void TextureStatsHandler(Capability cap, IHttpClientContext context, IHttpRequest request, IHttpResponse response)
 {
     try
     {
         OSD osd = OSDParser.Deserialize(request.Body);
         m_log.Info("Received a TextureStats message: " + osd.ToString());
     }
     catch (Exception)
     {
         m_log.Warn("Failed to decode TextureStats message");
     }
 }
Exemplo n.º 37
0
        private void RezAvatarRequestHandler(IHttpClientContext context, IHttpRequest request, IHttpResponse response)
        {
            OSDMap requestMap = null;

            try { requestMap = OSDParser.Deserialize(request.Body) as OSDMap; }
            catch (Exception ex)
            {
                m_log.Warn("Failed to decode rez_avatar/request message: " + ex.Message);
                response.Status = HttpStatusCode.BadRequest;
                return;
            }

            UUID    userID        = requestMap["agent_id"].AsUUID();
            UUID    sessionID     = requestMap["session_id"].AsUUID();
            bool    childAgent    = requestMap["child"].AsBoolean();
            Vector3 startPosition = requestMap["position"].AsVector3();
            Vector3 velocity      = requestMap["velocity"].AsVector3();
            Vector3 lookAt        = requestMap["look_at"].AsVector3();

            OSDMap responseMap = new OSDMap();

            UserSession session;

            if (m_userClient.TryGetSession(sessionID, out session))
            {
                session.CurrentSceneID  = m_scene.ID;
                session.CurrentPosition = startPosition;
                session.CurrentLookAt   = lookAt;

                if (!childAgent)
                {
                    // Set the agent velocity in case this is a child->root upgrade (border cross)
                    IScenePresence presence;
                    if (m_scene.TryGetPresence(session.User.ID, out presence) && presence is IPhysicalPresence)
                    {
                        ((IPhysicalPresence)presence).Velocity = velocity;
                    }

                    RezRootAgent(session, startPosition, lookAt, ref responseMap);
                }
                else
                {
                    RezChildAgent(session, startPosition, lookAt, ref responseMap);
                }
            }
            else
            {
                m_log.Error("Received a rez_avatar/request for agent " + userID + " with missing sessionID " + sessionID);
                responseMap["message"] = OSD.FromString("Session does not exist");
            }

            WebUtil.SendJSONResponse(response, responseMap);
        }
Exemplo n.º 38
0
    /// <summary>
    /// Initializes a new instance of the <see cref="IHttpResponse"/> class.
    /// </summary>
    /// <param name="context">Client that send the <see cref="IHttpRequest"/>.</param>
    /// <param name="request">Contains information of what the client want to receive.</param>
    /// <exception cref="ArgumentException"><see cref="IHttpRequest.HttpVersion"/> cannot be empty.</exception>
    public HttpResponse(IHttpClientContext context, IHttpRequest request)
    {
      Check.Require(context, "context");
      Check.Require(request, "request");

      _httpVersion = request.HttpVersion;
      if (string.IsNullOrEmpty(_httpVersion))
        throw new ArgumentException("HttpVersion in IHttpRequest cannot be empty.");

      Status = HttpStatusCode.OK;
      _context = context;
      Connection = request.Connection;
    }
Exemplo n.º 39
0
        private void UploadBakedTextureHandler(Capability cap, IHttpClientContext context, IHttpRequest request, IHttpResponse response)
        {
            UploadBakedTextureMessage reply      = new UploadBakedTextureMessage();
            UploaderRequestUpload     replyBlock = new UploaderRequestUpload();

            // Create a temporary uploader capability
            replyBlock.Url = m_scene.Capabilities.AddCapability(cap.OwnerID, true, m_scene.ID, "UploadBakedTextureData");
            reply.Request  = replyBlock;

            m_log.Debug("Created baked texture upload capability " + replyBlock.Url + " for " + cap.OwnerID);

            LLUtil.SendLLSDXMLResponse(response, reply.Serialize());
        }
Exemplo n.º 40
0
 private void ParcelVoiceInfoRequestHandler(Capability cap, IHttpClientContext context, IHttpRequest request, IHttpResponse response)
 {
     ParcelVoiceInfoRequestMessage message;
     if (LLUtil.TryGetMessage<ParcelVoiceInfoRequestMessage>(request.Body, out message))
     {
         m_log.DebugFormat("ParcelVoiceInfoRequest: RegionName={0}, ParcelID={1}, SipChannelUri={2}",
             message.RegionName, message.ParcelID, message.SipChannelUri);
     }
     else
     {
         m_log.Warn("Received invalid request data for ParcelVoiceInfoRequest");
         response.Status = System.Net.HttpStatusCode.BadRequest;
     }
 }
Exemplo n.º 41
0
 void DeleteHandler(IHttpClientContext context, IHttpRequest request, IHttpResponse response)
 {
     string username;
     if (server.AuthenticateRequest(request, response, out username))
     {
         Dictionary<string, HttpStatusCode> multiStatus = null;
         HttpStatusCode status = server.DeleteResource(request.Uri, username, out multiStatus);
         response.Status = status;
         if (status == (HttpStatusCode)207 && multiStatus != null) //multiple status
         {
             byte[] bytes = XmlResponse.WriteMultiStatusResponseBody(multiStatus);
             response.ContentLength = bytes.Length;
             //Console.WriteLine(Encoding.UTF8.GetString(bytes));
             response.Body.Write(bytes, 0, bytes.Length);
         }
     }
 }
Exemplo n.º 42
0
        void OptionsHandler(IHttpClientContext context, IHttpRequest request, IHttpResponse response)
        {
            response.AddHeader("DAV", "2");
            response.AddHeader("MS-Author-Via", "DAV");

            //This now gets all the events that have handler from the dav listener
            string allowString = server.GetAvailableMethods();

            //Add this information to both, Public and Allow. We currently have no way of separating these two
            response.AddHeader("Public", allowString);
            response.AddHeader("Allow", allowString);

            //Preserving the old headers as reference. These should be removed when method is mature enough
            //response.AddHeader("Public", "COPY, DELETE, GET, HEAD, MKCOL, MOVE, OPTIONS, PROPFIND, PROPPATCH, PUT");
            //response.AddHeader("Allow", "COPY, DELETE, GET, HEAD, MKCOL, MOVE, OPTIONS, PROPFIND, PROPPATCH, PUT");

            server.HttpServer.LogWriter.Write(this, LogPrio.Debug, "Sending OPTIONS response for request to " + request.UriPath);
        }
Exemplo n.º 43
0
 void UnlockHandler(IHttpClientContext context, IHttpRequest request, IHttpResponse response)
 {
     string username;
     if (server.AuthenticateRequest(request, response, out username))
     {
         string locktoken = (request.Headers.GetValues("Lock-Token"))[0];
         if (locktoken == null || locktoken == String.Empty)
         {
             response.Status = HttpStatusCode.BadRequest;
         }
         else
         {
             HttpStatusCode code = server.OnUnlockConnector(request.UriPath, locktoken, username);
             response.Status = code;
         }
     }
     else
     {
         response.Status = HttpStatusCode.Unauthorized;
     }
 }
Exemplo n.º 44
0
        public HttpClientContextTest()
        {
            _listenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            _listenSocket.Bind(new IPEndPoint(IPAddress.Any, 14862));
            _listenSocket.Listen(0);
            IAsyncResult res = _listenSocket.BeginAccept(null, null);
            _client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            _client.Connect("localhost", 14862);
            _remoteSocket = _listenSocket.EndAccept(res);

            _disconnectEvent.Reset();
            _event.Reset();
            _counter = 0;

            var requestParserFactory = new RequestParserFactory();
            _factory = new HttpContextFactory(NullLogWriter.Instance, 8192, requestParserFactory);
            _factory.RequestReceived += OnRequest;
            _context = _factory.CreateContext(_client);
            _context.Disconnected += OnDisconnect;
            //_context = new HttpClientContextImp(false, new IPEndPoint(IPAddress.Loopback, 21111), OnRequest, OnDisconnect, _client.GetStream(), ConsoleLogWriter.Instance);

            _request = null;
            _disconnected = false;
        }
Exemplo n.º 45
0
		/// <summary>
		/// To be able to track request count.
		/// </summary>
		/// <param name="context"></param>
		/// <param name="request"></param>
		private void ProcessRequestWrapper(IHttpClientContext context, IHttpRequest request)
		{
			_requestQueue.CurrentRequestCount += 1;
			ProcessRequest(context, request);
			_requestQueue.CurrentRequestCount -= 1;
		}
Exemplo n.º 46
0
 /// <summary>
 /// Create a response object.
 /// </summary>
 /// <returns>A new <see cref="IHttpResponse"/>.</returns>
 public IHttpResponse CreateResponse(IHttpClientContext context)
 {
   return new HttpResponse(context, this);
 }
Exemplo n.º 47
0
 public HttpServerContextObj(IHttpClientContext contxt, IHttpRequest reqs)
 {
     context = contxt;
     req = reqs;
 }
Exemplo n.º 48
0
 /// <summary>
 /// Handles SUBSCRIBE and UNSUBSCRIBE HTTP requests.
 /// </summary>
 /// <param name="request">The HTTP request instance to handle</param>
 /// <param name="context">The HTTP client context of the specified <paramref name="request"/>.</param>
 /// <param name="config">The UPnP endpoint over that the HTTP request was received.</param>
 /// <returns><c>true</c> if the request could be handled and a HTTP response was sent, else <c>false</c>.</returns>
 public bool HandleHTTPRequest(IHttpRequest request, IHttpClientContext context, EndpointConfiguration config)
 {
   if (request.Method == "SUBSCRIBE")
   { // SUBSCRIBE events
     string pathAndQuery = request.Uri.PathAndQuery;
     DvService service;
     if (config.EventSubPathsToServices.TryGetValue(pathAndQuery, out service))
     {
       IHttpResponse response = request.CreateResponse(context);
       string httpVersion = request.HttpVersion;
       string userAgentStr = request.Headers.Get("USER-AGENT");
       string callbackURLsStr = request.Headers.Get("CALLBACK");
       string nt = request.Headers.Get("NT");
       string sid = request.Headers.Get("SID");
       string timeoutStr = request.Headers.Get("TIMEOUT");
       int timeout = UPnPConsts.GENA_DEFAULT_SUBSCRIPTION_TIMEOUT;
       ICollection<string> callbackURLs = null;
       if ((!string.IsNullOrEmpty(timeoutStr) && (!timeoutStr.StartsWith("Second-") ||
           !int.TryParse(timeoutStr.Substring("Second-".Length).Trim(), out timeout))) ||
           (!string.IsNullOrEmpty(callbackURLsStr) &&
           !TryParseCallbackURLs(callbackURLsStr, out callbackURLs)))
       {
         response.Status = HttpStatusCode.BadRequest;
         response.Send();
         return true;
       }
       if (!string.IsNullOrEmpty(sid) && (callbackURLs != null || !string.IsNullOrEmpty(nt)))
       {
         response.Status = HttpStatusCode.BadRequest;
         response.Reason = "Incompatible Header Fields";
         response.Send();
         return true;
       }
       if (callbackURLs != null && !string.IsNullOrEmpty(nt))
       { // Subscription
         bool subscriberSupportsUPnP11;
         try
         {
           if (string.IsNullOrEmpty(userAgentStr))
             subscriberSupportsUPnP11 = false;
           else
           {
             int minorVersion;
             if (!ParserHelper.ParseUserAgentUPnP1MinorVersion(userAgentStr, out minorVersion))
             {
               response.Status = HttpStatusCode.BadRequest;
               response.Send();
               return true;
             }
             subscriberSupportsUPnP11 = minorVersion >= 1;
           }
         }
         catch (Exception e)
         {
           UPnPConfiguration.LOGGER.Warn("GENAServerController: Error in event subscription", e);
           response.Status = HttpStatusCode.BadRequest;
           response.Send();
           return true;
         }
         if (service.HasComplexStateVariables && !subscriberSupportsUPnP11)
         {
           response.Status = HttpStatusCode.ServiceUnavailable;
           response.Send();
           return true;
         }
         bool validURLs = callbackURLs.All(url => url.StartsWith("http://"));
         if (nt != "upnp:event" || !validURLs)
         {
           response.Status = HttpStatusCode.PreconditionFailed;
           response.Reason = "Precondition Failed";
           response.Send();
           return true;
         }
         DateTime date;
         if (Subscribe(config, service, callbackURLs, httpVersion, subscriberSupportsUPnP11, ref timeout,
             out date, out sid))
         {
           response.Status = HttpStatusCode.OK;
           response.AddHeader("DATE", date.ToUniversalTime().ToString("R"));
           response.AddHeader("SERVER", UPnPConfiguration.UPnPMachineInfoHeader);
           response.AddHeader("SID", sid);
           response.AddHeader("CONTENT-LENGTH", "0");
           response.AddHeader("TIMEOUT", "Second-"+timeout);
           response.Send();
           SendInitialEventNotification(sid);
           return true;
         }
         response.Status = HttpStatusCode.ServiceUnavailable;
         response.Reason = "Unable to accept renewal"; // See (DevArch), table 4-4
         response.Send();
         return true;
       }
       if (!string.IsNullOrEmpty(sid))
       { // Renewal
         DateTime date;
         if (RenewSubscription(config, sid, ref timeout, out date))
         {
           response.Status = HttpStatusCode.OK;
           response.AddHeader("DATE", date.ToUniversalTime().ToString("R"));
           response.AddHeader("SERVER", UPnPConfiguration.UPnPMachineInfoHeader);
           response.AddHeader("SID", sid);
           response.AddHeader("CONTENT-LENGTH", "0");
           response.AddHeader("TIMEOUT", "Second-"+timeout);
           response.Send();
           return true;
         }
         response.Status = HttpStatusCode.ServiceUnavailable;
         response.Reason = "Unable to accept renewal";
         response.Send();
         return true;
       }
     }
   }
   else if (request.Method == "UNSUBSCRIBE")
   { // UNSUBSCRIBE events
     string pathAndQuery = request.Uri.PathAndQuery;
     DvService service;
     if (config.EventSubPathsToServices.TryGetValue(pathAndQuery, out service))
     {
       IHttpResponse response = request.CreateResponse(context);
       string sid = request.Headers.Get("SID");
       string callbackURL = request.Headers.Get("CALLBACK");
       string nt = request.Headers.Get("NT");
       if (string.IsNullOrEmpty(sid) || !string.IsNullOrEmpty(callbackURL) || !string.IsNullOrEmpty(nt))
       {
         response.Status = HttpStatusCode.BadRequest;
         response.Reason = "Incompatible Header Fields";
         response.Send();
         return true;
       }
       if (Unsubscribe(config, sid))
       {
         response.Status = HttpStatusCode.OK;
         response.Send();
         return true;
       }
       response.Status = HttpStatusCode.PreconditionFailed;
       response.Reason = "Precondition Failed";
       response.Send();
       return true;
     }
   }
   return false;
 }
Exemplo n.º 49
0
        private void NewFileAgentInventoryVariablePriceUploadHandler(NewFileAgentInventoryVariablePriceMessage message, Capability cap,
            IHttpClientContext context, IHttpRequest request, IHttpResponse response)
        {
            byte[] assetData = request.GetBody();
            UUID assetID = UUID.Zero;
            LLInventoryItem item = null;

            m_log.Debug("Received inventory asset upload from " + cap.OwnerID + " (" + assetData.Length + " bytes)");

            if (assetData != null && assetData.Length > 0)
            {
                string contentType = LLUtil.LLAssetTypeToContentType((int)message.AssetType);

                // Create the asset
                if (m_assetClient.StoreAsset(contentType, false, false, assetData, cap.OwnerID, out assetID))
                {
                    // Create the inventory item
                    item = new LLInventoryItem();
                    item.AssetID = assetID;
                    item.ContentType = contentType;
                    item.CreationDate = DateTime.UtcNow;
                    item.CreatorID = cap.OwnerID;
                    item.Description = message.Description;
                    item.ID = UUID.Random();
                    item.Name = message.Name;
                    item.OwnerID = cap.OwnerID;
                    item.ParentID = message.FolderID;

                    Permissions perms = (m_permissions != null) ? m_permissions.GetDefaultPermissions() : Permissions.FullPermissions;
                    perms.EveryoneMask = message.EveryoneMask;
                    perms.GroupMask = message.GroupMask;
                    perms.NextOwnerMask = message.NextOwnerMask;
                    item.Permissions = perms;

                    item.SalePrice = 10;
                    item.SaleType = SaleType.Not;

                    if (!m_inventoryClient.TryCreateItem(cap.OwnerID, item))
                        m_log.Warn("Failed to create inventory item for uploaded asset " + assetID);
                }
                else
                {
                    m_log.WarnFormat("Failed to store uploaded inventory asset ({0} bytes)", assetData.Length);
                }
            }
            else
            {
                m_log.Warn("Inventory asset upload contained no data");
            }

            // Build the response message
            NewFileAgentInventoryUploadReplyMessage reply = new NewFileAgentInventoryUploadReplyMessage();
            reply.NewAsset = assetID;
            if (item != null)
            {
                reply.NewInventoryItem = item.ID;
                reply.NewBaseMask = item.Permissions.BaseMask;
                reply.NewEveryoneMask = item.Permissions.EveryoneMask;
                reply.NewNextOwnerMask = item.Permissions.NextOwnerMask;
                reply.NewOwnerMask = item.Permissions.OwnerMask;
            }

            LLUtil.SendLLSDXMLResponse(response, reply.Serialize());
        }
Exemplo n.º 50
0
        private void NewFileAgentInventoryVariablePriceHandler(Capability cap, IHttpClientContext context, IHttpRequest request, IHttpResponse response)
        {
            NewFileAgentInventoryVariablePriceMessage message;
            if (LLUtil.TryGetMessage<NewFileAgentInventoryVariablePriceMessage>(request.Body, out message))
            {
                NewFileAgentInventoryVariablePriceReplyMessage reply = new NewFileAgentInventoryVariablePriceReplyMessage();
                reply.ResourceCost = 0;
                reply.UploadPrice = 0;

                // Create a one time upload capability
                reply.Rsvp = m_scene.Capabilities.AddOneTimeCapability(cap.OwnerID, true,
                    delegate(Capability _cap, IHttpClientContext _context, IHttpRequest _request, IHttpResponse _response)
                    { NewFileAgentInventoryVariablePriceUploadHandler(message, _cap, _context, _request, _response); }
                );

                LLUtil.SendLLSDXMLResponse(response, reply.Serialize());
            }
            else
            {
                m_log.Warn("Received invalid data for NewFileAgentInventoryVariablePrice");
                response.Status = System.Net.HttpStatusCode.BadRequest;
            }
        }
Exemplo n.º 51
0
        private void NewFileAgentInventoryUploadHandler(NewFileAgentInventoryMessage message, Capability cap,
            IHttpClientContext context, IHttpRequest request, IHttpResponse response)
        {
            byte[] assetData = request.GetBody();
            UUID assetID = UUID.Zero;
            UUID itemID = UUID.Zero;

            m_log.Debug("Received inventory asset upload from " + cap.OwnerID + " (" + assetData.Length + " bytes)");

            if (assetData != null && assetData.Length > 0)
            {
                string contentType = LLUtil.LLAssetTypeToContentType((int)message.AssetType);

                // Create the asset
                if (m_assetClient.StoreAsset(contentType, false, false, assetData, cap.OwnerID, out assetID))
                {
                    // Create the inventory item
                    LLInventoryItem item = new LLInventoryItem();
                    item.AssetID = assetID;
                    item.ContentType = contentType;
                    item.CreationDate = DateTime.UtcNow;
                    item.CreatorID = cap.OwnerID;
                    item.Description = message.Description;
                    item.ID = UUID.Random();
                    item.Name = message.Name;
                    item.OwnerID = cap.OwnerID;
                    item.ParentID = message.FolderID;
                    item.Permissions = (m_permissions != null) ? m_permissions.GetDefaultPermissions() : Permissions.FullPermissions;
                    item.SalePrice = 10;
                    item.SaleType = SaleType.Not;

                    if (m_inventoryClient.TryCreateItem(cap.OwnerID, item))
                        itemID = item.ID;
                    else
                        m_log.Warn("Failed to create inventory item for uploaded asset " + assetID);
                }
                else
                {
                    m_log.WarnFormat("Failed to store uploaded inventory asset ({0} bytes)", assetData.Length);
                }
            }
            else
            {
                m_log.Warn("Inventory asset upload contained no data");
            }

            // Build the response message
            OSDMap reply = new OSDMap
            {
                { "state", OSD.FromString("complete") },
                { "new_asset", OSD.FromUUID(assetID) },
                { "new_inventory_item", OSD.FromUUID(itemID) }
            };

            LLUtil.SendLLSDXMLResponse(response, reply);
        }
Exemplo n.º 52
0
		/// <summary>
		/// Process an incoming request.
		/// </summary>
		/// <param name="context">connection to client</param>
		/// <param name="request">request information</param>
		/// <param name="response">response that should be filled</param>
		/// <param name="session">session information</param>
		protected virtual void HandleRequest(IHttpClientContext context, IHttpRequest request, IHttpResponse response,
											 IHttpSession session)
		{
			_logWriter.Write(this, LogPrio.Trace, "Processing request....");
			bool handled = false;
			try
			{
				DecodeBody(request);
				if (ProcessAuthentication(request, response, session))
				{
					foreach (HttpModule module in _modules)
					{
						if (!module.Process(request, response, session))
							continue;

						handled = true;
						if (!module.AllowSecondaryProcessing)
							break;
					}
				}
			}
			catch (HttpException err)
			{
				if (err.HttpStatusCode == HttpStatusCode.Unauthorized)
				{
					AuthenticationModule mod;
					lock (_authModules)
						mod = _authModules.Count > 0 ? _authModules[0] : null;

					if (mod != null)
						RequestAuthentication(mod, request, response);
				}
				else
					ErrorPage(response, err);
			}

			if (!handled && response.Status == HttpStatusCode.OK)
				ErrorPage(response, HttpStatusCode.NotFound, "Resource not found: " + request.Uri);

			if (!response.HeadersSent)
			{
				// Dispose session if it was not used.
				if (session.Count > 0)
				{
					_sessionStore.Save(session);
					// only set session cookie if it have not been sent in the request.
					if (request.Cookies[_sessionCookieName] == null)
						response.Cookies.Add(new ResponseCookie(_sessionCookieName, session.Id, DateTime.MinValue));//DateTime.Now.AddMinutes(20).AddDays(1)));
				}
				else
					_sessionStore.AddUnused(session);
			}

			if (!response.Sent)
				response.Send();

			_logWriter.Write(this, LogPrio.Trace, "....done.");
		}
Exemplo n.º 53
0
        public void Dispose()
        {
            if (_initialMsgTimeout > 0)
            {
                _receiveDone.Set();
                _initialMsgTimeout = 0;
            }
            if (_networkContext != null && _networkContext.Stream != null)
            {
                if (_networkContext.Stream.CanWrite)
                    _networkContext.Stream.Flush();
                _networkContext.Stream.Close();
                _networkContext.Stream.Dispose();
                _networkContext.Stream = null;
            }

            if (_request != null && _request.InputStream != null)
            {
                _request.InputStream.Close();
                _request.InputStream.Dispose();
                _request = null;
            }

            if (_clientContext != null)
            {
                _clientContext.Close();
                _clientContext = null;
            }
        }
Exemplo n.º 54
0
		/// <summary>
		/// Can be overloaded to implement stuff when a client have been connected.
		/// </summary>
		/// <remarks>
		/// Default implementation does nothing.
		/// </remarks>
		/// <param name="client">client that disconnected</param>
		/// <param name="error">disconnect reason</param>
		protected virtual void OnClientDisconnected(IHttpClientContext client, SocketError error)
		{
		}
Exemplo n.º 55
0
 public WebSocketHttpServerHandler(OSHttpRequest preq, IHttpClientContext pContext, int bufferlen)
     : base(preq.HttpMethod, preq.Url.OriginalString)
 {
     _request = preq;
     _networkContext = pContext.GiveMeTheNetworkStreamIKnowWhatImDoing();
     _networkContext.Stream.ReadTimeout = _defaultReadTimeout;
     _clientContext = pContext;
     _bufferLength = bufferlen;
     _buffer = new byte[_bufferLength];
 }
Exemplo n.º 56
0
		private void ProcessRequest(IHttpClientContext context, IHttpRequest request)
		{
			IHttpResponse response = request.CreateResponse(context);
			try
			{
				foreach (IRule rule in _rules)
				{
					if (!rule.Process(request, response))
						continue;
					response.Send();
					return;
				}

				// load cookies if the exist.
				RequestCookies cookies = request.Headers["cookie"] != null
											 ? new RequestCookies(request.Headers["cookie"])
											 : new RequestCookies(string.Empty);

				request.SetCookies(cookies);

				IHttpSession session;
				if (cookies[_sessionCookieName] != null)
				{
					string sessionCookie = cookies[_sessionCookieName].Value;

					// there's a bug somewhere which messes up headers which can render the session cookie useless.
					// therefore let's consider the session cookie as not set if that have happened.
					if (sessionCookie.Length > 40)
					{
						_logWriter.Write(this, LogPrio.Error, "Session cookie is invalid: " + sessionCookie);
						cookies.Remove(_sessionCookieName);
						_sessionStore.Remove(sessionCookie); // free the session cookie (and thus generating a new one).
						session = _sessionStore.Create();
					}
					else
						session = _sessionStore.Load(sessionCookie) ??
								  _sessionStore.Create(sessionCookie);
				}
				else
					session = _sessionStore.Create();

				HandleRequest(context, request, response, session);
			}
			catch (Exception err)
			{
				if (_exceptionHandler == null)
#if DEBUG
					throw;
#else
				{
					WriteLog(LogPrio.Fatal, err.Message);
					return;
				}
#endif
				_exceptionHandler(this, err);

				Exception e = err;
				while (e != null)
				{
					if (e is SocketException)
						return;

					e = e.InnerException;
				}

				try
				{
#if DEBUG
					context.Respond("HTTP/1.0", HttpStatusCode.InternalServerError, "Internal server error", err.ToString(), "text/plain");
#else
					context.Respond("HTTP/1.0", HttpStatusCode.InternalServerError, "Internal server error");
#endif
				}
				catch (Exception err2)
				{
					LogWriter.Write(this, LogPrio.Fatal, "Failed to respond on message with Internal Server Error: " + err2);
				}


			}
		}
Exemplo n.º 57
0
        public void httpServerDisconnectMonitor(IHttpClientContext source, SocketError err)
        {
            switch (err)
            {
                case SocketError.NotSocket:
                    NotSocketErrors++;

                    break;
            }
        }
Exemplo n.º 58
0
 private void NewFileAgentInventoryHandler(Capability cap, IHttpClientContext context, IHttpRequest request, IHttpResponse response)
 {
     NewFileAgentInventoryMessage message;
     if (LLUtil.TryGetMessage<NewFileAgentInventoryMessage>(request.Body, out message))
     {
         m_log.Error("Implement NewFileAgentInventory");
     }
     else
     {
         m_log.Warn("Received invalid data for NewFileAgentInventory");
         response.Status = System.Net.HttpStatusCode.BadRequest;
     }
 }
Exemplo n.º 59
0
        public void OnHandleRequestIOThread(IHttpClientContext context, IHttpRequest request)
        {
            OSHttpRequest req = new OSHttpRequest(context, request);
            OSHttpResponse resp = new OSHttpResponse(new HttpResponse(context, request),context);
            HandleRequest(req, resp);

            // !!!HACK ALERT!!!
            // There seems to be a bug in the underlying http code that makes subsequent requests
            // come up with trash in Accept headers. Until that gets fixed, we're cleaning them up here.
            if (request.AcceptTypes != null)
                for (int i = 0; i < request.AcceptTypes.Length; i++)
                    request.AcceptTypes[i] = string.Empty;
        }
Exemplo n.º 60
0
 public void OnHandleRequestIOThread(IHttpClientContext context, IHttpRequest request)
 {
     OSHttpRequest req = new OSHttpRequest(context, request);
     OSHttpResponse resp = new OSHttpResponse(new HttpResponse(context, request),context);
     //resp.KeepAlive = req.KeepAlive;
     //m_log.Info("[Debug BASE HTTP SERVER]: Got Request");
     //HttpServerContextObj objstate= new HttpServerContextObj(req,resp);
     //ThreadPool.QueueUserWorkItem(new WaitCallback(ConvertIHttpClientContextToOSHttp), (object)objstate);
     HandleRequest(req, resp);
 }