static void OriginalMain()
        {
            var done = false;
            var sw = new Stopwatch();

            sw.Start();
            for (var i = 0; i < N; i++)
            {
                var jintEngine = new Jint.Engine();
                jintEngine.Execute(currentScript);
                done = jintEngine.GetValue("done").AsBoolean();
            }
            sw.Stop();
            Console.WriteLine("jint: " + sw.ElapsedMilliseconds / N + " - " + done);

            done = false;
            sw.Restart();
            for (var i = 0; i < N; i++)
            {
                var ironjsEngine = new IronJS.Hosting.CSharp.Context();
                ironjsEngine.Execute(currentScript);
                done = ironjsEngine.GetGlobalAs<bool>("done");
            }
            sw.Stop();
            Console.WriteLine("ironjs: " + sw.ElapsedMilliseconds / N + " - " + done);

            done = false;
            sw.Restart();
            for (var i = 0; i < N; i++)
            {
                using (var jsNetEngine = new Noesis.Javascript.JavascriptContext())
                {
                    jsNetEngine.Run(currentScript);
                    done = (bool)jsNetEngine.GetParameter("done");
                }
            }
            sw.Stop();
            Console.WriteLine("js.net: " + sw.ElapsedMilliseconds / N + " - " + done);

            done = false;
            sw.Restart();
            for (var i = 0; i < N; i++)
            {
                var jurassicEngine = new Jurassic.ScriptEngine();
                jurassicEngine.Execute(currentScript);
                done = jurassicEngine.GetGlobalValue<bool>("done");
            }
            sw.Stop();
            Console.WriteLine("jurassic: " + sw.ElapsedMilliseconds / N + " - " + done);

            done = false;
            sw.Restart();
            for (var i = 0; i < N; i++)
            {
                using (var clearscriptV8 = new Microsoft.ClearScript.V8.V8ScriptEngine())
                {
                    clearscriptV8.Execute(currentScript);
                    done = clearscriptV8.Script.done;
                }
            }
            sw.Stop();
            Console.WriteLine("clearscriptV8: " + sw.ElapsedMilliseconds / N + " - " + done);

            done = false;
            sw.Restart();
            using (var clearscriptV8 = new Microsoft.ClearScript.V8.V8Runtime())
            {
                var compiled = clearscriptV8.Compile(currentScript);
                for (var i = 0; i < N; i++)
                {
                    using (var engine = clearscriptV8.CreateScriptEngine())
                    {
                        engine.Evaluate(compiled);
                        done = engine.Script.done;
                    }
                }
            }
            sw.Stop();
            Console.WriteLine("clearscriptV8 compiled: " + sw.ElapsedMilliseconds / N + " - " + done);

            done = false;
            sw.Restart();
            for (var i = 0; i < N; i++)
            {
                var nilcontext = new NiL.JS.Core.Context();
                nilcontext.Eval(currentScript);
                done = (bool)nilcontext.GetVariable("done");
            }
            sw.Stop();
            Console.WriteLine("niljs: " + sw.ElapsedMilliseconds / N + " - " + done);

            Console.Read();
        }
        public JavaScriptRunner(IFeedback<LogEntry> log, ICommandProcessor commandProcessor, IEntityContextConnection entityContextConnection)
        {
            if (log == null)
                throw new ArgumentNullException("log");

            if (commandProcessor == null)
                throw new ArgumentNullException("commandProcessor");

            if (entityContextConnection == null)
                throw new ArgumentNullException("entityContextConnection");

            Log = log;
            CommandProcessor = commandProcessor;
            EntityContextConnection = entityContextConnection;
            log.Source = "JavaScript Runner";

            JintEngine = new Jint.Engine(cfg =>
            {
                cfg.AllowClr();
                cfg.AllowDebuggerStatement(JavascriptDebugEnabled);
            });
            //JintEngine.Step += async (s, info) =>
            //{
            //    await Log.ReportInfoFormatAsync(CancellationToken.None, "{1} {2}",
            //         info.CurrentStatement.Source.Start.Line,
            //         info.CurrentStatement.Source.Code.Replace(Environment.NewLine, ""));
            //};

        }
Beispiel #3
0
        public static object ExeConfig(Models.Code code, WebSite site)
        {
            RenderContext context = new RenderContext();

            context.WebSite = site;
            var engine   = new Jint.Engine(JintSetting.SetOption);
            var kcontext = new k(context);

            engine.SetValue("k", kcontext);

            var k = engine.GetValue("k");

            kcontext.ReturnValues.Clear();
            try
            {
                engine.Execute(code.Config);
            }
            catch (System.Exception ex)
            {
            }

            if (kcontext.ReturnValues.Count() > 0)
            {
                return(kcontext.ReturnValues.Last());
            }
            return(null);
        }
Beispiel #4
0
        public bool Process(FileInfo file)
        {
            Jint.Engine engine = new Jint.Engine(cfg => cfg.AllowClr(
                                                     Assembly.GetAssembly(typeof(TagLib.File)),
                                                     Assembly.GetAssembly(typeof(Daramee.FileTypeDetector.IDetector)),
                                                     Assembly.GetAssembly(typeof(Daramkun.DaramRenamer.IProcessor))
                                                     ));
            engine.SetValue("file", file);

            var delegates = ProcessorExtensions.Delegates;

            foreach (Delegate dele in delegates)
            {
                engine.SetValue(dele.Method.Name, dele);
            }

            try
            {
                Jint.Engine proceed = engine.Execute(Script);
                return(proceed.GetCompletionValue().AsBoolean());
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.StackTrace);
                return(false);
            }
        }
Beispiel #5
0
        static void classAccessExceptions()
        {
            var engine  = new Jint.Engine();
            var someObj = new SomeClass(21, "12");

            engine.SetValue("someObj", someObj);
            engine.SetValue("callback", new Action <string>(s => { Console.WriteLine($"callback from js: {s}"); }));

            void runJs(string js)
            {
                try
                {
                    engine.Execute(js);
                    Console.WriteLine($"script <{js}> ran without issue");
                }
                catch (Exception e)
                {
                    Console.WriteLine($"script <{js}> threw {e.GetType()}: {e.Message}");
                }
            }

            runJs("callback(someObj)");
            runJs("callback(someObj.privateReadonlyString");
            runJs("someObj.publicReadonlyString = 'foo'");
            runJs("callback(someObj.publicReadonlyString)");
            Console.WriteLine($"someObj.publicReadonlyString: {someObj.publicReadonlyString}");
        }
Beispiel #6
0
 /* you must add this inside < Project > tag in your .csproj file
  * <ItemGroup>
  *  <PackageReference Include="Jint" Version="3.0.0-beta-1828"/>
  * </ItemGroup>
  */
 public DartConnector(string sourcePath)
 {
     engine = new Jint.Engine();
     engine.SetValue("CS_GD__Print", new Action <object>(o => GD.Print(o)));
     engine.SetValue("print", new Action <object>(o => GD.Print(o)));
     engine.SetValue("self", "this");
     engine.Execute(new StreamReader(sourcePath).ReadToEnd());
 }
Beispiel #7
0
        /// <summary>
        /// 通过js脚本执行获取时间戳
        /// </summary>
        /// <returns></returns>
        public static string getUnixTimestamp()
        {
            string cmd    = "function timeToken(){var t=0; var n=(new Date).getTime();return n<=t&&(n=t+1),t=n};";
            var    engine = new Jint.Engine().Execute(cmd).GetValue("timeToken");
            string stamp  = engine.Invoke().ToString();

            return(stamp);
        }
Beispiel #8
0
        public Handlebars(Jint.Engine engine)
        {
            Guard.AgainstNull(engine, "engine");
            this.engine = engine;
            var handlebarsJsText = GetHandlebarsJsText();

            engine.Execute(handlebarsJsText);
        }
Beispiel #9
0
        public static string ToJson(ObjectInstance objInstance, Jint.Engine jintEngine)
        {
            var o     = objInstance as Jint.Native.Object.ObjectInstance;
            var s     = new JsonSerializer(jintEngine);
            var ojson = s.Serialize(o, JsValue.Undefined, JsValue.Undefined).AsString();

            return(ojson);
        }
Beispiel #10
0
        public async Task Initialize(IManager mgr)
        {
            bool firstRun = ScriptEngine == null;

            // it's been loaded before so we need to call the unload event
            if (!firstRun)
            {
                await OnUnloadAsync();
            }

            Manager = mgr;
            string script;

            using (var stream = new FileStream(FileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            {
                using (var reader = new StreamReader(stream, Encoding.Default))
                {
                    script = await reader.ReadToEndAsync();
                }
            }

            ScriptEngine = new Jint.Engine(cfg =>
                                           cfg.AllowClr(new[]
            {
                typeof(System.Net.Http.HttpClient).Assembly,
                typeof(EFClient).Assembly,
            })
                                           .CatchClrExceptions());

            ScriptEngine.Execute(script);
            ScriptEngine.SetValue("_localization", Utilities.CurrentLocalization);
            dynamic pluginObject = ScriptEngine.GetValue("plugin").ToObject();

            this.Author  = pluginObject.author;
            this.Name    = pluginObject.name;
            this.Version = (float)pluginObject.version;


            try
            {
                if (pluginObject.isParser)
                {
                    await OnLoadAsync(mgr);

                    IEventParser eventParser = (IEventParser)ScriptEngine.GetValue("eventParser").ToObject();
                    IRConParser  rconParser  = (IRConParser)ScriptEngine.GetValue("rconParser").ToObject();
                    Manager.AdditionalEventParsers.Add(eventParser);
                    Manager.AdditionalRConParsers.Add(rconParser);
                }
            }
            catch { }


            if (!firstRun)
            {
                await OnLoadAsync(mgr);
            }
        }
Beispiel #11
0
        public static BlocksInstance CreateObject(Jint.Engine engine)
        {
            var e = new BlocksInstance(engine);

            e.Extensible = true;
            e.Prototype  = engine.Object.PrototypeObject;

            return(e);
        }
Beispiel #12
0
        public override void Dispose()
        {
            if (!_disposed)
            {
                _disposed = true;

                _jsEngine = null;
            }
        }
Beispiel #13
0
        void CreateEngine()
        {
            engine = new Jint.Engine(x =>
            {
                x.AllowClr(
                    typeof(System.Convert).Assembly,
#if UNITY_EDITOR
                    typeof(UnityEditor.EditorWindow).Assembly,
                    typeof(UnityEngine.GUILayout).Assembly,
                    typeof(UnityEngine.UIElements.StyleLength).Assembly,
#endif
                    typeof(UnityEngine.Vector3).Assembly,
                    typeof(UnityEngine.Component).Assembly,
                    typeof(ReactUnityRunner).Assembly
                    );
                x.CatchClrExceptions(ex =>
                {
                    Debug.LogException(ex);
                    return(true);
                });
            });

            engine.SetValue("log", new Func <object, object>((x) => { Debug.Log(x); return(x); }));
            engine.Execute("__dirname = '';");
            engine.Execute("WeakMap = Map;");
            engine.Execute("globalThis = global = window = parent = this;");
            engine.Execute("setTimeout = setInterval = clearTimeout = clearInterval = null;");
            engine.Execute("btoa = atob = null;");
            engine.Execute("process = { env: { NODE_ENV: 'production' }, argv: [], on: () => {} };");

            engine.SetValue("Engine", engine);
            engine.SetValue("Callback", typeof(Callback));

            CreateConsole(engine);
            CreateLocalStorage(engine);
            CreateScheduler(engine, context);

            engine.SetValue("importType", new ClrFunctionInstance(
                                engine,
                                "importType",
                                func: (thisObj, arguments) => TypeReference.CreateTypeReference(engine,
                                                                                                ReflectionHelpers.FindType(TypeConverter.ToString(arguments.At(0)),
                                                                                                                           arguments.Length > 1 ? TypeConverter.ToBoolean(arguments.At(1)) : false))));

            engine.SetValue("UnityEngine", new Jint.Runtime.Interop.NamespaceReference(engine, "UnityEngine"));
            engine.SetValue("ReactUnity", new Jint.Runtime.Interop.NamespaceReference(engine, "ReactUnity"));
            engine.SetValue("Facebook", new Jint.Runtime.Interop.NamespaceReference(engine, "Facebook"));
#if UNITY_EDITOR
            engine.SetValue("UnityEditor", new Jint.Runtime.Interop.NamespaceReference(engine, "UnityEditor"));
#endif

            // Load polyfills
            engine.Execute(Resources.Load <TextAsset>("ReactUnity/polyfills/promise").text);
            engine.Execute(Resources.Load <TextAsset>("ReactUnity/polyfills/base64").text);
            engine.Execute(Resources.Load <TextAsset>("ReactUnity/polyfills/fetch").text);
        }
Beispiel #14
0
        private Task LoadJs()
        {
            _engine = new Jint.Engine(options =>
            {
                options.Culture(CultureInfo.CurrentCulture);
                options.DebugMode();
            });

            return(Task.CompletedTask);
        }
Beispiel #15
0
 public JavaScriptEngine(bool safeHost, HtmlDocument doc, object window)
 {
     Engine = new Jint.Engine(cfg => {
         cfg.AllowClr()
                                 #if NETFX_CORE
         .AllowClr(typeof(GameObject).GetTypeInfo().Assembly);
                                 #else
         .AllowClr(typeof(GameObject).Assembly);
                                 #endif
     });
Beispiel #16
0
        public static JsValue GetValueByPath(this JSEngine engine, params string[] path)
        {
            JsValue value = engine.GetValue(path[0]);

            for (int i = 1; i < path.Length; ++i)
            {
                value = engine.GetValue(value, path[i]);
            }
            return(value);
        }
 public override void Dispose()
 {
     if (_disposedFlag.Set())
     {
         lock (_executionSynchronizer)
         {
             _jsEngine = null;
         }
     }
 }
Beispiel #18
0
        public static List <JsValue> MakeJsValues(List <object> os, Jint.Engine engine)
        {
            var l = new List <JsValue>();

            foreach (var o in os)
            {
                l.Add(MakeJsValue(o, engine));
            }
            return(l);
        }
Beispiel #19
0
        public Platform(Jint.Engine engine, MusicProvider musicProvider, ISettingsService settingsService, IMvxNavigationService mvxNavigationService, IAuthenticationService authenticationService, IMvxLogProvider logProvider)
        {
            _engine        = engine;
            _musicProvider = musicProvider;

            _settingsService       = settingsService;
            _mvxNavigationService  = mvxNavigationService;
            _authenticationService = authenticationService;
            _logProvider           = logProvider;
        }
        public bool TryConvert(OriginalEngine engine, object value, out OriginalValue result)
        {
            if (value is Undefined)
            {
                result = OriginalValue.Undefined;
                return(true);
            }

            result = OriginalValue.Null;
            return(false);
        }
        private static async Task Run(string url)
        {
            var baseUrl   = new Uri(url);
            var configUrl = new Uri(baseUrl, "standalone/config.js");

            var configJs = await LoadStringAsync(configUrl.ToString());

            var engine = new JintEngine();

            engine.Execute(configJs);

            var urlObj            = engine.Global.GetObject("config").url;
            var configurationUrl  = new Uri(baseUrl, urlObj.configuration);
            var configurationJson = await LoadStringAsync(configurationUrl.ToString());

            var configuration = JsonConvert.DeserializeObject <ConfigurationModel>(configurationJson);

            string updateUrlFormat = ((string)urlObj.update).Replace("{world}", "{0}").Replace("{timestamp}", "{1}");

            var update = new UpdateModel {
                timestamp = 0
            };

            while (true)
            {
                var updateUrl  = new Uri(baseUrl, string.Format(updateUrlFormat, "Main", update.timestamp));
                var updateJson = await LoadStringAsync(updateUrl.ToString());

                update = JsonConvert.DeserializeObject <UpdateModel>(updateJson);

                foreach (var updateData in update.updates)
                {
                    switch (updateData.type)
                    {
                    case "tile": continue;

                    case "playerjoin":
                    case "playerquit":
                        Console.WriteLine($"[{DateTime.Now:dd HH:mm:ss}] {updateData.type} {updateData.playerName}");
                        break;

                    case "chat":
                        Console.WriteLine($"[{DateTime.Now:dd HH:mm:ss}] {updateData.playerName}({updateData.source}): {updateData.message}");
                        break;

                    default:
                        Console.WriteLine($"[{DateTime.Now:dd HH:mm:ss}] {updateData.type}");
                        break;
                    }
                }

                await Task.Delay(TimeSpan.FromMilliseconds(configuration.updaterate));
            }
        }
Beispiel #22
0
 /// <summary>
 /// 获取好友列表时计算的Hash参数 v2014.06.14更新
 /// </summary>
 /// <param name="uin"></param>
 /// <param name="ptwebqq"></param>
 /// <returns></returns>
 public static string GetHash(string uin, string ptwebqq)
 {
     const string url = "https://raw.githubusercontent.com/im-qq/webqq-core/master/src/main/resources/hash.js";
     var js = Resource.LoadResourceAsync("hash.js", url, item => item.ToString(Encoding.UTF8)).Result;
     object[] args = { uin, ptwebqq };
     var code = string.Format("hash('{0}','{1}')", args);
     var engine = new Jint.Engine();
     engine.Execute(js);
     var s = engine.Execute(code).GetCompletionValue().AsString();
     return s;
 }
Beispiel #23
0
        public void EqualsDictionaryHandling()
        {
            //Generate a basic javascript model from a C# class

            var modelType = typeof(CollectionTesting);

            var outputJs = JsGenerator.Generate(new[] { modelType }, new JsGeneratorOptions()
            {
                ClassNameConstantsToRemove = new List <string>()
                {
                    "Dto"
                },
                CamelCase                    = true,
                IncludeMergeFunction         = true,
                OutputNamespace              = "models",
                RespectDataMemberAttribute   = true,
                RespectDefaultValueAttribute = true,
                IncludeEqualsFunction        = true
            });

            Assert.IsTrue(!string.IsNullOrEmpty(outputJs));


            var js = new Jint.Parser.JavaScriptParser();



            try
            {
                js.Parse(outputJs);
            }
            catch (Exception ex)
            {
                Assert.Fail("Expected no exception parsing javascript, but got: " + ex.Message);
            }

            var strToExecute = "this.models = {};\r\n" + outputJs + ";\r\n" + $"var p1 = new models.CollectionTesting({{ dictionaryCollection: {{ 'Prop1' : 'Test' }} }});\r\n" +
                               $"var p2 = new models.CollectionTesting({{ dictionaryCollection: {{ 'Prop1' : 'Test' }} }});\r\n" +
                               $"var result = p1.$equals(p2);";

            var jsEngine = new Jint.Engine().Execute(strToExecute);
            var res      = (bool)jsEngine.GetValue("result").ToObject();

            Assert.IsTrue(res);

            var strToExecuteNotEqual = "this.models = {};\r\n" + outputJs + ";\r\n" + $"var p1 = new models.CollectionTesting({{ dictionaryCollection: {{ 'Prop1' : 'Test' }} }});\r\n" +
                                       $"var p2 = new models.CollectionTesting({{ dictionaryCollection: {{ 'Prop1' : 'Test2' }} }});\r\n" +
                                       $"var result = p1.$equals(p2);";

            var jsEngineNotEqual = new Jint.Engine().Execute(strToExecuteNotEqual);
            var resNotEqual      = (bool)jsEngineNotEqual.GetValue("result").ToObject();

            Assert.IsFalse(resNotEqual);
        }
Beispiel #24
0
        internal object GetValueFromJsEngine(GetValueQuery query, Jint.Engine engine)
        {
            if (engine == null)
            {
                return(null);
            }

            if (query.IsMember)
            {
                var jsvalue = engine.GetValue(query.MemberName);
                if (jsvalue != null && jsvalue.Type != Jint.Runtime.Types.Undefined)
                {
                    return(jsvalue.ToObject());
                }
            }
            else
            {
                var value = engine.GetValue(query.Key);

                if (value != null && value.Type != Jint.Runtime.Types.Undefined)
                {
                    string[] subs = query.SubProperty.Split(".".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);

                    object rightvalue = value;

                    foreach (var sub in subs)
                    {
                        rightvalue = getMember(rightvalue, sub);
                        if (rightvalue == null)
                        {
                            break;
                        }
                    }

                    if (rightvalue != null)
                    {
                        if (rightvalue is Jint.Native.JsValue)
                        {
                            var jsvalue = rightvalue as Jint.Native.JsValue;
                            if (jsvalue != null && jsvalue.Type != Jint.Runtime.Types.Undefined)
                            {
                                return(jsvalue.ToObject());
                            }
                        }
                        else
                        {
                            return(rightvalue);
                        }
                    }
                }
            }

            return(null);
        }
Beispiel #25
0
        public static void Initialize()
        {
            TickRate = Shared.Settings.TickRate;
            if (!System.IO.File.Exists("serverconfig.xml"))
            {
                Console.WriteLine("Config file not found...");
                System.Threading.Thread.Sleep(5000);
                System.Diagnostics.Process.GetCurrentProcess().Kill();
            }
            XmlDocument Config = new XmlDocument();

            Config.Load("serverconfig.xml");
            Port       = int.Parse(Config.DocumentElement.SelectSingleNode("/config/serverport").InnerText);
            MaxPlayers = int.Parse(Config.DocumentElement.SelectSingleNode("/config/maxplayers").InnerText);
            XmlNodeList Resources = Config.DocumentElement.SelectNodes("/config/resource");

            NetPeerConfiguration NetConfig = new NetPeerConfiguration("ivmp");

            NetConfig.MaximumConnections = MaxPlayers;
            NetConfig.Port = Port;
            NetConfig.ConnectionTimeout = 50;
            NetConfig.EnableMessageType(NetIncomingMessageType.ConnectionApproval);
            NetConfig.EnableMessageType(NetIncomingMessageType.StatusChanged);
            NetServer = new NetServer(NetConfig);
            NetServer.Start();
            PlayersController  = new PlayersController();
            VehiclesController = new VehiclesController();
            ResourcesManager   = new Shared.Scripting.ResourcesManager();
            EventsManager      = new Shared.Scripting.EventsManager();
            Engine             = new Jint.Engine();

            // load resources
            foreach (XmlNode Resource in Resources)
            {
                try
                {
                    ResourcesManager.Load(Resource.Attributes["name"].InnerText);
                    ResourcesManager.Start(Resource.Attributes["name"].InnerText);
                }
                catch (Exception)
                {
                }
            }

            Timer tick = new Timer();

            tick.Elapsed += OnTick;
            tick.Interval = TickRate;
            tick.Enabled  = true;
            tick.Start();
            Console.WriteLine("Started game server on Port " + Port);
            Console.WriteLine("Max Players: " + MaxPlayers);
        }
Beispiel #26
0
        public static ObjectInstance ObjectFromJson(string json, Jint.Engine engine)
        {
            var p       = new JsonParser(engine);
            var jsValue = p.Parse(json);
            var o       = jsValue.TryCast <ObjectInstance>();

            if (o == null)
            {
                throw new ArgumentException(string.Format("json cannot parsed into an object. json:{0}", json));
            }
            return(o);
        }
Beispiel #27
0
 void CreateScheduler(Jint.Engine engine)
 {
     scheduler = new UnityScheduler();
     engine.SetValue("UnityScheduler", scheduler);
     engine.Execute("global.setTimeout = function setTimeout(fun, delay) { return UnityScheduler.setTimeout(new Callback(fun), delay); }");
     engine.Execute("global.setInterval = function setInterval(fun, delay) { return UnityScheduler.setInterval(new Callback(fun), delay); }");
     engine.Execute("global.setImmediate = function setImmediate(fun) { return UnityScheduler.setImmediate(new Callback(fun)); }");
     engine.Execute("global.requestAnimationFrame = function requestAnimationFrame(fun) { return UnityScheduler.requestAnimationFrame(new Callback(fun)); }");
     engine.SetValue("clearTimeout", new Action <int?>(scheduler.clearTimeout));
     engine.SetValue("clearInterval", new Action <int?>(scheduler.clearInterval));
     engine.SetValue("clearImmediate", new Action <int?>(scheduler.clearImmediate));
     engine.SetValue("cancelAnimationFrame", new Action <int?>(scheduler.cancelAnimationFrame));
 }
Beispiel #28
0
        private static string RsaQQ(long uin, string password, string verifyCode)
        {
            var js = Resource.LoadLocalResource("encrypt.js", stream => stream.ToString(Encoding.UTF8));

            object[] args   = { password, uin, verifyCode.ToUpper(), IsMd5(password).ToString().ToLower() };
            var      code   = string.Format("getEncryption('{0}','{1}','{2}',{3})", args);
            var      engine = new Jint.Engine();

            engine.Execute(js);
            var s = engine.Execute(code).GetCompletionValue().AsString();

            return(s);
        }
Beispiel #29
0
        void CreateLocation(Jint.Engine engine, ReactScript script)
        {
            var location = new DomProxies.Location(script.SourceLocation, Restart);

            engine.SetValue("location", location);

#if UNITY_EDITOR
            engine.SetValue("WebSocket", typeof(WebSocketProxy));
            engine.SetValue("oldXMLHttpRequest", typeof(XMLHttpRequest));
            engine.Execute(@"XMLHttpRequest = function() { return new oldXMLHttpRequest('" + location.origin + @"'); }");
#endif
            engine.SetValue("document", new DocumentProxy(unityContext, this, location.origin));
        }
Beispiel #30
0
        static void exceptions()
        {
            var engine = new Jint.Engine();

            try
            {
                engine.Execute("not_a_function()");
            }
            catch (Exception e)
            {
                Console.WriteLine($"caught expected exception: {e.Message}, {e.GetType()}");
            }
        }
Beispiel #31
0
        void CreateLocation(Jint.Engine engine)
        {
            engine.SetValue("location", context.Location);

            engine.Execute(@"WebSocket = function(url) { return new WebSocket.original(Context, url); }");
            engine.Execute(@"XMLHttpRequest = function() { return new XMLHttpRequest.original(Context, location.origin); }");
            (engine.GetValue(@"WebSocket") as FunctionInstance)
            .FastSetProperty("original", new Jint.Runtime.Descriptors.PropertyDescriptor(TypeReference.CreateTypeReference(engine, typeof(WebSocketProxy)), false, false, false));
            (engine.GetValue(@"XMLHttpRequest") as FunctionInstance)
            .FastSetProperty("original", new Jint.Runtime.Descriptors.PropertyDescriptor(TypeReference.CreateTypeReference(engine, typeof(XMLHttpRequest)), false, false, false));

            engine.SetValue("document", new DocumentProxy(context, this.ExecuteScript, context.Location.origin));
        }
Beispiel #32
0
        public static void ExchangeDebugInfo(Guid CodeId, DebugSession debugsession, Jint.Engine engine)
        {
            engine.BreakPoints.Clear();

            foreach (var item in debugsession.BreakLines.Where(w => w.codeId == CodeId))
            {
                engine.BreakPoints.Add(new Jint.Runtime.Debugger.BreakPoint(item.Line, 0));
            }

            debugsession.JsEngine      = engine;
            debugsession.CurrentCodeId = CodeId;
            debugsession.End           = false;
        }
Beispiel #33
0
        public static DebugVariables GetVariables(Jint.Engine engines)
        {
            DebugVariables variables = new DebugVariables();

            if (engines.ExecutionContext.LexicalEnvironment != null)
            {
                var lexicalEnvironment = engines.ExecutionContext.LexicalEnvironment;

                variables.Local  = GetLocalVariables(lexicalEnvironment);
                variables.Global = GetGlobalVariables(lexicalEnvironment);
            }

            return(variables);
        }
Beispiel #34
0
 private static string RsaQQ(long uin, string password, string verifyCode)
 {
     var js = Resource.LoadLocalResource("encrypt.js", stream => stream.ToString(Encoding.UTF8));
     object[] args = { password, uin, verifyCode.ToUpper(), IsMd5(password).ToString().ToLower() };
     var code = string.Format("getEncryption('{0}','{1}','{2}',{3})", args);
     var engine = new Jint.Engine();
     engine.Execute(js);
     var s = engine.Execute(code).GetCompletionValue().AsString();
     return s;
 }
Beispiel #35
0
        public static void Initialize()
        {
            TickRate = Shared.Settings.TickRate;
            if (!System.IO.File.Exists("serverconfig.xml"))
            {
                Console.WriteLine("Config file not found...");
                System.Threading.Thread.Sleep(5000);
                System.Diagnostics.Process.GetCurrentProcess().Kill();
            }
            XmlDocument Config = new XmlDocument();
            Config.Load("serverconfig.xml");
            Port = int.Parse(Config.DocumentElement.SelectSingleNode("/config/serverport").InnerText);
            MaxPlayers = int.Parse(Config.DocumentElement.SelectSingleNode("/config/maxplayers").InnerText);
            XmlNodeList Resources = Config.DocumentElement.SelectNodes("/config/resource");

            NetPeerConfiguration NetConfig = new NetPeerConfiguration("ivmp");
            NetConfig.MaximumConnections = MaxPlayers;
            NetConfig.Port = Port;
            NetConfig.ConnectionTimeout = 50;
            NetConfig.EnableMessageType(NetIncomingMessageType.ConnectionApproval);
            NetConfig.EnableMessageType(NetIncomingMessageType.StatusChanged);
            NetServer = new NetServer(NetConfig);
            NetServer.Start();
            PlayersController = new PlayersController();
            VehiclesController = new VehiclesController();
            ResourcesManager = new Shared.Scripting.ResourcesManager();
            EventsManager = new Shared.Scripting.EventsManager();
            Engine = new Jint.Engine();

            // load resources
            foreach (XmlNode Resource in Resources)
            {
                try
                {
                    ResourcesManager.Load(Resource.Attributes["name"].InnerText);
                    ResourcesManager.Start(Resource.Attributes["name"].InnerText);
                }
                catch(Exception)
                {
                }
            }

            Timer tick = new Timer();
            tick.Elapsed += OnTick;
            tick.Interval = TickRate;
            tick.Enabled = true;
            tick.Start();
            Console.WriteLine("Started game server on Port " + Port);
            Console.WriteLine("Max Players: " + MaxPlayers);
        }
        /// <summary>
        /// Tries to return a webclient with the neccessary cookies installed to do requests for a cloudflare protected website.
        /// </summary>
        /// <param name="url">The page which is behind cloudflare's anti-dDoS protection</param>
        /// <returns>A WebClient object or null on failure</returns>
        public static WebClientEx CreateBypassedWebClient(string url)
        {
            var JSEngine = new Jint.Engine(); //Use this JavaScript engine to compute the result.

            //Download the original page
            var uri = new Uri(url);
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.UserAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:40.0) Gecko/20100101 Firefox/40.0";
            //Try to make the usual request first. If this fails with a 503, the page is behind cloudflare.
            try
            {
                var res = req.GetResponse();
                string html = "";
                using (var reader = new StreamReader(res.GetResponseStream()))
                    html = reader.ReadToEnd();
                return new WebClientEx();
            }
            catch (WebException ex) //We usually get this because of a 503 service not available.
            {
                string html = "";
                using (var reader = new StreamReader(ex.Response.GetResponseStream()))
                    html = reader.ReadToEnd();
                //If we get on the landing page, Cloudflare gives us a User-ID token with the cookie. We need to save that and use it in the next request.
                var cookie_container = new CookieContainer();
                //using a custom function because ex.Response.Cookies returns an empty set ALTHOUGH cookies were sent back.
                var initial_cookies = GetAllCookiesFromHeader(ex.Response.Headers["Set-Cookie"], uri.Host);
                foreach (Cookie init_cookie in initial_cookies)
                    cookie_container.Add(init_cookie);

                /* solve the actual challenge with a bunch of RegEx's. Copy-Pasted from the python scrapper version.*/
                var challenge = Regex.Match(html, "name=\"jschl_vc\" value=\"(\\w+)\"").Groups[1].Value;
                var challenge_pass = Regex.Match(html, "name=\"pass\" value=\"(.+?)\"").Groups[1].Value;

                var builder = Regex.Match(html, @"setTimeout\(function\(\){\s+(var t,r,a,f.+?\r?\n[\s\S]+?a\.value =.+?)\r?\n").Groups[1].Value;
                builder = Regex.Replace(builder, @"a\.value =(.+?) \+ .+?;", "$1");
                builder = Regex.Replace(builder, @"\s{3,}[a-z](?: = |\.).+", "");

                //Format the javascript..
                builder = Regex.Replace(builder, @"[\n\\']", "");

                //Execute it.
                long solved = long.Parse(JSEngine.Execute(builder).GetCompletionValue().ToObject().ToString());
                solved += uri.Host.Length; //add the length of the domain to it.

                Console.WriteLine("***** SOLVED CHALLENGE ******: " + solved);
                Thread.Sleep(3000); //This sleeping IS requiered or cloudflare will not give you the token!!

                //Retreive the cookies. Prepare the URL for cookie exfiltration.
                string cookie_url = string.Format("{0}://{1}/cdn-cgi/l/chk_jschl", uri.Scheme, uri.Host);
                var uri_builder = new UriBuilder(cookie_url);
                var query = HttpUtility.ParseQueryString(uri_builder.Query);
                //Add our answers to the GET query
                query["jschl_vc"] = challenge;
                query["jschl_answer"] = solved.ToString();
                query["pass"] = challenge_pass;
                uri_builder.Query = query.ToString();

                //Create the actual request to get the security clearance cookie
                HttpWebRequest cookie_req = (HttpWebRequest)WebRequest.Create(uri_builder.Uri);
                cookie_req.AllowAutoRedirect = false;
                cookie_req.CookieContainer = cookie_container;
                cookie_req.Referer = url;
                cookie_req.UserAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:40.0) Gecko/20100101 Firefox/40.0";
                //We assume that this request goes through well, so no try-catch
                var cookie_resp = (HttpWebResponse)cookie_req.GetResponse();
                //The response *should* contain the security clearance cookie!
                if (cookie_resp.Cookies.Count != 0) //first check if the HttpWebResponse has picked up the cookie.
                    foreach (Cookie cookie in cookie_resp.Cookies)
                        cookie_container.Add(cookie);
                else //otherwise, use the custom function again
                {
                    //the cookie we *hopefully* received here is the cloudflare security clearance token.
                    if (cookie_resp.Headers["Set-Cookie"] != null)
                    {
                        var cookies_parsed = GetAllCookiesFromHeader(cookie_resp.Headers["Set-Cookie"], uri.Host);
                        foreach (Cookie cookie in cookies_parsed)
                            cookie_container.Add(cookie);
                    }
                    else
                    {
                        //No security clearence? something went wrong.. return null.
                        //Console.WriteLine("MASSIVE ERROR: COULDN'T GET CLOUDFLARE CLEARANCE!");
                        return null;
                    }
                }
                //Create a custom webclient with the two cookies we already acquired.
                WebClientEx modedWebClient = new WebClientEx(cookie_container);
                modedWebClient.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:40.0) Gecko/20100101 Firefox/40.0");
                modedWebClient.Headers.Add("Referer", url);
                return modedWebClient;
            }
        }
Beispiel #37
0
 private static void ExecuteWithJint(Test test)
 {
     Execute("jint", test, () =>
     {
         var jintEngine = new Jint.Engine();
         jintEngine.Execute(test.Content);
     });
 }
Beispiel #38
0
        public void EqualsHandling()
        {
            //Generate a basic javascript model from a C# class

            var modelType = typeof(AddressInformation);

            var outputJs = JsGenerator.Generate(new[] { modelType }, new JsGeneratorOptions()
            {
                ClassNameConstantsToRemove = new List<string>() { "Dto" },
                CamelCase = true,
                IncludeMergeFunction = true,
                OutputNamespace = "models",
                RespectDataMemberAttribute = true,
                RespectDefaultValueAttribute = true,
                IncludeEqualsFunction = true
            });

            Assert.IsTrue(!string.IsNullOrEmpty(outputJs));

            var js = new Jint.Parser.JavaScriptParser();

            try
            {
                js.Parse(outputJs);

            }
            catch (Exception ex)
            {
                Assert.Fail("Expected no exception parsing javascript, but got: " + ex.Message);
            }

            var strToExecute = "this.models = {};\r\n" + outputJs + ";\r\n" + $"var p1 = new models.AddressInformation({{ name: 'Test' }});\r\n" +
                               $"var p2 = new models.AddressInformation({{ name: 'Test' }});\r\n" +
                               $"var result = p1.$equals(p2);";

            var jsEngine = new Jint.Engine().Execute(strToExecute);
            var res = (bool)jsEngine.GetValue("result").ToObject();

            Assert.IsTrue(res);

            var strToExecuteNotEqual = "this.models = {};\r\n" + outputJs + ";\r\n" + $"var p1 = new models.AddressInformation({{ name: 'Test' }});\r\n" +
                               $"var p2 = new models.AddressInformation({{ name: 'Test2' }});\r\n" +
                               $"var result = p1.$equals(p2);";

            var jsEngineNotEqual = new Jint.Engine().Execute(strToExecuteNotEqual);
            var resNotEqual = (bool)jsEngineNotEqual.GetValue("result").ToObject();

            Assert.IsFalse(resNotEqual);
        }
Beispiel #39
0
        static void Main()
        {
            const bool runIronJs = true;
            const bool runJint = true;
            const bool runJurassic = true;

            const int iterations = 1000;
            const bool reuseEngine = false;

            var watch = new Stopwatch();


            if (runIronJs)
            {
                IronJS.Hosting.CSharp.Context ironjs;
                ironjs = new IronJS.Hosting.CSharp.Context();
                ironjs.Execute(Script);
                watch.Restart();
                for (var i = 0; i < iterations; i++)
                {
                    if (!reuseEngine)
                    {
                        ironjs = new IronJS.Hosting.CSharp.Context();
                    }

                    ironjs.Execute(Script);
                }

                Console.WriteLine("IronJs: {0} iterations in {1} ms", iterations, watch.ElapsedMilliseconds);
            }

            if (runJint)
            {
                Engine jint;
                jint = new Engine();
                jint.Execute(Script);

                watch.Restart();
                for (var i = 0; i < iterations; i++)
                {
                    if (!reuseEngine)
                    {
                        jint = new Jint.Engine();
                    }

                    jint.Execute(Script);
                }

                Console.WriteLine("Jint: {0} iterations in {1} ms", iterations, watch.ElapsedMilliseconds);
            }

            if (runJurassic)
            {
                Jurassic.ScriptEngine jurassic;
                jurassic = new Jurassic.ScriptEngine();
                jurassic.Execute(Script);

                watch.Restart();
                for (var i = 0; i < iterations; i++)
                {
                    if (!reuseEngine)
                    {
                        jurassic = new Jurassic.ScriptEngine();
                    }

                    jurassic.Execute(Script);
                }

                Console.WriteLine("Jurassic: {0} iterations in {1} ms", iterations, watch.ElapsedMilliseconds);
            }
        }