Beispiel #1
0
        /// <summary>
        ///   Send headers and no data to the requestor and terminate the connection.
        /// </summary>
        /// <returns>True if successful.</returns>
        public void Send()
        {
            SendHeaders(false);

            _outputStream.Flush();
            _outputStream.Close();

            _response?.Close();
        }
        [ConditionalFact(nameof(Helpers) + "." + nameof(Helpers.IsWindowsImplementationAndNotOnNano))] // [ActiveIssue(19975, TestPlatforms.AnyUnix)]
        public async Task Abort_Invoke_ForciblyTerminatesConnection()
        {
            Client.Send(Factory.GetContent("1.1", "POST", null, "Give me a context, please", null, headerOnly: false));
            HttpListenerContext context = await Factory.GetListener().GetContextAsync();

            HttpListenerResponse response = context.Response;
            Stream ouputStream            = response.OutputStream;

            response.Abort();

            // Aborting the response should dispose the response.
            Assert.Throws <ObjectDisposedException>(() => response.ContentType = null);

            // The output stream should be not be disposed.
            // NOTE: using Assert.Throws<ObjectDisposedException>(() => ...) doesn't work here as XUnit internally
            // throws an ObjectDisposedException after we have caught the ObjectDisposedException.
            bool threwObjectDisposedException = false;

            try
            {
                ouputStream.Write(SimpleMessage, 0, SimpleMessage.Length);
            }
            catch (ObjectDisposedException)
            {
                threwObjectDisposedException = true;
            }
            Assert.True(threwObjectDisposedException);

            // The connection should be forcibly terminated.
            Assert.Throws <SocketException>(() => GetClientResponse(120));

            // Extra calls to Abort, Close or Dispose are nops.
            response.Abort();
            response.Close();
            ((IDisposable)response).Dispose();
        }
Beispiel #3
0
        private void ReceiveGameState(IAsyncResult result)
        {
            HttpListenerContext context;

            try
            {
                context = _Listener.EndGetContext(result);
            }
            catch (ObjectDisposedException e)
            {
                // Listener was Closed due to call of Stop();
                return;
            }
            finally
            {
                waitForConnection.Set();
            }

            HttpListenerRequest request = context.Request;
            string JSON;

            using (Stream inputStream = request.InputStream)
            {
                using (StreamReader sr = new StreamReader(inputStream))
                {
                    JSON = sr.ReadToEnd();
                }
            }
            using (HttpListenerResponse response = context.Response)
            {
                response.StatusCode        = (int)HttpStatusCode.OK;
                response.StatusDescription = "OK";
                response.Close();
            }
            CurrentGameState = new GameState(JSON);
        }
        private void SendJson(HttpListenerResponse response, string content)
        {
            if (content == null)
            {
                content = "{}";
            }
            byte[] contentBytes = Encoding.UTF8.GetBytes(content);

            response.AddHeader("Cache-Control", "no-cache");
            response.AddHeader("Access-Control-Allow-Origin", "*");
            response.ContentLength64 = contentBytes.Length;
            response.ContentType     = "application/json";

            try {
                Stream outputStream = response.OutputStream;
                outputStream.Write(contentBytes, 0, contentBytes.Length);
                outputStream.Close();
            }
            catch (Exception ex) {
                Console.WriteLine(ex.Message);
            }

            response.Close();
        }
        private static void FinalizeRejectedResponse(HttpListenerRequest request, HttpListenerResponse response, int statusCode, string statusDescription, Uri callbackUrl)
        {
            string remoteAddress = request.RemoteEndPoint.Address.ToString();

            try
            {
                response.StatusCode        = statusCode;
                response.StatusDescription = statusDescription;
            }
            finally
            {
                response.Close();
            }

            Supervisor.Telemetry.RecordRejectedRequest();
            if (callbackUrl == null)
            {
                Supervisor.LogEvent(string.Format("Request rejected from {0} due to: {1}.", remoteAddress, statusDescription), TraceEventType.Verbose);
            }
            else
            {
                Supervisor.LogEvent(string.Format("Request rejected for {0} from {1} due to: {2}.", callbackUrl.OriginalString, remoteAddress, statusDescription), TraceEventType.Verbose);
            }
        }
Beispiel #6
0
 public void Route(string[] uri, HttpListenerRequest request, HttpListenerResponse response)
 {
     try {
         ParseUri(uri, request, response);
     } catch (DataBase.RequestException e) {
         logger.Debug(e);
         response.StatusCode        = (int)HttpStatusCode.BadRequest;
         response.StatusDescription = e.Message;
     } catch (MethodNotFoundException e) {
         logger.Debug(e);
         response.StatusCode        = (int)HttpStatusCode.BadRequest;
         response.StatusDescription = "No such method found";
     } catch (WrongParamsException e) {
         logger.Debug(e);
         response.StatusCode        = (int)HttpStatusCode.BadRequest;
         response.StatusDescription = "Wrong params exception";
     } catch (Exception e) {
         logger.Error(e);
         response.StatusCode        = (int)HttpStatusCode.InternalServerError;
         response.StatusDescription = "Server error. Try later.";
     } finally {
         response.Close();
     }
 }
Beispiel #7
0
        private void ReceiveGameState(IAsyncResult result)
        {
            HttpListenerContext context = net_Listener.EndGetContext(result);
            HttpListenerRequest request = context.Request;
            string JSON;

            waitForConnection.Set();

            using (Stream inputStream = request.InputStream)
            {
                using (StreamReader sr = new StreamReader(inputStream))
                    JSON = sr.ReadToEnd();
            }

            using (HttpListenerResponse response = context.Response)
            {
                response.StatusCode        = (int)HttpStatusCode.OK;
                response.StatusDescription = "OK";
                response.ContentType       = "text/html";
                response.ContentLength64   = 0;
                response.Close();
            }
            CurrentGameState = new EmptyGameState(JSON);
        }
        private void WriteBody <T>(T contents, HttpListenerResponse httpResponse)
        {
            try
            {
                if (typeof(T) == typeof(string))
                {
                    WriteResponseToOutputStream(httpResponse, contents.ToString());
                }
                else if (typeof(T) == typeof(object))
                {
                    // Handling dynamic objects
                    if (contentType.ToLowerInvariant().Contains("json"))
                    {
                        string responseBody = JsonConvert.SerializeObject(contents);

                        WriteResponseToOutputStream(httpResponse, responseBody);
                    }
                }
            }
            finally
            {
                httpResponse.Close();
            }
        }
Beispiel #9
0
        private void GetFileAttributes(HttpListenerContext context)
        {
            HttpListenerRequest  request  = context.Request;
            HttpListenerResponse response = context.Response;

            int fileID = int.Parse(request.QueryString.Get("fileid"));

            if (files.ContainsKey(fileID))
            {
                FileAttributes attributes = files[fileID];

                response.Headers.Set("name", attributes.Name);
                response.Headers.Set("size", attributes.Size.ToString());
                response.StatusCode = (int)HttpStatusCode.OK;
            }
            else
            {
                Console.WriteLine("File with id " + fileID.ToString() + " does not exist");

                response.StatusCode = (int)HttpStatusCode.NotFound;
            }

            response.Close();
        }
Beispiel #10
0
        /// <summary>
        /// Send headers and no data to the requestor and terminate the connection.
        /// </summary>
        /// <returns>True if successful.</returns>
        public async Task <bool> Send()
        {
            if (ChunkedTransfer)
            {
                throw new IOException("Response is configured to use chunked transfer-encoding.  Use SendChunk() and SendFinalChunk().");
            }
            if (!_HeadersSent)
            {
                SendHeaders();
            }

            await _OutputStream.FlushAsync();

            _OutputStream.Close();

            if (_Response != null)
            {
                _Response.Close();
            }
            return(true);
        }
Beispiel #11
0
 private static void SendBadReq(HttpListenerResponse res)
 {
     res.StatusCode = 400;
     res.Close();
 }
Beispiel #12
0
 private void SendError(HttpListenerResponse response, int status)
 {
     response.StatusCode = status;
     response.Close();
 }
Beispiel #13
0
        public static void HTTPHandler()
        {
            while (listener.IsListening)
            {
                try
                {
                    string server_metadata = string.Empty;
                    using (WebClient client = new WebClient())
                    {
                        server_metadata = client.DownloadString("http://www.growtopia2.com/growtopia/server_data.php");
                        client.Dispose();
                    }

                    if (server_metadata != "")
                    {
#if DEBUG
#endif
                        Console.WriteLine("Parsing server metadata...");



                        string[] tokens = server_metadata.Split('\n');
                        foreach (string s in tokens)
                        {
                            if (s.Length <= 0)
                            {
                                continue;
                            }
                            if (s[0] == '#')
                            {
                                continue;
                            }
                            if (s.StartsWith("RTENDMARKERBS1001"))
                            {
                                continue;
                            }
                            string key   = s.Substring(0, s.IndexOf('|')).Replace("\n", "");
                            string value = s.Substring(s.IndexOf('|') + 1);


                            switch (key)
                            {
                            case "server":
                            {
                                // server ip

                                Proxyhelper.globalUserData.Growtopia_Master_IP = value.Substring(0, value.Length);
                                break;
                            }

                            case "port":
                            {
                                ushort portval = ushort.Parse(value);
                                //mf.UpdatePortBoxSafe(portval);
                                Proxyhelper.globalUserData.Growtopia_Master_Port = portval;
                                break;
                            }

                            default:
                                break;
                            }
                        }
                        Proxyhelper.globalUserData.Growtopia_IP   = Proxyhelper.globalUserData.Growtopia_Master_IP;
                        Proxyhelper.globalUserData.Growtopia_Port = Proxyhelper.globalUserData.Growtopia_Master_Port;
                    }

                    HttpListenerContext  context  = listener.GetContext();
                    HttpListenerRequest  request  = context.Request;
                    HttpListenerResponse response = context.Response;
#if DEBUG
#endif

                    if (request.HttpMethod == "POST")
                    {
                        byte[] buffer = Encoding.UTF8.GetBytes(
                            "server|127.0.0.1\n" +
                            "port|2\n" +
                            "type|1\n" +
                            "beta_server|127.0.0.1\n" +
                            "beta_port|2\n" +
                            "meta|homebrew.com\n" +
                            "type2|1\n");

                        response.ContentLength64 = buffer.Length;
                        System.IO.Stream output = response.OutputStream;
                        output.Write(buffer, 0, buffer.Length);
                        output.Close();
                        response.Close();
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    Thread.Sleep(1000);
                    // probably cuz we stopped it, no need to worry.
                }
            }
        }
        /// <summary>
        /// Handles a quark crossing request. Checks to see if the request is possible, and returns true or false based on
        /// the validity of the crossing to the actor who requested. This is performed in 3 steps:
        /// Step 1: Tell root to be ready to receive crossing requests for the object
        /// Root will also do sanity checks (e.g. object was deleted before crossing), so checking actorStatus code
        /// is important.
        /// Step 2: Root provides URL for uploading updated properties and for downloading said object.
        /// Step 3: Tell actor about the URL where it may contact the root directly.
        /// TODO: This can be optimized if we are allowed to remember or calculate the URL. We could respond immediately with the URL
        /// and the actor would keep trying it until root accepts it. For now, we avoid concurrency.
        /// </summary>
        /// <param name="context"></param>
        /// <param name="actorRequest"></param>
        private void HandleCrossing(HttpListenerContext context, HttpListenerRequest actorRequest)
        {
            StreamReader    actorReader = new StreamReader(actorRequest.InputStream);
            XmlSerializer   deserializer = new XmlSerializer(typeof(CrossingRequest));
            CrossingRequest cross = (CrossingRequest)deserializer.Deserialize(actorReader);
            QuarkPublisher  curQp = null, prevQp = null;
            string          url = "";
            HttpStatusCode  status;

            m_crossLock.EnterReadLock();
            try
            {
                m_log.InfoFormat("{0}: Handling Crossing. Time: {1}", LogHeader, DateTime.Now.Ticks);
                if (m_quarkSubscriptions.TryGetValue(cross.curQuark, out curQp) && m_quarkSubscriptions.TryGetValue(cross.prevQuark, out prevQp))
                {
                    if (curQp.RootActorID != prevQp.RootActorID)
                    {
                        // TODO: Inter-root communication
                    }
                    else
                    {
                        // Actor's response variables
                        HttpListenerResponse actorResponse = context.Response;
                        Stream actorOutput = actorResponse.OutputStream;

                        // Root's request variables
                        RootInfo       root        = (RootInfo)m_actor[curQp.RootActorID];
                        HttpWebRequest rootRequest = (HttpWebRequest)WebRequest.Create("http://" + root.quarkAddress + "/cross/");
                        rootRequest.Credentials = CredentialCache.DefaultCredentials;
                        rootRequest.Method      = "POST";
                        rootRequest.ContentType = "text/json";
                        Stream rootOutput = rootRequest.GetRequestStream();

                        status = ValidateCrossing(cross);
                        if (status != HttpStatusCode.Created)
                        {
                            actorResponse.StatusCode = (int)status;
                            actorOutput.Close();
                            actorResponse.Close();
                            return;
                        }
                        // From here on, I might have to write, make sure we only do one of these at a time.
                        // Can't go in UpgradeableLock with a ReadLock, so let go first.
                        m_crossLock.ExitReadLock();
                        m_crossLock.EnterUpgradeableReadLock();
                        try
                        {
                            // First we double check nothing changed while we were waiting for the lock, and we are still valid to cross.
                            status = ValidateCrossing(cross);
                            if (status != HttpStatusCode.Created)
                            {
                                actorResponse.StatusCode = (int)status;
                                actorOutput.Close();
                                actorResponse.Close();
                                return;
                            }

                            // Step 1: Tell root to be ready to receive crossing requests for the object
                            // Root will also do sanity checks (e.g. object was deleted before crossing), so checking actorStatus code
                            // is important.
                            OSDMap DataMap = new OSDMap();
                            DataMap["uuid"] = OSD.FromUUID(cross.uuid);
                            DataMap["pq"]   = OSD.FromString(cross.prevQuark);
                            DataMap["cq"]   = OSD.FromString(cross.curQuark);
                            DataMap["ts"]   = OSD.FromLong(cross.timestamp);

                            string encodedMap     = OSDParser.SerializeJsonString(DataMap, true);
                            byte[] rootData       = System.Text.Encoding.ASCII.GetBytes(encodedMap);
                            int    rootDataLength = rootData.Length;
                            rootOutput.Write(rootData, 0, rootDataLength);
                            rootOutput.Close();

                            // Step 2: Root provides URL for uploading updated properties and for downloading said object.
                            HttpWebResponse response = (HttpWebResponse)rootRequest.GetResponse();
                            if (HttpStatusCode.OK == response.StatusCode)
                            {
                                m_crossLock.EnterWriteLock();
                                try
                                {
                                    m_crossings[cross.uuid]       = new CurrentCrossings();
                                    m_crossings[cross.uuid].cross = cross;
                                    m_crossings[cross.uuid].actors.UnionWith(m_quarkSubscriptions[cross.prevQuark].GetAllQuarkSubscribers());
                                    m_crossings[cross.uuid].actors.UnionWith(m_quarkSubscriptions[cross.curQuark].GetAllQuarkSubscribers());
                                    // Remove the starting actor from the list of actors to ACK.
                                    m_crossings[cross.uuid].actors.Remove(cross.actorID);
                                    m_crossings[cross.uuid].rootHandler = root;
                                }
                                finally
                                {
                                    m_crossLock.ExitWriteLock();
                                }
                                Stream       respData   = response.GetResponseStream();
                                StreamReader rootReader = new StreamReader(respData);
                                url = rootReader.ReadToEnd();
                                m_log.WarnFormat("{0}: Got URL for object request from server: {1}", LogHeader, url);
                                if (url.Length > 0)
                                {
                                    // Step 3: Tell actor about the URL where it may contact the root directly.
                                    // TODO: This can be optimized if we are allowed to remember or calculate the URL. We could respond immediately with the URL
                                    // and the actor would keep trying it until root accepts it. For now, we avoid concurrency.
                                    actorResponse.StatusCode = (int)HttpStatusCode.Created;
                                    byte[] actorUrlData       = System.Text.Encoding.ASCII.GetBytes(url);
                                    int    actorUrlDataLength = actorUrlData.Length;
                                    actorOutput.Write(actorUrlData, 0, actorUrlDataLength);
                                    actorOutput.Close();
                                    actorResponse.Close();
                                }
                                else
                                {
                                    m_log.ErrorFormat("{0}: Received empty URL from Root", LogHeader);
                                }
                            }
                            else
                            {
                                m_log.ErrorFormat("{0}: Failed to request crossing from root. Error Code: {1}", LogHeader, response.StatusCode);
                            }
                        }
                        finally
                        {
                            m_crossLock.ExitUpgradeableReadLock();
                        }
                    }
                }
            }
            catch (Exception e)
            {
                m_log.ErrorFormat("{0}: Failed to request crossing from root and forward to actor. Exception: {1}\n{2}", LogHeader, e, e.StackTrace);
            }
            finally
            {
                if (m_crossLock.IsReadLockHeld)
                {
                    m_crossLock.ExitReadLock();
                }
            }
        }
Beispiel #15
0
 public override void Close()
 {
     response.Close();
 }
Beispiel #16
0
        private static async Task HandleIncomingConnections(dynamic jsonObj)
        {
            bool runServer = true;

            while (runServer)
            {
                HttpListenerContext ctx = await listener.GetContextAsync();

                HttpListenerRequest  req  = ctx.Request;
                HttpListenerResponse resp = ctx.Response;

                Console.WriteLine("Request #: {0}", ++requestCount);
                Console.WriteLine(req.Url.ToString());
                Console.WriteLine(req.HttpMethod);
                Console.WriteLine(req.UserHostName);
                Console.WriteLine(req.UserAgent);
                Console.WriteLine();

                if ((req.HttpMethod == "POST") && (req.Url.AbsolutePath == "/findPath"))
                {
                    Graph.InitLists(jsonObj);
                    names = Graph.GetNodes();
                    using (Stream body = req.InputStream)
                    {
                        using (StreamReader reader = new StreamReader(body, req.ContentEncoding))
                        {
                            bool     badReq       = false;
                            string   s            = reader.ReadToEnd();
                            string[] mainResponse = s.Split('=', '&');
                            if (mainResponse.Length == 4 && Array.Exists(mainResponse, element => element.ToLower() == "source") && Array.Exists(mainResponse, element => element.ToLower() == "target"))
                            {
                                int sourceIndex = Array.FindIndex(mainResponse, t => t.Equals("source", StringComparison.InvariantCultureIgnoreCase));
                                int targetIndex = Array.FindIndex(mainResponse, t => t.Equals("target", StringComparison.InvariantCultureIgnoreCase));

                                if (Array.Exists(names, element => element == mainResponse[sourceIndex + 1]) && Array.Exists(names, element => element == mainResponse[targetIndex + 1]))
                                {
                                    source = mainResponse[sourceIndex + 1];
                                    target = mainResponse[targetIndex + 1];
                                }
                                else
                                {
                                    badReq = true;
                                }


                                if (!badReq)
                                {
                                    FindPath(jsonObj);

                                    if (Int16.Parse(Id) > 0)
                                    {
                                        byte[] data = Encoding.UTF8.GetBytes(String.Format(Id));
                                        resp.ContentType     = "text/plain";
                                        resp.ContentEncoding = Encoding.UTF8;
                                        resp.ContentLength64 = data.LongLength;

                                        await resp.OutputStream.WriteAsync(data, 0, data.Length);

                                        resp.Close();
                                    }
                                    else
                                    {
                                        await HandleBadRequest(resp);
                                    }
                                }
                                else
                                {
                                    await HandleBadRequest(resp);
                                }
                            }
                            else
                            {
                                await HandleBadRequest(resp);
                            }
                        }
                    }
                }
                else
                {
                    string response = "Invalid Request";
                    byte[] data     = Encoding.UTF8.GetBytes(String.Format(response));
                    resp.ContentType     = "text/plain";
                    resp.ContentEncoding = Encoding.UTF8;
                    resp.ContentLength64 = data.LongLength;

                    await resp.OutputStream.WriteAsync(data, 0, data.Length);

                    resp.Close();
                }
            }
        }
Beispiel #17
0
        private static void ProcessRequests(string[] prefixes)
        {
            if (!System.Net.HttpListener.IsSupported)
            {
                Console.WriteLine(
                    "Windows XP SP2, Server 2003, or higher is required to " +
                    "use the HttpListener class.");
                return;
            }
            // URI prefixes are required,
            if (prefixes == null || prefixes.Length == 0)
            {
                throw new ArgumentException("prefixes");
            }

            // Create a listener and add the prefixes.
            System.Net.HttpListener listener = new System.Net.HttpListener();
            foreach (string s in prefixes)
            {
                listener.Prefixes.Add(s);
            }

            try
            {
                // Start the listener to begin listening for requests.
                listener.Start();
                Console.WriteLine("Listening...");

                // Set the number of requests this application will handle.
                int numRequestsToBeHandled = 10;

                for (int i = 0; i < numRequestsToBeHandled; i++)
                {
                    HttpListenerResponse response = null;
                    try
                    {
                        // Note: GetContext blocks while waiting for a request.
                        HttpListenerContext context = listener.GetContext();

                        // Create the response.
                        response = context.Response;
                        string responseString =
                            "<HTML><BODY>The time is currently " +
                            DateTime.Now.ToString(
                                DateTimeFormatInfo.CurrentInfo) +
                            "</BODY></HTML>";
                        byte[] buffer =
                            System.Text.Encoding.UTF8.GetBytes(responseString);
                        response.ContentLength64 = buffer.Length;
                        System.IO.Stream output = response.OutputStream;
                        output.Write(buffer, 0, buffer.Length);
                    }
                    catch (HttpListenerException ex)
                    {
                        Console.WriteLine(ex.Message);
                    }
                    finally
                    {
                        if (response != null)
                        {
                            response.Close();
                        }
                    }
                }
            }
            catch (HttpListenerException ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                // Stop listening for requests.
                listener.Close();
                Console.WriteLine("Done Listening.");
            }
        }
Beispiel #18
0
 private static void SendNotFound(HttpListenerResponse res)
 {
     res.StatusCode = 404;
     res.Close();
 }
Beispiel #19
0
        private static void Handler(HttpListenerRequest req, HttpListenerResponse res)
        {
            switch (req.RawUrl)
            {
            case "/":
                if (req.HttpMethod != "GET")
                {
                    SendBadReq(res);
                    break;
                }
                SendPage(res, "index.html");
                break;

            case "/todo-list":
                if (req.HttpMethod != "GET")
                {
                    SendBadReq(res);
                    break;
                }
                res.StatusCode  = 200;
                res.ContentType = "text/json";
                Todo[] temp_todo = new Todo[count];
                Array.Copy(todos, temp_todo, count);
                res.OutputStream.Write(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(temp_todo)));
                res.Close();
                break;

            case "/add-todo":
                if (req.HttpMethod != "POST")
                {
                    SendBadReq(res);
                    break;
                }
                byte[] buffer = new byte[1024];
                for (int i = 0; ; i++)
                {
                    int t = req.InputStream.ReadByte();
                    if (t == -1)
                    {
                        Array.Resize(ref buffer, i);
                        break;
                    }
                    buffer[i] = (byte)t;
                }
                Todo temp = JsonConvert.DeserializeObject <Todo>(Encoding.UTF8.GetString(buffer));
                if (count == 5)
                {
                    for (int i = todos.Length - 1; i > 0; i--)
                    {
                        todos[i] = todos[i - 1];
                    }
                    todos[0] = temp;
                }
                else
                {
                    todos[count++] = temp;
                }
                res.StatusCode = 202;
                res.Close();
                break;

            default:
                SendNotFound(res);
                break;
            }
        }
Beispiel #20
0
 public static void CloseWithCode(this HttpListenerResponse resp, int code)
 {
     resp.StatusCode = 404;
     resp.Close();
 }
Beispiel #21
0
        public void HandleCheckFileInfoRequest(WopiRequest requestData)
        {
            lock (this)
            {
                // userId(user@polihub) will be passed from the policyHub application
                if (!_authorization.ValidateToken(requestData.AccessToken, "user@policyhub", requestData.Id))
                {
                    _errorHandler.ReturnInvalidToken(_response);
                    _response.Close();
                    return;
                }

                if (!File.Exists(requestData.FullPath))
                {
                    _errorHandler.ReturnFileUnknown(_response);
                    _response.Close();
                    return;
                }

                try
                {
                    FileInfo          fileInfo  = new FileInfo(requestData.FullPath);
                    ResponseGenerator generator = new ResponseGenerator(fileInfo);
                    if (!fileInfo.Exists)
                    {
                        _errorHandler.ReturnFileUnknown(_response);
                        return;
                    }

                    var memoryStream = new MemoryStream();
                    var json         = new DataContractJsonSerializer(typeof(WopiCheckFileInfo));
                    json.WriteObject(memoryStream, generator.GetFileInfoResponse());
                    memoryStream.Flush();
                    memoryStream.Position = 0;
                    StreamReader streamReader = new StreamReader(memoryStream);
                    var          jsonResponse = Encoding.UTF8.GetBytes(streamReader.ReadToEnd());

                    _response.ContentType     = @"application/json";
                    _response.ContentLength64 = jsonResponse.Length;
                    _response.OutputStream.Write(jsonResponse, 0, jsonResponse.Length);
                    _errorHandler.ReturnSuccess(_response);
                }
                catch (UnauthorizedAccessException)
                {
                    _errorHandler.ReturnFileUnknown(_response);
                }
                _response.Close();
            }
        }
Beispiel #22
0
        private Action SetupBGHttpListenerTask()
        {
            Action BGHttpListen = (() => {
                StringBuilder sb = new StringBuilder();
                string listFmt = @"""id"":{0}, ""kind"":""AquesTalk"", ""name"":""{1}"", ""alias"":""""";

                List <int> CidList = Config.AvatorNames.Select(c => c.Key).ToList();
                int cnt = CidList.Count;
                int cid;
                int ListenIf;

                while (KeepListen) // とりあえずの待ち受け構造
                {
                    try
                    {
                        HttpListenerContext context = HTTPListener.GetContext();
                        HttpListenerRequest request = context.Request;
                        HttpListenerResponse response = context.Response;
                        int voice = 0;
                        string TalkText = "本日は晴天ですか?";
                        string UrlPath = request.Url.AbsolutePath.ToUpper();

                        foreach (var item in Regex.Split(request.Url.Query, @"[&?]"))
                        {
                            if (item == "")
                            {
                                continue;
                            }

                            string[] s = Regex.Split(item, "=");
                            if (s.Length < 2)
                            {
                                s = new string[] { HttpUtility.UrlDecode(s[0]), "" }
                            }
                            ;
                            if (s.Length >= 2)
                            {
                                s = new string[] { HttpUtility.UrlDecode(s[0]), HttpUtility.UrlDecode(s[1]) }
                            }
                            ;

                            switch (s[0])
                            {
                            case "text":
                                TalkText = s[1];
                                break;

                            case "voice":
                                int.TryParse(s[1], out voice);
                                break;

                            case "volume":
                            case "speed":
                            case "tone":
                            default:
                                break;
                            }
                        }

                        response.ContentType = "application/json; charset=utf-8";

                        if (ListenPort == Config.HttpPortNum2)
                        {
                            ListenIf = (int)ListenInterface.Http2;
                        }
                        else
                        {
                            ListenIf = (int)ListenInterface.Http1;
                        }

                        voice = EditInputText.EditInputString((voice > 8 || voice == -1 ? 0 : voice), TalkText);
                        cid = UserData.SelectedCid[ListenIf][voice];
                        switch (UserData.RandomVoiceMethod[ListenIf])
                        {
                        case 1:
                            voice = r.Next(0, 9);
                            cid = UserData.SelectedCid[ListenIf][voice];
                            break;

                        case 2:
                            cid = CidList[r.Next(0, cnt)];
                            if (Config.AvatorNames.ContainsKey(cid))
                            {
                                UserData.VoiceParams[ListenIf][voice][cid] = Config.AvatorParams(cid);
                            }
                            break;
                        }

                        // dispath url
                        switch (UrlPath)
                        {
                        case "/TALK":
                            Dictionary <string, decimal> Effects = UserData.VoiceParams[ListenIf][voice][cid]["effect"].ToDictionary(k => k.Key, v => v.Value["value"]);
                            Dictionary <string, decimal> Emotions = UserData.VoiceParams[ListenIf][voice][cid]["emotion"].ToDictionary(k => k.Key, v => v.Value["value"]);

                            MessageData talk = new MessageData()
                            {
                                Cid = cid,
                                Message = EditInputText.ChangedTalkText,
                                BouyomiVoice = voice,
                                ListenInterface = ListenIf,
                                TaskId = MessQue.count + 1,
                                Effects = Effects,
                                Emotions = Emotions
                            };

                            switch (PlayMethod)
                            {
                            case Methods.sync:
                                MessQue.AddQueue(talk);
                                break;

                            case Methods.async:
                                OnCallAsyncTalk?.Invoke(talk);
                                break;
                            }

                            byte[] responseTalkContent = Encoding.UTF8.GetBytes("{" + string.Format(@"""taskId"":{0}", talk.TaskId) + "}");
                            response.OutputStream.Write(responseTalkContent, 0, responseTalkContent.Length);
                            response.Close();
                            break;

                        case "/GETVOICELIST":
                            sb.Clear();
                            sb.AppendLine(@"{ ""voiceList"":[");
                            sb.Append(
                                string.Join(",", Config.AvatorNames.Select(v => string.Format(listFmt, v.Key, v.Value))
                                            .Select(v => "{" + v + "}")
                                            .ToArray())
                                );
                            sb.AppendLine(@"] }");

                            byte[] responseListContent = Encoding.UTF8.GetBytes(sb.ToString());
                            response.OutputStream.Write(responseListContent, 0, responseListContent.Length);
                            response.Close();
                            break;

                        case "/GETTALKTASKCOUNT":
                            byte[] responseTaskCountContent = Encoding.UTF8.GetBytes("{" + string.Format(@"""talkTaskCount"":{0}", MessQue.count) + "}");
                            response.OutputStream.Write(responseTaskCountContent, 0, responseTaskCountContent.Length);
                            response.Close();
                            break;

                        case "/GETNOWTASKID":
                            byte[] responseTaskNowContent = Encoding.UTF8.GetBytes("{" + string.Format(@"""nowTaskId"":{0}", taskId) + "}");
                            response.OutputStream.Write(responseTaskNowContent, 0, responseTaskNowContent.Length);
                            response.Close();
                            break;

                        case "/GETNOWPLAYING":
                            byte[] responseTaskPlayingContent = Encoding.UTF8.GetBytes("{" + string.Format(@"""nowPlaying"":{0}", MessQue.count != 0) + "}");
                            response.OutputStream.Write(responseTaskPlayingContent, 0, responseTaskPlayingContent.Length);
                            response.Close();
                            break;

                        case "/CLEAR":
                            byte[] responseTaskClearContent = Encoding.UTF8.GetBytes(@"{}");
                            response.OutputStream.Write(responseTaskClearContent, 0, responseTaskClearContent.Length);
                            response.Close();
                            break;

                        default:
                            byte[] responseMessageContent = Encoding.UTF8.GetBytes(@"{ ""Message"":""content not found.""}");
                            response.StatusCode = 404;
                            response.OutputStream.Write(responseMessageContent, 0, responseMessageContent.Length);
                            response.Close();
                            break;
                        }
                    }
                    catch (Exception)
                    {
                        //Dispatcher.Invoke(() =>
                        //{
                        //    MessageBox.Show(e.Message, "sorry3");
                        //});
                    }
                }
            });

            return(BGHttpListen);
        }
Beispiel #23
0
 public void Dispose()
 {
     inner.Close();
 }
Beispiel #24
0
        private async Task HandleIncomingConnections()
        {
            bool runServer = true;

            // While a user hasn't visited the `shutdown` url, keep on handling requests
            while (!apiWorker.CancellationPending)
            {
                // Will wait here until we hear from a connection
                HttpListenerContext ctx = await listener.GetContextAsync();

                // Peel out the requests and response objects
                HttpListenerRequest  req  = ctx.Request;
                HttpListenerResponse resp = ctx.Response;
                //CORS - KIRIM DATA REPLY LANGSUNG KE WMS
                if (req.HttpMethod == "OPTIONS")
                {
                    resp.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With");
                    resp.AddHeader("Access-Control-Allow-Methods", "GET, POST");
                    resp.AddHeader("Access-Control-Max-Age", "1728000");
                }
                resp.AppendHeader("Access-Control-Allow-Origin", "*");

                // Make sure we don't increment the page views counter if `favicon.ico` is requested
                if (req.Url.AbsolutePath != "/favicon.ico")
                {
                    Console.WriteLine(req.Url.ToString());
                    Console.WriteLine(req.HttpMethod);
                    Console.WriteLine(req.UserHostName);
                    Console.WriteLine("Request to route " + req.QueryString["route"]);
                    Console.WriteLine();
                    int route = Convert.ToInt32(req.QueryString["route"]);
                    dataRoute = route;
                }
                PrintToLog logging = printLog;
                logging.Invoke("RX<-" + req.RawUrl);

                string disableSubmit = !runServer ? "disabled" : "";
                byte[] data;

                if (String.IsNullOrEmpty(req.QueryString["route"]))
                {
                    data = Encoding.UTF8.GetBytes("Infiniti 4.0 AGV API");
                }
                else
                {
                    try
                    {
                        int route = Convert.ToInt32(req.QueryString["route"]);
                        dataRoute = route;
                        ////Send Route
                        //sendByte((byte)route);
                        sendByte(route);
                        data = Encoding.UTF8.GetBytes("Accepted, route=" + route.ToString());
                    }
                    catch
                    {
                        data = Encoding.UTF8.GetBytes("Wrong data type");
                    }
                }
                resp.ContentType     = "text/html";
                resp.ContentEncoding = Encoding.UTF8;
                resp.ContentLength64 = data.LongLength;

                logging.Invoke("TX->" + Encoding.UTF8.GetString(data));

                await resp.OutputStream.WriteAsync(data, 0, data.Length);

                resp.Close();
            }
        }
        /// <summary>
        /// Used for actors ACKing received crossed messages. Once all expected actors have ACKEd the crossing message,
        /// the Sync Service informs the root actor to push a crossing finished.
        /// </summary>
        /// <param name="context"></param>
        /// <param name="request"></param>
        private void HandleAckCrossing(HttpListenerContext context, HttpListenerRequest request)
        {
            m_log.InfoFormat("{0}: HandleAckCrossing", LogHeader);
            StreamReader     actorReader  = new StreamReader(request.InputStream);
            XmlSerializer    deserializer = new XmlSerializer(typeof(CrossingFinished));
            CrossingFinished cf           = (CrossingFinished)deserializer.Deserialize(actorReader);
            string           ackActorID   = cf.ackActorID;
            CrossingRequest  cross        = cf.cross;
            RootInfo         root         = null;

            bool allAcksReceived = false;

            try
            {
                HttpStatusCode actorStatus;
                m_crossings[cross.uuid].actors.Remove(ackActorID);
                m_log.InfoFormat("{0}: Ack received from {1}, {2} acks remaining.", LogHeader, ackActorID, m_crossings[cross.uuid].actors.Count);
                if (m_crossings[cross.uuid].actors.Count == 0)
                {
                    root            = m_crossings[cross.uuid].rootHandler;
                    actorStatus     = CancelCrossing(cross);
                    allAcksReceived = true;
                }
                else
                {
                    actorStatus = HttpStatusCode.OK;
                }

                HttpListenerResponse actorResponse = context.Response;
                actorResponse.StatusCode = (int)actorStatus;
                actorResponse.Close();

                if (allAcksReceived)
                {
                    if (actorStatus == HttpStatusCode.OK)
                    {
                        m_log.InfoFormat("{0}: Informing root that crossing is finished", LogHeader);
                        // Now tell root to tell every actor that the crossing is finnished!
                        // Root's request variables
                        HttpWebRequest rootRequest = (HttpWebRequest)WebRequest.Create("http://" + root.quarkAddress + "/finished/");
                        rootRequest.Credentials = CredentialCache.DefaultCredentials;
                        rootRequest.Method      = "POST";
                        rootRequest.ContentType = "text/json";
                        Stream rootOutput = rootRequest.GetRequestStream();

                        OSDMap DataMap = new OSDMap();
                        DataMap["uuid"] = OSD.FromUUID(cross.uuid);
                        DataMap["ts"]   = OSD.FromLong(cross.timestamp);

                        string encodedMap     = OSDParser.SerializeJsonString(DataMap, true);
                        byte[] rootData       = System.Text.Encoding.ASCII.GetBytes(encodedMap);
                        int    rootDataLength = rootData.Length;
                        rootOutput.Write(rootData, 0, rootDataLength);
                        rootOutput.Close();

                        // Check if everything went OK
                        try
                        {
                            HttpWebResponse response = (HttpWebResponse)rootRequest.GetResponse();
                            if (response.StatusCode == HttpStatusCode.OK)
                            {
                                m_log.InfoFormat("{0}: Successfully finished crossing.", LogHeader);
                                return;
                            }
                        }
                        catch (WebException we)
                        {
                            var resp = we.Response as HttpWebResponse;
                            m_log.ErrorFormat("{0}: Sync Crossing finished fail with actorStatus code: {1}", LogHeader, resp.StatusCode);
                        }
                    }
                    else
                    {
                        throw new Exception("Could not find the object in the crossing dictionary");
                    }
                }
            }
            catch (Exception e)
            {
                m_log.ErrorFormat("{0}: Unkown exception while handling ACK from actor. Exception {1}", LogHeader, e);
            }
        }
Beispiel #26
0
    private void checkAndResponse(HttpListenerRequest request, HttpListenerResponse response)
    {
        NCMBSettings._responseValidationFlag = true;
        MockServerObject mockObj = null;

        StreamReader stream   = new StreamReader(request.InputStream);
        string       bodyJson = stream.ReadToEnd();

        if (request.HttpMethod.Equals("GET") && request.Url.ToString().Equals(SERVER))
        {
            mockObj        = new MockServerObject();
            mockObj.status = 200;
        }
        else
        {
            foreach (MockServerObject mock in mockObjectDic[request.HttpMethod])
            {
                if (request.Url.ToString().Equals(mock.url))
                {
                    if (bodyJson.Length > 0)
                    {
                        if (bodyJson.Equals(mock.body) || request.ContentType.Equals("multipart/form-data; boundary=_NCMBBoundary"))
                        {
                            mockObj         = mock;
                            mockObj.request = request;
                            mockObj.validate();
                            if (mockObj.status == 200 || mockObj.status == 201)
                            {
                                break;
                            }
                        }
                    }
                    else
                    {
                        mockObj         = mock;
                        mockObj.request = request;
                        mockObj.validate();
                        if (mockObj.status == 200 || mockObj.status == 201)
                        {
                            break;
                        }
                    }
                }
            }
        }

        if (mockObj == null)
        {
            mockObj = new MockServerObject();
        }

        //Set response signature
        if (mockObj.responseSignature)
        {
            string signature = _makeResponseSignature(request, mockObj.responseJson);
            response.AddHeader("X-NCMB-Response-Signature", signature);
        }
        //Set status code
        response.StatusCode = mockObj.status;
        byte[] buffer = System.Text.Encoding.UTF8.GetBytes(mockObj.responseJson);
        // Get a response stream and write the response to it.
        response.ContentLength64 = buffer.Length;
        System.IO.Stream output = response.OutputStream;
        output.Write(buffer, 0, buffer.Length);
        // You must close the output stream.
        response.Close();
    }
Beispiel #27
0
 /// <summary>
 /// Closes connection
 /// </summary>
 public void close() {
     response.Close();
     WebServer.Remove(this.connectionId);
 }
Beispiel #28
0
        private void Worker(object state)
        {
            HttpListenerRequest  request  = null;
            HttpListenerResponse response = null;

            try
            {
                var context = state as HttpListenerContext;
                //
                request  = context.Request;
                response = context.Response;
                //
                if (request.UserLanguages != null && request.UserLanguages.Length > 0)
                {
                    try
                    {
                        CultureInfo culture = CultureInfo.CreateSpecificCulture(request.UserLanguages[0].ToLowerInvariant().Trim());
                        Thread.CurrentThread.CurrentCulture   = culture;
                        Thread.CurrentThread.CurrentUICulture = culture;
                    }
                    catch
                    {
                    }
                }
                //
                if (request.IsSecureConnection)
                {
                    var clientCertificate = request.GetClientCertificate();
                    var chain             = new X509Chain
                    {
                        ChainPolicy = { RevocationMode = X509RevocationMode.NoCheck }
                    };
                    chain.Build(clientCertificate);
                    if (chain.ChainStatus.Length != 0)
                    {
                        // Invalid certificate
                        response.StatusCode = (int)HttpStatusCode.Unauthorized;
                        response.OutputStream.Close();
                        return;
                    }
                }
                //
                response.Headers.Set(HttpResponseHeader.Server, "MIG WebService Gateway");
                response.KeepAlive = false;
                //
                bool   requestHasAuthorizationHeader = request.Headers["Authorization"] != null;
                string remoteAddress = request.RemoteEndPoint.Address.ToString();
                string logExtras     = "";
                //
                if (servicePassword == "" || requestHasAuthorizationHeader) //request.IsAuthenticated)
                {
                    bool verified = false;
                    //
                    string authUser = "";
                    string authPass = "";
                    //
                    //NOTE: context.User.Identity and request.IsAuthenticated
                    //aren't working under MONO with this code =/
                    //so we proceed by manually parsing Authorization header
                    //
                    //HttpListenerBasicIdentity identity = null;
                    //
                    if (requestHasAuthorizationHeader)
                    {
                        //identity = (HttpListenerBasicIdentity)context.User.Identity;
                        // authuser = identity.Name;
                        // authpass = identity.Password;
                        byte[] encodedDataAsBytes = Convert.FromBase64String(request.Headers["Authorization"].Split(' ')[1]);
                        string authtoken          = Encoding.UTF8.GetString(encodedDataAsBytes);
                        authUser = authtoken.Split(':')[0];
                        authPass = authtoken.Split(':')[1];
                    }
                    //
                    //TODO: complete authorization (for now with one fixed user 'admin', add multiuser support)
                    //
                    if (servicePassword == "" || authUser == serviceUsername && Utility.Encryption.SHA1.GenerateHashString(authPass) == servicePassword)
                    {
                        verified = true;
                    }
                    //
                    if (verified)
                    {
                        string url = request.RawUrl.TrimStart('/').TrimStart('\\').TrimStart('.');
                        if (url.IndexOf("?") > 0)
                        {
                            url = url.Substring(0, url.IndexOf("?"));
                        }
                        // Check if this url is an alias
                        url = UrlAliasCheck(url.TrimEnd('/'));
                        //
                        // url aliasing check
                        if (url == "" || url.TrimEnd('/') == baseUrl.TrimEnd('/'))
                        {
                            // default home redirect
                            response.Redirect("/" + baseUrl.TrimEnd('/') + "/index.html");
                            //TODO: find a solution for HG homepage redirect ---> ?" + new TimeSpan(DateTime.UtcNow.Ticks).TotalMilliseconds + "#page_control");
                            response.Close();
                        }
                        else
                        {
                            var connectionWatch = Stopwatch.StartNew();
                            MigService.Log.Info(new MigEvent(this.GetName(), remoteAddress, "HTTP", request.HttpMethod,
                                                             $"{response.StatusCode} {request.RawUrl} [OPEN]"));
                            // this url is reserved for Server Sent Event stream
                            if (url.TrimEnd('/').Equals("events"))
                            {
                                HandleEventsRoute(request, response, context, remoteAddress);
                            }
                            else
                            {
                                try
                                {
                                    MigClientRequest migRequest = null;
                                    if (url.StartsWith("api/"))
                                    {
                                        string message    = url.Substring(url.IndexOf('/', 1) + 1);
                                        var    migContext = new MigContext(ContextSource.WebServiceGateway, context);
                                        migRequest = new MigClientRequest(migContext, new MigInterfaceCommand(message));
                                        // Disable HTTP caching
                                        response.Headers.Set(HttpResponseHeader.CacheControl, "no-cache, no-store, must-revalidate");
                                        response.Headers.Set(HttpResponseHeader.Pragma, "no-cache");
                                        response.Headers.Set(HttpResponseHeader.Expires, "0");
                                        // Store POST data (if any) in the migRequest.RequestData field
                                        migRequest.RequestData = WebServiceUtility.ReadToEnd(request.InputStream);
                                        migRequest.RequestText = request.ContentEncoding.GetString(migRequest.RequestData);
                                    }

                                    OnPreProcessRequest(migRequest);

                                    bool requestHandled = migRequest != null && migRequest.Handled;
                                    if (requestHandled)
                                    {
                                        SendResponseObject(context, migRequest.ResponseData);
                                    }
                                    else if (url.StartsWith(baseUrl) || baseUrl.Equals("/"))
                                    {
                                        // If request begins <base_url>, process as standard Web request
                                        string requestedFile = GetWebFilePath(url);
                                        if (!File.Exists(requestedFile))
                                        {
                                            response.StatusCode = (int)HttpStatusCode.NotFound;
                                            WebServiceUtility.WriteStringToContext(context, $"<h1>404 - Not Found</h1><br/>{requestedFile}");
                                        }
                                        else
                                        {
                                            bool isText = false;
                                            if (url.ToLower().EndsWith(".js")) // || requestedurl.EndsWith(".json"))
                                            {
                                                response.ContentType = "text/javascript";
                                                isText = true;
                                            }
                                            else if (url.ToLower().EndsWith(".css"))
                                            {
                                                response.ContentType = "text/css";
                                                isText = true;
                                            }
                                            else if (url.ToLower().EndsWith(".zip"))
                                            {
                                                response.ContentType = "application/zip";
                                            }
                                            else if (url.ToLower().EndsWith(".png"))
                                            {
                                                response.ContentType = "image/png";
                                            }
                                            else if (url.ToLower().EndsWith(".jpg"))
                                            {
                                                response.ContentType = "image/jpeg";
                                            }
                                            else if (url.ToLower().EndsWith(".gif"))
                                            {
                                                response.ContentType = "image/gif";
                                            }
                                            else if (url.ToLower().EndsWith(".svg"))
                                            {
                                                response.ContentType = "image/svg+xml";
                                            }
                                            else if (url.ToLower().EndsWith(".mp3"))
                                            {
                                                response.ContentType = "audio/mp3";
                                            }
                                            else if (url.ToLower().EndsWith(".wav"))
                                            {
                                                response.ContentType = "audio/x-wav";
                                            }
                                            else if (url.ToLower().EndsWith(".appcache"))
                                            {
                                                response.ContentType = "text/cache-manifest";
                                            }
                                            else if (url.ToLower().EndsWith(".otf") || url.ToLower().EndsWith(".ttf") || url.ToLower().EndsWith(".woff") || url.ToLower().EndsWith(".woff2"))
                                            {
                                                response.ContentType = "application/octet-stream";
                                            }
                                            else if (url.ToLower().EndsWith(".xml"))
                                            {
                                                response.ContentType = "text/xml";
                                                isText = true;
                                            }
                                            else
                                            {
                                                response.ContentType = "text/html";
                                                isText = true;
                                            }

                                            var file = new FileInfo(requestedFile);
                                            response.ContentLength64 = file.Length;

                                            bool modified = true;
                                            if (request.Headers.AllKeys.Contains("If-Modified-Since"))
                                            {
                                                var modifiedSince = DateTime.MinValue;
                                                DateTime.TryParse(request.Headers["If-Modified-Since"], out modifiedSince);
                                                if (file.LastWriteTime.ToUniversalTime().Equals(modifiedSince))
                                                {
                                                    modified = false;
                                                }
                                            }
                                            bool disableCacheControl = HttpCacheIgnoreCheck(url);
                                            if (!modified && !disableCacheControl)
                                            {
                                                // TODO: !IMPORTANT! exclude from caching files that contains SSI tags!
                                                response.StatusCode = (int)HttpStatusCode.NotModified;
                                                //!!DISABLED!! - The following line was preventing browser to load file from cache
                                                //response.Headers.Set(HttpResponseHeader.Date, file.LastWriteTimeUtc.ToString().Replace(",", "."));
                                            }
                                            else
                                            {
                                                response.Headers.Set(HttpResponseHeader.LastModified, file.LastWriteTimeUtc.ToString().Replace(",", "."));
                                                if (disableCacheControl)
                                                {
                                                    response.Headers.Set(HttpResponseHeader.CacheControl, "no-cache, no-store, must-revalidate");
                                                    response.Headers.Set(HttpResponseHeader.Pragma, "no-cache");
                                                    response.Headers.Set(HttpResponseHeader.Expires, "0");
                                                }
                                                else
                                                {
                                                    response.Headers.Set(HttpResponseHeader.CacheControl, "max-age=86400");
                                                }

                                                // PRE PROCESS text output
                                                if (isText)
                                                {
                                                    try
                                                    {
                                                        WebFile webFile = GetWebFile(requestedFile);
                                                        response.ContentEncoding = webFile.Encoding;
                                                        response.ContentType    += "; charset=" + webFile.Encoding.BodyName;
                                                        // We don't need to parse the content again if it's coming from the cache
                                                        if (!webFile.IsCached)
                                                        {
                                                            string body = webFile.Content;
                                                            if (requestedFile.EndsWith(".md"))
                                                            {
                                                                // Built-in Markdown files support
                                                                body = CommonMarkConverter.Convert(body);
                                                                // TODO: add a way to include HTML header and footer template to be appended to the
                                                                // TODO: translated markdown text
                                                            }
                                                            else
                                                            {
                                                                // HTML file
                                                                // replace prepocessor directives with values
                                                                bool tagFound;
                                                                do
                                                                {
                                                                    tagFound = false;
                                                                    var ts = body.IndexOf("{include ");
                                                                    if (ts >= 0)
                                                                    {
                                                                        var te = body.IndexOf("}", ts);
                                                                        if (te > ts)
                                                                        {
                                                                            var rs = body.Substring(ts + (te - ts) + 1);
                                                                            var cs = body.Substring(ts, te - ts + 1);
                                                                            var ls = body.Substring(0, ts);
                                                                            //
                                                                            try
                                                                            {
                                                                                if (cs.StartsWith("{include "))
                                                                                {
                                                                                    var fileName = cs.Substring(9).TrimEnd('}').Trim();
                                                                                    fileName = GetWebFilePath(fileName);

                                                                                    var fileEncoding = DetectWebFileEncoding(fileName) ??
                                                                                                       defaultWebFileEncoding;
                                                                                    var incFile = File.ReadAllText(fileName, fileEncoding) + rs;
                                                                                    body = ls + incFile;
                                                                                }
                                                                            }
                                                                            catch
                                                                            {
                                                                                body = ls + "<h5 style=\"color:red\">Error processing '" + cs.Replace("{", "[").Replace("}", "]") + "'</h5>" + rs;
                                                                            }
                                                                            tagFound = true;
                                                                        }
                                                                    }
                                                                } while (tagFound); // continue if a pre processor tag was found
                                                                // {hostos}
                                                                body = body.Replace("{hostos}", Environment.OSVersion.Platform.ToString());
                                                                // {filebase}
                                                                body = body.Replace("{filebase}", Path.GetFileNameWithoutExtension(requestedFile));
                                                            }
                                                            // update the cache content with parsing results
                                                            webFile.Content = body;
                                                        }
                                                        // Store the cache item if the file cache is enabled
                                                        if (enableFileCache)
                                                        {
                                                            UpdateWebFileCache(requestedFile, webFile.Content, response.ContentEncoding);
                                                        }
                                                        //
                                                        WebServiceUtility.WriteStringToContext(context, webFile.Content);
                                                    }
                                                    catch (Exception ex)
                                                    {
                                                        // TODO: report internal mig interface  error
                                                        response.StatusCode = (int)HttpStatusCode.InternalServerError;
                                                        WebServiceUtility.WriteStringToContext(context, ex.Message + "\n" + ex.StackTrace);
                                                        MigService.Log.Error(ex);
                                                    }
                                                }
                                                else
                                                {
                                                    WebServiceUtility.WriteBytesToContext(context, File.ReadAllBytes(requestedFile));
                                                }
                                            }
                                        }
                                        requestHandled = true;
                                    }

                                    OnPostProcessRequest(migRequest);

                                    if (!requestHandled && migRequest != null && migRequest.Handled)
                                    {
                                        SendResponseObject(context, migRequest.ResponseData);
                                    }
                                    else if (!requestHandled)
                                    {
                                        response.StatusCode = (int)HttpStatusCode.NotFound;
                                        WebServiceUtility.WriteStringToContext(context, "<h1>404 - Not Found</h1>");
                                    }
                                }
                                catch (Exception eh)
                                {
                                    // TODO: add error logging
                                    Console.Error.WriteLine(eh);
                                }
                            }
                            connectionWatch.Stop();
                            logExtras = " [CLOSED AFTER " + Math.Round(connectionWatch.Elapsed.TotalSeconds, 3) + " seconds]";
                        }
                    }
                    else
                    {
                        response.StatusCode = (int)HttpStatusCode.Unauthorized;
                        // this will only work in Linux (mono)
                        //response.Headers.Set(HttpResponseHeader.WwwAuthenticate, "Basic");
                        // this works both on Linux and Windows
                        response.AddHeader("WWW-Authenticate", "Basic realm=\"User Visible Realm\"");
                    }
                }
                else
                {
                    response.StatusCode = (int)HttpStatusCode.Unauthorized;
                    // this will only work in Linux (mono)
                    //response.Headers.Set(HttpResponseHeader.WwwAuthenticate, "Basic");
                    // this works both on Linux and Windows
                    response.AddHeader("WWW-Authenticate", "Basic realm=\"User Visible Realm\"");
                }
                MigService.Log.Info(new MigEvent(this.GetName(), remoteAddress, "HTTP", request.HttpMethod,
                                                 $"{response.StatusCode} {request.RawUrl}{logExtras}"));
            }
            catch (Exception ex)
            {
                MigService.Log.Error(ex);
            }
            finally
            {
                //
                // CleanUp/Dispose allocated resources
                //
                try { request.InputStream.Close(); } catch {
                    // TODO: add logging
                }
                try { response.OutputStream.Close(); } catch {
                    // TODO: add logging
                }
                try { response.Close(); } catch {
                    // TODO: add logging
                }
                try { response.Abort(); } catch {
                    // TODO: add logging
                }
            }
        }
Beispiel #29
0
        private void ProcessApiDataResponse(HttpListenerResponse response)
        {
            Task.Factory.StartNew(() =>
            {
                try
                {
                    double divisor = 1;
                    var api        = new JsonAPI();

                    PopulateCommonApiData(ref api, ref divisor);

                    foreach (var miner in m_miners)
                    {
                        foreach (var device in miner.Devices.Where(d => d.AllowDevice))
                        {
                            if (miner.HasMonitoringAPI)
                            {
                                switch (device.Type)
                                {
                                case "CUDA":
                                    JsonAPI.CUDA_Miner cudaMiner = null;
                                    PopulateCudaApiData((Miner.CUDA)miner, (Miner.Device.CUDA)device, divisor, ref cudaMiner);
                                    if (cudaMiner != null)
                                    {
                                        api.Miners.Add(cudaMiner);
                                    }
                                    break;

                                case "OpenCL":
                                    JsonAPI.AMD_Miner amdMiner = null;
                                    PopulateAmdApiData((Miner.OpenCL)miner, (Miner.Device.OpenCL)device, divisor, ref amdMiner);
                                    if (amdMiner != null)
                                    {
                                        api.Miners.Add(amdMiner);
                                    }
                                    break;
                                }
                            }
                            else
                            {
                                switch (device.Type)
                                {
                                case "OpenCL":
                                    JsonAPI.OpenCLMiner openClMiner = null;
                                    PopulateOpenCLApiData((Miner.OpenCL)miner, (Miner.Device.OpenCL)device, divisor, ref openClMiner);
                                    if (openClMiner != null)
                                    {
                                        api.Miners.Add(openClMiner);
                                    }
                                    break;

                                case "CPU":
                                default:
                                    JsonAPI.Miner cpuMiner = null;
                                    PopulateCpuApiData((Miner.CPU)miner, (Miner.Device.CPU)device, divisor, ref cpuMiner);
                                    if (cpuMiner != null)
                                    {
                                        api.Miners.Add(cpuMiner);
                                    }
                                    break;
                                }
                            }
                        }
                    }
                    api.Miners.Sort((x, y) => x.PciBusID.CompareTo(y.PciBusID));

                    byte[] buffer = Encoding.UTF8.GetBytes(Utils.Json.SerializeFromObject(api, Utils.Json.BaseClassFirstSettings));

                    using (var output = response.OutputStream)
                    {
                        if (buffer != null)
                        {
                            output.Write(buffer, 0, buffer.Length);
                            output.Flush();
                        }
                    }
                }
                catch (Exception ex)
                {
                    response.StatusCode = (int)HttpStatusCode.InternalServerError;

                    var errorMessage = string.Empty;
                    var currentEx    = ex;

                    while (currentEx != null)
                    {
                        if (!string.IsNullOrEmpty(errorMessage))
                        {
                            errorMessage += " ";
                        }
                        errorMessage += currentEx.Message;
                        currentEx     = currentEx.InnerException;
                    }
                    Program.Print(string.Format("[ERROR] {0}", errorMessage));
                }
                finally
                {
                    try
                    {
                        if (response != null)
                        {
                            response.Close();
                        }
                    }
                    catch (Exception ex)
                    {
                        var errorMessage = string.Empty;
                        var currentEx    = ex;

                        while (currentEx != null)
                        {
                            if (!string.IsNullOrEmpty(errorMessage))
                            {
                                errorMessage += " ";
                            }
                            errorMessage += currentEx.Message;
                            currentEx     = currentEx.InnerException;
                        }
                        Program.Print(string.Format("[ERROR] {0}", errorMessage));
                    }
                }
            },
                                  TaskCreationOptions.LongRunning);
        }
Beispiel #30
0
        public async Task HandleIncomingConnections()
        {
            bool runServer = true;

            // Create a Http server and start listening for incoming connections
            listener = new HttpListener();
            listener.Prefixes.Add(url);
            listener.Start();
            Console.WriteLine("Server listening...");
            while (runServer)
            {
                // Will wait here until we hear from a connection
                HttpListenerContext ctx = await listener.GetContextAsync();

                // Peel out the requests and response objects
                HttpListenerRequest  req  = ctx.Request;
                HttpListenerResponse resp = ctx.Response;
                resp.AddHeader("Access-Control-Allow-Origin", "*");
                if ((req.HttpMethod == "POST") && (req.Url.AbsolutePath == "/shutdown"))
                {
                    Console.WriteLine("Shutdown requested");
                    runServer       = false;
                    resp.StatusCode = 204;
                }
                else if ((req.HttpMethod == "POST") && (req.Url.AbsolutePath == "/start"))
                {
                    //Start
                    string jsonConfiguration;
                    using (var reader = new StreamReader(req.InputStream, req.ContentEncoding))
                    {
                        jsonConfiguration = reader.ReadToEnd();
                    }
                    try
                    {
                        Configuration config       = Configuration.FromJson(jsonConfiguration);
                        GeneticEngine engine       = new GeneticEngine(config);
                        var           population   = Enumerable.Range(0, engine.N).Select(_ => new Character(config.CharacterType));
                        var           engineThread = new Thread(() =>
                        {
                            metricsBuffer         = new BufferBlock <GenerationMetrics>();
                            int gen               = 0;
                            var currentPopulation = population;
                            Stopwatch sw          = new Stopwatch();
                            sw.Start();
                            while (!engine.Finish.IsFinished(currentPopulation, gen++, sw.ElapsedMilliseconds))
                            {
                                currentPopulation = engine.AdvanceGeneration(currentPopulation).ToList();
                                MeasureGenerationMetrics(currentPopulation);
                            }
                            sw.Stop();
                            metricsBuffer.Post(null);
                            metricsBuffer.Complete();
                        });
                        engineThread.Start();
                        resp.StatusCode = 204;
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.ToString());
                        byte[] responseData = Encoding.UTF8.GetBytes(ex.ToString());
                        resp.StatusCode      = 400;
                        resp.ContentEncoding = Encoding.UTF8;
                        resp.ContentLength64 = responseData.LongLength;
                        await resp.OutputStream.WriteAsync(responseData, 0, responseData.Length);
                    }
                }
                else if ((req.HttpMethod == "GET") && (req.Url.AbsolutePath == "/data"))
                {
                    //Get data
                    List <GenerationMetrics> values = new List <GenerationMetrics>();
                    while (metricsBuffer.TryReceive(out GenerationMetrics data))
                    {
                        values.Add(data);
                    }
                    byte[] responseData = Encoding.UTF8.GetBytes(
                        JsonConvert.SerializeObject(values, Formatting.None, new JsonSerializerSettings
                    {
                        ContractResolver = new CamelCasePropertyNamesContractResolver()
                    })
                        );
                    resp.ContentType     = "application/json";
                    resp.ContentEncoding = Encoding.UTF8;
                    resp.ContentLength64 = responseData.LongLength;
                    resp.StatusCode      = 200;
                    await resp.OutputStream.WriteAsync(responseData, 0, responseData.Length);
                }
                resp.Close();
            }
            listener.Close();
        }