internal HttpListenerContext(HttpConnection cnc)
 {
     this.cnc   = cnc;
     err_status = 400;
     request    = new HttpListenerRequest (this);
     response   = new HttpListenerResponse (this);
 }
        public bool process(HttpListenerRequest request, HttpListenerResponse response)
        {
            if (request.RawUrl.StartsWith(PAGE_PREFIX))
            {
                try
                {
                    var requestedFile = request.RawUrl.Substring(PAGE_PREFIX.Length);
                    var contentType = GetContentType(Path.GetExtension(requestedFile));
                    // Set a mime type, if we have one for this extension
                    if (!string.IsNullOrEmpty(contentType.mimeType))
                    {
                        response.ContentType = contentType.mimeType;
                    }

                    // Read the data, and set encoding type if text. Assume that any text encoding is UTF-8 (probably).
                    byte[] contentData = System.IO.File.ReadAllBytes(buildPath(escapeFileName(requestedFile)));
                    if (contentType.contentType == HTMLContentType.TextContent)
                    {
                        response.ContentEncoding = Encoding.UTF8;
                    }
                    // Write out the response to the client
                    response.WriteContent(contentData);

                    return true;
                }
                catch
                {

                }
            }
            return false;
        }
Esempio n. 3
0
 internal ResponseStream (
   Stream stream, HttpListenerResponse response, bool ignoreErrors)
 {
   _stream = stream;
   _response = response;
   _ignoreErrors = ignoreErrors;
 }
 internal HttpListenerContext(HttpConnection connection)
 {
     _connection = connection;
     _errorStatus = 400;
     _request = new HttpListenerRequest (this);
     _response = new HttpListenerResponse (this);
 }
 public void SendJsonBytes(HttpListenerResponse res, byte[] data)
 {
     res.StatusCode = (int)HttpStatusCode.OK;
     res.ContentType = "application/json";
     res.ContentEncoding = System.Text.Encoding.UTF8;
     res.AddHeader("Access-Control-Allow-Origin", "*");
     res.WriteContent(data);
 }
        bool Check(string path, HttpListenerRequest req, HttpListenerResponse res)
        {
            m_log.Info("path = " + path);
            string sessionId = System.Uri.EscapeUriString(req.RemoteEndPoint.Address.ToString()) + "_" + System.IO.Path.GetExtension(path);
            m_log.Info("sessionId: " + sessionId);
            bool isCheckingForApple = req.UserAgent.StartsWith("CaptiveNetworkSupport");
            bool isLoginURL = path.Equals("/game-login.html", StringComparison.Ordinal);
            bool isIndexURL = path.Equals("/index.html", StringComparison.Ordinal) ||
                              path.Equals("/", StringComparison.Ordinal)  ||
                              path.Equals(m_firstPath, StringComparison.Ordinal);

            if (isIndexURL)
            {
                m_log.Info("remove session: " + sessionId);
                m_sessions.Remove(sessionId);
                return false;
            }

            Session session = null;
            if (m_sessions.TryGetValue(sessionId, out session))
            {
                m_log.Info("found prev session:" + sessionId);
                if (isLoginURL)
                {
                    session.loggedIn = true;
                    SendCaptivePortalHTML(req, res, sessionId, "/hft/captive-portal/game-login.html");
                    return true;
                }

                // We've seen this device before. Either it's checking that it can connect or it's asking for a normal webpage.
                if (isCheckingForApple)
                {
                    if (session.loggedIn)
                    {
                        m_log.Info("send apple response");
                        m_webServerUtils.SendContent(res, path, m_appleResponseContent);
                        return true;
                    }
                }
                SendCaptivePortalHTML(req, res, sessionId, "/hft/captive-portal/captive-portal.html");
                return true;
            }

            if (!isCheckingForApple)
            {
                m_log.Info("not checking for apple so just fall through");
                return false;
            }

            m_log.Info("send captive-portal.html with new session: " + sessionId);
            // We are checking for apple for the first time so remember the path
            m_sessions[sessionId] = new Session();
            SendCaptivePortalHTML(req, res, sessionId, "/hft/captive-portal/captive-portal.html");
            return true;
        }
Esempio n. 7
0
        private static void onGet(HttpListenerRequest request, HttpListenerResponse response)
        {
            var content = getContent(request.RawUrl);
              if (content != null)
              {
            response.WriteContent(content);
            return;
              }

              response.StatusCode = (int)HttpStatusCode.NotFound;
        }
        public bool SendFile(string path, HttpListenerRequest req, HttpListenerResponse res)
        {
            byte[] content = null;
            if (!GetGameFile(path, out content))
            {
                return false;
            }

            SendContent(res, path, content);
            return true;
        }
 public void SendContent(HttpListenerResponse res, string path, byte[] content)
 {
     string mimeType = HFTMimeType.GetMimeType(path);
     res.ContentType = mimeType;
     if (mimeType.StartsWith("text/") ||
         mimeType == "application/javascript")
     {
         res.ContentEncoding = System.Text.Encoding.UTF8;
     }
     res.StatusCode = (int)HttpStatusCode.OK;
     res.AddHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1.
     res.AddHeader("Pragma",        "no-cache");                            // HTTP 1.0.
     res.AddHeader("Expires",       "0");                                   // Proxies.
     res.WriteContent(content);
 }
Esempio n. 10
0
 public bool Route(string path, HttpListenerRequest req, HttpListenerResponse res)
 {
     //UnityEngine.Debug.Log("routing: " + path);
     for (int i = 0; i < handlers_.Count; ++i)
     {
         RouteHandler handler = handlers_[i];
     //UnityEngine.Debug.Log("Route Checking: " + handler.Method.Name + " path: " + path);
         if (handler(path, req, res))
         {
     //UnityEngine.Debug.Log("handled");
             return true;
         }
     }
     return false;  // not handled
 }
        public bool process(HttpListenerRequest request, HttpListenerResponse response)
        {
            if (!request.RawUrl.StartsWith(PAGE_PREFIX)) return false;

            // Work out how big this request was
            long byteCount = request.RawUrl.Length + request.ContentLength64;
            // Don't count headers + request.Headers.AllKeys.Sum(x => x.Length + request.Headers[x].Length + 1);
            dataRates.RecieveDataFromClient(Convert.ToInt32(byteCount));

            IDictionary<string, object> apiRequests;
            if (request.HttpMethod.ToUpper() == "POST" && request.HasEntityBody)
            {
                System.IO.StreamReader streamReader = new System.IO.StreamReader(request.InputStream);
                apiRequests = parseJSONBody(streamReader.ReadToEnd());
            }
            else
            {
                apiRequests = splitArguments(request.Url.Query);
            }

            var results = new Dictionary<string, object>();
            var unknowns = new List<string>();
            var errors = new Dictionary<string, string>();

            foreach (var name in apiRequests.Keys)
            {
                try {
                    results[name] = kspAPI.ProcessAPIString(apiRequests[name].ToString());
                } catch (IKSPAPI.UnknownAPIException)
                {
                    unknowns.Add(apiRequests[name].ToString());
                } catch (Exception ex)
                {
                    errors[apiRequests[name].ToString()] = ex.ToString();
                }
            }
            // If we had any unrecognised API keys, let the user know
            if (unknowns.Count > 0) results["unknown"] = unknowns;
            if (errors.Count > 0)   results["errors"]  = errors;

            // Now, serialize the dictionary and write to the response
            var returnData = Encoding.UTF8.GetBytes(SimpleJson.SimpleJson.SerializeObject(results));
            response.ContentEncoding = Encoding.UTF8;
            response.ContentType = "application/json";
            response.WriteContent(returnData);
            dataRates.SendDataToClient(returnData.Length);
            return true;
        }
Esempio n. 12
0
        public static void WriteContent(this WebSocketSharp.Net.HttpListenerResponse response, byte[] content)
        {
            if (response == null)
            {
                throw new ArgumentNullException("response");
            }
            int num = 0;

            if (content != null && (num = content.Length) != 0)
            {
                Stream outputStream = response.OutputStream;
                response.ContentLength64 = num;
                outputStream.Write(content, 0, num);
                outputStream.Close();
            }
        }
Esempio n. 13
0
        public static void WriteContent(this WebSocketSharp.Net.HttpListenerResponse response, byte[] content)
        {
            if (response == null)
            {
                throw new ArgumentNullException("response");
            }
            if (content == null || content.Length == 0)
            {
                return;
            }
            Stream outputStream = response.OutputStream;

            response.ContentLength64 = (long)content.Length;
            outputStream.Write(content, 0, content.Length);
            outputStream.Close();
        }
    internal ResponseStream (
      Stream stream, HttpListenerResponse response, bool ignoreWriteExceptions)
    {
      _stream = stream;
      _response = response;

      if (ignoreWriteExceptions) {
        _write = writeWithoutThrowingException;
        _writeChunked = writeChunkedWithoutThrowingException;
      }
      else {
        _write = stream.Write;
        _writeChunked = writeChunked;
      }

      _body = new MemoryStream ();
    }
        public bool process(HttpListenerRequest request, HttpListenerResponse response)
        {
            PluginLogger.print("Falling back on default handler");

            // For now, copy the behaviour until we understand it more
            if (!KSP.IO.FileInfo.CreateForType<TelemachusDataLink>(INDEX_PAGE).Exists)
            {
                throw new FileNotFoundException("Unable to find the Telemachus index page. Is it installed in the PluginData folder?");
            }
            else if (request.RawUrl == "/" || request.RawUrl.ToLowerInvariant().StartsWith("/index"))
            {
                // Just redirect them
                var index = new Uri(request.Url, "/" + INDEX_PAGE);
                response.Redirect(index.ToString());
                return true;
            }
            return false;
        }
Esempio n. 16
0
 bool HandleFile(string path, HttpListenerRequest req, HttpListenerResponse res)
 {
     return m_webServerUtils.SendFile(path, req, res);
 }
Esempio n. 17
0
        bool HandleLiveSettings(string path, HttpListenerRequest req, HttpListenerResponse res)
        {
            if (!path.Equals("/hft/0.x.x/scripts/runtime/live-settings.js"))
            {
                return false;
            }

            m_webServerUtils.SendJsonBytes(res, m_liveSettings);
            return true;
        }
Esempio n. 18
0
 bool HandleMissingRoute(string path, HttpListenerRequest req, HttpListenerResponse res)
 {
     if (path.EndsWith(".html")) {
         if (m_webServerUtils.SendFile("/hft/missing.html", req, res)) {
             return true;
         }
     }
     return false;
 }
Esempio n. 19
0
 bool HandleNotFound(string path, HttpListenerRequest req, HttpListenerResponse res)
 {
     res.ContentType = "text/text";
     res.StatusCode = (int)HttpStatusCode.NotFound;
     res.WriteContent(System.Text.Encoding.UTF8.GetBytes("unknown path: " + path + "\n"));
     return true;
 }
        /// <summary>
        /// Copies properties from the specified <see cref="HttpListenerResponse"/> to this response.
        /// </summary>
        /// <param name="templateResponse">
        /// A <see cref="HttpListenerResponse"/> to copy.
        /// </param>
        /// <exception cref="InvalidOperationException">
        /// The response has already been sent.
        /// </exception>
        /// <exception cref="ObjectDisposedException">
        /// This object is closed.
        /// </exception>
        public void CopyFrom(HttpListenerResponse templateResponse)
        {
            checkDisposedOrHeadersSent ();

              _headers.Clear ();
              _headers.Add (templateResponse._headers);
              _contentLength = templateResponse._contentLength;
              _statusCode = templateResponse._statusCode;
              _statusDescription = templateResponse._statusDescription;
              _keepAlive = templateResponse._keepAlive;
              _version = templateResponse._version;
        }
Esempio n. 21
0
 internal ResponseStream(Stream stream, HttpListenerResponse response, bool ignoreErrors)
 {
     _stream       = stream;
     _response     = response;
     _ignoreErrors = ignoreErrors;
 }
        void SendCaptivePortalHTML(HttpListenerRequest req, HttpListenerResponse res, string sessionId, string path)
        {
            //var fullPath = path.normalize(path.join(this.options.baseDir, opt_path));
            byte[] content = null;
            if (!m_webServerUtils.GetGameFile(path, out content))
            {
                res.StatusCode = (int)HttpStatusCode.NotFound;
                return;
            }

            string str = System.Text.Encoding.UTF8.GetString(content);
            Dictionary<string, string> subs = new Dictionary<string, string>();
            subs["startUrl"] = GetBaseUrl(req) + m_firstPath + "?sessionId=" + sessionId;
            subs["sessionId"] = sessionId;
            str = HFTUtil.ReplaceParamsFlat(str, subs);
            m_log.Info("SCPH: Sending " + path);
            m_webServerUtils.SendContent(res, path, str);
        }
Esempio n. 23
0
 public ResponseEventArgs(HttpListenerContext context)
 {
   Request  = context.Request;
   Response = context.Response;
 }
    internal void Close (bool force)
    {
      if (_disposed)
        return;

      _disposed = true;
      if (!force && flush (true)) {
        _response.Close ();
      }
      else {
        if (_sendChunked) {
          var last = getChunkSizeBytes (0, true);
          _write (last, 0, last.Length);
        }

        _body.Dispose ();
        _body = null;

        _response.Abort ();
      }

      _response = null;
      _stream = null;
    }
 public void SendContent(HttpListenerResponse res, string path, string content)
 {
     SendContent(res, path, System.Text.Encoding.UTF8.GetBytes(content));
 }
 public CouchbaseListenerTcpContext(HttpListenerRequest request, HttpListenerResponse response, Manager manager) : base(manager)
 {
     _request = request;
     _response = response;
 }
Esempio n. 27
0
 internal static void Close(this WebSocketSharp.Net.HttpListenerResponse response, WebSocketSharp.Net.HttpStatusCode code)
 {
     response.StatusCode = (int)code;
     response.OutputStream.Close();
 }
 internal HttpRequestEventArgs (HttpListenerContext context)
 {
   _request = context.Request;
   _response = context.Response;
 }
Esempio n. 29
0
 bool HandleRoot(string path, HttpListenerRequest req, HttpListenerResponse res)
 {
     if (path.Equals("/index.html") ||
         path.Equals("/enter-name.html"))
     {
         var uri = req.Url;
         string url = uri.GetLeftPart(UriPartial.Authority) + m_gamePath + m_options.controllerFilename + uri.Query + uri.Fragment;
         res.StatusCode = (int)HttpStatusCode.Redirect;
         res.AddHeader("Location", url);
         res.ContentType = "text/html";
         res.WriteContent(System.Text.Encoding.UTF8.GetBytes("<script>window.location.href = decodeURIComponent(\"" + Uri.EscapeDataString(url) + "\");</script>"));
         m_log.Info("redirect: " + url);
         return true;
     }
     return false;
 }
    /// <summary>
    /// Copies some properties from the specified <see cref="HttpListenerResponse"/> to
    /// this response.
    /// </summary>
    /// <param name="templateResponse">
    /// A <see cref="HttpListenerResponse"/> to copy.
    /// </param>
    /// <exception cref="ArgumentNullException">
    /// <paramref name="templateResponse"/> is <see langword="null"/>.
    /// </exception>
    public void CopyFrom (HttpListenerResponse templateResponse)
    {
      if (templateResponse == null)
        throw new ArgumentNullException ("templateResponse");

      if (templateResponse._headers != null) {
        if (_headers != null)
          _headers.Clear ();

        Headers.Add (templateResponse._headers);
      }
      else if (_headers != null) {
        _headers = null;
      }

      _contentLength = templateResponse._contentLength;
      _statusCode = templateResponse._statusCode;
      _statusDescription = templateResponse._statusDescription;
      _keepAlive = templateResponse._keepAlive;
      _version = templateResponse._version;
    }
 public bool HandleRequest(string path, HttpListenerRequest req, HttpListenerResponse res)
 {
     return Check(path, req, res);
 }
Esempio n. 32
0
 internal static void CloseWithAuthChallenge(this WebSocketSharp.Net.HttpListenerResponse response, string challenge)
 {
     response.Headers.SetInternal("WWW-Authenticate", challenge, true);
     response.Close(WebSocketSharp.Net.HttpStatusCode.Unauthorized);
 }
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="response">The response object to write to</param>
 public TcpResponseWriter(HttpListenerResponse response)
 {
     _responseObject = response;
 }