//This gets called when the listener receives a request
        private void ProcessRequest (HttpListenerContext context)
        {
            var getContext = Task.Factory.FromAsync<HttpListenerContext>(_listener.BeginGetContext, _listener.EndGetContext, null);
            getContext.ContinueWith(t => ProcessRequest(t.Result));

            _router.HandleRequest(ContextGenerator(context));
        }
 internal HttpListenerRequest(HttpListenerContext context)
 {
     _context = context;
       _contentLength = -1;
       _headers = new WebHeaderCollection ();
       _identifier = Guid.NewGuid ();
 }
 internal ChunkedRequestStream (
   Stream stream, byte[] buffer, int offset, int count, HttpListenerContext context)
   : base (stream, buffer, offset, count)
 {
   _context = context;
   _decoder = new ChunkStream ((WebHeaderCollection) context.Request.Headers);
 }
Exemplo n.º 4
0
 public ChunkedRequestStream (
   HttpListenerContext context, Stream stream, byte [] buffer, int offset, int length)
   : base (stream, buffer, offset, length)
 {
   _context = context;
   _decoder = new ChunkStream ((WebHeaderCollection) context.Request.Headers);
 }
        public ChunkedInputStream(
			HttpListenerContext context, Stream stream, byte [] buffer, int offset, int length)
            : base(stream, buffer, offset, length)
        {
            this.context = context;
            WebHeaderCollection coll = (WebHeaderCollection) context.Request.Headers;
            decoder = new ChunkStream (coll);
        }
 internal HttpListenerResponse (HttpListenerContext context)
 {
   _context = context;
   _keepAlive = true;
   _statusCode = 200;
   _statusDescription = "OK";
   _version = HttpVersion.Version11;
 }
Exemplo n.º 7
0
        private void processRequest(WebSocketSharp.Net.HttpListenerContext context)
        {
            EventHandler <HttpRequestEventArgs> eventHandler;
            string httpMethod = context.Request.HttpMethod;

            if (httpMethod == "GET")
            {
                eventHandler = this.OnGet;
            }
            else if (httpMethod == "HEAD")
            {
                eventHandler = this.OnHead;
            }
            else if (httpMethod == "POST")
            {
                eventHandler = this.OnPost;
            }
            else if (httpMethod == "PUT")
            {
                eventHandler = this.OnPut;
            }
            else if (httpMethod == "DELETE")
            {
                eventHandler = this.OnDelete;
            }
            else if (httpMethod == "OPTIONS")
            {
                eventHandler = this.OnOptions;
            }
            else if (httpMethod == "TRACE")
            {
                eventHandler = this.OnTrace;
            }
            else if (httpMethod == "CONNECT")
            {
                eventHandler = this.OnConnect;
            }
            else if (httpMethod == "PATCH")
            {
                eventHandler = this.OnPatch;
            }
            else
            {
                eventHandler = null;
            }
            EventHandler <HttpRequestEventArgs> eventHandler1 = eventHandler;

            if (eventHandler1 == null)
            {
                context.Response.StatusCode = 501;
            }
            else
            {
                eventHandler1(this, new HttpRequestEventArgs(context));
            }
            context.Response.Close();
        }
        private void InitTask(HttpListenerContext context)
        {
            try
            {
                var task = this.ProcessRequestAsync(context);
                task.ContinueWith(x => HandleError(x.Exception, context), TaskContinuationOptions.OnlyOnFaulted | TaskContinuationOptions.AttachedToParent);

                if (task.Status == TaskStatus.Created)
                {
                    task.RunSynchronously();
                }
            }
            catch (Exception ex)
            {
                HandleError(ex, context);
            }
        }
        private Task ProcessRequestAsync(HttpListenerContext context)
        {
            var request = context.Request;

            LogHttpRequest(request);

            if (request.IsWebSocketRequest)
            {
                ProcessWebSocketRequest(context);
                return Task.FromResult(true);
            }

            if (string.IsNullOrEmpty(context.Request.RawUrl))
                return ((object)null).AsTaskResult();

            var httpReq = GetRequest(context);

            return RequestHandler(httpReq, request.Url);
        }
Exemplo n.º 10
0
 private void receiveRequest()
 {
     while (true)
     {
         try
         {
             WebSocketSharp.Net.HttpListenerContext context = this._listener.GetContext();
             ThreadPool.QueueUserWorkItem((object state) => {
                 try
                 {
                     if (!context.Request.IsUpgradeTo("websocket"))
                     {
                         this.processRequest(context);
                     }
                     else
                     {
                         this.processRequest(context.AcceptWebSocket(null));
                     }
                 }
                 catch (Exception exception)
                 {
                     this._logger.Fatal(exception.ToString());
                     context.Connection.Close(true);
                 }
             });
         }
         catch (WebSocketSharp.Net.HttpListenerException httpListenerException1)
         {
             WebSocketSharp.Net.HttpListenerException httpListenerException = httpListenerException1;
             this._logger.Warn(string.Concat("Receiving has been stopped.\n  reason: ", httpListenerException.Message));
             break;
         }
         catch (Exception exception1)
         {
             this._logger.Fatal(exception1.ToString());
             break;
         }
     }
     if (this.IsListening)
     {
         this.abort();
     }
 }
Exemplo n.º 11
0
 internal AuthenticationSchemes SelectAuthenticationScheme(HttpListenerContext context)
 {
     if (AuthenticationSchemeSelectorDelegate != null)
         return AuthenticationSchemeSelectorDelegate (context.Request);
     else
         return auth_schemes;
 }
Exemplo n.º 12
0
        internal void RegisterContext(HttpListenerContext context)
        {
            lock (((ICollection)registry).SyncRoot)
                registry [context] = context;

            ListenerAsyncResult ares = null;
            lock (((ICollection)wait_queue).SyncRoot) {
                if (wait_queue.Count == 0) {
                    lock (((ICollection)ctx_queue).SyncRoot)
                        ctx_queue.Add (context);
                } else {
                    ares = wait_queue [0];
                    wait_queue.RemoveAt (0);
                }
            }

            if (ares != null)
                ares.Complete (context);
        }
Exemplo n.º 13
0
    internal void UnregisterContext (HttpListenerContext context)
    {
      lock (_ctxRegistrySync)
        _ctxRegistry.Remove (context);

      lock (_ctxQueueSync) {
        var idx = _ctxQueue.IndexOf (context);
        if (idx >= 0)
          _ctxQueue.RemoveAt (idx);
      }
    }
Exemplo n.º 14
0
 internal AuthenticationSchemes SelectAuthenticationScheme (HttpListenerContext context)
 {
   return AuthenticationSchemeSelector != null
          ? AuthenticationSchemeSelector (context.Request)
          : _authSchemes;
 }
Exemplo n.º 15
0
 internal void UnregisterContext(HttpListenerContext context)
 {
     lock (_ctxRegistrySync)
         _ctxRegistry.Remove(context);
 }
Exemplo n.º 16
0
 public ResponseEventArgs(HttpListenerContext context)
 {
     Request  = context.Request;
       Response = context.Response;
 }
        internal void Complete(HttpListenerContext context, bool syncCompleted)
        {
            var listener = context.Listener;
              var schm = listener.SelectAuthenticationScheme (context);
              if (schm != AuthenticationSchemes.Anonymous &&
              !authenticate (context, schm, listener.Realm, listener.UserCredentialsFinder)) {
            listener.BeginGetContext (this);
            return;
              }

              _context = context;
              _syncCompleted = syncCompleted;

              lock (_sync)
            complete (this);
        }
 internal HttpListenerWebSocketContext(WebSocketSharp.Net.HttpListenerContext context, string protocol)
 {
     this._context   = context;
     this._websocket = new WebSocketSharp.WebSocket(this, protocol);
 }
Exemplo n.º 19
0
        private bool closeConnection()
        {
            _readyState = WsState.CLOSED;

            try
            {
                if (_httpContext != null)
                {
                    _httpContext.Response.Close();
                    _wsStream = null;
                    _httpContext = null;
                }

                if (_wsStream != null)
                {
                    _wsStream.Dispose();
                    _wsStream = null;
                }

                if (_tcpClient != null)
                {
                    _tcpClient.Close();
                    _tcpClient = null;
                }

                return true;
            }
            catch (Exception ex)
            {
                onError(ex.Message);
                return false;
            }
        }
Exemplo n.º 20
0
 internal WebSocket(HttpListenerWebSocketContext context)
     : this()
 {
     _uri = Ext.ToUri(context.Path);
     _context = context;
     _httpContext = context.BaseContext;
     _wsStream = context.Stream;
     _endPoint = context.ServerEndPoint;
     _isClient = false;
     _isSecure = context.IsSecureConnection;
 }
Exemplo n.º 21
0
 internal HttpListenerResponse(HttpListenerContext context)
 {
     this.context = context;
     Init();
 }
Exemplo n.º 22
0
        internal void UnregisterContext(HttpListenerContext context)
        {
            lock (((ICollection)registry).SyncRoot)
                registry.Remove (context);

            lock (((ICollection)ctx_queue).SyncRoot) {
                int idx = ctx_queue.IndexOf (context);
                if (idx >= 0)
                    ctx_queue.RemoveAt (idx);
            }
        }
 internal static WsStream CreateServerStream(HttpListenerContext context)
 {
     var conn = context.Connection;
       return new WsStream (conn.Stream, conn.IsSecure);
 }
Exemplo n.º 24
0
        void CleanupContextRegistry()
        {
            lock (((ICollection)registry).SyncRoot) {
                if (registry.Count == 0)
                    return;

                // Need to copy this since closing will call UnregisterContext
                ICollection keys = registry.Keys;
                var all = new HttpListenerContext [keys.Count];
                keys.CopyTo (all, 0);
                registry.Clear ();
                for (int i = all.Length - 1; i >= 0; i--)
                    all [i].Connection.Close (true);
            }
        }
Exemplo n.º 25
0
 internal void Complete (HttpListenerContext context)
 {
   Complete (context, false);
 }
Exemplo n.º 26
0
        internal bool RegisterContext(HttpListenerContext context)
        {
            if (!_listening)
            return false;

              lock (_ctxRegistrySync) {
            if (!_listening)
              return false;

            _ctxRegistry[context] = context;

            var ares = getAsyncResultFromQueue ();
            if (ares == null)
              _ctxQueue.Add (context);
            else
              ares.Complete (context);

            return true;
              }
        }
Exemplo n.º 27
0
 internal void Complete(HttpListenerContext context)
 {
     Complete(context, false);
 }
Exemplo n.º 28
0
 internal void UnregisterContext(HttpListenerContext context)
 {
     lock (_ctxRegistrySync)
     _ctxRegistry.Remove (context);
 }
    internal void Complete (HttpListenerContext context, bool syncCompleted)
    {
      var lsnr = context.Listener;
      if (!lsnr.Authenticate (context)) {
        lsnr.BeginGetContext (this);
        return;
      }

      _context = context;
      _syncCompleted = syncCompleted;

      lock (_sync)
        complete (this);
    }
 internal HttpListenerWebSocketContext(HttpListenerContext context)
 {
     _context = context;
       _stream  = WsStream.CreateServerStream(context);
       _socket  = new WebSocket(this);
 }
Exemplo n.º 31
0
    private void cleanupContextRegistry ()
    {
      lock (_ctxRegistrySync) {
        if (_ctxRegistry.Count == 0)
          return;

        // Need to copy this since closing will call the UnregisterContext method.
        var keys = _ctxRegistry.Keys;
        var ctxs = new HttpListenerContext[keys.Count];
        keys.CopyTo (ctxs, 0);
        _ctxRegistry.Clear ();
        for (var i = ctxs.Length - 1; i >= 0; i--)
          ctxs[i].Connection.Close (true);
      }
    }
        private static bool authenticate(
      HttpListenerContext context,
      AuthenticationSchemes scheme,
      string realm,
      Func<IIdentity, NetworkCredential> credentialsFinder)
        {
            if (!(scheme == AuthenticationSchemes.Basic || scheme == AuthenticationSchemes.Digest)) {
            context.Response.Close (HttpStatusCode.Forbidden);
            return false;
              }

              var req = context.Request;
              var user = HttpUtility.CreateUser (
            req.Headers["Authorization"], scheme, realm, req.HttpMethod, credentialsFinder);

              if (user != null && user.Identity.IsAuthenticated) {
            context.User = user;
            return true;
              }

              if (scheme == AuthenticationSchemes.Basic)
            context.Response.CloseWithAuthChallenge (
              AuthenticationChallenge.CreateBasicChallenge (realm).ToBasicString ());

              if (scheme == AuthenticationSchemes.Digest)
            context.Response.CloseWithAuthChallenge (
              AuthenticationChallenge.CreateDigestChallenge (realm).ToDigestString ());

              return false;
        }
Exemplo n.º 33
0
    internal bool Authenticate (HttpListenerContext context)
    {
      var schm = SelectAuthenticationScheme (context);
      if (schm == AuthenticationSchemes.Anonymous)
        return true;

      if (schm != AuthenticationSchemes.Basic && schm != AuthenticationSchemes.Digest) {
        context.Response.Close (HttpStatusCode.Forbidden);
        return false;
      }

      var realm = Realm;
      var req = context.Request;
      var user = HttpUtility.CreateUser (
        req.Headers["Authorization"], schm, realm, req.HttpMethod, UserCredentialsFinder);

      if (user != null && user.Identity.IsAuthenticated) {
        context.User = user;
        return true;
      }

      if (schm == AuthenticationSchemes.Basic)
        context.Response.CloseWithAuthChallenge (
          AuthenticationChallenge.CreateBasicChallenge (realm).ToBasicString ());

      if (schm == AuthenticationSchemes.Digest)
        context.Response.CloseWithAuthChallenge (
          AuthenticationChallenge.CreateDigestChallenge (realm).ToDigestString ());

      return false;
    }
Exemplo n.º 34
0
 internal HttpRequestEventArgs (HttpListenerContext context)
 {
   _request = context.Request;
   _response = context.Response;
 }
Exemplo n.º 35
0
    internal void RegisterContext (HttpListenerContext context)
    {
      lock (_ctxRegistrySync)
        _ctxRegistry[context] = context;

      HttpListenerAsyncResult ares = null;
      lock (_waitQueueSync) {
        if (_waitQueue.Count == 0) {
          lock (_ctxQueueSync)
            _ctxQueue.Add (context);
        }
        else {
          ares = _waitQueue[0];
          _waitQueue.RemoveAt (0);
        }
      }

      if (ares != null)
        ares.Complete (context);
    }
Exemplo n.º 36
0
    internal void Complete (HttpListenerContext context, bool syncCompleted)
    {
      var listener = context.Listener;
      var scheme = listener.SelectAuthenticationScheme (context);
      if (scheme == AuthenticationSchemes.None) {
        context.Response.Close (HttpStatusCode.Forbidden);
        listener.BeginGetContext (this);

        return;
      }

      var header = context.Request.Headers ["Authorization"];
      if (scheme == AuthenticationSchemes.Basic &&
          (header == null ||
           !header.StartsWith ("basic", StringComparison.OrdinalIgnoreCase))) {
        context.Response.CloseWithAuthChallenge (
          HttpUtility.CreateBasicAuthChallenge (listener.Realm));
        listener.BeginGetContext (this);

        return;
      }

      if (scheme == AuthenticationSchemes.Digest &&
          (header == null ||
           !header.StartsWith ("digest", StringComparison.OrdinalIgnoreCase))) {
        context.Response.CloseWithAuthChallenge (
          HttpUtility.CreateDigestAuthChallenge (listener.Realm));
        listener.BeginGetContext (this);

        return;
      }

      _context = context;
      _syncCompleted = syncCompleted;

      lock (_sync) {
        _completed = true;
        if (_waitHandle != null)
          _waitHandle.Set ();

        if (_callback != null)
            ThreadPool.QueueUserWorkItem(invokeCallback, this);
      }
    }
Exemplo n.º 37
0
 internal AuthenticationSchemes SelectAuthenticationScheme(HttpListenerContext context)
 {
     return(AuthenticationSchemeSelector != null
      ? AuthenticationSchemeSelector(context.Request)
      : _authSchemes);
 }