Example #1
0
        public static SwfDecompiledMap ReadSwfMap(string id, string mapid)
        {
            string           path       = (Constants.MapsPath + $"{id}" + "_" + $"{mapid}X.swf");
            SwfReader        Reader     = new SwfReader(path);
            Swf              swf        = Reader.ReadSwf();
            SwfDecompiledMap mapDatas   = null;
            IEnumerator      enumerator = swf.Tags.GetEnumerator();

            while (enumerator.MoveNext())
            {
                BaseTag current = (BaseTag)enumerator.Current;

                if (current.ActionRecCount != 0)
                {
                    string      sb = "";
                    IEnumerator currentenumerator = current.GetEnumerator();
                    while (currentenumerator.MoveNext())
                    {
                        Decompiler decompiler = new Decompiler(swf.Version);
                        ArrayList  actions    = decompiler.Decompile((byte[])currentenumerator.Current);

                        foreach (BaseAction obj in actions)
                        {
                            sb += obj.ToString();
                        }
                    }
                    mapDatas = ParseSwfMapDatas(sb);
                }
            }
            Reader.Close();
            return(mapDatas);
        }
Example #2
0
        private void GenerateFlexSystemManagerFrame()
        {
            if (IsSwc)
            {
                return;
            }
            if (!IsFlexApplication)
            {
                return;
            }

            var managerFullName = FlexSystemManager.BuildFrame();

            Debug.Assert(FrameWithFlexSystemManager != null);
            Swf.FrameCount++;

            Swf.SetFrameLabel("System Manager");

            var symTable = new SwfTagSymbolClass();

            AddAbcTag(FrameWithFlexSystemManager);
            Assets.ImportLateAssets();
            Assets.FlushAssets(symTable);

            symTable.AddSymbol(0, managerFullName);
            Swf.Tags.Add(symTable);
            Swf.ShowFrame();
        }
Example #3
0
        public string GetBytesCode()
        {
            StringBuilder code   = new StringBuilder();
            SwfReader     Reader = new SwfReader(this.File);
            Swf           swf    = null;

            try
            {
                swf = Reader.ReadSwf();
            }
            catch (Exception Ex) { throw new Exception(Ex.ToString()); }

            IEnumerator enumerator = swf.Tags.GetEnumerator();

            while (enumerator.MoveNext())
            {
                BaseTag current = (BaseTag)enumerator.Current;
                if (current.ActionRecCount != 0)
                {
                    IEnumerator currentenumerator = current.GetEnumerator();
                    while (currentenumerator.MoveNext())
                    {
                        Decompiler decompiler = new Decompiler(swf.Version);
                        foreach (BaseAction action in decompiler.Decompile((byte[])currentenumerator.Current))
                        {
                            code.AppendLine(action.ToString());
                        }
                    }
                }
            }

            return(code.ToString());
        }
Example #4
0
        public static void LoadSwf(byte[] module)
        {
            var swf = new Swf();

            swf.Decompile(module);

            foreach (var doAbcTag in swf.DoAbcTagList)
            {
                var abc          = doAbcTag.AbcData;
                var constantPool = abc.ConstantPool;
                var strlen       = constantPool.StringArrayLength;

                for (var index = 0u; index < strlen; index++)
                {
                    var constantStr = constantPool
                                      .GetStringAt(index)?.String;

                    if (!string.IsNullOrEmpty(constantStr) &&
                        constantStr.ToLower() is var i &&
                        i.EndsWith("_secret") && Add(i))
                    {
                        if (YoponSetting.I.IsDebugMode)
                        {
                            Logger.OutputAtBackground(
                                YoponSetting.DebugLogFile,
                                $"[DEBUG] アクション追加 ({i})");
                        }
                    }
                }
            }
        }
Example #5
0
        static void ExploreSWF(string swfname)
        {
            Stream             stream = File.OpenRead(swfname);
            SwfExportTagReader reader = new SwfExportTagReader(new BufferedStream(stream));
            Swf swf = reader.ReadSwf();

            Hashtable tagsSeen = new Hashtable();

            // list tags
            ExportTag export;

            foreach (BaseTag tag in swf)
            {
                export = tag as ExportTag;
                if (export != null)
                {
                    foreach (string name in export.Names)
                    {
                        if (!tagsSeen.Contains(name))
                        {
                            Console.WriteLine(name);
                            tagsSeen.Add(name, true);
                        }
                    }
                }
            }
        }
Example #6
0
        void BuildCatalog()
        {
            _modAppAssembly = GetMod(AppAssembly.Location);

            _catalog = new XmlDocument();
            var root = CreateXmlElement("swc");

            _catalog.AppendChild(root);

            var versions = CreateXmlElement("versions");

            root.AppendChild(versions);

            versions.AppendChild(CreateXmlElement("swc", "version", "1.2"));
            //TODO:
            if (HasFlexReference)
            {
                versions.AppendChild(CreateXmlElement("flex", "version", "3.0.0", "build", "477"));
            }

            var features = CreateXmlElement("features");

            root.AppendChild(features);
            features.AppendChild(CreateXmlElement("feature-script-deps"));
            if (SwcHasFiles)
            {
                features.AppendChild(CreateXmlElement("feature-files"));
            }

            //TODO: <components>

            var libs = CreateXmlElement("libraries");

            root.AppendChild(libs);

            var lib = CreateXmlElement(SwcCatalog.Elements.Library, "path", SwcFile.LIBRARY_SWF);

            libs.AppendChild(lib);

            CreateScriptElements(lib);

            _libraryBytes = ToByteArray(ms => Swf.Save(ms));

            var    digests = CreateXmlElement(SwcCatalog.Elements.Digests);
            string digest  = _libraryBytes.GetHashString(HashExtensions.TypeSHA256);

            digests.AppendChild(CreateDigestElement(HashExtensions.TypeSHA256, false, digest));
            lib.AppendChild(digests);

            _catalogBytes = ToByteArray(
                ms =>
            {
                var xws = new XmlWriterSettings {
                    Indent = true, IndentChars = "  "
                };
                using (var xw = XmlWriter.Create(ms, xws))
                    _catalog.Save(xw);
            });
        }
Example #7
0
 void SetupDebugInfo()
 {
     if (_options.Debug)
     {
         Swf.EnableDebugger(6517, _options.DebugPassword);
         Swf.Tags.Add(new SwfTagDebugID("7ae6b0e5-298b-42a8-01d9-a2a555be7ef8"));
     }
 }
        public TagsRemover(string fileName)
        {
            Stream    stream = new FileStream(fileName, FileMode.Open);
            SwfReader reader = new SwfReader(stream);

            swf = reader.ReadSwf();
            stream.Close();
        }
Example #9
0
        public static List <MapDatas> ReadListSwfMap(string id)
        {
            List <MapDatas> MapList = new List <MapDatas>();
            List <string>   Files   = Directory.GetFiles(Constants.MapsPath, "*.swf").ToList();

            Files = Files.Where(x => x.Contains("\\" + id)).ToList();
            SwfReader Reader;

            foreach (var mapFile in Files)
            {
                string path = mapFile;

                Reader = new SwfReader(path);
                Swf swf = Reader.ReadSwf();

                IEnumerator enumerator = swf.Tags.GetEnumerator();
                while (enumerator.MoveNext())
                {
                    BaseTag current = (BaseTag)enumerator.Current;
                    if (current.ActionRecCount != 0)
                    {
                        string      sb = "";
                        IEnumerator currentenumerator = current.GetEnumerator();
                        while (currentenumerator.MoveNext())
                        {
                            Decompiler decompiler = new Decompiler(swf.Version);
                            ArrayList  actions    = decompiler.Decompile((byte[])currentenumerator.Current);

                            foreach (BaseAction obj in actions)
                            {
                                sb += obj.ToString();
                            }
                        }
                        SwfDecompiledMap content = ParseSwfMapDatas(sb);
                        content.DecypheredMapData = Hash.DecypherData(content.CypheredMapData, MapKeyCracker.MapCrackKey(content.CypheredMapData));
                        GlobalMapsInfos.First(x => x.Id == content.Id).SwfDatas.MapId = path.Substring(path.IndexOf(id) + id.Length + 1, path.IndexOf(".swf") - (path.IndexOf(id) + id.Length + 1));
                        GlobalMapsInfos.First(x => x.Id == content.Id).SwfDatas       = content;
                        MapList.Add(GlobalMapsInfos.First(x => x.SwfDatas == content));
                        sb = "";
                    }
                }
                Reader.Close();
                swf = null;
            }
            string firstValue = MapList.First().SwfDatas.DecypheredMapData;

            if (MapList.All(x => x.SwfDatas.DecypheredMapData == firstValue))
            {
                return new List <MapDatas>()
                       {
                           MapList.First()
                       }
            }
            ;
            return(MapList);
        }
Example #10
0
        public static void ReadSwfLang(string path)
        {
            //This part is dirty but there arent so much ressources about how to decompile langs, decompilation & reading takes more than12 secondes..
            StringHelper.WriteLine($"[DataManager] Reading maps lang ..", ConsoleColor.Cyan);
            SwfReader   Reader     = new SwfReader(path);
            Swf         swf        = Reader.ReadSwf();
            IEnumerator enumerator = swf.Tags.GetEnumerator();

            while (enumerator.MoveNext())
            {
                BaseTag current = (BaseTag)enumerator.Current;
                if (current.ActionRecCount != 0)
                {
                    string      sb = "";
                    IEnumerator currentenumerator = current.GetEnumerator();
                    while (currentenumerator.MoveNext())
                    {
                        Decompiler decompiler = new Decompiler(swf.Version);
                        ArrayList  actions    = decompiler.Decompile((byte[])currentenumerator.Current);

                        foreach (BaseAction obj in actions)
                        {
                            sb += obj.ToString();
                        }

                        //maps coords & subarea id
                        string          regex   = @"getMemberpush ([0-9]*?) as int push (-?[0-9]*?) as var push (-?[0-9]*?) as int push (-?[0-9]*?) as var push (-?[0-9]*?) as int push (-?[0-9]*?) as var push (-?[0-9]*?) as int";
                        MatchCollection matches = Regex.Matches(sb, regex);
                        foreach (Match match in matches)
                        {
                            GlobalMapsInfos.Add(new MapDatas(int.Parse(match.Groups[1].Value), int.Parse(match.Groups[3].Value), int.Parse(match.Groups[5].Value), int.Parse(match.Groups[7].Value)));
                        }
                        //area id
                        foreach (var map in GlobalMapsInfos.Where(x => x.AreaId == -1))
                        {
                            var regex2   = @"getMemberpush " + map.SubAreaId + " as int push (-?[0-9]*?) as var push (-?[0-9]*?) as var push (-?[0-9]*?) as var push (-?[0-9]*?) ";
                            var matches2 = Regex.Matches(sb, regex2);
                            foreach (Match match2 in matches2)
                            {
                                map.AreaId = int.Parse(match2.Groups[4].Value);
                            }
                        }
                        GC.Collect();
                        GC.WaitForPendingFinalizers();
                        sb = "";
                        Console.Write($"\r{DateTime.Now:[HH:mm:ss:fff]} [DataManager] {GlobalMapsInfos.Count()} maps loaded..");
                    }
                }
            }
            Reader.Close();
            swf = null;

            Console.Write("\n");
            StringHelper.WriteLine($"[DataManager] {GlobalMapsInfos.Count()} maps added to list !", ConsoleColor.Cyan);
            StringHelper.WriteLine("[DataManager] Map with undefinied AreaId : " + GlobalMapsInfos.Count(x => x.AreaId == -1), ConsoleColor.Blue);
        }
Example #11
0
        public static void ConvertBmpToSwf(Bitmap bmp, string outputSwfFileName)
        {
            int   posX   = 0; //Posx
            int   posY   = 0; //Posy
            Image image  = bmp;
            int   width  = image.Width;
            int   height = image.Height;

            //自动缩小大图片
            if (width > 610)
            {
                double rw        = width;
                double rh        = height;
                double newheight = rh * 610 / rw;
                width  = 610;
                height = Convert.ToInt32(newheight);
                image  = image.GetThumbnailImage(width, height, null, IntPtr.Zero);
            }
            Swf swf = new Swf();

            swf.Size             = new Rect(0, 0, (posX + width) * 20, (posY + height) * 20);
            swf.Version          = 7;
            swf.Header.Signature = "CWS";
            swf.Tags.Add(new SetBackgroundColorTag(255, 255, 255));
            ushort newDefineId = swf.GetNewDefineId();

            swf.Tags.Add(DefineBitsJpeg2Tag.FromImage(newDefineId, image));
            DefineShapeTag tag = new DefineShapeTag();

            tag.CharacterId = swf.GetNewDefineId();
            tag.Rect        = new Rect((posX * 20) - 1, (posY * 20) - 1, ((posX + width) * 20) - 1, ((posY + height) * 20) - 1);
            FillStyleCollection fillStyleArray = new FillStyleCollection();

            fillStyleArray.Add(new BitmapFill(FillStyleType.ClippedBitmapFill, 0xffff, new Matrix(0, 0, 20.0, 20.0)));
            fillStyleArray.Add(new BitmapFill(FillStyleType.ClippedBitmapFill, newDefineId, new Matrix((posX * 20) - 1, (posY * 20) - 1, (20.0 * width) / ((double)image.Width), (20.0 * height) / ((double)image.Height))));
            LineStyleCollection   lineStyleArray = new LineStyleCollection();
            ShapeRecordCollection shapes         = new ShapeRecordCollection();

            shapes.Add(new StyleChangeRecord((posX * 20) - 1, (posY * 20) - 1, 2));
            shapes.Add(new StraightEdgeRecord(width * 20, 0));
            shapes.Add(new StraightEdgeRecord(0, height * 20));
            shapes.Add(new StraightEdgeRecord(-width * 20, 0));
            shapes.Add(new StraightEdgeRecord(0, -height * 20));
            shapes.Add(new EndShapeRecord());
            tag.ShapeWithStyle = new ShapeWithStyle(fillStyleArray, lineStyleArray, shapes);
            swf.Tags.Add(tag);
            swf.Tags.Add(new PlaceObject2Tag(tag.CharacterId, 1, 0, 0));
            swf.Tags.Add(new ShowFrameTag());
            swf.Tags.Add(new EndTag());
            SwfWriter writer = new SwfWriter(outputSwfFileName);

            writer.Write(swf);
            writer.Close();
            image.Dispose();
        }
Example #12
0
        void GenerateApplicationFrame()
        {
            Swf.FrameCount++;

            var g = new AbcGenerator {
                SwfCompiler = this
            };
            var abc = g.Generate(AppAssembly);

            if (IsSwc)
            {
                var symTable = new SwfTagSymbolClass();

                CreateScripts(abc, symTable);

                if (symTable.Symbols.Count > 0)
                {
                    Swf.Tags.Add(symTable);
                }
            }
            else
            {
                var rootName = IsFlexApplication ? _flexAppType.FullName : g.RootSprite.Instance.FullName;

                //label should be the same as root name
                Swf.SetFrameLabel(rootName);

                if (g.IsNUnit)
                {
                    GenerateHtmlWrapper = false;
                }

                var symTable = new SwfTagSymbolClass();
                //see http://bugs.adobe.com/jira/browse/ASC-3235
                AddAbcTag(abc);
                Assets.ImportLateAssets();
                Assets.FlushAssets(symTable);

                //NOTE: In MX application root sprite is autogenerated subclass of mx.managers.SystemManager.
                if (!IsFlexApplication)
                {
                    //define symbol for root sprite
                    symTable.AddSymbol(0, rootName);
                }

                if (symTable.Symbols.Count > 0)
                {
                    Swf.Tags.Add(symTable);
                }
            }

            Swf.ShowFrame();
        }
Example #13
0
        private void Save(Stream output)
        {
            CheckSwf();

            if (IsSwc)
            {
                SaveSwc(output);
            }
            else
            {
                Swf.Save(output);
            }
        }
Example #14
0
        private void Save(string path)
        {
            CheckSwf();

            if (IsSwc)
            {
                SaveSwc(path);
            }
            else
            {
                Swf.Save(path);
            }
        }
Example #15
0
        static void Main(string[] args)
        {
            Swf swf = new Swf();

            swf.Version = 5;
            swf.Tags.Add(new SetBackgroundColorTag(new RGB(0, 0, 255)));
            swf.Tags.Add(new ShowFrameTag());
            swf.Tags.Add(new EndTag());

            SwfWriter writer = new SwfWriter(path);

            writer.Write(swf);
            writer.Close();
        }
Example #16
0
        static void ExploreSWF(Stream stream)
        {
            if (stream == null)
            {
                return;
            }
            SwfReader reader = new SwfReader(stream);
            //SwfExportTagReader reader = new SwfExportTagReader(stream);
            Swf swf = null;

            try
            {
                swf = reader.ReadSwf();
                foreach (BaseTag tag in swf)
                {
                    if (tag is ExportTag)
                    {
                        ExportTag etag = (ExportTag)tag;
                        for (int i = 0; i < etag.Ids.Count; i++)
                        {
                            BaseTag ftag = FindObject(swf, (ushort)etag.Ids[i]);
                            if (ftag is DefineSpriteTag)
                            {
                                DefineSpriteTag stag = (DefineSpriteTag)ftag;
                                Console.WriteLine("Symbol '" + etag.Names[i] + "' - " + stag.Size);
                            }
                            else if (ftag is DefineSoundTag)
                            {
                                DefineSoundTag stag = (DefineSoundTag)ftag;
                                Console.WriteLine("Sound '" + etag.Names[i] + "' - " + stag.MediaData.Length);
                            }
                            else if (ftag is DefineBitsTag)
                            {
                                DefineBitsTag btag = (DefineBitsTag)ftag;
                                Console.WriteLine("Image '" + etag.Names[i] + "' - " + btag.MediaData.Length);
                            }
                        }
                    }
                    else if (tag is DefineFontTag)
                    {
                        DefineFontTag ftag = (DefineFontTag)tag;
                        Console.WriteLine("Font '" + ftag.Name + "' - " + ftag.Data.Length);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("-- Swf error: " + ex.Message);
            }
        }
Example #17
0
 private static BaseTag FindObject(Swf swf, ushort id)
 {
     foreach (BaseTag tag in swf)
     {
         if (tag is DefineSpriteTag && (tag as DefineSpriteTag).Id == id)
         {
             return(tag);
         }
         else if (tag is DefineBitsTag && (tag as DefineBitsTag).Id == id)
         {
             return(tag);
         }
     }
     return(null);
 }
Example #18
0
        IResourceHandler IResourceHandlerFactory.GetResourceHandler(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request)
        {
            // Debug.WriteLine(request.Url);

            if (request.Url.Contains("TypeShoot.swf"))
            {
                return(new SwfResourceHandler(raw =>
                {
                    var swf = new Swf();

                    // File.WriteAllBytes("TypeShoot.swf", raw);

                    swf.Decompile(raw);

                    foreach (var doAbcTag in swf.DoAbcTagList)
                    {
                        var abc = doAbcTag.AbcData;
                        var constantPool = abc.ConstantPool;

                        foreach (var scriptArray in abc.ScriptArray)
                        {
                            foreach (var traits in scriptArray.TraitsArray)
                            {
                                // Words Class
                                if (traits.Name.MKQName.Name == "Words")
                                {
                                    var initializer = ((TraitClass)traits.Trait).Class.StaticInitializer;
                                    var bin = initializer.MethodBody.Code;
                                    var byteCode = new ByteCode(bin, abc);
                                    var instructions = byteCode.Instructions;
                                    var words = new Words(constantPool);
                                    words.Constructor(instructions);
                                    initializer.MethodBody.Code = byteCode.GetBytes();
                                }
                            }
                        }
                    }

                    var compileSwf = swf.Compile();

                    // File.WriteAllBytes("-TypeShoot.swf", compileSwf);

                    return compileSwf;
                }));
            }
            return(null);
        }
        public Swf RemoveTags(int tagCode)
        {
            if (swf == null)
            {
                return(null);
            }
            List <BaseTag> tags = new List <BaseTag>();

            foreach (BaseTag tag in swf)
            {
                if (tag.TagCode != tagCode)
                {
                    tags.Add(tag);
                }
            }
            Swf newSwf = new Swf(swf.Header, tags.ToArray());

            newSwf.Version = swf.Version;
            swf            = newSwf;
            return(newSwf);
        }
Example #20
0
        private static void GetPackets()
        {
            if (!File.Exists(CLIENT_PATH))
            {
                Console.WriteLine($"Cannot find SWF file \"{CLIENT_FILE}\"");
                return;
            }

            Console.WriteLine($"Reading SWF file \"{CLIENT_FILE}\"...");

            SwfReader swfReader = new SwfReader(CLIENT_PATH);
            Swf       swf       = swfReader.ReadSwf();

            swfReader.Close();

            Console.WriteLine($"Done reading SWF file: \"{CLIENT_FILE}\"");

            WriteRABCDAsmToDisk();

            foreach (BaseTag tag in swf.Tags)
            {
                if (tag.name != null && tag.TagCode == (int)TagCodeEnum.DoABC2)
                {
                    WriteABCDataToDisk(tag);
                    RunRABCDAsm();

                    if (File.Exists(GAME_SERVER_CONNECTION_PATH))
                    {
                        ExtractPackets();
                    }
                    else
                    {
                        Console.WriteLine($"Cannot find ABC data for \"{PACKETS_FILE}\"");
                    }
                }
            }

            DeleteTempFiles();
        }
        /// <summary>
        /// Writes the (compressed or uncompressed) swf data to a stream.
        /// The stream gets flushed and closed afterwards.
        /// </summary>
        public void Write(Swf swf)
        {
            swf.UpdateData();                   // update tag lengths to adapt to bytecode length
            SwfHeader header = swf.Header;

            BinaryWriter writer     = new BinaryWriter(baseStream, System.Text.Encoding.GetEncoding("ascii"));          // ASCII seems to be ok for Flash 5 and 6+ as well
            BinaryWriter dataWriter = writer;

            bool isCompressed = (header.Signature[0] == 'C');

            if (isCompressed)
            {
                // SharpZipLib makes it easy for us, simply chain a Deflater into the stream
                DeflaterOutputStream def = new DeflaterOutputStream(baseStream);
                dataWriter = new BinaryWriter(def);
            }

            // writer header data, always uncompressed
            writer.Write(header.Signature);
            writer.Write(swf.Version);
            writer.Write(swf.ByteCount);
            writer.Flush();

            // write header data pt.2, using either original stream or deflater stream
            dataWriter.Write(header.Rect);
            dataWriter.Write(header.Fps);
            dataWriter.Write(header.Frames);

            // write tag data
            foreach (BaseTag tag in swf)
            {
                dataWriter.Write(tag.Data);
            }

            // flush + close
            dataWriter.Flush();
            dataWriter.Close();
        }
Example #22
0
        private void buttSerialize_Click(object sender, System.EventArgs e)
        {
            if (txtPath.Text == string.Empty)
            {
                return;
            }

            string swfPath = txtPath.Text;
            string xmlPath = txtPath.Text + ".xml";

            SwfReader reader = new SwfReader(swfPath);
            Swf       swf    = reader.ReadSwf();

            reader.Close();

            XmlTextWriter writer = new XmlTextWriter(xmlPath, Encoding.UTF8);

            swf.Serialize(writer);
            writer.Close();

            object o = null;

            this.axWebBrowser1.Navigate("file://" + xmlPath, ref o, ref o, ref o, ref o);
        }
Example #23
0
        /// <summary>
        /// Resolves method.
        /// This method provides the way to update the textrecords glyph indexes
        /// from Font object contained by the Swf Dictionnary.
        /// </summary>
        /// <param name="swf">SWF.</param>
        public override void Resolve(Swf swf)
        {
            IEnumerator records = textRecords.GetEnumerator();

            while (records.MoveNext())
            {
                TextRecord  textRecord = (TextRecord)records.Current;
                IEnumerator glyphs     = textRecord.GlyphEntries.GetEnumerator();
                while (glyphs.MoveNext())
                {
                    GlyphEntry glyph = (GlyphEntry)glyphs.Current;
                    if (glyph.GlyphCharacter != '\0')
                    {
                        object font = swf.Dictionary[textRecord.FontId];
                        if (font != null && font is DefineFont2Tag)
                        {
                            int glyphIndex = ((DefineFont2Tag)font).GlyphShapesTable.GetCharIndex(glyph.GlyphCharacter);
                            glyph.GlyphIndex = (uint)glyphIndex;
                        }
                        //TODO: For DefineFont
                    }
                }
            }
        }
Example #24
0
 /// <summary>
 /// Resolves the specified SWF.
 /// </summary>
 /// <param name="swf">SWF.</param>
 public virtual void Resolve(Swf swf)
 {
 }
Example #25
0
        public void ExtractFilesFromSWF(object obj)
        {
            string file;

            if (!obj.GetType().Equals(typeof(string)))
            {
                return;
            }
            file = (string)obj;

            swfReader = new SwfReader(file);
            Swf swf = swfReader.ReadSwf();

            swfReader.Close();
            swfReader = null;

            foreach (BaseTag tag in swf.Tags)
            {
                if (tag is SymbolClass)
                {
                    symbols = tag as SymbolClass;
                    break;
                }
            }

            foreach (BaseTag tag in swf.Tags)
            {
                if (tag is DefineBitsJpeg3Tag)
                {
                    DefineBitsJpeg3Tag imgTag = tag as DefineBitsJpeg3Tag;
                    var ic = new ImageContainer();
                    ic.SWFFileName = Path.GetFileNameWithoutExtension(file);

                    if (symbols != null)
                    {
                        ic.Name = symbols.GetCharcterIdName(imgTag.CharacterId);
                    }
                    else
                    {
                        ic.Name = imgTag.CharacterId.ToString();
                    }

                    ic.PngTag = imgTag;
                    ImgPNG.Add(ic);
                }
                else if (tag is DefineBitsJpeg2Tag)
                {
                    DefineBitsJpeg2Tag imgTag = tag as DefineBitsJpeg2Tag;
                    var ic = new ImageContainer();
                    ic.SWFFileName = Path.GetFileNameWithoutExtension(file);

                    if (symbols != null)
                    {
                        ic.Name = symbols.GetCharcterIdName(imgTag.CharacterId);
                    }
                    else
                    {
                        ic.Name = imgTag.CharacterId.ToString();
                    }

                    ic.JpegTag = imgTag;
                    ImgJPG.Add(ic);
                }
            }
        }
Example #26
0
        public static byte[] EditHost(byte[] raw, int localPort)
        {
            var swf = new Swf();

            swf.Decompile(raw);

            foreach (var doAbcTag in swf.DoAbcTagList)
            {
                var abc          = doAbcTag.AbcData;
                var constantPool = abc.ConstantPool;
                var localServer  = $"info@{ProductConfiguration.LocalIP}";

                foreach (var instance in abc.InstanceArray)
                {
                    var className = instance.Name.MKQName.Name;
                    var nameSpace = instance.ProtectedNamespace?.Name?.String;
                    var traits    = instance.TraitArray.GetTraits();

                    if (nameSpace != "ProductConfiguration")
                    {
                        continue;
                    }

                    foreach (var trait in traits)
                    {
                        var memberName = trait.Name.MKQName.Name;

                        if (memberName == "infoHost")
                        {
                            var method   = ((TraitGetter)trait.Trait).Method;
                            var bin      = method.MethodBody.Code;
                            var byteCode = new ByteCode(bin, abc);

                            var instructions = new List <As3Instruction>();
                            var index        = constantPool.StringArrayLength;
                            var stringInfo   = new StringInfo(index, localServer);

                            constantPool.SetStringAt(stringInfo, index);

                            instructions.Add(new As3PushString(index));
                            instructions.Add(new As3ReturnValue());

                            var count = 0;

                            foreach (var instruction in instructions)
                            {
                                byteCode.AddInstructionAt(instruction, count++);
                            }

                            while (byteCode.GetInstructions().Count > count)
                            {
                                byteCode.RemoveInstructionAt(count - 1);
                            }

                            method.MethodBody.Code = byteCode.GetBytes();
                        }
                        else if (memberName == "infoWebSocketPort")
                        {
                            var method       = ((TraitGetter)trait.Trait).Method;
                            var bin          = method.MethodBody.Code;
                            var byteCode     = new ByteCode(bin, abc);
                            var instructions = byteCode.GetInstructions();

                            for (var count = 0; count < instructions.Count; count++)
                            {
                                if (instructions[count] is As3PushShort port &&
                                    443 == port.Short)
                                {
                                    var index = constantPool.IntArrayLength;
                                    constantPool.SetIntAt(localPort, index);
                                    instructions[count] = new As3PushInt(index);
                                }
                            }

                            method.MethodBody.Code = byteCode.GetBytes();
                        }
                    }
                }
            }

            return(swf.Compile());
        }
Example #27
0
 /// <summary>
 /// Resolves method.
 /// This method provides the way to update the textrecords glyph indexes
 /// from Font object contained by the Swf Dictionnary.
 /// </summary>
 /// <param name="swf">SWF.</param>
 public override void Resolve(Swf swf)
 {
     IEnumerator records = textRecords.GetEnumerator();
     while (records.MoveNext())
     {
         TextRecord textRecord = (TextRecord)records.Current;
         IEnumerator glyphs = textRecord.GlyphEntries.GetEnumerator();
         while (glyphs.MoveNext())
         {
             GlyphEntry glyph = (GlyphEntry)glyphs.Current;
             if (glyph.GlyphCharacter != '\0')
             {
                 object font = swf.Dictionary[textRecord.FontId];
                 if (font != null && font is DefineFont2Tag)
                 {
                     int glyphIndex = ((DefineFont2Tag)font).GlyphShapesTable.GetCharIndex(glyph.GlyphCharacter);
                     glyph.GlyphIndex = (uint)glyphIndex;
                 }
                 //TODO: For DefineFont
             }
         }
     }
 }
Example #28
0
        private void TestFile(string file)
        {
            if (log.IsInfoEnabled)
            {
                log.Info("--- " + file + " (READING)");
            }

            this.Cursor = Cursors.WaitCursor;

            Swf swf = null;

            DateTime readStart = DateTime.Now;
            DateTime readEnd;

            try
            {
                SwfReader reader = new SwfReader(file, true);
                swf = reader.ReadSwf();
                reader.Close();

                readEnd = DateTime.Now;
                TimeSpan duration = new TimeSpan(readEnd.Ticks - readStart.Ticks);
                string   min      = duration.Minutes.ToString();
                if (min.Length == 1)
                {
                    min = "0" + min;
                }
                string sec = duration.Seconds.ToString();
                if (sec.Length == 1)
                {
                    sec = "0" + sec;
                }
                string msec = duration.Milliseconds.ToString();
                if (msec.Length == 1)
                {
                    msec = "0" + msec;
                }
                string dur = min + ":" + sec + ":" + msec;

                System.Windows.Forms.ListViewItem listViewItem1 = new System.Windows.Forms.ListViewItem(new string[] { "READ: " + file, "OK", dur }, -1);
                listViewItem1.ForeColor = Color.Black;
                this.listView1.Items.Add(listViewItem1);
                this.listView1.Refresh();
                succeded++;

                swfList.Add(swf);
            }
            catch (Exception e)
            {
                readEnd = DateTime.Now;
                TimeSpan duration = new TimeSpan(readEnd.Ticks - readStart.Ticks);
                string   min      = duration.Minutes.ToString();
                if (min.Length == 1)
                {
                    min = "0" + min;
                }
                string sec = duration.Seconds.ToString();
                if (sec.Length == 1)
                {
                    sec = "0" + sec;
                }
                string msec = duration.Milliseconds.ToString();
                if (msec.Length == 1)
                {
                    msec = "0" + msec;
                }
                string dur = min + ":" + sec + ":" + msec;

                System.Windows.Forms.ListViewItem listViewItem1 = new System.Windows.Forms.ListViewItem(new string[] { "READ: " + file, "KO", dur }, -1);
                listViewItem1.ForeColor = Color.Red;
                this.listView1.Items.Add(listViewItem1);
                this.listView1.Refresh();
                if (log.IsErrorEnabled)
                {
                    log.Error("READING KO", e);
                }
                swfList.Add(null);
            }

            if (log.IsInfoEnabled)
            {
                log.Info("--- " + file + " (WRITING)");
            }

            readStart = DateTime.Now;
            try
            {
                string fileName = System.IO.Path.GetFileName(file);
                string path     = this.textBoxOutput.Text + fileName;

                SwfWriter writer = new SwfWriter(path);
                writer.Write(swf);
                writer.Close();

                readEnd = DateTime.Now;
                TimeSpan duration = new TimeSpan(readEnd.Ticks - readStart.Ticks);
                string   min      = duration.Minutes.ToString();
                if (min.Length == 1)
                {
                    min = "0" + min;
                }
                string sec = duration.Seconds.ToString();
                if (sec.Length == 1)
                {
                    sec = "0" + sec;
                }
                string msec = duration.Milliseconds.ToString();
                if (msec.Length == 1)
                {
                    msec = "0" + msec;
                }
                string dur = min + ":" + sec + ":" + msec;

                System.Windows.Forms.ListViewItem listViewItem1 = new System.Windows.Forms.ListViewItem(new string[] { "WRITE: " + path, "OK", dur }, -1);
                listViewItem1.ForeColor = Color.Black;
                this.listView1.Items.Add(listViewItem1);
                this.listView1.Refresh();

                succededWrite++;
            }
            catch (Exception ee)
            {
                readEnd = DateTime.Now;
                TimeSpan duration = new TimeSpan(readEnd.Ticks - readStart.Ticks);
                string   min      = duration.Minutes.ToString();
                if (min.Length == 1)
                {
                    min = "0" + min;
                }
                string sec = duration.Seconds.ToString();
                if (sec.Length == 1)
                {
                    sec = "0" + sec;
                }
                string msec = duration.Milliseconds.ToString();
                if (msec.Length == 1)
                {
                    msec = "0" + msec;
                }
                string dur = min + ":" + sec + ":" + msec;

                if (log.IsErrorEnabled)
                {
                    log.Error("WRITING KO", ee);
                }

                System.Windows.Forms.ListViewItem listViewItem1 = new System.Windows.Forms.ListViewItem(new string[] { "WRITE: " + file, "KO", dur }, -1);
                listViewItem1.ForeColor = Color.Red;
                this.listView1.Items.Add(listViewItem1);
                this.listView1.Refresh();
            }

            totalParsed++;
            this.Cursor = Cursors.Default;
            Result.Text = succeded.ToString() + "/" + totalParsed.ToString();
            Result.Refresh();
            WriteResult.Text = succededWrite.ToString() + "/" + totalParsed.ToString();
            WriteResult.Refresh();
        }
Example #29
0
        static void Main(string[] args)
        {
            //Picture to transform
            string imgPath = "img.jpg";
            string path    = "test_alpha.swf";
            //Alpha translation informations
            int alphaFrameNum = 35;  //frame duration
            int alphaStart    = 10;  //alpha percent start
            int alphaEnd      = 100; //alpha percent end

            //Load the picture to a GDI image
            Image img       = Image.FromFile(imgPath);
            int   posX      = 0;
            int   posY      = 0;
            int   imgWidth  = img.Width / 2;
            int   imgHeight = img.Height / 2;

            //Create a new Swf instance
            Swf swf = new Swf();

            swf.Size    = new Rect(0, 0, (posX + imgWidth) * 20, (posY + imgHeight) * 20);
            swf.Version = 5;

            //Set the background color tag
            swf.Tags.Add(new SetBackgroundColorTag(255, 255, 255));

            //Set the jpeg tag
            ushort jpegId = swf.GetNewDefineId();

            //Load the jped from an image
            swf.Tags.Add(DefineBitsJpeg2Tag.FromImage(jpegId, img));

            //Define the picture's shape tag
            DefineShapeTag shapeTag = new DefineShapeTag();

            shapeTag.CharacterId = swf.GetNewDefineId();
            shapeTag.Rect        = new Rect(posX * 20 - 1, posY * 20 - 1, (posX + imgWidth) * 20 - 1, (posY + imgHeight) * 20 - 1);
            FillStyleCollection fillStyles = new FillStyleCollection();

            fillStyles.Add(new BitmapFill(FillStyleType.ClippedBitmapFill, ushort.MaxValue, new Matrix(0, 0, 20, 20)));
            fillStyles.Add(new BitmapFill(FillStyleType.ClippedBitmapFill, jpegId, new Matrix(posX * 20 - 1, posY * 20 - 1, (20.0 * imgWidth) / img.Width, (20.0 * imgHeight) / img.Height)));
            LineStyleCollection   lineStyles = new LineStyleCollection();
            ShapeRecordCollection shapes     = new ShapeRecordCollection();

            shapes.Add(new StyleChangeRecord(posX * 20 - 1, posY * 20 - 1, 2));
            shapes.Add(new StraightEdgeRecord(imgWidth * 20, 0));
            shapes.Add(new StraightEdgeRecord(0, imgHeight * 20));
            shapes.Add(new StraightEdgeRecord(-imgWidth * 20, 0));
            shapes.Add(new StraightEdgeRecord(0, -imgHeight * 20));
            shapes.Add(new EndShapeRecord());
            shapeTag.ShapeWithStyle = new ShapeWithStyle(fillStyles, lineStyles, shapes);
            swf.Tags.Add(shapeTag);

            //Place the picture
            swf.Tags.Add(new PlaceObject2Tag(shapeTag.CharacterId, 1, 0, 0));
            //Add a frame
            swf.Tags.Add(new ShowFrameTag());

            for (int i = 0; i < alphaFrameNum; i++)
            {
                int percent    = (i * 100) / alphaFrameNum;
                int diff       = alphaEnd - alphaStart;
                int valPercent = (diff * percent) / 100 + alphaStart;
                int valRgb     = (255 * valPercent) / 100;
                swf.Tags.Add(new PlaceObject2Tag(1, new CXFormWithAlphaData(256, 256, 256, valRgb)));
                swf.Tags.Add(new ShowFrameTag());
            }
            swf.Tags.Add(new EndTag());

            //Write the swf to a file
            SwfWriter writer = new SwfWriter(path);

            writer.Write(swf);
            writer.Close();
            img.Dispose();
        }
Example #30
0
        private void ReadSwf(Swf swf)
        {
            this.labelVersion.Text   = swf.Version.ToString();
            this.labelFileSize.Text  = swf.Header.FileSize.ToString();
            this.labelFps.Text       = swf.Header.Fps.ToString();
            this.labelWidth.Text     = swf.Header.Size.Rectangle.Width.ToString();
            this.labelHeight.Text    = swf.Header.Size.Rectangle.Height.ToString();
            this.labelFrameCnt.Text  = swf.Header.Frames.ToString();
            this.labelSignature.Text = swf.Header.Signature;
            this.labelASbytes.Text   = swf.ActionCount.ToString();

            this.listBoxActions.Items.Clear();
            BaseTagCollection tags = swf.Tags;
            int i = 0;

            for (; i < tags.Count; i++)
            {
                BaseTag tag  = tags[i];
                int     code = tag.TagCode;
                if (code != -1)
                {
                    SwfDotNet.IO.Tags.TagCodeEnum val = SwfDotNet.IO.Tags.TagCodeEnum.DefineBits;
                    val = (SwfDotNet.IO.Tags.TagCodeEnum)System.Enum.Parse(val.GetType(), code.ToString());
                    this.listBoxActions.Items.Add(val.ToString());

                    if (tag is SetBackgroundColorTag)
                    {
                        this.listBoxActions.Items.Add("       R:" +
                                                      ((SetBackgroundColorTag)tag).RGB.red +
                                                      "  G:" + ((SetBackgroundColorTag)tag).RGB.green +
                                                      "  B:" + ((SetBackgroundColorTag)tag).RGB.blue);
                    }

                    if (tag is FrameLabelTag)
                    {
                        this.listBoxActions.Items.Add("       Name: " +
                                                      ((FrameLabelTag)tag).Name);
                    }

                    if (((SwfDotNet.IO.Tags.BaseTag)tag) is DefineFontInfo2Tag)
                    {
                        this.listBoxActions.Items.Add("       FontName: " +
                                                      ((DefineFontInfo2Tag)tag).FontName);
                    }


                    if (((SwfDotNet.IO.Tags.BaseTag)tag).ActionRecCount != 0)
                    {
                        IEnumerator enum2 = ((SwfDotNet.IO.Tags.BaseTag)tag).GetEnumerator();
                        while (enum2.MoveNext())
                        {
                            SwfDotNet.IO.ByteCode.Decompiler dc = new SwfDotNet.IO.ByteCode.Decompiler(swf.Version);
                            ArrayList actions = dc.Decompile((byte[])enum2.Current);
                            foreach (BaseAction obj in actions)
                            {
                                this.listBoxActions.Items.Add("       " + obj.ToString());
                            }
                        }
                    }
                }
            }
            this.labelTagsCnt.Text = i.ToString();
        }
Example #31
0
        private void getpackets_Click_1(object sender, EventArgs e)
        {
            {
                TextWriter writer = new TextBoxConsole(tbConsole);
                Console.SetOut(writer);

                string swfPath = Path.Combine(Directory.GetCurrentDirectory(), "client.swf");
                bool   all     = true;


                if (!File.Exists(swfPath))
                {
                    MessageBox.Show("Cant find client.swf.");
                    return;
                }


                Console.WriteLine("Reading swf...");
                SwfReader swfReader = new SwfReader(swfPath);
                Swf       swf       = swfReader.ReadSwf();
                Console.WriteLine("Completed reading the swf!");


                IEnumerator tagsEnu = swf.Tags.GetEnumerator();
                while (tagsEnu.MoveNext())
                {
                    BaseTag tag = (BaseTag)tagsEnu.Current;
                    if (tag.name != null)
                    {
                        if (tag.TagCode == (int)TagCodeEnum.DoABC2 && all)
                        {
                            Console.WriteLine("Extracting...");
                            BinaryWriter abc = new BinaryWriter(File.Open("abcdata.abc", FileMode.Create));
                            for (int i = 0; i < ((DoABC2Tag)tag).ABC.Length; i++)
                            {
                                abc.Write(((DoABC2Tag)tag).ABC[i]);
                            }
                            abc.Close();

                            if (!File.Exists("rabcdasm.exe"))
                            {
                                string tempExeName = Path.Combine(Directory.GetCurrentDirectory(), "rabcdasm.exe");
                                using (FileStream fsDst = new FileStream(tempExeName, FileMode.CreateNew, FileAccess.Write))
                                {
                                    byte[] bytes = Resource1.GetRabcdasmExe();

                                    fsDst.Write(bytes, 0, bytes.Length);
                                }
                            }

                            ProcessStartInfo Info = new ProcessStartInfo();
                            Info.FileName  = "rabcdasm.exe";
                            Info.Arguments = "abcdata.abc";
                            Info.RedirectStandardOutput = true;
                            Info.RedirectStandardError  = true;
                            Info.UseShellExecute        = false;
                            Info.CreateNoWindow         = true;
                            Info.WindowStyle            = ProcessWindowStyle.Hidden;

                            Process processTemp = new Process();
                            processTemp.StartInfo           = Info;
                            processTemp.EnableRaisingEvents = true;
                            try
                            {
                                processTemp.Start();
                                processTemp.WaitForExit();
                            }
                            catch (Exception)
                            {
                                throw;
                            }

                            Console.WriteLine("Extracting completed!");
                            if (File.Exists("abcdata\\kabam\\rotmg\\messaging\\impl\\GameServerConnection.class.asasm"))
                            {
                                Console.WriteLine("Writing Packets.xml...");
                                StreamWriter packets = new StreamWriter("packets.xml");
                                packets.WriteLine("<Packets>");
                                StreamReader read    = new StreamReader("abcdata\\kabam\\rotmg\\messaging\\impl\\GameServerConnection.class.asasm");
                                string       pattern = "QName\\(PackageNamespace\\(\\\"\\\"\\), \\\"(\\w+)\\\"\\) slotid (?:.+) type QName\\(PackageNamespace\\(\\\"\\\"\\), \\\"int\\\"\\) value Integer\\((\\d+)\\)";

                                Regex           rgx     = new Regex(pattern, RegexOptions.IgnoreCase | RegexOptions.Multiline);
                                MatchCollection matches = rgx.Matches(read.ReadToEnd());
                                foreach (Match match in matches)
                                {
                                    if (match.Groups.Count == 3)
                                    {
                                        //Console.WriteLine("{0} = {1}", match.Groups[1].Value, match.Groups[2].Value);
                                        packets.WriteLine("\t<Packet>\n\t\t<PacketName>{0}</PacketName>\n\t\t<PacketID>{1}</PacketID>\n\t</Packet>", match.Groups[1].Value.ToString().Replace("_", ""), match.Groups[2].Value.ToString());
                                    }
                                }
                                packets.WriteLine("</Packets>");
                                packets.Close();
                                Console.WriteLine("Writing Packets.xml done...");

                                string[] a = Directory.GetFiles(Environment.CurrentDirectory, "rabcdasm.exe");
                                Array.ForEach(a, File.Delete);

                                string[] b = Directory.GetFiles(Environment.CurrentDirectory, "abcdata.abc");
                                Array.ForEach(b, File.Delete);
                            }
                            else
                            {
                                Console.WriteLine("Cant find data for packets.xml");
                            }
                        }
                    }
                }
                Thread.Sleep(1000);
                swfReader.Close();
            }
        }
Example #32
0
        static void Main(string[] args)
        {
            //Picture to transform
            string imgPath = "img.jpg";
            //string imgPath = "Untitled-1.bmp";
            //File name of the result swf file
            string path = "test.swf";

            //Load the picture to a GDI image
            Image img       = Image.FromFile(imgPath);
            int   posX      = 0;
            int   posY      = 0;
            int   imgWidth  = img.Width + 100;
            int   imgHeight = img.Height + 100;

            //Create a new Swf instance
            Swf swf = new Swf();

            swf.Size    = new Rect(0, 0, (posX + imgWidth) * 20, (posY + imgHeight) * 20);
            swf.Version = 5;

            //Set the background color tag
            swf.Tags.Add(new SetBackgroundColorTag(255, 255, 255));

            //Set the jpeg tag
            ushort jpegId = swf.GetNewDefineId();

            //Load the jped from an image
            swf.Tags.Add(DefineBitsJpeg2Tag.FromImage(jpegId, img));

            //Define the picture's shape tag
            DefineShapeTag shapeTag = new DefineShapeTag();

            shapeTag.CharacterId = swf.GetNewDefineId();
            shapeTag.Rect        = new Rect(posX * 20 - 1, posY * 20 - 1, (posX + imgWidth) * 20 - 1, (posY + imgHeight) * 20 - 1);
            FillStyleCollection fillStyles = new FillStyleCollection();

            fillStyles.Add(new BitmapFill(FillStyleType.ClippedBitmapFill, ushort.MaxValue, new Matrix(0, 0, 20, 20)));
            fillStyles.Add(new BitmapFill(FillStyleType.ClippedBitmapFill, jpegId, new Matrix(posX * 20 - 1, posY * 20 - 1, (20.0 * imgWidth) / img.Width, (20.0 * imgHeight) / img.Height)));
            LineStyleCollection   lineStyles = new LineStyleCollection();
            ShapeRecordCollection shapes     = new ShapeRecordCollection();

            shapes.Add(new StyleChangeRecord(posX * 20 - 1, posY * 20 - 1, 2));
            shapes.Add(new StraightEdgeRecord(imgWidth * 20, 0));
            shapes.Add(new StraightEdgeRecord(0, imgHeight * 20));
            shapes.Add(new StraightEdgeRecord(-imgWidth * 20, 0));
            shapes.Add(new StraightEdgeRecord(0, -imgHeight * 20));
            shapes.Add(new EndShapeRecord());
            shapeTag.ShapeWithStyle = new ShapeWithStyle(fillStyles, lineStyles, shapes);
            swf.Tags.Add(shapeTag);

            //Place the picture
            swf.Tags.Add(new PlaceObject2Tag(shapeTag.CharacterId, 1, 0, 0));
            //Add a frame
            swf.Tags.Add(new ShowFrameTag());
            swf.Tags.Add(new EndTag());

            //Write the swf to a file
            SwfWriter writer = new SwfWriter(path);

            writer.Write(swf);
            writer.Close();
            img.Dispose();
        }