Пример #1
0
 public override void Write(EndianBinaryWriter er, CGFXWriterContext c)
 {
     base.Write(er, c);
     if (TextureImage != null) er.Write((uint)4);
     else er.Write((uint)0);
     if (TextureImage != null) TextureImage.Write(er, c);
 }
Пример #2
0
 private static void WriteHeader(EndianBinaryWriter writer, BmpFileHeader fileHeader)
 {
     writer.Write(fileHeader.Type);
     writer.Write(fileHeader.FileSize);
     writer.Write(fileHeader.Reserved);
     writer.Write(fileHeader.Offset);
 }
Пример #3
0
        override public void encode(EndianBinaryWriter binWriter)
        {
        
            binWriter.Write(battleId);
            
			ushort len_damageList = (ushort)damageList.Length;
			binWriter.Write(len_damageList);
            for (int i = 0; i < len_damageList; i++)
            {

            damageList[i].encode(binWriter);
            
            }
            
        }
Пример #4
0
        private void Write32bit(EndianBinaryWriter writer, IPixelAccessor pixels, int amount)
        {
            for (int y = pixels.Height - 1; y >= 0; y--){
                for (int x = 0; x < pixels.Width; x++){
                    // Convert back to b-> g-> r-> a order.
                    byte[] bytes = pixels[x, y].ToBytes();
                    writer.Write(new[]{bytes[2], bytes[1], bytes[0], bytes[3]});
                }

                // Pad
                for (int i = 0; i < amount; i++){
                    writer.Write((byte) 0);
                }
            }
        }
Пример #5
0
 public void encode(EndianBinaryWriter binWriter)
 {
 
     binWriter.Write(battleId);
     
     binWriter.Write(teamId);
     
     binWriter.Write(actorId);
     
     binWriter.Write(curX);
     
     binWriter.Write(curY);
     
     binWriter.Write(fast);
     
 }
Пример #6
0
 public void encode(EndianBinaryWriter binWriter)
 {
 
     binWriter.Write(m_ushort);
     
     binWriter.Write(m_int);
     
     binWriter.Write(m_uint);
     
     binWriter.Write(m_Boolean);
     
     binWriter.Write(m_Binary.Length);
     binWriter.Write(m_Binary);
     
     binWriter.WriteUTF(m_string);
     
 }
Пример #7
0
 public void Write(EndianBinaryWriter er)
 {
     long offpos = er.BaseStream.Position;
     //header.Write(er, 0);
     er.Write(Signature, Encoding.ASCII, false);
     er.Write((uint)0);
     dict.Write(er);
     for (int i = 0; i < models.Length; i++)
     {
         dict[i].Value.Offset = (uint)(er.BaseStream.Position - offpos);
         models[i].Write(er);
     }
     long curpos = er.BaseStream.Position;
     er.BaseStream.Position = offpos + 4;
     er.Write((UInt32)(curpos - offpos));
     dict.Write(er);
     er.BaseStream.Position = curpos;
 }
Пример #8
0
        override public void encode(EndianBinaryWriter binWriter)
        {
        
            binWriter.Write(actorId);
            
            binWriter.Write(m_byte);
            
            binWriter.WriteDate(m_date);
            
            binWriter.WriteFloat(m_float);
            
            testStruct.encode(binWriter);
            
			ushort len_playerList = (ushort)playerList.Length;
			binWriter.Write(len_playerList);
            for (int i = 0; i < len_playerList; i++)
            {

            playerList[i].encode(binWriter);
            
            }
            
        }
Пример #9
0
        public void Encode(ImageBase image, Stream stream, BmpBitsPerPixel bitsPerPixel)
        {
            if (image == null || stream == null){
                throw new ArgumentNullException();
            }
            bmpBitsPerPixel = bitsPerPixel;
            int rowWidth = image.Width;

            // TODO: Check this for varying file formats.
            int amount = (image.Width*(int) bmpBitsPerPixel)%4;
            if (amount != 0){
                rowWidth += 4 - amount;
            }

            // Do not use IDisposable pattern here as we want to preserve the stream.
            EndianBinaryWriter writer = new EndianBinaryWriter(EndianBitConverter.Little, stream);
            int bpp = (int) bmpBitsPerPixel;
            BmpFileHeader fileHeader = new BmpFileHeader{
                Type = 19778, // BM
                Offset = 54,
                FileSize = 54 + image.Height*rowWidth*bpp
            };
            BmpInfoHeader infoHeader = new BmpInfoHeader{
                HeaderSize = 40,
                Height = image.Height,
                Width = image.Width,
                BitsPerPixel = (short) (8*bpp),
                Planes = 1,
                ImageSize = image.Height*rowWidth*bpp,
                ClrUsed = 0,
                ClrImportant = 0
            };
            WriteHeader(writer, fileHeader);
            WriteInfo(writer, infoHeader);
            WriteImage(writer, image);
            writer.Flush();
        }
Пример #10
0
 public override void Write(EndianBinaryWriter er)
 {
     er.Write(Offset);
 }
Пример #11
0
 public override void Write(EndianBinaryWriter er)
 {
     base.Write(er);
     er.WriteVector3(CenterPosition);
     er.Write(OrientationMatrix, 0, 3 * 3);
     er.WriteVector3(Size);
 }
Пример #12
0
 public override void Write(EndianBinaryWriter er, CGFXWriterContext c)
 {
     base.Write(er, c);
     c.WriteStringReference(LinkedTextureName, er);
     if (LinkedTextureOffset == 0) er.Write((uint)0);
     else er.Write((uint)0);//TODO!
 }
Пример #13
0
 public virtual void Write(EndianBinaryWriter er, CGFXWriterContext c)
 {
     er.Write(Type);
     er.Write(Signature, Encoding.ASCII, false);
     er.Write(Revision);
     c.WriteStringReference(Name, er);
     er.Write(Unknown2);
     er.Write(Unknown3);
 }
Пример #14
0
 public void Write(EndianBinaryWriter er)
 {
     er.Write(vramKey);
     er.Write((UInt16)(sizeTex >> 3));
     er.Write(ofsDict);
     er.Write(flag);
     er.Write((UInt16)0);//PADDING(2 bytes);
     er.Write(ofsTex);
 }
Пример #15
0
        static void Handle(object client_obj)
        {
            string name = Thread.CurrentThread.Name;
            FileStream[] files = new FileStream[256];
            Dictionary<int, FileStream> files_request = new Dictionary<int, FileStream>();
            StreamWriter log = null;

            try
            {
                TcpClient client = (TcpClient)client_obj;
                using (NetworkStream stream = client.GetStream())
                {
                    EndianBinaryReader reader = new EndianBinaryReader(stream);
                    EndianBinaryWriter writer = new EndianBinaryWriter(stream);

                    uint[] ids = reader.ReadUInt32s(4);

                    // Log connection
                    Console.WriteLine(name + " Accepted connection from client " + client.Client.RemoteEndPoint.ToString());
                    Console.WriteLine(name + " TitleID: " + ids[0].ToString("X8") + "-" + ids[1].ToString("X8"));

                    if (!Directory.Exists(root + "\\" + ids[0].ToString("X8") + "-" + ids[1].ToString("X8")))
                    {
                        writer.Write(BYTE_NORMAL);
                        throw new Exception("Not interested.");
                    }

                    // Create log file for current thread
                    log = new StreamWriter(logs_root + "\\" + DateTime.Now.ToString("yyyy-MM-dd") + "-" + name + "-" + ids[0].ToString("X8") + "-" + ids[1].ToString("X8") + ".txt");
                    log.WriteLine(name + " Accepted connection from client " + client.Client.RemoteEndPoint.ToString());
                    log.WriteLine(name + " TitleID: " + ids[0].ToString("X8") + "-" + ids[1].ToString("X8"));

                    string LocalRoot = root + "\\" + ids[0].ToString("X8") + "-" + ids[1].ToString("X8");
                    writer.Write(BYTE_SPECIAL);

                    while (true)
                    {
                        byte cmd_byte = reader.ReadByte();
                        switch (cmd_byte)
                        {
                            case BYTE_OPEN:
                                {
                                    bool request_slow = false;

                                    int len_path = reader.ReadInt32();
                                    int len_mode = reader.ReadInt32();
                                    string path = reader.ReadString(Encoding.ASCII, len_path - 1);
                                    if (reader.ReadByte() != 0) throw new InvalidDataException();
                                    string mode = reader.ReadString(Encoding.ASCII, len_mode - 1);
                                    if (reader.ReadByte() != 0) throw new InvalidDataException();
                                    Log(log, name + " " + path);
                                    if (File.Exists(LocalRoot + path))
                                    {
                                        int handle = -1;
                                        for (int i = 0; i < files.Length; i++)
                                        {
                                            if (files[i] == null)
                                            {
                                                handle = i;
                                                break;
                                            }
                                        }
                                        if (handle == -1)
                                        {
                                            Log(log, name + " Out of file handles!");
                                            writer.Write(BYTE_SPECIAL);
                                            writer.Write(-19);
                                            writer.Write(0);
                                            break;
                                        }
                                        Log(log, name + " -> fopen(\"" + path + "\", \"" + mode + "\") = " + handle.ToString());

                                        files[handle] = new FileStream(LocalRoot + path, FileMode.Open, FileAccess.Read, FileShare.Read);

                                        writer.Write(BYTE_SPECIAL);
                                        writer.Write(0);
                                        writer.Write(0x0fff00ff | (handle << 8));

                                    }
                                    // Check for file request : filename + "-request" or + "-request_slow"
                                    else if (File.Exists(LocalRoot + path + "-request") || (request_slow = File.Exists(LocalRoot + path + "-request_slow")))
                                    {
                                        // Check if dump has already been done
                                        if (!File.Exists(LocalRoot + path + "-dump"))
                                        {
                                            // Inform cafiine that we request file to be sent
                                            writer.Write(!request_slow ? BYTE_REQUEST : BYTE_REQUEST_SLOW);
                                        }
                                        else
                                        {
                                            // Nothing to do
                                            writer.Write(BYTE_NORMAL);
                                        }
                                    }
                                    else
                                    {
                                        writer.Write(BYTE_NORMAL);
                                    }
                                    break;
                                }
                            case BYTE_HANDLE:
                                {
                                    // Read buffer params : fd, path length, path string
                                    int fd = reader.ReadInt32();
                                    int len_path = reader.ReadInt32();
                                    string path = reader.ReadString(Encoding.ASCII, len_path - 1);
                                    if (reader.ReadByte() != 0) throw new InvalidDataException();

                                    // Add new file for incoming data
                                    files_request.Add(fd, new FileStream(LocalRoot + path + "-dump", FileMode.OpenOrCreate, FileAccess.Write, FileShare.Write));

                                    // Send response
                                    writer.Write(BYTE_SPECIAL);
                                    break;
                                }
                            case BYTE_DUMP:
                                {
                                    // Read buffer params : fd, size, file data
                                    int fd = reader.ReadInt32();
                                    int sz = reader.ReadInt32();
                                    byte[] buffer = new byte[sz];
                                    buffer = reader.ReadBytes(sz);

                                    // Look for file descriptor
                                    foreach (var item in files_request)
                                    {
                                        if (item.Key == fd)
                                        {
                                            FileStream dump_file = item.Value;
                                            if (dump_file == null)
                                                break;

                                            Log(log, name + " -> dump(\"" + Path.GetFileName(dump_file.Name) + "\") " + (sz / 1024).ToString() + "kB");

                                            // Write to file
                                            dump_file.Write(buffer, 0, sz);

                                            break;
                                        }
                                    }

                                    // Send response
                                    writer.Write(BYTE_SPECIAL);
                                    break;
                                }
                            case BYTE_READ:
                                {
                                    int size = reader.ReadInt32();
                                    int count = reader.ReadInt32();
                                    int fd = reader.ReadInt32();
                                    if ((fd & 0x0fff00ff) == 0x0fff00ff)
                                    {
                                        int handle = (fd >> 8) & 0xff;
                                        if (files[handle] == null)
                                        {
                                            writer.Write(BYTE_SPECIAL);
                                            writer.Write(-19);
                                            writer.Write(0);
                                            break;
                                        }
                                        FileStream f = files[handle];

                                        byte[] buffer = new byte[size * count];
                                        int sz = f.Read(buffer, 0, buffer.Length);
                                        writer.Write(BYTE_SPECIAL);
                                        writer.Write(sz / size);
                                        writer.Write(sz);
                                        writer.Write(buffer, 0, sz);
                                        if (reader.ReadByte() != BYTE_OK)
                                            throw new InvalidDataException();
                                    }
                                    else
                                    {
                                        writer.Write(BYTE_NORMAL);
                                    }
                                    break;
                                }
                            case BYTE_CLOSE:
                                {
                                    int fd = reader.ReadInt32();
                                    if ((fd & 0x0fff00ff) == 0x0fff00ff)
                                    {
                                        int handle = (fd >> 8) & 0xff;
                                        if (files[handle] == null)
                                        {
                                            writer.Write(BYTE_SPECIAL);
                                            writer.Write(-38);
                                            break;
                                        }
                                        Log(log, name + " close(" + handle.ToString() + ")");
                                        FileStream f = files[handle];

                                        writer.Write(BYTE_SPECIAL);
                                        writer.Write(0);
                                        f.Close();
                                        files[handle] = null;
                                    }
                                    else
                                    {
                                        // Check if it is a file to dump
                                        foreach (var item in files_request)
                                        {
                                            if (item.Key == fd)
                                            {
                                                FileStream dump_file = item.Value;
                                                if (dump_file == null)
                                                    break;

                                                Log(log, name + " -> dump complete(\"" + Path.GetFileName(dump_file.Name) + "\")");

                                                // Close file and remove from request list
                                                dump_file.Close();
                                                files_request.Remove(fd);

                                                break;
                                            }
                                        }

                                        // Send response
                                        writer.Write(BYTE_NORMAL);
                                    }
                                    break;
                                }
                            case BYTE_SETPOS:
                                {
                                    int fd = reader.ReadInt32();
                                    int pos = reader.ReadInt32();
                                    if ((fd & 0x0fff00ff) == 0x0fff00ff)
                                    {
                                        int handle = (fd >> 8) & 0xff;
                                        if (files[handle] == null)
                                        {
                                            writer.Write(BYTE_SPECIAL);
                                            writer.Write(-38);
                                            break;
                                        }
                                        FileStream f = files[handle];

                                        f.Position = pos;
                                        writer.Write(BYTE_SPECIAL);
                                        writer.Write(0);
                                    }
                                    else
                                    {
                                        writer.Write(BYTE_NORMAL);
                                    }
                                    break;
                                }
                            case BYTE_STATFILE:
                                {
                                    int fd = reader.ReadInt32();
                                    if ((fd & 0x0fff00ff) == 0x0fff00ff)
                                    {
                                        int handle = (fd >> 8) & 0xff;
                                        if (files[handle] == null)
                                        {
                                            writer.Write(BYTE_SPECIAL);
                                            writer.Write(-38);
                                            writer.Write(0);
                                            break;
                                        }
                                        FileStream f = files[handle];

                                        FSStat stat = new FSStat();

                                        stat.flags = FSStatFlag.None;
                                        stat.permission = 0x400;
                                        stat.owner = ids[1];
                                        stat.group = 0x101e;
                                        stat.file_size = (uint)f.Length;

                                        writer.Write(BYTE_SPECIAL);
                                        writer.Write(0);
                                        writer.Write(Marshal.SizeOf(stat));
                                        writer.Write(stat);
                                    }
                                    else
                                    {
                                        writer.Write(BYTE_NORMAL);
                                    }
                                    break;
                                }
                            case BYTE_EOF:
                                {
                                    int fd = reader.ReadInt32();
                                    if ((fd & 0x0fff00ff) == 0x0fff00ff)
                                    {
                                        int handle = (fd >> 8) & 0xff;
                                        if (files[handle] == null)
                                        {
                                            writer.Write(BYTE_SPECIAL);
                                            writer.Write(-38);
                                            break;
                                        }
                                        FileStream f = files[handle];

                                        writer.Write(BYTE_SPECIAL);
                                        writer.Write(f.Position == f.Length ? -5 : 0);
                                    }
                                    else
                                    {
                                        writer.Write(BYTE_NORMAL);
                                    }
                                    break;
                                }
                            case BYTE_GETPOS:
                                {
                                    int fd = reader.ReadInt32();
                                    if ((fd & 0x0fff00ff) == 0x0fff00ff)
                                    {
                                        int handle = (fd >> 8) & 0xff;
                                        if (files[handle] == null)
                                        {
                                            writer.Write(BYTE_SPECIAL);
                                            writer.Write(-38);
                                            writer.Write(0);
                                            break;
                                        }
                                        FileStream f = files[handle];

                                        writer.Write(BYTE_SPECIAL);
                                        writer.Write(0);
                                        writer.Write((int)f.Position);
                                    }
                                    else
                                    {
                                        writer.Write(BYTE_NORMAL);
                                    }
                                    break;
                                }
                            case BYTE_PING:
                                {
                                    int val1 = reader.ReadInt32();
                                    int val2 = reader.ReadInt32();

                                    Log(log, name + " PING RECEIVED with values : " + val1.ToString() + " - " + val2.ToString());
                                    break;
                                }
                            default:
                                throw new InvalidDataException();
                        }
                    }
                }
            }
            catch (Exception e)
            {
                if (log != null)
                    Log(log, name + " " + e.Message);
                else
                    Console.WriteLine(name + " " + e.Message);
            }
            finally
            {
                foreach (var item in files)
                {
                    if (item != null)
                        item.Close();
                }
                foreach (var item in files_request)
                {
                    if (item.Value != null)
                        item.Value.Close();
                }

                if (log != null)
                    log.Close();
            }
            Console.WriteLine(name + " Exit");
        }
Пример #16
0
        static void Handle(object client_obj)
        {
            string name = Thread.CurrentThread.Name;
            FileStream[] files = new FileStream[256];
            Dictionary<int, FileStream> files_request = new Dictionary<int, FileStream>();
            StreamWriter log = null;
            Dictionary<string, Dictionary<string, byte>> dir_files = new Dictionary<string, Dictionary<string, byte>>();

            try
            {
                TcpClient client = (TcpClient)client_obj;
                using (NetworkStream stream = client.GetStream())
                {
                    EndianBinaryReader reader = new EndianBinaryReader(stream);
                    EndianBinaryWriter writer = new EndianBinaryWriter(stream);

                    uint[] ids = reader.ReadUInt32s(4);

                    string LocalRootDump = root + "\\" + "dump" + "\\" + ids[0].ToString("X8") + "-" + ids[1].ToString("X8") + "\\";
                   string LocalRootInject = root + "\\" + "inject" + "\\" + ids[0].ToString("X8") + "-" + ids[1].ToString("X8") + "\\";

                   if (!ids[0].ToString("X8").Equals("00050000"))
                    {
                        writer.Write(BYTE_NORMAL);
                        throw new Exception("Not interested.");
                    }
                   else
                   {
                       if (!Directory.Exists(LocalRootDump))
                       {
                           Directory.CreateDirectory(LocalRootDump);
                       }
                       if (!Directory.Exists(LocalRootInject))
                       {
                           Directory.CreateDirectory(LocalRootInject);
                       }
                   }
                   // Log connection
                   Console.WriteLine(name + " Accepted connection from client " + client.Client.RemoteEndPoint.ToString());
                   Console.WriteLine(name + " TitleID: " + ids[0].ToString("X8") + "-" + ids[1].ToString("X8"));

                    // Create log file for current thread
                    log = new StreamWriter(logs_root + "\\" + DateTime.Now.ToString("yyyy-MM-dd") + "-" + name + "-" + ids[0].ToString("X8") + "-" + ids[1].ToString("X8") + ".txt", true, Encoding.ASCII, 1024*64);
                    log.WriteLine(name + " Accepted connection from client " + client.Client.RemoteEndPoint.ToString());
                    string title_id = ids[0].ToString("X8") + "-" + ids[1].ToString("X8");
                    log.WriteLine(name + " TitleID: " + title_id);

                    writer.Write(BYTE_SPECIAL);

                    while (true)
                    {
                        //Log(log, "cmd_byte");
                        byte cmd_byte = reader.ReadByte();
                        switch (cmd_byte)
                        {
                            case BYTE_OPEN:
                                {
                                    //Log(log, "BYTE_OPEN");
                                    Boolean failed = false;

                                    int len_path = reader.ReadInt32();
                                    int len_mode = reader.ReadInt32();
                                    string path = reader.ReadString(Encoding.ASCII, len_path - 1);
                                    if (reader.ReadByte() != 0) throw new InvalidDataException();
                                    string mode = reader.ReadString(Encoding.ASCII, len_mode - 1);
                                    if (reader.ReadByte() != 0) throw new InvalidDataException();

                                    //Log(log, "old path" + path);
                                    //Log(log, "currentID: " + currentPersistentID);
                                    if (op_mode == BYTE_MODE_I)
                                        path = getRealPathCurrentInject(path, title_id);

                                    //Log(log, "new path" + path);
                                    if (path.Length == 0) failed = true;

                                    if (File.Exists(path) && !failed)
                                    {
                                        //Log(log, "path exits");
                                        int handle = -1;
                                        for (int i = 1; i < files.Length; i++)
                                        {
                                            if (files[i] == null)
                                            {
                                                handle = i;
                                                break;
                                            }
                                        }
                                        if (handle == -1)
                                        {
                                            Log(log, name + " Out of file handles!");
                                            writer.Write(BYTE_SPECIAL);
                                            writer.Write(-19);
                                            writer.Write(0);
                                            break;
                                        }
                                        //Log(log, name + " -> fopen(\"" + path + "\", \"" + mode + "\") = " + handle.ToString());

                                        files[handle] = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);

                                        writer.Write(BYTE_SPECIAL);
                                        writer.Write(0);
                                        writer.Write(handle);
                                        break;
                                    }
                                    //Log(log, "error fopen");
                                    //else on error:
                                    writer.Write(BYTE_NORMAL);

                                    break;
                                }
                            case BYTE_SETPOS:
                                {
                                    //Log(log, "BYTE_SETPOS");
                                    int fd = reader.ReadInt32();
                                    int pos = reader.ReadInt32();
                                    if ((fd & 0x0fff00ff) == 0x0fff00ff)
                                    {
                                        int handle = (fd >> 8) & 0xff;
                                        if (files[handle] == null)
                                        {
                                            writer.Write(BYTE_SPECIAL);
                                            writer.Write(-38);
                                            break;
                                        }
                                        FileStream f = files[handle];
                                        Log(log, "Postion was set to " + pos + "for handle " + handle);
                                        f.Position = pos;
                                        writer.Write(BYTE_SPECIAL);
                                        writer.Write(0);
                                    }
                                    else
                                    {
                                        writer.Write(BYTE_NORMAL);
                                    }
                                    break;
                                }
                            case BYTE_INJECTSTART:
                                {
                                    long wiiUpersistentID = (long)reader.ReadUInt32();
                                    int dumpCommon = 0;
                                    Boolean injectioncanceled = false;
                                    SaveSelectorDialog ofd = new SaveSelectorDialog(title_id, wiiUpersistentID);
                                    try
                                    {
                                        DialogResult result = ofd.ShowDialog();
                                        if (result == System.Windows.Forms.DialogResult.OK)
                                        {
                                            currentPersistentID = ofd.NewPersistentID;
                                            dumpCommon = ofd.DumpCommon;
                                            //Console.WriteLine("Injecting " + currentPersistentID.ToString() + " into " + wiiUpersistentID.ToString() + " for title id " + title_id);
                                            if (dumpCommon == 1) Console.WriteLine("clean and inject common folder");
                                            if (dumpCommon == 2) Console.WriteLine("inject common folder");
                                            if (dumpCommon > 0 && currentPersistentID == 0) currentPersistentID = COMMON_PERSISTENTID;
                                        }
                                        else
                                        {
                                            Console.WriteLine("Injection canceled");
                                            injectioncanceled = true;
                                        }
                                    }
                                    catch (Exception e)
                                    {
                                        Console.WriteLine("Injection canceled");
                                        injectioncanceled = true;
                                    }
                                    if (injectioncanceled)
                                    {
                                        writer.Write(BYTE_NORMAL);
                                    }
                                    else
                                    {
                                        writer.Write(BYTE_SPECIAL);
                                    }
                                    int dumpmask = MASK_NORMAL;
                                    if (currentPersistentID != 0 && currentPersistentID != COMMON_PERSISTENTID)
                                        dumpmask |= MASK_USER;

                                    if (dumpCommon >= 1) {
                                        dumpmask |= MASK_COMMON;
                                      if(dumpCommon == 2)
                                        dumpmask |= MASK_COMMON_CLEAN;
                                    }
                                    writer.Write(dumpmask);
                                    writer.Write(BYTE_SPECIAL);

                                    break;
                                }
                            case BYTE_INJECTEND:
                                {
                                    currentPersistentID = 0;
                                    //close all opened files
                                    for (int i = 1; i < files.Length; i++)
                                    {
                                        if (files[i] != null)
                                        {
                                            files[i].Close();
                                            files[i] = null;
                                        }
                                    }
                                    writer.Write(BYTE_OK);
                                    //Console.WriteLine("InjectionEND");

                                    break;
                                }
                            case BYTE_DUMPSTART:
                                {
                                    long wiiUpersistentID = (long)reader.ReadUInt32();
                                    Boolean dumpCommon = false;
                                    Boolean dumpUser = false;
                                    currentPersistentID = wiiUpersistentID;

                                    Boolean dumpcanceled = false;
                                    DumpDialog ofd = new DumpDialog(title_id, wiiUpersistentID);
                                    try
                                    {
                                        DialogResult result = ofd.ShowDialog();
                                        if (result == System.Windows.Forms.DialogResult.OK)
                                        {
                                            dumpUser = ofd.DumpUser;
                                            dumpCommon = ofd.DumpCommon;
                                            //Console.WriteLine("Injecting " + currentPersistentID.ToString() + " into " + wiiUpersistentID.ToString() + " for title id " + title_id);
                                            if (dumpCommon) Console.WriteLine("dumping common data");
                                            if (dumpUser) Console.WriteLine("dumping user data");
                                        }
                                        else
                                        {
                                            Console.WriteLine("dump canceled");
                                            dumpcanceled = true;
                                        }
                                    }
                                    catch (Exception e)
                                    {
                                        Console.WriteLine("dump canceled");
                                        dumpcanceled = true;
                                    }
                                    if (dumpcanceled)
                                    {
                                        writer.Write(BYTE_NORMAL);
                                    }
                                    else
                                    {
                                        writer.Write(BYTE_SPECIAL);
                                    }

                                    int dumpmask = MASK_NORMAL;
                                    if (dumpUser)
                                        dumpmask |= MASK_USER;

                                    if (dumpCommon)
                                    {
                                        dumpmask |= MASK_COMMON;
                                    }
                                    writer.Write(dumpmask);
                                    writer.Write(BYTE_SPECIAL);

                                    break;
                                }
                            case BYTE_DUMPEND:
                                {
                                    currentPersistentID = 0;
                                    //close all opened files
                                    for (int i = 1; i < files.Length; i++)
                                    {
                                        if (files[i] != null)
                                        {
                                            files[i].Close();
                                            files[i] = null;
                                        }
                                    }
                                    writer.Write(BYTE_OK);
                                    //Console.WriteLine("dumpEND");

                                    break;
                                }
                            case BYTE_READ_DIR:
                                {
                                    Boolean failed = false;
                                    int len_path = reader.ReadInt32();
                                    string path = reader.ReadString(Encoding.ASCII, len_path-1);
                                    if (reader.ReadByte() != 0) throw new InvalidDataException();
                                    int x = 0;
                                    //Console.WriteLine("old" + path);
                                    if(op_mode == BYTE_MODE_I)
                                        path = getRealPathCurrentInject(path, title_id);
                                    //Console.WriteLine("new" + path);
                                    if(path.Length == 0)failed = true;

                                    if (Directory.Exists(path) && !failed)
                                    {
                                        x = countDirectory(path);
                                        if (x > 0)
                                        {
                                            Dictionary<string, byte> value;
                                            if (!dir_files.TryGetValue(path, out value))
                                            {
                                                //Console.Write("found no \"" + path + "\" in dic \n");
                                                value = new Dictionary<string, byte>();
                                                string[] fileEntries = Directory.GetFiles(path);
                                                foreach (string fn in fileEntries)
                                                {
                                                    string fileName = Path.GetFileName(fn);
                                                    value.Add(fileName, BYTE_FILE);
                                                }
                                                string[] subdirectoryEntries = Directory.GetDirectories(path);
                                                foreach (string sd in subdirectoryEntries)
                                                {
                                                    string subdirectory = Path.GetFileName(sd);
                                                    value.Add(subdirectory, BYTE_FOLDER);
                                                }
                                                dir_files.Add(path, value);
                                                //Console.Write("added \"" + path + "\" to dic \n");
                                            }
                                            else
                                            {
                                                //Console.Write("dic for \"" + path + "\" ready \n");
                                            }

                                            if (value.Count > 0)
                                            {
                                                writer.Write(BYTE_OK);
                                                //Console.Write("sent ok byte \n");
                                                foreach (var item in value)
                                                { //Write
                                                    writer.Write(item.Value);
                                                    //Console.Write("type : " + item.Value);
                                                    writer.Write(item.Key.Length);
                                                    //Console.Write("length : " + item.Key.Length);
                                                    writer.Write(item.Key, Encoding.ASCII, true);
                                                    //Console.Write("filename : " + item.Key);
                                                    int length = 0;
                                                    if (item.Value == BYTE_FILE) length = (int)new System.IO.FileInfo(path + "/" + item.Key).Length;
                                                    writer.Write(length);
                                                    //Console.Write("filesize : " + length + " \n");
                                                    value.Remove(item.Key);
                                                    //Console.Write("removed from list! " + value.Count + " remaining\n");
                                                    break;
                                                }
                                                writer.Write(BYTE_SPECIAL); //
                                                //Console.Write("file sent, wrote special byte \n");
                                                break;
                                            }
                                            else
                                            {

                                                dir_files.Remove(path);
                                                //Console.Write("removed \"" + path + "\" from dic \n");
                                            }
                                        }
                                    }
                                    writer.Write(BYTE_END); //
                                    //Console.Write("list was empty return BYTE_END \n");

                                    //Console.Write("in break \n");
                                    break;
                                }
                            case BYTE_READ:
                                {
                                    //Log(log,"BYTE_READ");
                                    int size = reader.ReadInt32();
                                    int fd = reader.ReadInt32();

                                    FileStream f = files[fd];

                                    byte[] buffer = new byte[size];
                                    int sz = (int)f.Length;
                                    int rd = 0;

                                    //Log(log, "want size:" + size + " for handle: " + fd);

                                    writer.Write(BYTE_SPECIAL);

                                    rd = f.Read(buffer, 0, buffer.Length);
                                    //Log(log,"rd:" + rd);
                                    writer.Write(rd);
                                    writer.Write(buffer, 0, rd);

                                    int offset = (int)f.Position;
                                    int progress = (int)(((float)offset / (float)sz) * 100);
                                    string strProgress = progress.ToString().PadLeft(3, ' ');
                                    string strSize = (sz / 1024).ToString();
                                    string strCurrent = (offset / 1024).ToString().PadLeft(strSize.Length, ' ');
                                    Console.Write("\r\t--> {0}% ({1} kB / {2} kB)", strProgress, strCurrent, strSize);

                                    //Console.Write("send " + rd );
                                    if (offset == sz)
                                    {
                                        Console.Write("\n");
                                        log.Write("\r\t--> {0}% ({1} kB / {2} kB)\n", strProgress, strCurrent, strSize);
                                    }
                                    int ret = -5;
                                    if ((ret =reader.ReadByte()) != BYTE_OK)
                                    {
                                        Console.Write("error, got " + ret + " instead of " + BYTE_OK);
                                        //throw new InvalidDataException();
                                    }

                                    //Log(log, "break READ");

                                    break;
                                }
                            case BYTE_HANDLE:
                                {
                                    //Log(log,"BYTE_HANDLE");
                                    // Read buffer params : fd, path length, path string
                                    int fd = reader.ReadInt32();
                                    int len_path = reader.ReadInt32();
                                    string path = reader.ReadString(Encoding.ASCII, len_path - 1);
                                    if (reader.ReadByte() != 0) throw new InvalidDataException();
                                    //Console.WriteLine("old " + path);
                                    if (op_mode == BYTE_MODE_D)
                                        path = getRealPathCurrentDump(path, title_id);
                                    //Console.WriteLine("new " + path);

                                    if (path.Length == 0)
                                    {
                                        writer.Write(BYTE_SPECIAL);
                                        break;
                                    }

                                    if (!Directory.Exists(path))
                                    {
                                        Directory.CreateDirectory(Path.GetDirectoryName(path));
                                    }

                                    // Add new file for incoming data
                                    files_request.Add(fd, new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Write));
                                    // Send response
                                    if (fastmode) {
                                        writer.Write(BYTE_REQUEST);
                                    }
                                    else
                                    {
                                        writer.Write(BYTE_REQUEST_SLOW);
                                    }
                                    LogNoLine(log, "-> [");
                                    // Send response
                                    writer.Write(BYTE_SPECIAL);
                                    break;
                                }
                            case BYTE_DUMP:
                                {
                                    //Log(log,"BYTE_DUMP");
                                    // Read buffer params : fd, size, file data
                                    int fd = reader.ReadInt32();
                                    int sz = reader.ReadInt32();
                                    byte[] buffer = new byte[sz];
                                    buffer = reader.ReadBytes(sz);

                                    // Look for file descriptor
                                    foreach (var item in files_request)
                                    {
                                        if (item.Key == fd)
                                        {
                                            FileStream dump_file = item.Value;
                                            if (dump_file == null)
                                                break;

                                            LogNoLine(log, ".");

                                            // Write to file
                                            dump_file.Write(buffer, 0, sz);

                                            break;
                                        }
                                    }
                                    // Send response
                                    writer.Write(BYTE_SPECIAL);
                                    break;
                                }
                            case BYTE_CLOSE:
                                {
                                    //Log(log, "BYTE_CLOSE");
                                    int fd = reader.ReadInt32();

                                    if (files[fd] == null)
                                    {
                                        writer.Write(BYTE_SPECIAL);
                                        writer.Write(-38);
                                        break;
                                    }
                                    //Log(log, name + " close(" + fd.ToString() + ")");
                                    FileStream f = files[fd];

                                    writer.Write(BYTE_SPECIAL);
                                    writer.Write(0);
                                    f.Close();
                                    files[fd] = null;

                                    break;
                                }
                            case BYTE_CLOSE_DUMP:
                                {
                                    int fd = reader.ReadInt32();
                                    if ((fd & 0x0fff00ff) != 0x0fff00ff)
                                    {
                                        // Check if it is a file to dump
                                        foreach (var item in files_request)
                                        {
                                            if (item.Key == fd)
                                            {
                                                FileStream dump_file = item.Value;
                                                if (dump_file == null)
                                                    break;

                                                LogNoLine(log,"]");
                                                Log(log, "");
                                                // Close file and remove from request list
                                                dump_file.Close();
                                                files_request.Remove(fd);
                                                break;
                                            }
                                        }

                                        // Send response
                                        writer.Write(BYTE_NORMAL);
                                    }
                                    break;
                                }
                            case BYTE_PING:
                                {
                                    //Log(log, "BYTE_PING");
                                    int val1 = reader.ReadInt32();
                                    int val2 = reader.ReadInt32();

                                    Log(log, name + " PING RECEIVED with values : " + val1.ToString() + " - " + val2.ToString());
                                    break;
                                }
                            case BYTE_G_MODE:
                                {
                                    if (op_mode == BYTE_MODE_D)
                                    {
                                        writer.Write(BYTE_MODE_D);
                                    }
                                    else if (op_mode == BYTE_MODE_I)
                                    {
                                        writer.Write(BYTE_MODE_I);
                                    }
                                    break;
                                }

                            case BYTE_LOG_STR:
                                {
                                    //Log(log, "BYTE_LOG_STR");
                                    int len_str = reader.ReadInt32();
                                    string str = reader.ReadString(Encoding.ASCII, len_str - 1);
                                    if (reader.ReadByte() != 0) throw new InvalidDataException();

                                    Log(log,"-> " + str);
                                    break;
                                }
                            default:
                                Log(log, "xx" + cmd_byte);
                                throw new InvalidDataException();
                        }
                    }
                }
            }
            catch (Exception e)
            {
                if (log != null)
                    Log(log, name + " " + e.Message);
                else
                    Console.WriteLine(name + " " + e.Message);
            }
            finally
            {
                foreach (var item in files)
                {
                    if (item != null)
                        item.Close();
                }
                foreach (var item in files_request)
                {
                    if (item.Value != null)
                        item.Value.Close();
                }

                if (log != null)
                    log.Close();
            }
            Console.WriteLine(name + " Exit");
        }
Пример #17
0
 public override void Write(EndianBinaryWriter er)
 {
     er.Write((ushort)(offset >> 3));
     er.Write(flag);
 }
Пример #18
0
        /**
         * "Move" the packet data out of the buffer we're sitting on and into
         * buf at the current position.
         */
        void MovePacket( EndianBinaryWriter buf )
        {
            Log.v ( "ddms", "moving " + Length + " bytes" );
            int oldPosn = (int)Buffer.BaseStream.Position;
            Buffer.BaseStream.Position = 0;

            byte[] tdata = new byte[oldPosn];
            byte[] fdata = ( Buffer.BaseStream as MemoryStream ).ToArray ( );
            for ( int i = 0; i < tdata.Length; i++ ) {
                tdata[i] = fdata[i];
            }

            buf.Write ( tdata );
            Buffer.BaseStream.Position = Length;
        }
Пример #19
0
        static void Handle(object client_obj)
        {
            string name = Thread.CurrentThread.Name;
            StreamWriter log = null;

            try
            {
                TcpClient client = (TcpClient)client_obj;
                using (NetworkStream stream = client.GetStream())
                {
                    EndianBinaryReader reader = new EndianBinaryReader(stream);
                    EndianBinaryWriter writer = new EndianBinaryWriter(stream);

                    uint[] ids = reader.ReadUInt32s(4);

                    // Log connection
                    Console.WriteLine(name + " Accepted connection from client " + client.Client.RemoteEndPoint.ToString());
                    Console.WriteLine(name + " TitleID: " + ids[0].ToString("X8") + "-" + ids[1].ToString("X8"));

                    // Create log file for current thread
                    log = new StreamWriter(logs_root + "\\" + DateTime.Now.ToString("yyyy-MM-dd") + "-" + name + "-" + ids[0].ToString("X8") + "-" + ids[1].ToString("X8") + ".txt");
                    log.WriteLine(name + " Accepted connection from client " + client.Client.RemoteEndPoint.ToString());
                    log.WriteLine(name + " TitleID: " + ids[0].ToString("X8") + "-" + ids[1].ToString("X8"));

                    writer.Write(BYTE_SPECIAL);

                    while (true)
                    {
                        byte cmd_byte = reader.ReadByte();
                        switch (cmd_byte)
                        {
                            case BYTE_OPEN_FILE:
                            case BYTE_OPEN_FILE_ASYNC:
                                {
                                    int len_path = reader.ReadInt32();
                                    int len_mode = reader.ReadInt32();
                                    string path = reader.ReadString(Encoding.ASCII, len_path - 1);
                                    if (reader.ReadByte() != 0) throw new InvalidDataException();
                                    string mode = reader.ReadString(Encoding.ASCII, len_mode - 1);
                                    if (reader.ReadByte() != 0) throw new InvalidDataException();

                                    if (cmd_byte == BYTE_OPEN_FILE)
                                        Log(log, name + " FSOpenFile(\"" + path + "\", \"" + mode + "\")");
                                    else
                                        Log(log, name + " FSOpenFileAsync(\"" + path + "\", \"" + mode + "\")");

                                    break;
                                }
                            case BYTE_READ_FILE:
                            case BYTE_READ_FILE_ASYNC:
                                {
                                    int size = reader.ReadInt32();
                                    int count = reader.ReadInt32();
                                    int fd = reader.ReadInt32();

                                    if (cmd_byte == BYTE_READ_FILE)
                                        Log(log, name + " FSReadFile(size=" + size.ToString() + ", count=" + count.ToString() + ", fd=" + fd.ToString() + ")");
                                    else
                                        Log(log, name + " FSReadFileAsync(size=" + size.ToString() + ", count=" + count.ToString() + ", fd=" + fd.ToString() + ")");

                                    break;
                                }
                            case BYTE_CLOSE_FILE:
                            case BYTE_CLOSE_FILE_ASYNC:
                                {
                                    int fd = reader.ReadInt32();

                                    if (cmd_byte == BYTE_CLOSE_FILE)
                                        Log(log, name + " FSCloseFile(" + fd.ToString() + ")");
                                    else
                                        Log(log, name + " FSCloseFileAsync(" + fd.ToString() + ")");

                                    break;
                                }
                            case BYTE_SETPOS:
                                {
                                    int fd = reader.ReadInt32();
                                    int pos = reader.ReadInt32();

                                    Log(log, name + " FSSetPos(fd=" + fd.ToString() + ", pos=" + pos.ToString() + ")");

                                    break;
                                }
                            case BYTE_STATFILE:
                                {
                                    int fd = reader.ReadInt32();
                                    Log(log, name + " FSGetStatFile(" + fd.ToString() + ")");

                                    break;
                                }
                            case BYTE_OPEN_DIR:
                            case BYTE_OPEN_DIR_ASYNC:
                                {
                                    int len_path = reader.ReadInt32();
                                    string path = reader.ReadString(Encoding.ASCII, len_path - 1);
                                    if (reader.ReadByte() != 0) throw new InvalidDataException();

                                    if (cmd_byte == BYTE_OPEN_DIR)
                                        Log(log, name + " FSOpenDir(\"" + path + "\")");
                                    else
                                        Log(log, name + " FSOpenDirAsync(\"" + path + "\")");

                                    break;
                                }
                            case BYTE_READ_DIR:
                            case BYTE_READ_DIR_ASYNC:
                                {
                                    int fd = reader.ReadInt32();

                                    if (cmd_byte == BYTE_READ_DIR)
                                        Log(log, name + " FSReadDir(fd=" + fd.ToString() + ")");
                                    else
                                        Log(log, name + " FSReadDirAsync(fd=" + fd.ToString() + ")");

                                    break;
                                }
                            case BYTE_CLOSE_DIR:
                            case BYTE_CLOSE_DIR_ASYNC:
                                {
                                    int fd = reader.ReadInt32();

                                    if (cmd_byte == BYTE_CLOSE_DIR)
                                        Log(log, name + " FSCloseDir(" + fd.ToString() + ")");
                                    else
                                        Log(log, name + " FSCloseDirAsync(" + fd.ToString() + ")");

                                    break;
                                }
                            case BYTE_CHANGE_DIR:
                            case BYTE_CHANGE_DIR_ASYNC:
                                {
                                    int len_path = reader.ReadInt32();
                                    string path = reader.ReadString(Encoding.ASCII, len_path - 1);
                                    if (reader.ReadByte() != 0) throw new InvalidDataException();

                                    Log(log, name + " FSChangeDir(\"" + path + "\")");

                                    break;
                                }
                            case BYTE_GET_CWD:
                                {
                                    Log(log, name + " FSGetCwd()");

                                    break;
                                }
                            case BYTE_STAT:
                            case BYTE_STAT_ASYNC:
                                {
                                    int len_path = reader.ReadInt32();
                                    string path = reader.ReadString(Encoding.ASCII, len_path - 1);
                                    if (reader.ReadByte() != 0) throw new InvalidDataException();

                                    Log(log, name + " FSGetStat(\"" + path + "\")");
                                    break;
                                }
                            case BYTE_EOF:
                                {
                                    int fd = reader.ReadInt32();
                                    Log(log, name + " FSGetEof(" + fd.ToString() + ")");
                                    break;
                                }
                            case BYTE_GETPOS:
                                {
                                    int fd = reader.ReadInt32();
                                    Log(log, name + " FSGetPos(" + fd.ToString() + ")");
                                    break;
                                }
                            case BYTE_MOUNT_SD:
                                {
                                    Log(log, name + " Trying to mount SD card");
                                    break;
                                }
                            case BYTE_MOUNT_SD_OK:
                                {
                                    Log(log, name + " SD card mounted !");
                                    break;
                                }
                            case BYTE_MOUNT_SD_BAD:
                                {
                                    Log(log, name + " Can't mount SD card");
                                    break;
                                }
                            case BYTE_PING:
                                {
                                    int val1 = reader.ReadInt32();
                                    int val2 = reader.ReadInt32();

                                    Log(log, name + " PING RECEIVED with values : " + val1.ToString() + " - " + val2.ToString());
                                    break;
                                }
                            case BYTE_LOG_STR:
                                {
                                    int len_str = reader.ReadInt32();
                                    string str = reader.ReadString(Encoding.ASCII, len_str - 1);
                                    if (reader.ReadByte() != 0) throw new InvalidDataException();

                                    Log(log, name + " LogString =>(\"" + str + "\")");
                                    break;
                                }
                            default:
                                throw new InvalidDataException();
                        }
                    }
                }
            }
            catch (Exception e)
            {
                if (log != null)
                    Log(log, name + " " + e.Message);
                else
                    Console.WriteLine(name + " " + e.Message);
            }
            finally
            {
                if (log != null)
                    log.Close();
            }
            Console.WriteLine(name + " Exit");
        }
Пример #20
0
        /// <summary>
        /// Finish a packet created with newPacket().
        /// This always creates a command packet, with the next serial number
        /// in sequence.
        /// We have to take "payloadLength" as an argument because we can't
        /// see the position in the "slice" returned by getPayload().  We could
        /// fish it out of the chunk header, but it's legal for there to be
        /// more than one chunk in a JDWP packet.
        /// On exit, "position" points to the end of the data.		
        /// </summary>
        /// <param name="payloadLength">Length of the payload.</param>
        void finishPacket( int payloadLength )
        {
            System.Diagnostics.Debug.Assert ( IsNew );

            if ( ChunkHandler.CHUNK_ORDER == ChunkHandler.ByteOrder.LittleEndian ) {
                if ( Buffer.BitConverter != EndianBitConverter.Little ) {
                    Buffer = new EndianBinaryWriter ( EndianBitConverter.Little, Buffer.BaseStream );
                }
            }

            Length = JDWP_HEADER_LEN + payloadLength;
            ID = GetNextSerial ( );
            Flags = 0;
            CommandSet = DDMS_CMD_SET;
            Command = DDMS_CMD;

            Buffer.Write ( Length );
            Buffer.Write ( ID );
            Buffer.Write ( Flags );
            Buffer.Write ( CommandSet );
            Buffer.Write ( Command );

            if ( oldOrder == EndianBitConverter.Little ) {
                if ( Buffer.BitConverter != EndianBitConverter.Little ) {
                    Buffer = new EndianBinaryWriter ( EndianBitConverter.Little, Buffer.BaseStream );
                }
            } else {
                if ( Buffer.BitConverter != EndianBitConverter.Big ) {
                    Buffer = new EndianBinaryWriter ( EndianBitConverter.Big, Buffer.BaseStream );
                }
            }

            // move to end
            Buffer.BaseStream.Position = Length;
        }
Пример #21
0
        public static ByamlNode FromXml(XmlDocument doc, XmlNode xmlNode, List<string> nodes, List<string> values, List<string> data)
        {
            XmlNode child = xmlNode.FirstChild;
            while (child != null && child.NodeType == XmlNodeType.Comment)
                child = child.NextSibling;

            if (child == null || child.NodeType == XmlNodeType.Element)
            {
                if (xmlNode.Attributes["type"] != null && xmlNode.Attributes["type"].Value == "array")
                {
                    UnamedNode node = new UnamedNode();
                    foreach (XmlNode item in xmlNode.ChildNodes)
                        if (item.NodeType == XmlNodeType.Element)
                            node.Nodes.Add(FromXml(doc, item, nodes, values, data));
                    return node;
                }
                else if (xmlNode.Attributes["type"] != null && xmlNode.Attributes["type"].Value == "path")
                {
                    string value;
                    using (MemoryStream ms = new MemoryStream())
                    {
                        using (EndianBinaryWriter wr = new EndianBinaryWriter(ms))
                        {
                            foreach (XmlNode item in xmlNode.ChildNodes)
                            {
                                if (item.NodeType == XmlNodeType.Element && string.Equals(item.Name, "point", StringComparison.OrdinalIgnoreCase))
                                {
                                    wr.Write(float.Parse(item.Attributes["x"].Value.Remove(item.Attributes["x"].Value.Length - 1), CultureInfo.InvariantCulture));
                                    wr.Write(float.Parse(item.Attributes["y"].Value.Remove(item.Attributes["y"].Value.Length - 1), CultureInfo.InvariantCulture));
                                    wr.Write(float.Parse(item.Attributes["z"].Value.Remove(item.Attributes["z"].Value.Length - 1), CultureInfo.InvariantCulture));
                                    wr.Write(float.Parse(item.Attributes["nx"].Value.Remove(item.Attributes["nx"].Value.Length - 1), CultureInfo.InvariantCulture));
                                    wr.Write(float.Parse(item.Attributes["ny"].Value.Remove(item.Attributes["ny"].Value.Length - 1), CultureInfo.InvariantCulture));
                                    wr.Write(float.Parse(item.Attributes["nz"].Value.Remove(item.Attributes["nz"].Value.Length - 1), CultureInfo.InvariantCulture));
                                    wr.Write(int.Parse(item.Attributes["val"].Value, CultureInfo.InvariantCulture));
                                }
                            }
                        }
                        value = Convert.ToBase64String(ms.ToArray());
                    }
                    if (!data.Contains(value))
                        data.Add(value);
                    return new Data(data.IndexOf(value));
                }
                else
                {
                    NamedNode node = new NamedNode();
                    foreach (XmlNode item in xmlNode.ChildNodes)
                    {
                        if (item.NodeType == XmlNodeType.Element)
                        {
                            if (!nodes.Contains(item.Name))
                                nodes.Add(item.Name);
                            node.Nodes.Add(new KeyValuePair<int, ByamlNode>(nodes.IndexOf(item.Name), FromXml(doc, item, nodes, values, data)));
                        }
                    }
                    foreach (XmlAttribute item in xmlNode.Attributes)
                    {
                        if (!nodes.Contains(item.Name))
                            nodes.Add(item.Name);
                        node.Nodes.Add(new KeyValuePair<int, ByamlNode>(nodes.IndexOf(item.Name), FromXml(doc, item, nodes, values, data)));
                    }
                    return node;
                }
            }
            else
            {
                if (xmlNode.Attributes != null && xmlNode.Attributes["type"] != null)
                {
                    if (xmlNode.Attributes["type"].Value == "string")
                    {
                        if (!values.Contains(xmlNode.InnerText))
                            values.Add(xmlNode.InnerText);
                        return new String(values.IndexOf(xmlNode.InnerText));
                    }
                }

                int value_int;
                bool value_bool;

                if (xmlNode.InnerText.EndsWith("f", StringComparison.OrdinalIgnoreCase))
                    return new Single(float.Parse(xmlNode.InnerText.Remove(xmlNode.InnerText.Length - 1), CultureInfo.InvariantCulture));
                else if (int.TryParse(xmlNode.InnerText, out value_int))
                    return new Int(value_int);
                else if (bool.TryParse(xmlNode.InnerText, out value_bool))
                    return new Boolean(value_bool);
                else
                    throw new InvalidDataException();
            }
        }
Пример #22
0
        private static void ConvertToByaml(EndianBinaryReader reader, string outpath)
        {
            XmlDocument doc = new XmlDocument();
            doc.Load(reader.BaseStream);

            if (doc.LastChild.Name != "yaml")
                throw new InvalidDataException();

            List<string> nodes = new List<string>();
            List<string> values = new List<string>();
            List<string> data = new List<string>();

            ByamlNode tree = ByamlNode.FromXml(doc, doc.LastChild, nodes, values, data);

            List<ByamlNode> flat = new List<ByamlNode>();
            Stack<ByamlNode> process = new Stack<ByamlNode>();

            List<string> sorted_nodes = new List<string>();
            sorted_nodes.AddRange(nodes);
            sorted_nodes.Sort(StringComparer.Ordinal);
            List<string> sorted_values = new List<string>();
            sorted_values.AddRange(values);
            sorted_values.Sort(StringComparer.Ordinal);

            process.Push(tree);
            while (process.Count > 0)
            {
                ByamlNode current = process.Pop();
                flat.Add(current);

                if (current.GetType() == typeof(ByamlNode.NamedNode))
                {
                    ByamlNode.NamedNode cur = current as ByamlNode.NamedNode;
                    SortedDictionary<int, ByamlNode> dict = new SortedDictionary<int, ByamlNode>();
                    Stack<ByamlNode> reverse = new Stack<ByamlNode>();
                    foreach (var item in cur.Nodes)
                    {
                        dict.Add(sorted_nodes.IndexOf(nodes[item.Key]), item.Value);
                        reverse.Push(item.Value);
                    }
                    while (reverse.Count > 0)
                        process.Push(reverse.Pop());
                    cur.Nodes.Clear();
                    foreach (var item in dict)
                        cur.Nodes.Add(item);
                }
                else if (current.GetType() == typeof(ByamlNode.UnamedNode))
                {
                    Stack<ByamlNode> reverse = new Stack<ByamlNode>();
                    foreach (var item in (current as ByamlNode.UnamedNode).Nodes)
                    {
                        reverse.Push(item);
                    }
                    while (reverse.Count > 0)
                        process.Push(reverse.Pop());
                }
                else if (current.GetType() == typeof(ByamlNode.String))
                {
                    ByamlNode.String cur = current as ByamlNode.String;

                    cur.Value = sorted_values.IndexOf(values[cur.Value]);
                }
            }

            using (EndianBinaryWriter writer = new EndianBinaryWriter(new FileStream(outpath, FileMode.Create)))
            {
                uint[] off = new uint[4];

                for (int i = 0; i < 2; i++)
                {
                    writer.BaseStream.Position = 0;

                    writer.Write(0x42590001);
                    writer.Write(off, 0, 4);

                    if (sorted_nodes.Count > 0)
                    {
                        off[0] = (uint)writer.BaseStream.Position;

                        int len = 8 + 4 * sorted_nodes.Count;
                        writer.Write(sorted_nodes.Count | ((int)ByamlNodeType.StringList << 24));
                        foreach (var item in sorted_nodes)
                        {
                            writer.Write(len);
                            len += item.Length + 1;
                        }
                        writer.Write(len);
                        foreach (var item in sorted_nodes)
                            writer.Write(item, Encoding.ASCII, true);
                        writer.WritePadding(4, 0);
                    }
                    else
                        off[0] = 0;

                    if (sorted_values.Count > 0)
                    {
                        off[1] = (uint)writer.BaseStream.Position;

                        int len = 8 + 4 * sorted_values.Count;
                        writer.Write(sorted_values.Count | ((int)ByamlNodeType.StringList << 24));
                        foreach (var item in sorted_values)
                        {
                            writer.Write(len);
                            len += item.Length + 1;
                        }
                        writer.Write(len);
                        foreach (var item in sorted_values)
                            writer.Write(item, Encoding.ASCII, true);
                        writer.WritePadding(4, 0);
                    }
                    else
                        off[1] = 0;

                    if (data.Count > 0)
                    {
                        off[2] = (uint)writer.BaseStream.Position;

                        int len = 8 + 4 * data.Count;
                        writer.Write(data.Count | ((int)ByamlNodeType.BinaryDataList << 24));
                        foreach (var item in data)
                        {
                            byte[] val = Convert.FromBase64String(item);
                            writer.Write(len);
                            len += val.Length;
                        }
                        writer.Write(len);
                        foreach (var item in data)
                        {
                            byte[] val = Convert.FromBase64String(item);
                            writer.Write(val, 0, val.Length);
                        }
                        writer.WritePadding(4, 0);
                    }
                    else
                        off[2] = 0;

                    off[3] = (uint)writer.BaseStream.Position;

                    foreach (var current in flat)
                    {
                        current.Address = writer.BaseStream.Position;
                        if (current.GetType() == typeof(ByamlNode.NamedNode))
                        {
                            ByamlNode.NamedNode cur = current as ByamlNode.NamedNode;
                            writer.Write(cur.Nodes.Count | ((int)cur.Type << 24));
                            foreach (var item in cur.Nodes)
                            {
                                writer.Write(((int)item.Value.Type) | (item.Key << 8));
                                switch (item.Value.Type)
                                {
                                    case ByamlNodeType.String:
                                        writer.Write((item.Value as ByamlNode.String).Value);
                                        break;
                                    case ByamlNodeType.Data:
                                        writer.Write((item.Value as ByamlNode.Data).Value);
                                        break;
                                    case ByamlNodeType.Boolean:
                                        writer.Write((item.Value as ByamlNode.Boolean).Value ? 1 : 0);
                                        break;
                                    case ByamlNodeType.Int:
                                        writer.Write((item.Value as ByamlNode.Int).Value);
                                        break;
                                    case ByamlNodeType.Single:
                                        writer.Write((item.Value as ByamlNode.Single).Value);
                                        break;
                                    case ByamlNodeType.UnamedNode:
                                    case ByamlNodeType.NamedNode:
                                        writer.Write((int)item.Value.Address);
                                        break;
                                    default:
                                        throw new NotImplementedException();
                                }
                            }
                        }
                        else if (current.GetType() == typeof(ByamlNode.UnamedNode))
                        {
                            ByamlNode.UnamedNode cur = current as ByamlNode.UnamedNode;
                            writer.Write(cur.Nodes.Count | ((int)cur.Type << 24));
                            foreach (var item in cur.Nodes)
                                writer.Write((byte)item.Type);
                            writer.WritePadding(4, 0);
                            foreach (var item in cur.Nodes)
                            {
                                switch (item.Type)
                                {
                                    case ByamlNodeType.String:
                                        writer.Write((item as ByamlNode.String).Value);
                                        break;
                                    case ByamlNodeType.Data:
                                        writer.Write((item as ByamlNode.Data).Value);
                                        break;
                                    case ByamlNodeType.Boolean:
                                        writer.Write((item as ByamlNode.Boolean).Value ? 1 : 0);
                                        break;
                                    case ByamlNodeType.Int:
                                        writer.Write((item as ByamlNode.Int).Value);
                                        break;
                                    case ByamlNodeType.Single:
                                        writer.Write((item as ByamlNode.Single).Value);
                                        break;
                                    case ByamlNodeType.UnamedNode:
                                    case ByamlNodeType.NamedNode:
                                        writer.Write((int)item.Address);
                                        break;
                                    default:
                                        throw new NotImplementedException();
                                }
                            }
                        }

                    }
                }

                writer.Close();
            }
        }
Пример #23
0
 public override void Write(EndianBinaryWriter er)
 {
     base.Write(er);
     er.WriteVector3(CenterPosition);
     er.WriteVector3(Size);
 }
Пример #24
0
        static void Handle(object client_obj)
        {
            string name = Thread.CurrentThread.Name;
            StreamWriter log = null;

            try
            {
                TcpClient client = (TcpClient)client_obj;
                using (NetworkStream stream = client.GetStream())
                {
                    EndianBinaryReader reader = new EndianBinaryReader(stream);
                    EndianBinaryWriter writer = new EndianBinaryWriter(stream);


                    // Log connection
                    Console.WriteLine(name + " Accepted connection from client " + client.Client.RemoteEndPoint.ToString());

                    // Create log file for current thread
                    log = new StreamWriter(logs_root + "\\" + DateTime.Now.ToString("yyyy-MM-dd") + "-" + name + ".txt");
                    log.WriteLine(name + " Accepted connection from client " + client.Client.RemoteEndPoint.ToString());

                    writer.Write(BYTE_SPECIAL);

                    while (true)
                    {
                        byte cmd_byte = reader.ReadByte();
                        switch (cmd_byte)
                        {
                            // cmd
                            case BYTE_PING:
                                {
                                    int val1 = reader.ReadInt32();
                                    int val2 = reader.ReadInt32();

                                    Log(log, name + " PING RECEIVED with values : " + val1.ToString() + " - " + val2.ToString());
                                    break;
                                }
                            case BYTE_LOG_STR:
                                {
                                    int len_str = reader.ReadInt32();
                                    string str = reader.ReadString(Encoding.ASCII, len_str - 1);
                                    if (reader.ReadByte() != 0) throw new InvalidDataException();

                                    Log(log, name + " LogString =>(\"" + str + "\")");
                                    break;
                                }
                            case BYTE_DISCONNECT:
                                {
                                    Log(log, name + " DISCONNECT");
                                    break;
                                }

                            // sd
                            case BYTE_MOUNT_SD:
                                {
                                    Log(log, name + " Trying to mount SD card");
                                    break;
                                }
                            case BYTE_MOUNT_SD_OK:
                                {
                                    Log(log, name + " SD card mounted !");
                                    break;
                                }
                            case BYTE_MOUNT_SD_BAD:
                                {
                                    Log(log, name + " Can't mount SD card");
                                    break;
                                }

                            // replacement
                            case BYTE_STAT:
                            case BYTE_STAT_ASYNC:
                                {
                                    int len_path = reader.ReadInt32();
                                    string path = reader.ReadString(Encoding.ASCII, len_path - 1);
                                    if (reader.ReadByte() != 0) throw new InvalidDataException();

                                    if (cmd_byte == BYTE_STAT)
                                        Log(log, name + " FSGetStat(\"" + path + "\")");
                                    else
                                        Log(log, name + " FSGetStatAsync(\"" + path + "\")");
                                    break;
                                }
                            case BYTE_OPEN_FILE:
                            case BYTE_OPEN_FILE_ASYNC:
                                {
                                    int len_str = reader.ReadInt32();
                                    string str = reader.ReadString(Encoding.ASCII, len_str - 1);
                                    if (reader.ReadByte() != 0) throw new InvalidDataException();

                                    if (cmd_byte == BYTE_OPEN_FILE)
                                        Log(log, name + " FSOpenFile(\"" + str + "\")");
                                    else
                                        Log(log, name + " FSOpenFileAsync(\"" + str + "\")");

                                    break;
                                }
                            case BYTE_OPEN_DIR:
                            case BYTE_OPEN_DIR_ASYNC:
                                {
                                    int len_path = reader.ReadInt32();
                                    string path = reader.ReadString(Encoding.ASCII, len_path - 1);
                                    if (reader.ReadByte() != 0) throw new InvalidDataException();

                                    if (cmd_byte == BYTE_OPEN_DIR)
                                        Log(log, name + " FSOpenDir(\"" + path + "\")");
                                    else
                                        Log(log, name + " FSOpenDirAsync(\"" + path + "\")");

                                    break;
                                }
                            case BYTE_CHANGE_DIR:
                            case BYTE_CHANGE_DIR_ASYNC:
                                {
                                    int len_path = reader.ReadInt32();
                                    string path = reader.ReadString(Encoding.ASCII, len_path - 1);
                                    if (reader.ReadByte() != 0) throw new InvalidDataException();

                                    if (cmd_byte == BYTE_CHANGE_DIR)
                                        Log(log, name + " FSChangeDir(\"" + path + "\")");
                                    else
                                        Log(log, name + " FSChangeDirAsync(\"" + path + "\")");

                                    break;
                                }
                            case BYTE_MAKE_DIR:
                            case BYTE_MAKE_DIR_ASYNC:
                                {
                                    int len_path = reader.ReadInt32();
                                    string path = reader.ReadString(Encoding.ASCII, len_path - 1);
                                    if (reader.ReadByte() != 0) throw new InvalidDataException();

                                    if (cmd_byte == BYTE_CHANGE_DIR)
                                        Log(log, name + " FSMakeDir(\"" + path + "\")");
                                    else
                                        Log(log, name + " FSMakeDirAsync(\"" + path + "\")");

                                    break;
                                }
                            case BYTE_RENAME:
                            case BYTE_RENAME_ASYNC:
                                {
                                    int len_path = reader.ReadInt32();
                                    string path = reader.ReadString(Encoding.ASCII, len_path - 1);
                                    if (reader.ReadByte() != 0) throw new InvalidDataException();

                                    if (cmd_byte == BYTE_CHANGE_DIR)
                                        Log(log, name + " FSRename(\"" + path + "\")");
                                    else
                                        Log(log, name + " FSRenameAsync(\"" + path + "\")");

                                    break;
                                }
                            case BYTE_REMOVE:
                            case BYTE_REMOVE_ASYNC:
                                {
                                    int len_path = reader.ReadInt32();
                                    string path = reader.ReadString(Encoding.ASCII, len_path - 1);
                                    if (reader.ReadByte() != 0) throw new InvalidDataException();

                                    if (cmd_byte == BYTE_CHANGE_DIR)
                                        Log(log, name + " FSRemove(\"" + path + "\")");
                                    else
                                        Log(log, name + " FSRemoveAsync(\"" + path + "\")");

                                    break;
                                }

                            // Log
                            case BYTE_CLOSE_FILE:
                                {
                                     Log(log, name + " FSCloseFile()");
                                     break;
                                }
                            case BYTE_CLOSE_FILE_ASYNC:
                                {
                                    Log(log, name + " FSCloseFileAsync()");
                                    break;
                                }
                            case BYTE_CLOSE_DIR:
                                {
                                    Log(log, name + " FSCloseDir()");
                                    break;
                                }
                            case BYTE_CLOSE_DIR_ASYNC:
                                {
                                    Log(log, name + " FSCloseDirAsync()");
                                    break;
                                }
                            case BYTE_FLUSH_FILE:
                                {
                                    Log(log, name + " FSFlushFile()");
                                    break;
                                }
                            case BYTE_GET_ERROR_CODE_FOR_VIEWER:
                                {
                                    Log(log, name + " FSGetErrorCodeForViewer()");
                                    break;
                                }
                            case BYTE_GET_LAST_ERROR:
                                {
                                    Log(log, name + " FSGetLastError()");
                                    break;
                                }
                            case BYTE_GET_MOUNT_SOURCE:
                                {
                                    Log(log, name + " FsGetMountSource()");
                                    break;
                                }
                            case BYTE_GET_MOUNT_SOURCE_NEXT:
                                {
                                    Log(log, name + " FsGetMountSourceNext()");
                                    break;
                                }
                            case BYTE_GET_POS_FILE:
                                {
                                    Log(log, name + " FSGetPos()");
                                    break;
                                }
                            case BYTE_SET_POS_FILE:
                                {
                                    Log(log, name + " FSSetPos()");
                                    break;
                                }
                            case BYTE_GET_STAT_FILE:
                                {
                                    Log(log, name + " FSGetStatFile()");
                                    break;
                                }
                            case BYTE_EOF:
                                {
                                    Log(log, name + " FSGetEof()");
                                    break;
                                }
                            case BYTE_READ_FILE:
                                {
                                    Log(log, name + " FSReadFile()");
                                    break;
                                }
                            case BYTE_READ_FILE_ASYNC:
                                {
                                    Log(log, name + " FSReadFileAsync()");
                                    break;
                                }
                            case BYTE_READ_FILE_WITH_POS:
                                {
                                    Log(log, name + " FSReadFileWithPos()");
                                    break;
                                }
                            case BYTE_READ_DIR:
                                {
                                    Log(log, name + " FSReadDir()");
                                    break;
                                }
                            case BYTE_READ_DIR_ASYNC:
                                {
                                    Log(log, name + " FSReadDirAsync()");
                                    break;
                                }
                            case BYTE_GET_CWD:
                                {
                                    Log(log, name + " FSGetCwd()");
                                    break;
                                }
                            case BYTE_SET_STATE_CHG_NOTIF:
                                {
                                    Log(log, name + " FSSetStateChangeNotification()");
                                    break;
                                }
                            case BYTE_TRUNCATE_FILE:
                                {
                                    Log(log, name + " FSTruncateFile()");
                                    break;
                                }
                            case BYTE_WRITE_FILE:
                                {
                                    Log(log, name + " FSWriteFile()");
                                    break;
                                }
                            case BYTE_WRITE_FILE_WITH_POS:
                                {
                                    Log(log, name + " FSWriteFileWithPos()");
                                    break;
                                }


                            case BYTE_CREATE_THREAD:
                                {
                                    Log(log, name + " CreateThread()");
                                    break;
                                }

                            default:
                                throw new InvalidDataException();
                        }
                    }
                }
            }
            catch (Exception e)
            {
                if (log != null)
                    Log(log, name + " " + e.Message);
                else
                    Console.WriteLine(name + " " + e.Message);
            }
            finally
            {
                if (log != null)
                    log.Close();
            }
            Console.WriteLine(name + " Exit");
        }
Пример #25
0
 public virtual void Write(EndianBinaryWriter er)
 {
     er.Write(Type);
 }
Пример #26
0
 public void Write(EndianBinaryWriter er, CGFXWriterContext c)
 {
     er.Write(Height);
     er.Write(Width);
     er.Write(DataSize);
     c.WriteDataReference(Data, er);
     er.Write(DynamicAllocator);
     er.Write(BitsPerPixel);
     er.Write(LocationAddress);
     er.Write(MemoryAddress);
 }
Пример #27
0
 public override void Write(EndianBinaryWriter er)
 {
     int newS = 0;
     int newT = 0;
     do newS++;
     while (8 << newS != S);
     do newT++;
     while (8 << newT != T);
     texImageParam = (UInt32)(((TransparentColor ? 1 : 0) << 29) | ((byte)Fmt << 26) | ((newT & 0x7) << 23) | ((newS & 0x7) << 20) | ((Offset >> 3) & 0xFFFF));
     er.Write(texImageParam);
     extraParam = (UInt32)((1 << 31) | ((T & 0x3FF) << 11) | ((S & 0x3FF) << 0));
     er.Write(extraParam);
 }
Пример #28
0
 public override void Write(EndianBinaryWriter er, CGFXWriterContext c)
 {
     base.Write(er, c);
     er.Write(Height);
     er.Write(Width);
     er.Write(GLFormat);
     er.Write(Type);
     er.Write(NrLevels);
     er.Write(TextureObject);
     er.Write(LocationFlag);
     er.Write((uint)HWFormat);
 }
Пример #29
0
        public void Write(EndianBinaryWriter er)
        {
            long offpos = er.BaseStream.Position;
            //header.Write(er, 0);
            er.Write(Signature, Encoding.ASCII, false);
            er.Write((uint)0);

            List<byte> TexData = new List<byte>();
            List<byte> Tex4x4Data = new List<byte>();
            List<byte> Tex4x4PlttIdxData = new List<byte>();
            foreach (DictTexData d in dictTex.entry.data)
            {
                if (d.Fmt != Textures.ImageFormat.COMP4x4) TexData.AddRange(d.Data);
                else
                {
                    Tex4x4Data.AddRange(d.Data);
                    Tex4x4PlttIdxData.AddRange(d.Data4x4);
                }
            }
            List<byte> PaletteData = new List<byte>();
            foreach (DictPlttData d in dictPltt.entry.data)
            {
                PaletteData.AddRange(d.Data);
            }

            TexInfo.ofsDict = 60;
            TexInfo.sizeTex = (uint)TexData.Count;
            TexInfo.ofsTex = (UInt32)(60 + 8 + (dictTex.numEntry + 1) * 4 + 4 + dictTex.numEntry * 8 + dictTex.numEntry * 16 + 8 + (dictPltt.numEntry + 1) * 4 + 4 + dictPltt.numEntry * 4 + dictPltt.numEntry * 16);
            Tex4x4Info.ofsDict = 60;
            Tex4x4Info.sizeTex = (uint)Tex4x4Data.Count;
            Tex4x4Info.ofsTex = (UInt32)(60 + 8 + (dictTex.numEntry + 1) * 4 + 4 + dictTex.numEntry * 8 + dictTex.numEntry * 16 + 8 + (dictPltt.numEntry + 1) * 4 + 4 + dictPltt.numEntry * 4 + dictPltt.numEntry * 16 + TexData.Count);
            Tex4x4Info.ofsTexPlttIdx = (UInt32)(60 + 8 + (dictTex.numEntry + 1) * 4 + 4 + dictTex.numEntry * 8 + dictTex.numEntry * 16 + 8 + (dictPltt.numEntry + 1) * 4 + 4 + dictPltt.numEntry * 4 + dictPltt.numEntry * 16 + TexData.Count + Tex4x4Data.Count);
            PlttInfo.ofsDict = (ushort)(60 + 8 + (dictTex.numEntry + 1) * 4 + 4 + dictTex.numEntry * 8 + dictTex.numEntry * 16);
            PlttInfo.sizePltt = (uint)PaletteData.Count;
            PlttInfo.ofsPlttData = (UInt32)(60 + 8 + (dictTex.numEntry + 1) * 4 + 4 + dictTex.numEntry * 8 + dictTex.numEntry * 16 + 8 + (dictPltt.numEntry + 1) * 4 + 4 + dictPltt.numEntry * 4 + dictPltt.numEntry * 16 + TexData.Count + Tex4x4Data.Count + Tex4x4PlttIdxData.Count);
            TexInfo.Write(er);
            Tex4x4Info.Write(er);
            PlttInfo.Write(er);
            uint offset = 0;
            uint offset4x4 = 0;
            for (int i = 0; i < dictTex.numEntry; i++)
            {
                if (dictTex[i].Value.Fmt != Textures.ImageFormat.COMP4x4)
                {
                    dictTex[i].Value.Offset = offset;
                    offset += (uint)dictTex[i].Value.Data.Length;
                }
                else
                {
                    dictTex[i].Value.Offset = offset4x4;
                    offset4x4 += (uint)dictTex[i].Value.Data.Length;
                }
            }
            dictTex.Write(er);
            uint offsetPltt = 0;
            for (int i = 0; i < dictPltt.numEntry; i++)
            {
                dictPltt[i].Value.offset = offsetPltt;
                offsetPltt += (uint)dictPltt[i].Value.Data.Length;
            }
            dictPltt.Write(er);
            er.Write(TexData.ToArray(), 0, TexData.Count);
            er.Write(Tex4x4Data.ToArray(), 0, Tex4x4Data.Count);
            er.Write(Tex4x4PlttIdxData.ToArray(), 0, Tex4x4PlttIdxData.Count);
            er.Write(PaletteData.ToArray(), 0, PaletteData.Count);
            long curpos = er.BaseStream.Position;
            er.BaseStream.Position = offpos + 4;
            er.Write((UInt32)(curpos - offpos));
            er.BaseStream.Position = curpos;
        }
Пример #30
0
 public static void Pack(String FolderPath, String OutFile)
 {
     string[] he = Directory.GetFiles(FolderPath, "*.he*");
     string[] a = Directory.GetFiles(FolderPath, "*.(a)");
     string[] b = Directory.GetFiles(FolderPath, "*.(b)");
     MD5Entry game = new MD5Entry();
     foreach (string s in he)
     {
         if (s.ToLower().EndsWith("he0"))
         {
             byte[] hash = System.Security.Cryptography.MD5.Create().ComputeHash(File.ReadAllBytes(s));
             string hashs = BitConverter.ToString(hash).Replace("-", "").ToLower();
             MD5Entry[] e = MD5Table.Where(ss => ss.hash == hashs).ToArray();
             if (e.Length != 0)
             {
                 game = e[0];
                 break;
             }
             else
             {
                 System.Windows.Forms.MessageBox.Show("Unknown Game!\n" + hashs);
                 game = new MD5Entry(hashs, "Unknown Game", 0);
                 break;
             }
             return;
         }
     }
     if (game.name == null) return;
     //System.Windows.Forms.MessageBox.Show(String.Format("{0}\nHE {1}", game.name, game.version));
     //-- Header (0xC) --
     //0x00 - HEPA
     //0x04 - FileSize (BE!)
     //0x08 - HE Version
     //0x0A - Nr Files
     //-- File Index Block (0xC) --
     //0x00 - File Id (he0 = 0, he1 = 1, he2 = 2, (a) = 1, (b) = 0xB)
     //0x04 - File Offset
     //0x08 - File Length
     //MemoryStream m = new MemoryStream();
     EndianBinaryWriter er = new EndianBinaryWriter(/*m*/File.Create(OutFile), Endianness.LittleEndian);
     er.Write("HEPA", Encoding.ASCII, false);
     er.Write((UInt32)0);
     er.Write((UInt16)(game.version * 10));
     er.Write((UInt16)(he.Length + a.Length + b.Length));
     Dictionary<int, String> Files = new Dictionary<int, String>();
     for (int i = 0; i < he.Length; i++)
     {
         char idx = he[i][he[i].Length - 1];
         Files.Add((int)char.GetNumericValue(idx), he[i]);
     }
     if (a.Length != 0) Files.Add(1, a[0]);
     if (b.Length != 0) Files.Add(0xB, b[0]);
     int[] files = Files.Keys.ToArray();
     Array.Sort(files);
     for (int i = 0; i < files.Length; i++)
     {
         er.Write((UInt32)(files[i]));
         er.Write((UInt32)0);
         er.Write((UInt32)0);
     }
     for (int i = 0; i < files.Length; i++)
     {
         byte[] d = File.ReadAllBytes(Files[files[i]]);
         if (files[i] == 0 || files[i] == 1)
         {
             for (int q = 0; q < d.Length; q++)
             {
                 d[q] ^= 0x69;
             }
         }
         long curpos = er.BaseStream.Position;
         er.BaseStream.Position = 12 + i * 12 + 4;
         er.Write((UInt32)(curpos));
         er.Write((UInt32)(d.Length));
         er.BaseStream.Position = curpos;
         er.Write(d, 0, d.Length);
     }
     er.BaseStream.Position = 4;
     er.Endianness = Endianness.BigEndian;
     er.Write((UInt32)(er.BaseStream.Length));
     //byte[] data = m.GetBuffer();
     er.Close();
     //File.Create(OutFile).Close();
     //File.WriteAllBytes(OutFile, data);
 }