示例#1
0
        static void Main(string[] args)
        {
            ProtoGLSMessage.ReqUpdateServerInfoMessage glmessage = new ProtoGLSMessage.ReqUpdateServerInfoMessage();
            glmessage.Connects = 5;
            glmessage.ServerID = 1;
            glmessage.ZoneID   = 1;
            byte[] buff = MessageHelper.MessageSerialize(glmessage);
            Console.WriteLine(buff.Length);

            HttpServer httpserver = NettyPool.AddHttpBind("127.0.0.1", 9527, 2);

            httpserver.AddHandler("*", new ActionHttpHandler((session) =>
            {
            }));

            httpserver.AddHandler("login", new ActionHttpHandler((session) =>
            {
                session.AddContent("<html><body>login holle !</body></html>");
            }));

            httpserver.Start();

            string msg = HttpClient.SendUrl("http://127.0.0.1:9527", "GET");

            Console.WriteLine(msg);
            Console.ReadLine();
        }
示例#2
0
        static void Main(string[] args)
        {
            HttpServer server = new HttpServer();

            server.Start("localhost", 4006);

            //add MiddleWares
            server.AddMiddleWares(new LogMiddleWare());

            //set common page handlers
            server.SetHomePageHandler(new HomeHttpHandler());
            server.SetPageErrorHandler(new PageErrorHandler());

            //dispatch urls to handlers
            server.AddHandler("/test", new TestHttpHandler());
            server.AddHandler("/test/child", new TestChildHttpHandler());

            // wait for system exit
            while (true)
            {
                string text = Console.ReadLine();
                if (text == "exit" || text == "quit")
                {
                    server.Stop();
                    break;
                }
                Console.WriteLine("please type 'exit' or 'quit' to exit this application...");
            }
        }
示例#3
0
        static void Main(string[] args)
        {
            HttpServer httpserver = NettyPool.AddHttpBind("127.0.0.1", 9527, 2);

            httpserver.AddHandler("*", new ActionHttpHandler((session) =>
            {
                session.AddContent("<html><body>webapi!</body></html>");
            }));

            httpserver.AddHandler("login", new ActionHttpHandler((session) =>
            {
                session.AddContent("<html><body>login holle !</body></html>");
            }));

            httpserver.Start();
        }
        public void TestBypassRemoteError_no_response_stream()
        {
            using (HttpServer proxyServer = new HttpServer(80))
                using (HttpServer targetServer = new HttpServer(8080))
                {
                    proxyServer.AddHandler("/", new MyHandler("dummy"));             // dummy
                    BypassHttpHandler bypasser = new BypassHttpHandler("http://localhost:8080");
                    proxyServer.AddDefaultHandler(bypasser);
                    proxyServer.Start();

                    targetServer.AddHandler("/bypass/", new ErrorHttpHandler(502, null));
                    targetServer.Start();

                    WebClient agent = new WebClient();
                    try
                    {
                        agent.DownloadData("http://localhost:80/bypass/");
                    }
                    catch (WebException e)
                    {
                        Assert.AreEqual(HttpStatusCode.BadGateway,
                                        ((HttpWebResponse)e.Response).StatusCode);
                        using (StreamReader r = new StreamReader(e.Response.GetResponseStream()))
                        {
                            string json = r.ReadToEnd();
                            Assert.AreEqual("", json);
                        }
                        return;
                    }

                    Assert.Fail("Expected exception is not thrown");
                }
        }
        public void TestBypassException_pathWithQueryString()
        {
            using (HttpServer proxyServer = new HttpServer(80))
            {
                proxyServer.AddHandler("/", new MyHandler("dummy"));                 // dummy
                BypassHttpHandler bypasser = new BypassHttpHandler("http://localhost:8080");
                bypasser.AddExceptPrefix("/bypass/");
                proxyServer.AddDefaultHandler(bypasser);
                proxyServer.Start();

                WebClient agent = new WebClient();
                try
                {
                    agent.DownloadData("http://localhost:80/bypass?abc=123");
                }
                catch (WebException e)
                {
                    Assert.AreEqual(WebExceptionStatus.ProtocolError, e.Status);
                    using (StreamReader r = new StreamReader(e.Response.GetResponseStream()))
                    {
                        string        json = r.ReadToEnd();
                        CloudResponse resp = fastJSON.JSON.Instance.ToObject <CloudResponse>(json);
                        Assert.AreEqual(-1, resp.api_ret_code);
                        Assert.AreEqual(403, resp.status);
                        Assert.AreEqual("Station does not support this REST API; only Cloud does",
                                        resp.api_ret_message);
                    }
                    return;
                }

                Assert.Fail("Expected exception is not thrown");
            }
        }
示例#6
0
        public void setUp()
        {
            wammerDb = mongodb.GetDatabase("wammer");
            if (wammerDb.CollectionExists("attachments"))
            {
                wammerDb.DropCollection("attachments");
            }

            wammerDb.CreateCollection("attachments");

            objectId1 = Guid.NewGuid().ToString();

            doc = new Attachment
            {
                object_id   = objectId1,
                title       = "title1",
                description = "description1"
            };

            AttachmentCollection.Instance.Save(doc);


            handler = new AttachmentGetHandler();
            server  = new HttpServer(8080);
            server.AddHandler("/api/get/", handler);
            server.Start();
            //host = new WebServiceHost(svc, new Uri("http://localhost:8080/api/"));
            //host.Open();
        }
示例#7
0
        public BanManager(
            IDashboardCommandHandler handler,
            HttpServer httpServer,
            IPasswordFile passwordFile,
            IDatabase <string, PlayerBan> banDatabase,
            ObjectPool <StringBuilder> sbPool,
            IEventManager eventManager,
            ILogManager logManager,
            FileOperationHandler fileOperationHandler,
            RecordOperationHandler operationHandler)
        {
            _banDatabase = banDatabase;
            _sbPool      = sbPool;
            _logManager  = logManager;

            logManager.LogInformation($"Ban Manager loaded {_banDatabase.Elements.Count()} bans.");

            handler.AddCommand(new DashboardCommand(operationHandler.Handle, "/ban",
                                                    "ban database record operations. Usage: /ban add/remove/exists/info ip/name [--offline] [Player Name / IP Address] [reason]. Note that the player name and reason may be supplied in quotes (\").",
                                                    6, 3));

            handler.AddCommand(new DashboardCommand(fileOperationHandler.Handle, "/bans",
                                                    "ban database file operations. Usage: /bans list/purge/download", 1, 1));

            eventManager.RegisterListener(this);

            foreach (var password in passwordFile.Passwords)
            {
                httpServer.AddHandler(new DynamicHandler($"/bans.csv?{password}", GenerateHttpResponseBody));
            }
        }
示例#8
0
        private static HttpServer PrepareHttpServer()
        {
            var server = new HttpServer(int.Parse(Settings.HttpPort));

            return(server
                   .AddHandler(HologramsHandler.Instance));
        }
示例#9
0
        public void TestObjectUploadHandler_ResponseCompleted()
        {
            using (HttpServer cloud = new HttpServer(8080))
                using (HttpServer server = new HttpServer(80))
                {
                    List <UserGroup> groups = new List <UserGroup>();
                    groups.Add(new UserGroup {
                        creator_id = "id1", group_id = "gid1", name = "group1", description = "none"
                    });
                    FileStorage fileStore = new FileStorage(new Driver {
                        email = "*****@*****.**", folder = @"resource\group1", groups = groups, session_token = "session_token1", user_id = "id1"
                    });
                    AttachmentUploadHandler handler = new AttachmentUploadHandler();

                    DummyRequestCompletedHandler evtHandler = new DummyRequestCompletedHandler();
                    handler.ImageAttachmentCompleted += evtHandler.Handle;

                    server.AddHandler("/test/", handler);
                    server.Start();

                    cloud.AddHandler("/" + CloudServer.DEF_BASE_PATH + "/attachments/upload/",
                                     new DummyImageUploadHandler());
                    cloud.Start();

                    ObjectUploadResponse res = Wammer.Model.Attachment.UploadImage(
                        "http://localhost:80/test/", new ArraySegment <byte>(imageRawData), "group1", null,
                        "orig_name.jpeg", "image/jpeg", ImageMeta.Origin, "apiKey1", "token1");

                    Assert.IsTrue(evtHandler.EventReceived());
                }
        }
        public void TestView_ByPOST()
        {
            using (HttpServer server = new HttpServer(80))
            {
                server.AddHandler("/v1/objects/view", new AttachmentViewHandler("sid"));
                server.Start();

                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(
                    "http://localhost/v1/objects/view");
                req.ContentType = "application/x-www-form-urlencoded";
                req.Method      = "POST";
                using (StreamWriter fs = new StreamWriter(req.GetRequestStream()))
                {
                    fs.Write("object_id=" + object_id1.ToString());
                }

                HttpWebResponse response = (HttpWebResponse)req.GetResponse();
                Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
                Assert.AreEqual("image/png", response.ContentType);

                using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                {
                    string responseText = reader.ReadToEnd();
                    Assert.AreEqual("1234567890", responseText);
                }
            }
        }
        public void TestView_AlsoForwardBodyRequestToCloud_ByGet()
        {
            using (HttpServer cloud = new HttpServer(80))
                using (HttpServer server = new HttpServer(8080))
                {
                    cloud.AddHandler("/v1/objects/view", new FakeCloudRemoteHandler());
                    cloud.Start();
                    server.AddHandler("/v1/objects/view", new AttachmentViewHandler("sid"));
                    server.Start();

                    HttpWebRequest req = (HttpWebRequest)WebRequest.Create(
                        "http://localhost:8080/v1/objects/view" +
                        "?object_id=abc&apikey=123&session_token=token123");

                    HttpWebResponse response = (HttpWebResponse)req.GetResponse();
                    Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
                    Assert.AreEqual("image/jpeg", response.ContentType);

                    using (BinaryReader reader = new BinaryReader(response.GetResponseStream()))
                    {
                        byte[] readData = reader.ReadBytes(1000);
                        Assert.AreEqual(10, readData.Length);

                        for (int i = 0; i < readData.Length; i++)
                        {
                            Assert.AreEqual((byte)i + 1, readData[i]);
                        }
                    }

                    Assert.AreEqual("sid", FakeCloudRemoteHandler.SavedParams["station_id"]);
                }
        }
示例#12
0
        public void TestStationRecv_NewThumbnailImage()
        {
            using (HttpServer cloud = new HttpServer(8080))
                using (HttpServer server = new HttpServer(80))
                {
                    List <UserGroup> groups = new List <UserGroup>();
                    groups.Add(new UserGroup {
                        creator_id = "id1", group_id = "gid1", name = "group1", description = "none"
                    });
                    FileStorage fileStore = new FileStorage(new Driver {
                        email = "*****@*****.**", folder = @"resource\group1", groups = groups, session_token = "session_token1", user_id = "id1"
                    });
                    AttachmentUploadHandler handler = new AttachmentUploadHandler();
                    server.AddHandler("/test/", handler);
                    server.Start();
                    cloud.AddHandler("/" + CloudServer.DEF_BASE_PATH + "/attachments/upload/",
                                     new DummyImageUploadHandler());
                    cloud.Start();

                    string oid = Guid.NewGuid().ToString();
                    ObjectUploadResponse res = Wammer.Model.Attachment.UploadImage(
                        "http://localhost:80/test/", new ArraySegment <byte>(imageRawData), "group1", oid,
                        "orig_name2.jpeg", "image/jpeg", ImageMeta.Large, "apikey1", "token1");

                    // verify
                    Assert.AreEqual(oid, res.object_id);
                    using (FileStream f = fileStore.Load(oid + "_large.jpeg"))
                    {
                        Assert.AreEqual((long)imageRawData.Length, f.Length);
                        for (int i = 0; i < imageRawData.Length; i++)
                        {
                            Assert.AreEqual((int)imageRawData[i], f.ReadByte());
                        }
                    }

                    BsonDocument saveData = mongodb.GetDatabase("wammer").
                                            GetCollection("attachments").FindOne(
                        new QueryDocument("_id", oid));

                    Assert.IsNotNull(saveData);
                    Assert.IsFalse(saveData.Contains("title"));
                    Assert.IsFalse(saveData.Contains("description"));
                    Assert.IsFalse(saveData.Contains("mime_type"));
                    Assert.IsFalse(saveData.Contains("url"));
                    Assert.IsFalse(saveData.Contains("file_size"));
                    Assert.AreEqual((int)AttachmentType.image, saveData["type"].AsInt32);
                    BsonDocument meta = saveData["image_meta"].AsBsonDocument;
                    Assert.AreEqual(
                        string.Format("/v2/attachments/view/?object_id={0}&image_meta=large",
                                      res.object_id),
                        meta["large"].AsBsonDocument["url"].AsString);

                    Assert.AreEqual(res.object_id + "_large.jpeg",
                                    meta["large"].AsBsonDocument["file_name"]);
                    Assert.AreEqual(imageRawData.Length, meta["large"].AsBsonDocument["file_size"].ToInt32());
                    Assert.AreEqual("image/jpeg", meta["large"].AsBsonDocument["mime_type"].AsString);
                }
        }
示例#13
0
        void InitHttpServer(int port, bool ssl)
        {
            HttpServer = new HttpServer(HttpPort, ssl);

            // Login webpage HEAD request, used to check if the login webpage is alive
            HttpServer.AddHandler("head", null, "^/loginpage", new HttpServer.HttpRequestCallback(LoginWebpageHeadHandler));

            // Login webpage GET request, gets the login webpage data (purely aesthetic)
            HttpServer.AddHandler("get", null, "^/loginpage", new HttpServer.HttpRequestCallback(LoginWebpageGetHandler));

            // Client XML-RPC login
            HttpServer.AddHandler("post", "text/xml", "^/login", new HttpServer.HttpRequestCallback(LoginXmlRpcPostHandler));

            // Client LLSD login
            HttpServer.AddHandler("post", "application/xml", "^/login", new HttpServer.HttpRequestCallback(LoginLLSDPostHandler));

            HttpServer.Start();
        }
示例#14
0
 public EventQueueServer(HttpServer server, string path)
 {
     HttpRequestSignature signature = new HttpRequestSignature();
     signature.Method = "post";
     signature.ContentType = String.Empty;
     signature.Path = path;
     HttpServer.HttpRequestCallback callback = new HttpServer.HttpRequestCallback(EventQueueHandler);
     HttpServer.HttpRequestHandler handler = new HttpServer.HttpRequestHandler(signature, callback);
     server.AddHandler(handler);
 }
示例#15
0
        public void TestObjectReceiveHandler_UploadNewSmallImage()
        {
            using (FakeCloud cloud = new FakeCloud(cloudResponse))
                using (HttpServer server = new HttpServer(8080))
                {
                    server.AddHandler("/test/", new AttachmentUploadHandler());
                    server.Start();

                    ObjectUploadResponse res = null;
                    using (FileStream input = File.OpenRead("Penguins.jpg"))
                        using (MemoryStream output = new MemoryStream())
                        {
                            input.CopyTo(output);
                            res = Attachment.UploadImage("http://*****:*****@"resource\group1\" + res.object_id + ".jpg"));

                            using (Bitmap largeImg = new Bitmap(@"resource\group1\" + res.object_id + "_large.jpg"))
                            {
                                Assert.AreEqual(1024, largeImg.Width);
                                Assert.AreEqual(768, largeImg.Height);
                            }
                        }
                }
        }
        public void TestInvokingPathHasNoEndingSlash()
        {
            using (HttpServer server = new HttpServer(80))
            {
                string reply1 = "from handler1";
                string reply2 = "from handler2";

                server.AddHandler("/class1/action1/", new MyHandler(reply1));
                server.AddHandler("/class1", new MyHandler(reply2));
                server.Start();

                WebClient agent             = new WebClient();
                string    replyFromHandler1 = agent.DownloadString(
                    "http://127.0.0.1:80/class1/action1");
                string replyFromHandler2 = agent.DownloadString(
                    "http://127.0.0.1:80/class1");
                Assert.AreEqual(reply1, replyFromHandler1);
                Assert.AreEqual(reply2, replyFromHandler2);
            }
        }
示例#17
0
 private static void Main()
 {
     using (var server = new HttpServer())
     {
         server.AddListener(new HttpListener(server, IPAddress.Any, 8080));
         server.AddListener(new HttpsListener(server, IPAddress.Any, 8081, new X509Certificate2("key.pfx")));
         server.AddHandler(new GenericHttpHandler(new TestServer()));
         server.StartListen();
         server.WaitForAll();
     }
 }
示例#18
0
        static void Main(string[] args)
        {
            XmlConfigurator.Configure();
            try
            {
                var contractsUpdater = new ContractsUpdater(abiFilepath, contractByteCodePath, Settings.GethRpcUrl, Settings.CoinbasePass, Settings.ContactCreationGas, Settings.ContractDeployPeriod);
                contractsUpdater.Start();

                var httpServer = new HttpServer(port);
                httpServer
                .AddHandler(HttpMethod.Get.ToString(), latestContractHttpPath, context => context.WriteStringAsync(contractsUpdater.MostRecentContract?.Address))
                .AddHandler(HttpMethod.Get.ToString(), coinbaseHttpPath, async context =>
                {
                    var coinbaseAddress = contractsUpdater.CoinbaseAddress;
                    if (coinbaseAddress == null)
                    {
                        throw new HttpException((int)HttpStatusCode.NotFound, "can't find coinbase. my geth node still not running?");
                    }
                    await context.WriteStringAsync(contractsUpdater.CoinbaseAddress);
                })
                .AddHandler(HttpMethod.Get.ToString(), "/", async context =>
                {
                    context.Response.ContentType = "text/plain";
                    await context.WriteStringAsync(@"Hello! This is PirateCoin service. It's a smart contracts deploying service, based on Ethereum blockchain.
This service does not store any flag by itself, it only serves as a coins wallet.
You can rather buy flags on BlackMarket after you steal coins from other team's smart contracts.

Check blockchain and find other team's smart contracts, which are regularly populated by checksystem with coins,
and try to steal that coins from them. If you manage to convince BlackMarket that you stole coins
from other team's contract, you'll be given team's flag(s).

NOTE that:
 * 'steal' means: withdraw more than you deposited
 * The steal should be a result of a single transaction rather than a result of complex set of your actions 
 * Your smart contract, which helps you steal coins, will be checked by BlackMarket according to this ABI:
   [{""constant"":true,""inputs"":[],""name"":""ownerIp"",""outputs"":[{""name"":"""",""type"":""uint32""}],""payable"":false,""stateMutability"":""view"",
   ""type"":""function""},{""payable"":true,""stateMutability"":""payable"",""type"":""fallback""}]{""payable"":true,""stateMutability"":""payable"",""type"":""fallback""}]

   -> so it should contain a public variable named 'ownerIp' with any packed ip-address from your team's subnet.
      'packed' means BlackMarket will unpack it with: new IPAddress(BitConverter.GetBytes(ownerIp)).ToString()

Use /checkTransaction?transaction=<STEALING_TRANSACTION_HASH>&contractAddr=<VICTIM_SMART_CONTRACT_ADDR>
on http://blackmarket.piratecoin.ructfe.org:14474 (which is http://10.10.10.101:14474) after you steal the coins.

GL HF");
                })
                .AcceptLoopAsync(CancellationToken.None)
                .Wait();
            }
            catch (Exception e)
            {
                log.Fatal("Unexpected App Error", e);
            }
        }
        public void setUp()
        {
            server  = new HttpServer(8080);
            handler = new AddDriverHandler("stationId", "resource");
            server.AddHandler("/v2/station/drivers/add/", handler);
            server.Start();

            CloudServer.BaseUrl = "http://localhost/v2/";

            mongodb.GetDatabase("wammer").GetCollection <Driver>("drivers").RemoveAll();
            mongodb.GetDatabase("wammer").GetCollection("station").RemoveAll();
        }
示例#20
0
        public void TestStationRecv_OldOriginalImage()
        {
            using (HttpServer cloud = new HttpServer(8080))
                using (HttpServer server = new HttpServer(80))
                {
                    List <UserGroup> groups = new List <UserGroup>();
                    groups.Add(new UserGroup {
                        creator_id = "id1", group_id = "gid1", name = "group1", description = "none"
                    });
                    FileStorage fileStore = new FileStorage(new Driver {
                        email = "*****@*****.**", folder = @"resource\group1", groups = groups, session_token = "session_token1", user_id = "id1"
                    });
                    AttachmentUploadHandler handler = new AttachmentUploadHandler();
                    server.AddHandler("/test/", handler);
                    server.Start();
                    cloud.AddHandler("/" + CloudServer.DEF_BASE_PATH + "/attachments/upload/",
                                     new DummyImageUploadHandler());
                    cloud.Start();

                    ObjectUploadResponse res = Wammer.Model.Attachment.UploadImage(
                        "http://localhost:80/test/", new ArraySegment <byte>(imageRawData), "group1", object_id1,
                        "orig_name2.png", "image/png", ImageMeta.Origin, "apikey1", "token1");

                    // verify saved file
                    using (FileStream f = fileStore.Load(object_id1 + ".png"))
                    {
                        byte[] imageData = new byte[f.Length];
                        Assert.AreEqual(imageData.Length, f.Read(imageData, 0, imageData.Length));

                        for (int i = 0; i < f.Length; i++)
                        {
                            Assert.AreEqual(imageData[i], imageRawData[i]);
                        }
                    }

                    // verify db
                    MongoCursor <Attachment> cursor =
                        mongodb.GetDatabase("wammer").GetCollection <Attachment>("attachments")
                        .Find(new QueryDocument("_id", object_id1));


                    Assert.AreEqual <long>(1, cursor.Count());
                    foreach (Attachment doc in cursor)
                    {
                        Assert.AreEqual(object_id1, doc.object_id);
                        Assert.AreEqual("orig_desc", doc.description);
                        Assert.AreEqual("orig_title", doc.title);
                        Assert.AreEqual(AttachmentType.image, doc.type);
                        Assert.AreEqual(imageRawData.Length, doc.file_size);
                        Assert.AreEqual("image/png", doc.mime_type);
                    }
                }
        }
        public void TestByPass()
        {
            using (HttpServer proxyServer = new HttpServer(80))
                using (HttpServer targetServer = new HttpServer(8080))
                {
                    MyForwardedHandler target = new MyForwardedHandler();
                    targetServer.AddHandler("/target/", target);
                    targetServer.Start();
                    proxyServer.AddHandler("/", new MyHandler("21212"));             // dummy
                    proxyServer.AddDefaultHandler(new BypassHttpHandler("http://localhost:8080"));
                    proxyServer.Start();

                    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(
                        "http://localhost:80/target/?abc=123&qaz=wsx");

                    request.ContentType   = "application/shawn";
                    request.Method        = "POST";
                    request.ContentLength = 20;

                    request.CookieContainer = new CookieContainer();
                    request.CookieContainer.Add(new Cookie("cookie1", "val1", "", "localhost"));
                    request.CookieContainer.Add(new Cookie("cookie2", "val2", "", "localhost"));

                    using (StreamWriter w = new StreamWriter(request.GetRequestStream()))
                    {
                        w.Write("1234567890qwertyuiop");
                    }

                    HttpWebResponse resp = (HttpWebResponse)request.GetResponse();

                    Assert.AreEqual(request.ContentType, MyForwardedHandler.recvContentType);
                    Assert.AreEqual(request.ContentLength, MyForwardedHandler.recvContentLength);
                    Assert.AreEqual(request.Method, MyForwardedHandler.recvMethod);
                    Assert.AreEqual("val1", MyForwardedHandler.recvCookies["cookie1"].Value);
                    Assert.AreEqual("val2", MyForwardedHandler.recvCookies["cookie2"].Value);
                    Assert.AreEqual(2, MyForwardedHandler.recvCookies.Count);
                    Assert.AreEqual("123", MyForwardedHandler.recvQueryString["abc"]);
                    Assert.AreEqual("wsx", MyForwardedHandler.recvQueryString["qaz"]);
                    Assert.AreEqual("/target/", MyForwardedHandler.recvPath);
                    Assert.AreEqual("1234567890qwertyuiop", MyForwardedHandler.recvData);

                    using (StreamReader r = new StreamReader(resp.GetResponseStream()))
                    {
                        Assert.AreEqual("write from target", r.ReadToEnd());
                    }

                    Assert.AreEqual(2, resp.Cookies.Count);
                    Assert.AreEqual("111", resp.Cookies["aaa"].Value);
                    Assert.AreEqual("/target/", resp.Cookies["aaa"].Path);
                    Assert.AreEqual("222", resp.Cookies["bbb"].Value);
                }
        }
示例#22
0
        private static HttpServer PrepareServer(SimpleSettings settings)
        {
            var port = int.Parse(settings.GetValue("port"));

            var server = new HttpServer(port);

            server
            .AddHandler(LoginHandler.Instance)
            .AddHandler(AddPointHandler.Instance)
            .AddHandler(GetAllPublicsHandler.Instance)
            .AddHandler(GetPointsHandler.Instance)
            .AddHandler(ShortestPathHandler.Instance);

            return(server);
        }
        public void TestDefaultHandler()
        {
            using (HttpServer server = new HttpServer(80))
            {
                string reply1 = "from handler1";

                server.AddDefaultHandler(new MyHandler("1234567890"));
                server.AddHandler("/class1/action1/", new MyHandler(reply1));
                server.Start();

                WebClient agent             = new WebClient();
                string    replyFromHandler1 = agent.DownloadString(
                    "http://127.0.0.1:80/class1/action1/pp/");
                Assert.AreEqual(replyFromHandler1, "1234567890");
            }
        }
示例#24
0
        public void TestObjectUploadHandler_SessionTokenIsInParams()
        {
            using (HttpServer server = new HttpServer(80))
            {
                DummyImageUploadHandler handler = new DummyImageUploadHandler();
                server.AddHandler("/test/", handler);
                server.Start();

                ObjectUploadResponse res = Wammer.Model.Attachment.UploadImage(
                    "http://localhost:80/test/", new ArraySegment <byte>(imageRawData), "group1", null,
                    "orig_name.jpeg", "image/jpeg", ImageMeta.Origin, "apikey1", "token1");

                Assert.AreEqual("token1",
                                DummyImageUploadHandler.recvParameters["session_token"]);
            }
        }
        public void TestEncoding()
        {
            using (HttpServer server = new HttpServer(80))
            {
                MyHandler2 h2 = new MyHandler2();
                server.AddHandler("/class1/action1/", h2);
                server.Start();

                WebClient agent             = new WebClient();
                string    replyFromHandler1 = agent.DownloadString(
                    "http://127.0.0.1:80/class1/action1/?email=sh%40wave.com&password=a+b&f**k=KE1fz9mriidjlLmhGgF7WVXl.K5xxvp8gb1rQVKjBNcrrQq8xjtCxhmAxo%2bqWzwoEy0g");


                Assert.AreEqual("*****@*****.**", MyHandler2.SavedParameters["email"]);
                Assert.AreEqual("a b", MyHandler2.SavedParameters["password"]);
                Assert.AreEqual("KE1fz9mriidjlLmhGgF7WVXl.K5xxvp8gb1rQVKjBNcrrQq8xjtCxhmAxo+qWzwoEy0g", MyHandler2.SavedParameters["f**k"]);
            }
        }
        public void TestEncoding_POST()
        {
            using (HttpServer server = new HttpServer(80))
            {
                MyHandler2 h2 = new MyHandler2();
                server.AddHandler("/class1/action1/", h2);
                server.Start();

                WebClient agent = new WebClient();
                string    text  = "email=sh%40wave.com&password=a+b&f**k=KE1fz9mriidjlLmhGgF7WVXl.K5xxvp8gb1rQVKjBNcrrQq8xjtCxhmAxo%2bqWzwoEy0g";
                agent.Headers.Add("Content-Type:application/x-www-form-urlencoded");
                agent.UploadData("http://127.0.0.1:80/class1/action1/", Encoding.UTF8.GetBytes(text));


                Assert.AreEqual("*****@*****.**", MyHandler2.SavedParameters["email"]);
                Assert.AreEqual("a b", MyHandler2.SavedParameters["password"]);
                Assert.AreEqual("KE1fz9mriidjlLmhGgF7WVXl.K5xxvp8gb1rQVKjBNcrrQq8xjtCxhmAxo+qWzwoEy0g", MyHandler2.SavedParameters["f**k"]);
            }
        }
        private async void FetchLogRequested(DashboardCommandNotification obj)
        {
            if (!_logManager.EnumerateLogFiles().Contains(obj.Tokens[0]))
            {
                await obj.User.Write(_messageFactory.CreateFetchLog(null, false));

                return;
            }

            foreach (var password in _passwords)
            {
                var path = $"/logs.csv?{password}&{obj.Tokens[0]}.csv";
                if (!_server.ContainsHandler(path))
                {
                    _server.AddHandler(new StaticHandler(path, _logManager.GetFullPath(obj.Tokens[0]), "text/csv"));
                }
            }

            await obj.User.Write(_messageFactory.CreateFetchLog(obj.Tokens[0], true));
        }
        public void TestView_FileNotFound_ForwardToCloud_ByPost()
        {
            CloudServer.BaseUrl = "http://localhost/v2/";

            RawDataResponseWriter writer = new RawDataResponseWriter
            {
                RawData     = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 },
                ContentType = "image/jpeg"
            };

            using (FakeCloud cloud = new FakeCloud(writer))
                using (HttpServer server = new HttpServer(8080))
                {
                    server.AddHandler("/v1/objects/view", new AttachmentViewHandler("sid"));
                    server.Start();

                    HttpWebRequest req = (HttpWebRequest)WebRequest.Create(
                        "http://localhost:8080/v1/objects/view");
                    req.ContentType = "application/x-www-form-urlencoded";
                    req.Method      = "POST";
                    using (StreamWriter fs = new StreamWriter(req.GetRequestStream()))
                    {
                        fs.Write("object_id=abc&apikey=123&session_token=token123&image_meta=medium");
                    }

                    HttpWebResponse response = (HttpWebResponse)req.GetResponse();
                    Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
                    Assert.AreEqual("image/jpeg", response.ContentType);

                    using (BinaryReader reader = new BinaryReader(response.GetResponseStream()))
                    {
                        byte[] readData = reader.ReadBytes(1000);
                        Assert.AreEqual(writer.RawData.Length, readData.Length);

                        for (int i = 0; i < readData.Length; i++)
                        {
                            Assert.AreEqual(writer.RawData[i], readData[i]);
                        }
                    }
                }
        }
        public void setUp()
        {
            server  = new HttpServer(8080);
            handler = new RemoveOwnerHandler("stationId");
            server.AddHandler("/v2/station/drivers/remove/", handler);
            server.Start();

            if (!Directory.Exists(@"C:\TempUT"))
            {
                Directory.CreateDirectory(@"c:\TempUT");
            }
            if (!Directory.Exists(@"C:\TempUT\user1"))
            {
                Directory.CreateDirectory(@"c:\TempUT\user1");
            }

            CloudServer.BaseUrl = "http://localhost/v2/";

            mongodb.GetDatabase("wammer").GetCollection <Driver>("drivers").RemoveAll();
            mongodb.GetDatabase("wammer").GetCollection("station").RemoveAll();
        }
        public void TestRestartHttpServer()
        {
            using (HttpServer server = new HttpServer(80))
            {
                string reply1 = "from handler1";

                server.AddHandler("/class1/action1/", new MyHandler(reply1));
                server.Start();

                WebClient agent = new WebClient();
                Assert.AreEqual(reply1, agent.DownloadString("http://127.0.0.1:80/class1/action1"));


                server.Stop();

                System.Threading.Thread.Sleep(1000);
                server.Start();

                Assert.AreEqual(reply1, agent.DownloadString("http://127.0.0.1:80/class1/action1"));
            }
        }
示例#31
0
文件: Program.cs 项目: s-buss/Deimos
        static void Main(string[] args)
        {
            Log.ToConsole();

            if (args.Length != 1)
            {
                Console.WriteLine("Usage: RequestLogger <port number>", args[0]);
                return;
            }

            int portNumber;

            if (!int.TryParse(args[0], out portNumber))
            {
                Console.WriteLine("Illegal port number.", args[0]);
                return;
            }

            HttpServer server = new HttpServer(portNumber);

            server.AddHandler(new Handler());
            server.Run();
        }
示例#32
0
        void InitHttpServer(int port, bool ssl)
        {
            HttpServer = new HttpServer(HttpPort, ssl);

            // Login webpage HEAD request, used to check if the login webpage is alive
            HttpServer.AddHandler("head", null, "^/loginpage", new HttpServer.HttpRequestCallback(LoginWebpageHeadHandler));

            // Login webpage GET request, gets the login webpage data (purely aesthetic)
            HttpServer.AddHandler("get", null, "^/loginpage", new HttpServer.HttpRequestCallback(LoginWebpageGetHandler));

            // Client XML-RPC login
            HttpServer.AddHandler("post", "text/xml", "^/login", new HttpServer.HttpRequestCallback(LoginXmlRpcPostHandler));

            // Client LLSD login
            HttpServer.AddHandler("post", "application/xml", "^/login", new HttpServer.HttpRequestCallback(LoginLLSDPostHandler));

            HttpServer.Start();
        }
示例#33
0
        void InitHttpServer(int port, bool ssl)
        {
            HttpServer = new HttpServer(tcpPort, ssl);

            // Login webpage HEAD request, used to check if the login webpage is alive
            HttpRequestSignature signature = new HttpRequestSignature();
            signature.Method = "head";
            signature.ContentType = String.Empty;
            signature.Path = "/loginpage";
            HttpServer.HttpRequestCallback callback = new HttpServer.HttpRequestCallback(LoginWebpageHeadHandler);
            HttpServer.HttpRequestHandler handler = new HttpServer.HttpRequestHandler(signature, callback);
            HttpServer.AddHandler(handler);

            // Login webpage GET request, gets the login webpage data (purely aesthetic)
            signature.Method = "get";
            signature.ContentType = String.Empty;
            signature.Path = "/loginpage";
            callback = new HttpServer.HttpRequestCallback(LoginWebpageGetHandler);
            handler.Signature = signature;
            handler.Callback = callback;
            HttpServer.AddHandler(handler);

            // Client XML-RPC login
            signature.Method = "post";
            signature.ContentType = "text/xml";
            signature.Path = "/login";
            callback = new HttpServer.HttpRequestCallback(LoginXmlRpcPostHandler);
            handler.Signature = signature;
            handler.Callback = callback;
            HttpServer.AddHandler(handler);

            // Client LLSD login
            signature.Method = "post";
            signature.ContentType = "application/xml";
            signature.Path = "/login";
            callback = new HttpServer.HttpRequestCallback(LoginLLSDPostHandler);
            handler.Signature = signature;
            handler.Callback = callback;
            HttpServer.AddHandler(handler);

            HttpServer.Start();
        }