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;
        }
 internal HttpListenerContext(HttpConnection cnc)
 {
     this.cnc   = cnc;
     err_status = 400;
     request    = new HttpListenerRequest (this);
     response   = new HttpListenerResponse (this);
 }
 internal HttpListenerContext(HttpConnection connection)
 {
     _connection = connection;
     _errorStatus = 400;
     _request = new HttpListenerRequest (this);
     _response = new HttpListenerResponse (this);
 }
        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. 5
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;
        }
Esempio n. 7
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. 9
0
 public static bool IsUpgradeTo(this WebSocketSharp.Net.HttpListenerRequest request, string protocol)
 {
     if (request == null)
     {
         throw new ArgumentNullException("request");
     }
     if (protocol == null)
     {
         throw new ArgumentNullException("protocol");
     }
     if (protocol.Length == 0)
     {
         throw new ArgumentException("Must not be empty.", "protocol");
     }
     return(request.Headers.Contains("Upgrade", protocol) && request.Headers.Contains("Connection", "Upgrade"));
 }
        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. 11
0
 bool HandleFile(string path, HttpListenerRequest req, HttpListenerResponse res)
 {
     return m_webServerUtils.SendFile(path, req, res);
 }
Esempio n. 12
0
        internal AuthenticationSchemes SelectAuthenticationScheme(HttpListenerRequest request)
        {
            var selector = _authSchemeSelector;
              if (selector == null)
            return _authSchemes;

              try {
            return selector (request);
              }
              catch {
            return AuthenticationSchemes.None;
              }
        }
Esempio n. 13
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;
 }
Esempio n. 14
0
 internal AuthenticationSchemes SelectAuthenticationScheme (HttpListenerRequest request)
 {
   var selector = _authSchemeSelector;
   return selector != null ? selector (request) : _authSchemes;
 }
Esempio n. 15
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;
        }
 public CouchbaseListenerTcpContext(HttpListenerRequest request, HttpListenerResponse response, Manager manager) : base(manager)
 {
     _request = request;
     _response = response;
 }
        /// <summary>
        /// Logs the request.
        /// </summary>
        /// <param name="logger">The logger.</param>
        /// <param name="request">The request.</param>
        private static void LogRequest(ILogger logger, HttpListenerRequest request)
        {
            var log = new StringBuilder();

            var headers = string.Join(",", request.Headers.AllKeys.Where(i => !string.Equals(i, "cookie", StringComparison.OrdinalIgnoreCase) && !string.Equals(i, "Referer", StringComparison.OrdinalIgnoreCase)).Select(k => k + "=" + request.Headers[k]));

            log.AppendLine("Ip: " + request.RemoteEndPoint + ". Headers: " + headers);

            var type = request.IsWebSocketRequest ? "Web Socket" : "HTTP " + request.HttpMethod;

            logger.LogMultiline(type + " " + request.Url, LogSeverity.Debug, log);
        }
Esempio n. 18
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;
 }
        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);
        }
 internal HttpRequestEventArgs (HttpListenerContext context)
 {
   _request = context.Request;
   _response = context.Response;
 }
 public bool HandleRequest(string path, HttpListenerRequest req, HttpListenerResponse res)
 {
     return Check(path, req, res);
 }
        /// <summary>
        /// Logs the HTTP request.
        /// </summary>
        /// <param name="request">The request.</param>
        private void LogHttpRequest(HttpListenerRequest request)
        {
            var endpoint = request.LocalEndPoint;

            if (endpoint != null)
            {
                var address = endpoint.ToString();

                _endpointListener(address);
            }

            LogRequest(_logger, request);
        }
Esempio n. 23
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;
 }
 string GetBaseUrl(HttpListenerRequest req)
 {
     System.Net.IPEndPoint localEndPoint = req.LocalEndPoint;
     return (req.IsSecureConnection ? "https://" : "http://")
         + (localEndPoint.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6
             ? ("[" + localEndPoint.Address.ToString() + "]")
             : localEndPoint.Address.ToString())
         + ":" + localEndPoint.Port.ToString();
 }
        private AuthenticationSchemes SelectAuthScheme(HttpListenerRequest request)
        {
            if (request.Url.LocalPath == "/") {
                Log.To.Listener.V(TAG, "Disregarding authentication for root request");
                return AuthenticationSchemes.Anonymous;
            }

            if (RequiresAuth) {
                var schemes = AuthenticationSchemes.Digest;
                if (_allowsBasicAuth) {
                    schemes |= AuthenticationSchemes.Basic;
                }

                return schemes;
            }

            return AuthenticationSchemes.Anonymous;
        }