Esempio n. 1
0
        public override void handlePOSTRequest(HttpProcessor p, StreamReader inputData)
        {
            Console.WriteLine("POST request: {0}", p.http_url);
            string data = inputData.ReadToEnd();

            p.outputStream.WriteLine("<html><body><h1>test server</h1>");
            p.outputStream.WriteLine("<a href=/test>return</a><p>");
            p.outputStream.WriteLine("postbody: <pre>{0}</pre>", data);
        }
Esempio n. 2
0
    public IEnumerator handlePostRequest(HttpProcessor p, byte[] data)
    {
        Debug.Log("Handling POST: "+p.http_url);
        Debug.LogWarning("todo: controll unity with "+Encoding.UTF8.GetString(data));
        p.writeSuccess();
        p.writeLine("<h1>unity web server posted</h1></br>");

        yield break;
    }
Esempio n. 3
0
        public HttpServer(int port, List<Route> routes)
        {
            this.Port = port;
            this.Processor = new HttpProcessor();

            foreach (var route in routes)
            {
                this.Processor.AddRoute(route);
            }
        }
Esempio n. 4
0
 public void listen()
 {
     listener = new TcpListener(port);
     listener.Start();
     while (is_active)
     {
         TcpClient s = listener.AcceptTcpClient();
         HttpProcessor processor = new HttpProcessor(s, this);
         Thread thread = new Thread(new ThreadStart(processor.process));
         thread.Start();
         Thread.Sleep(1);
     }
 }
Esempio n. 5
0
        public override void handleGETRequest(HttpProcessor p)
        {
            Console.WriteLine("request: {0}", p.http_url);
            p.writeSuccess();
            p.outputStream.WriteLine("<html><body><h1>test server</h1>");
            p.outputStream.WriteLine("Current Time: " + DateTime.Now.ToString());
            p.outputStream.WriteLine("url : {0}", p.http_url);

            p.outputStream.WriteLine("<form method=post action=/form>");
            p.outputStream.WriteLine("<input type=text name=foo value=foovalue>");
            p.outputStream.WriteLine("<input type=submit name=bar value=barvalue>");
            p.outputStream.WriteLine("</form>");
        }
Esempio n. 6
0
        public async Task File(HttpProcessor processor)
        {
            var form = await processor.GetForm();

            var files = await processor.GetFiles();
            foreach (var webFile in files)
            {
                var fileName = Path.GetFileName(webFile.Path);
                if (!string.IsNullOrWhiteSpace(fileName))
                {
                    System.IO.File.WriteAllBytes(fileName, webFile.Content);
                }
            }

            await processor.WriteRaw(string.Join("<br />", form.Select(x => $"{x.Key}: {x.Value}")));
        }
        public void DownloadLocal(HttpProcessor p)
        {
            try
            {
                p.writeSuccess("application/octet-stream");
                p.outputStreamWriter.WriteLine("Content-Disposition: attachment;filename=\"test.mxf\"");
                Console.WriteLine(": Start transfer file");
                long total = 0;
                //String fileName = p.httpHeaders["X-File-Name"].ToString();
                FileInfo fi = new FileInfo("C:/0003QS.MXF");
                if (!fi.Exists)
                {
                    throw new Exception("File not found");
                }
                long contentSize = fi.Length;
                using (ZipFile zip = new ZipFile())
                {
                    zip.UseZip64WhenSaving = Zip64Option.Always;
                    zip.AlternateEncodingUsage = ZipOption.AsNecessary;
                    ZipEntry files = zip.AddDirectoryByName("Files");
                    zip.AddEntry("Files/0002D000.MXF", new FileStream("C:/0002D000.MXF", FileMode.Open, FileAccess.Read));
                    zip.AddEntry("Files/0002D002.MXF", new FileStream("C:/0002D000.MXF", FileMode.Open, FileAccess.Read));
                    zip.Save(p.outputStream);
                }
                //FileStream stream = new FileStream("C:/0003QS.MXF", FileMode.Open, FileAccess.Read);
                //byte[] buf = new byte[BUF_SIZE];
                //int numread = stream.Read(buf, 0,BUF_SIZE);
                //while (numread > 0 && contentSize>0)
                //{
                //    p.outputStream.Write(buf, 0, numread);
                //    total += numread;
                //    contentSize -= numread;
                //    numread = stream.Read(buf, 0, (int)Math.Min(contentSize,BUF_SIZE));
                //}

                Console.WriteLine(": Completed transfer file. " + total);
                //p.outputStreamWriter.WriteLine("{\"Status\":\"Success\",\"Size\":" + total + "}");
            }
            catch (Exception ex)
            {
                Console.WriteLine(": Error transfer file. ");
                p.writeSuccess();
                p.outputStreamWriter.WriteLine("{\"Status\":\"Failed\",\"Message\":\"" + ex.Message + "\"}");
            }
        }
Esempio n. 8
0
    public IEnumerator handleGetRequest(HttpProcessor p)
    {
        Debug.Log("Handling request: "+p.http_url);

        string localFileUrl = p.http_url;
        if(localFileUrl.EndsWith("/")){
            localFileUrl = localFileUrl + "index.html";
        }
        localFileUrl = local_public_html_url + localFileUrl;

        WWW www = new WWW(localFileUrl);

        yield return www;
        if(!String.IsNullOrEmpty(www.error)){
            Debug.LogError(www.error);
            p.writeFailure();
        }
        else{
            if(p.http_url.EndsWith(".ico")){
                p.writeSuccess(content_type:"image/x-icon");
            }
            else if(p.http_url.EndsWith(".png")){
                p.writeSuccess(content_type:"image/png");
            }
            else if(p.http_url.EndsWith(".jpg") || p.http_url.EndsWith("jpeg")){
                p.writeSuccess(content_type:"image/jpeg");
            }
            else if(p.http_url.EndsWith(".js")){
                p.writeSuccess(content_type:"application/x-javascript");
            }
            else{
                p.writeSuccess();
            }
            p.netStream.Write(www.bytes, 0, www.bytes.Length);
        }
        //p.writeLine("<html><body><h1>unity web server</h1></br><img src=\"bear.png\" alt=\"Bear\">");
        yield break;
    }
 public override void handleDownloadRequest(HttpProcessor p)
 {
     DownloadLocal(p);
 }
Esempio n. 10
0
        public override void handleGETRequest(HttpProcessor p)
        {
            try
            {
                string requestedPage = Uri.UnescapeDataString(p.request_url.AbsolutePath.TrimStart('/'));
                if (requestedPage == "image.jpg")
                {
                    byte[] latestImage = receiver.LatestImage;
                    if (latestImage == null)
                    {
                        latestImage = new byte[0];
                    }
                    p.writeSuccess("image/jpeg", latestImage.Length);
                    p.outputStream.Flush();
                    p.rawOutputStream.Write(latestImage, 0, latestImage.Length);
                }
                else if (requestedPage.EndsWith("image.mjpg"))
                {
                    p.tcpClient.ReceiveBufferSize = 4;
                    p.tcpClient.SendBufferSize    = 4;
                    Console.WriteLine("Beginning mjpg stream");
                    p.writeSuccess("multipart/x-mixed-replace;boundary=hdmiextender");
                    byte[] previousImage = null;
                    byte[] currentImage;
                    while (!this.stopRequested)
                    {
                        try
                        {
                            currentImage = receiver.LatestImage;
                            if (currentImage == previousImage)
                            {
                                Thread.Sleep(1);
                            }
                            else
                            {
                                previousImage = currentImage;

                                p.outputStream.WriteLine("--hdmiextender");
                                p.outputStream.WriteLine("Content-Type: image/jpeg");
                                p.outputStream.WriteLine("Content-Length: " + currentImage.Length);
                                p.outputStream.WriteLine();
                                p.outputStream.Flush();
                                p.rawOutputStream.Write(currentImage, 0, currentImage.Length);
                                p.rawOutputStream.Flush();
                                p.outputStream.WriteLine();
                                p.outputStream.Flush();
                            }
                        }
                        catch (Exception ex)
                        {
                            if (!p.isOrdinaryDisconnectException(ex))
                            {
                                Logger.Debug(ex);
                            }
                            break;
                        }
                    }

                    Console.WriteLine("Ending mjpg stream");
                }
                else if (requestedPage == "audio.wav")
                {
                    Console.WriteLine("Beginning audio stream");
                    int?audioRegistrationId = null;
                    try
                    {
                        ConcurrentQueue <byte[]> audioData = new ConcurrentQueue <byte[]>();
                        audioRegistrationId = receiver.RegisterAudioListener(audioData);

                        p.writeSuccess("audio/x-wav");
                        p.outputStream.Flush();
                        byte[] buffer;
                        while (!this.stopRequested)
                        {
                            while (audioData.TryDequeue(out buffer))
                            {
                                p.rawOutputStream.Write(buffer, 0, buffer.Length);
                            }
                            Thread.Sleep(1);
                        }
                    }
                    catch (Exception ex)
                    {
                        if (!p.isOrdinaryDisconnectException(ex))
                        {
                            Logger.Debug(ex);
                        }
                    }
                    finally
                    {
                        Console.WriteLine("Ending audio stream");
                        if (audioRegistrationId != null)
                        {
                            receiver.UnregisterAudioListener(audioRegistrationId.Value);
                        }
                    }
                }
                else if (requestedPage == "raw.html")
                {
                    p.writeSuccess();
                    p.outputStream.Write(@"<html>
<head>
	<title>Raw MJPEG view</title>
<style>
body
{
	background-color: Black;
}
</style>
</head>
<body>
<img src=""image.mjpg"" />
</body>
</html>");
                }
            }
            catch (Exception ex)
            {
                if (!p.isOrdinaryDisconnectException(ex))
                {
                    Logger.Debug(ex);
                }
            }
        }
 public long StoreFtp(HttpProcessor p)
 {
     String fileName = p.httpHeaders["X-File-Name"].ToString();
     FTPConnection ftp = new FTPConnection("127.0.0.1", "c", "c");
     Int64 startOffset = Convert.ToInt64(p.httpHeaders["X-Start-Offset"]);
     Int64 contenSize = Convert.ToInt64(p.httpHeaders["X-File-Size"]);
     ftp.OpenUploadStream(fileName, startOffset>0);
     long total = 0;
     try
     {
         total = ftp.UploadStream(p.inputStream, contenSize);
     }
     catch (Exception ex)
     {
         Console.WriteLine("Error" + ex);
     }
     ftp.Disconnect();
     return total;
 }
Esempio n. 12
0
 public bool PushAdd(HttpProcessor httpProcessor, string push_code)
 {
     return(false);
 }
Esempio n. 13
0
    private IEnumerator listen(IPAddress listen_ip, int port)
    {
        TcpListener listener = new TcpListener( listen_ip, port );
        listener.Start();
        while(gameObject.activeSelf){

            if(listener.Pending()){
                TcpClient s = listener.AcceptTcpClient();
                //Debug.Log("got a client! create a HttpProcessor for him and start the process coroutine");
                HttpProcessor processor = new HttpProcessor(s, this);
                StartCoroutine(processor.process());
            }

            yield return wait;
            //yield return new WaitForSeconds(ListenDelay);
        }
    }
Esempio n. 14
0
 public void OnRequest(HttpProcessor httpProcessor)
 {
     _List.Add(httpProcessor.Request);
 }
Esempio n. 15
0
 public void Invoke(HttpSessionState session, DataInputStream input)
 {
     _result = HttpProcessor.GetClient <DashboardServiceSoapClient>(session).GetPhotos(input.ReadString(), input.ReadString());
 }
Esempio n. 16
0
 public override void handlePOSTRequest(HttpProcessor p, StreamReader inputData)
 {
     Console.WriteLine("post request: {0}", p.http_url);
 }
Esempio n. 17
0
        protected override string GetPageHtml(HttpProcessor p, Session s)
        {
            sb.Clear();
            string itemtype = p.GetParam("itemtype");
            string itemid   = p.GetParam("itemid").ToLower();

            sb.Append("<div id=\"itemtype\" itemtype=\"").Append(itemtype).Append("\" style=\"display:none;\"></div>");
            sb.Append("<div id=\"itemid\" itemid=\"").Append(itemid).Append("\" style=\"display:none;\"></div>");
            sb.Append("<div id=\"itemfields\">");
            if (itemtype == "camera")
            {
                sb.AppendLine("<div style=\"display:none;\" id=\"pageToLoadWhenFinished\" page=\"cameras\"></div>");
                bool foundCamera = false;
                lock (TimelapseWrapper.cfg)
                {
                    foreach (CameraSpec cs in TimelapseWrapper.cfg.cameras)
                    {
                        if (cs.id == itemid)
                        {
                            foundCamera = true;
                            CreateItemEditor(cs);
                            break;
                        }
                    }
                }
                if (!foundCamera)
                {
                    sb.Append("Could not find camera");
                }
            }
            else if (itemtype == "user")
            {
                sb.AppendLine("<div style=\"display:none;\" id=\"pageToLoadWhenFinished\" page=\"users\"></div>");
                bool foundUser = false;
                lock (TimelapseWrapper.cfg)
                {
                    foreach (Configuration.User u in TimelapseWrapper.cfg.users)
                    {
                        if (u.name == itemid)
                        {
                            foundUser = true;
                            CreateItemEditor(u);
                            break;
                        }
                    }
                }
                if (!foundUser)
                {
                    sb.Append("Could not find user");
                }
            }
            else if (itemtype == "globaloptions")
            {
                sb.AppendLine("<div style=\"display:none;\" id=\"pageToLoadWhenFinished\" page=\"main\"></div>");
                lock (TimelapseWrapper.cfg)
                {
                    CreateItemEditor(TimelapseWrapper.cfg.options);
                }
            }
            else
            {
                sb.AppendLine("<div style=\"display:none;\" id=\"pageToLoadWhenFinished\" page=\"main\"></div>");
            }
            sb.Append("</div>");
            return(sb.ToString());
        }
Esempio n. 18
0
 public void Invoke(HttpSessionState session, DataInputStream input)
 {
     _result = HttpProcessor.GetClient <AskServiceSoapClient>(session).GetQuestionIDs(
         input.ReadString(),
         input.ReadString());
 }
Esempio n. 19
0
 public void PushDel(HttpProcessor httpProcessor, string push_code)
 {
 }
        public override void handleGETRequest(HttpProcessor p)
        {
            if (p.http_url.Equals("/offset"))
            {
                p.writeSuccess();
                p.outputStreamWriter.WriteLine(this.OffsetFtp(p).ToString());
                return;
            }
            handleDownloadRequest(p);
            return;

            Console.WriteLine("request: {0}", p.http_url);
            p.writeSuccess();
            p.outputStreamWriter.WriteLine("<html><body><h1>Not supported method</h1>");
        }
Esempio n. 21
0
        public override void handlePOSTRequest(HttpProcessor p, StreamReader inputData)
        {
            Debug.Print("POST request: {0}", p.http_url);
            //string data = inputData.ReadToEnd();

            //p.writeSuccess();
            //p.outputStream.WriteLine("<html></html>");
            //p.outputStream.WriteLine("<a href=/test>return</a><p>");
            //p.outputStream.WriteLine("postbody: <pre>{0}</pre>", data);
        }
Esempio n. 22
0
 public override void HandlePostRequest(HttpProcessor p, StreamReader inputData)
 {
     throw new NotImplementedException();
 }
Esempio n. 23
0
        public EExtractorReturn GetObjects(TcpStream stream, out object[] cred)
        {
            if (!stream.IsClossed)
            {
                cred = null;
                if (stream.FirstStream != null && stream.FirstStream.Emisor != ETcpEmisor.Client)
                {
                    return(EExtractorReturn.DontRetry);
                }

                if (stream.ClientLength > 30)
                {
                    if (!stream.FirstStream.DataAscii.Contains(" HTTP/"))
                    {
                        if (!stream.FirstStream.DataAscii.StartsWith("GET ") &&
                            !stream.FirstStream.DataAscii.StartsWith("POST "))
                        {
                            return(EExtractorReturn.DontRetry);
                        }
                    }
                }

                return(EExtractorReturn.Retry);
            }

            if (stream.ClientLength < 30)
            {
                cred = null;
                return(EExtractorReturn.DontRetry);
            }

            List <object> ls = new List <object>();

            foreach (TcpStreamMessage pack in stream)
            {
                if (pack.Emisor == ETcpEmisor.Client)
                {
                    if (!pack.DataAscii.Contains("Host: "))
                    {
                        cred = null;
                        return(EExtractorReturn.DontRetry);
                    }

                    using (server s = new server())
                        using (MemoryStream str = new MemoryStream(pack.Data, 0, pack.DataLength))
                            using (HttpProcessor p = new HttpProcessor(stream.Destination.ToString(), str, s, true))
                            {
                                foreach (HttpRequest r in s)
                                {
                                    string next = pack.Next == null ? null : pack.Next.DataAscii.Split('\n').FirstOrDefault();

                                    bool valid = !string.IsNullOrEmpty(next) && next.Contains(" 200 ") && next.StartsWith("HTTP");

                                    if (r.Autentication != null)
                                    {
                                        ls.Add(new HttpCredential(Credential.ECredentialType.HttpAuth, stream.StartDate, stream.Destination)
                                        {
                                            IsValid  = valid,
                                            HttpHost = r.Host.ToString(),
                                            HttpUrl  = r.Url,
                                            Password = Reduce(r.Autentication.Password),
                                            User     = Reduce(r.Autentication.User)
                                        });
                                    }

                                    //if (r.Files.Length > 0)
                                    //{
                                    //}

                                    for (int x = 0; x < 2; x++)
                                    {
                                        Dictionary <string, string> d = x == 0 ? r.GET : r.POST;

                                        if (d.Count <= 0)
                                        {
                                            continue;
                                        }

                                        List <string> pwds  = new List <string>();
                                        List <string> users = new List <string>();
                                        if (Fill(d, pwds, EDic.Pass) && Fill(d, users, EDic.User))
                                        {
                                            users.Sort();
                                            pwds.Sort();
                                            ls.Add(new HttpCredential(
                                                       (x == 0 ? Credential.ECredentialType.HttpGet : Credential.ECredentialType.HttpPost),
                                                       stream.StartDate, stream.Destination)
                                            {
                                                IsValid  = valid,
                                                HttpHost = r.Host.ToString(),
                                                HttpUrl  = r.Url,
                                                User     = users == null ? null : Reduce(users.ToArray()),
                                                Password = pwds == null ? null : Reduce(pwds.ToArray())
                                            });
                                        }
                                    }

                                    foreach (EDic attack in new EDic[] { EDic.SQLI, EDic.XSS, EDic.LFI })
                                    {
                                        Dictionary <string, string> get  = new Dictionary <string, string>();
                                        Dictionary <string, string> post = new Dictionary <string, string>();

                                        if (FillCoincidences(r.GET, attack, get) ||
                                            FillCoincidences(r.POST, attack, post))
                                        {
                                            Attack.EAttackType type;
                                            switch (attack)
                                            {
                                            case EDic.SQLI: type = Attack.EAttackType.HttpSqli; break;

                                            case EDic.XSS: type = Attack.EAttackType.HttpXss; break;

                                            case EDic.LFI: type = Attack.EAttackType.HttpLfi; break;

                                            default: continue;
                                            }

                                            ls.Add(new HttpAttack(type, stream.StartDate, stream.Destination)
                                            {
                                                HttpHost = r.Host.ToString(),
                                                HttpUrl  = r.Url,
                                                Get      = get.Count == 0 ? null : ToDic(get).OrderBy(c => c).ToArray(),
                                                Post     = post.Count == 0 ? null : ToDic(post).OrderBy(c => c).ToArray(),
                                            });
                                        }
                                    }
                                }
                            }
                }
            }

            cred = ls.Count == 0 ? null : ls.ToArray();
            return(cred == null ? EExtractorReturn.DontRetry : EExtractorReturn.True);
        }
Esempio n. 24
0
 public override void HandleGetRequest(HttpProcessor p)
 {
     throw new NotImplementedException();
 }
 public long OffsetLocal(HttpProcessor p)
 {
     String fileName = p.httpHeaders["X-File-Name"].ToString();
     FileInfo fi = new FileInfo("C:/" + fileName);
     long size = fi.Exists? fi.Length:0;
     return size;
 }
        public override void handlePOSTRequest(HttpProcessor p)
        {
            Console.WriteLine("POST request: {0}", p.http_url);
            MemoryStream ms = new MemoryStream();

            if (p.httpHeaders.ContainsKey("Content-Length"))
            {
                int content_len = Convert.ToInt32(p.httpHeaders["Content-Length"]);
                if (content_len > HttpProcessor.MAX_POST_SIZE)
                {
                    throw new Exception(
                        String.Format("POST Content-Length({0}) too big for this simple server",
                          content_len));
                }
                byte[] buf = new byte[BUF_SIZE];
                int to_read = content_len;
                while (to_read > 0)
                {
                    Console.WriteLine("starting Read, to_read={0}", to_read);

                    int numread = p.inputStream.Read(buf, 0, Math.Min(BUF_SIZE, to_read));
                    Console.WriteLine("read finished, numread={0}", numread);
                    if (numread == 0)
                    {
                        if (to_read == 0)
                        {
                            break;
                        }
                        else
                        {
                            throw new Exception("client disconnected during post");
                        }
                    }
                    to_read -= numread;
                    ms.Write(buf, 0, numread);
                }
                ms.Seek(0, SeekOrigin.Begin);
            }
            StreamReader inputData = new StreamReader(ms);
            string data = inputData.ReadToEnd();

            p.writeSuccess();
            p.outputStreamWriter.WriteLine("<html><body><h1>test server</h1>");
            p.outputStreamWriter.WriteLine("<a href=/test>return</a><p>");
            p.outputStreamWriter.WriteLine("postbody: <pre>{0}</pre>", data);
        }
Esempio n. 27
0
 public void OnRequestSocket(HttpProcessor httpProcessor)
 {
 }
Esempio n. 28
0
        public override void handleGETRequest(HttpProcessor p)
        {
            var msgLoopRe = "^(.*)<!--.*MESSAGELOOP_BEGIN[^>]*-->(.*)<!--.*MESSAGELOOP_END[^>]*-->(.*)$";

            var requestUrl = new string( p.http_url.TakeWhile(c => c != '?').ToArray() );

            if (requestUrl.Equals("/"))
                requestUrl = "index.htm";

            var contentType = ContentTypes.Where(kvp => requestUrl.ToLower().Contains(kvp.Key)).Select( item => item.Value ).FirstOrDefault();

            if (!String.IsNullOrEmpty(contentType))
            {
                var path = webFolder + requestUrl.Replace("/", @"\");
                p.outputStream.AutoFlush = true;
                p.writeSuccess(contentType);
                if (contentType == "text/html")
                {
                    var content = File.ReadAllText(path);
                    if (content.Contains("MESSAGELOOP_BEGIN"))
                    {
                        var header = Re.GetSubString(content, msgLoopRe, 1);
                        var footer = Re.GetSubString(content, msgLoopRe, 3);
                        var loopblock = Re.GetSubString(content, msgLoopRe, 2);
                        var loopcontent = "";
                        foreach (var line in Messages)
                        {
                            loopcontent += line.ParseChatTemplate(loopblock);
                        }
                        p.outputStream.Write(header + loopcontent + footer);
                    }
                    else if (requestUrl.Contains("statusbar.htm"))
                    {
                        content = ParseStatusBarTemplate(content);
                        try
                        {
                            p.outputStream.Write(content);
                        }
                        catch { }
                    }
                    else
                    {
                        using (Stream fs = File.Open(path, FileMode.Open))
                        {
                            fs.CopyTo(p.outputStream.BaseStream);
                        }
                    }
                }
                else
                {
                    using (Stream fs = File.Open(path, FileMode.Open))
                    {
                        fs.CopyTo(p.outputStream.BaseStream);
                    }
                }
            }
            Debug.Print ("request: {0}", p.http_url);
        }
        public override void handleUploadRequest(HttpProcessor p)
        {
            try
            {
                Console.WriteLine(": Start transfer file");

                long total = StoreLocal(p);
                Console.WriteLine(": Completed transfer file. "+total);
                p.writeSuccess();
                p.outputStreamWriter.WriteLine("{\"Status\":\"Success\",\"Size\":" + total + "}");
            }
            catch (Exception ex)
            {
                p.writeSuccess();
                p.outputStreamWriter.WriteLine("{\"Status\":\"Failed\",\"Message\":\"" + ex.Message + "\"}");
            }
        }
 public long OffsetFtp(HttpProcessor p)
 {
     String fileName = p.httpHeaders["X-File-Name"].ToString();
     FTPConnection ftp = new FTPConnection("127.0.0.1", "c", "c");
     long size = ftp.GetFileSize(fileName);
     ftp.Disconnect();
     return size;
 }
        public long StoreLocal(HttpProcessor p)
        {
            long total = 0;
            try
            {
                String fileName = p.httpHeaders["X-File-Name"].ToString();
                String fullpath = "C:/" + fileName;
                Int64 startOffset = Convert.ToInt64(p.httpHeaders["X-Start-Offset"]);
                Int64 contenSize = Convert.ToInt64(p.httpHeaders["X-File-Size"]);
                FileStream ms = null;
                byte[] buf = new byte[BUF_SIZE];
                Console.WriteLine(": Start transfer file. Start-Offset: " + startOffset);
                if (startOffset > 0)
                {
                    ms = new FileStream("C:/" + fileName, FileMode.Append, FileAccess.Write);
                }
                else
                {
                    ms = new FileStream("C:/" + fileName, FileMode.Create, FileAccess.Write);
                }

                //ms.Seek(startOffset, SeekOrigin.Begin);
                int numread = p.inputStream.Read(buf, 0, (int)Math.Min(BUF_SIZE, contenSize));
                while (numread > 0 && contenSize > 0)
                {
                    ms.Write(buf, 0, numread);
                    total += numread;
                    contenSize -= numread;
                    numread = p.inputStream.Read(buf, 0, (int)Math.Min(BUF_SIZE, contenSize));
                }
                ms.Flush();
                ms.Close();
            }
            catch (Exception)
            {
                Console.WriteLine("!!!Error: You do not have permission to acess this folder!");
            }
            return total;
        }
Esempio n. 32
0
            public override void handleGETRequest(HttpProcessor p)
            {
                switch (p.http_url)
                {
                    case "/channels":
                        p.writeSuccess("text/javascript");
                        //p.outputStream.WriteLine("{\"channel\":\"[{\"GuideNumber\":\"570\",\"GuideName\":\"ESPN\",\"LogoUrl\":\"http://192.168.1.23:888/logos/cbs.png\",\"Favorite\": true},{\"GuideNumber\":\"590\",\"GuideName\":\"FOX\",\"LogoUrl\":\"http://192.168.1.23:888/logos/cbs.png\",\"Favorite\": true},{\"GuideNumber\":\"600\",\"GuideName\":\"CBS\",\"LogoUrl\":\"http://192.168.1.23:888/logos/cbs.png\",\"Favorite\": true}]\"} ");
                        p.outputStream.WriteLine("{\"GuideNumber\":\"570\",\"GuideName\":\"ESPN\",\"LogoUrl\":\"http://192.168.1.23:888/logos/cbs.png\",\"Favorite\": true}");
                        break;

                    case "/favicon.png":
                        Stream fs = File.Open("../../favicon.png", FileMode.Open);
                        p.writeSuccess("image/png");
                        fs.CopyTo(p.outputStream.BaseStream);
                        p.outputStream.BaseStream.Flush();
                        break;

                    default:
                         Console.WriteLine("request: {0}", p.http_url);
                        p.writeSuccess();
                        p.outputStream.WriteLine("<html><body><h1>test server</h1>");
                        p.outputStream.WriteLine("Current Time: " + DateTime.Now.ToString());
                        p.outputStream.WriteLine("url : {0}", p.http_url);

                        p.outputStream.WriteLine("<form method=post action=/form>");
                        p.outputStream.WriteLine("<input type=text name=foo value=foovalue>");
                        p.outputStream.WriteLine("<input type=submit name=bar value=barvalue>");
                        p.outputStream.WriteLine("</form>");
                        break;
                }
            }
Esempio n. 33
0
        public async void TestHandleClient(TcpClient tcpClient,
                                           CancellationToken token)
        {
            HttpChannel channel = ServerInfo._httpChannels.Add(tcpClient);

            try
            {
                List <byte> cache        = new List <byte>();
                string      ip           = "";
                Stream      inputStream  = tcpClient.GetStream();
                Stream      outputStream = tcpClient.GetStream();

                try
                {
                    ip = GetClientIP(tcpClient);
                    channel.Touch();

                    int  i       = 0;
                    bool running = true;
                    while (running)
                    {
                        HttpRequest request = await HttpProcessor.GetIncomingRequest(inputStream,
                                                                                     cache,
                                                                                     (headers) =>
                        {
#if NO
                            StringBuilder text = new StringBuilder();
                            text.Append(string.Join("\r\n", headers.Select(x => string.Format("{0}: {1}", x.Key, x.Value))));
                            Console.WriteLine("=== headers ===\r\n" + text.ToString());
#endif

                            if (headers.ContainsKey("User-Agent") == false)
                            {
                                return(false);
                            }
                            if (headers["User-Agent"] != "dp2LibraryClient")
                            {
                                throw new InvalidRequestException("请求不是来自 dp2LibraryClient");
                            }
                            return(true);
                        },
                                                                                     token);

                        if (request == null)
                        {
                            Console.WriteLine("client close on request " + i);
                            break;
                        }
                        Console.WriteLine("request " + i);

                        TimeSpan timeout = GetTimeout(request);
                        if (timeout != TimeSpan.MinValue)
                        {
                            channel.Touch(timeout);
                        }
                        else
                        {
                            channel.Touch();
                        }

                        // 添加头字段 _dp2router_clientip
                        request.Headers.Add("_dp2router_clientip", ip);

                        // Console.WriteLine("=== request ===\r\n" + request.Dump());
                        // ServerInfo.WriteErrorLog("=== request ===\r\n" + request.Dump());

                        HttpResponse response = await ServerInfo.WebCall(request, "content", timeout);   // content text.utf-7

                        channel.Touch();
                        // string content = response.GetContentString();

                        // Console.WriteLine("=== response ===\r\n" + response.Dump());

                        await HttpProcessor.WriteResponseAsync(outputStream, response, token);

                        channel.Touch();

                        // Console.WriteLine("http version = '"+request.Version+"'");

                        if (request.Headers.ContainsKey("Connection"))
                        {
                            string strValue = request.Headers["Connection"];
                            if (strValue == "Keep-Alive")
                            {
                                running = true;
                            }
                            else
                            {
                                running = false;
                            }
                        }
                        else
                        {
                            if (StringUtil.CompareVersion(request.Version, "1.1") >= 0)
                            {
                                running = true; // HTTP 1.1 默认就是 Connection Keep-Alive。即便没有 Connection 头字段,也是 Keep-Alive 状态
                            }
                            else
                            {
                                running = false;
                            }
                        }

                        i++;
                    }
                }
                catch (InvalidRequestException ex)
                {
                    // 2016/11/20
                    ServerInfo.WriteErrorLog("ip:" + ip + " : " + ex.Message);
                }
                catch (Exception ex)
                {
                    // 2016/11/14
                    ServerInfo.WriteErrorLog("ip:" + ip + " TestHandleClient() 异常: " + ExceptionUtil.GetExceptionText(ex));
                }
                finally
                {
                    outputStream.Flush();
                    outputStream.Close();
                    outputStream = null;

                    inputStream.Close();
                    inputStream = null;
                }
            }
            finally
            {
                ServerInfo._httpChannels.Remove(channel);
            }
        }
Esempio n. 34
0
 public abstract void handleGETRequest(HttpProcessor p);
Esempio n. 35
0
 public abstract void handlePOSTRequest(HttpProcessor p, StreamReader inputData);
Esempio n. 36
-1
        public async Task Ping(HttpProcessor processor)
        {
            var req = await processor.GetJsonBody<PingRequest>();

            await processor.WriteJson(new PongResponse
            {
                Response = req?.Request ?? await processor.GetRequestBody()
            });
        }