Esempio n. 1
0
        public static Http2Frame ParseHeader(ArraySegment <byte> data)
        {
            if (data.Count < 9)
            {
                return(null);
            }

            var header = new Http2Frame();

            header.length   = data.ElementAt(0) << 2 | data.ElementAt(1) << 1 | data.ElementAt(2);
            header.type     = (Http2FrameType)data.ElementAt(3);
            header.streamId = BitConverter.ToInt32(data.ToArray(), 4);

            Console.WriteLine("HLENGTH : " + header.length.ToString());
            Console.WriteLine("TYPE : " + header.type.ToString());
            Console.WriteLine("STREAM ID : " + header.streamId);

            if (header.type == Http2FrameType.Headers)
            {
                Console.WriteLine("END HEADER : " + header.endHeaders.ToString());
                Console.WriteLine("PRIORITY : " + header.hasPriority.ToString());
                Console.WriteLine("PADDING : " + header.hasPadding.ToString());

                for (int i = 0; i < header.length; i++)
                {
                    Console.Write(data.ElementAt(9 + i).ToString() + " ");
                }
                Console.WriteLine();
            }

            return(header);
        }
Esempio n. 2
0
 public BazelyStageData(ArraySegment <string> data)
 {
     Vnum          = double.Parse(data.ElementAt(0));
     Vden          = double.Parse(data.ElementAt(1));
     SameDirection = (double.Parse(data.ElementAt(2)) == 1);
     Ex            = double.Parse(data.ElementAt(3));
     PHI           = double.Parse(data.ElementAt(4));
 }
Esempio n. 3
0
        public static Http2HeadersRequest ParseHeaders(Http2Frame frame, ArraySegment <byte> data)
        {
            if (frame.type == Http2FrameType.Headers)
            {
                throw new InvalidOperationException("frame.type != Headers");
            }
            if (frame.length > data.Count)
            {
                return(null);
            }

            var req = new Http2HeadersRequest();

            for (int i = 0; i < frame.length; i++)
            {
                var ch = data.ElementAt(i);

                // 1 0 -> Indexed_HasNothing
                if ((ch & 0x80) != 0)
                {
                    req.hpackCommands.Add(HPackCommandFactory.Indexed(ch ^ 0x80));
                }
                // 0 1 -> Indexed_HasValue
                else if ((ch & 0x40) != 0)
                {
                    var length = data.ElementAt(i + 1);
                    var huff   = (length & 0x80) != 0;

                    length &= 0x7F;

                    var payload = new byte[length];

                    Console.WriteLine("hUFF : " + huff.ToString());
                    Console.WriteLine("LEN : " + length.ToString());

                    Buffer.BlockCopy(data.Array, data.Offset + i + 2, payload, 0, length);

                    if (huff)
                    {
                        payload = Huffman.Convert.Decode(payload);
                    }

                    Console.WriteLine(Encoding.UTF8.GetString(payload));

                    req.hpackCommands.Add(
                        HPackCommandFactory.UpdateValue(ch ^ 0x40, Encoding.UTF8.GetString(payload)));

                    i += 1 + length;
                }
            }

            return(req);
        }
        /// <inheritdoc/>
        public override bool Compute(ArraySegment <string> arguments, ICommandSender sender, out string response)
        {
            // Verify the following arguments: Gamemode prefix, Config property name, new value.
            if (arguments.Count >= 3)
            {
                // Search and verify send Gamemode type
                Type type = arguments.ElementAt(0).ToLower() == API.Gamemode.current.Prefix.ToLower() ? API.Gamemode.current.GetType() : null;
                if (type != null)
                {
                    // Try to get configs linked to the specified Gamemode
                    if (Loader.Config.TryGetConfig(type, out IEnumerable <API.Config.MetaConfig> value))
                    {
                        // Look for specified property through every Configs
                        foreach (API.Config.MetaConfig config in value)
                        {
                            // When found, try to change its value
                            if (config.properties.TryGetValue(arguments.ElementAt(1).ToLower(), out PropertyInfo info))
                            {
                                try
                                {
                                    info.SetValue(null, Convert.ChangeType(arguments.ElementAt(2), info.PropertyType), null);
                                }
                                catch (Exception)
                                {
                                    response = $"An exception has occured, its type and/or the string format might be incorrect...";
                                    return(false);
                                }

                                response = $"{ arguments.ElementAt(1) }, { (info.GetCustomAttribute(typeof(API.Config.Attributes.Description)) as API.Config.Attributes.Description)?.Text ?? "x" }, was set to: { arguments.ElementAt(2) }.";
                                return(true);
                            }
                        }
                        response = $"{ arguments.ElementAt(1) } property couldn't be found, is this for the right Gamemode ?";
                    }
                    else
                    {
                        response = "No dynamic config has been registered to the selected Gamemode...";
                    }
                }
                else
                {
                    response = "No Gamemode could be found, is this a correct prefix ?";
                }
            }
            else
            {
                response = "Too few arguments were given, expecting a Gamemode prefix, a proprety name and a value.";
            }

            return(false);
        }
Esempio n. 5
0
        public BazelyChuck(int pnum, String[] data)
            : base(PatternType.bazley, 0, 1)
        {
            PatternIndex = pnum;
            try
            {
                SR = double.Parse(data[5]);
            }
            catch
            {
                SR = 0;
            }
            Stages = new ObservableCollection <BazelyStageData>();
            // now one or more stages
            ArraySegment <string> stage1 = new ArraySegment <string>(data, 0, 5);
            ArraySegment <string> stage2 = new ArraySegment <string>(data, 6, 5);
            BazelyStageData       sdata  = new BazelyStageData(stage1);

            this.Add(sdata);
            string s2 = stage2.ElementAt(0);

            if (double.Parse(s2) != 0)
            {
                this.Add(new BazelyStageData(stage2));
            }
            var resourceLoader = new ResourceLoader();

            Script = resourceLoader.GetString("RUN");
        }
Esempio n. 6
0
        static public Code GetOpCode(ArraySegment <byte> data)
        {
            switch (data.ElementAt(0) & 0x0f)
            {
            //*  % x0 denotes a continuation frame
            case 0x00:
                return(Code.continuation);

            //*  % x1 denotes a text frame
            case 0x01:
                return(Code.text);

            //*  % x2 denotes a binary frame
            case 0x02:
                return(Code.binary);

            //*  % x3 - 7 are reserved for further non-control frames
            //*  % x8 denotes a connection close
            case 0x08:
                return(Code.close);

            //*  % x9 denotes a ping
            case 0x09:
                return(Code.ping);

            //*  % xA denotes a pong
            case 0x0A:
                return(Code.pong);

            //*  % xB - F are reserved for further control frames
            default:
                return(Code.error);
            }
        }
        /// <summary>
        /// Web socket frame format from client:
        /// <list type="bullet">
        ///   <item>
        ///     <description>one byte which contains the type of data. Text type is 129.</description>
        ///   </item>
        ///   <item>
        ///     <description>one byte which contains the length of the payload.</description>
        ///   </item>
        ///   <item>
        ///     <description>either 2 or 8 additional bytes if length does not fit in the 2nd byte.
        ///     </description>
        ///   </item>
        /// </list>
        /// </summary>
        /// <param name="dataBuffer"></param>
        /// <param name="bytesReceived"></param>
        /// <returns></returns>
        private Byte[] Decode(Byte[] dataBuffer, Int32 bytesReceived)
        {
            Log.Debug(dataBuffer.Length);
            Log.DebugFormat("bytes recived = {0}", bytesReceived);
            var secondByte = dataBuffer[1];

            Int32 length         = secondByte & (Byte)127;
            var   indexFirstMask = 2; // If not a special case.

            if (length == 126)
            {
                indexFirstMask = 4;
            }
            else if (length == 127)
            {
                indexFirstMask = 10;
            }
            Log.DebugFormat("Index of first mask = {0}", indexFirstMask);
            var mask = new ArraySegment <byte>(dataBuffer, indexFirstMask, NumMaskBytes);
            var indexFirstDataByte = indexFirstMask + NumMaskBytes;
            var decoded            = new Byte[bytesReceived - indexFirstDataByte];

            for (Int32 i = indexFirstDataByte, j = 0; i < bytesReceived; i++, j++)
            {
                decoded[j] = (Byte)(dataBuffer[i] ^ mask.ElementAt <Byte>(j % NumMaskBytes));
            }
            return(decoded);
        }
Esempio n. 8
0
        public static HttpRequest PraseData(Http2Frame frame, ArraySegment <byte> data)
        {
            if (frame.type == Http2FrameType.Data)
            {
                throw new InvalidOperationException("frame.type != Data");
            }
            if (frame.length > data.Count)
            {
                return(null);
            }

            int padLength  = 0;
            int dataLength = frame.length;

            if (frame.hasPadding)
            {
                padLength   = Convert.ToInt32(data.ElementAt(0));
                dataLength -= 1 /* padLength */ - padLength;
            }

            var request = new HttpRequest();

            request.content = data
                              .Skip(frame.hasPadding ? 1 : 0)
                              .Take(dataLength).ToArray();

            return(request);
        }
Esempio n. 9
0
        public override bool Run(ArraySegment <string> arguments, ICommandSender sender, out string response)
        {
            Player target;

            if ((target = Player.List.ElementAt(0)) != null)
            {
                string msg = $"The survivor {target.Nickname} is located in {target.CurrentRoom.Name} !";
                if (arguments.Count() > 0)
                {
                    if (arguments.ElementAt(0).ToLower().StartsWith("z"))
                    {
                        Player.List.Where(e => e.Role == RoleType.Scp0492).Do(e => e.Broadcast(5, msg));

                        response = $"The command has successfully broadcast {target.Nickname} position to every Zombies !";
                        return(true);
                    }
                    else
                    {
                        response = "Command unknown, if you wish to broadcast a survivor position to Zombies: only give 'z' as a first argument...";
                        return(false);
                    }
                }

                Map.Broadcast(5, msg);
                response = $"Everyone is now aware of {target.Nickname} position !";
                return(true);
            }
            else
            {
                response = "Couldn't find a target to broadcast...";
            }

            return(false);
        }
Esempio n. 10
0
        //Mask:  1 bit

        //Defines whether the "Payload data" is masked.If set to 1, a
        //masking key is present in masking-key, and this is used to unmask
        //the "Payload data" as per Section 5.3.  All frames sent from
        //client to server have this bit set to 1.
        static public void CheckMask(ArraySegment <byte> data)
        {
            if ((data.ElementAt(1) & 0x80) != 0x80)
            {
                throw new InvalidFormatException();
            }
        }
Esempio n. 11
0
        private static CommandInfo Parse(string input)
        {
            var split = new ArraySegment <string>(input.Split(' '));

            return(new CommandInfo()
            {
                key = split.ElementAt(0),
                args = split.Skip(1).ToArray <string>()
            });
        }
Esempio n. 12
0
        public Handshake(ArraySegment <byte> message)
        {
            if (message.Array == null || message.Count != 4)
            {
                throw new ArgumentException("Expected a 4 length ArraySegment<byte>.", nameof(message));
            }

            MagicOctet = message.ElementAt(0);

            if (MagicOctet != RawSocketMagicOctet)
            {
                throw new ArgumentException($"First octet must be 0x{RawSocketMagicOctet:X}.",
                                            nameof(message));
            }

            SecondOctet = message.ElementAt(1);

            ReservedOctets = BitConverter.ToInt16(message.Array, message.Offset + 2);
        }
Esempio n. 13
0
        public static Http2PingRequest ParsePing(Http2Frame frame, ArraySegment <byte> data)
        {
            if (frame.type == Http2FrameType.Ping)
            {
                throw new InvalidOperationException("frame.type != Ping");
            }
            if (frame.length > data.Count)
            {
                return(null);
            }

            var req = new Http2PingRequest();

            req.opaqueData[0] = data.ElementAt(0);
            req.opaqueData[1] = data.ElementAt(1);

            Console.WriteLine("OPAQUE");
            Console.WriteLine(req.opaqueData[0]);
            Console.WriteLine(req.opaqueData[1]);

            return(req);
        }
Esempio n. 14
0
        private static bool InnerParse(bool throwExceptions, ArraySegment <byte> headerBytes, out FrameType frameType, out int messageLength)
        {
            frameType     = default(FrameType);
            messageLength = default(int);

            if (!ValidateHeaderArray(headerBytes, throwExceptions))
            {
                return(false);
            }

            byte messageTypeInBytes = headerBytes.ElementAt(0);

            if (!ValidateMessageType(messageTypeInBytes, throwExceptions))
            {
                return(false);
            }

            frameType = (FrameType)messageTypeInBytes;

            messageLength = headerBytes.ElementAt(3) + (headerBytes.ElementAt(2) << 8) + (headerBytes.ElementAt(1) << 16);

            return(true);
        }
Esempio n. 15
0
        public bool Execute(ArraySegment <string> arguments, ICommandSender sender, out string respone)
        {
            if (sender.GetPlayer() == Server.Host)
            {
                respone = "Nope the Console cant use this!";
                return(false);
            }

            if (arguments.Count < 1)
            {
                respone = "Use .key sync in order to sync your binds and use all Features of the Plugins!";
                return(false);
            }

            switch (arguments.FirstOrDefault().ToUpper())
            {
            case "SYNC":
                var component = sender.GetPlayer().ClassManager;
                foreach (var key in (KeyCode[])Enum.GetValues(typeof(KeyCode)))
                {
                    component.TargetChangeCmdBinding(component.connectionToClient, key, $".key send {(int)key}");
                }

                respone = "All Keys was synced!";
                return(true);

            case "SEND":
                if (!Enum.TryParse <KeyCode>(arguments.ElementAt(1), out var key2))
                {
                    respone = "Invalid KeyBind! If they are binded by Synapse please report this!";
                    return(false);
                }

                try
                {
                    Events.Events.InvokeKeyPressEvent(sender.GetPlayer(), key2);
                }
                catch (Exception e)
                {
                    Log.Error($"KeyPressEvent Error: {e} ");
                }
                respone = "Key was accepted";
                return(true);

            default:
                respone = "Use .key sync in order to sync your binds and use all Features of the Plugins!";
                return(false);
            }
        }
Esempio n. 16
0
 private static CommandInfo Parse(string input)
 {
     if (string.IsNullOrEmpty(input) == false && string.IsNullOrWhiteSpace(input) == false)
     {
         var split = new ArraySegment <string>(input.Split(' '));
         return(new CommandInfo()
         {
             key = split.ElementAt(0),
             args = split.Skip(1).ToArray <string>()
         });
     }
     else
     {
         return(new CommandInfo()
         {
             key = emptyKey
         });
     }
 }
Esempio n. 17
0
        public static bool TryParse(ArraySegment <byte> message, out Handshake result)
        {
            result = default(Handshake);

            if (message.Array == null || message.Count != 4)
            {
                throw new ArgumentException("Expected a 4 length ArraySegment<byte>.", nameof(message));
            }

            byte magicOctet = message.ElementAt(0);

            if (magicOctet != RawSocketMagicOctet)
            {
                return(false);
            }

            result = new Handshake(message);
            return(true);
        }
Esempio n. 18
0
        public static int GetPlayloadExtraOffset(ArraySegment <byte> data)
        {
            var byte0 = data.ElementAt(1) & 0x7f;

            if (0 <= byte0 && byte0 <= 125)
            {
                return(0);
            }
            if (byte0 == 126)
            {
                return(2);
            }
            if (byte0 == 127)
            {
                return(8);
            }

            throw new InvalidPayloadException();
        }
Esempio n. 19
0
        //Payload length:  7 bits, 7+16 bits, or 7+64 bits

        //The length of the "Payload data", in bytes: if 0-125, that is the
        //payload length.If 126, the following 2 bytes interpreted as a
        //16-bit unsigned integer are the payload length.If 127, the
        //following 8 bytes interpreted as a 64-bit unsigned integer(the
        //most significant bit MUST be 0) are the payload length.Multibyte
        //length quantities are expressed in network byte order.  Note that
        //in all cases, the minimal number of bytes MUST be used to encode
        //the length, for example, the length of a 124-byte-long string
        //can't be encoded as the sequence 126, 0, 124.  The payload length
        //is the length of the "Extension data" + the length of the
        //"Application data".  The length of the "Extension data" may be
        //zero, in which case the payload length is the length of the
        //"Application data".
        public static int GetPlayloadLength(ArraySegment <byte> data)
        {
            var byte0 = data.ElementAt(1) & 0x7f;

            if (0 <= byte0 && byte0 <= 125)
            {
                return(byte0);
            }
            if (byte0 == 126)
            {
                return(BitConverter.ToInt16(data.Array, 3));
            }
            if (byte0 == 127)
            {
                //though this is allowed, we don't allow our game payload is longer than int.MaxValue.
                //return BitConverter.ToInt64(data.Array, 3);
                throw new InvalidPayloadException();
            }

            throw new InvalidPayloadException();
        }
Esempio n. 20
0
        public override bool Run(ArraySegment <string> arguments, ICommandSender sender, out string response)
        {
            int amount = 1;

            if (arguments.Count > 0)
            {
                if (!int.TryParse(arguments.ElementAt(0), out amount))
                {
                    response = "First argument is incorrect, expecting an integer...";
                    return(false);
                }
            }

            var zombies = Player.List.Where(e => e.Role == RoleType.Scp0492);

            for (int ii = 0; ii < amount; ++ii)
            {
                zombies.Do(e => e.ReferenceHub.playerEffectsController.EnableEffect <CustomPlayerEffects.Scp207>());
            }

            response = $"Every zombies has got its speed boosted by {amount} !";
            return(true);
        }
Esempio n. 21
0
        public bool Execute(ArraySegment <string> arguments, ICommandSender sender, out string response)
        {
            if (arguments.Count > 0)
            {
                if (int.TryParse(arguments.ElementAt(0), out int value))
                {
                    if (Methods.CheckSeedValidity(value))
                    {
                        Data.currentSeed.value = value;
                        response = $"Seed was set to {value} successfully !";

                        if (Data.isRandom.value)
                        {
                            Data.isRandom.value = false;
                            response           += "\n[INFO] Seed was locked on set.";
                        }

                        return(true);
                    }
                    else
                    {
                        response = "Seed shouldn't be 10 digits long (or more) nor equal to -1...";
                    }
                }
                else
                {
                    response = "Seed couldn't be parsed, try sending a valid Integer...";
                }
            }
            else
            {
                response = "No argument was found, expecting the seed to set...";
            }

            return(false);
        }
Esempio n. 22
0
        private Tuple <string, string, string> GetFormattedFilters(
            string[] expressions,
            CosmosElement[] orderByItems,
            SortOrder[] sortOrders)
        {
            // When we run cross partition queries,
            // we only serialize the continuation token for the partition that we left off on.
            // The only problem is that when we resume the order by query,
            // we don't have continuation tokens for all other partition.
            // The saving grace is that the data has a composite sort order(query sort order, partition key range id)
            // so we can generate range filters which in turn the backend will turn into rid based continuation tokens,
            // which is enough to get the streams of data flowing from all partitions.
            // The details of how this is done is described below:
            int           numOrderByItems = expressions.Length;
            bool          isSingleOrderBy = numOrderByItems == 1;
            StringBuilder left            = new StringBuilder();
            StringBuilder target          = new StringBuilder();
            StringBuilder right           = new StringBuilder();

            Tuple <StringBuilder, StringBuilder, StringBuilder> builders = new Tuple <StringBuilder, StringBuilder, StringBuilder>(left, right, target);

            if (isSingleOrderBy)
            {
                //For a single order by query we resume the continuations in this manner
                //    Suppose the query is SELECT* FROM c ORDER BY c.string ASC
                //        And we left off on partition N with the value "B"
                //        Then
                //            All the partitions to the left will have finished reading "B"
                //            Partition N is still reading "B"
                //            All the partitions to the right have let to read a "B
                //        Therefore the filters should be
                //            > "B" , >= "B", and >= "B" respectively
                //    Repeat the same logic for DESC and you will get
                //            < "B", <= "B", and <= "B" respectively
                //    The general rule becomes
                //        For ASC
                //            > for partitions to the left
                //            >= for the partition we left off on
                //            >= for the partitions to the right
                //        For DESC
                //            < for partitions to the left
                //            <= for the partition we left off on
                //            <= for the partitions to the right
                string        expression          = expressions.First();
                SortOrder     sortOrder           = sortOrders.First();
                CosmosElement orderByItem         = orderByItems.First();
                string        orderByItemToString = JsonConvert.SerializeObject(orderByItem, DefaultJsonSerializationSettings.Value);
                left.Append($"{expression} {(sortOrder == SortOrder.Descending ? "<" : ">")} {orderByItemToString}");
                target.Append($"{expression} {(sortOrder == SortOrder.Descending ? "<=" : ">=")} {orderByItemToString}");
                right.Append($"{expression} {(sortOrder == SortOrder.Descending ? "<=" : ">=")} {orderByItemToString}");
            }
            else
            {
                //For a multi order by query
                //    Suppose the query is SELECT* FROM c ORDER BY c.string ASC, c.number ASC
                //        And we left off on partition N with the value("A", 1)
                //        Then
                //            All the partitions to the left will have finished reading("A", 1)
                //            Partition N is still reading("A", 1)
                //            All the partitions to the right have let to read a "(A", 1)
                //        The filters are harder to derive since their are multiple columns
                //        But the problem reduces to "How do you know one document comes after another in a multi order by query"
                //        The answer is to just look at it one column at a time.
                //        For this particular scenario:
                //        If a first column is greater ex. ("B", blah), then the document comes later in the sort order
                //            Therefore we want all documents where the first column is greater than "A" which means > "A"
                //        Or if the first column is a tie, then you look at the second column ex. ("A", blah).
                //            Therefore we also want all documents where the first column was a tie but the second column is greater which means = "A" AND > 1
                //        Therefore the filters should be
                //            (> "A") OR (= "A" AND > 1), (> "A") OR (= "A" AND >= 1), (> "A") OR (= "A" AND >= 1)
                //            Notice that if we repeated the same logic we for single order by we would have gotten
                //            > "A" AND > 1, >= "A" AND >= 1, >= "A" AND >= 1
                //            which is wrong since we missed some documents
                //    Repeat the same logic for ASC, DESC
                //            (> "A") OR (= "A" AND < 1), (> "A") OR (= "A" AND <= 1), (> "A") OR (= "A" AND <= 1)
                //        Again for DESC, ASC
                //            (< "A") OR (= "A" AND > 1), (< "A") OR (= "A" AND >= 1), (< "A") OR (= "A" AND >= 1)
                //        And again for DESC DESC
                //            (< "A") OR (= "A" AND < 1), (< "A") OR (= "A" AND <= 1), (< "A") OR (= "A" AND <= 1)
                //    The general we look at all prefixes of the order by columns to look for tie breakers.
                //        Except for the full prefix whose last column follows the rules for single item order by
                //        And then you just OR all the possibilities together
                for (int prefixLength = 1; prefixLength <= numOrderByItems; prefixLength++)
                {
                    ArraySegment <string>        expressionPrefix   = new ArraySegment <string>(expressions, 0, prefixLength);
                    ArraySegment <SortOrder>     sortOrderPrefix    = new ArraySegment <SortOrder>(sortOrders, 0, prefixLength);
                    ArraySegment <CosmosElement> orderByItemsPrefix = new ArraySegment <CosmosElement>(orderByItems, 0, prefixLength);

                    bool lastPrefix  = prefixLength == numOrderByItems;
                    bool firstPrefix = prefixLength == 1;

                    this.AppendToBuilders(builders, "(");

                    for (int index = 0; index < prefixLength; index++)
                    {
                        string        expression  = expressionPrefix.ElementAt(index);
                        SortOrder     sortOrder   = sortOrderPrefix.ElementAt(index);
                        CosmosElement orderByItem = orderByItemsPrefix.ElementAt(index);
                        bool          lastItem    = (index == prefixLength - 1);

                        // Append Expression
                        this.AppendToBuilders(builders, expression);
                        this.AppendToBuilders(builders, " ");

                        // Append binary operator
                        if (lastItem)
                        {
                            string inequality = sortOrder == SortOrder.Descending ? "<" : ">";
                            this.AppendToBuilders(builders, inequality);
                            if (lastPrefix)
                            {
                                this.AppendToBuilders(builders, "", "=", "=");
                            }
                        }
                        else
                        {
                            this.AppendToBuilders(builders, "=");
                        }

                        // Append SortOrder
                        string orderByItemToString = JsonConvert.SerializeObject(orderByItem, DefaultJsonSerializationSettings.Value);
                        this.AppendToBuilders(builders, " ");
                        this.AppendToBuilders(builders, orderByItemToString);
                        this.AppendToBuilders(builders, " ");

                        if (!lastItem)
                        {
                            this.AppendToBuilders(builders, "AND ");
                        }
                    }

                    this.AppendToBuilders(builders, ")");
                    if (!lastPrefix)
                    {
                        this.AppendToBuilders(builders, " OR ");
                    }
                }
            }

            return(new Tuple <string, string, string>(left.ToString(), target.ToString(), right.ToString()));
        }
Esempio n. 23
0
 private Opcode.Code _GetOpcode(ArraySegment <byte> data)
 {
     return(Opcode.GetOpCode(data.ElementAt(1)));
 }
        /// <summary>
        /// Web socket frame format from client:
        /// <list type="bullet">
        ///   <item>
        ///     <description>one byte which contains the type of data. Text type is 129.</description>  
        ///   </item>
        ///   <item>
        ///     <description>one byte which contains the length of the payload.</description>
        ///   </item>
        ///   <item>
        ///     <description>either 2 or 8 additional bytes if length does not fit in the 2nd byte.
        ///     </description>
        ///   </item>
        /// </list>
        /// </summary>
        /// <param name="dataBuffer"></param>
        /// <param name="bytesReceived"></param>
        /// <returns></returns>
        private Byte[] Decode(Byte[] dataBuffer, Int32 bytesReceived)
        {
            Log.Debug(dataBuffer.Length);
              Log.DebugFormat("bytes recived = {0}", bytesReceived);
              var secondByte = dataBuffer[1];

              Int32 length = secondByte & (Byte)127;
              var indexFirstMask = 2; // If not a special case.
              if (length == 126) {
            indexFirstMask = 4;
              } else if (length == 127) {
            indexFirstMask = 10;
              }
              Log.DebugFormat("Index of first mask = {0}", indexFirstMask);
              var mask = new ArraySegment<byte>(dataBuffer, indexFirstMask, NumMaskBytes);
              var indexFirstDataByte = indexFirstMask + NumMaskBytes;
              var decoded = new Byte[bytesReceived - indexFirstDataByte];
              for (Int32 i = indexFirstDataByte, j = 0; i < bytesReceived; i++, j++) {
            decoded[j] = (Byte)(dataBuffer[i] ^ mask.ElementAt<Byte>(j % NumMaskBytes));
              }
              return decoded;
        }