public static uint ComputePartitionArrayCRC32(Disk disk, GuidPartitionTableHeader header)
        {
            int sectorsToRead = (int)Math.Ceiling((double)header.NumberOfPartitionEntries * header.SizeOfPartitionEntry / disk.BytesPerSector);

            byte[] buffer = disk.ReadSectors((long)header.PartitionEntriesLBA, sectorsToRead);
            return(CRC32.Compute(buffer));
        }
        private static List <GuidPartitionEntry> ReadEntriesFromDisk(Disk disk, GuidPartitionTableHeader header)
        {
            int bufferLength  = (int)(header.NumberOfPartitionEntries * header.SizeOfPartitionEntry);
            int sectorsToRead = (int)Math.Ceiling((double)bufferLength / disk.BytesPerSector);

            byte[] buffer = disk.ReadSectors((long)header.PartitionEntriesLBA, sectorsToRead);
            if (buffer.Length > bufferLength)
            {
                buffer = ByteReader.ReadBytes(buffer, 0, bufferLength);
            }
            uint expectedCRC32 = CRC32.Compute(buffer);

            if (header.PartitionArrayCRC32 != expectedCRC32)
            {
                return(null);
            }

            int offset = 0;
            List <GuidPartitionEntry> result = new List <GuidPartitionEntry>();

            for (int index = 0; index < header.NumberOfPartitionEntries; index++)
            {
                GuidPartitionEntry entry = new GuidPartitionEntry(buffer, offset);
                entry.EntryIndex = index;
                // Unused entries use Guid.Empty as PartitionTypeGuid
                if (entry.PartitionTypeGuid != Guid.Empty)
                {
                    result.Add(entry);
                }
                offset += (int)header.SizeOfPartitionEntry;
            }
            return(result);
        }
Example #3
0
    public void CRC32TestSimplePasses()
    {
        var IEND = new byte[] { 0x49, 0x45, 0x4e, 0x44 };
        var crc  = CRC32.Compute(IEND, 0, 4);

        Assert.AreEqual(crc, 0xAE426082, "IEND chunk's CRC");
    }
Example #4
0
        /// <summary>Used internally by the netcode to send unconnected messages.</summary>
        private async Task <int> SendAsync(PacketType type, IPEndPoint remote, IWritable message)
        {
            // Buffers allocated by the allocator
            byte[] compress = null;
            Writer writer   = null;

            try {
                // Write message
                writer = new Writer(Allocator, 5);
                message?.Write(writer);
                ArraySegment <byte> packet = new ArraySegment <byte>(writer.Buffer, 5, writer.Position - 5);

                // Create flags
                PacketFlags flags = PacketFlags.None;

                // Compress
                if (Config.Compression)
                {
                    int max = Compressor.MaxCompressedLength(packet.Count) + packet.Offset;
                    compress = Allocator.CreateMessage(max);
                    int len = Compressor.Compress(packet, compress, packet.Offset);
                    if (len <= 0)
                    {
                        throw new InvalidOperationException(string.Format(
                                                                "Compressing {0} bytes returned {1} bytes", packet.Count, len
                                                                ));
                    }
                    else if (len < packet.Count)
                    {
                        packet = new ArraySegment <byte>(compress, packet.Offset, len);
                        flags |= PacketFlags.Compressed;
                    }
                }

                // Write CRC32
                if (Config.CRC32)
                {
                    uint crc32 = CRC32.Compute(packet.Array, packet.Offset, packet.Count);
                    Serializer.Write32(packet.Array, packet.Offset - 4, crc32);
                    packet = new ArraySegment <byte>(packet.Array, packet.Offset - 4, packet.Count + 4);
                    flags |= PacketFlags.Verified;
                }

                // Write header
                packet.Array[packet.Offset - 1] = (byte)(((byte)type) | ((byte)flags));
                packet = new ArraySegment <byte>(packet.Array, packet.Offset - 1, packet.Count + 1);

                // Send
                return(await SendSocketAsync(remote, packet.Array, packet.Offset, packet.Count));
            } catch (Exception exception) {
                // Notify listener about the exception
                Listener.OnHostException(remote, exception);
                throw;
            } finally {
                // Return the allocated buffers back to the allocator
                writer?.Dispose();
                Allocator.ReturnMessage(ref compress);
            }
        }
Example #5
0
        public void TestCRC32()
        {
            var data = Encoding.ASCII.GetBytes("abcdefg");

            Assert.AreEqual((uint)0x312A6AA6, CRC32.Compute(data));
            data = Encoding.ASCII.GetBytes("abcdefg12345678");
            Assert.AreEqual(0x9AE0DAAF, CRC32.Compute(data, 7, 8));
        }
Example #6
0
        public Market(SystemBody body, string code)
        {
            this.entries = new Dictionary <int, MarketEntry>();
            ulong systemId = body.SystemId;
            int   seed     = Math.Abs(CRC32.Compute(systemId.ToString() + code));

            //int seed = (int)(body.SystemBodyId | (int)((systemId >> 16) & 0xFFFFFFFF));

            Random rand = new Random(seed);

            double timeBase = DateTime.Now.Subtract(new DateTime(2011, 1, 1)).TotalHours;

            double pfluctuation = 1.5 + Math.Sin(timeBase / 2);
            double qfluctuation = 1.5 + Math.Cos(timeBase);


            foreach (var tGood in TradeGood.Goods)
            {
                double quantity;
                double baseQuantity = (double)tGood.BaseQuantity;

                //int overTech = (int)body.StarSystem.TechLevel - tGood.MinTechLevel;

                int overTech = 10;

                bool mainP = overTech > 10;

                if (tGood.MainOrigin.Count > 0)
                {
                    mainP &= tGood.MainOrigin.Contains(body.BodyType);
                }

                if (!mainP)
                {
                    quantity = rand.Next(0, (int)baseQuantity / 8);
                }
                else
                {
                    quantity = rand.Next((int)baseQuantity / 8, (int)baseQuantity * 2);
                    if (tGood.MinTechLevel > 0)
                    {
                        quantity *= 1 + (overTech * 0.1);
                    }
                }

                quantity *= qfluctuation;

                double actBasePrice = pfluctuation * tGood.BasePrice;

                double bQ        = quantity / baseQuantity;
                double f         = Math.Pow(3, (-(bQ - 1))) + 0.1;
                var    currPrice = f * actBasePrice;

                MarketEntry entry = new MarketEntry(tGood, (int)currPrice, actBasePrice, (int)quantity);

                this.entries.Add(tGood.TradeGoodId, entry);
            }
        }
Example #7
0
        protected void SpawnInhibitor(string name)
        {
            uint      netId     = BuildingProvider.BUILDING_NETID_X | CRC32.Compute(Encoding.ASCII.GetBytes(name));
            Inhibitor inhibitor = new Inhibitor(netId, BuildingRecord.GetBuildingRecord(this.Game.Map.Id, name), Game.Map.Record.GetObject(name));

            inhibitor.DefineGame(Game);
            Game.AddUnitToTeam(inhibitor, BuildingProvider.Instance.GetTeamId(name));
            Game.Map.AddUnit(inhibitor);
        }
Example #8
0
        protected void SpawnNexus(string name)
        {
            uint  netId = BuildingProvider.BUILDING_NETID_X | CRC32.Compute(Encoding.ASCII.GetBytes(name));
            Nexus nexus = new Nexus(netId, BuildingRecord.GetBuildingRecord(this.Game.Map.Id, name), Game.Map.Record.GetObject(name));

            nexus.DefineGame(Game);
            Game.AddUnitToTeam(nexus, BuildingProvider.Instance.GetTeamId(name));
            Game.Map.AddUnit(nexus);
        }
Example #9
0
        private void LoadUpdateXMLOK(Dictionary <string, UpdateFileInfo> _dic, int _remoteVersion, Func <string, string> _fixFun, Action _callBack)
        {
            int loadNum = _dic.Count;

            foreach (KeyValuePair <string, UpdateFileInfo> pair in _dic)
            {
                string         path = pair.Key;
                UpdateFileInfo info = pair.Value;

                string url = _fixFun(info.path + path);

                Action <WWW> callBack = delegate(WWW obj) {
                    if (obj.error != null)
                    {
                        SuperDebug.Log("文件热更新失败 文件名:" + obj.url);

                        return;
                    }

                    UInt32 crc = CRC32.Compute(obj.bytes);

                    if (crc != info.crc)
                    {
                        SuperDebug.Log("文件热更新CRC比对错误 文件名:" + obj.url);

                        return;
                    }

                    SystemIO.SaveFile(Application.persistentDataPath + "/" + path, obj.bytes);

                    if (data.dic.ContainsKey(path))
                    {
                        data.dic[path] = info.version;
                    }
                    else
                    {
                        data.dic.Add(path, info.version);
                    }

                    loadNum--;

                    if (loadNum == 0)
                    {
                        UpdateOver(_remoteVersion, _callBack);
                    }
                };

                WWWManager.Instance.LoadRemote(url, callBack);
            }
        }
Example #10
0
        public static void Add(string phonenumber)
        {
            if (phonenumber.Trim() == string.Empty)
            {
                return;
            }

            WhiteList     wl  = new WhiteList();
            WhiteListItem wli = new WhiteListItem();

            wli.phoneNumber = phonenumber;
            wli.checkSum    = CRC32.Compute(phonenumber);
            wl.Load();
            wl.Add(wli);
            wl.Save();
        }
Example #11
0
        internal void Add(ulong gcNID, Protos.GC2BS_EndBattle endBattle)
        {
            //检查玩家是否重复提交
            if (this._playerSnapshots.Any(snapshot => snapshot.gcNID == gcNID))
            {
                Logger.Error($"user:{gcNID} duplicate commit snapshot!");
                return;
            }

            PlayerSnapshot playerSnapshot = new PlayerSnapshot();

            playerSnapshot.gcNID = gcNID;
            playerSnapshot.data  = endBattle.Snapshot;
            playerSnapshot.crc   = CRC32.Compute(endBattle.Snapshot.ToByteArray());
            this._playerSnapshots.Add(playerSnapshot);
        }
        public static void InitializeDisk(Disk disk, long firstUsableLBA, List <GuidPartitionEntry> partitionEntries)
        {
            MasterBootRecord mbr = new MasterBootRecord();

            mbr.DiskSignature = (uint)new Random().Next(Int32.MaxValue);
            mbr.PartitionTable[0].PartitionTypeName = PartitionTypeName.EFIGPT;
            mbr.PartitionTable[0].FirstSectorLBA    = 1;
            mbr.PartitionTable[0].SectorCountLBA    = (uint)Math.Min(disk.TotalSectors - firstUsableLBA, UInt32.MaxValue);
            mbr.MBRSignature = 0xAA55;
            MasterBootRecord.WriteToDisk(disk, mbr);

            const int DefaultNumberOfEntries       = 128;
            const int DefaultSizeOfEntry           = 128;
            int       partitionEntriesLength       = DefaultNumberOfEntries * DefaultSizeOfEntry;
            long      partitionEntriesPrimaryLBA   = 2;
            long      partitionEntriesSecondaryLBA = disk.TotalSectors - 1 - partitionEntriesLength / disk.BytesPerSector;

            GuidPartitionTableHeader primaryHeader = new GuidPartitionTableHeader();

            primaryHeader.HeaderSize               = 92;
            primaryHeader.CurrentLBA               = 1;
            primaryHeader.BackupLBA                = (ulong)(disk.TotalSectors - 1);
            primaryHeader.DiskGuid                 = Guid.NewGuid();
            primaryHeader.FirstUsableLBA           = (ulong)firstUsableLBA;
            primaryHeader.LastUsableLBA            = (ulong)(partitionEntriesSecondaryLBA - 1);
            primaryHeader.PartitionEntriesLBA      = (ulong)partitionEntriesPrimaryLBA;
            primaryHeader.NumberOfPartitionEntries = DefaultNumberOfEntries;
            primaryHeader.SizeOfPartitionEntry     = DefaultSizeOfEntry;
            byte[] partitionTableEntries = new byte[partitionEntriesLength];

            for (int index = 0; index < partitionEntries.Count; index++)
            {
                partitionEntries[index].WriteBytes(partitionTableEntries, index * DefaultSizeOfEntry);
            }
            primaryHeader.PartitionArrayCRC32 = CRC32.Compute(partitionTableEntries);

            GuidPartitionTableHeader secondaryHeader = primaryHeader.Clone();

            secondaryHeader.CurrentLBA          = (ulong)(disk.TotalSectors - 1);
            secondaryHeader.BackupLBA           = 1;
            secondaryHeader.PartitionEntriesLBA = (ulong)partitionEntriesSecondaryLBA;

            GuidPartitionTableHeader.WriteToDisk(disk, primaryHeader);
            disk.WriteSectors(partitionEntriesPrimaryLBA, partitionTableEntries);
            GuidPartitionTableHeader.WriteToDisk(disk, secondaryHeader);
            disk.WriteSectors(partitionEntriesSecondaryLBA, partitionTableEntries);
        }
Example #13
0
    static void ExecuteCRCScript(int expectedCRC)
    {
        using (var sr = new StreamReader(Path.GetFullPath("Script.cs")))
        {
            string code = sr.ReadToEnd();
            var    crc  = CRC32.Compute(code);
            if (crc != expectedCRC)
            {
                Console.WriteLine("ExecuteCRCScript: Cannot execute Script.cs as it has been altered.");
            }
            else
            {
                var Print = new AsmHelper(CSScript.LoadCode(code))
                            .GetStaticMethod("*.Print", "");

                Print("ExecuteCRCScript: Hello World!");
            }
        }
    }
Example #14
0
        protected void SpawnAITurret(string turretName, string aiUnitRecordName, string customAIUnitRecord = null)
        {
            AIUnitRecord aIUnitRecord = AIUnitRecord.GetAIUnitRecord(customAIUnitRecord != null ? customAIUnitRecord : aiUnitRecordName);

            MapObjectRecord objectRecord = Game.Map.Record.GetObject(turretName);

            if (objectRecord == null)
            {
                logger.Write(string.Format(SPAWN_EX_STRING, turretName, "the GameObjectRecord do not exist."), MessageState.WARNING);
                return;
            }
            if (aIUnitRecord == null)
            {
                logger.Write(string.Format(SPAWN_EX_STRING, turretName, "the AIUnitRecord do not exist."), MessageState.WARNING);
                return;
            }

            string fullName = turretName + BuildingProvider.TOWER_SUFFIX;

            var teamId = BuildingProvider.Instance.GetTeamId(turretName);

            if (teamId != TeamId.UNKNOWN)
            {
                uint     netId  = (uint)(BuildingProvider.BUILDING_NETID_X | CRC32.Compute(Encoding.ASCII.GetBytes(fullName)));
                AITurret turret = new AITurret(netId, aIUnitRecord, objectRecord, BuildingRecord.GetBuildingRecord(Game.Map.Id, turretName), BuildingProvider.TOWER_SUFFIX);
                turret.DefineGame(Game);
                Game.AddUnitToTeam(turret, teamId);
                Game.Map.AddUnit(turret);

                if (customAIUnitRecord != null)
                {
                    turret.AddStackData(customAIUnitRecord, 0, false, true, true, false);
                }
            }
            else
            {
                logger.Write(string.Format(SPAWN_EX_STRING, turretName, "Unable to find a team."), MessageState.WARNING);
            }
        }
Example #15
0
        /// <summary>
        /// 处理玩家提交的快照数据
        /// </summary>
        internal bool Commit(int frame, ulong gcNID, ByteString data)
        {
            if (!this._frameToSnapshots.TryGetValue(frame, out List <PlayerSnapshot> playerSnapshots))
            {
                playerSnapshots = new List <PlayerSnapshot>();
                this._frameToSnapshots[frame] = playerSnapshots;
            }

            //检查玩家是否重复提交
            if (playerSnapshots.Any(snapshot => snapshot.gcNID == gcNID))
            {
                Logger.Error($"user:{gcNID} duplicate commit snapshot!");
                return(false);
            }

            PlayerSnapshot playerSnapshot = new PlayerSnapshot();

            playerSnapshot.gcNID = gcNID;
            playerSnapshot.data  = data;
            playerSnapshot.crc   = CRC32.Compute(data.ToByteArray());
            playerSnapshots.Add(playerSnapshot);
            return(this.CheckPlayerSnapshots(frame, playerSnapshots));
        }
        /// <summary>
        /// Atualiza impressão de dados referente ao servidor
        /// </summary>
        public void Update()
        {
            // Binário para dados de descoberta
            using (MemoryStream memory = new MemoryStream())
            {
                // Salta 4bytes referentes ao CRC
                memory.Write(new byte[4], 0, 4);

                // Parâmetros do XML
                XmlWriterSettings settings = new XmlWriterSettings()
                {
                    CheckCharacters    = true,
                    CloseOutput        = false,
                    ConformanceLevel   = ConformanceLevel.Fragment,
                    Indent             = false,
                    OmitXmlDeclaration = true
                };

                // Gravação de XML
                using (XmlWriter xml = XmlWriter.Create(memory, settings))
                {
                    // Grava informações sobre o serviço
                    xml.WriteStartElement("Server");
                    this._Server.Write(xml);
                    xml.WriteEndElement();
                }

                // Volta a posição referente aos dados, calcula e grava CRC
                memory.Position = 4;
                uint crc = CRC32.Compute(memory);
                memory.Position = 0;
                memory.Write(BitConverter.GetBytes(crc), 0, 4);

                // Recupera dados em binário
                this._Data = memory.ToArray();
            }
        }
Example #17
0
        public static bool Exists(string phonenumber)
        {
            WhiteList wl = new WhiteList();

            wl.Load();

            WhiteListItem wli = wl.Find(p => p.phoneNumber == phonenumber);

            if (wli != null)
            {
                if (wli.checkSum == CRC32.Compute(phonenumber))
                {
                    return(true);
                }
                else
                {
                    return(false);
                }
            }
            else
            {
                return(false);
            }
        }
Example #18
0
        public byte[] ToBytes()
        {
            CRC32        crc32 = new CRC32();
            var          ms    = new MemoryStream();
            var          sw    = new StreamWriter(ms);
            const string magic = "SYNC"; // magic!

            sw.Write(magic);
            crc32.Compute(magic);

            sw.Write(packetID);
            crc32.Compute(packetID);

            sw.Write(_type);
            crc32.Compute(_type);

            var len = datas.Length;

            if (len <= 127)
            {
                sw.Write((char)len);
                crc32.Compute(new byte[] { (byte)len });
            }
            else
            {
                sw.Write((ushort)len & 0x8000);
                crc32.Compute((ushort)len & 0x8000);
            }

            datas.Seek(0, SeekOrigin.Begin);
            datas.CopyTo(ms);
            crc32.Compute(datas.ToArray());

            sw.Write(crc32.hash);
            return(ms.ToArray());
        }
Example #19
0
 /// <summary>Return the checksum of this array of bytes</summary>
 public static int Crc32(this byte[] arr, uint initial_value = 0xFFFFFFFF)
 {
     return(CRC32.Compute(arr, initial_value));
 }
        /// <summary>
        /// Pacote de dados recebido
        /// </summary>
        private void Socket_Received(object sender, BroadcastReceivedEventArgs e)
        {
            try
            {
                // Dados válidos?
                if (e.Data.Length > 4)
                {
                    // Calcula e valida CRC
                    uint inputcrc    = BitConverter.ToUInt32(e.Data, 0);
                    uint computedcrc = CRC32.Compute(e.Data, 4, e.Data.Length - 4);
                    if (inputcrc == computedcrc)
                    {
                        // Cria stream com os dados recebidos
                        using (MemoryStream stream = new MemoryStream(e.Data, 4, e.Data.Length - 4, false))
                        {
                            // Inicia leitor XML
                            using (XmlReader xml = XmlReader.Create(stream))
                            {
                                // Momento atual
                                int now = Environment.TickCount;

                                // Executa primeira leitura
                                while (xml.Read())
                                {
                                    // Está numa estrutura de informação de servidor?
                                    if ((xml.NodeType == XmlNodeType.Element) && (xml.Name == "Server"))
                                    {
                                        // Servidor adicionado na lista?
                                        bool added = false;

                                        // Recupera informações do servidor
                                        ServerInfo info = new ServerInfo(xml, now, e.Source);

                                        // Sincroniza
                                        lock (this._SyncRoot)
                                        {
                                            // Tenta recuperar elemento na lista
                                            ServerInfo server = this._Servers.FirstOrDefault(x => x.Name == info.Name);
                                            if (server != null)
                                            {
                                                // Servidor já está na lista, mas já está considerado como morto?
                                                // Então simula que foi adicionado
                                                added |= (now - server.LastTouch) > this._DeadThreshold;

                                                // Adiciona endereço na lista
                                                server.Update(info, e.Source, now);
                                            }
                                            else
                                            {
                                                // Adiciona servidor na lista
                                                this._Servers.Add(info);
                                                added = true;
                                            }
                                        }

                                        // Se adicionado (agora já fora do lock)
                                        if (added)
                                        {
                                            // Dispara evento de adição
                                            EventHandler <ServerEventArgs> foundhandler = this.Found;
                                            foundhandler?.Invoke(this, new ServerEventArgs(info));
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }

            // Reporta exceções
            catch (Exception ex) { ex.Log(); }
        }
Example #21
0
        private void LoadUpdateXMLOK(Dictionary <string, UpdateFileInfo> _dic, int _remoteVersion, Func <string, string> _fixFun, Action _callBack, Action <string> _setTextCallBack, Action <float> _setPercentCallBack, int _allFileSize)
        {
            int loadNum = _dic.Count;

            int loadSize = 0;

            foreach (KeyValuePair <string, UpdateFileInfo> pair in _dic)
            {
                string path = pair.Key;

                UpdateFileInfo info = pair.Value;

                string url = _fixFun(info.path + path);

                Action <WWW> callBack = delegate(WWW obj) {
                    if (obj.error != null)
                    {
                        _setTextCallBack("文件热更新失败 文件名:" + obj.url);

                        SuperDebug.Log("文件热更新失败 文件名:" + obj.url);

                        return;
                    }

                    UInt32 crc = CRC32.Compute(obj.bytes);

                    if (crc != info.crc)
                    {
                        _setTextCallBack("文件热更新CRC比对错误 文件名:" + obj.url);

                        SuperDebug.Log("文件热更新CRC比对错误 文件名:" + obj.url);

                        return;
                    }

#if PLATFORM_PC || PLATFORM_ANDROID
                    if (path.Equals(CODE_BYTES_NAME))
                    {
                        codeBytes = obj.bytes;
                    }
                    else
                    {
                        SystemIO.SaveFile(Application.persistentDataPath + "/" + path, obj.bytes);
                    }
#else
                    SystemIO.SaveFile(Application.persistentDataPath + "/" + path, obj.bytes);
#endif

                    if (data.dic.ContainsKey(path))
                    {
                        data.dic[path] = info.version;
                    }
                    else
                    {
                        data.dic.Add(path, info.version);
                    }

                    loadNum--;

                    //_setTextCallBack("正在更新:" + (_dic.Count - loadNum) + "/" + _dic.Count);

                    loadSize += info.size;

                    _setTextCallBack("正在更新:" + Math.Round((float)loadSize / (float)_allFileSize * 100) + "%(" + Math.Round((float)loadSize / 1024 / 1024, 1) + "/" + Math.Round((float)_allFileSize / 1024 / 1024, 1) + ")");

                    _setPercentCallBack((float)loadSize / (float)_allFileSize);

                    if (loadNum == 0)
                    {
                        UpdateOver(_remoteVersion, _callBack);
                    }
                };

                WWWManager.Instance.LoadRemote(url, callBack);
            }
        }
Example #22
0
        /// <summary>Used internally by the netcode to process a received packet.</summary>
        private async Task Receive(IPEndPoint remote, byte[] buffer, int length)
        {
            byte[] bufferDecompress = null;
            try {
                // Notify listener
                Listener.OnHostReceiveSocket(remote, buffer, length);

                // Discard if empty
                if (length < 1)
                {
                    return;
                }

                // Extract packet information
                PacketType          type   = (PacketType)(buffer[0] & (byte)PacketType.Mask);
                PacketFlags         flags  = (PacketFlags)(buffer[0] & (byte)PacketFlags.Mask);
                ArraySegment <byte> packet = new ArraySegment <byte>(buffer, 1, length - 1);

                // Peer packets
                if (type == PacketType.Connected || type == PacketType.Reject || type == PacketType.Accept)
                {
                    Peer peer = FindPeer(remote);
                    if (peer == null)
                    {
                        throw new FormatException(string.Format(
                                                      "No peer to receive packet {0} ({1}) from {2}", type, flags, remote
                                                      ));
                    }
                    else
                    {
                        await peer.OnReceiveAsync(buffer, length);

                        return;
                    }
                }

                // Discard if unused packet type
                if (type == PacketType.Unused1 || type == PacketType.Unused2)
                {
                    throw new FormatException(string.Format(
                                                  "Unused packet {0} ({1} received from {2}", type, flags, remote
                                                  ));
                }

                // Fragmentation, multiple messages and timing not supported
                if (flags.HasFlag(PacketFlags.Fragmented))
                {
                    throw new FormatException(string.Format(
                                                  "Packet {0} ({1}) from {2} length {3} is fragmented", flags, type, remote, length
                                                  ));
                }
                else if (flags.HasFlag(PacketFlags.Combined))
                {
                    throw new FormatException(string.Format(
                                                  "Packet {0} ({1}) from {2} length {3} has multiple messages", flags, type, remote, length
                                                  ));
                }
                else if (flags.HasFlag(PacketFlags.Timed))
                {
                    throw new FormatException(string.Format(
                                                  "Packet {0} ({1}) from {2} length {3} is timed", flags, type, remote, length
                                                  ));
                }

                // Verify CRC32
                if (flags.HasFlag(PacketFlags.Verified))
                {
                    if (packet.Count < 4)
                    {
                        throw new FormatException(string.Format(
                                                      "Packet {0} ({1}) from {2} with length {3} is too short for CRC32",
                                                      type, flags, remote, length
                                                      ));
                    }
                    else if (Config.CRC32)
                    {
                        uint computed = CRC32.Compute(packet.Array, packet.Offset + 4, packet.Count - 4);
                        uint received = Serializer.ReadUInt32(packet.Array, packet.Offset);
                        if (computed != received)
                        {
                            throw new FormatException(string.Format(
                                                          "CRC32 {0} does not match {1} in packet {2} ({3}) from {4} with length {5}",
                                                          received, computed, type, flags, remote, length
                                                          ));
                        }
                    }
                    packet = new ArraySegment <byte>(packet.Array, packet.Offset + 4, packet.Count - 4);
                }

                // Decompress
                if (flags.HasFlag(PacketFlags.Compressed))
                {
                    bufferDecompress = Allocator.CreateMessage(packet.Count);
                    int len = Compressor.Decompress(packet, ref bufferDecompress, 0);
                    packet = new ArraySegment <byte>(bufferDecompress, 0, len);
                }

                // Process packet based on type
                switch (type)
                {
                case PacketType.Request:
                    ReceiveRequest(remote, packet);
                    break;

                case PacketType.Unconnected:
                    using (Reader reader = new Reader(packet.Array, 0, packet.Count)) {
                        Listener.OnHostReceiveUnconnected(remote, reader);
                    }
                    break;

                case PacketType.Broadcast:
                    using (Reader reader = new Reader(packet.Array, 0, packet.Count)) {
                        Listener.OnHostReceiveBroadcast(remote, reader);
                    }
                    break;
                }
            } catch (Exception exception) {
                Listener.OnHostException(remote, exception);
            } finally {
                Allocator.ReturnPacket(ref buffer);
                Allocator.ReturnMessage(ref bufferDecompress);
                ReceiveSemaphore.Release();
            }
        }
Example #23
0
 public int GetSetAccessorHashCode()
 {
     return(CRC32.Compute(Encoding.UTF8.GetBytes(this + "::Set(" + Type + " value)")));
 }
Example #24
0
        public static int Crc32(string str)
        {
            Encoding unicode = Encoding.Unicode;

            return(CRC32.Compute(unicode.GetBytes(str)));
        }
Example #25
0
 public static uint GetCrc(byte[] bytes)
 {
     return(CRC32.Compute(bytes));
 }
Example #26
0
        public void ChecksumMatches(string str, uint val)
        {
            var computed = CRC32.Compute(str);

            computed.Should().Be(val);
        }
Example #27
0
 public int GetGetAccessorHashCode()
 {
     return(CRC32.Compute(Encoding.UTF8.GetBytes(this + "::Get()")));
 }
        public static void Main(string[] args)
        {
            bool         verbose       = false;
            bool         showHelp      = false;
            uint         baseRevision  = 0;
            uint         revision      = 0;
            string       deletionsPath = null;
            bool         noCrypto      = false;
            const Endian endian        = Endian.Little;

            var options = new OptionSet()
            {
                {
                    "R|baseRevision=", "specify archive base revision",
                    v => baseRevision = v == null ? 0 : uint.Parse(v)
                },
                { "r|revision=", "specify archive revision", v => revision = v == null ? 0 : uint.Parse(v) },
                { "d|deletions=", "path of deletions file", v => deletionsPath = v },
                { "no-crypto", "don't use any encryption", v => noCrypto = v != null },
                { "v|verbose", "show verbose messages", v => verbose = v != null },
                { "h|help", "show this message and exit", v => showHelp = v != null },
            };

            List <string> extras;

            try
            {
                extras = options.Parse(args);
            }
            catch (OptionException e)
            {
                Console.Write("{0}: ", GetExecutableName());
                Console.WriteLine(e.Message);
                Console.WriteLine("Try `{0} --help' for more information.", GetExecutableName());
                return;
            }

            if (extras.Count < 1 || showHelp == true)
            {
                Console.WriteLine("Usage: {0} [OPTIONS]+ output_ipf input_directory+", GetExecutableName());
                Console.WriteLine();
                Console.WriteLine("Pack files from input directories into a archive.");
                Console.WriteLine();
                Console.WriteLine("Options:");
                options.WriteOptionDescriptions(Console.Out);
                return;
            }

            var    inputPaths = new List <string>();
            string outputPath;

            if (extras.Count == 1)
            {
                inputPaths.Add(extras[0]);
                outputPath = Path.ChangeExtension(extras[0], ".ipf");
            }
            else
            {
                outputPath = Path.ChangeExtension(extras[0], ".ipf");
                inputPaths.AddRange(extras.Skip(1));
            }

            var pendingEntries = new SortedDictionary <string, PendingEntry>();

            if (verbose == true)
            {
                Console.WriteLine("Finding files...");
            }

            foreach (var relativePath in inputPaths)
            {
                string inputPath = Path.GetFullPath(relativePath);

                if (inputPath.EndsWith(Path.DirectorySeparatorChar.ToString(CultureInfo.InvariantCulture)) == true)
                {
                    inputPath = inputPath.Substring(0, inputPath.Length - 1);
                }

                foreach (string path in Directory.GetFiles(inputPath, "*", SearchOption.AllDirectories))
                {
                    string fullPath = Path.GetFullPath(path);

                    string partPath = fullPath.Substring(inputPath.Length + 1)
                                      .Replace(Path.DirectorySeparatorChar, '/')
                                      .Replace(Path.AltDirectorySeparatorChar, '/');

                    var key = partPath.ToLowerInvariant();

                    if (pendingEntries.ContainsKey(key) == true)
                    {
                        Console.WriteLine("Ignoring duplicate of {0}: {1}", partPath, fullPath);

                        if (verbose == true)
                        {
                            Console.WriteLine("  Previously added from: {0}",
                                              pendingEntries[key]);
                        }

                        continue;
                    }

                    var archiveSeparatorIndex = partPath.IndexOf('/');
                    if (archiveSeparatorIndex < 0)
                    {
                        continue;
                    }

                    var archiveName = partPath.Substring(0, archiveSeparatorIndex);
                    var fileName    = partPath.Substring(archiveSeparatorIndex + 1);

                    pendingEntries[key] = new PendingEntry(fullPath, archiveName, fileName);
                }
            }

            using (var output = File.Create(outputPath))
            {
                var fileEntries     = new List <ArchiveFileEntry>();
                var deletionEntries = new List <ArchiveDeletionEntry>();

                if (string.IsNullOrEmpty(deletionsPath) == false)
                {
                    if (verbose == true)
                    {
                        Console.WriteLine("Reading deletions...");
                    }

                    var serializer = JsonSerializer.Create();
                    using (var input = File.OpenRead(deletionsPath))
                        using (var streamReader = new StreamReader(input))
                            using (var jsonReader = new JsonTextReader(streamReader))
                            {
                                var jsonDeletionEntries = serializer.Deserialize <JsonArchiveDeletionEntry[]>(jsonReader);
                                deletionEntries.AddRange(jsonDeletionEntries.Select(jde => new ArchiveDeletionEntry()
                                {
                                    Name    = jde.Name,
                                    Archive = jde.Archive,
                                }));
                            }
                }

                if (verbose == true)
                {
                    Console.WriteLine("Writing file data...");
                }

                long current = 0;
                long total   = pendingEntries.Count;
                var  padding = total.ToString(CultureInfo.InvariantCulture).Length;

                foreach (var pendingEntry in pendingEntries.Select(kv => kv.Value))
                {
                    var fullPath    = pendingEntry.FullPath;
                    var archiveName = pendingEntry.ArchiveName;
                    var fileName    = pendingEntry.FileName;

                    current++;

                    if (verbose == true)
                    {
                        Console.WriteLine("[{0}/{1}] {2} => {3}",
                                          current.ToString(CultureInfo.InvariantCulture).PadLeft(padding),
                                          total,
                                          archiveName,
                                          fileName);
                    }

                    var bytes = File.ReadAllBytes(fullPath);

                    var fileEntry = new ArchiveFileEntry();
                    fileEntry.Name             = fileName;
                    fileEntry.Archive          = archiveName;
                    fileEntry.Hash             = CRC32.Compute(bytes, 0, bytes.Length);
                    fileEntry.UncompressedSize = (uint)bytes.Length;
                    fileEntry.Offset           = (uint)output.Position;

                    if (fileEntry.ShouldCompress == true)
                    {
                        int compressionLevel = Deflater.BEST_COMPRESSION;

                        byte[] compressedBytes;

                        using (var temp = new MemoryStream())
                        {
                            var zlib = new DeflaterOutputStream(temp, new Deflater(compressionLevel, true));
                            zlib.WriteBytes(bytes);
                            zlib.Finish();
                            temp.Flush();
                            temp.Position = 0;

                            compressedBytes = temp.ToArray();
                        }

                        if (noCrypto == false)
                        {
                            var crypto = new ArchiveCrypto();
                            crypto.Encrypt(compressedBytes, 0, compressedBytes.Length);
                        }

                        output.WriteBytes(compressedBytes);

                        fileEntry.CompressedSize = (uint)compressedBytes.Length;
                    }
                    else
                    {
                        fileEntry.CompressedSize = fileEntry.UncompressedSize;
                        output.WriteBytes(bytes);
                    }

                    fileEntries.Add(fileEntry);
                }

                if (verbose == true)
                {
                    Console.WriteLine("Writing file table...");
                }

                long fileTableOffset = output.Position;
                for (int i = 0; i < fileEntries.Count; i++)
                {
                    fileEntries[i].Write(output, endian);
                }

                if (verbose == true)
                {
                    Console.WriteLine("Writing deletion table...");
                }

                long deletionTableOffset = output.Position;
                for (int i = 0; i < deletionEntries.Count; i++)
                {
                    deletionEntries[i].Write(output, endian);
                }

                if (verbose == true)
                {
                    Console.WriteLine("Writing header...");
                }

                ArchiveHeader header;
                header.FileTableCount      = (ushort)fileEntries.Count;
                header.FileTableOffset     = (uint)fileTableOffset;
                header.DeletionTableCount  = (ushort)deletionEntries.Count;
                header.DeletionTableOffset = (uint)deletionTableOffset;
                header.Magic        = ArchiveHeader.Signature;
                header.BaseRevision = baseRevision;
                header.Revision     = revision;
                header.Write(output, endian);

                if (verbose == true)
                {
                    Console.WriteLine("Done!");
                }
            }
        }
Example #29
0
        // Métodos internos
        #region Internal
        /// <summary>
        /// Carrega informações do XML
        /// </summary>
        /// <param name="reader">Leitor XML</param>
        /// <param name="touch">Momento de criação</param>
        /// <param name="source">Fonte de dados</param>
        internal ServerInfo(XmlReader reader, int touch, IPAddress source)
        {
            // Valida entrada
            if (reader == null)
            {
                throw new ArgumentNullException(nameof(reader));
            }

            // Recupera identificador
            if (!ulong.TryParse(reader.GetAttribute("id"), out this._Id))
            {
                throw new ArgumentNullException(nameof(this._Id));
            }

            // Calcula hash da id
            this._IdHash = unchecked ((int)CRC32.Compute(this._Id));

            // Recupera nome e descrição
            this._Name        = reader.GetAttribute("name");
            this._Description = reader.GetAttribute("description");

            // Inicializa lista de serviços
            Dictionary <string, ServiceInfo> services = new Dictionary <string, ServiceInfo>();

            this._Services = new ReadOnlyDictionary <string, ServiceInfo>(services);

            // Cria lista de parâmetros extras
            Dictionary <string, string> parameters = new Dictionary <string, string>(0);

            this._Parameters = new ReadOnlyDictionary <string, string>(parameters);

            // Possui elementos?
            if (!reader.IsEmptyElement)
            {
                // Enquanto ler elementos
                while (reader.Read())
                {
                    // Verifica tipo de dado
                    switch (reader.NodeType)
                    {
                    // Elemento
                    case XmlNodeType.Element:

                        // Verifica tipo de dado
                        switch (reader.Name)
                        {
                        // Serviço
                        case "Service":

                            // Recupera informações do serviço
                            ServiceInfo service = new ServiceInfo(reader, this);

                            // Adiciona ao dicionário
                            services.Add(service.Name, service);
                            break;

                        // Outros
                        default:

                            // Inicializa chave
                            string key = reader.Name;

                            // Quantidade de fechamentos esperados
                            int findcloses = 1;

                            // Enquanto ler elementos
                            while (reader.Read())
                            {
                                // Verifica tipo de dado
                                switch (reader.NodeType)
                                {
                                // Elemento
                                case XmlNodeType.Element:
                                    key = reader.Name;
                                    findcloses++;
                                    break;

                                // Texto
                                case XmlNodeType.Text:

                                    // Mas não há chave definida?
                                    if (key == null)
                                    {
                                        throw new ArgumentNullException(nameof(key));
                                    }

                                    // Adiciona parâmetro
                                    parameters.Add(key, reader.Value);
                                    break;

                                // Fechamento de elemento
                                case XmlNodeType.EndElement:
                                    findcloses--;
                                    break;
                                }

                                // Fechou todos os elements esperados? Sai do laço
                                if (findcloses == 0)
                                {
                                    break;
                                }
                            }
                            break;
                        }
                        break;
                    }
                }
            }

            // Inicia touch
            this._Touch = touch;

            // Inicia listagem de endereços
            this._Address = new List <IPAddress>(2);
            if (source != null)
            {
                this._Address.Add(source);
            }
        }
Example #30
0
        public static string GetUriSignature(this Member member)
        {
            if (member == null)
            {
                throw new ArgumentNullException(nameof(member));
            }

            // Try to identify the master definition of this member
            if (!member.IsMasterDefinition)
            {
                do
                {
                    member = member.MasterDefinition;
                } while (!member.IsMasterDefinition);
            }

            var sb = new StringBuilder();

            if (member is Constructor)
            {
                sb.Append("_ctor");
            }
            else if (member is Method)
            {
                var method = (Method)member;

                // If the method is an explicit implementation of another method,
                // don't use the UnoName directly as it will contain something like
                // Uno.Collections.ICollection<T>.Add which is not a valid URI identifier.
                //
                // Instead, we convert those to uno_collections_icollection_1_add to follow
                // the uri patterns used elsewhere.
                if (method.ImplementedMethod != null)
                {
                    var implementedMethodTypeUri = GetUri(method.ImplementedMethod.DeclaringType).Replace("/", "_");
                    var implementedMethodUri     = GetUriSignature(method.ImplementedMethod);
                    sb.Append(implementedMethodTypeUri + "_" + implementedMethodUri);
                }
                else
                {
                    sb.Append(method.UnoName.ToLowerInvariant());
                    if (method.IsGenericDefinition && method.GenericParameters.Length > 0)
                    {
                        sb.AppendFormat("_{0}", method.GenericParameters.Length);
                    }
                }
            }
            else
            {
                sb.Append(member.UnoName.ToLowerInvariant());
            }

            if (member is ParametersMember)
            {
                var paramMember = (ParametersMember)member;
                var paramIds    = new List <string>();

                // Casts can have the same method signature (name + parameter types), but vary by return type - so in case of
                // casts, we add the return type as the first parameter type to the list in order to make the parameter checksum
                // unique for each cast.
                if (member is Cast)
                {
                    paramIds.Add(member.ReturnType.ToStringDontAlias());
                }

                foreach (var param in paramMember.Parameters)
                {
                    var paramId = param.Type.ToStringDontAlias();
                    if (param.Type.IsGenericParameter)
                    {
                        paramId = param.Type.Name;
                    }

                    paramIds.Add(paramId);
                }

                if (paramIds.Count > 0)
                {
                    var paramChecksum = CRC32.Compute(Encoding.UTF8.GetBytes(string.Join(",", paramIds)));
                    sb.AppendFormat("_{0:x8}", paramChecksum);
                }
            }

            return(sb.ToString());
        }