Exemplo n.º 1
0
        public Task Start(string binFile, Action <double> progress)
        {
            IsCanceled = false;
            listener?.Start();

            return(Task.Run(async() =>
            {
                var context = listener?.GetContext();
                context.Response.SendChunked = false;
                context.Response.ContentType = System.Net.Mime.MediaTypeNames.Application.Octet;
                context.Response.AddHeader("Content-disposition", "attachment; filename=" + Path.GetFileName(binFile));
                using (var stream = context.Response.OutputStream)
                {
                    using (FileStream fs = File.OpenRead(binFile))
                    {
                        context.Response.ContentLength64 = fs.Length;
                        byte[] buffer = new byte[64 * 1024];
                        int read;
                        int readed = 0;
                        using (BinaryWriter bw = new BinaryWriter(stream))
                        {
                            try
                            {
                                while ((read = fs.Read(buffer, 0, buffer.Length)) > 0)
                                {
                                    if (!IsCanceled)
                                    {
                                        bw.Write(buffer, 0, read);
                                        bw.Flush(); //seems to have no effect
                                        readed += read;
                                        progress(100.0 * readed / fs.Length);
                                    }
                                }

                                bw.Close();
                            }
                            catch (Exception ex)
                            {
                            }
                        }
                    }
                    await Task.Delay(500);// wait for ESP to write to SPI
                    if (!IsCanceled)
                    {
                        context.Response.StatusCode = (int)HttpStatusCode.OK;
                        context.Response.StatusDescription = "OK";
                    }
                    else
                    {
                        context.Response.StatusCode = (int)HttpStatusCode.NotAcceptable;
                        context.Response.StatusDescription = "Canceled";
                    }
                    stream.Close();
                }
            }));
        }
Exemplo n.º 2
0
Arquivo: host.cs Projeto: mono/gert
	public void StartListener (Object args)
	{
		HttpListener listener = new HttpListener ();
		string prefix = string.Format ("http://*:8880/{0}/", args);
		listener.Prefixes.Add (prefix);
		listener.Start ();

		for (; ; ) {
			HttpListenerContext ctx = listener.GetContext ();
			new Thread (new Worker (ctx).ProcessRequest).Start ();
		}
	}
Exemplo n.º 3
0
Arquivo: test.cs Projeto: mono/gert
	private static void Listen ()
	{
		HttpListener listener = new HttpListener ();
		listener.Prefixes.Add ("http://127.0.0.1:8080/a/");
		listener.Start ();

		HttpListenerResponse response = listener.GetContext().Response;
		response.ContentType = "text/xml";

		byte [] buffer = Encoding.UTF8.GetBytes ("<ok/>");
		response.ContentLength64 = buffer.Length;
		Stream output = response.OutputStream;
		output.Write (buffer, 0, buffer.Length);
		output.Close ();
		listener.Stop ();
	}
Exemplo n.º 4
0
Arquivo: server.cs Projeto: mono/gert
	static int Main ()
	{
		TinyHost h = CreateHost ();

		HttpListener listener = new HttpListener ();
		listener.Prefixes.Add ("http://" + IPAddress.Loopback.ToString () + ":8081/");
		listener.Start ();

		HttpListenerContext ctx = listener.GetContext ();
		StreamWriter sw = new StreamWriter (ctx.Response.OutputStream);
		h.Execute ("FaultService.asmx", sw);
		sw.Flush ();
		ctx.Response.Close ();

		return 0;
	}
Exemplo n.º 5
0
    static void Main(string[] args)
    {
        var port   = "1982";
        var root   = ".";
        var prefix = String.Format("http://*:{0}/", port);

        Log("listening {0}", prefix);

        var listener = new HttpListener();
        listener.Prefixes.Add(prefix);
        listener.Start();

        while (true) {
          var context  = listener.GetContext();
          var request  = context.Request;
          var response = context.Response;

          Log("{0} {1}", request.HttpMethod, request.RawUrl);

          if (request.RawUrl == "/api") {
        ApiResponse(response, request);
          }
          else {
        var path = root + request.RawUrl;

        try {
          var content = File.ReadAllBytes(path);
          response.ContentType = "text/plain";
          response.AppendHeader("Content-Length", content.Length.ToString());
          response.OutputStream.Write(content, 0, content.Length);
        }
        catch (FileNotFoundException e) {
          ErrorResponse(response, 404, e);
        }
        catch (UnauthorizedAccessException e) {
          ErrorResponse(response, 403, e);
        }
        catch (Exception e) {
          ErrorResponse(response, 500, e);
        }
          }
          Log("  -> {0}", response.StatusCode);
          response.Close();
        }
    }
Exemplo n.º 6
0
Arquivo: test1.cs Projeto: mono/gert
	static void run_server ()
	{
		HttpListener listener = new HttpListener ();
		listener.Prefixes.Add (url);
		listener.Start ();

		while (server_count < count) {
			HttpListenerContext context = listener.GetContext ();
			HttpListenerResponse response = context.Response;
			string responseString = "my data";
			byte [] buffer = Encoding.UTF8.GetBytes (responseString);
			response.ContentLength64 = buffer.Length;
			Stream output = response.OutputStream;
			output.Write (buffer, 0, buffer.Length);
			output.Close ();
			server_count++;
		}
	}
Exemplo n.º 7
0
Arquivo: server.cs Projeto: mono/gert
	static void Main ()
	{
		HttpListener listener = new HttpListener ();
		listener.Prefixes.Add ("http://*:8081/");
		listener.Start ();

		HttpListenerContext context = listener.GetContext ();

		// Create the response.
		HttpListenerResponse response = context.Response;
		string responseString = "<html><body>hi client</body></html>";
		byte [] buffer = Encoding.UTF8.GetBytes (responseString);
		response.ContentLength64 = buffer.Length;
		System.Threading.Thread.Sleep (3000);
		response.OutputStream.Write (buffer, 0, buffer.Length);
		if (response != null)
			response.Close ();
		listener.Close ();

		string dir = AppDomain.CurrentDomain.BaseDirectory;
		File.Create (Path.Combine (dir, "ok")).Close ();
	}
Exemplo n.º 8
0
 private void Start(CancellationToken token)
 {
     _listener?.Start();
     do
     {
         try
         {
             HttpListenerContext?request = _listener?.GetContext();
             if (token.IsCancellationRequested)
             {
                 break;
             }
             ThreadPool.QueueUserWorkItem(ProcessRequest, request);
         }
         catch (HttpListenerException lex)
         {
             _log.Warning(lex);
         }
         catch (InvalidOperationException iex)
         {
             _log.Warning(iex);
         }
     }while (!token.IsCancellationRequested);
 }
Exemplo n.º 9
0
    //用户可能需要具有管理员身份才能运行此应用程序
    static void Main()
    {
        var listener = new HttpListener();

        listener.Prefixes.Add("http://+:8086/csharpfeeds/");
        listener.Start();

        // 打开指向将为其提供服务的源的浏览器。
        string uri = @"http://localhost:8086/csharpfeeds/";
        System.Diagnostics.Process browser = new System.Diagnostics.Process();
        browser.StartInfo.FileName = "iexplore.exe";
        browser.StartInfo.Arguments = uri;
        browser.Start();

        // 为请求提供服务。
        while (true) {
            var context = listener.GetContext();
            var body = GetReplyBody();
            context.Response.ContentType = "text/xml";
            using (XmlWriter writer = new XmlTextWriter(context.Response.OutputStream, Encoding.UTF8))
                body.WriteTo(writer);

        }
    }
Exemplo n.º 10
0
    static void Main(string[] args)
    {
        StaticStore.ReadFromFile();
        StaticStore.RebuildHashTables();
        DynamicStore.ReadFromFile();

        var srv = new HttpListener();
        srv.Prefixes.Add("http://*:23455/");
        srv.Start();
        using (srv) {
          for (;;) {
        Handle(srv.GetContext());
          }
        }
    }
Exemplo n.º 11
0
        public static void Listen(string[] args)
        {
            foreach (var arg in args)
            {
                if (arg.Contains("port"))
                {
                    var port = arg.Split('=')[1];
                    _port = int.Parse(port);
                }
            }

            try
            {
                using (var client = new TcpClient("127.0.0.1", _port))
                    _isInUse = true;
            }
            catch { }

            if (_isInUse)
            {
                Console.WriteLine($"Port is in use!");
                Console.ReadKey();
                Environment.Exit(0);
            }

            var server = new HttpListener();

            try
            {
                server.Prefixes.Add($"http://127.0.0.1:{_port}/");
                server.Start();
                Console.WriteLine($"Listening On Port {_port}");
            }
            catch
            {
                Console.WriteLine($"Run program as admin!");
                Console.ReadKey();
                Environment.Exit(0);
            }

            while (true)
            {
                var context = server.GetContext();

                if (context.Request.Url.PathAndQuery == "/fortnite/api/cloudstorage/system")
                {
                    var data = JsonConvert.SerializeObject(new
                    {
                        uniqueFilename = "3460cbe1c57d4a838ace32951a4d7171",
                        filename = "DefaultGame.ini",
                        hash = "603E6907398C7E74E25C0AE8EC3A03FFAC7C9BB4",
                        hash256 = "973124FFC4A03E66D6A4458E587D5D6146F71FC57F359C8D516E0B12A50AB0D9",
                        length = File.ReadAllText("DefaultGame.ini").Length,
                        contentType = "application/octet-stream",
                        uploaded = DateTime.Now.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss.fff'Z'"),
                        storageType = "S3",
                        doNotCache = false
                    });

                    context.Response.ContentType = "application/json";
                    context.Response.StatusCode = 200;
                    context.Response.ContentLength64 = Encoding.UTF8.GetBytes(data).Length;
                    context.Response.OutputStream.Write(Encoding.UTF8.GetBytes(data), 0, Encoding.UTF8.GetBytes(data).Length);
                }

                if (context.Request.Url.PathAndQuery.Contains("/api/public/account"))
                {
                    var data = JsonConvert.SerializeObject(new
                    {
                        id = DeviceAuth.Default.AccountID,
                        displayName = JObject.Parse(File.ReadAllText("config.json"))["displayName"],
                        name = "skidalot",
                        email = "*****@*****.**",
                        failedLoginAttempts = 0,
                        lastLogin = DateTime.Now.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss.fff'Z'"),
                        numberOfDisplayNameChanges = 3,
                        ageGroup = "UNKNOWN",
                        headless = false,
                        country = "BR",
                        countryUpdatedTime = DateTime.Now.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss.fff'Z'"),
                        lastName = "skidalot",
                        preferredLanguage = "en",
                        lastDisplayNameChange = DateTime.Now.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss.fff'Z'"),
                        canUpdateDisplayName = true,
                        tfaEnabled = true,
                        emailVerified = true,
                        minorVerified = false,
                        minorExpected = false,
                        minorStatus = "UNKNOWN"
                    });

                    context.Response.ContentType = "application/json";
                    context.Response.StatusCode = 200;
                    context.Response.ContentLength64 = Encoding.UTF8.GetBytes(data).Length;
                    context.Response.OutputStream.Write(Encoding.UTF8.GetBytes(data), 0, Encoding.UTF8.GetBytes(data).Length);

                }

                if (context.Request.Url.PathAndQuery.Contains("/fortnite/api/game/v2/profile"))
                {
                    if (context.Request.Url.PathAndQuery.Contains("QueryProfile"))
                    {
                        if (context.Request.Url.PathAndQuery.Contains("athena"))
                        {
                            var data = new WebClient().DownloadString("https://raw.githubusercontent.com/Ender-0001/Cloudstorage-Editor-Profile/main/profile_athena.json");
                            context.Response.ContentType = "application/json";
                            context.Response.StatusCode = 200;
                            context.Response.ContentLength64 = Encoding.UTF8.GetBytes(data).Length;
                            context.Response.OutputStream.Write(Encoding.UTF8.GetBytes(data), 0, Encoding.UTF8.GetBytes(data).Length);
                        }
                        else if (context.Request.Url.PathAndQuery.Contains("common_core"))
                        {
                            var data = new WebClient().DownloadString("https://raw.githubusercontent.com/Ender-0001/Cloudstorage-Editor-Profile/main/profile_common_core.json");
                            context.Response.ContentType = "application/json";
                            context.Response.StatusCode = 200;
                            context.Response.ContentLength64 = Encoding.UTF8.GetBytes(data).Length;
                            context.Response.OutputStream.Write(Encoding.UTF8.GetBytes(data), 0, Encoding.UTF8.GetBytes(data).Length);
                        }
                        else if (context.Request.Url.PathAndQuery.Contains("common_public"))
                        {
                            var data = new WebClient().DownloadString("https://raw.githubusercontent.com/Ender-0001/Cloudstorage-Editor-Profile/main/profile_common_public.json");
                            context.Response.ContentType = "application/json";
                            context.Response.StatusCode = 200;
                            context.Response.ContentLength64 = Encoding.UTF8.GetBytes(data).Length;
                            context.Response.OutputStream.Write(Encoding.UTF8.GetBytes(data), 0, Encoding.UTF8.GetBytes(data).Length);
                        }
                        else if (context.Request.Url.PathAndQuery.Contains("creative"))
                        {
                            var data = new WebClient().DownloadString("https://raw.githubusercontent.com/Ender-0001/Cloudstorage-Editor-Profile/main/profile_creative.json");
                            context.Response.ContentType = "application/json";
                            context.Response.StatusCode = 200;
                            context.Response.ContentLength64 = Encoding.UTF8.GetBytes(data).Length;
                            context.Response.OutputStream.Write(Encoding.UTF8.GetBytes(data), 0, Encoding.UTF8.GetBytes(data).Length);
                        }
                        else if (context.Request.Url.PathAndQuery.Contains("collections"))
                        {
                            var data = new WebClient().DownloadString("https://raw.githubusercontent.com/Ender-0001/Cloudstorage-Editor-Profile/main/profile_collections.json");
                            context.Response.ContentType = "application/json";
                            context.Response.StatusCode = 200;
                            context.Response.ContentLength64 = Encoding.UTF8.GetBytes(data).Length;
                            context.Response.OutputStream.Write(Encoding.UTF8.GetBytes(data), 0, Encoding.UTF8.GetBytes(data).Length);
                        }
                    }
                    else
                    {
                        var data = new WebClient().DownloadString("https://raw.githubusercontent.com/Ender-0001/Cloudstorage-Editor-Profile/main/error.json");
                        context.Response.ContentType = "application/json";
                        context.Response.StatusCode = 200;
                        context.Response.ContentLength64 = Encoding.UTF8.GetBytes(data).Length;
                        context.Response.OutputStream.Write(Encoding.UTF8.GetBytes(data), 0, Encoding.UTF8.GetBytes(data).Length);
                    }
                }

                if (context.Request.Url.PathAndQuery == "/fortnite/api/cloudstorage/system/config")
                {
                    var data = JsonConvert.SerializeObject(new
                    {
                    });

                    context.Response.ContentType = "application/json";
                    context.Response.StatusCode = 200;
                    context.Response.ContentLength64 = Encoding.UTF8.GetBytes(data).Length;
                    context.Response.OutputStream.Write(Encoding.UTF8.GetBytes(data), 0, Encoding.UTF8.GetBytes(data).Length);
                }

                if (context.Request.Url.PathAndQuery.Contains("/fortnite/api/cloudstorage/user"))
                {
                    var data = JsonConvert.SerializeObject(new
                    {
                    });

                    context.Response.ContentType = "application/json";
                    context.Response.StatusCode = 200;
                    context.Response.ContentLength64 = Encoding.UTF8.GetBytes(data).Length;
                    context.Response.OutputStream.Write(Encoding.UTF8.GetBytes(data), 0, Encoding.UTF8.GetBytes(data).Length);
                }

                

                if (context.Request.Url.PathAndQuery.Contains("/lightswitch/api/service/bulk/status"))
                {
                    var data = "[{\"serviceInstanceId\":\"fortnite\",\"status\":\"UP\",\"message\":\"GO AWAY KID\",\"maintenanceUri\":null,\"allowedActions\":[\"PLAY\",\"DOWNLOAD\"],\"banned\":false}]";

                    context.Response.ContentType = "application/json";
                    context.Response.StatusCode = 200;
                    context.Response.ContentLength64 = Encoding.UTF8.GetBytes(data).Length;
                    context.Response.OutputStream.Write(Encoding.UTF8.GetBytes(data), 0, Encoding.UTF8.GetBytes(data).Length);
                }

                if (context.Request.Url.PathAndQuery == "/fortnite/api/cloudstorage/system/3460cbe1c57d4a838ace32951a4d7171")
                {
                    var defaultGame = File.ReadAllBytes("DefaultGame.ini");

                    context.Response.ContentType = "application/octet-stream";
                    context.Response.StatusCode = 200;
                    context.Response.ContentLength64 = defaultGame.Length;
                    context.Response.OutputStream.Write(defaultGame, 0, defaultGame.Length);
                }
            }
        }
Exemplo n.º 12
0
 private void Listen()
 {
     _listener = new HttpListener();
     _listener.Prefixes.Add("http://localhost:" + _port.ToString() + "/");
     _listener.Start();
     while (true)
     {
         try
         {
             HttpListenerContext context = _listener.GetContext();
             Process(context);
         }
         catch (Exception ex)
         {
             Console.WriteLine(ex.Message);
             break;
         }
     }
 }
Exemplo n.º 13
0
    public static void Main(string[] args)
    {
        if (!HttpListener.IsSupported)
        {
            Console.WriteLine ("Windows XP SP2 or Server 2003 is required to use the HttpListener class.");
            return;
        }

        // Create a listener.
        HttpListener listener = new HttpListener();
        // Add the prefixes.
        listener.Prefixes.Add("http://+:42000/");

        int sessionCounter = 0;
        Dictionary<int,SCXML> sessions = new Dictionary<int,SCXML>();

        listener.Start();

        while(true){
            // Note: The GetContext method blocks while waiting for a request. 
            HttpListenerContext context = listener.GetContext();
            HttpListenerRequest request = context.Request;

            // Obtain a response object.
            HttpListenerResponse response = context.Response;
            System.IO.Stream output = response.OutputStream;

            String jsonBody  = new StreamReader(request.InputStream).ReadToEnd();

            //Dictionary<string, Dictionary<string,string>> values = JsonConvert.DeserializeObject<Dictionary<string, Dictionary<string,string>>>(jsonBody);
            JObject reqJson = JObject.Parse(jsonBody);

            JToken scxmlToken,eventToken,sessionJsonToken;
            int sessionToken;

            try{
                if(reqJson.TryGetValue("load",out scxmlToken)){
                    Console.WriteLine("Loading new statechart");

                    string scxmlStr = scxmlToken.ToString();
                    SCXML scxml = new SCXML(new System.Uri(scxmlStr));
                    IList<string> initialConfiguration = scxml.Start();

                    sessionToken = sessionCounter++;
                    sessions[sessionToken] = scxml;

                    // Construct a response.
                    string responseString = TestServer.getResponseJson(sessionToken,initialConfiguration);
                    System.Console.WriteLine(responseString);
                    byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
                    // Get a response stream and write the response to it.
                    response.ContentLength64 = buffer.Length;
                    output.Write(buffer,0,buffer.Length);
                }else if(reqJson.TryGetValue("event",out eventToken) && reqJson.TryGetValue("sessionToken",out sessionJsonToken)){

                    string eventName = (string) reqJson["event"]["name"];
                    sessionToken = (int) reqJson["sessionToken"];
                    
                    IList<string> nextConfiguration = sessions[sessionToken].Gen(eventName,null);

                    string responseString = TestServer.getResponseJson(sessionToken,nextConfiguration);
                    byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
                    response.ContentLength64 = buffer.Length;
                    output.Write(buffer,0,buffer.Length);
                }else{
                    string responseString = "Unrecognized request.";
                    byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
                    response.ContentLength64 = buffer.Length;
                    output.Write(buffer,0,buffer.Length);
                }
            }catch(Exception e){
                string responseString = "An error occured: " + e.ToString();
                byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
                response.ContentLength64 = buffer.Length;
                output.Write(buffer,0,buffer.Length);
            }

            output.Close();
        }
        
    }
Exemplo n.º 14
0
        void Run()
        {
            Router router = new Router();

            RestMethods restMethods = new RestMethods(VerifyToken);

            router.AddHandler("/login", HttpMethod.Post, HandleLogin);
            router.AddHandler("/logout", HttpMethod.Post, HandleLogout);

            router.AddHandler("/users", HttpMethod.Get,
                              (context) =>
            {
                SignEventAttendance(RestMethods.GetToken(context.Request));
                restMethods.PerformGet <User>(context, GetUsersByQuery);
            }
                              );
            router.AddHandler("/users/" + Router.IntegerUrlParameter, HttpMethod.Get,
                              (context) => restMethods.PerformGetById <User>(context, _users.TryGetValue,
                                                                             context.Request.Url.Segments[2])
                              );

            router.AddHandler("/messages", HttpMethod.Post,
                              (context) => restMethods.PerformPost <Message>(context, AddMessage)
                              );
            router.AddHandler("/messages", HttpMethod.Get,
                              (context) =>
            {
                SignEventAttendance(RestMethods.GetToken(context.Request));
                restMethods.PerformGet <Message>(context, GetMessagesByQuery);
            }
                              );
            router.AddHandler("/messages/" + Router.IntegerUrlParameter, HttpMethod.Get,
                              (context) => restMethods.PerformGetById <Message>(context, _messages.TryGetValue,
                                                                                context.Request.Url.Segments[2])
                              );
            router.AddHandler("/messages/" + Router.IntegerUrlParameter, HttpMethod.Delete,
                              (context) => restMethods.PerformDelete(context,
                                                                     DeleteMessage, context.Request.Url.Segments[2])
                              );

            using (HttpListener httpListener = new HttpListener())
            {
                httpListener.Prefixes.Add("http://localhost:" + _port + "/");
                httpListener.Start();

                while (true)
                {
                    var context = httpListener.GetContext();
                    HttpListenerRequest request = context.Request;
                    Thread t = new Thread(() =>
                    {
                        if (router.TryGetHandler(request, out HandlerFunc handler))
                        {
                            handler(context);
                        }
                        else
                        {
                            RestMethods.WriteError(context.Response, HttpStatusCode.BadRequest, "no handler provided");
                        }
                    });
                    t.Start();
                }
            }
        }
        [Category("NotWorking")]          // Bug #5742
        public void HasEntityBody()
        {
            HttpListenerContext ctx;
            HttpListenerRequest request;
            NetworkStream       ns;
            HttpListener        listener = NetworkHelpers.CreateAndStartHttpListener(
                "http://127.0.0.1:", out var port, "/HasEntityBody/");

            // POST with non-zero Content-Lenth
            ns = HttpListener2Test.CreateNS(port);
            HttpListener2Test.Send(ns, "POST /HasEntityBody/ HTTP/1.1\r\nHost: 127.0.0.1\r\nContent-Length: 3\r\n\r\n123");
            ctx     = listener.GetContext();
            request = ctx.Request;
            Assert.IsTrue(request.HasEntityBody, "#A");
            HttpListener2Test.Send(ctx.Response.OutputStream, "%%%OK%%%");

            // POST with zero Content-Lenth
            ns = HttpListener2Test.CreateNS(port);
            HttpListener2Test.Send(ns, "POST /HasEntityBody/ HTTP/1.1\r\nHost: 127.0.0.1\r\nContent-Length: 0\r\n\r\n123");
            ctx     = listener.GetContext();
            request = ctx.Request;
            Assert.IsFalse(request.HasEntityBody, "#B");
            HttpListener2Test.Send(ctx.Response.OutputStream, "%%%OK%%%");

            // POST with chunked encoding
            ns = HttpListener2Test.CreateNS(port);
            HttpListener2Test.Send(ns, "POST /HasEntityBody HTTP/1.1\r\nHost: 127.0.0.1\r\nTransfer-Encoding: chunked\r\n\r\n0\r\n");
            ctx     = listener.GetContext();
            request = ctx.Request;
            Assert.IsTrue(request.HasEntityBody, "#C");
            HttpListener2Test.Send(ctx.Response.OutputStream, "%%%OK%%%");

            // GET with no Content-Length
            ns = HttpListener2Test.CreateNS(port);
            HttpListener2Test.Send(ns, "GET /HasEntityBody HTTP/1.1\r\nHost: 127.0.0.1\r\n\r\n");
            ctx     = listener.GetContext();
            request = ctx.Request;
            Assert.IsFalse(request.HasEntityBody, "#D");
            HttpListener2Test.Send(ctx.Response.OutputStream, "%%%OK%%%");

            // GET with non-zero Content-Length
            ns = HttpListener2Test.CreateNS(port);
            HttpListener2Test.Send(ns, "GET /HasEntityBody HTTP/1.1\r\nHost: 127.0.0.1\r\nContent-Length: 3\r\n\r\n");
            ctx     = listener.GetContext();
            request = ctx.Request;
            Assert.IsTrue(request.HasEntityBody, "#E");
            HttpListener2Test.Send(ctx.Response.OutputStream, "%%%OK%%%");

            // GET with zero Content-Length
            ns = HttpListener2Test.CreateNS(port);
            HttpListener2Test.Send(ns, "GET /HasEntityBody HTTP/1.1\r\nHost: 127.0.0.1\r\nContent-Length: 0\r\n\r\n");
            ctx     = listener.GetContext();
            request = ctx.Request;
            Assert.IsFalse(request.HasEntityBody, "#F");
            HttpListener2Test.Send(ctx.Response.OutputStream, "%%%OK%%%");

            // GET with chunked encoding
            ns = HttpListener2Test.CreateNS(port);
            HttpListener2Test.Send(ns, "GET /HasEntityBody HTTP/1.1\r\nHost: 127.0.0.1\r\nTransfer-Encoding: chunked\r\n\r\n0\r\n");
            ctx     = listener.GetContext();
            request = ctx.Request;
            Assert.IsTrue(request.HasEntityBody, "#G");
            HttpListener2Test.Send(ctx.Response.OutputStream, "%%%OK%%%");

            // PUT with non-zero Content-Lenth
            ns = HttpListener2Test.CreateNS(port);
            HttpListener2Test.Send(ns, "PUT /HasEntityBody/ HTTP/1.1\r\nHost: 127.0.0.1\r\nContent-Length: 3\r\n\r\n123");
            ctx     = listener.GetContext();
            request = ctx.Request;
            Assert.IsTrue(request.HasEntityBody, "#H");

            // PUT with zero Content-Lenth
            ns = HttpListener2Test.CreateNS(port);
            HttpListener2Test.Send(ns, "PUT /HasEntityBody/ HTTP/1.1\r\nHost: 127.0.0.1\r\nContent-Length: 0\r\n\r\n123");
            ctx     = listener.GetContext();
            request = ctx.Request;
            Assert.IsFalse(request.HasEntityBody, "#I");

            // INVALID with non-zero Content-Lenth
            ns = HttpListener2Test.CreateNS(port);
            HttpListener2Test.Send(ns, "INVALID /HasEntityBody/ HTTP/1.1\r\nHost: 127.0.0.1\r\nContent-Length: 3\r\n\r\n123");
            ctx     = listener.GetContext();
            request = ctx.Request;
            Assert.IsTrue(request.HasEntityBody, "#J");

            // INVALID with zero Content-Lenth
            ns = HttpListener2Test.CreateNS(port);
            HttpListener2Test.Send(ns, "INVALID /HasEntityBody/ HTTP/1.1\r\nHost: 127.0.0.1\r\nContent-Length: 0\r\n\r\n123");
            ctx     = listener.GetContext();
            request = ctx.Request;
            Assert.IsFalse(request.HasEntityBody, "#K");

            // INVALID with chunked encoding
            ns = HttpListener2Test.CreateNS(port);
            HttpListener2Test.Send(ns, "INVALID /HasEntityBody/ HTTP/1.1\r\nHost: 127.0.0.1\r\nTransfer-Encoding: chunked\r\n\r\n0\r\n");
            ctx     = listener.GetContext();
            request = ctx.Request;
            Assert.IsTrue(request.HasEntityBody, "#L");

            listener.Close();
        }
Exemplo n.º 16
0
        private static async void StartListener(string prefix)
        {
            if (!HttpListener.IsSupported)
            {
                Console.ForegroundColor = ConsoleColor.DarkMagenta;
                Console.Write("[Heartbeat] ");
                Console.ForegroundColor = ConsoleColor.White;
                Console.Write("Stopping Keep Alive loop.\n");
                Console.ForegroundColor = ConsoleColor.Red;
                Console.Write("[Error] ");
                Console.ForegroundColor = ConsoleColor.White;
                Console.Write("Unsupported Windows Version, stopping.\n");
                HeartbeatTimer.Stop();
                Thread.Sleep(-1);
            }

            CreateDummyFile();

            listener.Prefixes.Add(prefix);

            listener.Start();

            Console.ForegroundColor = ConsoleColor.DarkMagenta;
            Console.Write("[Interium] ");
            Console.ForegroundColor = ConsoleColor.White;
            Console.Write("Started Listener.\n");

            while (true)
            {
                var context = listener.GetContext();
                var request = context.Request;

                var response = context.Response;

                CreateDummyFile();

                var filePath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + @"/KibbeWater/dummy.txt";
                var found    = false;

                if (request.RawUrl.StartsWith("/Update"))
                {
                    response.AddHeader("Content-Type", "application/force-download");
                    response.AddHeader("Content-Disposition", "attachment; filename=dummy.txt");
                    response.AddHeader("Content-Transfer-Encoding", "binary");
                    response.AddHeader("Accept-Ranges", "bytes");

                    response.AddHeader("Cache-Control", "private");
                    response.AddHeader("Pragma", "private");
                    response.AddHeader("Expires", "Mon, 26 Jul 1997 05:00:00 GMT");
                    string responseString = " Success!";
                    byte[] buffer         = File.ReadAllBytes(filePath);
                    response.ContentLength64 = buffer.Length;
                    System.IO.Stream output = response.OutputStream;
                    output.Write(buffer, 0, buffer.Length);
                    output.Close();
                    response.Close();

                    var querys = ParseQueryFromURL(request.RawUrl);

                    if (querys.Count < 1)
                    {
                        return;
                    }

                    var game  = "";
                    var Event = "";
                    var value = 0;
                    var frame = new Dictionary <string, string>();
                    for (int i = 0; i < querys.Count; i++)
                    {
                        var query   = querys[i];
                        var proceed = true;
                        if (query.key.ToLower() == "game")
                        {
                            game    = query.value;
                            proceed = false;
                        }
                        if (query.key.ToLower() == "event")
                        {
                            Event   = query.value;
                            proceed = false;
                        }
                        if (query.key.ToLower() == "value")
                        {
                            value   = Convert.ToInt32(query.value);
                            proceed = false;
                        }
                        if (proceed)
                        {
                            frame.Add(query.key, query.value);
                        }
                    }

                    if (heartbeatData == null)
                    {
                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.Write("[Eror] ");
                        Console.ForegroundColor = ConsoleColor.White;
                        Console.Write("No valid port saved.\n");
                    }
                    else
                    {
                        UpdateEvent(heartbeatData.port, game, Event, value, frame);

                        #if DEBUG
                        Console.ForegroundColor = ConsoleColor.DarkMagenta;
                        Console.Write("[Listener] ");
                        Console.ForegroundColor = ConsoleColor.White;
                        Console.Write("Updating Game Event, " + querys.Count + " Querys.\n");
                        #endif
                    }
                }
                if (request.RawUrl.StartsWith("/Edgebug"))
                {
                    response.AddHeader("Content-Type", "application/force-download");
                    response.AddHeader("Content-Disposition", "attachment; filename=dummy.txt");
                    response.AddHeader("Content-Transfer-Encoding", "binary");
                    response.AddHeader("Accept-Ranges", "bytes");

                    response.AddHeader("Cache-Control", "private");
                    response.AddHeader("Pragma", "private");
                    response.AddHeader("Expires", "Mon, 26 Jul 1997 05:00:00 GMT");
                    string responseString = " Success!";
                    byte[] buffer         = File.ReadAllBytes(filePath);
                    response.ContentLength64 = buffer.Length;
                    System.IO.Stream output = response.OutputStream;
                    output.Write(buffer, 0, buffer.Length);
                    output.Close();
                    response.Close();

                    var querys = ParseQueryFromURL(request.RawUrl);

                    if (querys.Count < 1)
                    {
                        return;
                    }

                    var game     = "";
                    var Event    = "";
                    var value    = 0;
                    var tickrate = 0;
                    var frame    = new Dictionary <string, string>();
                    for (int i = 0; i < querys.Count; i++)
                    {
                        var query   = querys[i];
                        var proceed = true;
                        if (query.key.ToLower() == "game")
                        {
                            game    = query.value;
                            proceed = false;
                        }
                        if (query.key.ToLower() == "event")
                        {
                            Event   = query.value;
                            proceed = false;
                        }
                        if (query.key.ToLower() == "value")
                        {
                            value   = Convert.ToInt32(query.value);
                            proceed = false;
                        }
                        if (query.key.ToLower() == "tickrate")
                        {
                            tickrate = Convert.ToInt32(query.value);
                            proceed  = false;
                        }
                        if (proceed)
                        {
                            frame.Add(query.key, query.value);
                        }
                    }

                    StartFadeTimer(heartbeatData.port, game, Event);
                    #if DEBUG
                    Console.ForegroundColor = ConsoleColor.DarkMagenta;
                    Console.Write("[Listener] ");
                    Console.ForegroundColor = ConsoleColor.White;
                    Console.Write("Updating Game Event, " + querys.Count + " Querys.\n");
                    #endif
                }
            }
        }
        public void Start()
        {
            State     = EntityState.Starting;
            StateName = Enum.GetName(typeof(EntityState), EntityState.Starting);

            _httpListener = new HttpListener();
            ChannelConfigurationInfo channelConfig = _configuration.Configure(_httpListener, _channel, _method, _baseURL);

            Url = channelConfig.MethodUrl;
            //Keep the ChannelMethod open for new requests
            while (true)
            {
                try
                {
                    _httpListener.Start();
                    State     = EntityState.Running;
                    StateName = Enum.GetName(typeof(EntityState), EntityState.Running);
                }
                catch (HttpListenerException hle)
                {
                    Console.WriteLine($"System.Net.HttpListenerException encountered on {channelConfig.MethodUrl} with reason :{hle.Message}");
                    return;
                }

                if (!_isManaged)
                {
                    Console.WriteLine($"Listening on {Url}");
                }

                HttpListenerContext      context       = _httpListener.GetContext();
                HttpListenerRequest      request       = context.Request;
                HttpListenerResponse     response      = context.Response;
                IChannelHeuristicContext heuristicsCtx = _services.Get <IChannelHeuristicContext>();

                LogChannel.Write(LogSeverity.Info, $"Request coming to {channelConfig.Endpoint.Name}");
                LogChannel.Write(LogSeverity.Info, $"HttpMethod:{request.HttpMethod}");

                ChannelAuthenticationInspector authInspector = new ChannelAuthenticationInspector(_authenticationService, _msgService, _settings, _session, _basicAuthenticationMethod, _tokenAuthenticationMethod);

                //Even if method is cached check authenticaion first
                bool authFailed = authInspector.AuthenticationFailedIfRequired(context, request, response, channelConfig, out bool authenticated);
                if (authFailed)
                {
                    goto EndRequest;
                }

                List <object> channelRequestBody = null;

                ChannelMethodCacheInspector cacheInspector       = new ChannelMethodCacheInspector(_msgService, _heuristics);
                CacheExecutionResult        cacheExecutionResult = cacheInspector.ExecuteIfCached(_channel, _method, request, response, heuristicsCtx);

                if (cacheExecutionResult.Executed)
                {
                    heuristicsCtx.Clear();
                    goto EndRequest;
                }

                if (channelConfig.HttpMethod.ToString() != request.HttpMethod && channelConfig.HttpMethod != ChannelHttpMethod.Unknown)
                {
                    _msgService.WrongHttpMethod(response, channelConfig.HttpMethod);
                    LogChannel.Write(LogSeverity.Error, "Wrong HttpMethod... Closing request");
                    goto EndRequest;
                }

                ChannelMethodInfo   methodDescription   = _channelMethodDescriptor.GetMethodDescription(_method);
                ChannelMethodCaller channelMethodCaller = new ChannelMethodCaller(_msgService, _contextProvider, _requestActivator);

                if (request.HttpMethod == "GET")
                {
                    channelMethodCaller.TryInvokeGetRequest(_channel, _method, request, response, methodDescription, channelConfig, channelRequestBody, authenticated, cacheExecutionResult);
                    goto EndRequest;
                }

                //Enter only if Request Body is supplied with POST Method
                if (request.HasEntityBody == true && request.HttpMethod == "POST")
                {
                    channelMethodCaller.TryInvokePostRequest(_channel, _method, request, response, channelRequestBody, methodDescription, channelConfig, authenticated, cacheExecutionResult);
                }

EndRequest:
                LogChannel.Write(LogSeverity.Debug, "Request finished...");
                LogChannel.Write(LogSeverity.Debug, "Closing the response");
                response.Close();
            }
        }
Exemplo n.º 18
0
        private void GetAccessToken(string redirectUrl, Action <string, string, string> onTokenReceived, Action onError)
        {
            new Thread(async() =>
            {
                try
                {
                    if (listener == null || !listener.IsListening)
                    {
                        listener = new HttpListener();
                        listener.Prefixes.Add("http://*:8182/");
                        listener.Start();
                    }

                    try
                    {
                        while (true)
                        {
                            var context = listener.GetContext();
                            var req     = context.Request;
                            var res     = context.Response;

                            if (req.Url.ToString().Contains("twitchredirect"))
                            {
                                res.Redirect(redirectUrl);
                                res.Close();
                            }
                            else
                            {
                                var state       = req.QueryString["state"];
                                var accessToken = req.QueryString["token"];

                                var user   = req.QueryString["user"];
                                var userId = req.QueryString["id"];

                                if (string.IsNullOrEmpty(user))
                                {
                                    var result = await ValidateOAuthAsync(accessToken);
                                    if (result != null)
                                    {
                                        user   = result.Login;
                                        userId = result.UserID;
                                    }
                                }

                                onTokenReceived(accessToken, user, userId);
                                res.StatusCode = 200;
                                res.Close();
                                return;
                            }
                        }
                    }
                    catch (Exception exc)
                    {
                        Console.WriteLine(exc);
                        onError?.Invoke();

                        Console.WriteLine("You need to run RavenBot.exe as administrator.");
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                    onError?.Invoke();

                    Console.WriteLine("You need to run RavenBot.exe as administrator.");
                }
            }).Start();
        }
Exemplo n.º 19
0
        private void HttpRun()
        {
            http_listener = new HttpListener();

            string prefix  = null;
            int    port    = 4000;
            bool   success = false;
            string host    = "localhost";

            if (enable_network_svc)
            {
                host = "*";
            }

            do
            {
                prefix  = String.Format("http://{0}:{1}/", host, port);
                success = true;

                try {
                    http_listener.Prefixes.Add(prefix);
                    http_listener.Start();
                } catch (SocketException) {
                    http_listener.Prefixes.Remove(prefix);
                    success = false;
                    port++;
                }
            } while (!success);

            Shutdown.WorkerStart(this.http_listener, String.Format("HTTP Server '{0}'", prefix));
            Log.Always("HTTP Server: Listening on {0}", prefix);

            while (this.running)
            {
                HttpListenerContext context = null;

                try {
                    context = http_listener.GetContext();
                } catch (Exception e) {
                    // Log a warning if not due to shutdown
                    if (!this.running ||
                        (!this.enable_network_svc && !this.webinterface))
                    {
                        break;
                    }
                    Logger.Log.Warn(e, "HTTP Server: Exception while getting context:");
                }

                if (context == null)
                {
                    continue;
                }

                if (context.Request.HttpMethod == "GET")
                {
                    try {
                        WebServer.HandleStaticPages(context);
                    } catch (IOException ex1) {
                        // Socket was shut down
                        Log.Debug("Exception while serving static page: " + ex1.Message);
                        // FIXME: Should anything be done here to free "context" ? This context seems to remain in http_listener's ctxt table
                    } catch (SocketException ex2) {
                        // Socket is not connected anymore
                        Log.Debug("Exception while serving static page: " + ex2.Message);
                    }
                    continue;
                }

                if (context.Request.HttpMethod != "POST")
                {
                    // FIXME: Send better HTTP error ?
                    context.Response.StatusCode = 404;
                    context.Response.Close();
                    continue;
                }

                if (context.Request.RawUrl == "/")
                {
                    // We have received a new query request
                    Guid            guid         = Guid.NewGuid();
                    HttpItemHandler item_handler = new HttpItemHandler();
                    item_handlers [guid] = item_handler;

                    ConnectionHandler handler = new HttpConnectionHandler(guid, context, item_handler);

                    lock (live_handlers)
                        live_handlers [handler] = handler;

                    ExceptionHandlingThread.Start(new ThreadStart(handler.HandleConnection));
                }
                else
                {
                    // We have received a hit request
                    Uri    uri  = context.Request.Url;
                    string path = null;

                    // Second Uri segment contains the Guid
                    string g = uri.Segments [1];

                    if (g [g.Length - 1] == '/')
                    {
                        g = g.Remove(g.Length - 1, 1);
                    }

                    Guid guid = Guid.Empty;

                    try {
                        guid = new Guid(g);
                    } catch (FormatException) {
                        // FIXME: return HTTP error
                        Logger.Log.Debug("HTTP Server: Invalid query guid '{0}'", g);
                        context.Response.Close();
                        continue;
                    }

                    if (uri.Query.Length > 0)
                    {
                        path = uri.Query.Remove(0, 1);
                    }
                    else
                    {
                        // FIXME: return HTTP error
                        Logger.Log.Debug("HTTP Server: Empty query string in item request");
                        context.Response.Close();
                        continue;
                    }

                    System.Uri      item_uri = new Uri(path);
                    HttpItemHandler handler  = (HttpItemHandler)item_handlers [guid];

                    if (handler == null)
                    {
                        // FIXME: return HTTP error
                        Logger.Log.Debug("HTTP Server: Query ({0}) does not exist", g);
                        context.Response.Close();
                    }
                    else
                    {
                        Logger.Log.Debug("HTTP Server: Asked for item '{0}' on query '{1}'", path, g);
                        handler.HandleRequest(context, item_uri);
                    }
                }
            }


            Shutdown.WorkerFinished(http_listener);
            Logger.Log.Info("HTTP Server: '{0}' shut down...", prefix);
            http_listener = null;
        }
Exemplo n.º 20
0
        void mainWebserver()
        {
            //start status checking thread
            ThreadStart tmaxCheckerStarter = delegate { status(); };

            Thread tmaxChecker = new Thread(tmaxCheckerStarter);

            tmaxChecker.Start();

            LogEvent("TmaxChecker thread started", EventLogEntryType.Information);

            //start status check listener
            ThreadStart listnerStatusStarter = delegate { statusListener(); };

            Thread listenerStatusThread = new Thread(listnerStatusStarter);

            listenerStatusThread.Start();

            LogEvent("Listener Status Thread started", EventLogEntryType.Information);

            HttpListener listener = new HttpListener();

            listener.Prefixes.Add("http://*:4567/");

            while (true)
            {
                try
                {
                    listener.Start();
                    //LogEvent("Listener 4567 started", EventLogEntryType.Information);

                    //System.Threading.Thread.Sleep(100);

                    HttpListenerContext context = listener.GetContext();
                    HttpListenerRequest request = context.Request;
                    context.Response.AppendHeader("Access-Control-Allow-Origin", "*");
                    context.Response.StatusCode = 400;

                    string   url       = context.Request.RawUrl;
                    string   no_host   = url.Remove(0, 1);
                    string[] url_array = no_host.Split('/');

                    int command = 0;// default if none given

                    try
                    {
                        command = Int32.Parse(url_array[0]);
                    }
                    catch
                    {
                        //TODO catch code
                    }

                    if (command == 0)
                    {
                        context.Response.ContentType = "text/html";
                        byte[] buffer = Encoding.UTF8.GetBytes("555.55.555");
                        context.Response.ContentLength64 = buffer.Length;
                        using (Stream s = context.Response.OutputStream)
                            s.Write(buffer, 0, buffer.Length);
                    }
                    else if (command == 1)
                    {
                        int bed = 0;
                        int min = 0;
                        int dla = 3;

                        try
                        {
                            bed = Int32.Parse(url_array[1]);
                            min = Int32.Parse(url_array[2]);
                            dla = Int32.Parse(url_array[3]);
                        }
                        catch
                        {
                            //TODO catch code
                        }

                        threadStop.Reset();           //stop listnerStatusThread from checking tmax status

                        mainThreadStop.WaitOne(1000); //wait until oThread tmax.status in progress completes or 1 sec passes

                        if (tmax.activate((byte)(bed), (byte)(min), (byte)(dla)))
                        {
                            context.Response.StatusCode = 201;
                        }

                        threadStop.Set();//resume oThread checking tmax.status
                    }
                    else if (command == 2)
                    {
                        int bed = 0;

                        try
                        {
                            bed = Int32.Parse(url_array[1]);
                        }
                        catch
                        {
                            //TODO catch code
                        }

                        threadStop.Reset();           //stop listnerStatusThread from checking tmax status

                        mainThreadStop.WaitOne(1000); //wait until oThread tmax.status in progress completes or 1 sec passes

                        if (tmax.activate((byte)(bed), 0, 0))
                        {
                            context.Response.StatusCode = 201;
                        }

                        threadStop.Set();//resume oThread checking tmax.status
                    }

                    context.Response.Close();
                }
                catch (Exception e)
                {
                    LogEvent("Main Webserver 4567 Error. " + e, EventLogEntryType.Error);
                }
            }
        }
Exemplo n.º 21
0
        static void statusListener()
        {
            HttpListener listener = new HttpListener();

            listener.Prefixes.Add("http://*:4568/");

            while (true)
            {
                try
                {
                    listener.Start();
                    //LogEvent("Listener 4568 started", EventLogEntryType.Information);

                    //System.Threading.Thread.Sleep(100);

                    HttpListenerContext context = listener.GetContext();
                    HttpListenerRequest request = context.Request;
                    context.Response.AppendHeader("Access-Control-Allow-Origin", "*");
                    context.Response.ContentType = "text/javascript";
                    context.Response.StatusCode  = 200;

                    string   url       = context.Request.RawUrl;
                    string   no_host   = url.Remove(0, 1);
                    string[] url_array = no_host.Split('/');

                    int number_of_beds = 15;// default if none given

                    try
                    {
                        number_of_beds = Int32.Parse(url_array[0]);
                    }
                    catch
                    {
                        context.Response.StatusCode = 400;
                    }

                    int[] stbuff = tmax.status_buffer_accessor();

                    /*foreach (int st in stbuff)
                     * {
                     *  Console.Write(st.ToString() + " ");
                     * }*/

                    List <int> status = new List <int>();

                    for (int i = 6; i < number_of_beds + 6; i++) //length determined by number of beds
                    {
                        status.Add(stbuff[i]);
                    }

                    //Console.WriteLine("[]");

                    int[] tbuff = tmax.time_buffer_accessor();

                    /*foreach (int t in tbuff)
                     * {
                     *  Console.Write(t.ToString() + " ");
                     * }*/

                    List <int> time = new List <int>();

                    for (int i = 6; i < (number_of_beds * 2 + 6); i += 2) //length determined by number of beds
                    {
                        time.Add(tbuff[i] + tbuff[i + 1] * 256);          //255 or 256 not sure
                    }

                    List <string> time_status = new List <string>();

                    for (int i = 0; i < number_of_beds; i++)
                    {
                        string n = (i + 1).ToString();
                        string s = status[i].ToString();
                        string t = time[i].ToString();

                        time_status.Add("{\"number\": \"" + n + "\", \"status\": \"" + s + "\", \"time\": " + t + "}");
                    }

                    string time_status_string = string.Join(",", time_status.ToArray());

                    time_status_string = "[" + time_status_string + "]";

                    byte[] buffer = Encoding.UTF8.GetBytes(time_status_string);
                    context.Response.ContentLength64 = buffer.Length;
                    using (Stream s = context.Response.OutputStream)
                        s.Write(buffer, 0, buffer.Length);

                    //Console.WriteLine("\n status inquiry");

                    context.Response.Close();
                }
                catch (Exception e)
                {
                    LogEvent("Status Listener 4568 Error " + e, EventLogEntryType.Error);
                }
            }
        }
Exemplo n.º 22
0
        public Task Start()
        {
            return(Task.Run(() =>
            {
                _listener = new HttpListener();

                _listener.Prefixes.Add($"http://*****:*****@"^\/(\d+)?$"))
                            {
                                var pageID = context.Request.RawUrl == "/" ? 0 : int.Parse(context.Request.RawUrl.Substring(1));

                                var page = context.Request.HttpMethod == "GET" ?
                                           _db.GetCollection($"$dump({pageID})").Query().FirstOrDefault() :
                                           GetPost(context.Request.InputStream);

                                if (page == null)
                                {
                                    body = $"Page {pageID} not found in database";
                                }
                                else
                                {
                                    var dump = new HtmlPageDump(page);

                                    body = dump.Render();
                                }
                            }
                            else if (Regex.IsMatch(context.Request.RawUrl, @"^\/list/(\d+)$"))
                            {
                                var pageID = int.Parse(context.Request.RawUrl.Substring(6));
                                var exp = new HtmlPageList(_db.GetCollection($"$page_list({pageID})").Query().Limit(1000).ToEnumerable());

                                body = exp.Render();
                            }
                            else
                            {
                                body = "Url not found";
                                status = 404;
                            }

                            var message = Encoding.UTF8.GetBytes(body);

                            context.Response.StatusCode = status;
                            context.Response.ContentType = "text/html";
                            context.Response.ContentLength64 = message.Length;
                            context.Response.OutputStream.Write(message, 0, message.Length);
                        });
                    }
                    catch (Exception)
                    {
                    }
                }
            }));
        }
Exemplo n.º 23
0
        // This example requires the System and System.Net namespaces.
        public static void SimpleListenerExample(string[] prefixes)
        {
            bool isrunning = true;

            if (!HttpListener.IsSupported)
            {
                Console.WriteLine("Windows XP SP2 or Server 2003 is required to use the HttpListener class.");
                return;
            }
            // URI prefixes are required,
            // for example "http://contoso.com:8080/index/".
            if (prefixes == null || prefixes.Length == 0)
            {
                throw new ArgumentException("prefixes");
            }

            // Create a listener.
            HttpListener listener = new HttpListener();

            // Add the prefixes.
            foreach (string s in prefixes)
            {
                listener.Prefixes.Add(s);
            }
            listener.Start();
            Console.WriteLine("Listening...");
            System.IO.Stream output = null;
            while (isrunning)
            {
                try
                {
                    // Note: The GetContext method blocks while waiting for a request.
                    HttpListenerContext context = listener.GetContext();
                    string url = context.Request.RawUrl;
                    if (url == "/" || url == "/favicon.ico")
                    {
                        url = "\\index.html";
                    }
                    string fileExtension        = url.Substring(url.LastIndexOf("."));
                    HttpListenerRequest request = context.Request;
                    // Obtain a response object.
                    HttpListenerResponse response = context.Response;
                    // Construct a response.
                    //string responseString = "<HTML><BODY> Hello dsfdsfsfsffsdfFarid!</BODY></HTML>";
                    //int length = responseString.Length;
                    byte[] buffer = GetView(url);
                    //byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
                    // Get a response stream and write the response to it.
                    response.ContentLength64 = buffer.Length;
                    response.AddHeader("Content-type", _mimeTypeMappings[fileExtension]);
                    output = response.OutputStream;

                    output.Write(buffer, 0, buffer.Length);
                    // You must close the output stream.
                }
                catch (Exception e)
                {
                    isrunning = false;
                    Console.WriteLine(e);
                }
                finally
                {
                    if (output != null)
                    {
                        output.Close();
                    }
                }
            }
            listener.Stop();
        }
Exemplo n.º 24
0
 public void httplisten()
 {
     try
     {
         while (true)
         {
             listener.Start();
             HttpListenerContext context = listener.GetContext();
             HttpListenerRequest request = context.Request;
             StreamReader        input   = new StreamReader(request.InputStream, request.ContentEncoding);
             string kvpair = input.ReadToEnd();
             if (kvpair.Contains("="))
             {
                 string action = kvpair.Split('=')[0];
                 if (action == "stop")
                 {
                     StopAtNext = true;
                     MyConsole.WriteLine("#" + CurrentFile + ": Stopping Bot after dataset.");
                 }
                 else if (action == "start")
                 {
                     StopAtNext = false;
                     if (!TrimBot.IsAlive)
                     {
                         MyConsole.WriteLine("#" + CurrentFile + ": Restarting Bot.");
                         Start();
                     }
                     else
                     {
                         MyConsole.WriteLine("#" + (CurrentFile + 1) + ": Restarting Bot at dataset.");
                     }
                 }
                 else if (action == "refresh")
                 {
                     int curLine = int.Parse(kvpair.Split('=')[1]);
                     HttpListenerResponse response = context.Response;
                     byte[] buffer = Encoding.UTF8.GetBytes("{ \"text\" : \"" + MyConsole.GetHTML(curLine) + "\", \"curLine\" : " + MyConsole.Lines.Count + ", \"curSet\" : " + CurrentFile + ", \"numcrash\" : " + Crashes + ", \"time\" : \"" + calcRestTime() + "\"}");
                     response.ContentLength64 = buffer.Length;
                     Stream output = response.OutputStream;
                     output.Write(buffer, 0, buffer.Length);
                     output.Close();
                     listener.Stop();
                 }
             }
             else
             {
                 HttpListenerResponse response = context.Response;
                 XmlDocument          html     = new XmlDocument();
                 html.LoadXml(Properties.Resources.template);
                 XmlNode curLineSpan = html.SelectSingleNode("//span[@id='curLineSpan']");
                 XmlNode dataset     = html.SelectSingleNode("//p[@id='dataset']");
                 XmlNode crashes     = html.SelectSingleNode("//p[@id='crashes']");
                 XmlNode console     = html.SelectSingleNode("//div[@id='console']");
                 XmlNode button      = html.SelectSingleNode("//div[@id='button']");
                 XmlNode time        = html.SelectSingleNode("//p[@id='time']");
                 XmlNode script      = html.SelectSingleNode("//script[@type='text/javascript']");
                 curLineSpan.InnerText = MyConsole.Lines.Count.ToString();
                 dataset.InnerText     = "Current dataset: #" + Properties.Settings.Default.progress;
                 crashes.InnerText     = "Number of crashes: " + Crashes;
                 console.InnerXml      = MyConsole.GetHTML(0);
                 time.InnerText        = calcRestTime();
                 XmlAttribute btnAttr1 = html.CreateAttribute("class");
                 XmlAttribute btnAttr2 = html.CreateAttribute("onclick");
                 if (StopAtNext)
                 {
                     btnAttr1.Value = "start";
                     btnAttr2.Value = "start();";
                 }
                 else
                 {
                     btnAttr1.Value = "stop";
                     btnAttr2.Value = "stop();";
                 }
                 button.Attributes.Append(btnAttr1);
                 button.Attributes.Append(btnAttr2);
                 script.InnerText = Properties.Resources.script;
                 byte[] buffer = Encoding.UTF8.GetBytes(html.OuterXml);
                 response.ContentLength64 = buffer.Length;
                 Stream output = response.OutputStream;
                 output.Write(buffer, 0, buffer.Length);
                 output.Close();
                 listener.Stop();
             }
         }
     }
     catch (Exception exc)
     {
         listener.Stop();
         WebBot.Abort();
     }
 }
Exemplo n.º 25
0
        static void Main(string[] args)
        {
            // WARNING!!!
            // Application should have administrator rights otherwise "listener.Start();" throws an exception.
            try
            {
                HttpListener listener = new HttpListener();
                listener.Prefixes.Add(LicenseServerData.LICENSE_GENERATOR_SERVER_URI);
                listener.Start();
                Console.WriteLine("Waiting for connections...");

                long connectionsCount = 0;
                while (true)
                {
                    ++connectionsCount;

                    HttpListenerContext  context  = listener.GetContext();
                    HttpListenerRequest  request  = context.Request;
                    HttpListenerResponse response = context.Response;

                    // Display request and parse parameters.
                    Console.WriteLine("\nConnection #{0}\nQuery: {1}", connectionsCount, request.Url);
                    string strUsername     = string.Empty;
                    string strPassword     = string.Empty;
                    string strEthAddr      = string.Empty;
                    string strGUID         = string.Empty;
                    string strEndDate      = string.Empty;
                    string strPlatformID   = string.Empty;
                    string strWinMajor     = string.Empty;
                    string strWinMinor     = string.Empty;
                    string strExcelVersion = string.Empty;
                    string strPath         = string.Empty;
                    foreach (var queryKey in context.Request.QueryString.Keys)
                    {
                        if (queryKey == null)
                        {
                            continue;
                        }

                        string strQueryKey = queryKey.ToString();
                        if (string.IsNullOrEmpty(strQueryKey))
                        {
                            continue;
                        }

                        object queryValue    = context.Request.QueryString[strQueryKey];
                        string strQueryValue = string.Empty;
                        if (queryValue != null)
                        {
                            strQueryValue = queryValue.ToString();
                        }

                        Console.WriteLine("{0} = {1}", strQueryKey, strQueryValue);

                        if (strQueryKey == LicenseServerData.PARAM_USERNAME)
                        {
                            strUsername = strQueryValue;
                        }
                        else if (strQueryKey == LicenseServerData.PARAM_PASSWORD)
                        {
                            strPassword = strQueryValue;
                        }
                        else if (strQueryKey == LicenseServerData.PARAM_ETHERNET_ADDRESS)
                        {
                            strEthAddr = strQueryValue;
                        }
                        else if (strQueryKey == LicenseServerData.PARAM_GUID)
                        {
                            strGUID = strQueryValue;
                        }
                        else if (strQueryKey == LicenseServerData.PARAM_END_DATE)
                        {
                            strEndDate = strQueryValue;
                        }
                        else if (strQueryKey == LicenseServerData.PARAM_PLATFORM_ID)
                        {
                            strPlatformID = strQueryValue;
                        }
                        else if (strQueryKey == LicenseServerData.PARAM_WINVER_MAJOR)
                        {
                            strWinMajor = strQueryValue;
                        }
                        else if (strQueryKey == LicenseServerData.PARAM_WINVER_MINOR)
                        {
                            strWinMinor = strQueryValue;
                        }
                        else if (strQueryKey == LicenseServerData.PARAM_EXCEL_VERSION)
                        {
                            strExcelVersion = strQueryValue;
                        }
                    }

                    // Try to create license.
                    LicenseData licenseData = new LicenseData();
                    licenseData.Username        = strUsername;
                    licenseData.Password        = strPassword;
                    licenseData.EthernetAddress = strEthAddr;
                    licenseData.GUID            = strGUID;
                    //
                    if (string.IsNullOrEmpty(strEndDate))
                    {
                        licenseData.IncludeDate = false;
                    }
                    else
                    {
                        licenseData.IncludeDate = true;
                        try
                        {
                            licenseData.CanRunTill = Convert.ToDateTime(strEndDate);
                        }
                        catch (Exception ex)
                        {
                            response.StatusCode        = (int)HttpStatusCode.BadRequest;
                            response.StatusDescription = "Incorrect parameters.";
                            response.OutputStream.Close();

                            Console.WriteLine("ERROR, cant parse \"end_date\" parameter: " + ex.Message);
                            continue;
                        }
                    }
                    //
                    licenseData.PlatformID          = strPlatformID;
                    licenseData.WindowsVersionMajor = strWinMajor;
                    licenseData.WindowsVersionMinor = strWinMinor;
                    licenseData.ExcelVersion        = strExcelVersion;

                    // Try to create license file in the assembly directory.
                    string assemblyFolder  = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
                    string licenseFilePath = assemblyFolder + "\\RackDrawingAppLicense.lic";
                    string strError;
                    bool   bError = !LicenseUtilities.sCreateLicense(licenseData, licenseFilePath, out strError);

                    // Send license file in response.
                    if (!bError)
                    {
                        using (FileStream fs = File.OpenRead(licenseFilePath))
                        {
                            string filename = Path.GetFileName(licenseFilePath);
                            //response is HttpListenerContext.Response...
                            response.ContentLength64 = fs.Length;
                            response.SendChunked     = false;
                            response.ContentType     = System.Net.Mime.MediaTypeNames.Application.Octet;
                            response.AddHeader("Content-disposition", "attachment; filename=" + filename);

                            byte[] buffer = new byte[64 * 1024];
                            int    read;
                            using (BinaryWriter bw = new BinaryWriter(response.OutputStream))
                            {
                                while ((read = fs.Read(buffer, 0, buffer.Length)) > 0)
                                {
                                    bw.Write(buffer, 0, read);
                                    bw.Flush();                                     //seems to have no effect
                                }

                                bw.Close();
                            }

                            response.StatusCode        = (int)HttpStatusCode.OK;
                            response.StatusDescription = "OK";
                            response.OutputStream.Close();
                        }

                        Console.WriteLine("SUCCESS. License file was sent.");
                    }
                    else
                    {
                        response.StatusCode        = (int)HttpStatusCode.BadRequest;
                        response.StatusDescription = "Incorrect parameters.";
                        response.OutputStream.Close();

                        Console.WriteLine("ERROR. " + strError);
                    }

                    File.Delete(licenseFilePath);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("ERROR: " + ex.Message);
                Console.WriteLine("Press any key...");
                Console.ReadKey();
            }
        }
Exemplo n.º 26
0
        private static void GetPacList(object config)
        {
            var cfg  = config as Config;
            var port = Global.sysAgentPort;

            if (port <= 0)
            {
                return;
            }
            var proxy = string.Format("PROXY 127.0.0.1:{0};", port);

            while (pacLinstener != null && pacLinstener.IsListening)
            {
                HttpListenerContext requestContext = null;
                try
                {
                    requestContext = pacLinstener.GetContext(); //接受到新的请求
                    //reecontext 为开启线程传入的 requestContext请求对象
                    Thread subthread = new Thread(new ParameterizedThreadStart((reecontext) =>
                    {
                        requestContext.Response.StatusCode      = 200;
                        requestContext.Response.ContentType     = "application/x-ns-proxy-autoconfig";
                        requestContext.Response.ContentEncoding = Encoding.UTF8;
                        string strPacFile = Utils.GetPath(PAC_FILE);
                        if (!File.Exists(strPacFile))
                        {
                            //TODO:暂时没解决更新PAC列表的问题,用直接解压现有PAC解决
                            //new PACListHandle().UpdatePACFromGFWList(cfg);
                            FileManager.UncompressFile(strPacFile, Resources.pac_txt);
                        }
                        var pac       = File.ReadAllText(strPacFile, Encoding.UTF8);
                        pac           = pac.Replace("__PROXY__", proxy);
                        byte[] buffer = System.Text.Encoding.UTF8.GetBytes(pac);
                        //对客户端输出相应信息.
                        requestContext.Response.ContentLength64 = buffer.Length;
                        System.IO.Stream output = requestContext.Response.OutputStream;
                        output.Write(buffer, 0, buffer.Length);
                        //关闭输出流,释放相应资源
                        output.Close();
                    }));
                    subthread.Start(requestContext); //开启处理线程处理下载文件
                }
                catch (HttpListenerException)
                {
                    continue;
                }
                catch (Exception ex)
                {
                    try
                    {
                        requestContext.Response.StatusCode      = 500;
                        requestContext.Response.ContentType     = "application/text";
                        requestContext.Response.ContentEncoding = Encoding.UTF8;
                        byte[] buffer = System.Text.Encoding.UTF8.GetBytes("System Error");
                        //对客户端输出相应信息.
                        requestContext.Response.ContentLength64 = buffer.Length;
                        System.IO.Stream output = requestContext.Response.OutputStream;
                        output.Write(buffer, 0, buffer.Length);
                        //关闭输出流,释放相应资源
                        output.Close();
                    }
                    catch
                    {
                    }
                }
            }
        }
Exemplo n.º 27
0
        private void startHttpThread()
        {
            using (HttpListener listerner = new HttpListener())
            {
                listerner.AuthenticationSchemes = AuthenticationSchemes.Anonymous;//指定身份验证 Anonymous匿名访问
                listerner.Prefixes.Add("http://127.0.0.1:" + port + "/report/");

                listerner.Start();

                log.Info("WebServer Start Successed.......");
                PrinterControl printerControl = new PrinterControl();
                var            reportTemplate = string.Empty;
                while (true)
                {
                    //等待请求连接
                    //没有请求则GetContext处于阻塞状态

                    HttpListenerContext ctx = listerner.GetContext();
                    string callback         = string.Empty;
                    try
                    {
                        log.Info("开始处理请求…… ");
                        Uri url = ctx.Request.Url;
                        ctx.Response.StatusCode  = 200;//设置返回给客服端http状态代码
                        ctx.Response.ContentType = "application/json";
                        Dictionary <string, string> parm = getData(ctx);
                        if (parm.Count > 0)
                        {
                            var printUrl = parm["url"].ToString().Trim();
                            callback = parm["callback"].ToString().Trim();
                            log.Info(printUrl + ":   " + printUrl);
                            var postData = parm["postData"].ToString().Trim();
                            log.Info(postData + ":   " + postData);
                            var cookieStr = parm["cookieStr"].ToString().Trim();
                            log.Info(cookieStr + ":   " + cookieStr);
                            var printerParams = parm["printerParams"].ToString().Trim();
                            log.Info(printerParams + ":   " + printerParams);
                            var charset = parm["charset"].ToString().Trim();
                            log.Info(charset + ":   " + charset);
                            reportTemplate = parm["_report"].ToString().Trim();
                            log.Info(reportTemplate + ":   " + reportTemplate);
                            SetPrint(sysIniPath, reportTemplate);
                            PrinterSettings settings = new PrinterSettings();
                            //settings.DefaultPageSettings.PaperSize.Kind= System.Drawing.Printing.PaperKind.Custom;
                            //1.设置打印机名称
                            settings.PrinterName = INIHepler.INIGetStringValue(sysIniPath, reportTemplate, reportTemplate, null);
                            //2.设置打印机打印方向
                            settings.DefaultPageSettings.Landscape = Convert.ToBoolean(INIHepler.INIGetStringValue(sysIniPath, reportTemplate, "SetLandscape", null));
                            //3.设置纸张

                            //settings.DefaultPageSettings.PaperSize.PaperName = INIHepler.INIGetStringValue(sysIniPath, reportTemplate, "SetPaperName", null);


                            //纸张高度
                            var SetPaperHeight = INIHepler.INIGetStringValue(sysIniPath, reportTemplate, "SetPaperHeight", 0 + "");
                            //纸张宽度
                            var SetPaperWidth = INIHepler.INIGetStringValue(sysIniPath, reportTemplate, "SetPaperWidth", 0 + "");

                            PaperSize paperSize = new PaperSize(reportTemplate, Convert.ToInt32(SetPaperWidth), Convert.ToInt32(SetPaperHeight));
                            settings.DefaultPageSettings.PaperSize = paperSize;



                            //4下边距
                            var SetMarginsBottom = INIHepler.INIGetStringValue(sysIniPath, reportTemplate, "SetMarginsBottom", 0 + "");
                            //5上边距
                            var SetMarginsTop = INIHepler.INIGetStringValue(sysIniPath, reportTemplate, "SetMarginsTop", 0 + "");
                            //6左边距
                            var SetMarginsLeft = INIHepler.INIGetStringValue(sysIniPath, reportTemplate, "SetMarginsLeft", 0 + "");
                            //7右边距
                            var SetMarginsRight = INIHepler.INIGetStringValue(sysIniPath, reportTemplate, "SetMarginsRight", 0 + "");
                            //8------设置边距
                            Margins margins = new Margins();
                            margins.Bottom = Convert.ToInt32(SetMarginsBottom);
                            margins.Top    = Convert.ToInt32(SetMarginsTop);
                            margins.Left   = Convert.ToInt32(SetMarginsLeft);
                            margins.Right  = Convert.ToInt32(SetMarginsRight);
                            settings.DefaultPageSettings.Margins = margins;
                            var result = printerControl.SilentPrint(printUrl, postData, cookieStr, printerParams, charset, settings);
                            log.Info("本地打印服务调用打印操作:" + result);
                            using (StreamWriter writer = new StreamWriter(ctx.Response.OutputStream))
                            {
                                // writer.WriteLine(result);
                                writeJS(writer, result.ToString(), callback);
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        if (ctx != null)
                        {
                            ctx.Response.StatusCode = 500;//设置返回给客服端http状态代码
                            using (StreamWriter writer = new StreamWriter(ctx.Response.OutputStream))
                            {
                                writeJS(writer, "{status:'error',msg:'" + e.StackTrace + "'}", callback);
                                log.Info("调用本地打印服务出现异常" + e.StackTrace + "*******" + e.Message + "*******" + e.InnerException.StackTrace);
                            }
                        }
                    }
                }
            }
        }
Exemplo n.º 28
0
        private void StartRequestHandler(HttpListener listener)
        {
#pragma warning disable EPC13 // Suspiciously unobserved result.
            Task.Run(
                () =>
            {
                while (listener.IsListening)
                {
                    // Note: The GetContext method blocks while waiting for a request.
                    var context  = listener.GetContext();
                    var fileName = Path.GetFileName(context.Request.Url.LocalPath);
                    var response = context.Response;

                    byte[] worldBuffer    = System.Text.Encoding.UTF8.GetBytes("Hello World");
                    byte[] galaxyBuffer   = System.Text.Encoding.UTF8.GetBytes("Hello Galaxy");
                    byte[] universeBuffer = System.Text.Encoding.UTF8.GetBytes("Hello Universe");

                    switch (Path.GetExtension(fileName))
                    {
                    case ".zip":
                        MemoryStream outputMemStream = new MemoryStream();
                        ZipOutputStream zipStream    = new ZipOutputStream(outputMemStream);

                        zipStream.SetLevel(5);

                        AddFile(zipStream, "world", worldBuffer);
                        AddFile(zipStream, "galaxy", galaxyBuffer);
                        AddFile(zipStream, "multi/universe", universeBuffer);

                        zipStream.IsStreamOwner = false;
                        zipStream.Close();

                        outputMemStream.Position = 0;
                        response.ContentLength64 = outputMemStream.Length;
                        StreamUtils.Copy(outputMemStream, response.OutputStream, new byte[4096]);
                        break;

                    case ".404":
                        response.StatusCode      = 404;
                        response.ContentLength64 = worldBuffer.Length;
                        response.OutputStream.Write(worldBuffer, 0, worldBuffer.Length);
                        break;

                    case ".txt":
                        var buffer = m_useGalaxyInsteadOfWorldFromServer
                                    ? galaxyBuffer
                                    : worldBuffer;
                        response.ContentLength64 = buffer.Length;
                        response.OutputStream.Write(buffer, 0, buffer.Length);
                        break;

                    default:
                        Assert.True(false, "Unexpected http request..");
                        break;
                    }


                    // Write buffer and close request
                    response.Headers.Add("Content-type: application/octet-stream");
                    response.Headers.Add("Content-Description: File Transfer");
                    response.Headers.Add($"Content-Disposition: attachment; filename=\"{fileName}\")");
                    response.OutputStream.Close();

                    m_webRequestCount++;
                }
            });
#pragma warning restore EPC13 // Suspiciously unobserved result.
        }
Exemplo n.º 29
0
 public IHttpContext GetContext()
 {
     return(new HttpContextWrapper(_httpListener.GetContext()));
 }
Exemplo n.º 30
0
	private void Listen()
	{
		_listener = new HttpListener();
		_listener.Prefixes.Add("http://*:" + _port.ToString() + "/");
		_listener.Start();
		while (true)
		{
			try
			{
				HttpListenerContext context = _listener.GetContext();
				Process(context);
			}
			catch (Exception ex)
			{
				UnityEngine.Debug.Log(ex);
			}
		}
	}
Exemplo n.º 31
0
        /// <summary>
        /// Starts the http server. Internally, one async task is used for all requests.
        /// </summary>
        public void Start()
        {
            if (_isRunning)
            {
                return;
            }

            if (!HttpListener.IsSupported)
            {
                Console.WriteLine("ERROR! Windows XP SP2 or Server 2003 is required to use the HttpListener class.");
                return;
            }

            if (_prefix == null)
            {
                Console.WriteLine("ERROR! prefix missing");
                return;
            }

            try
            {
                _listener = new HttpListener();
                _listener.Prefixes.Add(_prefix);
                _listener.Start();

                _isRunning = true;
            }
            catch (HttpListenerException ex)
            {
                Console.WriteLine("ERROR! http listener at {0} could not be started", _prefix);
                Console.WriteLine("make sure the user has the rights for this port or run as administrator");
                Console.WriteLine(ex);

                _isRunning = false;
            }

            if (_isRunning)
            {
                Console.WriteLine("started at " + _prefix);

                Task.Factory.StartNew(() =>
                {
                    while (!_isStopping)
                    {
                        var context  = _listener.GetContext();
                        var request  = context.Request;
                        var response = context.Response;

                        //Console.WriteLine("KeepAlive: {0}", request.KeepAlive);
                        //Console.WriteLine("Local end point: {0}", request.LocalEndPoint.ToString());
                        //Console.WriteLine("Remote end point: {0}", request.RemoteEndPoint.ToString());
                        //Console.WriteLine("Is local? {0}", request.IsLocal);
                        //Console.WriteLine("HTTP method: {0}", request.HttpMethod);
                        //Console.WriteLine("Protocol version: {0}", request.ProtocolVersion);
                        //Console.WriteLine("Is authenticated: {0}", request.IsAuthenticated);
                        //Console.WriteLine("Is secure: {0}", request.IsSecureConnection);

                        if (OnReceivedRequest != null)
                        {
                            OnReceivedRequest(request, response);
                        }
                    }

                    _isRunning  = false;
                    _isStopping = false;
                    _listener.Close();

                    Console.WriteLine("stopped");

                    if (OnStopped != null)
                    {
                        OnStopped();
                    }
                });
            }
        }
Exemplo n.º 32
0
        private static void Main(string[] args)
        {
            //if HttpListener is not supported by the Framework
            if (!HttpListener.IsSupported)
            {
                Console.WriteLine("A more recent Windows version is required to use the HttpListener class.");
                return;
            }


            // Create a listener.
            HttpListener listener = new HttpListener();

            // Add the prefixes.
            if (args.Length != 0)
            {
                foreach (string s in args)
                {
                    listener.Prefixes.Add(s);
                    // don't forget to authorize access to the TCP/IP addresses localhost:xxxx and localhost:yyyy
                    // with netsh http add urlacl url=http://localhost:xxxx/ user="******"
                    // and netsh http add urlacl url=http://localhost:yyyy/ user="******"
                    // user="******" is language dependent, use user=Everyone in english
                }
            }
            else
            {
                Console.WriteLine("Syntax error: the call must contain at least one web server url as argument");
            }
            listener.Start();

            // get args
            foreach (string s in args)
            {
                Console.WriteLine("Listening for connections on " + s);
            }

            // Trap Ctrl-C on console to exit
            Console.CancelKeyPress += delegate {
                // call methods to close socket and exit
                listener.Stop();
                listener.Close();
                Environment.Exit(0);
            };


            while (true)
            {
                // Note: The GetContext method blocks while waiting for a request.
                HttpListenerContext context = listener.GetContext();
                HttpListenerRequest request = context.Request;

                string documentContents;
                using (Stream receiveStream = request.InputStream)
                {
                    using (StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8))
                    {
                        documentContents = readStream.ReadToEnd();
                    }
                }

                // get url
                Console.WriteLine($"Received request for {request.Url}");

                //get url protocol
                Console.WriteLine(request.Url.Scheme);
                //get user in url
                Console.WriteLine(request.Url.UserInfo);
                //get host in url
                Console.WriteLine(request.Url.Host);
                //get port in url
                Console.WriteLine(request.Url.Port);
                //get path in url
                Console.WriteLine(request.Url.LocalPath);

                // parse path in url
                foreach (string str in request.Url.Segments)
                {
                    Console.WriteLine(str);
                }

                //get params un url. After ? and between &

                Console.WriteLine(request.Url.Query);

                //parse params in url
                Console.WriteLine("param1 = " + HttpUtility.ParseQueryString(request.Url.Query).Get("param1"));
                Console.WriteLine("param2 = " + HttpUtility.ParseQueryString(request.Url.Query).Get("param2"));
                Console.WriteLine("param3 = " + HttpUtility.ParseQueryString(request.Url.Query).Get("param3"));
                Console.WriteLine("param4 = " + HttpUtility.ParseQueryString(request.Url.Query).Get("param4"));

                String param1 = HttpUtility.ParseQueryString(request.Url.Query).Get("param1");
                String param2 = HttpUtility.ParseQueryString(request.Url.Query).Get("param2");

                //
                Console.WriteLine(documentContents);

                // Obtain a response object.
                HttpListenerResponse response = context.Response;

                // Construct a response.
                MyMethods m = new MyMethods();
                string    responseString = "<HTML><BODY> Hello world!</BODY></HTML>";
                if ("MyMethod".Equals(request.Url.Segments[request.Url.Segments.Length - 1]))
                {
                    responseString = m.MyMethod(param1, param2);
                }
                else if ("MyExeMethod".Equals(request.Url.Segments[request.Url.Segments.Length - 1]))
                {
                    responseString = m.MyExeMethod(param1, param2);
                }
                byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
                // 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.
                output.Close();
            }
            // Httplistener neither stop ... But Ctrl-C do that ...
            // listener.Stop();
        }
Exemplo n.º 33
0
        public static void Main()
        {
            const Int32 c_port = 80;
            byte[] ip = { 192, 168, 1, 222 };
            byte[] subnet = { 255, 255, 255, 0 };
            byte[] gateway = { 192, 168, 1, 1 };
            byte[] mac = { 0x00, 0x88, 0x98, 0x90, 0xD4, 0xE0 };
            WIZnet_W5100.Enable(SPI.SPI_module.SPI1, (Cpu.Pin)FEZ_Pin.Digital.Di10,
                                                (Cpu.Pin)FEZ_Pin.Digital.Di7, true);
            NetworkInterface.EnableStaticIP(ip, subnet, gateway, mac);
            NetworkInterface.EnableStaticDns(new byte[] { 192, 168, 1, 1 });
            HttpListener listener = new HttpListener("http", c_port);
            String file = string.Empty;
            sdCard.MountFileSystem();
            Debug.EnableGCMessages(false);
            listener.Start();

            while (true)
            {
                HttpListenerResponse response = null;
                HttpListenerContext context = null;
                HttpListenerRequest request = null;
                try
                {

                    context = listener.GetContext();
                    request = context.Request;
                    response = context.Response;
                    response.StatusCode = (int)HttpStatusCode.OK;
                    Debug.Print(request.RawUrl);
                    Debug.Print(request.HttpMethod);
                    if (request.RawUrl.Length > 1)
                    {
                        if (request.HttpMethod == "GET")
                        {

                            if (request.RawUrl =="/testtemp.jpg")
                            {
                                if (pictureTaken)
                                {
                                    Debug.GC(true);
                                    sendFile(request, response);
                                }
                            }
                            else
                            {
                                Debug.GC(true);
                                sendFile(request, response);
                            }
                        }
                        else if (request.HttpMethod == "POST")
                        {

                            if (request.RawUrl.CompareTo("/getPicture") == 0)
                            {
                                if (pictureTaken)
                                {
                                    Thread thread = new Thread(takePicture);
                                    thread.Start();
                                    response.OutputStream.Write(Encoding.UTF8.GetBytes("Picture Taken"), 0, 13);
                                }
                                else
                                {
                                    Byte[] aString = Encoding.UTF8.GetBytes("Picture already being taken");
                                    response.OutputStream.Write(aString, 0, aString.Length);
                                }
                            }
                        }
                    }
                    else
                    {
                        string rootDirectory =
                        VolumeInfo.GetVolumes()[0].RootDirectory;
                        string[] files = Directory.GetFiles(rootDirectory);
                        for (int i = 0; i < files.Length; i++)
                        {
                            response.OutputStream.Write(Encoding.UTF8.GetBytes(files[i]), 0, files[i].Length);
                            response.OutputStream.WriteByte(10);
                        }
                        string[] folders = Directory.GetDirectories(rootDirectory);
                        for (int i = 0; i < folders.Length; i++)
                        {
                            Debug.Print(folders[i]);
                            string[] subFiles = Directory.GetFiles(folders[i]);
                            for (int j = 0; j < subFiles.Length; j++)
                            {
                                response.OutputStream.Write(Encoding.UTF8.GetBytes(subFiles[j]), 0, subFiles[j].Length);
                                response.OutputStream.WriteByte(10);
                            }
                        }

                    }
                    //We are ignoring the request, assuming GET
                    // Sends response:
                    response.Close();
                    context.Close();
                }
                catch
                {
                    if (context != null)
                    {
                        context.Close();
                    }
                }
            }
        }
        private void ExecuteFullAuth()
        {
            // Generate state and PKCE values.
            expectedState = CryptoUtils.RandomDataBase64Uri(32);
            codeVerifier  = CryptoUtils.RandomDataBase64Uri(32);
            var codeVerifierHash = CryptoUtils.Sha256(codeVerifier);
            var codeChallenge    = CryptoUtils.Base64UriEncodeNoPadding(codeVerifierHash);

            // Creates a redirect URI using an available port on the loopback address.
            redirectUri = string.Format("{0}:{1}", LOOPBACK_URI, GetRandomUnusedPort());

            // Listen for requests on the redirect URI.
            var httpListener = new HttpListener();

            httpListener.Prefixes.Add(redirectUri + '/');
            httpListener.Start();

            // Create the OAuth 2.0 authorization request.
            // https://developers.google.com/identity/protocols/OAuth2WebServer#creatingclient
            var authRequest = string.Format("{0}?response_type=code&scope={1}&redirect_uri={2}&client_id={3}&state={4}&code_challenge={5}&code_challenge_method={6}" +
                                            "&access_type=offline" +  // Forces to return a refresh token at the auth code exchange phase.
                                            "&approval_prompt=force", // Forces to show consent screen for each auth request. Needed to return refresh tokens on consequent auth runs.
                                            settings.AuthCredentials.AuthUri,
                                            settings.AccessScope,
                                            Uri.EscapeDataString(redirectUri),
                                            settings.AuthCredentials.ClientId,
                                            expectedState,
                                            codeChallenge,
                                            GoogleDriveSettings.CODE_CHALLENGE_METHOD);

            // Open request in the browser.
            Application.OpenURL(authRequest);

            // Wait for the authorization response.
            var context = httpListener.GetContext();

            // Send an HTTP response to the browser to notify the user to close the browser.
            var response       = context.Response;
            var responseString = settings.LoopbackResponseHtml;
            var buffer         = System.Text.Encoding.UTF8.GetBytes(responseString);

            response.ContentLength64 = buffer.Length;
            var responseOutput = response.OutputStream;

            responseOutput.Write(buffer, 0, buffer.Length);
            responseOutput.Close();
            httpListener.Stop();

            // Check for errors.
            if (context.Request.QueryString.Get("error") != null)
            {
                Debug.LogError(string.Format("UnityGoogleDrive: OAuth authorization error: {0}.", context.Request.QueryString.Get("error")));
                HandleProvideAccessTokenComplete(true);
                return;
            }
            if (context.Request.QueryString.Get("code") == null || context.Request.QueryString.Get("state") == null)
            {
                Debug.LogError("UnityGoogleDrive: Malformed authorization response. " + context.Request.QueryString);
                HandleProvideAccessTokenComplete(true);
                return;
            }

            // Extract the authorization code.
            authorizationCode = context.Request.QueryString.Get("code");
            var incomingState = context.Request.QueryString.Get("state");

            // Compare the receieved state to the expected value, to ensure that
            // this app made the request which resulted in authorization.
            if (incomingState != expectedState)
            {
                Debug.LogError(string.Format("UnityGoogleDrive: Received request with invalid state ({0}).", incomingState));
                HandleProvideAccessTokenComplete(true);
                return;
            }

            // Exchange the authorization code for tokens.
            authCodeExchanger.ExchangeAuthCode(authorizationCode, codeVerifier, redirectUri);
        }
Exemplo n.º 35
0
        //static void Main(string[] args)
        //{
        //    //    var properties = new NameValueCollection();
        //    //    //properties["quartz.scheduler.instanceName"] = "RemoteServerSchedulerClient";
        //    //    //// 设置线程池
        //    //    //properties["quartz.threadPool.type"] = "Quartz.Simpl.SimpleThreadPool, Quartz";
        //    //    //properties["quartz.threadPool.threadCount"] = "5";
        //    //    //properties["quartz.threadPool.threadPriority"] = "Normal";
        //    //    //// 远程输出配置
        //    //    //properties["quartz.scheduler.exporter.type"] = "Quartz.Simpl.RemotingSchedulerExporter, Quartz";
        //    //    //properties["quartz.scheduler.exporter.port"] = "3556";
        //    //    //properties["quartz.scheduler.exporter.bindName"] = "QuartzScheduler";
        //    //    //properties["quartz.scheduler.exporter.channelType"] = "tcp";


        //    //    //properties["quartz.dataSource.default.provider"] = "SqlServer-20";
        //    //    //properties["quartz.dataSource.default.connectionString"] = "server=local;database=quartz";
        //    //    //properties["quartz.jobStore.tablePrefix"] = "QRTZ_";
        //    //    //properties["quartz.jobStore.clustered"] = "true";
        //    //    //properties["quartz.jobStore.driverDelegateType"] = "Quartz.Impl.AdoJobStore.SqlServerDelegate, Quartz";
        //    //    // properties["quartz.jobStore.dataSource"]="myDs";
        //    //    //IScheduler scheduler = StdSchedulerFactory.GetDefaultScheduler();

        //    //    //服务器连接
        //    //    //properties["quartz.jobStore.clustered"] = "true";
        //    //    //properties["quartz.scheduler.instanceId"] = "AUTO";
        //    //    // properties["quartz.scheduler."] = "false";SHOU-PC\SQLEXPRESS

        //    //    //===持久化====
        //    //    // 存储类型
        //    //    properties["quartz.jobStore.type"] = "Quartz.Impl.AdoJobStore.JobStoreTX, Quartz";
        //    //    //表明前缀
        //    //    properties["quartz.jobStore.tablePrefix"] = "QRTZ_";
        //    //    //驱动类型
        //    //    properties["quartz.jobStore.driverDelegateType"] = "Quartz.Impl.AdoJobStore.SqlServerDelegate, Quartz";
        //    //    //数据源名称
        //    //    properties["quartz.jobStore.dataSource"] = "myDS";
        //    //    //连接字符串
        //    //    properties["quartz.dataSource.myDS.connectionString"] = @"Data Source = SHOU-PC\SQLEXPRESS;Initial Catalog = JobScheduler;Integrated Security = SSPI;";
        //    //    //sqlserver版本
        //    //    properties["quartz.dataSource.myDS.provider"] = "SqlServer-20";


        //    var schedulerFactory = new StdSchedulerFactory();
        //    IJobDetail job3 = JobBuilder.Create<DumbJObC>()
        //                     .WithIdentity("myJob2", "group2")
        //                     .UsingJobData("StatjobSays", "Stat Hello World!")
        //                     .Build();
        //    var scheduler = schedulerFactory.GetScheduler();

        //    ITrigger trigger1 = TriggerBuilder.Create().WithIdentity("触发器名称", "触发器组")
        //    .StartAt(new DateTimeOffset(new DateTime(2019,1,1))).Build();


        //    scheduler.ScheduleJob(job3, trigger1);
        //    scheduler.Start();
        //    JobKey jobKey = job3.Key;
        //    scheduler.TriggerJob(jobKey);


        //    //    //判断一个作用时否存在
        //    //    var c = scheduler.CheckExists(new JobKey("作业名称", "作业组"));

        //    //    scheduler.Clear();



        //    //    //IJobDetail job11 = JobBuilder.Create(tpe).WithIdentity("作业名称2", "作业组").Build();

        //    //    //ITrigger trigger11 = TriggerBuilder.Create().WithIdentity("触发器名称", "触发器组").StartNow()
        //    //    //  .WithSimpleSchedule(x => x.WithIntervalInSeconds(15).RepeatForever())
        //    //    // .Build();

        //    //    //scheduler.ScheduleJob(job11, trigger11);

        //    //    // IJobDetail job1 = JobBuilder.Create<HelloJob>().WithIdentity("作业名称", "作业组").Build();

        //    //    ITrigger trigger1 = TriggerBuilder.Create().WithIdentity("触发器名称", "触发器组").StartNow()
        //    //        .WithSimpleSchedule(x => x.WithIntervalInSeconds(15).RepeatForever())
        //    //        .Build();

        //    //    //scheduler.ScheduleJob(job1, trigger1);

        //    //    ////==========例子2 (执行时 作业数据传递,时间表达式使用)===========
        //    //    //Type tpe = Assembly.LoadFrom("QuartzExterior.dll").GetType("QuartzExterior.Dumb1Job");

        //    //IJobDetail job2 = JobBuilder.Create(tpe)
        //    //                           .WithIdentity("myJob", "group1")
        //    //                           .UsingJobData("jobSays", "Hello World!")

        //    //                           .Build();

        //    //ITrigger trigger2 = TriggerBuilder.Create()
        //    //                           .WithIdentity("mytrigger", "group1")
        //    //                           .StartNow()
        //    //                           .WithCronSchedule("/10 * * ? * *")    //时间表达式,5秒一次
        //    //                           .Build();
        //    //scheduler.ScheduleJob(job2, trigger2);


        //    //    //IJobDetail job3 = JobBuilder.Create<DumbJObC>()
        //    //    //                        .WithIdentity("myJob2", "group2")
        //    //    //                        .UsingJobData("StatjobSays", "Stat Hello World!")
        //    //    //                        .Build();
        //    //    //ITrigger trigger3 = TriggerBuilder.Create().WithIdentity("触发器名称2", "触发器组2").StartNow()
        //    //    //  .WithSimpleSchedule(x => x.WithIntervalInSeconds(5).RepeatForever())
        //    //    //  .Build();



        //    //    //TriggerState state = scheduler.GetTriggerState(new TriggerKey("mytrigger"));
        //    //    //Console.WriteLine(state.ToString());

        //    //    scheduler.Start();       //开启调度器

        //    //    IJobDetail job2 = JobBuilder.Create <HelloJob>()
        //    //                               .WithIdentity("myJob", "group1")
        //    //                               .UsingJobData("jobSays", "Hello World!")
        //    //                               .Build();
        //    //    ITrigger trigger2 = TriggerBuilder.Create()
        //    //                               .WithIdentity("mytrigger", "group1")
        //    //                               .StartNow()
        //    //                               .WithCronSchedule("/10 * * ? * *")    //时间表达式,5秒一次
        //    //                               .Build();
        //    //    scheduler.ScheduleJob(job2, trigger2);
        //    //}
        //}

        static void Main(string[] args)
        {
            var properties = new NameValueCollection();

            properties["quartz.jobStore.clustered"]   = "true";
            properties["quartz.scheduler.instanceId"] = "AUTO";
            //===持久化====
            // 存储类型
            properties["quartz.jobStore.type"] = "Quartz.Impl.AdoJobStore.JobStoreTX, Quartz";
            //表明前缀
            properties["quartz.jobStore.tablePrefix"] = "QRTZ_";
            //驱动类型
            properties["quartz.jobStore.driverDelegateType"] = "Quartz.Impl.AdoJobStore.SqlServerDelegate, Quartz";
            //数据源名称
            properties["quartz.jobStore.dataSource"] = "myDS";
            //连接字符串
            properties["quartz.dataSource.myDS.connectionString"] = @"Data Source = SHOU-PC\SQLEXPRESS;Initial Catalog = JobScheduler;Integrated Security = SSPI;";
            //sqlserver版本
            properties["quartz.dataSource.myDS.provider"] = "SqlServer-20";

            QuartzFactory quartzFactory = new QuartzFactory(null);

            quartzFactory.Start();

            if (!HttpListener.IsSupported)
            {
                throw new System.InvalidOperationException(
                          "使用 HttpListener 必须为 Windows XP SP2 或 Server 2003 以上系统!");
            }
            // 注意前缀必须以 / 正斜杠结尾
            string[]       prefixes = new string[] { "http://*****:*****@"<html> <head><title>From HttpListener Server</title></head> <body>" + sb.ToString() + "</body> </html>";
                    response.ContentLength64 = System.Text.Encoding.UTF8.GetByteCount(responseString);
                    response.ContentType     = "text/html; charset=UTF-8";
                    // 输出回应内容
                    System.IO.Stream output       = response.OutputStream;
                    System.IO.StreamWriter writer = new System.IO.StreamWriter(output);
                    writer.Write(responseString);
                    // 必须关闭输出流
                    writer.Close();
                    if (Console.KeyAvailable)
                    {
                        break;
                    }
                }
            });

            thread31.Start();
        }
        //public event EventHandler<EventArgs> Msg;

        //public string system;
        public static void Main(string[] args)
        {
            HttpListener hl = new HttpListener();

            hl.Prefixes.Add(PREFIXO);
            hl.Start();
            for (; ;)
            {
                var    ctx = hl.GetContext();
                string url = ctx.Request.RawUrl;
                Console.WriteLine("Request: " + url);



                //using (var tw = new StreamWriter("res.html"))
                using (var tw = new StreamWriter(ctx.Response.OutputStream))
                {
                    //BrowseType.Browse("System.IO", "DirectoryInfo", tw);
                    //BrowseType.Browse("BrowserTipos", "Program", tw);
                    //BrowseType.Browse("System", "Object", tw);



                    Assembly NossoAssembly = Assembly.GetExecutingAssembly();
                    Type []  n1            = NossoAssembly.GetExportedTypes();

                    foreach (Type n in n1)
                    {
                        if (!n.IsDefined(typeof(UrlAttribute), false))
                        {
                            continue;
                        }
                        MethodInfo[] met = n.GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);

                        foreach (MethodInfo mt in met)
                        {
                            if (!mt.IsDefined(typeof(UrlAttribute), false))
                            {
                                continue;
                            }


                            var      mt_atrib = (UrlAttribute)mt.GetCustomAttributes(typeof(UrlAttribute), false)[0];
                            string[] p;
                            if (Program.CompareUrl(mt_atrib._st, url, out p))
                            {
                                //ParameterInfo[] par = mt.GetParameters();

                                object[] arg = new object[p.Length + 1];
                                int      i;
                                for (i = 0; i < p.Length; i++)
                                {
                                    arg[i] = p[i];
                                }

                                arg[p.Length] = tw;

                                mt.Invoke(null, arg);
                            }
                        }
                    }
                }
            }
            //hl.Stop();
        }
Exemplo n.º 37
0
        public static WebHeaderCollection GetWebBrowserRequestHeaders(IWebBrowserInfo webBrowserInfo, TimeSpan timeout, string responseBody)
        {
            WebHeaderCollection requestHeaders = new WebHeaderCollection();

            if (webBrowserInfo is null)
            {
                throw new ArgumentNullException(nameof(webBrowserInfo));
            }

            if (!File.Exists(webBrowserInfo?.ExecutablePath))
            {
                throw new FileNotFoundException();
            }

            // Start an HTTP server on a random port.

            Uri  requestUri        = new Uri($"http://localhost:{SocketUtilities.GetAvailablePort()}/");
            bool listenForRequests = true;

            using (HttpListener listener = new HttpListener()) {
                listener.Prefixes.Add(requestUri.AbsoluteUri);

                listener.Start();

                // Open the HTTP server in the user's web browser.

                Process.Start(webBrowserInfo.ExecutablePath, requestUri.AbsoluteUri);

                // Wait for an incoming request.

                while (listenForRequests)
                {
                    listenForRequests = false;

                    HttpListenerContext context = listener.GetContext(timeout);

                    if (!(context is null))
                    {
                        HttpListenerRequest request = context.Request;

                        if (request.HttpMethod.Equals("get", StringComparison.OrdinalIgnoreCase))
                        {
                            // The web browser requested our webpage, so copy the request headers.

                            context.Request.Headers.CopyTo(requestHeaders);

                            // Respond to the request.

                            HttpListenerResponse response = context.Response;

                            StringBuilder responseBuilder = new StringBuilder();

                            responseBuilder.AppendLine("<!DOCTYPE html>");
                            responseBuilder.Append("<html>");
                            responseBuilder.Append("<body>");
                            responseBuilder.Append("<script>fetch(\"" + requestUri.AbsoluteUri + "\", {method: \"POST\"});</script>");
                            responseBuilder.Append(responseBody ?? "This window may now be closed.");
                            responseBuilder.Append("</body>");
                            responseBuilder.Append("</html>");

                            using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(responseBuilder.ToString())))
                                ms.CopyTo(response.OutputStream);

                            response.Close();

                            // Wait for the web browser to POST back let us know it got our response.

                            listenForRequests = true;
                        }
                        else
                        {
                            // The web browser has POSTed back to let us know it got our response.
                        }
                    }
                }
            }

            return(requestHeaders);
        }
Exemplo n.º 38
0
        public void StartServer()
        {
            if (_config.enabled)
            {
                _httplistener.Start();
                new Thread(() =>
                {
                    while (_httplistener.IsListening)
                    {
                        HttpListenerContext ctx = _httplistener.GetContext();
                        ThreadPool.QueueUserWorkItem((_) =>
                        {
                            string ipAddress   = ctx.Request.RemoteEndPoint.Address.ToString();
                            string requestPath = ctx.Request.Url.AbsolutePath;
                            if (_config.whitelist)
                            {
                                if (!_config.addresses.Contains(ipAddress))
                                {
                                    LogMessage("Connection Refused from " + ipAddress + " to " + ctx.Request.Url.AbsolutePath);
                                    return;
                                }
                            }
                            string username = "******";
                            if (_config.authentication)
                            {
                                if (ctx.User.Identity.IsAuthenticated)
                                {
                                    HttpListenerBasicIdentity identity = (HttpListenerBasicIdentity)ctx.User.Identity;
                                    username = identity.Name;
                                    if (!_config.users.ContainsKey(username))
                                    {
                                        LogMessage("Connection Refused from " + ipAddress + " to " + requestPath
                                                   + " for user " + username + ". User not found.");
                                        return;
                                    }
                                    if (!_config.users[identity.Name].Equals(identity.Password))
                                    {
                                        LogMessage("Connection Refused from " + ipAddress + " to " + requestPath
                                                   + " for user " + username + ". Incorrect Password.");
                                        return;
                                    }
                                }
                                else
                                {
                                    LogMessage("Connection Refused from " + ipAddress + " to " + requestPath + " due to lack of credentials.");
                                    return;
                                }
                            }

                            LogMessage("Connection Accepted from " + ipAddress + " to " + requestPath + " for user " + username + ".");

                            _httpRouter.Route(ctx.Request.Url.AbsolutePath.Trim().ToLower(), ctx.Request, ctx.Response);

                            ctx.Response.Close();
                        });
                    }
                }).Start();
                if (_httplistener.IsListening)
                {
                    LogMessage("Started REST Server on Port " + _config.port);
                }
                else
                {
                    LogMessage("REST Server Disabled");
                }
            }
        }
Exemplo n.º 39
0
        public static void HTTPHandler()
        {
            while (listener.IsListening)
            {
                try
                {
                    Console.WriteLine("Starting HTTP Client to Auto-get port and IP...");

                    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 != "")
                    {
                        Console.WriteLine("Got response, server metadata:\n" + server_metadata);
                        Console.WriteLine("Parsing server metadata...");

                        string[] tokens = server_metadata.Split('\n');
                        foreach (string s in tokens)
                        {
                            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
                                MainForm.globalUserData.Growtopia_Master_IP = value.Substring(0, value.Length - 1);
                                break;
                            }

                            case "port":
                            {
                                MainForm.globalUserData.Growtopia_Master_Port = ushort.Parse(value);
                                break;
                            }

                            default:
                                break;
                            }
                        }
                        MainForm.globalUserData.Growtopia_IP   = MainForm.globalUserData.Growtopia_Master_IP;
                        MainForm.globalUserData.Growtopia_Port = MainForm.globalUserData.Growtopia_Master_Port;
                        Console.WriteLine("Parsing done, detected IP:Port -> " + MainForm.globalUserData.Growtopia_IP + ":" + MainForm.globalUserData.Growtopia_Port.ToString());
                    }

                    HttpListenerContext  context  = listener.GetContext();
                    HttpListenerRequest  request  = context.Request;
                    HttpListenerResponse response = context.Response;
                    Console.WriteLine("New request from client:\n" + request.RawUrl + " " + request.HttpMethod + " " + request.UserAgent);
                    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|growbrew.com\n");

                        response.ContentLength64 = buffer.Length;
                        System.IO.Stream output = response.OutputStream;
                        output.Write(buffer, 0, buffer.Length);
                        output.Close();
                        response.Close();
                    }
                }
                catch (HttpListenerException ex)
                {
                    Console.WriteLine(ex.Message);
                    // probably cuz we stopped it, no need to worry.
                }
            }
        }
Exemplo n.º 40
0
    private void ListenThread()
    {
        try
        {
            listener = new HttpListener();

            foreach (string prefix in prefixes)
            {
                listener.Prefixes.Add(prefix);
            }

            listener.Start();

            while (true)
            {
                HttpListenerContext context = listener.GetContext();

                Debug.LogFormat("Recieved request from {0}.", context.Request.RemoteEndPoint.ToString());

                context.Response.StatusCode = 200;

                lock (waitingContexts)
                {
                    waitingContexts.AddLast(context);
                }
            }
        }
        catch(Exception e)
        {
            Debug.LogErrorFormat("Web server error at {0}.", e.Source);
            Debug.LogError(e.Message, this);
        }
    }
Exemplo n.º 41
0
        private void Run()
        {
            try
            {
                const string Xml =
                    @"<?xml version=""1.0""?> 
<methodResponse>
  <params>
    <param>
      <value>Alabama</value>
    </param>
  </params>
</methodResponse>";

                while (_running)
                {
                    var context = _lstner.GetContext();
                    switch (_encoding)
                    {
                    case "gzip":
                        context.Response.Headers.Add("Content-Encoding", "gzip");
                        break;

                    case "deflate":
                        context.Response.Headers.Add("Content-Encoding", "deflate");
                        break;
                    }

                    context.Response.ContentEncoding = System.Text.Encoding.UTF32;
                    var    respStm = context.Response.OutputStream;
                    Stream compStm;
                    switch (_encoding)
                    {
                    case "gzip":
                        compStm = new System.IO.Compression.GZipStream(
                            respStm,
                            System.IO.Compression.CompressionMode.Compress);
                        break;

                    case "deflate":
                        compStm = new System.IO.Compression.DeflateStream(
                            respStm,
                            System.IO.Compression.CompressionMode.Compress);
                        break;

                    default:
                        compStm = null;
                        break;
                    }

                    if (compStm == null)
                    {
                        continue;
                    }

                    var wrtr = new StreamWriter(compStm);
                    wrtr.Write(Xml);
                    wrtr.Close();
                }
            }
            catch (HttpListenerException)
            {
            }
        }
Exemplo n.º 42
0
    public void Run()
    {
        HttpListener listener = new HttpListener();
        listener.Prefixes.Add("http://localhost:8080/");
        listener.Start();

        // Wait for a request
        HttpListenerContext context = listener.GetContext();
        HttpListenerRequest request = context.Request;

        // process the request
        string path = request.Url.AbsolutePath;
        string responseString;

        try
        {
            responseString = handler(context);
        }
        catch (Exception e)
        {
            responseString = e.ToString();
        }

        // write the response
        HttpListenerResponse response = context.Response;
        System.IO.Stream output = response.OutputStream;

        if (!String.IsNullOrEmpty(responseString))
        {
            byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
            response.ContentLength64 = buffer.Length;
            output.Write(buffer, 0, buffer.Length);
        }
        output.Close();

        // shut down the listener
        listener.Stop();
    }
Exemplo n.º 43
0
        public static void SimpleListenerExample(string[] prefixes)
        {
            if (!HttpListener.IsSupported)
            {
                Console.WriteLine("Windows XP SP2 or Server 2003 is required to use the HttpListener class.");
                return;
            }
            // URI prefixes are required,
            // for example "http://contoso.com:8080/index/".
            if (prefixes == null || prefixes.Length == 0)
            {
                throw new ArgumentException("prefixes");
            }

            Console.WriteLine("Starting server...");

            new Thread(async() =>
            {
                Console.WriteLine("Server running in background thread...");

                Thread.CurrentThread.IsBackground = true;

                // Create a listener.
                HttpListener listener = new HttpListener();
                // Add the prefixes.
                foreach (string s in prefixes)
                {
                    listener.Prefixes.Add(s);
                }
                listener.Start();
                while (running)
                {
                    // Note: The GetContext method blocks while waiting for a request.
                    HttpListenerContext context = listener.GetContext();
                    HttpListenerRequest request = context.Request;
                    //Console.WriteLine("Request received at endpoint: " + request.RawUrl);
                    // Obtain a response object.
                    HttpListenerResponse response = context.Response;
                    // Construct a response.
                    string responseString = "";//"<HTML><BODY> Hello world!" + request.RawUrl + "</BODY></HTML>";
                    try
                    {
                        responseString = generateResponseForRequest(request);
                    }
                    catch (Exception e)
                    {
                        responseString = e.Message;
                    }

                    response.Headers.Add("Access-Control-Allow-Origin:*");

                    byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
                    // 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.
                    output.Close();
                    //Console.WriteLine("Responded to requester...");
                }
                listener.Stop();
            }).Start();
        }
Exemplo n.º 44
0
    static void Main(string []args)
    {
        if(args.Length != 2)
        {
            Console.WriteLine("Error: please specify URI to listen on and Authentication type to use:\nAuthListener.exe ServerURI AuthenticationScheme");
            return;
        }
        string serverUri = args[0];
        AuthenticationSchemes authScheme;
        switch(args[1].ToLower())
        {
            case "none":
                authScheme = AuthenticationSchemes.None;
                break;
            case "anonymous":
                authScheme = AuthenticationSchemes.Anonymous;
                break;
            case "basic":
                authScheme = AuthenticationSchemes.Basic;
                break;
            case "digest":
                authScheme = AuthenticationSchemes.Digest;
                break;
            case "ntlm":
                authScheme = AuthenticationSchemes.Ntlm;
                break;
            case "negotiate":
                authScheme = AuthenticationSchemes.Negotiate;
                break;
            case "integrated":
                authScheme = AuthenticationSchemes.IntegratedWindowsAuthentication;
                break;
            default:
                Console.WriteLine("Error: unrecognized AuthenticationScheme:{0}", args[1]);
                return;
        }
    
        HttpListener listener = new HttpListener();
        listener.Prefixes.Add(serverUri);
        listener.AuthenticationSchemes = authScheme;

        listener.Start();
        Console.WriteLine("Listening...");

		HttpListenerContext context = listener.GetContext();
		Console.WriteLine("Received request...");
		StreamWriter writer = new StreamWriter(context.Response.OutputStream);

		// Verify correct authentication scheme was used.
		if (!VerifyAuthenticationScheme(listener.AuthenticationSchemes, context))
		{
			context.Response.StatusCode = (int)HttpStatusCode.ExpectationFailed;
			writer.Write("Error authentication validation failed");
		}

		context.Response.Close();
	}
Exemplo n.º 45
0
        private void Process(HttpListener listener)
        {
            listener.Start();
            Program.Print(string.Format("[INFO] JSON-API service started at {0}...", listener.Prefixes.ElementAt(0)));
            while (m_isOngoing)
            {
                HttpListenerResponse response = listener.GetContext().Response;

                var   api           = new JsonAPI();
                float divisor       = 1;
                ulong totalHashRate = 0ul;

                foreach (var miner in m_miners)
                {
                    totalHashRate += miner.GetTotalHashrate();
                }

                var sTotalHashRate = totalHashRate.ToString();
                if (sTotalHashRate.Length > 12 + 1)
                {
                    divisor          = 1000000000000;
                    api.HashRateUnit = "TH/s";
                }
                else if (sTotalHashRate.Length > 9 + 1)
                {
                    divisor          = 1000000000;
                    api.HashRateUnit = "GH/s";
                }
                else if (sTotalHashRate.Length > 6 + 1)
                {
                    divisor          = 1000000;
                    api.HashRateUnit = "MH/s";
                }
                else if (sTotalHashRate.Length > 3 + 1)
                {
                    divisor          = 1000;
                    api.HashRateUnit = "KH/s";
                }

                var networkInterface = m_miners.Select(m => m.NetworkInterface).FirstOrDefault(m => m != null);

                api.EffectiveHashRate = (networkInterface?.GetEffectiveHashrate() ?? 0f) / divisor;

                api.TotalHashRate = totalHashRate / divisor;

                api.MinerAddress = networkInterface.MinerAddress ?? string.Empty;

                api.MiningURL = networkInterface.SubmitURL ?? string.Empty;

                api.CurrentChallenge = networkInterface.CurrentChallenge ?? string.Empty;

                api.CurrentDifficulty = networkInterface.Difficulty;

                api.LastSubmitLatencyMS = networkInterface?.LastSubmitLatency ?? -1;

                api.LatencyMS = networkInterface?.Latency ?? -1;

                api.Uptime = (long)(DateTime.Now - Program.LaunchTime).TotalSeconds;

                api.RejectedShares = m_miners.Select(m => m.NetworkInterface).Distinct().Sum(i => (long)(i.RejectedShares));

                api.AcceptedShares = m_miners.Select(m => m.NetworkInterface).Distinct().Sum(i => (long)(i.SubmittedShares)) - api.RejectedShares;

                foreach (var miner in m_miners)
                {
                    foreach (var device in miner.Devices.Where(d => d.AllowDevice))
                    {
                        JsonAPI.Miner newMiner = null;
                        if (miner.HasMonitoringAPI)
                        {
                            switch (device.Type)
                            {
                            case "CUDA":
                            {
                                var tempValue   = 0;
                                var tempSize    = 0ul;
                                var tempStr     = new StringBuilder(1024);
                                var instancePtr = ((Miner.CUDA)miner).m_instance;

                                newMiner = new JsonAPI.CUDA_Miner()
                                {
                                    Type             = device.Type,
                                    DeviceID         = device.DeviceID,
                                    PciBusID         = device.PciBusID,
                                    ModelName        = device.Name,
                                    HashRate         = miner.GetHashrateByDevice(device.Platform, device.DeviceID) / divisor,
                                    HasMonitoringAPI = miner.HasMonitoringAPI,
                                    SettingIntensity = device.Intensity
                                };

                                if (((Miner.CUDA)miner).UseNvSMI)
                                {
                                    ((JsonAPI.CUDA_Miner)newMiner).SettingMaxCoreClockMHz = -1;

                                    ((JsonAPI.CUDA_Miner)newMiner).SettingMaxMemoryClockMHz = -1;

                                    tempValue = Miner.API.NvSMI.GetDeviceSettingPowerLimit(device.PciBusID);
                                    ((JsonAPI.CUDA_Miner)newMiner).SettingPowerLimitPercent = tempValue;

                                    tempValue = Miner.API.NvSMI.GetDeviceSettingThermalLimit(device.PciBusID);
                                    ((JsonAPI.CUDA_Miner)newMiner).SettingThermalLimitC = tempValue;

                                    tempValue = Miner.API.NvSMI.GetDeviceSettingFanLevelPercent(device.PciBusID);
                                    ((JsonAPI.CUDA_Miner)newMiner).SettingFanLevelPercent = tempValue;

                                    ((JsonAPI.CUDA_Miner)newMiner).CurrentFanTachometerRPM = -1;

                                    tempValue = Miner.API.NvSMI.GetDeviceCurrentTemperature(device.PciBusID);
                                    ((JsonAPI.CUDA_Miner)newMiner).CurrentTemperatureC = tempValue;

                                    tempValue = Miner.API.NvSMI.GetDeviceCurrentCoreClock(device.PciBusID);
                                    ((JsonAPI.CUDA_Miner)newMiner).CurrentCoreClockMHz = tempValue;

                                    tempValue = Miner.API.NvSMI.GetDeviceCurrentMemoryClock(device.PciBusID);
                                    ((JsonAPI.CUDA_Miner)newMiner).CurrentMemoryClockMHz = tempValue;

                                    tempValue = Miner.API.NvSMI.GetDeviceCurrentUtilizationPercent(device.PciBusID);
                                    ((JsonAPI.CUDA_Miner)newMiner).CurrentUtilizationPercent = tempValue;

                                    tempValue = Miner.API.NvSMI.GetDeviceCurrentPstate(device.PciBusID);
                                    ((JsonAPI.CUDA_Miner)newMiner).CurrentPState = tempValue;

                                    tempStr.Append(Miner.API.NvSMI.GetDeviceCurrentThrottleReasons(device.PciBusID));
                                    ((JsonAPI.CUDA_Miner)newMiner).CurrentThrottleReasons = tempStr.ToString();
                                }
                                else
                                {
                                    Miner.CUDA.Solver.GetDeviceSettingMaxCoreClock(instancePtr, device.DeviceID, ref tempValue);
                                    ((JsonAPI.CUDA_Miner)newMiner).SettingMaxCoreClockMHz = tempValue;

                                    Miner.CUDA.Solver.GetDeviceSettingMaxMemoryClock(instancePtr, device.DeviceID, ref tempValue);
                                    ((JsonAPI.CUDA_Miner)newMiner).SettingMaxMemoryClockMHz = tempValue;

                                    Miner.CUDA.Solver.GetDeviceSettingPowerLimit(instancePtr, device.DeviceID, ref tempValue);
                                    ((JsonAPI.CUDA_Miner)newMiner).SettingPowerLimitPercent = tempValue;

                                    Miner.CUDA.Solver.GetDeviceSettingThermalLimit(instancePtr, device.DeviceID, ref tempValue);
                                    ((JsonAPI.CUDA_Miner)newMiner).SettingThermalLimitC = tempValue;

                                    Miner.CUDA.Solver.GetDeviceSettingFanLevelPercent(instancePtr, device.DeviceID, ref tempValue);
                                    ((JsonAPI.CUDA_Miner)newMiner).SettingFanLevelPercent = tempValue;

                                    Miner.CUDA.Solver.GetDeviceCurrentFanTachometerRPM(instancePtr, device.DeviceID, ref tempValue);
                                    ((JsonAPI.CUDA_Miner)newMiner).CurrentFanTachometerRPM = tempValue;

                                    Miner.CUDA.Solver.GetDeviceCurrentTemperature(instancePtr, device.DeviceID, ref tempValue);
                                    ((JsonAPI.CUDA_Miner)newMiner).CurrentTemperatureC = tempValue;

                                    Miner.CUDA.Solver.GetDeviceCurrentCoreClock(instancePtr, device.DeviceID, ref tempValue);
                                    ((JsonAPI.CUDA_Miner)newMiner).CurrentCoreClockMHz = tempValue;

                                    Miner.CUDA.Solver.GetDeviceCurrentMemoryClock(instancePtr, device.DeviceID, ref tempValue);
                                    ((JsonAPI.CUDA_Miner)newMiner).CurrentMemoryClockMHz = tempValue;

                                    Miner.CUDA.Solver.GetDeviceCurrentUtilizationPercent(instancePtr, device.DeviceID, ref tempValue);
                                    ((JsonAPI.CUDA_Miner)newMiner).CurrentUtilizationPercent = tempValue;

                                    Miner.CUDA.Solver.GetDeviceCurrentPstate(instancePtr, device.DeviceID, ref tempValue);
                                    ((JsonAPI.CUDA_Miner)newMiner).CurrentPState = tempValue;

                                    Miner.CUDA.Solver.GetDeviceCurrentThrottleReasons(instancePtr, device.DeviceID, tempStr, ref tempSize);
                                    ((JsonAPI.CUDA_Miner)newMiner).CurrentThrottleReasons = tempStr.ToString();
                                }
                            }
                            break;

                            case "OpenCL":
                            {
                                var tempValue   = 0;
                                var tempStr     = new StringBuilder(1024);
                                var instancePtr = ((Miner.OpenCL)miner).m_instance;

                                newMiner = new JsonAPI.AMD_Miner()
                                {
                                    Type             = device.Type,
                                    DeviceID         = device.DeviceID,
                                    PciBusID         = device.PciBusID,
                                    ModelName        = device.Name,
                                    HashRate         = miner.GetHashrateByDevice(device.Platform, device.DeviceID) / divisor,
                                    HasMonitoringAPI = miner.HasMonitoringAPI,
                                    Platform         = device.Platform,
                                    SettingIntensity = device.Intensity
                                };

                                if (((Miner.OpenCL)miner).UseLinuxQuery)
                                {
                                    ((JsonAPI.AMD_Miner)newMiner).SettingMaxCoreClockMHz = -1;

                                    ((JsonAPI.AMD_Miner)newMiner).SettingMaxMemoryClockMHz = -1;

                                    ((JsonAPI.AMD_Miner)newMiner).SettingPowerLimitPercent = -1;

                                    ((JsonAPI.AMD_Miner)newMiner).SettingThermalLimitC = int.MinValue;

                                    ((JsonAPI.AMD_Miner)newMiner).SettingFanLevelPercent = Miner.API.AmdLinuxQuery.GetDeviceSettingFanLevelPercent(device.PciBusID);

                                    ((JsonAPI.AMD_Miner)newMiner).CurrentFanTachometerRPM = Miner.API.AmdLinuxQuery.GetDeviceCurrentFanTachometerRPM(device.PciBusID);

                                    ((JsonAPI.AMD_Miner)newMiner).CurrentTemperatureC = Miner.API.AmdLinuxQuery.GetDeviceCurrentTemperature(device.PciBusID);

                                    ((JsonAPI.AMD_Miner)newMiner).CurrentCoreClockMHz = Miner.API.AmdLinuxQuery.GetDeviceCurrentCoreClock(device.PciBusID);

                                    ((JsonAPI.AMD_Miner)newMiner).CurrentMemoryClockMHz = Miner.API.AmdLinuxQuery.GetDeviceCurrentCoreClock(device.PciBusID);

                                    ((JsonAPI.AMD_Miner)newMiner).CurrentUtilizationPercent = Miner.API.AmdLinuxQuery.GetDeviceCurrentUtilizationPercent(device.PciBusID);
                                }
                                else
                                {
                                    Miner.OpenCL.Solver.GetDeviceSettingMaxCoreClock(instancePtr, new StringBuilder(device.Platform), device.DeviceID, ref tempValue);
                                    ((JsonAPI.AMD_Miner)newMiner).SettingMaxCoreClockMHz = tempValue;

                                    Miner.OpenCL.Solver.GetDeviceSettingMaxMemoryClock(instancePtr, new StringBuilder(device.Platform), device.DeviceID, ref tempValue);
                                    ((JsonAPI.AMD_Miner)newMiner).SettingMaxMemoryClockMHz = tempValue;

                                    Miner.OpenCL.Solver.GetDeviceSettingPowerLimit(instancePtr, new StringBuilder(device.Platform), device.DeviceID, ref tempValue);
                                    ((JsonAPI.AMD_Miner)newMiner).SettingPowerLimitPercent = tempValue;

                                    Miner.OpenCL.Solver.GetDeviceSettingThermalLimit(instancePtr, new StringBuilder(device.Platform), device.DeviceID, ref tempValue);
                                    ((JsonAPI.AMD_Miner)newMiner).SettingThermalLimitC = tempValue;

                                    Miner.OpenCL.Solver.GetDeviceSettingFanLevelPercent(instancePtr, new StringBuilder(device.Platform), device.DeviceID, ref tempValue);
                                    ((JsonAPI.AMD_Miner)newMiner).SettingFanLevelPercent = tempValue;

                                    Miner.OpenCL.Solver.GetDeviceCurrentFanTachometerRPM(instancePtr, new StringBuilder(device.Platform), device.DeviceID, ref tempValue);
                                    ((JsonAPI.AMD_Miner)newMiner).CurrentFanTachometerRPM = tempValue;

                                    Miner.OpenCL.Solver.GetDeviceCurrentTemperature(instancePtr, new StringBuilder(device.Platform), device.DeviceID, ref tempValue);
                                    ((JsonAPI.AMD_Miner)newMiner).CurrentTemperatureC = tempValue;

                                    Miner.OpenCL.Solver.GetDeviceCurrentCoreClock(instancePtr, new StringBuilder(device.Platform), device.DeviceID, ref tempValue);
                                    ((JsonAPI.AMD_Miner)newMiner).CurrentCoreClockMHz = tempValue;

                                    Miner.OpenCL.Solver.GetDeviceCurrentMemoryClock(instancePtr, new StringBuilder(device.Platform), device.DeviceID, ref tempValue);
                                    ((JsonAPI.AMD_Miner)newMiner).CurrentMemoryClockMHz = tempValue;

                                    Miner.OpenCL.Solver.GetDeviceCurrentUtilizationPercent(instancePtr, new StringBuilder(device.Platform), device.DeviceID, ref tempValue);
                                    ((JsonAPI.AMD_Miner)newMiner).CurrentUtilizationPercent = tempValue;
                                }
                            }
                            break;
                            }
                        }
                        else
                        {
                            switch (device.Type)
                            {
                            case "OpenCL":
                                newMiner = new JsonAPI.OpenCLMiner()
                                {
                                    Type             = device.Type,
                                    DeviceID         = device.DeviceID,
                                    ModelName        = device.Name,
                                    HashRate         = miner.GetHashrateByDevice(device.Platform, device.DeviceID) / divisor,
                                    HasMonitoringAPI = miner.HasMonitoringAPI,

                                    Platform         = device.Platform,
                                    SettingIntensity = device.Intensity
                                };
                                break;

                            default:
                                newMiner = new JsonAPI.Miner()
                                {
                                    Type      = device.Type,
                                    DeviceID  = device.DeviceID,
                                    ModelName = device.Name,
                                    HashRate  = miner.GetHashrateByDevice(device.Platform, (device.Type == "CPU")
                                                                                                ? Array.IndexOf(miner.Devices, device)
                                                                                                : device.DeviceID) / divisor,
                                    HasMonitoringAPI = miner.HasMonitoringAPI
                                };
                                break;
                            }
                        }

                        if (newMiner != null)
                        {
                            api.Miners.Add(newMiner);
                        }
                    }
                }

                api.Miners.Sort((x, y) => x.PciBusID.CompareTo(y.PciBusID));

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

                using (var output = response.OutputStream)
                    if (buffer != null)
                    {
                        output.Write(buffer, 0, buffer.Length);
                    }

                response.Close();
            }
        }