示例#1
0
 public void ShouldThrowExceptionWhenStreamIsEmpty()
 {
     using (var memStream = new MemoryStream())
     {
         Assert.Throws <ArgumentException>("stream", () => Bytes.Create(memStream));
     }
 }
示例#2
0
        //Content-Length形式の受信(RecvServer()から使用される)
        bool RecvServerContentLength()
        {
            int len = proxy.Sock(CS.SERVER).Length();

            if (len <= 0)
            {
                return(true);
            }
            byte[] b = proxy.Sock(CS.SERVER).Recv(len, proxy.OptionTimeout);
            if (b == null)
            {
                return(false);
            }


            oneObj.Buf[CS.SERVER] = Bytes.Create(oneObj.Buf[CS.SERVER], b);

            if (isText)
            {
                //コンテンツ制限の確認
                if (IsHitLimitString(oneObj.Buf[CS.SERVER]))
                {
                    return(false);
                }
            }

            lastRecvServer = DateTime.Now.Ticks;
            return(true);
        }
示例#3
0
 void Pipe()
 {
     _sockTcp = SockServer.CreateConnection(_kernel, _ip, _listenPort, null, this);
     if (_sockTcp != null)
     {
         while (_life)
         {
             var len = _sockTcp.Length();
             if (len > 0)
             {
                 const int tout = 3; //受信バイト数がわかっているので、ここでのタイムアウト値はあまり意味が無い
                 var       b    = _sockTcp.Recv(len, tout, this);
                 if (b != null)
                 {
                     _buffer = Bytes.Create(_buffer, b);
                 }
             }
             if (_sockTcp.Length() == 0 && _sockTcp.SockState != SockState.Connect)
             {
                 break;
             }
         }
         _sockTcp.Close();
     }
     IsRecv = false;
 }
示例#4
0
        //public string RequestStr {
        //    get { return request.RequestStr; }
        //}
        //public PROXY_PROTOCOL Protocol {
        //    get { return request.Protocol; }
        //}

        //キャッシュ確認
        public void CacheConform()
        {
            //キャッシュ対象のリクエストかどうかの確認
            if (oneObj.Request.Protocol == PROXY_PROTOCOL.HTTP && !oneObj.Request.Cgi)
            {
                if (Http.Cache.IsTarget(oneObj.Request.HostName, oneObj.Request.Uri, oneObj.Request.Ext))
                {
                    // Pragma: no-cache が指定されている場合は、蓄積されたキャッシュを否定する
                    string pragmaStr = oneObj.Header[CS.CLIENT].GetVal("Pragma");
                    if (pragmaStr != null && pragmaStr.ToLower().IndexOf("no-cache") >= 0)
                    {
                        proxy.Logger.Set(LOG_KIND.DETAIL, null, 16, oneObj.Request.Uri);
                        Http.Cache.Remove(oneObj.Request.HostName, oneObj.Request.Port, oneObj.Request.Uri);//存在する場合は、無効化する
                    }
                    else
                    {
                        string   modifiedStr = oneObj.Header[CS.CLIENT].GetVal("If-Modified-Since");
                        DateTime modified    = Util.Str2Time(modifiedStr);
                        byte[]   dat         = Http.Cache.Get(oneObj.Request, modified);
                        if (dat != null) //キャッシュが見つかった場合
                        {
                            proxy.Logger.Set(LOG_KIND.DETAIL, null, 14, oneObj.Request.Uri);

                            sideState[CS.SERVER]  = HTTP_SIDE_STATE.SERVER_SIDE_RECV_BODY;   //一気に受信完了
                            sideState[CS.CLIENT]  = HTTP_SIDE_STATE.CLIENT_SIDE_SEND_HEADER; //ヘッダ送信完了まで進める
                            oneObj.Buf[CS.SERVER] = Bytes.Create("HTTP/1.1 200 OK\r\n", dat);
                        }
                    }
                    string url = string.Format("{0}:{1}{2}", oneObj.Request.HostName, oneObj.Request.Port, oneObj.Request.Uri);
                    //キャッシュ対象の場合だけ、受信用のオブジェクトを生成する
                    IsCacheTarget = true;
                }
            }
        }
示例#5
0
            public void ShouldThrowExceptionWhenStreamPositionIsNotZero()
            {
                using (var memStream = new MemoryStream(new byte[] { 42 }))
                {
                    memStream.Position = 10;

                    Assert.Throws <ArgumentException>("stream", () => Bytes.Create(memStream));
                }
            }
示例#6
0
        //FTPサーバから取得したLISTの情報をHTMLにコンバートする
        byte [] ConvFtpList(List <string> lines, string path)
        {
            List <string> tmp = new List <string>();

            tmp.Add("<head><title>");
            tmp.Add(string.Format("current directory \"{0}\"", path));
            tmp.Add("</title></head>");
            tmp.Add(string.Format("current directory \"{0}\"", path));
            tmp.Add("<hr>");
            tmp.Add("<pre>");
            tmp.Add(string.Format("<a href=\"{0}\">ParentDirector</a>", path + "../"));
            tmp.Add("");
            foreach (string line in lines)
            {
                string[] cols = line.Split(new char[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);
                try {
                    string dir  = cols[0];
                    string name = cols[8];
                    string size = cols[4];
                    string date = cols[5] + " " + cols[6] + " " + cols[7];

                    if (name == ".")
                    {
                        continue;
                    }
                    if (name == "..")
                    {
                        continue;
                    }

                    if (dir[0] == 'd')
                    {
                        tmp.Add(string.Format("<a href=\"{0}/\" style=\"text-decoration: none\">{1,-50}</a>\t{2,7}\t-", path + name, name, "&ltDIR&gt"));
                    }
                    else if (dir[0] == 'l')
                    {
                        tmp.Add(string.Format("<a href=\"{0}/\" style=\"text-decoration: none\">{1,-50}</a>\t{2,7}\t-", path + name, name, "&ltLINK&gt"));
                    }
                    else
                    {
                        tmp.Add(string.Format("<a href=\"{0}\" style=\"text-decoration: none\">{1,-50}</a>\t{2,7}\t{3}", path + name, name, size, date));
                    }
                } catch {
                    tmp.Add(line);
                }
            }
            tmp.Add("</pre>");

            //byte[]に変換する
            byte[] doc = new byte[0];
            foreach (string str in tmp)
            {
                doc = Bytes.Create(doc, str + "\r\n");
            }
            return(doc);
        }
示例#7
0
        public bool SendClient(ref bool life)
        {
            if (sideState[CS.SERVER] != HTTP_SIDE_STATE.SERVER_SIDE_RECV_HEADER && sideState[CS.SERVER] != HTTP_SIDE_STATE.SERVER_SIDE_RECV_BODY)
            {
                return(true);
            }

            byte[] sendBuf = new byte[0];
            if (sideState[CS.CLIENT] == HTTP_SIDE_STATE.CLIENT_SIDE_RECV_REQUEST)
            {
                //サーバから受信したレスポンス及びヘッダをバッファに展開する
                sendBuf = Bytes.Create(response.ToString(), "\r\n", oneObj.Header[CS.SERVER].GetBytes());
                if (!Send(proxy.Sock(CS.CLIENT), sendBuf))//送信
                {
                    return(false);
                }
                sideState[CS.CLIENT] = HTTP_SIDE_STATE.CLIENT_SIDE_SEND_HEADER;//ヘッダ送信完了
            }
            if (sideState[CS.CLIENT] == HTTP_SIDE_STATE.CLIENT_SIDE_SEND_HEADER)
            {
                //バッファに残っているデータの送信
                if (!SendBuf(CS.SERVER))
                {
                    return(false);
                }
            }

            //クライアントへの送信完了を確認する(ステータス変更)
            if (oneHttpKind == ONE_HTTP_KIND.CONTENT_LENGTH) //Content-Lengthの場合
            //posがContentLengthまで達したら完了
            {
                if (oneObj.Pos[CS.SERVER] >= contentLength)
                {
                    sideState[CS.CLIENT] = HTTP_SIDE_STATE.CLIENT_SIDE_SEND_BODY;
                }
            }
            else if (oneHttpKind == ONE_HTTP_KIND.CHUNK)   //chunkの場合
            //サーバ側の受信が完了し、バッファをすべて送信したら完了
            {
                if (sideState[CS.SERVER] == HTTP_SIDE_STATE.SERVER_SIDE_RECV_BODY && oneObj.Buf[CS.SERVER].Length <= oneObj.Pos[CS.SERVER])
                {
                    sideState[CS.CLIENT] = HTTP_SIDE_STATE.CLIENT_SIDE_SEND_BODY;
                }
            }
            //上記の条件で送信完了していない場合でも
            if (sideState[CS.CLIENT] != HTTP_SIDE_STATE.CLIENT_SIDE_SEND_BODY)
            {
                //サーバ側が切断され、受信未処理のデータが存在せず、バッファをすべて送信していたら完了
                if (proxy.Sock(CS.SERVER).State == SOCKET_OBJ_STATE.DISCONNECT && proxy.Sock(CS.SERVER).Length() == 0 && oneObj.Buf[CS.SERVER].Length <= oneObj.Pos[CS.SERVER])
                {
                    sideState[CS.CLIENT] = HTTP_SIDE_STATE.CLIENT_SIDE_SEND_BODY;
                }
            }

            return(true);
        }
示例#8
0
        public bool SendServer(ref bool life)
        {
            //サーバ側との接続処理
            if (!proxy.Connect(ref life, oneObj.Request.HostName, oneObj.Request.Port, oneObj.Request.RequestStr, oneObj.Request.Protocol))
            {
                proxy.Logger.Set(LOG_KIND.DEBUG, null, 999, "□Break http.Connect()==false");
                return(false);
            }

            //ヘッダ送信
            byte[] sendBuf = new byte[0];
            if (sideState[CS.SERVER] == HTTP_SIDE_STATE.NON)
            {
                if (oneObj.Request.Protocol == PROXY_PROTOCOL.SSL)
                {
                    if (!proxy.UpperProxy.Use)
                    {
                        //取得したリクエストをバッファに格納する
                        //sendBuf = new byte[0];
                        //sendBuf[CS.CLIENT] = Bytes.Create("HTTP/1.0 200 Connection established\r\n\r\n");//CONNECTが成功したことをクライアントに返す
                    }
                    else
                    {
                        //上位プロキシを使用する場合(リクエストラインはそのまま使用される)
                        sendBuf = Bytes.Create(oneObj.Request.SendLine(proxy.UpperProxy.Use), oneObj.Header[CS.CLIENT].GetBytes());
                    }
                }
                else if (oneObj.Request.Protocol == PROXY_PROTOCOL.HTTP)   //HTTPの場合
                //header.Remove("Proxy-Connection");//<=■これ入れていいのか?

                //取得したリクエストをバッファに格納する
                //上位プロキシを使用する場合(リクエストラインはそのまま使用される)
                {
                    sendBuf = Bytes.Create(oneObj.Request.SendLine(proxy.UpperProxy.Use), oneObj.Header[CS.CLIENT].GetBytes());
                }
                if (!Send(proxy.Sock(CS.SERVER), sendBuf))//送信
                {
                    return(false);
                }
                sideState[CS.SERVER] = HTTP_SIDE_STATE.SERVER_SIDE_SEND_HEADER;
            }

            if (sideState[CS.SERVER] == HTTP_SIDE_STATE.SERVER_SIDE_SEND_HEADER)
            {
                //バッファに残っているデータの送信
                if (!SendBuf(CS.CLIENT))
                {
                    return(false);
                }
            }

            //サーバへの送信完了を確認する(ステータス変更)
            sideState[CS.SERVER] = HTTP_SIDE_STATE.SERVER_SIDE_SEND_BODY;

            return(true);
        }
示例#9
0
 public void ShouldThrowExceptionWhenStreamCannotRead()
 {
     using (var stream = new TestStream(false, true, true))
     {
         Assert.Throws <ArgumentException>("stream", () =>
         {
             Bytes.Create(stream);
         });
     }
 }
示例#10
0
        public bool SendClient(ILife iLife)
        {
            if (_sideState[CS.Server] != HttpSideState.ServerSideRecvHeader && _sideState[CS.Server] != HttpSideState.ServerSideRecvBody)
            {
                return(true);
            }

            if (_sideState[CS.Client] == HttpSideState.ClientSideRecvRequest)
            {
                //サーバから受信したレスポンス及びヘッダをバッファに展開する
                var sendBuf = Bytes.Create(_response.ToString(), "\r\n", _oneObj.Header[CS.Server].GetBytes());
                if (!Send(_proxy.Sock(CS.Client), sendBuf))//送信
                {
                    return(false);
                }
                _sideState[CS.Client] = HttpSideState.ClientSideSendHeader;//ヘッダ送信完了
            }
            if (_sideState[CS.Client] == HttpSideState.ClientSideSendHeader)
            {
                //バッファに残っているデータの送信
                if (!SendBuf(CS.Server))
                {
                    return(false);
                }
            }

            //クライアントへの送信完了を確認する(ステータス変更)
            if (_oneHttpKind == OneHttpKind.ContentLength)   //Content-Lengthの場合
            //posがContentLengthまで達したら完了
            {
                if (_oneObj.Pos[CS.Server] >= _contentLength)
                {
                    _sideState[CS.Client] = HttpSideState.ClientSideSendBody;
                }
            }
            else if (_oneHttpKind == OneHttpKind.Chunk)     //chunkの場合
            //サーバ側の受信が完了し、バッファをすべて送信したら完了
            {
                if (_sideState[CS.Server] == HttpSideState.ServerSideRecvBody && _oneObj.Body[CS.Server].Length <= _oneObj.Pos[CS.Server])
                {
                    _sideState[CS.Client] = HttpSideState.ClientSideSendBody;
                }
            }
            //上記の条件で送信完了していない場合でも
            if (_sideState[CS.Client] != HttpSideState.ClientSideSendBody)
            {
                //サーバ側が切断され、受信未処理のデータが存在せず、バッファをすべて送信していたら完了
                if (_proxy.Sock(CS.Server).SockState == SockState.Error && _proxy.Sock(CS.Server).Length() == 0 && _oneObj.Body[CS.Server].Length <= _oneObj.Pos[CS.Server])
                {
                    _sideState[CS.Client] = HttpSideState.ClientSideSendBody;
                }
            }

            return(true);
        }
示例#11
0
            public void ShouldSetPropertiesWhenStreamIsEmptyAndAllowEmptyStreamIsSet()
            {
                using (var memStream = new MemoryStream())
                {
                    var bytes = Bytes.Create(memStream, allowEmptyStream: true);

                    Assert.Equal(0, bytes.Length);
                    Assert.NotNull(bytes.GetData());
                    Assert.Empty(bytes.GetData());
                }
            }
示例#12
0
            public void ShouldSetPropertiesWhenStreamIsFileStream()
            {
                using (var fileStream = File.OpenRead(Files.ImageMagickJPG))
                {
                    var bytes = Bytes.Create(fileStream);

                    Assert.Equal(18749, bytes.Length);
                    Assert.NotNull(bytes.GetData());
                    Assert.Equal(18749, bytes.GetData().Length);
                }
            }
示例#13
0
            public void ShouldThrowExceptionWhenStreamIsTooLong()
            {
                using (var stream = new TestStream(true, true, true))
                {
                    stream.SetLength(long.MaxValue);

                    Assert.Throws <ArgumentException>("length", () =>
                    {
                        Bytes.Create(stream);
                    });
                }
            }
示例#14
0
        //�t�@�C������̎擾
        public bool Read(string fileName)
        {
            //���݂̓�e����ׂĔj�����ēǂݒ���
            _header.Clear();
            _body.Clear();
            _body = new List <byte[]>();

            if (File.Exists(fileName))
            {
                var tmpBuf = new byte[0];
                using (var br = new BinaryReader(new FileStream(fileName, FileMode.Open))) {
                    var info = new FileInfo(fileName);
                    while (true)
                    {
                        var len = info.Length - tmpBuf.Length;
                        if (len <= 0)
                        {
                            break;
                        }
                        if (len > 65535)
                        {
                            len = 65535;
                        }
                        var tmp = br.ReadBytes((int)len);
                        tmpBuf = Bytes.Create(tmpBuf, tmp);
                    }
                    br.Close();

                    var lines = Inet.GetLines(tmpBuf);
                    var head  = true;
                    foreach (byte[] line in lines)
                    {
                        if (head)
                        {
                            var str = Encoding.ASCII.GetString(line);
                            if (str == "\r\n")
                            {
                                head = false;
                                continue;
                            }
                            _header.Add(str);
                        }
                        else
                        {
                            _body.Add(line);
                        }
                    }
                    return(true);
                }
            }
            return(false);
        }
示例#15
0
        public void TotalTest()
        {
            const int max = 5;
            var       sb  = new StringBuilder();

            for (int i = 0; i < max; i++)
            {
                sb.Append(string.Format("key_{0:D3}: val_{0:D3}\r\n", i));
            }
            byte [] buf    = Bytes.Create(sb.ToString());
            var     header = new Header(buf);

            //GetBytes()
            //自動的に追加される空行を追加すると、初期化したbyte[]と同じになるはず
            var tmp = Bytes.Create(header.GetBytes(), "\r\n");

            for (int i = 0; i < buf.Length; i++)
            {
                Assert.AreEqual(buf[i], tmp[i]);
            }

            //Count
            Assert.AreEqual(header.Count, max);


            for (var i = 0; i < header.Count; i++)
            {
                var key    = string.Format("key_{0:D3}", i);
                var valStr = string.Format("val_{0:D3}", i);

                //GetVal(string key)
                Assert.AreEqual(header.GetVal(key), valStr);

                //Replace(string key,string str)
                var replaceStr = string.Format("replace_{0:D3}", i);
                header.Replace(key, replaceStr);
                Assert.AreEqual(header.GetVal(key), replaceStr);
            }

            const int appendMax = 3;

            for (int i = 0; i < appendMax; i++)
            {
                //Append(string key,string val)
                var key = string.Format("AppendKey_{0:D3}", i);
                var val = string.Format("AppendVal_{0:D3}", i);
                header.Append(key, Encoding.ASCII.GetBytes(val));
                //string s = header.GetVal(key);
                Assert.AreEqual(header.GetVal(key), val);
            }
            Assert.AreEqual(header.Count, max + appendMax);
        }
示例#16
0
        //受信時の処理
        protected override byte[] Assumption(byte[] buf, ILife iLife)
        {
            var resultBuf = new byte[0];

            //一度に複数行分のデータが来る場合が有るので、行単位に分割して処理する
            var lines = Inet.GetLines(buf);

            foreach (var l in lines)
            {
                resultBuf = Bytes.Create(resultBuf, AssumptionLine(l, iLife));
            }
            return(resultBuf);
        }
示例#17
0
        //バイトイメージの取得
        public byte[] GetBytes()
        {
            var buffer = _dnsHeader.GetBytes();

            for (var i = 0; i < 4; i++)
            {
                var a = _ar[i];
                foreach (var o in a)
                {
                    var dataName = (new Compress(buffer, DnsUtil.Str2DnsName(o.Name))).GetData();
                    var data     = o.Data;
                    var dnsType  = o.DnsType;

                    if (i != 0)
                    {
                        //QDでは、data部分は存在しない
                        if (dnsType == DnsType.Ns || dnsType == DnsType.Cname || dnsType == DnsType.Ptr)
                        {
                            data = (new Compress(buffer, o.Data)).GetData(); //圧縮
                        }
                        else if (dnsType == DnsType.Mx)
                        {
                            var preference = Conv.GetUShort(o.Data, 0);
                            var mlServer   = new byte[o.Data.Length - 2];
                            //System.arraycopy(o.Data, 2, mlServer, 0, o.Data.Length - 2);
                            Buffer.BlockCopy(o.Data, 2, mlServer, 0, o.Data.Length - 2);

                            mlServer = (new Compress(buffer, mlServer)).GetData(); //圧縮
                            data     = Bytes.Create(Conv.GetBytes(preference), mlServer);
                        }
                    }
                    //PacketRrは、QD(i==0)の時、data.Length=0となり、内部でisQueryがセットされる
                    var packetRr = new PacketRr(data.Length);
                    try{
                        packetRr.Cls     = 1;
                        packetRr.DnsType = dnsType;
                        packetRr.Ttl     = o.Ttl; //PacketRr.isQueryがセットされているとき、処理なし
                        packetRr.Data    = data;  //PacketRr.isQueryがセットされているとき、処理なし
                    } catch (IOException e) {
                        //設計上の問題
                        Util.RuntimeException(e.Message);
                    }
                    //PacketRr.isQueryがセットされているとき、getBytes()は4バイト(TTL,DLEN,DATAなし)になっている
                    buffer = Bytes.Create(buffer, dataName, packetRr.GetBytes());
                }
            }
            return(buffer);
        }
示例#18
0
        //データオブジェクトの追加
        override public void Add(OneObj oneObj)
        {
            _oneObj = oneObj;

            if (Proxy.UpperProxy.Use)
            {
                //上位プロキシを使用する場合(リクエストラインはそのまま使用される)
                oneObj.Body[CS.Client].Set(Bytes.Create(oneObj.Request.SendLine(Proxy.UpperProxy.Use), oneObj.Header[CS.Client].GetBytes()));
            }
            else
            {
                //取得したリクエストをバッファに格納する
                oneObj.Body[CS.Client].Set(new byte[0]);
                oneObj.Body[CS.Server].Set(Bytes.Create("HTTP/1.0 200 Connection established\r\n\r\n"));//CONNECTが成功したことをクライアントに返す
            }
        }
示例#19
0
        //受信(無効な場合 return null)
        public static OneRemoteData Recv(SockTcp sockTcp, ILife iLife)
        {
            if (sockTcp != null)
            {
                //Ver5.8.6
                var sec = 10;                          //最初はタイムアウト値を最小に設定する
                var b   = sockTcp.Recv(1, sec, iLife); //REMOTE_DATA_KINDの受信
                if (b != null && b.Length == 1)
                {
                    var kind = (RemoteDataKind)b[0];

                    //これ以降は、データが到着しているはずなので、タイムアウト値を上げて待機する
                    //timeout = 3000;
                    //Ver5.8.6
                    sec = 10;
                    Thread.Sleep(1);
                    b = sockTcp.Recv(4, sec, iLife);//データサイズの受信

                    if (b != null && b.Length == 4)
                    {
                        var len = BitConverter.ToInt32(b, 0);
                        if (len == 0)
                        {
                            return(new OneRemoteData(kind, ""));//データ本体はサイズ0
                        }
                        //Ver5.8.6
                        b = new byte[0];
                        while (iLife.IsLife())
                        {
                            Thread.Sleep(1);
                            var buf = sockTcp.Recv(len, sec, iLife);//データ本体の受信
                            if (buf == null)
                            {
                                return(null);
                            }
                            b = Bytes.Create(b, buf);
                            if (b.Length == len)
                            {
                                return(new OneRemoteData(kind, Encoding.GetEncoding(932).GetString(b)));
                            }
                        }
                    }
                }
            }
            return(null);
        }
示例#20
0
            public static byte[] Generate()
            {
                const int max = 100;
                var       dmy = new byte[max];

                for (byte i = 0; i < max; i++)
                {
                    dmy[i] = i;
                }
                const byte   b  = 1;
                const short  a1 = 2;
                const int    a2 = 3;
                const long   a3 = 4L;
                const string s  = "123";

                return(Bytes.Create(dmy, b, a1, a2, a3, s, dmy));
            }
示例#21
0
 public byte[] GetBuffer()
 {
     return(Bytes.Create(
                _headerDhcp.Opcode,
                _headerDhcp.HwType,
                _headerDhcp.HwAddrLen,
                _headerDhcp.HopCount,
                _headerDhcp.TransactionId,
                _headerDhcp.NumberOfSecounds,
                _headerDhcp.Flags,
                _headerDhcp.ClientIp,
                _headerDhcp.YourIp,
                _headerDhcp.ServerIp,
                _headerDhcp.GatewayIp,
                _headerDhcp.ClientHwAddr,
                _headerDhcp.ServerHostName,
                _headerDhcp.BootFile,
                _headerDhcp.MagicCookie,
                _option));
 }
示例#22
0
        public void ホスト名を圧縮しないで格納する()
        {
            //setUp
            var buf      = TestUtil.HexStream2Bytes(Str0);
            var hostName = new byte[] { 0x03, 0x67, 0x6f, 0x6f, 0x03, 0x63, 0x6f, 0x6d, 0x00 }; //goo.com
            var sut      = new Compress(buf, hostName);
            var expected = new byte[] { 0x03, 0x67, 0x6f, 0x6f, 0xC0, 0x1b };

            //exercise
            var actual = sut.GetData();

            //verify
            Assert.That(actual, Is.EqualTo(expected));

            //以下の、UnCompressでもう一度元に戻してみる
            //exercise
            var s = new UnCompress(Bytes.Create(buf, actual), buf.Length);

            //verify
            Assert.That(s.HostName, Is.EqualTo("goo.com."));
        }
示例#23
0
        Mail Get1(int start, int end)
        {
            const string boundaryStr = "BJD-Boundary";
            var          buf         = new byte[0];
            //実際に取得したライブラリ番号
            var s = -1;
            var e = -1;

            //ライブラリからの取得
            for (var i = start; i <= end; i++)
            {
                var mail = _mlDb.Read(i);
                if (mail == null)
                {
                    continue;
                }
                if (s == -1)
                {
                    s = i;
                    e = i;
                }
                else
                {
                    e = i;
                }
                buf = Bytes.Create(buf, Encoding.ASCII.GetBytes(string.Format("--{0}\r\n", boundaryStr)));
                buf = Bytes.Create(buf, Encoding.ASCII.GetBytes("Content-Type: message/rfc822\r\n\r\n"));
                buf = Bytes.Create(buf, mail.GetBytes());
            }
            buf = Bytes.Create(buf, Encoding.ASCII.GetBytes(string.Format("--{0}--\r\n", boundaryStr)));
            var subject = string.Format("result for get [{0}-{1} MIME/multipart] ({2} ML)", s, e, _mlAddr.Name);

            if (s == -1)  //1件も取得できなかった場合
            {
                subject = string.Format("not found No.{0} ({1} ML)", start, _mlAddr.Name);
            }
            var contentType = string.Format("multipart/mixed;\r\n boundary=\"{0}\"", boundaryStr);

            return(Create(subject, contentType, buf));
        }
示例#24
0
 void Pipe()
 {
     //int idleTime = 0;
     while (life)
     {
         int len = tcpObj.Length();
         if (len > 0)
         {
             int    tout = 3;//受信バイト数がわかっているので、ここでのタイムアウト値はあまり意味が無い
             byte[] b    = tcpObj.Recv(len, tout);
             if (b != null)
             {
                 buffer = Bytes.Create(buffer, b);
             }
         }
         if (tcpObj.Length() == 0 && tcpObj.State != SOCKET_OBJ_STATE.CONNECT)
         {
             break;
         }
     }
     tcpObj.Close();
 }
示例#25
0
        public Mail Get(MlMailDb mlDb, int start, int end)
        {
            string boundaryStr = "BJD-Boundary";

            byte[] buf = new byte[0];
            //ライブラリからの取得
            for (int i = start; i <= end; i++)
            {
                var mail = mlDb.Read(i);
                if (mail != null)
                {
                    buf = Bytes.Create(buf, Encoding.ASCII.GetBytes(string.Format("--{0}\r\n", boundaryStr)));
                    buf = Bytes.Create(buf, Encoding.ASCII.GetBytes("Content-Type: message/rfc822\r\n\r\n"));
                    buf = Bytes.Create(buf, mail.GetBytes());
                }
            }
            buf = Bytes.Create(buf, Encoding.ASCII.GetBytes(string.Format("--{0}--\r\n", boundaryStr)));

            var subject     = string.Format("result for get [{0}-{1} MIME/multipart] ({2} ML)", start, end, mlAddr.Name);
            var contentType = string.Format("multipart/mixed;\r\n boundary=\"{0}\"\r\n", boundaryStr);

            return(Create(subject, contentType, buf));
        }
示例#26
0
        //リクエスト行・ヘッダ・POSTデータ
        public bool RecvRequest(bool useRequestLog, LimitUrl limitUrl, ILife iLife)
        {
            //リクエスト取得(内部データは初期化される)ここのタイムアウト値は、大きすぎるとブラウザの切断を取得できないでブロックしてしまう
            if (!Request.Recv(Proxy.Logger, Proxy.Sock(CS.Client), /*timeout*/ 3, iLife))
            {
                return(false);
            }
            //ヘッダの取得
            if (!Header[CS.Client].Recv(Proxy.Sock(CS.Client), Proxy.OptionTimeout, iLife))
            {
                return(false);
            }
            //POSTの場合は、更にクライアントからのデータを読み込む
            if (Request.Protocol == ProxyProtocol.Http && Request.HttpMethod == HttpMethod.Post)  //POSTの場合
            {
                string strContentLength = Header[CS.Client].GetVal("Content-Length");
                if (strContentLength != null)
                {
                    try {
                        var len = Convert.ToInt32(strContentLength);
                        //Ver5.9.7
//                        if(0 < len) {
//                            Body[CS.Client].Set(Proxy.Sock(CS.Client).Recv(len,Proxy.OptionTimeout,iLife));
//                        }
                        if (0 < len)
                        {
                            var buf = new byte[0];
                            while (iLife.IsLife())
                            {
                                var size = len - buf.Length;
                                var b    = Proxy.Sock(CS.Client).Recv(size, Proxy.OptionTimeout, iLife);
                                buf = Bytes.Create(buf, b);
                                if (len <= buf.Length)
                                {
                                    break;
                                }
                            }
                            Body[CS.Client].Set(buf);
                        }
                    } catch {
                        Proxy.Logger.Set(LogKind.Error, null, 22, Request.Uri);
                        return(false);
                    }
                }
            }

            //bool useRequestLog リクエストを通常ログで表示する
            //proxy.Logger.Set(useRequestLog ? LogKind.Normal : LogKind.Detail,null,0,string.Format("{0}",Request.RequestStr));
            Proxy.Logger.Set(useRequestLog ? LogKind.Normal : LogKind.Detail, Proxy.Sock(CS.Client), 0, string.Format("{0}", Request.RequestStr));

            //URL制限
            string[] tmp = Request.RequestStr.Split(' ');
            if (tmp.Length != 3)
            {
                Proxy.Logger.Set(LogKind.Normal, null, 10, "a parameter includes a problem");
                return(false);
            }
            string errorStr = "";

            if (!limitUrl.IsAllow(tmp[1], ref errorStr))
            {
                Proxy.Logger.Set(LogKind.Normal, null, 10, errorStr);
                return(false);
            }
            return(true);
        }
示例#27
0
        //アップロード(ファイル受信)
        bool UpLoad(SockUdp childObj, string path)
        {
            var ret = false;

            ushort       no        = 0;
            var          totalSize = 0;
            FileStream   fs        = null;
            BinaryWriter bw        = null;

            if (!(bool)Conf.Get("write"))  //「書込み」が許可されていない
            {
                Logger.Set(LogKind.Secure, childObj, 11, path);
                //エラーコード(2) アクセス違反
                childObj.Send(Bytes.Create(Util.htons((ushort)Opcode.Error), Util.htons(2), "Transmission of a message prohibition"));
                goto end;
            }
            if (!(bool)Conf.Get("override"))  //「上書き」が許可されていない
            {
                if (File.Exists(path))
                {
                    Logger.Set(LogKind.Secure, childObj, 12, path);
                    //エラーコード(6) アクセス違反
                    childObj.Send(Bytes.Create(Util.htons((ushort)Opcode.Error), Util.htons(6), "There is already a file"));
                    goto end;
                }
            }


            //ACK(0)送信
            childObj.Send(Bytes.Create(Util.htons((ushort)Opcode.Ack), Util.htons(no)));

            try {
                fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write);
            } catch (Exception e) {
                //エラーコード(2) アクセス違反
                childObj.Send(Bytes.Create(Util.htons((ushort)Opcode.Error), Util.htons(2), e.Message));
                goto end;
            }

            bw = new BinaryWriter(fs);

            while (true)
            {
                //受信
//                if (!childObj.Recv(Timeout)) {
                var buf = childObj.Recv(Timeout);
                if (buf.Length == 0)
                {
                    Logger.Set(LogKind.Error, childObj, 7, string.Format("{0}sec", Timeout));
                    break;
                }
                if ((Opcode)(buf[1]) != Opcode.Data)
                {
                    break;
                }

                //次のデータかどうかの確認
                if (Util.htons(BitConverter.ToUInt16(buf, 2)) != no + 1)
                {
                    continue;
                }
                no++;

                int size = buf.Length - 4;
                bw.Write(buf, 4, size); //Write
                totalSize += size;

                //ACK送信
                childObj.Send(Bytes.Create(Util.htons((ushort)Opcode.Ack), Util.htons(no)));

                if (size != 512)
                {
                    Logger.Set(LogKind.Normal, childObj, 8, string.Format("{0} {1}byte", path, totalSize));
                    ret = true;
                    goto end;
                }
                Thread.Sleep(1);
            }
end:
            if (bw != null)
            {
                bw.Close();
            }
            if (fs != null)
            {
                fs.Close();
            }
            return(ret);
        }
示例#28
0
        //ダウンロード(ファイル送信)
        bool DownLoad(SockUdp childObj, string path)
        {
            var          ret   = false;
            var          no    = (ushort)1;
            var          total = 0;
            FileStream   fs    = null;
            BinaryReader br    = null;

            if (!(bool)Conf.Get("read"))  //「読込み」が許可されていない
            {
                Logger.Set(LogKind.Secure, childObj, 10, path);
                //エラーコード(2) アクセス違反
                childObj.Send(Bytes.Create(Util.htons((ushort)Opcode.Error), Util.htons(2), "Receive of a message prohibition"));
                goto end;
            }

            if (!File.Exists(path))  //ファイルが見つからない
            {
                Logger.Set(LogKind.Secure, childObj, 13, path);
                //エラーコード(1) ファイルが見つからない
                childObj.Send(Bytes.Create(Util.htons((ushort)Opcode.Error), Util.htons(1), "A file is not found"));
                goto end;
            }

            try {
                fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Read);
            } catch (Exception e) {
                //エラーコード(2) アクセス違反
                childObj.Send(Bytes.Create(Util.htons((ushort)Opcode.Error), Util.htons(2), e.Message));
                goto end;
            }

            br = new BinaryReader(fs);
            // Init retry counter.
            var retryCount = (int)Conf.Get("retryCount");

            while (true)
            {
                var data = br.ReadBytes(512);

                //DATA 送信
                childObj.Send(Bytes.Create(Util.htons((ushort)Opcode.Data), Util.htons(no), data));
                total += data.Length;

                if (data.Length < 512)
                {
                    if (data.Length == 0)
                    {
                        //最後の 0bytes データを送る
                        childObj.Send(Bytes.Create(Util.htons((ushort)Opcode.Data), Util.htons(no)));
                    }
                    Logger.Set(LogKind.Normal, childObj, 9, string.Format("{0} {1}byte", path, total));
                    ret = true;
                    goto end;
                }

                Thread.Sleep(10);

                // ACK待ち
                //if (!childObj.Recv(Timeout)) {
                var buf = childObj.Recv(Timeout);
                if (buf.Length == 0)
                {
                    Logger.Set(LogKind.Error, childObj, 7, string.Format("{0}sec", Timeout));
                    break;
                }
                if ((Opcode)(buf[1]) != Opcode.Ack)
                {
                    break;
                }
                //ACK番号が整合しているかどうかの確認
                var ackNo = Util.htons(BitConverter.ToUInt16(buf, 2));
                //if (no != ackNo) {
                //    Logger.Set(LogKind.Error,childObj,14,string.Format("no={0} ack={1}",no,ackNo));
                //    //エラーとして処理する
                //    childObj.Send(Bytes.Create(Util.htons((ushort)Opcode.Error),Util.htons(2),"unmatch ACK"));
                //    goto end;
                //}
                //
                //某所で頻繁にパケットが落ちてACK番号が整合しないケースを救済する 2021.6.27
                if (no == 1 + ackNo)
                {
                    if (retryCount > 0)
                    {
                        total       -= data.Length; //pull back total count.
                        fs.Position -= data.Length; //pull back filestream position.
                        retryCount--;
                        Logger.Set(LogKind.Error, childObj, 14, string.Format("no={0} ack={1} marginal count={2}", no, ackNo, retryCount));
                        continue;
                    }
                }
                else if (no != ackNo)
                {
                    Logger.Set(LogKind.Error, childObj, 14, string.Format("no={0} ack={1} Abort!", no, ackNo));
                    //エラーとして処理する
                    childObj.Send(Bytes.Create(Util.htons((ushort)Opcode.Error), Util.htons(2), "unmatch ACK"));
                    goto end;
                }
                if ((bool)Conf.Get("printCounter"))
                {   // debug option.
                    Logger.Set(LogKind.Debug, childObj, 16, string.Format("br_count={0} fs_position={1}", no, fs.Position));
                }
                no++;//次のデータ
                // Reset retry counter.
                retryCount = (int)Conf.Get("retryCount");
            }
end:
            if (br != null)
            {
                br.Close();
            }
            if (fs != null)
            {
                fs.Close();
            }
            return(ret);
        }
示例#29
0
文件: RrSoa.cs 项目: schifflee/bjd5
 public RrSoa(string name, uint ttl, string n1, string n2, uint serial, uint refresh, uint retry, uint expire, uint minimum) : base(name, DnsType.Soa, ttl, Bytes.Create(DnsUtil.Str2DnsName(n1), DnsUtil.Str2DnsName(n2), Conv.GetBytes(serial), Conv.GetBytes(refresh), Conv.GetBytes(retry), Conv.GetBytes(expire), Conv.GetBytes(minimum)))
 {
 }
示例#30
0
        public void Pipe(SockTcp server, SockTcp client, ILife iLife)
        {
            Sock[CS.Client] = client;
            Sock[CS.Server] = server;

            //�A�C�h�������p�̃^�C�}������
            ResetIdle();

            var cs = CS.Server;

            while (iLife.IsLife())
            {
                cs = Reverse(cs);//�T�[�o���ƃN���C�A���g�����݂ɏ�������
                Thread.Sleep(1);

                // �N���C�A���g�̐ؒf�̊m�F
                if (Sock[CS.Client].SockState != SockState.Connect)
                {
                    //Ver5.2.8
                    //�N���C�A���g���ؒf���ꂽ�ꍇ�ł�A�T�[�o�����ڑ����ő��M����ׂ��f�[�^���c���Ă���ꍇ�͏�����p������
                    if (Sock[CS.Server].SockState == SockState.Connect && Sock[CS.Client].Length() != 0)
                    {
                    }
                    else
                    {
                        Logger.Set(LogKind.Detail, Sock[CS.Server], 9000043, "close client");
                        break;
                    }
                }

                //*******************************************************
                //��������f�[�^���������Ă��Ȃ��ꍇ�̏���
                //*******************************************************
                if (Sock[CS.Client].Length() == 0 && Sock[CS.Server].Length() == 0 && _byteBuf[CS.Client].Length == 0 && _byteBuf[CS.Server].Length == 0)
                {
                    // �T�[�o�̐ؒf�̊m�F
                    if (Sock[CS.Server].SockState != SockState.Connect)
                    {
                        //���M����ׂ��f�[�^���Ȃ��A�T�[�o���ؒf���ꂽ�ꍇ�́A�����I��
                        Logger.Set(LogKind.Detail, Sock[CS.Server], 9000044, "close server");
                        break;
                    }

                    Thread.Sleep(100);

                    //�A�C�h������ �^�C���A�E�g�̊m�F
                    if (IsTimeout())
                    {
                        Logger.Set(LogKind.Normal, Sock[CS.Server], 9000019, string.Format("option IDLETIME={0}min", IdleTime));
                        break;
                    }
                }
                else
                {
                    //�A�C�h�������p�̃^�C�}������
                    ResetIdle();
                }

                //*******************************************************
                // ��M����
                //*******************************************************
                if (_byteBuf[cs].Length == 0)  //�o�b�t�@����̎�������������
                //�������ׂ��f�[�^���̎擾
                {
                    var len = Sock[cs].Length();
                    if (len > 0)
                    {
                        const int sec = 10; //��M�o�C�g�����킩���Ă���̂ŁA�����ł̃^�C���A�E�g�l�͂��܂�Ӗ�������
                        var       b   = Sock[cs].Recv(len, sec, iLife);
                        if (b != null)
                        {
                            //Assumption() ��M���̏���
                            _byteBuf[cs] = Bytes.Create(_byteBuf[cs], Assumption(b, iLife));
                        }
                    }
                }
                //*******************************************************
                // ���M����
                //*******************************************************
                if (_byteBuf[cs].Length != 0)  //�o�b�t�@�Ƀf�[�^�������Ă���ꍇ������������

                {
                    var c = Sock[Reverse(cs)].SendUseEncode(_byteBuf[cs]);
                    if (c == _byteBuf[cs].Length)
                    {
                        _byteBuf[cs] = new byte[0];
                    }
                    else
                    {
                        Logger.Set(LogKind.Error, server, 9000020, string.Format("sock.Send() return {0}", c));
                        break;
                    }
                }
            }
        }