예제 #1
0
        private byte[] GenerateC2SRequest()
        {
            string host = _uri.DnsSafeHost;

            string path = _uri.AbsolutePath;

            if (!string.IsNullOrEmpty(_uri.Query))
            {
                path += "?" + _uri.Query;
            }
            var origin = "http://" + host;

            if ("".Equals(path))
            {
                path = "/";
            }

            string handShake =
                "GET " + path + " HTTP/1.1 \r\n"
                + "Host: " + host + "\r\n"
                + "Upgrade: WebSocket\r\n"
                + "Connection: Upgrade\r\n"
                + "Sec-WebSocket-Key: " + _hybiKey + "\r\n"
                + "Origin: " + origin + "\r\n"
                + "Sec-WebSocket-Protocol: " + _protocol + "\r\n"
                + "Sec-WebSocket-Version: " + _version + "\r\n\r\n";

            return(WebSocketConvert.StringToBytes(handShake, WebSocketTypeEncoding.UTF8));;
        }
예제 #2
0
        private void VerifyS2CResponse(byte[] handshakeResponse)
        {
            var handshakeResponseString = WebSocketConvert.BytesToString(handshakeResponse, WebSocketTypeEncoding.UTF8);
            var responseFields          = new Dictionary <string, string>();
            var headers           = handshakeResponseString.Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
            var firstlineResponse = headers[0];

            foreach (var headerLine in headers.Skip(1))
            {
                var headerKeyValue = headerLine.Split(new[] { ":" }, StringSplitOptions.None);
                responseFields.Add(headerKeyValue[0].Trim(), headerKeyValue[1].Trim());
            }
            if (!firstlineResponse.Equals("HTTP/1.1 101 Switching Protocols"))
            {
                throw new WebSocketException("connection failed: missing header field in server handshake: HTTP/1.1");
            }
            if (!responseFields[WebSocketConstants.UPGRADE].Equals("websocket"))
            {
                throw new WebSocketException("connection failed: missing header field in server handshake: Upgrade");
            }
            if (!responseFields[WebSocketConstants.CONNECTION].Equals("Upgrade"))
            {
                throw new WebSocketException("connection failed: missing header field in server handshake: Connection");
            }
            if (!responseFields[WebSocketConstants.SEC_WEBSOCKET_ACCEPT].Equals(_expectedHybiResponseKey))
            {
                throw new WebSocketException("connection failed: missing header field in server handshake: Sec-WebSocket-Key");
            }
            if (!responseFields[WebSocketConstants.SEC_WEBSOCKET_PROTOCOL].Equals(_protocol))
            {
                throw new WebSocketException("connection failed: missing header field in server handshake: Sec-WebSocket-Protocol");
            }
        }
예제 #3
0
        public Token PacketToToken(WebSocketPacket aPacket)
        {
            var byteArray       = aPacket.GetByteArray();
            var packetString    = WebSocketConvert.BytesToString(byteArray, WebSocketTypeEncoding.UTF8);
            var dictionary      = JsonConvert.DeserializeObject <Dictionary <string, object> >(packetString);
            var dictionaryToken = new DictionaryToken();

            dictionaryToken.SetDictionary(dictionary);
            return(dictionaryToken);
        }
예제 #4
0
        /// <summary>
        /// Reads the response from stream.
        /// </summary>
        /// <param name="aSR">Data stream from server.</param>
        public void ReadResponseFromStream(NetworkStream aSR)
        {
            if (mLog.IsDebugEnabled)
            {
                mLog.Debug(WebSocketMessage.READING_RESPONSE_FROM_STREAM);
            }

            bool lHeaderComplete = false;
            int  lRT             = -1;
            int  lNL             = -1;
            int  lLines          = 0;

            byte[] lBuff = new byte[0];

            while (!lHeaderComplete)
            {
                lRT = lNL;
                lNL = Read(aSR);

                if (lRT.Equals(0x0D) && lNL.Equals(0x0A))
                {
                    string lLine = WebSocketConvert.BytesToString(lBuff, WebSocketTypeEncoding.UTF8);
                    if (lLines > 0)
                    {
                        if (!string.Empty.Equals(lLine))
                        {
                            char[]   c       = { WebSocketMessage.TWO_POINT2 };
                            string[] lKeyVal = lLine.Split(c, 2);
                            if (lKeyVal[0].Equals(WebSocketMessage.SET_COOKIE))
                            {
                                mCookies.Add(lLine);
                            }
                            else
                            {
                                mResponseFields.Add(lKeyVal[0].Trim(), lKeyVal[1].Trim());
                            }
                        }
                        else
                        {
                            lHeaderComplete = true;
                        }
                    }
                    else
                    {
                        mFirstLineResponse = lLine;
                    }
                    lLines++;
                    lBuff = new byte[0];
                }
                else if (!lNL.Equals(0x0A) && !lNL.Equals(0x0D))
                {
                    Write(ref lBuff, lNL);
                }
            }
        }
예제 #5
0
 public string GetASCII()
 {
     try
     {
         return(WebSocketConvert.BytesToString(mByteArray, WebSocketTypeEncoding.ASCII));
     }
     catch (Exception)
     {
         return(null);
     }
 }
예제 #6
0
        public void PackFragments()
        {
            StringBuilder lSB = new StringBuilder();

            for (int i = 0; i < mFragments.Length; i++)
            {
                lSB.Append(mFragments[i]);
                mFragments[i] = null;
            }
            mByteArray = WebSocketConvert.StringToBytes(lSB.ToString(), WebSocketTypeEncoding.UTF8);
        }
예제 #7
0
        /// <summary>
        /// Reads the request from buffer.
        /// </summary>
        /// <param name="aBuff">Data buffer from client.</param>
        public void ReadRequestFromBuffer(byte[] aBuff)
        {
            if (mLog.IsDebugEnabled)
            {
                mLog.Debug(WebSocketMessage.READING_REQUEST_FROM_BUFFER);
            }

            int lHeaderComplete = 0;
            int lLines          = 0;
            int lSizeBuff       = aBuff.Length - 2;

            byte lRT = 0;
            byte lNL = 0;

            byte[] lBuff = new byte[0];

            while (lHeaderComplete < lSizeBuff)
            {
                lRT = lNL;
                lNL = aBuff[lHeaderComplete];
                if (lRT.Equals(0x0D) && lNL.Equals(0x0A))
                {
                    string lLine = WebSocketConvert.BytesToString(lBuff, WebSocketTypeEncoding.UTF8);
                    if (lLines > 0)
                    {
                        char[]   c       = { WebSocketMessage.TWO_POINT2 };
                        string[] lKeyVal = lLine.Split(c, 2);
                        if (lKeyVal.Length == 2)
                        {
                            mRequestFields.Add(lKeyVal[0].Trim(), lKeyVal[1].Trim());
                        }
                    }
                    else
                    {
                        mFirstLineRequest = lLine;
                    }
                    lBuff = new byte[0];
                    lLines++;
                }
                else if (!lNL.Equals(0x0A) && !lNL.Equals(0x0D))
                {
                    Write(ref lBuff, lNL);
                }
                lHeaderComplete++;
            }
        }
예제 #8
0
        private static string CalcHybiSecKeyAccept(string aKey)
        {
            aKey = aKey + WebSocketMessage.KEY;
            string lAccept = null;
            SHA1   lSHA1   = new SHA1CryptoServiceProvider();

            byte[] lBufSource = WebSocketConvert.StringToBytes(aKey, WebSocketTypeEncoding.Default);
            try
            {
                byte[] lBufTarget = lSHA1.ComputeHash(lBufSource);
                lAccept = Convert.ToBase64String(lBufTarget);
            }
            catch (Exception lEx)
            {
                throw new WebSocketException(WebSocketMessage.ERROR_CONVERTING_BASE64 + lEx.Message);
            }
            return(lAccept);
        }
예제 #9
0
        private string CalcHybiSecKeyAccept()
        {
            var    key = _hybiKey + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
            string acceptedResponseKey = null;
            var    sha1 = new SHA1Managed();

            byte[] keyByteArray = WebSocketConvert.StringToBytes(key, WebSocketTypeEncoding.UTF8);
            try
            {
                byte[] hashedKeyByteArray = sha1.ComputeHash(keyByteArray);
                acceptedResponseKey = Convert.ToBase64String(hashedKeyByteArray);
            }
            catch (Exception)
            {
                //TODO - handle exception
            }
            return(acceptedResponseKey);
        }
예제 #10
0
        /// <summary>
        /// Generates the initial Handshake from a Client to the WebSocket.
        /// </summary>
        /// <returns>Handshake as byte array.</returns>
        public byte[] GenerateC2SRequest()
        {
            if (mLog.IsDebugEnabled)
            {
                mLog.Debug(WebSocketMessage.GENERATING_C2S_REQUEST);
            }

            string lHost = mUri.DnsSafeHost;
            string lPath = mUri.PathAndQuery;

            mOrigin = WebSocketMessage.HTTP + lHost;

            if (string.Empty.Equals(lPath))
            {
                lPath = WebSocketMessage.SLASH;
            }

            string lHandshake =
                WebSocketMessage.GET + lPath + WebSocketMessage.HTTP11
                + WebSocketMessage.HOST + WebSocketMessage.TWO_POINT + lHost + WebSocketMessage.NL_RETURN
                + WebSocketMessage.UPGRADE_WEBSOCEKT + WebSocketMessage.NL_RETURN
                + WebSocketMessage.CONNECTION_UPGRADE + WebSocketMessage.NL_RETURN
                + WebSocketMessage.SEC_WEBSOCKET_KEY + WebSocketMessage.TWO_POINT
                + mHybiKey + WebSocketMessage.NL_RETURN
                + WebSocketMessage.ORIGIN + WebSocketMessage.TWO_POINT + mOrigin + WebSocketMessage.NL_RETURN
                + WebSocketMessage.SEC_WEBSOCKET_PROTOCOL + WebSocketMessage.TWO_POINT + mProtocol
                + WebSocketMessage.NL_RETURN
                + WebSocketMessage.SEC_WEBSOCKET_VERSION + WebSocketMessage.TWO_POINT + mVersion;

            if (mCookieManage.Count() > 0)
            {
                lHandshake += WebSocketMessage.NL_RETURN + mCookieManage.ProcessCookies(mCookieManage.GetCookies(mUri));
            }

            lHandshake += WebSocketMessage.NL_RETURN + WebSocketMessage.NL_RETURN;
            return(WebSocketConvert.StringToBytes(lHandshake, WebSocketTypeEncoding.ASCII));
        }
예제 #11
0
 public byte[] TokenToByte(Token aToken)
 {
     return(WebSocketConvert.StringToBytes(TokenToText(aToken), WebSocketTypeEncoding.UTF8));
 }
예제 #12
0
 public string GetString(WebSocketTypeEncoding aEncoding)
 {
     return(WebSocketConvert.BytesToString(mByteArray, aEncoding));
 }
예제 #13
0
 public string GetString()
 {
     return(WebSocketConvert.BytesToString(mByteArray, WebSocketTypeEncoding.Default));
 }
예제 #14
0
 public void SetASCII(string aString)
 {
     mByteArray = WebSocketConvert.StringToBytes(aString, WebSocketTypeEncoding.ASCII);
 }
예제 #15
0
 public void SetUTF8(string aString)
 {
     mByteArray = WebSocketConvert.StringToBytes(aString, WebSocketTypeEncoding.UTF8);
 }
예제 #16
0
 public void SetString(string aString, WebSocketTypeEncoding aEncoding)
 {
     mByteArray = WebSocketConvert.StringToBytes(aString, aEncoding);
 }